5

I'm looking for a way, preferable an NPM Package, to parse an SQL query to JSON. I found some for SELECT statements, but I actually need for UPDATE and INSERT INTO statements.
For example, a Query in the form of

"UPDATE "users" SET name = $2 where id in ($1)", ['new name', 1]

The result should be something like:

{ 
  action: 'UPDATE',
  entity: 'users',
  values: { name: 'new name' },
  conditions: { 'id': 1} 
}

Thank you for your help!

1 Answer 1

5

Welcome to StackOverflow!

There are multiple libraries out there for doing this. One example is node-sql-parser. Based on their readme, you can simply do:

const { Parser } = require('node-sql-parser');
const parser = new Parser();
const ast = parser.astify('SELECT * FROM t'); // mysql sql grammer parsed by default

console.log(ast);

And the output would be something like this:

{
  "type": "select",
  "columns": "*",
  "from": [
    {
      "table": "t"
    }
  ]
}

You can play around with it here to see if it matches your expectations: https://npm.runkit.com/node-sql-parser.

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

1 Comment

You've been a member long enough to know that questions for off-site resources, like libraries, is off-topic) for SO. Vote to close accordingly instead of adding an opinion-based recommendation.

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.