Created
July 10, 2018 18:01
-
-
Save ancms2600/076108dc16ba8dd1de10e8b3156c7eb1 to your computer and use it in GitHub Desktop.
SQL Parser in Javascript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
(exports => { | |
// console.clear(); | |
// | |
// let SAMPLE = ``+ | |
// `SELECT\n`+ | |
// ` Instance.Instance.Id AS Name,\n`+ | |
// ` Instance.Instance.PrivateIpAddress AS "IP Address",\n`+ | |
// ` Instance.Instance.LaunchTime AS Created,\n`+ | |
// ` Instance.Instance.Placement.AvailabilityZone AS Location,\n`+ | |
// ` Instance.Instance.Tags.*.[Key=Name].Value AS "Tech owner"\n`+ | |
// `FROM ec2`; | |
// | |
// SAMPLE = `SELECT Instance.Instance.Id AS Name, Instance.Instance.PrivateIpAddress AS \"IP Address\", Instance.Instance.LaunchTime AS Created, Instance.Instance.Placement.AvailabilityZone AS Location, Instance.Instance.Tags.*.[Key=Name].Value AS \"Tech owner\" FROM ec2`; | |
const RX_STATEMENT = /^\s*select\s+([\s\S]+)\s+from\s+([^\s]+?)\s*$/i; | |
const RX_FIELD = /^([^\s]+?)(?:\s+as\s+(['"]?)(.+?)\2)?\s*(?:,\s*|$)/i; | |
const RX_SEGMENT = /^\s*(?:\[\s*([^\s=[\]]*)(?:\s*=\s*(['"]?)(.*?)\2)?\s*\]|(\*)|([^\s]+?))\s*(?:\.\s*|$)/i; | |
exports.sqlesque = { parse: s => { | |
let m = s.match(RX_STATEMENT); | |
if (null == m) throw Error("Invalid statement."); | |
let [,fields,table] = s.match(RX_STATEMENT); | |
const r = { table: table, fields: [] }; | |
while (null != (m = RX_FIELD.exec(fields))) { | |
let [,field,,alias=''] = m; | |
const _field = { segments: [], alias: alias || field }; | |
fields = fields.substr(m[0].length); | |
while (null != (m = RX_SEGMENT.exec(field))) { | |
field = field.substr(m[0].length); | |
let [,attrName,,attrValue,wildcard,key] = m; | |
if (null != attrName) { | |
_field.segments.push({ | |
type: 'attr', | |
name: attrName, | |
value: attrValue, | |
}); | |
} | |
else if (null != wildcard) { | |
_field.segments.push({ | |
type: 'wildcard', | |
}); | |
} | |
else if (null != key) { | |
_field.segments.push({ | |
type: 'key', | |
key: key | |
}); | |
} | |
} | |
r.fields.push(_field); | |
}; | |
return r; | |
}}; | |
// console.log('r', parse(SAMPLE)); | |
})(typeof exports === 'undefined' ? window : exports); // browser compatible |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment