views:

91

answers:

1

I'm trying to extract column names from a SQLite result set from sqlite_master's sql column. I get hosed up in the regular expressions in the match() and split() functions.

t1.executeSql('SELECT name, sql FROM sqlite_master WHERE type="table" and name!="__WebKitDatabaseInfoTable__";', [],
  function(t1, result) {
   for(i = 0;i < result.rows.length; i++){
     var tbl = result.rows.item(i).name;
     var dbSchema = result.rows.item(i).sql;
// errors out on next line
     var columns = dbSchema.match(/.*CREATE\s+TABLE\s+(\S+)\s+\((.*)\).*/)[2].split(/\s+[^,]+,?\s*/);
   }
  },
  function(){console.log('err1');}
);

I want to parse SQL statements like these...

CREATE TABLE sqlite_sequence(name,seq);
CREATE TABLE tblConfig (Key TEXT NOT NULL,Value TEXT NOT NULL);
CREATE TABLE tblIcon (IconID INTEGER NOT NULL PRIMARY KEY,png TEXT NOT NULL,img32 TEXT NOT NULL,img64 TEXT NOT NULL,Version TEXT NOT NULL)

into a strings like theses...

name,seq
Key,Value
IconID,png,img32,img64,Version

Any help with a RegEx would be greatly appreciated.

A: 

Main problem is \s+ in your match regex. Should be /.*CREATE\s+TABLE\s+(\S+)\s*\((.*)\).*/)

Second problem is the split. I'm not quite sure what you tried to do in that regex, but here's a bit more straightforward way of doing it that does work on all of your examples:

var columns= dbSchema.match(/.*CREATE\s+TABLE\s+(\S+)\s*\((.*)\).*/)[2].split(/,/);
for(i = 0;i < columns.length; i++) {
    columns[i] = columns[i].replace(/\s.*/g, '');
}
DVK
Thanks! I think it's almost there. Here's the output of the RegEx in #1.["CREATE TABLE sqlite_sequence(name,seq)", "sqlite_sequence", "name,seq"]["CREATE TABLE tblConfig (Key TEXT NOT NULL,Value TEXT NOT NULL)", "tblConfig", "Key TEXT NOT NULL,Value TEXT NOT NULL"]If I run #2 I get ["CREATE", "sqlite_sequence", "name,seq"]. Not quite what I wanted.How do I strip out "INTEGER NOT NULL " and the other column attributes in columns[2] whle keeping the comma?
NimbusSoftware
@NimbusSoftware - see #2. The replace in the for loop dows that
DVK
Here's what happens when columns is run through the loop: ["CREATE", "tblConfig", "Key"]. EVERYTHING except the 1st word in columns[2] is nuked. I'd like to see columns[2] like this: "Key,Value". I do appreciate your help. Thanks.
NimbusSoftware
NEVERMIND! I missed ".split(/,/)" after the match. It works perfectly. Thanks
NimbusSoftware