node-mysql2 icon indicating copy to clipboard operation
node-mysql2 copied to clipboard

What is the correct syntax for including SQL values AND rowsAsArray option in a query?

Open millerbryan opened this issue 1 year ago • 1 comments

Discussed in https://github.com/sidorares/node-mysql2/discussions/3095

This is really a documentation enhancement request and should not be moved to a discussion.

There is no place in the docs where the correct syntax for using both rowsAsArray and a SQL value is shown.

Originally posted by millerbryan October 2, 2024 I've looked at all the examples in the docs which use rowsAsArray and it isn't clear how to specify it in a query (rather than in the connection) when passing in SQL values. Is this possible to pass both?

// simplified code
const sql = "select county_name from static_web_data.state_counties where state_name = ?";
const state = "TX"

        try {
          const [rows, fields] = await pool.query({sql, [state], rowsAsArray: true});
          if (rows) {
            return rows;
          }
        } catch (err) {
          console.log(err);
        }
```</div>

millerbryan avatar Oct 18 '24 02:10 millerbryan

Thanks, @millerbryan 🤝

Based on the types, there are two ways to use it:

https://github.com/sidorares/node-mysql2/blob/c06d2aea35cf2e45386bae5804d712f8902652ad/typings/mysql/lib/protocol/sequences/promise/QueryableBase.d.ts#L13-L19 https://github.com/sidorares/node-mysql2/blob/c06d2aea35cf2e45386bae5804d712f8902652ad/typings/mysql/lib/protocol/sequences/Query.d.ts#L7-L15

// A
pool.query({ sql: '', values: [], rowsAsArray: true });

// B
pool.query({ sql: '', rowsAsArray: true }, []);

I'll check it out in practice and also what happens if both are used at the same time with different values:

🧐💭

pool.query({ sql: '', values: [], rowsAsArray: true }, []);

wellwelwel avatar Oct 18 '24 18:10 wellwelwel

Thank you @wellwelwel and apologies for missing your response.

I will have a go at your syntax now and see what happens.

millerbryan avatar Jan 06 '25 23:01 millerbryan

The syntax works perfectly but the result set is different from what I expected. It includes quotes and [ ] for each item.

JavaScript syntax used: const [rows_array, fields] = await pool.query({ sql: sql, values: [state], rowsAsArray: true });

image

millerbryan avatar Jan 07 '25 00:01 millerbryan

I was hoping for something more like this:

image

millerbryan avatar Jan 07 '25 00:01 millerbryan