How to Parse/Tokenize an SQL Statement in Node.Js

Any Javascript/Jquery Library To validate SQL statment?

Here is an example fiddle using the JS SQL Parser:

http://jsfiddle.net/Hb6az/

The parser will throw an error if it hits something unexpected, so you have to wrap your checking code in a try {} catch(error) {} block.

Javascript Regex get list of string not in single or double quotes

DISCLAIMER: The solution below is by no means a generic solution for parsing arbitrary SQL queries. To parse arbitrary SQL queries, you need to build or use an existing one. See also How to parse / tokenize an SQL statement in Node.js.

So, taking into account your specific input strings, you can use a regex that will match what you do not need, and then will capture what you need:

/"[^"]*"|'[^']*'|\s+AS\s+|\s*((?:(?!\sAS\s)[^,\s])+)/gi

See the regex demo

Explanation:

  • "[^"]*" - match a double-quoted substring that has no " inside (replace with "[^"\\]*(?:\\.[^"\\]*)*" if you need to support escaped " inside)
  • | - or
  • '[^']*' - match single-quoted substring having no ' inside (replace with '[^'\\]*(?:\\.[^'\\]*)*' if you need to support escaped ' inside)
  • | - or
  • \s+AS\s+ - "AS" word inside 1+ whitespaces
  • | - or
  • \s* - 0+ whitespaces
  • ((?:(?!\sAS\s)[^,\s])+) - Group 1 capturing one or more symbols other than , and whitespace (see [^,\s])+) that are not starting a sequence of a whitespace + AS + whitespace. It matches any text that is not space+AS+space.

JS demo:

var re = /"[^"]*"|'[^']*'|\s+AS\s+|\s*((?:(?!\sAS\s)[^,\s])+)/gi; var str = 'Select id AS "cusId ", name as \'cusName\', gendar as \' Gendar.\', isPaid as " is\'Paid " total , datetime FROM';var res = [];while ((m = re.exec(str)) !== null) {    if (m[1]) {         res.push(m[1]); // Add the Capture group 1 to the resulting array    }}document.body.innerHTML = "<pre>" + JSON.stringify(res, 0, 4) + "</pre>";

Package subpath './lib/tokenize' is not defined by exports

I tried updating the node modules with

npm update

and the issue was solved. I am keeping it here so that someone else can find the answer if they are looking for



Related Topics



Leave a reply



Submit