1

Using MySQL 8.0 on a node.js server (X DevAPI), I'm trying to get data with

var res = session.sql('SELECT * FROM users').execute(function (row) {
  console.log(row); // [1,'foo','bar']
});

but this returns only an array of values. The column names are missing. Is there a way I can get key-value pairs such as that in classic SQL data sets?

i.e. id: 1, fName: 'foo', lName: 'bar'

3 Answers 3

2

Right now you would have to construct the key-value pair structure "by hand" using the column metadata available through a second callback parameter on execute().

Something like the following would do the trick:

var result = []

session.sql('SELECT 1 AS id, "foo" AS fName, "bar" AS lName')
  .execute(row => {
    row.forEach((value, i) => { result[i] = Object.assign({}, result[i], { value }) })
  }, columns => {
    columns.forEach((key, i) => { result[i] = Object.assign({}, result[i], { key: key.getColumnName() }) })
  })

console.log(result.reduce((res, pair) => Object.assign(res, { [pair.key]: pair.value }), {}))

I have to admit this is convoluted and making it better is already on the radar.

Disclaimer: I'm the X DevAPI connector lead dev.

Sign up to request clarification or add additional context in comments.

2 Comments

I was affraid of that. Thank you for clearing that up though, I'll move forward with that in mind.
You did a brilliant job! I hope that this connector will have a great future!
1

Use the JSON_OBJECT function in your query.

 var res = session.sql("select JSON_OBJECT('id', id, 'name', name) from users").execute(function (row) {
      console.log(row); // {"id": 87, "name": "rui"} 
 });

Comments

0

This is a workaround maybe will help someone.

    //This is declared outside of class
    const mapTest = (row) =>{
    return{
            id:row[0],
            price:row[1]
        }
    }
    //This where you get the result.
    .execute()
    .then(myResult =>{
          let myRows = myResult.fetchAll();
          resolve(myRows.map(row=>mapTest(row))); // returns {"id":1,"price":200000},{"id":2,"price":300000}
    })
   

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.