我的项目涉及针对SQLite数据库运行临时SQL语句。我正在寻找一个JavaScript正则表达式来解析ALTER,CREATE和UPDATE sql语句。以下是我正在寻找的例子和结果。
CREATE INDEX Christy...
CREATE INDEX IF NOT EXISTS Christy...
CREATE UNIQUE INDEX Christy...
CREATE UNIQUE INDEX IF NOT EXISTS Christy...
a = [..."CREATE", "INDEX", "Christy"]
CREATE TABLE Vicky (id INTEGER PRIMARY KEY AUTOINCREMENT,name TEXT,score REAL DEFAULT .10 CHECK (weight<=1));
CREATE TABLE IF NOT EXISTS Vicky (id INTEGER PRIMARY KEY AUTOINCREMENT,name TEXT,score REAL DEFAULT .10 CHECK (weight<=1));
a = [..."CREATE", "TABLE", "Vicky", "id INTEGER PRIMARY KEY AUTOINCREMENT","name TEXT","score REAL DEFAULT .10 CHECK (weight<=1)"]
CREATE TABLE Vicky (id INTEGER PRIMARY KEY AUTOINCREMENT,name TEXT,score REAL DEFAULT .10 CHECK (weight<=1)),PRIMARY KEY (id, name));
CREATE TABLE IF NOT EXISTS Vicky (id INTEGER PRIMARY KEY AUTOINCREMENT,name TEXT,score REAL DEFAULT .10 CHECK (weight<=1)),PRIMARY KEY (id, name));
a = [..."CREATE", "TABLE", "Vicky", "id INTEGER PRIMARY KEY AUTOINCREMENT","name TEXT","score REAL DEFAULT .10 CHECK (weight<=1)","PRIMARY KEY (id, name))"]
CREATE TRIGGER Arwen...
CREATE TRIGGER IF NOT EXISTS Arwen...
a = [..."CREATE", "TRIGGER", "Arwen"]
CREATE VIEW Snow...
CREATE VIEW IF NOT EXISTS Snow...
a = [..."CREATE", "VIEW", "Snow"]
ALTER TABLE Vicky...
a = [..."ALTER", "TABLE", "Vicky"]
UPDATE Vicky...
UPDATE OR ROLLBACK Vicky...
UPDATE OR ABORT Vicky...
UPDATE OR REPLACE Vicky...
UPDATE OR FAIL Vicky...
UPDATE OR IGNORE Vicky...
a = [..."UPDATE", "TABLE", "Vicky"]
<小时/> 这是SQLite用于这些SQL语句的文档的链接。
ALTER TABLE
CREATE INDEX
CREATE TABLE
CREATE TRIGGER
CREATE VIEW
UPDATE
谢谢,
HeadDataZombie
答案 0 :(得分:0)
您是否正在尝试解析它们以验证准确性?有效期是多久?安全
解析SQL并不容易,我怀疑你能用这么多模式在正则表达式中做到这一点。也许this link可能会有所帮助。另见上一个问题parsing-sql-create-table-statement-using-jquery并注意提到TrimQuery,它可能有助于JS的实现。
如果您正在尝试记录这些修改(CREATE / ALTER / UPDATE)语句正在运行的活动,那么创建触发器以插入日志记录表可能就足够了。
答案 1 :(得分:0)
使用正则表达式解析SQL很困难(如果不是不可能)。然而...
SQLite手册每页顶部的奇怪图表实际上告诉您使用PEG.js或JS/CC等解析器生成器需要知道的一切解析你的SQL语句。
例如,以下PEG.js代码将完美地解析ALTER TABLE语句:
start = altertable
altertable = "alter" w "table" w ( dbname:identifier w? "." ) ? w? tablename:identifier w ( renameto / addcolumn)
renameto = "rename" w "to" w newname:identifier
addcolumn = "add" w ( "column" w )? col:identifier
identifier = chars:([a-zA-Z][a-zA-Z_0-9]*)
w = " " +
当然,您需要添加构建解析树的操作。