Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add indexed properties to RowDataPacket #2164

Open
nickshanks opened this issue Jan 9, 2019 · 6 comments
Open

Add indexed properties to RowDataPacket #2164

nickshanks opened this issue Jan 9, 2019 · 6 comments

Comments

@nickshanks
Copy link

I would like to be able to access fields by their index in the query, without having to modify the query to include an 'AS' field alias. For example, given:

SELECT COUNT(*), MAX(some_field) + 1 FROM table

I want to be able to refer to the results like this:

const count = rows[0][0];
const max_thingy = rows[0][1];

Instead of:

const count = rows[0]['COUNT(*)'];
const max_thingy = rows[0]['MAX(some_field) + 1'];

You can imagine how these field names can get very long and unwieldy.
The solution is to add one line to the end of the for loop in the parse function of RowDataPacket (after line 49 in the current code):

Object.defineProperty(this, i, { value });
@nickshanks
Copy link
Author

I forgot to mention, the suggested property definition is deliberately non-enumerable so that looping over the properties doesn't cause values to be returned twice.

@sidorares
Copy link
Member

there is #1637 proposed which does this via rowsAsArray flag ( same flag is used by mysql2 library )

@BufoViridis
Copy link

It's easy to be added, it was suggested many times and there is pull requests as well.
*reference

@nickshanks
Copy link
Author

Those alternatives are all rather more complex than my suggestion (and address a different concern — returning an actual array).

There is no reason to have this behind an options flag, as SQL field names (and AS … aliases) cannot begin with a digit, so there could not be any clashes with existing code. I think adding it is cheap, unproblematic, and beneficial.

@sqlbot
Copy link

sqlbot commented Jan 22, 2019

SQL field names (and AS … aliases) cannot begin with a digit

That seems inaccurate.

From the docs: "Identifiers may begin with a digit but unless quoted may not consist solely of digits."

@theanurin
Copy link

theanurin commented Mar 5, 2019

I have another case for index-based access to RowDataPacket: Result set with duplicates in column names. For example, I want to parse result set of a query:

SELECT 1 AS "A", 2 as "A", 3 AS "A"

A result of the query should be 3 columns, but RowDataPacket has only one value.
What do you think about?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

5 participants