├── src ├── helpers │ ├── jSQLReset.js │ ├── jSQLMinifier.js │ └── removeQuotes.js ├── sugar │ ├── tokenize.js │ ├── update.js │ ├── insertInto.js │ ├── deleteFrom.js │ ├── dropTable.js │ ├── select.js │ └── createTable.js ├── wrapper │ ├── head.js.part │ └── foot.js.part ├── import_export │ ├── import.js │ └── export.js ├── parser │ ├── jSQLParseDropTokens.js │ ├── jSQLParseDeleteTokens.js │ ├── jSQLParseUpdateTokens.js │ ├── jSQLParseSelectTokens.js │ ├── jSQLParseQuery.js │ ├── jSQLParseInsertTokens.js │ ├── jSQLParseWhereClause.js │ ├── jSQLParseCreateTokens.js │ └── jSQLWhereClause.js ├── error_handling │ ├── error_handling.js │ ├── jSQL_Parse_Error.js │ ├── jSQL_Lexer_Error.js │ └── jSQL_Error.js ├── query_types │ ├── jSQLDropQuery.js │ ├── jSQLCreateQuery.js │ ├── jSQLInsertQuery.js │ ├── jSQLQuery.js │ ├── jSQLSelectQuery.js │ ├── jSQLDeleteQuery.js │ └── jSQLUpdateQuery.js ├── lexer │ ├── token.js │ ├── jSQLLexer.js │ └── token_types.js ├── persistence │ ├── persistenceManager.js │ └── API.js ├── data_types │ └── jSQLDataTypeList.js └── table │ └── jSQLTable.js ├── .travis.yml ├── .gitignore ├── .codeclimate.yml ├── test ├── test6.js ├── test5.js ├── test3.js ├── test4.js ├── test2.js └── test1.js ├── package.json ├── Gruntfile.js ├── README.md ├── LICENSE └── jSQL.min.js /src/helpers/jSQLReset.js: -------------------------------------------------------------------------------- 1 | 2 | function jSQLReset(){ 3 | jSQL.tables = {}; 4 | jSQL.commit(); 5 | } -------------------------------------------------------------------------------- /src/sugar/tokenize.js: -------------------------------------------------------------------------------- 1 | 2 | function tokenize(sql){ 3 | return new jSQLLexer(sql).getTokens(); 4 | } -------------------------------------------------------------------------------- /src/sugar/update.js: -------------------------------------------------------------------------------- 1 | 2 | function update(table){ 3 | return new jSQLQuery("UPDATE").init(table); 4 | } 5 | -------------------------------------------------------------------------------- /src/sugar/insertInto.js: -------------------------------------------------------------------------------- 1 | 2 | function insertInto(tablename){ 3 | return new jSQLQuery("INSERT").init(tablename); 4 | } -------------------------------------------------------------------------------- /src/sugar/deleteFrom.js: -------------------------------------------------------------------------------- 1 | 2 | function deleteFrom(tablename){ 3 | return new jSQLQuery("DELETE").init(tablename); 4 | } 5 | -------------------------------------------------------------------------------- /src/sugar/dropTable.js: -------------------------------------------------------------------------------- 1 | 2 | function dropTable(tablename){ 3 | return new jSQLQuery("DROP").init(tablename); 4 | } 5 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | node_js: 3 | - "node" 4 | script: npm run coverage 5 | after_success: 'npm run coveralls' -------------------------------------------------------------------------------- /src/sugar/select.js: -------------------------------------------------------------------------------- 1 | 2 | function select(cols){ 3 | if(!Array.isArray(cols)) cols=[cols]; 4 | return new jSQLQuery("SELECT").init(cols); 5 | } 6 | -------------------------------------------------------------------------------- /src/wrapper/head.js.part: -------------------------------------------------------------------------------- 1 | ;(function(){ 2 | var isNode = !!(typeof module !== 'undefined' && module.exports); 3 | var jSQL = (function(){ 4 | "use strict"; -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /nbproject/ 2 | /test/.jsqldatastore 3 | .jsqldatastore 4 | package-lock.json 5 | node_modules 6 | coverage 7 | .coveralls.yml 8 | browser_tests -------------------------------------------------------------------------------- /src/import_export/import.js: -------------------------------------------------------------------------------- 1 | 2 | 3 | function jsql_import(dump){ 4 | dump = dump.split(";\n"); 5 | for(var i=0; i pos + max_ellipse_len ? max_ellipse_len : 5 | context.length - pos; 6 | var preview = context.substr(pos, ellipse_len); 7 | this.error = "0070"; 8 | this.message = "Unknown token near char "+pos+" of "+context.length+" \""+preview+"\"."; 9 | this.stack = undefined; 10 | var e = new Error(); 11 | if(e.stack) this.stack = e.stack; 12 | this.toString = function () { 13 | return "jSQL Lexer Error #"+this.error+" - "+this.message; 14 | }; 15 | } 16 | -------------------------------------------------------------------------------- /test/test6.js: -------------------------------------------------------------------------------- 1 | var expect = require('chai').expect; 2 | var jSQL = require("../jSQL.js"); 3 | 4 | jSQL.load(()=>{ 5 | describe('Temp Table Test', function () { 6 | it('Testing temp table', function(){ 7 | jSQL.createTable({myTable: [ 8 | { name: "ID", type: "INT", args: [], key: "primary", auto_increment: true }, 9 | { name: "Name", type: "VARCHAR", args: [30] } 10 | ]}).temporary().execute(); 11 | expect(!!jSQL.tables.myTable).to.be.true; 12 | }); 13 | it('Testing temp table parser', function(){ 14 | jSQL.query("create temporary table fartypoops (id int, name varchar)").execute(); 15 | expect(jSQL.tables.fartypoops.isTemp).to.be.true; 16 | }); 17 | }); 18 | }); 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /src/wrapper/foot.js.part: -------------------------------------------------------------------------------- 1 | 2 | return { 3 | version: {{ VERSION }}, 4 | tables: {}, 5 | query: jSQLParseQuery, 6 | createTable: createTable, 7 | dropTable: dropTable, 8 | select: select, 9 | update: update, 10 | deleteFrom: deleteFrom, 11 | insertInto: insertInto, 12 | types: new jSQLDataTypeList(), 13 | load: persistenceManager.load, 14 | onError: onError, 15 | reset: jSQLReset, 16 | minify: jSQLMinifier, 17 | commit: persistenceManager.commit, 18 | rollback: persistenceManager.rollback, 19 | setApiPriority: persistenceManager.setApiPriority, 20 | getApi: persistenceManager.getApi, 21 | tokenize: tokenize, 22 | export: jsql_export, 23 | import: jsql_import 24 | }; 25 | 26 | })(); 27 | 28 | // Determine if we're running Node or browser 29 | if (isNode) { 30 | module.exports = jSQL; 31 | } else { 32 | window.jSQL = jSQL; 33 | } 34 | 35 | })(); 36 | -------------------------------------------------------------------------------- /src/query_types/jSQLCreateQuery.js: -------------------------------------------------------------------------------- 1 | 2 | function jSQLCreateQuery(){ 3 | this.init = function(tablename, columns, types, keys, auto_increment){ 4 | this.tablename = tablename; 5 | this.columns = columns; 6 | this.coltypes = types; 7 | this.keys = keys; 8 | this.ai_col = auto_increment; 9 | return this; 10 | }; 11 | this.ifNotExists = function(){ this.INEFlag=true; return this; }; 12 | this.execute = function(data){ 13 | if(undefined !== data) this.data = data; 14 | if(!(this.INEFlag && jSQL.tables.hasOwnProperty(this.tablename))){ 15 | jSQL.tables[this.tablename] = new jSQLTable(this.tablename, this.columns, this.data, this.coltypes, this.keys, this.ai_col); 16 | if(this.isTemp) jSQL.tables[this.tablename].isTemp = true; 17 | } 18 | return this; 19 | }; 20 | this.temporary = function(){ 21 | this.isTemp = true; 22 | return this; 23 | }; 24 | this.fetch = function(){ return null; }; 25 | this.fetchAll = function(){ return []; }; 26 | } -------------------------------------------------------------------------------- /src/lexer/token.js: -------------------------------------------------------------------------------- 1 | 2 | 3 | function jSQLToken(pos, literal, tok_index){ 4 | this.type_id = tok_index; 5 | this.input_pos = pos; 6 | this.literal = literal; 7 | this.value = literal; 8 | this.length = literal.length; 9 | this.type = jSQLLexer.token_types[tok_index].type; 10 | this.name = jSQLLexer.token_types[tok_index].name; 11 | 12 | if(this.type === "IDENTIFIER" && this.name === "UNQTD IDENTIFIER" && jSQL.types.exists(this.literal)) 13 | this.name = "DATA TYPE"; 14 | if(this.type === "IDENTIFIER" && this.name === "QTD IDENTIFIER") 15 | this.value = literal.replace(/`/g,''); 16 | if(this.type === "STRING" && this.name === "DQ STRING") 17 | this.value = literal.substr(1, literal.length - 2).replace(/\"/g, '"'); 18 | if(this.type === "STRING" && this.name === "SQ STRING") 19 | this.value = literal.substr(1, literal.length - 2).replace(/\'/g, "'"); 20 | if(this.type === "NUMBER") this.value = parseFloat(this.literal); 21 | if(this.type === "KEYWORD" && this.name === "NULL") this.value = null; 22 | } 23 | -------------------------------------------------------------------------------- /src/parser/jSQLParseUpdateTokens.js: -------------------------------------------------------------------------------- 1 | 2 | function jSQLParseUpdateTokens(tokens){ 3 | var table_name, query, newVals = {}; 4 | var token = tokens.shift(); 5 | 6 | table_name = jSQLParseQuery.validateTableNameToken(token); 7 | token = tokens.shift(); 8 | 9 | if(token.type !== "KEYWORD" && token.name !== "SET") 10 | return _throw(new jSQL_Parse_Error(token, "SET")); 11 | 12 | while(tokens.length){ 13 | var column_name = jSQLParseQuery.validateColumnName(tokens.shift().value, table_name); 14 | token = tokens.shift(); 15 | if(token.type !== 'SYMBOL' && token.name !== 'EQUALS') 16 | return _throw(new jSQL_Parse_Error(token, "EQUALS")); 17 | var value = tokens.shift().value; 18 | newVals[column_name] = value; 19 | if(!tokens.length) break; 20 | token = tokens.shift(); 21 | if(token.type === "SYMBOL" && token.name === "COMMA") continue; 22 | if(token.type === "KEYWORD" && token.name === "WHERE"){ 23 | tokens.unshift(token); 24 | break; 25 | } 26 | } 27 | 28 | query = jSQL.update(table_name).set(newVals); 29 | query = jSQLParseWhereClause(query, tokens, table_name); 30 | return query; 31 | } -------------------------------------------------------------------------------- /src/query_types/jSQLInsertQuery.js: -------------------------------------------------------------------------------- 1 | 2 | function jSQLInsertQuery(){ 3 | this.init = function(table){ 4 | this.table = table; 5 | this.ignoreFlag = false; 6 | return this; 7 | }; 8 | this.values = function(data){ 9 | if(undefined === jSQL.tables[this.table]) 10 | return _throw(new jSQL_Error("0021")); 11 | this.data = data; 12 | return this; 13 | }; 14 | this.execute = function(preparedVals){ 15 | if(preparedVals !== undefined && Array.isArray(preparedVals) && preparedVals.length>0){ 16 | if(Array.isArray(this.data)){ 17 | for(var i=this.data.length; i-- && preparedVals.length;) 18 | if(this.data[i]=="?") this.data[i]=preparedVals.shift(); 19 | }else{ 20 | for(var i in this.data) 21 | if(this.data.hasOwnProperty(i) && preparedVals.length && this.data[i] == "?") 22 | this.data[i] = preparedVals.shift(); 23 | } 24 | } 25 | jSQL.tables[this.table].insertRow(this.data, this.ignoreFlag); 26 | return this; 27 | }; 28 | this.ignore = function(){ this.ignoreFlag=true; return this; }; 29 | this.fetch = function(){ return null; }; 30 | this.fetchAll = function(){ return []; }; 31 | } 32 | -------------------------------------------------------------------------------- /src/query_types/jSQLQuery.js: -------------------------------------------------------------------------------- 1 | 2 | function jSQLQuery(type){ 3 | var self = this; 4 | self.type = type.toUpperCase(); 5 | self.tablename = null; 6 | self.columns = []; 7 | self.data = []; 8 | self.INEFlag= false; 9 | self.coltypes = []; 10 | self.table = null; 11 | self.newvals = {}; 12 | self.whereClause = new jSQLWhereClause(self); 13 | self.resultSet = []; 14 | self.isTemp = false; 15 | 16 | // Methods that every query class should implement 17 | var methods = ['init', 'ifNotExists', 'execute', 'fetch', 'ignore', 18 | 'fetchAll', 'values', 'set', 'where', 'from', 'orderBy', 'asc', 19 | 'desc', 'limit', 'distinct', 'temporary']; 20 | var queryTypeConstructors = { 21 | CREATE: jSQLCreateQuery, 22 | UPDATE: jSQLUpdateQuery, 23 | SELECT: jSQLSelectQuery, 24 | INSERT: jSQLInsertQuery, 25 | DROP: jSQLDropQuery, 26 | DELETE: jSQLDeleteQuery 27 | }; 28 | for(var i=0; i{ 5 | jSQL.query("-- Generated with jSQL Devel on Tuesday, February 6th 2018, 3:31pm \n\ 6 | CREATE TABLE IF NOT EXISTS `testeroo` (\n\ 7 | `id` INT(5) NOT NULL,\n\ 8 | `name` VARCHAR(5) NULL,\n\ 9 | `another_id` NUMERIC(6) NOT NULL,\n\ 10 | `uni1` INT(3) NOT NULL UNIQUE KEY,\n\ 11 | `uni2` INT(3) NOT NULL UNIQUE KEY,\n\ 12 | PRIMARY KEY (`id`, `another_id`)\n\ 13 | )").execute(); 14 | 15 | var sql = "insert into testeroo values(?, ?, ?, ?, ?)"; 16 | jSQL.query(sql).execute([0,'farts',1,5,9]); 17 | jSQL.query(sql).execute([1,'tird',2,6,8]); 18 | jSQL.query(sql).execute([1,'berb',3,7,7]); 19 | jSQL.query(sql).execute([5,'farts',4,1,6]); 20 | 21 | var exp = jSQL.export(true, ['testeroo']); 22 | 23 | jSQL.reset(); 24 | 25 | setTimeout(()=>{ 26 | jSQL.import(exp); 27 | 28 | describe('Export Test', function () { 29 | 30 | it('Testing Export up in this biaaatch', function(){ 31 | var q = jSQL.query("select * from testeroo where id = 1").execute().fetchAll("ASSOC").length; 32 | expect(q.length === 2).to.be.true; 33 | }); 34 | 35 | }); 36 | }, 1000); 37 | 38 | 39 | }); 40 | 41 | 42 | 43 | -------------------------------------------------------------------------------- /src/lexer/jSQLLexer.js: -------------------------------------------------------------------------------- 1 | 2 | 3 | function jSQLLexer(input) { 4 | this.input = input; 5 | this.pos = 0; 6 | this.real_pos = 0; 7 | this.tokens = []; 8 | this.token_matches = []; 9 | } 10 | 11 | jSQLLexer.prototype.getNextToken = function(){ 12 | var r; 13 | for(var i=0; i 0){ 63 | res.push(this.fetch(Mode)); 64 | } 65 | return res; 66 | }; 67 | this.orderBy = function(columns){ 68 | return this.whereClause.orderBy(columns); 69 | }; 70 | this.asc = function(){ 71 | return this.whereClause.asc(); 72 | }; 73 | this.desc = function(){ 74 | return this.whereClause.desc(); 75 | }; 76 | this.limit = function(){ 77 | return this.whereClause.limit(); 78 | }; 79 | this.distinct = function(){ 80 | this.whereClause.isDistinct = true; 81 | return this; 82 | }; 83 | } 84 | -------------------------------------------------------------------------------- /src/sugar/createTable.js: -------------------------------------------------------------------------------- 1 | 2 | function createTable(name, columnsOrData, types, keys, auto_increment){ 3 | 4 | // allow for all params to be passed in a single object 5 | // jSQL.createTable({myTable: [ 6 | // { name: "ID", type: "INT", args: [] }, 7 | // { name: "Name", type: "VARCHAR", args: [30] } 8 | // ]}) 9 | // 10 | // OR, for compund keys 11 | // 12 | // jSQL.createTable({myTable: [ 13 | // { name: "ID", type: "INT", args: [] }, 14 | // { name: "Name", type: "VARCHAR", args: [30] } 15 | // ]}, [ 16 | // { column: ["ID", "Name"], type: "primary" } 17 | // ]) 18 | // 19 | // OR, for single-column keys 20 | // 21 | // jSQL.createTable({myTable: [ 22 | // { name: "ID", type: "INT", args: [], key: "primary", auto_increment: true }, 23 | // { name: "Name", type: "VARCHAR", args: [30] } 24 | // ]}) 25 | var dataObjNoKeys = undefined === columnsOrData && undefined === types && "object" === typeof name && undefined === keys; 26 | var dataObjWithKeys = Array.isArray(columnsOrData) && undefined === types && "object" === typeof name && undefined === keys; 27 | if(dataObjNoKeys || dataObjWithKeys){ 28 | if(dataObjWithKeys) keys = undefined === columnsOrData ? [] : columnsOrData; 29 | if(undefined === keys) keys = []; 30 | columnsOrData = []; 31 | types = []; 32 | for(var tblname in name){ 33 | if(!name.hasOwnProperty(tblname))continue; 34 | var columnDefs = name[tblname]; 35 | name = tblname; 36 | for(var n=0; n-1) delete this.table.keys.primary.map[pk_vals]; 30 | else this.table.keys.primary.map[pk_vals] = newData.length;; 31 | } 32 | } 33 | 34 | // If there are any unique columns in this row, delete them 35 | var ukey; 36 | for(var k=0; ukey=this.table.keys.unique[k]; k++){ 37 | var key_columns = Array.isArray(ukey.column) ? ukey.column : [ukey.column]; 38 | var col, vals = []; 39 | for(var uk=0; col=key_columns[uk]; uk++){ 40 | var index = this.table.colmap[col]; 41 | if(null === row[index]) return _throw(new jSQL_Error("0018")); 42 | vals.push(row[index]); 43 | } 44 | vals = JSON.stringify(vals); 45 | if(ukey.map.hasOwnProperty(vals) && ukey.map[vals] == i){ 46 | if(this.ignoreFlag === true) return this; 47 | if(resultRowIndexes.indexOf(i)>-1) delete this.table.keys.unique[k].map[vals]; 48 | else this.table.keys.unique[k].map[vals] = newData.length; 49 | } 50 | } 51 | 52 | if(resultRowIndexes.indexOf(i)>-1) results.push(row); 53 | else newData.push(this.table.data[i]); 54 | } 55 | this.table.data = newData; 56 | this.resultSet = results; 57 | return this; 58 | }; 59 | this.where = function(column){ 60 | return this.whereClause.where(column); 61 | }; 62 | this.fetch = function(){ return null; }; 63 | this.fetchAll = function(){ return []; }; 64 | this.orderBy = function(columns){ 65 | return this.whereClause.orderBy(columns); 66 | }; 67 | this.asc = function(){ 68 | return this.whereClause.asc(); 69 | }; 70 | this.desc = function(){ 71 | return this.whereClause.desc(); 72 | }; 73 | this.limit = function(){ 74 | return this.whereClause.limit(); 75 | }; 76 | this.distinct = function(){ 77 | this.whereClause.isDistinct = true; 78 | return this; 79 | }; 80 | } 81 | -------------------------------------------------------------------------------- /test/test4.js: -------------------------------------------------------------------------------- 1 | var expect = require('chai').expect; 2 | var jSQL = require("../jSQL.js"); 3 | 4 | 5 | jSQL.load(function () { 6 | jSQL.reset(); 7 | describe('ERROR tests', function () { 8 | 9 | it('Testing Error 0001', function(){ 10 | jSQL.query("create table myfunct (f function, id int)").execute(); 11 | var q = jSQL.query("insert into myfunct values (?)"); 12 | var e_ = false; 13 | try{ 14 | q.execute(["not a function"]); 15 | }catch(e){ 16 | console.log(e.toString()); 17 | e_ = e.error === "0001"; 18 | } 19 | expect(e_).to.be.true; 20 | }); 21 | 22 | it('Testing Error 0003', function(){ 23 | var e_ = false; 24 | try{ 25 | jSQL.types.add("poop"); 26 | }catch(e){ 27 | e_ = e.error === '0003'; 28 | } 29 | expect(e_).to.be.true; 30 | }); 31 | 32 | it('Testing Error 0004', function(){ 33 | var e_ = false; 34 | try{ 35 | jSQL.types.add({}); 36 | }catch(e){ 37 | e_ = e.error === '0004'; 38 | } 39 | expect(e_).to.be.true; 40 | }); 41 | 42 | it('Testing Error 0005', function(){ 43 | var e_ = false; 44 | try{ 45 | jSQL.types.add({type:"booty", serialize: "poop"}); 46 | }catch(e){ 47 | e_ = e.error === '0005'; 48 | } 49 | expect(e_).to.be.true; 50 | }); 51 | 52 | it('Testing Error 0006', function(){ 53 | var e_ = false; 54 | try{ 55 | jSQL.types.add({type:"booty", unserialize: "poop", serialize: function(){}}); 56 | }catch(e){ 57 | e_ = e.error === '0006'; 58 | } 59 | expect(e_).to.be.true; 60 | }); 61 | 62 | it('Testing Error 0007', function(){ 63 | var e_ = false; 64 | try{ 65 | jSQL.createTable({yerMom: [ 66 | {name: 'poo', type: 'piddly'} 67 | ]}).execute(); 68 | }catch(e){ 69 | console.log(e.toString()); 70 | e_ = e.error === "0007"; 71 | } 72 | expect(e_).to.be.true; 73 | }); 74 | 75 | it('Testing Error 0072', function(){ 76 | jSQL.query("create table namesnstuff (id int not null, name varchar)").execute(); 77 | var e_ = false; 78 | try{ 79 | jSQL.query("insert into namesnstuff (name) values ('bob dole')").execute(); 80 | }catch(e){ 81 | console.log(e.toString()); 82 | e_ = e.error === "0072"; 83 | } 84 | expect(e_).to.be.true; 85 | }); 86 | 87 | it('Testing Lexer Error', function(){ 88 | var e_ = false; 89 | try{ 90 | jSQL.query("hi im bob ~~~~``~~~``~`~").execute(); 91 | q.execute(); 92 | }catch(e){ 93 | console.log(e.toString()); 94 | e_ = true; 95 | } 96 | expect(e_).to.be.true; 97 | }); 98 | 99 | it('Testing Parser Error', function(){ 100 | var e_ = false; 101 | try{ 102 | jSQL.query("hi im bob").execute(); 103 | q.execute(); 104 | }catch(e){ 105 | console.log(e.toString()); 106 | e_ = true; 107 | } 108 | expect(e_).to.be.true; 109 | }); 110 | 111 | it('Testing Parser Error', function(){ 112 | var e_ = false; 113 | try{ 114 | jSQL.query("insert into farts suckbudda suckbudda suckbudda suckbudda suckbudda suckbudda suckbudda suckbudda suckbudda suckbudda suckbudda suckbudda").execute(); 115 | q.execute(); 116 | }catch(e){ 117 | console.log(e.toString()); 118 | e_ = true; 119 | } 120 | expect(e_).to.be.true; 121 | }); 122 | 123 | }); 124 | }); -------------------------------------------------------------------------------- /test/test2.js: -------------------------------------------------------------------------------- 1 | var expect = require('chai').expect; 2 | var jSQL = require("../jSQL.js"); 3 | 4 | jSQL.onError(function(e){ 5 | console.log(e.message); 6 | }); 7 | 8 | jSQL.load(function () { 9 | jSQL.reset(); 10 | describe('FuNkY TaBlE TeSts', function () { 11 | 12 | it('inserting inconsistent objects', function(){ 13 | jSQL.createTable("oTable", [ 14 | {a:1, b:2, c:3, d:4, e:5, f:6, g:7}, 15 | {a:2, b:3, c:3, d:54, e:7, f:6}, 16 | {a:2, b:3, c:3, d:54, e:7, f:6, g:7, h:"d"}, 17 | {a:2, b:3, c:3, d:54, e:7, f:6, g:7, h:"d"} 18 | ]).execute(); 19 | expect((jSQL.tables.oTable.data.length === 4 && jSQL.tables.oTable.columns.length === 8)).to.be.true; 20 | }); 21 | 22 | it('checking distinct', function(){ 23 | var res = jSQL.query("select distinct * from oTable").execute().fetchAll("ASSOC"); 24 | expect(res.length === 3).to.be.true; 25 | }); 26 | 27 | it('dynamically adding columns', function(){ 28 | jSQL.createTable("aTable", ["u0", "b", "c"]).execute([ 29 | [12, 34, 56, 78], 30 | [23, 45, 67, 89, 78, 78], 31 | [7] 32 | ]); 33 | expect((jSQL.tables.aTable.data.length === 3 && jSQL.tables.aTable.columns.length === 6)).to.be.true; 34 | }); 35 | 36 | it('mixing arrays and objects', function(){ 37 | jSQL.createTable("cjjTable", ['u0', 'b', 'c', 'd', 'e', 'f', 'g']).execute([ 38 | [12, 34, 56, 78], 39 | [23, 45, 67, 89, 78, 78], 40 | [7], {"a": 1, "b": 2, "g": 3} 41 | ]); 42 | 43 | expect((jSQL.tables.cjjTable.data.length === 4 && jSQL.tables.cjjTable.columns.length === 7)).to.be.true; 44 | }); 45 | 46 | it('rename columns', function(){ 47 | jSQL.query("create table ceTable (u0, b, c, d, e, f, g, primary key(b), unique key(c))").execute(); 48 | jSQL.insertInto("ceTable").values({u0:2, b:3, c:34}).execute(); 49 | try{ 50 | jSQL.tables.ceTable.renameColumn('u0', {}); 51 | }catch(e){} 52 | try{ 53 | jSQL.tables.ceTable.renameColumn('b', 'adfa'); 54 | }catch(e){} 55 | try{ 56 | jSQL.tables.ceTable.renameColumn('b', 'c'); 57 | }catch(e){} 58 | try{ 59 | jSQL.deleteFrom("asdf").execute(); 60 | }catch(e){} 61 | try{ 62 | jSQL.deleteFrom("ceTable").execute(); 63 | }catch(e){} 64 | 65 | jSQL.tables.ceTable.renameColumn('u0', 'ufff'); 66 | expect(jSQL.tables.ceTable.columns[0] == 'ufff').to.be.true; 67 | 68 | jSQL.query("create table abc (a, b, c, primary key (a, b))").execute(); 69 | jSQL.query("create table bcd (a int auto_increment, b, c, primary key (a))").execute(); 70 | jSQL.query("insert into bcd values (1, 'd', 'e')").execute(); 71 | jSQL.query("insert into bcd values (2, 'd', 'j')").execute(); 72 | jSQL.query("insert into bcd (b,c) values ('d', 'f')").execute(); 73 | jSQL.query("update bcd set a = ? where c = ?").execute([5, 'f']); 74 | jSQL.query("update bcd set a = ? where c = ?").execute([null, 'f']); 75 | 76 | jSQL.query("create table cde (a, b, c, unique key (a, b))").execute(); 77 | jSQL.query("insert into abc values ('a', 'c', 'c')").execute(); 78 | jSQL.query("insert into abc values ('c', 'd', 'e')").execute(); 79 | jSQL.query("insert into cde values ('a', 'c', 'c')").execute(); 80 | jSQL.query("insert into cde values ('c', 'd', 'e')").execute(); 81 | jSQL.query("update abc set a = ? where c = ?").execute(['a', 'e']); 82 | jSQL.query("update cde set a = ? where c = ?").execute(['a', 'e']); 83 | 84 | try{jSQL.query("update asdfasd set a = ? where c = ?").execute(['a', 'e']);}catch(e){} 85 | try{jSQL.update("asdfasd")}catch(e){} 86 | }); 87 | 88 | }); 89 | }); -------------------------------------------------------------------------------- /src/parser/jSQLParseWhereClause.js: -------------------------------------------------------------------------------- 1 | 2 | function jSQLParseWhereClause(query, tokens, table_name){ 3 | var orderColumns = []; 4 | while(tokens.length){ 5 | var token = tokens.shift(); 6 | switch(token.type){ 7 | case "KEYWORD": 8 | switch(token.name){ 9 | case "WHERE": 10 | case "AND": 11 | query = query.where(jSQLParseQuery.validateColumnName(tokens.shift().value, table_name)); 12 | break; 13 | case "LIKE": 14 | var substr = tokens.shift().value; 15 | // "%text%" - Contains text 16 | if(substr.substr(0,1)=="%" && substr.substr(substr.length-1,1)=="%"){ 17 | query = query.contains(substr.substr(1,substr.length-2)); 18 | // "%text" - Ends with text 19 | }else if(substr.substr(0,1)=="%"){ 20 | query = query.endsWith(substr.substr(1,substr.length-1)); 21 | // "text%" - Begins with text 22 | }else if(substr.substr(substr.length-1,1)=="%"){ 23 | query = query.beginsWith(substr.substr(0,substr.length-1)); 24 | }else if(substr === "?"){ 25 | // Is a pepared statement, no value available at this time 26 | query = query.preparedLike(); 27 | }else{ 28 | // no "%" on either side. jSQL only supports % when 29 | // the string begins or ends with it, so treat it like an equal 30 | query = query.equals(substr); 31 | } 32 | break; 33 | case "OR": 34 | query = query.or(jSQLParseQuery.validateColumnName(tokens.shift().value, table_name)); 35 | break; 36 | case "LIMIT": 37 | var limit = tokens.shift().value, offset, commaFound=false; 38 | token = tokens.shift(); 39 | if(token.type === "SYMBOL" && token.name === "COMMA") commaFound = true; 40 | else tokens.unshift(token); 41 | if(commaFound){ 42 | offset = limit; 43 | limit = tokens.shift().value; 44 | } 45 | if(tokens.length && !commaFound){ 46 | var token = tokens.shift(); 47 | if(token.type === "KEYWORD" && token.name === "OFFSET"){ 48 | offset = tokens.shift().value; 49 | }else tokens.unshift(token); 50 | } 51 | query = query.limit(limit, offset); 52 | break; 53 | case "ORDER BY": 54 | while(tokens.length){ 55 | var token = tokens.shift(); 56 | if(token.type === "SYMBOL" && token.name === "COMMA") continue; 57 | try{ 58 | var column_name = jSQLParseQuery.validateColumnName(token.value, table_name); 59 | orderColumns.push(column_name); 60 | }catch(e){ 61 | tokens.unshift(token); 62 | break; 63 | } 64 | } 65 | query = query.orderBy(orderColumns); 66 | break; 67 | case "ASC": 68 | if(!orderColumns.length) return _throw(new jSQL_Error("0026")); 69 | query = query.asc(); 70 | break; 71 | case "DESC": 72 | if(!orderColumns.length) return _throw(new jSQL_Error("0027")); 73 | query = query.desc(); 74 | break; 75 | default: return _throw(new jSQL_Parse_Error(token)); 76 | } 77 | break; 78 | case "SYMBOL": 79 | switch(token.name){ 80 | case "EQUALS": 81 | query = query.equals(tokens.shift().value); 82 | break; 83 | case "GREATER THAN": 84 | query = query.greaterThan(tokens.shift().value); 85 | break; 86 | case "LESS THAN": 87 | query = query.lessThan(tokens.shift().value); 88 | break; 89 | case "NOT EQUAL": 90 | query = query.doesNotEqual(tokens.shift().value); 91 | break; 92 | default: return _throw(new jSQL_Parse_Error(token)); 93 | } 94 | break; 95 | default: return _throw(new jSQL_Parse_Error(token, "SYMBOL OR KEYWORD")); 96 | } 97 | } 98 | return query; 99 | } -------------------------------------------------------------------------------- /Gruntfile.js: -------------------------------------------------------------------------------- 1 | 2 | module.exports = function(grunt) { 3 | 4 | var pkg = grunt.file.readJSON('package.json'); 5 | pkg.version = pkg.version.split("."); 6 | var subversion = pkg.version.pop(); 7 | subversion++; 8 | pkg.version.push(subversion); 9 | pkg.version = pkg.version.join("."); 10 | grunt.file.write('package.json', JSON.stringify(pkg, null, 2)); 11 | 12 | console.log("---------------------------------------"); 13 | console.log(" Building jSQL Version "+pkg.version); 14 | console.log("---------------------------------------"); 15 | 16 | grunt.initConfig({ 17 | pkg: pkg, 18 | concat: { 19 | options: { 20 | banner: '/**\n * <%= pkg.name %> - v<%= pkg.version %>' + 21 | '\n * <%= pkg.description %>' + 22 | '\n * @author <%= pkg.author %>' + 23 | '\n * @website <%= pkg.homepage %>' + 24 | '\n * @license <%= pkg.license %>' + 25 | '\n */\n\n' 26 | }, 27 | dist: { 28 | src: [ 29 | 'src/wrapper/head.js.part', 30 | 'src/error_handling/jSQL_Error.js', 31 | 'src/error_handling/jSQL_Lexer_Error.js', 32 | 'src/error_handling/jSQL_Parse_Error.js', 33 | 'src/error_handling/error_handling.js', 34 | 'src/data_types/jSQLDataTypeList.js', 35 | 'src/table/jSQLTable.js', 36 | 'src/query_types/jSQLQuery.js', 37 | 'src/query_types/jSQLDeleteQuery.js', 38 | 'src/query_types/jSQLDropQuery.js', 39 | 'src/query_types/jSQLInsertQuery.js', 40 | 'src/query_types/jSQLSelectQuery.js', 41 | 'src/query_types/jSQLUpdateQuery.js', 42 | 'src/query_types/jSQLCreateQuery.js', 43 | 'src/lexer/jSQLLexer.js', 44 | 'src/lexer/token_types.js', 45 | 'src/lexer/token.js', 46 | 'src/parser/jSQLParseQuery.js', 47 | 'src/parser/jSQLParseCreateTokens.js', 48 | 'src/parser/jSQLParseInsertTokens.js', 49 | 'src/parser/jSQLParseSelectTokens.js', 50 | 'src/parser/jSQLParseUpdateTokens.js', 51 | 'src/parser/jSQLParseDeleteTokens.js', 52 | 'src/parser/jSQLParseDropTokens.js', 53 | 'src/parser/jSQLParseWhereClause.js', 54 | 'src/parser/jSQLWhereClause.js', 55 | 'src/persistence/API.js', 56 | 'src/persistence/persistenceManager.js', 57 | 'src/sugar/createTable.js', 58 | 'src/sugar/select.js', 59 | 'src/sugar/update.js', 60 | 'src/sugar/insertInto.js', 61 | 'src/sugar/dropTable.js', 62 | 'src/sugar/deleteFrom.js', 63 | 'src/sugar/tokenize.js', 64 | 'src/helpers/jSQLReset.js', 65 | 'src/helpers/jSQLMinifier.js', 66 | 'src/helpers/removeQuotes.js', 67 | 'src/import_export/export.js', 68 | 'src/import_export/import.js', 69 | 'src/wrapper/foot.js.part' 70 | ], 71 | dest: 'jSQL.js', 72 | }, 73 | }, 74 | 'string-replace': { 75 | source: { 76 | files: { 77 | "jSQL.js": "jSQL.js" 78 | }, 79 | options: { 80 | replacements: [{ 81 | pattern: /{{ VERSION }}/g, 82 | replacement: '"<%= pkg.version %>"' 83 | }] 84 | } 85 | }, 86 | readme: { 87 | files: { 88 | "README.md": "README.md" 89 | }, 90 | options: { 91 | replacements: [{ 92 | pattern: /\d+.\d+.\d+/g, 93 | replacement: '<%= pkg.version %>' 94 | }] 95 | } 96 | } 97 | }, 98 | uglify: { 99 | options: { 100 | banner: '/*! <%= pkg.name %> - v<%= pkg.version %> */' 101 | }, 102 | build: { 103 | src: 'jSQL.js', 104 | dest: 'jSQL.min.js' 105 | } 106 | } 107 | }); 108 | 109 | grunt.loadNpmTasks('grunt-contrib-concat'); 110 | grunt.loadNpmTasks('grunt-string-replace'); 111 | grunt.loadNpmTasks('grunt-contrib-uglify'); 112 | 113 | grunt.registerTask('default', [ 114 | 'concat', 115 | 'string-replace', 116 | 'uglify' 117 | ]); 118 | 119 | }; -------------------------------------------------------------------------------- /src/error_handling/jSQL_Error.js: -------------------------------------------------------------------------------- 1 | 2 | function jSQL_Error(error_no) { 3 | this.error = error_no; 4 | this.stack = undefined; 5 | var e = new Error(); 6 | if(e.stack) this.stack = e.stack; 7 | this.message = jSQL_Error.message_codes[error_no]; 8 | this.toString = function () { 9 | return "jSQL Error #"+this.error+" - "+this.message; 10 | }; 11 | } 12 | 13 | jSQL_Error.message_codes = { 14 | "0001": "Corrupted function stored in data.", 15 | "0003": "Invalid datatype definition.", 16 | "0004": "DataType must have a `type` property.", 17 | "0005": "DataType must have a `serialize` function.", 18 | "0006": "DataType must have an `unserialize` function.", 19 | "0007": "Unsupported data type.", 20 | "0010": "Invalid constraint.", 21 | "0011": "This table already has a primary key.", 22 | "0012": "renameColumn expects and old column name and a new one, both must be strings.", 23 | "0013": "Column does not exist.", 24 | "0014": "Data must be an array.", 25 | "0015": "Data not structured properly.", 26 | "0016": "Cannot insert a null value in a primary column.", 27 | "0017": "Primary Key violated.", 28 | "0018": "Cannot insert a null value in a unique column.", 29 | "0019": "Unique key violated.", 30 | "0020": "Data type's serialize() method did not return a string.", 31 | "0021": "Table does not exist.", 32 | "0022": "Method does not apply to query type.", 33 | "0023": "Fetch expects paramter one to be 'ASSOC', 'ARRAY', or undefined.", 34 | "0024": "Expected number or quoted string.", 35 | "0025": "Expected 'ORDER BY'.", 36 | "0026": "Must call ORDER BY before using ASC.", 37 | "0027": "Must call ORDER BY before using DESC.", 38 | "0028": "Unintelligible query. Expected 'FROM'.", 39 | "0029": "Unintelligible query. Expected 'TABLE'.", 40 | "0030": "Unintelligible query. Expected 'INTO'.", 41 | "0031": "Unintelligible query. Expected 'VALUES'.", 42 | "0032": "Unintelligible query. Too many values.", 43 | "0033": "Unintelligible query. Columns mismatch.", 44 | "0034": "Invalid Column definition.", 45 | "0035": "Unintelligible query. Expected 'NOT'.", 46 | "0036": "Unintelligible query. Expected 'EXISTS'.", 47 | "0037": "Unintelligible query. expected ')'.", 48 | "0038": "Invalid Arg definition.", 49 | "0039": "Unintelligible query. Expected 'SET'.", 50 | "0040": "Unintelligible query. Expected 'FROM'.", 51 | "0041": "Unintelligible query. WTF?", 52 | "0042": "Must add a conditional before adding another 'Where' condition.", 53 | "0043": "Column name must be a string.", 54 | "0044": "Must add a 'where' clause before the 'equals' call.", 55 | "0045": "Must add a 'where' clause before the 'preparedLike' call.", 56 | "0046": "Must add a 'where' clause before the 'doesNotEqual' call.", 57 | "0047": "Must add a 'where' clause before the 'lessThan' call.", 58 | "0048": "Must add a 'where' clause before the 'greaterThan' call.", 59 | "0049": "Must add a 'where' clause before the 'contains' call.", 60 | "0050": "Must add a 'where' clause before the 'endsWith' call.", 61 | "0051": "Must add a 'where' clause before the 'beginsWith' call.", 62 | "0052": "Must use orderBy clause before using ASC.", 63 | "0053": "Must use orderBy clause before using DESC.", 64 | "0054": "Could not execute query.", 65 | "0055": "Error creating table.", 66 | "0056": "Error opening database.", 67 | "0057": "indexedDB is not supported in this browser.", 68 | "0058": "Could not add data after 10 seconds.", 69 | "0059": "Error updating datastore version.", 70 | "0060": "Could not connect to the indexedDB datastore.", 71 | "0061": "Could not initiate a transaction.", 72 | "0062": "Could not initiate a request.", 73 | "0063": "Browser doesn't support Web SQL or IndexedDB.", 74 | "0064": "Unable towrite to datastore file.", 75 | "0065": "AUTO_INCREMENT column must be a key.", 76 | "0066": "AUTO_INCREMENT column must be an INT type.", 77 | "0067": "API is out of memory, cannot store more data.", 78 | "0068": "Invalid ENUM value.", 79 | "0069": "NUMERIC or INT type invalid or out of range.", 80 | "0070": "Unknown Lexer Error.", 81 | "0071": "Unknown Parser Error.", 82 | "0072": "Inserting null into a non-null column." 83 | }; -------------------------------------------------------------------------------- /src/parser/jSQLParseCreateTokens.js: -------------------------------------------------------------------------------- 1 | 2 | function jSQLParseCreateTokens(tokens){ 3 | var table_name = false, 4 | token, 5 | if_not_exists = false, 6 | keys = [], 7 | params = {}, 8 | temp = false; 9 | 10 | token = tokens.shift(); 11 | 12 | if(token.type === 'KEYWORD' && token.name === 'TEMPORARY'){ 13 | temp = true; 14 | token = tokens.shift(); 15 | } 16 | 17 | if(token.name !== 'TABLE') return _throw(new jSQL_Parse_Error(token, "TABLE")); 18 | token = tokens.shift(); 19 | 20 | if(token.type === "QUALIFIER" && token.name === "IF NOT EXISTS"){ 21 | if_not_exists = true; 22 | token = tokens.shift(); 23 | } 24 | 25 | if(token.type === "IDENTIFIER") table_name = token.value; 26 | 27 | if(!table_name) return _throw(new jSQL_Parse_Error(token, "TABLE NAME")); 28 | 29 | params[table_name] = []; 30 | 31 | token = tokens.shift(); 32 | if(token.type !== "SYMBOL" || token.name !== "LEFT PEREN") 33 | return _throw(new jSQL_Parse_Error(token, "LEFT PEREN")); 34 | 35 | while(tokens.length){ 36 | token = tokens.shift(); 37 | if(token.type === "SYMBOL" && token.name === "COMMA") continue; 38 | if(token.type === "SYMBOL" && token.name === "RIGHT PEREN") break; 39 | 40 | // If this line is actually a key definition rather than a column defintion 41 | if(token.type === "KEYWORD" && (token.name === "UNIQUE KEY" || token.name === "PRIMARY KEY")){ 42 | var key_type = token.name.split(" ")[0].toLowerCase(); 43 | token = tokens.shift(); 44 | if(token.type !== "SYMBOL" || token.name !== "LEFT PEREN") 45 | return _throw(new jSQL_Parse_Error(token, "LEFT PEREN")); 46 | 47 | var key_cols = []; 48 | while(tokens.length){ 49 | token = tokens.shift(); 50 | if(token.type === "SYMBOL" && token.name === "COMMA") continue; 51 | if(token.type === "SYMBOL" && token.name === "RIGHT PEREN") break; 52 | 53 | if(token.type === "IDENTIFIER") var key_col_name = token.value; 54 | else return _throw(new jSQL_Parse_Error(token, "COLUMN NAME")); 55 | 56 | key_cols.push(key_col_name); 57 | } 58 | 59 | if(!key_cols.length) return _throw(new jSQL_Parse_Error(token, "COLUMN NAME")); 60 | 61 | keys.push({column: key_cols, type: key_type}); 62 | continue; 63 | } 64 | 65 | if(token.type === "IDENTIFIER") var col_name = token.value; 66 | else return _throw(new jSQL_Parse_Error(token, "COLUMN NAME")); 67 | 68 | var column = {name: col_name, type:"AMBI", args:[], null: true, default: undefined}; 69 | 70 | token = tokens.shift(); 71 | 72 | // column definition 73 | if(token.name === "DATA TYPE"){ 74 | column.type = token.literal.toUpperCase(); 75 | token = tokens.shift(); 76 | 77 | if(token.type === "SYMBOL" && token.name === "LEFT PEREN"){ 78 | while(tokens.length){ 79 | token = tokens.shift(); 80 | if(token.type === "SYMBOL" && token.name === "COMMA") continue; 81 | if(token.type === "SYMBOL" && token.name === "RIGHT PEREN") break; 82 | if(token.type === "STRING" || token.type === "NUMBER"){ 83 | column.args.push(token.value); 84 | continue; 85 | } 86 | return _throw(new jSQL_Parse_Error(token, "DATA TYPE PARAM OR CLOSING PEREN")); 87 | } 88 | token = tokens.shift(); 89 | } 90 | } 91 | 92 | if(token.type === "KEYWORD" && (token.name === "NULL" || token.name === "NOT NULL")){ 93 | column.null = token.name === "NULL"; 94 | token = tokens.shift(); 95 | } 96 | 97 | if(token.type === "KEYWORD" && token.name === "DEFAULT"){ 98 | column.default = tokens.shift().value; 99 | token = tokens.shift(); 100 | } 101 | 102 | if(token.type === "KEYWORD" && token.name === "AUTO_INCREMENT"){ 103 | column.auto_increment = true; 104 | token = tokens.shift(); 105 | } 106 | 107 | if(token.type === "KEYWORD" && (token.name === "UNIQUE KEY" || token.name === "PRIMARY KEY")){ 108 | keys.push({column: col_name, type: token.name.split(" ")[0].toLowerCase()}); 109 | token = tokens.shift(); 110 | } 111 | 112 | params[table_name].push(column); 113 | 114 | } 115 | 116 | if(tokens.length){ 117 | token = tokens.shift(); 118 | if(token.type !== "SYMBOL" || token.name !== "SEMICOLON") 119 | return _throw(new jSQL_Parse_Error(token, "END OF STATEMENT")); 120 | } 121 | 122 | var query = jSQL.createTable(params, keys); 123 | if(temp) query.temporary(); 124 | if(if_not_exists) query.ifNotExists(); 125 | 126 | return query; 127 | 128 | } -------------------------------------------------------------------------------- /src/lexer/token_types.js: -------------------------------------------------------------------------------- 1 | 2 | jSQLLexer.token_types = [ 3 | 4 | // STRINGs 5 | {pattern: /"(?:[^"\\]|\\.)*"/g, 6 | type: 'STRING', 7 | name: "DQ STRING"}, 8 | {pattern: /'(?:[^'\\]|\\.)*'/g, 9 | type: 'STRING', 10 | name: "SQ STRING"}, 11 | 12 | // COMMENTs 13 | {pattern: /--.*[\n\r$]/g, 14 | type: 'COMMENT', 15 | name: "SINGLE LINE COMMENT"}, 16 | {pattern: /\/\*([\s\S]*?)\*\//g, 17 | type: 'COMMENT', 18 | name: "MULTI LINE COMMENT"}, 19 | 20 | // WHITESPACE 21 | {pattern: /\r?\n|\r/g, 22 | type: 'WHITESPACE', 23 | name: "LINEBREAK"}, 24 | {pattern: /[ \t]/g, 25 | type: 'WHITESPACE', 26 | name: "WHITESPACE"}, 27 | 28 | // NUMBERs 29 | {pattern: /[?-]?\d+.\.\d+/g, 30 | type: 'NUMBER', 31 | name: 'FLOAT'}, 32 | {pattern: /[?-]?\d+/g, 33 | type: 'NUMBER', 34 | name: 'INTEGER'}, 35 | 36 | // QUALIFIERs 37 | {pattern: /if not exists/gi, 38 | type: 'QUALIFIER', 39 | name: "IF NOT EXISTS"}, 40 | 41 | // SYMBOLs 42 | {pattern: /!=/gi, 43 | type: 'SYMBOL', 44 | name: "NOT EQUAL"}, 45 | {pattern: /<>/gi, 46 | type: 'SYMBOL', 47 | name: "NOT EQUAL"}, 48 | {pattern: /\(/gi, 49 | type: 'SYMBOL', 50 | name: "LEFT PEREN"}, 51 | {pattern: /\)/gi, 52 | type: 'SYMBOL', 53 | name: "RIGHT PEREN"}, 54 | {pattern: /,/gi, 55 | type: 'SYMBOL', 56 | name: "COMMA"}, 57 | {pattern: /\?/gi, 58 | type: 'SYMBOL', 59 | name: "QUESTION MARK"}, 60 | {pattern: /,/gi, 61 | type: 'SYMBOL', 62 | name: "COMMA"}, 63 | {pattern: /\*/gi, 64 | type: 'SYMBOL', 65 | name: "ASTERISK"}, 66 | {pattern: /;/gi, 67 | type: 'SYMBOL', 68 | name: "SEMICOLON"}, 69 | {pattern: /=/gi, 70 | type: 'SYMBOL', 71 | name: "EQUALS"}, 72 | {pattern: />/gi, 73 | type: 'SYMBOL', 74 | name: "GREATER THAN"}, 75 | {pattern: /= this.table.auto_inc_seq) this.table.auto_inc_seq = this.newvals[this.columns[n]]+1; 39 | } 40 | row[this.table.colmap[this.columns[n]]] = this.table.normalizeColumnStoreValue(this.columns[n], this.newvals[this.columns[n]]); 41 | } 42 | 43 | var primary_key_columns = this.table.keys.primary.column; 44 | var pk_vals = false; 45 | if(primary_key_columns !== false){ 46 | if(!Array.isArray(primary_key_columns)) primary_key_columns = [primary_key_columns]; 47 | var pk_col; pk_vals = []; 48 | for(var pk=0; pk_col=primary_key_columns[pk]; pk++){ 49 | var primary_index = this.table.colmap[pk_col]; 50 | if(null === row[primary_index]){ 51 | if(this.ignoreFlag === true) return this; 52 | return _throw(new jSQL_Error("0016")); 53 | } 54 | pk_vals.push(row[primary_index]); 55 | } 56 | pk_vals = JSON.stringify(pk_vals); 57 | if(this.table.keys.primary.map.hasOwnProperty(pk_vals) && this.table.keys.primary.map[pk_vals] !== rowIndex){ 58 | if(this.ignoreFlag === true) return this; 59 | return _throw(new jSQL_Error("0017")); 60 | } 61 | } 62 | 63 | // Check the unique keys, There may be multiple and they may be compound 64 | var ukey, uni_vals = []; 65 | for(var k=0; ukey=this.table.keys.unique[k]; k++){ 66 | var key_columns = Array.isArray(ukey.column) ? ukey.column : [ukey.column]; 67 | var col, vals = []; 68 | for(var uk=0; col=key_columns[uk]; uk++){ 69 | var index = this.table.colmap[col]; 70 | if(null === row[index]){ 71 | if(this.ignoreFlag === true) return this; 72 | return _throw(new jSQL_Error("0018")); 73 | } 74 | vals.push(row[index]); 75 | } 76 | vals = JSON.stringify(vals); 77 | if(ukey.map.hasOwnProperty(vals) && ukey.map[vals] !== rowIndex){ 78 | if(this.ignoreFlag === true) return this; 79 | return _throw(new jSQL_Error("0019")); 80 | } 81 | uni_vals.push(vals); 82 | } 83 | 84 | new_rows.push({ 85 | rowIndex: rowIndex, 86 | row: row, 87 | pk_vals: pk_vals, 88 | uni_vals: uni_vals 89 | }); 90 | } 91 | 92 | for(var i=0; i 500){ 155 | mute_jsql_errors = false; 156 | self.isLoading = false; 157 | self.loaded = true; 158 | while(self.loadingCallbacks.length) 159 | self.loadingCallbacks.shift()(); 160 | return; 161 | } 162 | else setTimeout(function(){waitForSchema(tries+1);}, 10); 163 | } 164 | 165 | })(0); 166 | }; 167 | 168 | // Initiate the database 169 | self.init = function(successCallback){ 170 | if("function" !== typeof successCallback) successCallback = function(){}; 171 | self.initiated = true; 172 | if(isNode){ 173 | self.api = new API.nodeAPI(); 174 | self.api.init([{name: "jSQL_data_schema", rows:[]}], successCallback); 175 | }else{ 176 | var priority = self.api_user_priority.concat(self.api_default_priority); 177 | var tried = [], APIIsSet = false; 178 | 179 | (function loop(i){ 180 | if(i>=priority.length){ 181 | if(!APIIsSet) return _throw(new jSQL_Error("0063")); 182 | } 183 | if(self.api_default_priority.indexOf(priority[i]) === -1) return loop(1+i); 184 | if(tried.indexOf(priority[i]) > -1) return loop(1+i); 185 | 186 | try{ 187 | self.api = new API[priority[i]](); 188 | self.api.init([{name: "jSQL_data_schema", rows:[]}], successCallback); 189 | APIIsSet = true; 190 | }catch(ex){ 191 | APIIsSet = false; 192 | } 193 | if(!APIIsSet) loop(1+i); 194 | })(0); 195 | 196 | } 197 | }; 198 | 199 | })(); -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![jSQL Logo](http://i.imgur.com/VQlJKOc.png)](http://pamblam.github.io/jSQL/) 2 | 3 | jSQL (Official) - Version 3.3.19 - *Now available without a prescription!* 4 | 5 | [![npm version](https://badge.fury.io/js/jsql-official.svg)](https://badge.fury.io/js/jsql-official) [![Build Status](https://travis-ci.org/Pamblam/jSQL.svg?branch=master)](https://travis-ci.org/Pamblam/jSQL) [![Inline docs](http://inch-ci.org/github/Pamblam/jSQL.svg?branch=master)](https://github.com/Pamblam/jSQL/wiki) [![Coverage Status](https://coveralls.io/repos/github/Pamblam/jSQL/badge.svg?branch=master)](https://coveralls.io/github/Pamblam/jSQL?branch=master) 6 | 7 |
8 | 9 | jSQL is a state and data management tool as well as a robust SQL engine for both Node and the browser. For complete documentation, please see [the jSQL Wiki](https://github.com/Pamblam/jSQL/wiki). For plugins, live demos and other information see the [official website](http://pamblam.github.io/jSQL/). 10 | 11 | ![jSQL Layers](http://pamblam.github.io/jSQL/imgs/3layers.png) 12 | 13 | # Under the hood, jSQL has 3 layers... 14 | 15 | - **At the Lowest level**, jSQL automatically chooses the best method of storage to save state and interacts directly with it. This layer exposes a persistence method, [`jSQL.commit()`](https://github.com/Pamblam/jSQL/wiki/Persistence-Management#jsqlcommit), which is called to serialize and store all data currently in the jSQL database on the user's hard drive. While the app is open and loaded in the browser, this data is serialized and stored within reach in the [`jSQL.tables`](https://github.com/Pamblam/jSQL/wiki/Persistence-Management#jsqltables) object where the library is able to perform operations on it. 16 | 17 | - **In the middle**, a set of methods are used to build [`jSQLQuery` objects](https://github.com/Pamblam/jSQL/wiki/jSQLquery-interface) which execute CRUD commands on the jSQL database and it's tables. *(See: [`jSQL.createTable()`](https://github.com/Pamblam/jSQL/wiki/Querying-the-Database#jsqlcreatetableparams), [`jSQL.select()`](https://github.com/Pamblam/jSQL/wiki/Querying-the-Database#jsqlselectcolumns), [`jSQL.insertInto()`](https://github.com/Pamblam/jSQL/wiki/Querying-the-Database#jsqlinsertintotablename), [`jSQL.dropTable()`](https://github.com/Pamblam/jSQL/wiki/Querying-the-Database#jsqldroptabletablename), [`jSQL.update()`](https://github.com/Pamblam/jSQL/wiki/Querying-the-Database#jsqlupdatetablename), and [`jSQL.deleteFrom()`](https://github.com/Pamblam/jSQL/wiki/Querying-the-Database#jsqldeletefromtablename))* 18 | 19 | - **At the highest level**, jSQL is an SQL engine (hence the name: Javascript Query Language) which understands a subset of MySQL passed to the [`jSQL.query()`](https://github.com/Pamblam/jSQL/wiki/Querying-the-Database#jsqlquerysqlquery) method, which parses a [jSQL statement](https://github.com/Pamblam/jSQL/wiki/jSQL-Syntax) and uses the above methods to create [`jSQLQuery` objects](https://github.com/Pamblam/jSQL/wiki/jSQLquery-interface) to perform operations on the database. 20 | 21 | jSQL is written with flexibility, ease of use, and efficiency in mind. It supports prepared statements, column typing, and can store any kind of data you need it to, including functions and instances of custom objects. It's applications include caching server-sourced data, state persistence, data management and querying and more. 22 | 23 |
24 | 25 | ## Quick Start 26 | 27 | jSQL is implemented in a single JavaScript file. You only need either the [`jSQL.js`](https://github.com/Pamblam/jSQL/blob/master/jSQL.js) file or the minified [`jSQL.min.js`](https://github.com/Pamblam/jSQL/blob/master/jSQL.min.js) file. Feel free to download them directly or use [`npm`](https://www.npmjs.com/package/jsql-official/tutorial): 28 | 29 | npm install jsql-official 30 | 31 | If you're running jSQL in a browser, include it in a script tag. 32 | 33 | 34 | 35 | Or use the one hosted on the github.io site: 36 | 37 | http://pamblam.github.io/jSQL/scripts/jSQL.min.js 38 | 39 | If you're running jSQL in Node, `require` the jSQL module. 40 | 41 | var jSQL = require("jSQL.js"); 42 | 43 | #### Create a table 44 | 45 | When the database has loaded into memory, you'll want to make sure you have a table to work with. Any database operations that are to be made immediately when the app loads should be called from within the [`jSQL.load()`](https://github.com/Pamblam/jSQL/wiki/Persistence-Management#jsqlloadonloadcallback) callback. 46 | 47 | jSQL.load(function(){ 48 | var sql = "create table if not exists users (name varchar(25), age int)"; 49 | jSQL.query(sql).execute(); 50 | }); 51 | 52 | #### Insert into table 53 | 54 | At some point, you might want to put some data in that table. 55 | 56 | jSQL.query("insert into users ('bob', 34)").execute(); 57 | 58 | Prefer prepared statements? Just replace values with question marks and pass the values to the execute method in an array. 59 | 60 | jSQL.query("insert into users (?, ?)").execute(['bob', 34]); 61 | 62 | #### Select from table 63 | 64 | Once you've got the data in there, you're probably going to want to get it back out. 65 | 66 | var users = jSQL.query("select * from users where name like '%ob'").execute().fetchAll("ASSOC"); 67 | 68 | #### Persisting changes in the browser 69 | 70 | When you've made changes or additions to the database, call [`jSQL.commit()`](https://github.com/Pamblam/jSQL/wiki/Persistence-Management#jsqlcommit) to commit your changes. 71 | 72 | For more information and to read about other update, delete and other operations, see the [jSQL Wiki](https://github.com/Pamblam/jSQL/wiki#jsql-docs). 73 | 74 |
75 | 76 | ## Documentation & Examples 77 | 78 | jSQL is fully documented in the [jSQL Wiki](https://github.com/Pamblam/jSQL/wiki#jsql-docs), which even includes more [simple usage examples](https://github.com/Pamblam/jSQL/wiki/Examples). You may also refer to the package's tests for more [complete and complex examples](https://github.com/Pamblam/jSQL/tree/master/tests). There is also a [live demo](http://pamblam.github.io/jSQL/demo.html) available on the official website. 79 | 80 |
81 | 82 | ## Browser Support 83 | 84 | Works in basically all browsers. jSQL degrades gracefully because it falls back on cookies for persistence if localStorage, IndexedDB and WebSQL are not available. 85 | 86 | While jSQL will work in basically all browsers, these ones are preferred: 87 | 88 | | **FireFox** | **Android** | **Safari** | **Chrome** | **Samsung** | **Blackberry** | **IE** | **Opera** | **Edge** | 89 | |-------------|-------------|------------|------------|-------------|----------------|--------|-----------|----------| 90 | | 2+ | 2.1+ | 3.1+ | 4+ | 4+ | 7+ | 8+ | 11.5+ | 12+ | 91 | 92 |
93 | 94 | ## It's Official 95 | 96 | In the same way Fedex is Federal. 97 | 98 |
99 | 100 | ## Thanks to 101 | 102 | - [**outofgamut**](https://github.com/outofgamut) for the cool "3 layers" graphic. 103 | 104 |
105 | 106 | :us: 107 | -------------------------------------------------------------------------------- /src/data_types/jSQLDataTypeList.js: -------------------------------------------------------------------------------- 1 | 2 | function jSQLDataTypeList(){ 3 | this.list = [{ 4 | type: "NUMERIC", 5 | aliases: ["NUMBER", "DECIMAL", "FLOAT"], 6 | serialize: function(value, args){ 7 | if(value === null) value = 0; 8 | return !isNaN(parseFloat(value)) && isFinite(value) ? 9 | parseFloat(value) : 10 | _throw(new jSQL_Error("0069")) ; 11 | }, 12 | unserialize: function(value, args){ 13 | if(!value) value = 0; 14 | return !isNaN(parseFloat(value)) && isFinite(value) ? 15 | parseFloat(value) : 16 | _throw(new jSQL_Error("0069")) ; 17 | } 18 | },{ 19 | type: "ENUM", 20 | serialize: function(value, args){ 21 | if(value === null) return "jsqlNull"; 22 | for(var i=args.length; i--;) 23 | if(value === removeQuotes(args[i])) return value; 24 | return _throw(new jSQL_Error("0068")); 25 | }, 26 | unserialize: function(value, args){ 27 | if(value === "jsqlNull") return null; 28 | for(var i=args.length; i--;) 29 | if(value === removeQuotes(args[i])) return value; 30 | return _throw(new jSQL_Error("0068")); 31 | } 32 | },{ 33 | type: "TINYINT", 34 | serialize: function(value, args){ 35 | if(value === null) value = 0; 36 | return !isNaN(parseInt(value)) && isFinite(value) && 37 | value >= -128 && value <= 127 ? 38 | parseInt(value) : 0; 39 | }, 40 | unserialize: function(value, args){ 41 | if(!value) value = 0; 42 | return !isNaN(parseInt(value)) && isFinite(value) ? 43 | parseInt(value) : 0; 44 | } 45 | },{ 46 | type: "SMALLINT", 47 | serialize: function(value, args){ 48 | if(value === null) value = 0; 49 | return !isNaN(parseInt(value)) && isFinite(value) && 50 | value >= -32768 && value <= 32767 ? 51 | parseInt(value) : 52 | _throw(new jSQL_Error("0069")) ; 53 | }, 54 | unserialize: function(value, args){ 55 | if(!value) value = 0; 56 | return !isNaN(parseInt(value)) && isFinite(value) ? 57 | parseInt(value) : 58 | _throw(new jSQL_Error("0069")) ; 59 | } 60 | },{ 61 | type: "MEDIUMINT", 62 | serialize: function(value, args){ 63 | if(value === null) value = 0; 64 | return !isNaN(parseInt(value)) && isFinite(value) && 65 | value >= -8388608 && value <= 8388607 ? 66 | parseInt(value) : 67 | _throw(new jSQL_Error("0069")) ; 68 | }, 69 | unserialize: function(value, args){ 70 | if(!value) value = 0; 71 | return !isNaN(parseInt(value)) && isFinite(value) ? 72 | parseInt(value) : 73 | _throw(new jSQL_Error("0069")) ; 74 | } 75 | },{ 76 | type: "INT", 77 | serialize: function(value, args){ 78 | if(value === null) value = 0; 79 | return !isNaN(parseInt(value)) && isFinite(value) && 80 | value >= -2147483648 && value <= 2147483647 ? 81 | parseInt(value) : _throw(new jSQL_Error("0069")); 82 | }, 83 | unserialize: function(value, args){ 84 | if(!value) value = 0; 85 | return !isNaN(parseInt(value)) && isFinite(value) ? 86 | parseInt(value) : _throw(new jSQL_Error("0069")); 87 | } 88 | },{ 89 | type: "BIGINT", 90 | serialize: function(value, args){ 91 | if(value === null) value = 0; 92 | return !isNaN(parseInt(value)) && isFinite(value) && 93 | value >= -9007199254740991 && value <= 9007199254740991 ? 94 | parseInt(value) : _throw(new jSQL_Error("0069")); 95 | }, 96 | unserialize: function(value, args){ 97 | if(!value) value = 0; 98 | return !isNaN(parseInt(value)) && isFinite(value) ? 99 | parseInt(value) : _throw(new jSQL_Error("0069")); 100 | } 101 | },{ 102 | type: "JSON", 103 | aliases: ["ARRAY", "OBJECT"], 104 | serialize: function(value){ 105 | if(value === null) return "jsqlNull"; 106 | if(typeof value === "string") return value; 107 | return JSON.stringify(value); 108 | }, 109 | unserialize: function(value){ 110 | if(value === "jsqlNull") return null; 111 | return JSON.parse(value); 112 | } 113 | },{ 114 | type: "FUNCTION", 115 | serialize: function(value){ 116 | if(value === null) return "jsqlNull"; 117 | if(typeof value !== "function"){ 118 | var f = null; 119 | try{ 120 | eval("f = "+value); 121 | }catch(e){}; 122 | if("function" === typeof f) value = f; 123 | else _throw(new jSQL_Error("0001")); 124 | } 125 | return "jSQLFunct-"+value.toString(); 126 | }, 127 | unserialize: function(value){ 128 | if(value === "jsqlNull") return null; 129 | var p = value.split("-"); 130 | if(p.shift() !== "jSQLFunct") return _throw(new jSQL_Error("0001")); 131 | p = value.split("-"); 132 | p.shift(); 133 | var f = null; 134 | try{ 135 | eval("f = "+p.join("-")); 136 | }catch(e){}; 137 | if("function" === typeof f) return f; 138 | return _throw(new jSQL_Error("0001")); 139 | } 140 | },{ 141 | type: "BOOLEAN", 142 | aliases: ['BOOL'], 143 | serialize: function(value){ 144 | if(value === null) return "jsqlNull"; 145 | return value === true || value.toUpperCase() == "TRUE" || value == 1 ? 146 | "1" : "0" ; 147 | }, 148 | unserialize: function(value){ 149 | if(value === "jsqlNull") return null; 150 | return value === true || value.toUpperCase() == "TRUE" || value == 1 ; 151 | } 152 | },{ 153 | type: "CHAR", 154 | serialize: function(value, args){ 155 | if(value === null) return "jsqlNull"; 156 | return ""+value; 157 | }, 158 | unserialize: function(value, args){ 159 | if(value === "jsqlNull") return null; 160 | var targetLength = args[0]>>0, padString = ' '; 161 | if (value.length > targetLength) return value.substr(0, args[0]); 162 | else { 163 | targetLength = targetLength-value.length; 164 | if (targetLength > padString.length) 165 | padString += padString.repeat(targetLength/padString.length); 166 | return String(value) + padString.slice(0,targetLength); 167 | } 168 | return ""+value; 169 | } 170 | },{ 171 | type: "VARCHAR", 172 | aliases: ["LONGTEXT", "MEDIUMTEXT"], 173 | serialize: function(value, args){ 174 | if(value === null) return "jsqlNull"; 175 | return ""+value; 176 | }, 177 | unserialize: function(value, args){ 178 | if(value === "jsqlNull") return null; 179 | return ""+value; 180 | } 181 | },{ 182 | type: "DATE", 183 | serialize: function(value){ 184 | if(value === null) return "jsqlNull"; 185 | if(!(value instanceof Date)) return new Date(value).getTime(); 186 | return value.getTime(); 187 | }, 188 | unserialize: function(value){ 189 | if(value === "jsqlNull") return null; 190 | return new Date(value); 191 | } 192 | },{ 193 | type: "AMBI", 194 | serialize: function(value){ 195 | if(value === null) return "jsqlNull"; 196 | if(value instanceof Date) return value.getTime(); 197 | if(typeof value === "function") return "jSQLFunct-"+value.toString(); 198 | if(!isNaN(parseFloat(value)) && isFinite(value)) return value; 199 | return ""+value; 200 | }, 201 | unserialize: function(value){ 202 | if(value === "jsqlNull") return null; 203 | if(typeof value === "string"){ 204 | if(value.split("-")[0] === "jSQLFunct"){ 205 | var p = value.split("-"); 206 | p.shift(); 207 | var f = null; 208 | try{ 209 | eval("f = "+p.join("-")); 210 | }catch(e){}; 211 | if("function" === typeof f) return f; 212 | } 213 | } 214 | return value; 215 | } 216 | }]; 217 | this.add = function(type){ 218 | if(typeof type !== "object") return _throw(new jSQL_Error("0003")); 219 | if(undefined === type.type) return _throw(new jSQL_Error("0004")); 220 | if("function" !== typeof type.serialize) return _throw(new jSQL_Error("0005")); 221 | if("function" !== typeof type.unserialize) return _throw(new jSQL_Error("0006")); 222 | this.list.push({ 223 | type: type.type.toUpperCase(), 224 | aliases: Array.isArray(type.aliases) ? type.aliases : [], 225 | serialize: type.serialize, 226 | unserialize: type.unserialize 227 | }); 228 | }; 229 | this.exists = function(type){ 230 | type = type.toUpperCase(); 231 | for(var i=this.list.length;i--;) 232 | if(this.list[i].type===type || 233 | (this.list[i].aliases !== undefined && this.list[i].aliases.indexOf(type) > -1)) 234 | return true; 235 | return false; 236 | }; 237 | this.getByType = function(type){ 238 | type = type.toUpperCase(); 239 | for(var i=this.list.length;i--;) 240 | if(this.list[i].type===type || 241 | (this.list[i].aliases !== undefined && this.list[i].aliases.indexOf(type) > -1)) 242 | return this.list[i]; 243 | return _throw(new jSQL_Error("0007")); 244 | }; 245 | } 246 | -------------------------------------------------------------------------------- /src/parser/jSQLWhereClause.js: -------------------------------------------------------------------------------- 1 | 2 | function jSQLWhereClause(context){ 3 | var self = this; 4 | self.context = context; 5 | self.pendingColumn = ""; 6 | self.conditions = []; 7 | self.LIMIT = 0; 8 | self.OFFSET = 0; 9 | self.finalConditions = []; 10 | self.sortColumn = []; 11 | self.sortDirection = "ASC"; 12 | self.isDistinct = false; 13 | 14 | self.where = function(column){ 15 | if(self.pendingColumn !== "") return _throw(new jSQL_Error("0042")); 16 | if('string' != typeof column) return _throw(new jSQL_Error("0043")); 17 | self.pendingColumn = column; 18 | return self; 19 | }; 20 | 21 | self.equals = function(value){ 22 | if(self.pendingColumn == "") return _throw(new jSQL_Error("0044")); 23 | self.conditions.push({col: self.pendingColumn, type: '=', value: value}); 24 | self.pendingColumn = ""; 25 | return self; 26 | }; 27 | 28 | self.preparedLike = function(){ 29 | if(self.pendingColumn == "") return _throw(new jSQL_Error("0045")); 30 | self.conditions.push({col: self.pendingColumn, type: 'pl', value: "?"}); 31 | self.pendingColumn = ""; 32 | return self; 33 | }; 34 | 35 | self.doesNotEqual = function(value){ 36 | if(self.pendingColumn == "") return _throw(new jSQL_Error("0046")); 37 | self.conditions.push({col: self.pendingColumn, type: '!=', value: value}); 38 | self.pendingColumn = ""; 39 | return self; 40 | }; 41 | 42 | self.lessThan = function(value){ 43 | if(self.pendingColumn == "") return _throw(new jSQL_Error("0047")); 44 | self.conditions.push({col: self.pendingColumn, type: '<', value: value}); 45 | self.pendingColumn = ""; 46 | return self; 47 | }; 48 | 49 | self.greaterThan = function(value){ 50 | if(self.pendingColumn == "") return _throw(new jSQL_Error("0048")); 51 | self.conditions.push({col: self.pendingColumn, type: '>', value: value}); 52 | self.pendingColumn = ""; 53 | return self; 54 | }; 55 | 56 | self.contains = function(value){ 57 | if(self.pendingColumn == "") return _throw(new jSQL_Error("0049")); 58 | self.conditions.push({col: self.pendingColumn, type: '%%', value: value}); 59 | self.pendingColumn = ""; 60 | return self; 61 | }; 62 | 63 | self.endsWith = function(value){ 64 | if(self.pendingColumn == "") return _throw(new jSQL_Error("0050")); 65 | self.conditions.push({col: self.pendingColumn, type: '%-', value: value}); 66 | self.pendingColumn = ""; 67 | return self; 68 | }; 69 | 70 | self.beginsWith = function(value){ 71 | if(self.pendingColumn == "") return _throw(new jSQL_Error("0051")); 72 | self.conditions.push({col: self.pendingColumn, type: '-%', value: value}); 73 | self.pendingColumn = ""; 74 | return self; 75 | }, 76 | 77 | self.and = function(column){ return self.where(column); }; 78 | 79 | self.or = function(column){ 80 | self.finalConditions.push(self.conditions); 81 | self.conditions = []; 82 | return self.where(column); 83 | }; 84 | 85 | self.limit = function(limit, offset){ 86 | self.LIMIT = parseInt(limit); 87 | if(undefined !== offset) 88 | self.OFFSET = parseInt(offset); 89 | return self; 90 | }; 91 | 92 | self.orderBy = function(columns){ 93 | if(!Array.isArray(columns)) columns = [columns]; 94 | self.sortColumn = columns; 95 | return self; 96 | }; 97 | 98 | self.asc = function(){ 99 | if('' == self.sortColumn) return _throw(new jSQL_Error("0052")); 100 | self.sortDirection = "ASC"; 101 | return self; 102 | }; 103 | 104 | self.desc = function(){ 105 | if('' == self.sortColumn) return _throw(new jSQL_Error("0053")); 106 | self.sortDirection = "DESC"; 107 | return self; 108 | }; 109 | 110 | self.execute = function(preparedVals){ 111 | if(undefined === preparedVals) preparedVals = []; 112 | if(self.conditions.length > 0) self.finalConditions.push(self.conditions); 113 | 114 | if(preparedVals.length > 0){ 115 | for(var i = self.finalConditions.length; i--;){ 116 | for(var n = self.finalConditions[i].length; n--;){ 117 | if(self.finalConditions[i][n].value === "?" && self.finalConditions[i][n].type === "pl"){ 118 | var substr = preparedVals.pop(); 119 | // "%text%" - Contains text 120 | if(substr.substr(0,1)=="%" && substr.substr(substr.length-1,1)=="%"){ 121 | self.finalConditions[i][n].value = substr.substr(1,substr.length-2); 122 | self.finalConditions[i][n].type = "%%"; 123 | // "%text" - Ends with text 124 | }else if(substr.substr(0,1)=="%"){ 125 | self.finalConditions[i][n].value = substr.substr(1,substr.length-1); 126 | self.finalConditions[i][n].type = "%-"; 127 | // "text%" - Begins with text 128 | }else if(substr.substr(substr.length-1,1)=="%"){ 129 | self.finalConditions[i][n].value = substr.substr(0,substr.length-1); 130 | self.finalConditions[i][n].type = "-%"; 131 | }else{ 132 | // no "%" on either side. jSQL only supports % when 133 | // the string begins or ends with it, so treat it like an equal 134 | self.finalConditions[i][n].value = substr; 135 | self.finalConditions[i][n].type = "="; 136 | } 137 | 138 | }else if(self.finalConditions[i][n].value === "?" && preparedVals.length > 0){ 139 | self.finalConditions[i][n].value = preparedVals.pop(); 140 | } 141 | } 142 | } 143 | } 144 | return self.context.execute(preparedVals); 145 | }; 146 | 147 | self.fetch = function(Mode){ 148 | return self.context.fetch(Mode); 149 | }; 150 | 151 | self.fetchAll = function(Mode){ 152 | return self.context.fetchAll(Mode); 153 | }; 154 | 155 | self.getResultRowIndexes = function(){ 156 | var resultRowIndexes = []; 157 | for(var i=0; i": 177 | if(isNaN(parseFloat(col_value)) || col_value <= condition.value) 178 | safeCondition = false; 179 | break; 180 | case "<": 181 | if(isNaN(parseFloat(col_value)) || col_value >= condition.value) 182 | safeCondition = false; 183 | break; 184 | case "=": 185 | if(col_value != condition.value) 186 | safeCondition = false; 187 | break; 188 | case "!=": break; 189 | if(col_value == condition.value) 190 | safeCondition = false; 191 | break; 192 | case "%%": 193 | if(col_value.indexOf(condition.value) < 0) 194 | safeCondition = false; 195 | break; 196 | case "%-": 197 | if(col_value.indexOf(condition.value) != col_value.length - condition.value.length) 198 | safeCondition = false; 199 | break; 200 | case "-%": 201 | if(col_value.indexOf(condition.value) != 0) 202 | safeCondition = false; 203 | break; 204 | } 205 | if(!safeCondition) break; 206 | } 207 | if(safeCondition){ 208 | addToResults = true; 209 | break; 210 | } 211 | } 212 | if(addToResults){ 213 | resultRowIndexes.push(i); 214 | } 215 | } 216 | } 217 | 218 | if(self.sortColumn.length > 0){ 219 | resultRowIndexes.sort(function(a, b){ 220 | a=self.context.table.data[a]; 221 | b=self.context.table.data[b]; 222 | return (function srrrrt(i){ 223 | if(undefined === self.sortColumn[i]) return 0; 224 | var sortColumn = self.sortColumn[i]; 225 | var sortColumnIndex = self.context.table.colmap[sortColumn]; 226 | if(a[sortColumnIndex] < b[sortColumnIndex]) return -1; 227 | if(a[sortColumnIndex] > b[sortColumnIndex]) return 1; 228 | return srrrrt(i+1); 229 | }(0)); 230 | }); 231 | if(self.sortDirection == "DESC") resultRowIndexes.reverse(); 232 | } 233 | 234 | if(self.isDistinct){ 235 | var resultRows = []; 236 | for(var i=0; i-1) continue; 248 | newResultRows.push(resultRowIndexes[i]); 249 | distinctRows.push(testRow); 250 | } 251 | resultRowIndexes = newResultRows; 252 | } 253 | 254 | if(self.LIMIT > 0 && resultRowIndexes.length > self.LIMIT){ 255 | if(self.OFFSET > resultRowIndexes.length){ 256 | resultRowIndexes = []; 257 | } 258 | if(self.LIMIT > resultRowIndexes.length) self.LIMIT = resultRowIndexes.length; 259 | if(resultRowIndexes.length){ 260 | resultRowIndexes = resultRowIndexes.slice(self.OFFSET, self.OFFSET+self.LIMIT); 261 | } 262 | } 263 | 264 | return resultRowIndexes; 265 | }; 266 | } 267 | -------------------------------------------------------------------------------- /test/test1.js: -------------------------------------------------------------------------------- 1 | var expect = require('chai').expect; 2 | var jSQL = require("../jSQL.js"); 3 | 4 | jSQL.onError(function(e){ 5 | console.log(e.message); 6 | }); 7 | 8 | jSQL.load(function () { 9 | jSQL.reset(); 10 | describe('Lexer/Parser tests', function () { 11 | 12 | it('create wtf_test table', function(){ 13 | jSQL.query("create table wtf_test (id, name, `somekey` varchar(), something enum('hello','goodbye'), primary key(`id`, name), unique key (somekey) )").execute(); 14 | expect((jSQL.tables.wtf_test !== undefined)).to.be.true; 15 | }); 16 | 17 | it('create typetest table', function(){ 18 | jSQL.query("create table typetest (id numeric(3), data json, greet function, active boolean, `number` int(3), code char(4), name varchar(4), created date, anything ambi, something enum('hello','goodbye') )").execute(); 19 | expect((jSQL.tables.typetest.colmap.number === 4 && jSQL.tables.typetest.types[9].args[0] === 'hello' && jSQL.tables.typetest.types[9].args[1] === 'goodbye')).to.be.true; 20 | }); 21 | 22 | it('create keytest table', function(){ 23 | jSQL.query("create table keytest (id int auto_increment primary key, data, greet, active, `number`, code, name varchar, created date, anything ambi, something enum('hello','goodbye') )").execute(); 24 | expect((jSQL.tables.keytest.keys.primary.column === 'id' && jSQL.tables.keytest.auto_inc_col === 'id')).to.be.true; 25 | }); 26 | 27 | it('create keytest2 table', function(){ 28 | jSQL.query("create table keytest2 (id int auto_increment, data, greet, active, `number`, code, name varchar, created date, anything ambi, something enum('hello','goodbye'), primary key(`id`, name) )").execute(); 29 | expect((jSQL.tables.keytest2.keys.primary.column[0] === 'id' && jSQL.tables.keytest2.keys.primary.column[1] === 'name' && jSQL.tables.keytest2.auto_inc_col === 'id')).to.be.true; 30 | }); 31 | 32 | it('create keytest3 table', function(){ 33 | jSQL.query("create table keytest3 (id int auto_increment, name, num1 int, num2 int, primary key(`id`, name), unique key(num1, num2) )").execute(); 34 | expect(!!jSQL.tables.keytest3).to.be.true; 35 | }); 36 | 37 | it('insert into keytest3 table', function(){ 38 | jSQL.query("insert ignore into keytest3 (name, num1, num2) values (?, ?, ?)").execute(['bob', 3, 5]); 39 | expect(jSQL.tables.keytest3.data.length === 1).to.be.true; 40 | }); 41 | 42 | it('insert into keytest3 table', function(){ 43 | jSQL.query("insert ignore into keytest3 (name, num1, num2) values (?, ?, ?)").execute(['bill', 3, 5]); 44 | expect(jSQL.tables.keytest3.data.length === 1).to.be.true; 45 | }); 46 | 47 | it('insert into keytest3 table', function(){ 48 | jSQL.query("insert ignore into keytest3 (name, num1, num2) values (?, ?, ?)").execute(['bill', 3, 7]); 49 | expect(jSQL.tables.keytest3.data.length === 2).to.be.true; 50 | }); 51 | 52 | it('create smalltest table', function(){ 53 | jSQL.query("create table `smalltest` (id int, str varchar)").execute(); 54 | expect((!!jSQL.tables.smalltest)).to.be.true; 55 | }); 56 | 57 | it('insert into smalltest table', function(){ 58 | jSQL.query("insert into smalltest (id, str) values (7, 'testing')").execute(); 59 | expect((jSQL.tables.smalltest.data.length === 1)).to.be.true; 60 | }); 61 | 62 | it('insert into smalltest table again', function(){ 63 | jSQL.query("insert into `smalltest` values (11, 'testing again')").execute(); 64 | expect((jSQL.tables.smalltest.data.length === 2)).to.be.true; 65 | }); 66 | 67 | it('insert into typetest table', function(){ 68 | jSQL.query("insert into `typetest` values (11, '{\"greeting\":\"hello\"}', 'function(){console.log(\"hello world\")}', true, 3, '72', 'rob', 'Mon, 25 Dec 1995 13:30:00 +0430', 'scooby doo', \"hello\")").execute(); 69 | expect((jSQL.tables.typetest.data.length === 1)).to.be.true; 70 | }); 71 | 72 | it('insert into keytest2 table', function(){ 73 | jSQL.query("insert into `keytest2` (id, `greet`) values (11, 'holla')").execute(); 74 | expect((jSQL.tables.keytest2.data[0][0] === 11)).to.be.true; 75 | }); 76 | 77 | it('insert into keytest2 table again', function(){ 78 | jSQL.query("insert into `keytest2` (`greet`) values ('poopums')").execute(); 79 | expect((jSQL.tables.keytest2.data[1][0] === 12)).to.be.true; 80 | }); 81 | 82 | it('select from typetest table', function(){ 83 | var res = jSQL.query("select * from `typetest` limit 1 offset 0").execute().fetchAll("ARRAY"); 84 | expect((res[0][7] instanceof Date && "function" === typeof res[0][2])).to.be.true; 85 | }); 86 | 87 | it('select from keytest2 table', function(){ 88 | var q = jSQL.query("SELECT id, greet FROM `keytest2` WHERE `id` > 11").execute(); 89 | expect((q.fetch("ASSOC").greet === "poopums")).to.be.true; 90 | }); 91 | 92 | it('select from keytest2 table again', function(){ 93 | var q = jSQL.query("SELECT id, greet FROM `keytest2` WHERE `id` < 12").execute(); 94 | expect((q.fetch("ASSOC").greet === "holla")).to.be.true; 95 | }); 96 | 97 | it('select from keytest2 table again again', function(){ 98 | var q = jSQL.query("SELECT * FROM `keytest2` WHERE `id` < 12 and greet = 'holla'").execute(); 99 | expect((q.fetch("ASSOC").greet === "holla")).to.be.true; 100 | }); 101 | 102 | it('select from keytest2 table once again', function(){ 103 | var q = jSQL.query("SELECT * FROM `keytest2` WHERE `id` < 12 and greet = 'holla' and greet <> \"poo\" or id = 11").execute(); 104 | expect((q.fetch("ASSOC").greet === "holla")).to.be.true; 105 | }); 106 | 107 | it('select from keytest2 table again once again', function(){ 108 | var q = jSQL.query("SELECT * FROM `keytest2` WHERE `greet` LIKE '%olla'").execute(); 109 | expect((q.fetch("ASSOC").greet === "holla")).to.be.true; 110 | }); 111 | 112 | it('select from keytest2 table again once again', function(){ 113 | var q = jSQL.query("SELECT * FROM `keytest2` WHERE `greet` LIKE ?").execute(['%olla']); 114 | expect((q.fetch("ASSOC").greet === "holla")).to.be.true; 115 | }); 116 | 117 | it('select from keytest2 table again once again', function(){ 118 | var q = jSQL.query("SELECT * FROM `keytest2` order by id asc").execute(); 119 | expect((q.fetchAll("ASSOC").length === 2)).to.be.true; 120 | }); 121 | 122 | it('select from keytest2 table again once again', function(){ 123 | var q = jSQL.query("SELECT * FROM `keytest2` order by id, greet desc").execute(); 124 | expect((q.fetchAll("ASSOC").length === 2)).to.be.true; 125 | }); 126 | 127 | it('select from keytest2 table again once again once', function(){ 128 | var q = jSQL.query("SELECT * FROM `keytest2` WHERE `greet` LIKE '%o%'").execute(); 129 | expect((q.fetchAll("ASSOC").length === 2)).to.be.true; 130 | }); 131 | 132 | it('select from keytest2 table again once again once', function(){ 133 | var q = jSQL.query("SELECT * FROM `keytest2` WHERE `greet` LIKE ?").execute(['%o%']); 134 | expect((q.fetchAll("ASSOC").length === 2)).to.be.true; 135 | }); 136 | 137 | it('select from keytest2 table again once again once more', function(){ 138 | var q = jSQL.query("SELECT * FROM `keytest2` WHERE `greet` LIKE 'p%'").execute(); 139 | expect((q.fetchAll("ASSOC").length === 1)).to.be.true; 140 | }); 141 | 142 | it('select from keytest2 table again once again once more', function(){ 143 | var q = jSQL.query("SELECT * FROM `keytest2` WHERE `greet` LIKE ?").execute(['p%']); 144 | expect((q.fetchAll("ASSOC").length === 1)).to.be.true; 145 | }); 146 | 147 | it('update keytest2 table', function(){ 148 | var q = jSQL.query("update `keytest2` set `greet` = 'yyyyo' where id = 12").execute(); 149 | expect((jSQL.tables.keytest2.data[1][2] === 'yyyyo')).to.be.true; 150 | }); 151 | 152 | it('update keytest2 table again', function(){ 153 | var q = jSQL.query("update`keytest2`set`greet`='waddapp',data=\"data\"where`id`=11").execute(); 154 | expect((jSQL.tables.keytest2.data[0][2] === 'waddapp' && jSQL.tables.keytest2.data[0][1] === 'data')).to.be.true; 155 | }); 156 | 157 | it('delete from keytest2 table', function(){ 158 | var q = jSQL.query("delete from `keytest2` where `greet` = 'waddapp'").execute(); 159 | expect((jSQL.tables.keytest2.data.length === 1)).to.be.true; 160 | }); 161 | 162 | it('drop keytest2 table', function(){ 163 | var q = jSQL.query("drop table `keytest2`").execute(); 164 | expect((jSQL.tables.keytest2 === undefined)).to.be.true; 165 | }); 166 | 167 | it("should create a table with a bunch of numbers", function(){ 168 | var sql = jSQL.minify(`CREATE TABLE IF NOT EXISTS nmbrs ( 169 | numba1 tinyint(3), 170 | numba2 smallint(3), 171 | numba3 mediumint(3), 172 | numba4 bigint(3) 173 | )`); 174 | 175 | jSQL.query(sql).execute(); 176 | expect((jSQL.tables.nmbrs !== undefined)).to.be.true; 177 | }); 178 | 179 | it("should insert into a table with a bunch of numbers", function(){ 180 | jSQL.query(`insert into nmbrs values (?, ?, ?, ?)`).execute([3,3,3,3]); 181 | expect((jSQL.tables.nmbrs !== undefined)).to.be.true; 182 | }); 183 | 184 | it("should select from a table with a bunch of numbers", function(){ 185 | var r = jSQL.query(`select * from nmbrs`).execute().fetch("ARRAY"); 186 | expect((r[0] === 3)).to.be.true; 187 | }); 188 | 189 | 190 | it("should create a table with a function", function(){ 191 | jSQL.query(`CREATE TABLE IF NOT EXISTS fff (fff)`).execute(); 192 | expect((jSQL.tables.fff !== undefined)).to.be.true; 193 | }); 194 | 195 | it("should insert into a table with a function", function(){ 196 | jSQL.query(`insert into fff values (?)`).execute([function(){return "poop"}]); 197 | expect((jSQL.tables.fff !== undefined)).to.be.true; 198 | }); 199 | 200 | it("should select from a table with a function", function(){ 201 | var r = jSQL.query(`select * from fff`).execute().fetch("ARRAY"); 202 | expect((r[0]() === "poop")).to.be.true; 203 | }); 204 | 205 | it("should test the null and defult stuff", function(){ 206 | var r = jSQL.query("create table popopopopo (ID int() not null auto_increment primary key, Name varchar(30) default 'bob' )").execute(); 207 | expect(jSQL.tables.popopopopo.types[0].null === false && jSQL.tables.popopopopo.types[1].default === "bob").to.be.true; 208 | }); 209 | 210 | }); 211 | }); -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2018 Rob Parham 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /src/table/jSQLTable.js: -------------------------------------------------------------------------------- 1 | 2 | function jSQLTable(name, columns, data, types, keys, auto_increment){ 3 | var self = this; 4 | self.isTemp = false; // Is a temporary table? 5 | self.name = ""; // Table name 6 | self.columns = []; // Array of column names 7 | self.data = []; // Array of arrays 8 | self.colmap = {}; // Colmap 9 | self.types = []; // array of data types for each column [{type:"",args:[]}..] 10 | self.auto_inc_col = false; // If there's an auto_increment column, it's name 11 | self.auto_inc_seq = 0; // The next value in the auto increment sequence 12 | 13 | // List of column keys on the table 14 | self.keys = { 15 | primary: {column: false, map: {}}, 16 | unique: [] 17 | }; 18 | 19 | self.name = name; 20 | 21 | // If the types array does not exist, create it 22 | if(undefined === types) types = []; 23 | 24 | // If first param is array, no third param 25 | if(Array.isArray(columns) && undefined === data) 26 | // Create the data parameter from column param 27 | {data = columns; columns = [];} 28 | 29 | // If second param is array of objects 30 | // - Create table from first object 31 | // - Generate data (3rd) param 32 | if(Array.isArray(columns) && !Array.isArray(columns[0]) && typeof columns[0]==="object"){ 33 | var cols = [], n; 34 | for(n in columns[0]) 35 | if(columns[0].hasOwnProperty(n)) 36 | cols.push(n); 37 | data = columns; 38 | columns = cols; 39 | } 40 | 41 | self.initColumns(columns, types); 42 | 43 | self.initKeys(keys, auto_increment); 44 | 45 | self.initAI(auto_increment); 46 | 47 | // Load the data, if there is any 48 | if(data !== undefined) self.loadData(data); 49 | } 50 | 51 | jSQLTable.prototype.initColumns = function(columns, types){ 52 | // At this point, columns should be an array 53 | this.columns = columns; 54 | var i; 55 | 56 | // Fill any missing holes in the types array 57 | // with "ambi" which means it can be any type 58 | for(i=0; i -1; 97 | var isPK = this.keys.primary.column === auto_increment; 98 | var isInUKArrayArray = false; 99 | for(var i=this.keys.unique.length; i--;){ 100 | var isInUKArray = Array.isArray(this.keys.unique[i].column) && this.keys.unique[i].column.indexOf(auto_increment) > -1; 101 | var isUK = this.keys.unique[i].column === auto_increment; 102 | if(isInUKArray || isUK) isInUKArrayArray = true; 103 | } 104 | if(isInPKArray || isPK || isInUKArrayArray){ 105 | if(this.types[this.colmap[auto_increment]].type !== "INT") return _throw(new jSQL_Error("0066")); 106 | this.auto_inc_col = auto_increment; 107 | }else return _throw(new jSQL_Error("0065")); 108 | } 109 | }; 110 | 111 | jSQLTable.prototype.renameColumn = function(oldname, newname){ 112 | if(undefined === oldname || "string" !== typeof newname) return _throw(new jSQL_Error("0012")); 113 | if(this.columns.indexOf(oldname) < 0) return _throw(new jSQL_Error("0013")); 114 | // Update the columns 115 | this.columns.splice(this.columns.indexOf(oldname), 1, newname); 116 | // Update the primary keys 117 | if(this.keys.primary.column === oldname) this.keys.primary.column = newname; 118 | if(Array.isArray(this.keys.primary.column)) 119 | for(var i=this.keys.primary.column.length; i--;) 120 | if(this.keys.primary.column[i] === oldname) this.keys.primary.column[i] = newname; 121 | // Update the unique keys 122 | for(var n=this.keys.unique.length; n--;){ 123 | if(this.keys.unique[n].column === oldname) this.keys.unique[n].column = newname; 124 | if(Array.isArray(this.keys.unique[n].column)) 125 | for(i=this.keys.unique[n].column.length; i--;) 126 | if(this.keys.unique[n].column[i] === oldname) this.keys.unique[n].column[i] = newname; 127 | } 128 | // Update colmap 129 | var colmap = {}; 130 | for(var col in this.colmap) 131 | if(this.colmap.hasOwnProperty(col)) 132 | if(col === oldname) colmap[newname] = this.colmap[col]; 133 | else colmap[col] = this.colmap[col]; 134 | this.colmap = colmap; 135 | // Update the AI column 136 | if(this.auto_inc_col === oldname) this.auto_inc_col = newname; 137 | }; 138 | 139 | jSQLTable.prototype.addColumn = function(name, defaultVal, type){ 140 | if(undefined === type || undefined === type.type) 141 | type = {type:"AMBI",args:[], null:true, default: undefined}; 142 | type.type = type.type.toUpperCase(); 143 | if(undefined === defaultVal) defaultVal = null; 144 | if('string' !== typeof name){ 145 | var self = this; 146 | name = (function r(n){ 147 | for(var i=0; i this.columns.length) 181 | this.addColumn(); 182 | while(data.length < this.columns.length) 183 | data.push(null); 184 | for(n=0; n -1){ 205 | // ...let the undefined row inherit this title, 206 | this.renameColumn("u0", colname); 207 | // and shift the unknown column titles 208 | var i=1; while(this.columns.indexOf("u"+i)>-1)this.renameColumn("u"+i, "u"+(i-1)); 209 | // ..otherwise, just add the column to the table. 210 | }else this.addColumn(colname); 211 | } 212 | 213 | for(n=0; n= this.auto_inc_seq) this.auto_inc_seq = parseInt(row[i], 10)+1; 232 | } 233 | row[i] = this.normalizeColumnStoreValue(this.columns[i], row[i]); 234 | } 235 | if(false === this.updateKeysOnInsert(row, ignore)) return false; 236 | this.data.push(row); 237 | }; 238 | 239 | jSQLTable.prototype.updateKeysOnInsert = function(row, ignore){ 240 | // Make sure the primary key(s) is/are not violated 241 | // There can only be one primary key, but if it's an array it 242 | // is treated as a compound key 243 | if(this.keys.primary.column){ 244 | var primary_key_columns = Array.isArray(this.keys.primary.column) ? this.keys.primary.column : [this.keys.primary.column]; 245 | var pk_col, pk_vals = []; 246 | for(var pk=0; pk-1 && value === null) return _throw(new jSQL_Error("0072")); 289 | 290 | if(null === value && type.default !== undefined) value = type.default; 291 | var storeVal = jSQL.types.getByType(type.type.toUpperCase()).serialize(value, type.args); 292 | if((!isNaN(parseFloat(storeVal)) && isFinite(storeVal)) || typeof storeVal === "string") 293 | return storeVal; 294 | return _throw(new jSQL_Error("0020")); 295 | }; 296 | 297 | jSQLTable.prototype.normalizeColumnFetchValue = function(colName, value){ 298 | var type = this.types[this.colmap[colName]]; 299 | return jSQL.types.getByType(type.type.toUpperCase()).unserialize(value, type.args); 300 | }; -------------------------------------------------------------------------------- /src/persistence/API.js: -------------------------------------------------------------------------------- 1 | 2 | /* istanbul ignore next */ 3 | var API = { 4 | 5 | cookieAPI: function(){ 6 | var self = this; 7 | 8 | var setCookie = function(cname, cvalue) { 9 | var d = new Date(); 10 | d.setTime(d.getTime() + 864000000000); 11 | var expires = "expires="+d.toUTCString(); 12 | document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/"; 13 | }; 14 | 15 | var getCookie = function(cname) { 16 | var name = cname + "="; 17 | var ca = document.cookie.split(';'); 18 | for(var i = 0; i < ca.length; i++) { 19 | var c = ca[i]; 20 | while (c.charAt(0) == ' ') c = c.substring(1); 21 | if (c.indexOf(name) == 0) return c.substring(name.length, c.length); 22 | } 23 | return ""; 24 | }; 25 | 26 | self.init = function(modelData, successCallback){ 27 | if("function" !== typeof successCallback) successCallback = function(){}; 28 | for(var i=0, db; db=modelData[i]; i++) self.insert(db.name, db.rows); 29 | successCallback(); 30 | }; 31 | 32 | self.insert = function(model, rows, successCallback){ 33 | if("function" !== typeof successCallback) successCallback = function(){}; 34 | var data; 35 | try{ data = JSON.parse(getCookie(model)); } 36 | catch(e){ data = []; } 37 | if(!Array.isArray(data)) data = []; 38 | for(var n=0; n 1000){ 215 | clearInterval(ivl); 216 | return _throw(new jSQL_Error("0058")); 217 | } 218 | working = false; 219 | } 220 | }, 10); 221 | 222 | }; 223 | 224 | request.onsuccess = function (event) { 225 | var setVersionRequest; 226 | self.db = event.target.result; 227 | version = String(version); 228 | if (self.db.setVersion && version !== self.db.version) { 229 | setVersionRequest = self.db.setVersion(version); 230 | setVersionRequest.onfailure = function(){ 231 | return _throw(new jSQL_Error("0059")); 232 | }; 233 | setVersionRequest.onsuccess = function (event) { 234 | installModels(); 235 | setVersionRequest.result.oncomplete = function () { 236 | successCallback(); 237 | }; 238 | }; 239 | } else { 240 | // User already has the datastores, no need to reinstall 241 | successCallback(); 242 | } 243 | }; 244 | request.onupgradeneeded = function (event) { 245 | self.db = event.target.result; 246 | installModels(); 247 | }; 248 | request.onerror = function (event) { 249 | return _throw(new jSQL_Error("0060")); 250 | }; 251 | }; 252 | 253 | // Insert a group of rows 254 | self.insert = function(model, data, successCallback) { 255 | if(typeof successCallback !== "function") successCallback = function(){}; 256 | var transaction = self.db.transaction([model], undefined === IDBTransaction.READ_WRITE ? 'readwrite' : IDBTransaction.READ_WRITE); 257 | var store, i, request; 258 | var total = data.length; 259 | 260 | var successCallbackInner = function() { 261 | total = total - 1; 262 | if (total === 0) successCallback(total); 263 | }; 264 | 265 | transaction.onerror = function(){ return _throw(new jSQL_Error("0061")); }; 266 | store = transaction.objectStore(model); 267 | for (i in data) { 268 | if (data.hasOwnProperty(i)) { 269 | request = store.add(data[i]); 270 | request.onsuccess = successCallbackInner; 271 | request.onerror = function(){ return _throw(new jSQL_Error("0062")); }; 272 | } 273 | } 274 | }; 275 | 276 | // Delete all items from the database 277 | self.delete = function(model, successCallback) { 278 | if(typeof successCallback != "function") successCallback = function(){}; 279 | var transaction = self.db.transaction([model], undefined === IDBTransaction.READ_WRITE ? 'readwrite' : IDBTransaction.READ_WRITE), store, request; 280 | transaction.onerror = function(){ return _throw(new jSQL_Error("0061")); }; 281 | store = transaction.objectStore(model); 282 | request = store.clear(); 283 | request.onerror = function(){ return _throw(new jSQL_Error("0062")); }; 284 | request.onsuccess = successCallback; 285 | }; 286 | 287 | // Get all data from the datastore 288 | self.select = function(model, successCallback) { 289 | if("function" !== typeof successCallback) successCallback = function(){}; 290 | var transaction = self.db.transaction([model], undefined === IDBTransaction.READ_ONLY ? 'readonly' : IDBTransaction.READ_ONLY), store, request, results = []; 291 | transaction.onerror = function(){ return _throw(new jSQL_Error("0061")); };; 292 | store = transaction.objectStore(model); 293 | request = store.openCursor(); 294 | request.onerror = function(){ return _throw(new jSQL_Error("0062")); }; 295 | var successCBCalled = false; 296 | request.onsuccess = function (event) { 297 | if(successCBCalled) return; 298 | var result = event.target.result; 299 | if (!result) { 300 | successCBCalled = true; 301 | successCallback(results); 302 | return; 303 | }else{ 304 | results.push(result.value); 305 | result['continue'](); 306 | } 307 | }; 308 | }; 309 | }, 310 | 311 | WebSQLAPI: function() { 312 | var self = this; 313 | self.db = null; 314 | 315 | // private function to execute a query 316 | var __runQuery = function(query, data, successCallback, failureCallback) { 317 | if(typeof successCallback != "function") successCallback = function(){}; 318 | if(typeof failureCallback != "function") failureCallback = function(){ return _throw(new jSQL_Error("0054")); }; 319 | 320 | var i, l, remaining; 321 | 322 | if(!Array.isArray(data[0])) data = [data]; 323 | remaining = data.length; 324 | var innerSuccessCallback = function(tx, rs) { 325 | var i, l, output = []; 326 | remaining = remaining - 1; 327 | if (!remaining) { 328 | for (i = 0, l = rs.rows.length; i < l; i = i + 1){ 329 | var j = rs.rows.item(i).json; 330 | //j = JSON.parse(j); 331 | output.push(j); 332 | } 333 | successCallback(output); 334 | } 335 | }; 336 | self.db.transaction(function (tx) { 337 | for (i = 0, l = data.length; i < l; i = i + 1) { 338 | tx.executeSql(query, data[i], innerSuccessCallback, failureCallback); 339 | } 340 | }); 341 | }; 342 | 343 | // Check that datastores exist. 344 | // If not, create and populate them. 345 | self.init = function(modelData, successCallback){ 346 | if(typeof successCallback != "function") successCallback = function(){}; 347 | 348 | var installModels = function(){ 349 | try{ 350 | for(var i=modelData.length; i--;) 351 | (function(n, r){ 352 | __runQuery("DROP TABLE IF EXISTS "+n, [], function(){ 353 | __runQuery("CREATE TABLE IF NOT EXISTS "+n+"(json TEXT)", [], function(){ 354 | self.insert(n, r); 355 | }); 356 | }); 357 | })(modelData[i].name, modelData[i].rows); 358 | }catch(e){ return _throw(new jSQL_Error("0055")); } 359 | }; 360 | 361 | try { 362 | var dbname = window.location.href.replace(/\W+/g, ""); // use the current url to keep it unique 363 | self.db = openDatabase("jSQL_"+dbname, "1.0", "jSQL "+dbname, (5 * 1024 * 1024)); 364 | } catch(e){ return _throw(new jSQL_Error("0056")); } 365 | 366 | __runQuery("SELECT COUNT(*) FROM "+modelData[0].name, [], null, function(){ 367 | installModels(); 368 | }); 369 | 370 | successCallback(); 371 | }; 372 | 373 | // Insert a group of rows 374 | self.insert = function(model, data, successCallback) { 375 | if(typeof successCallback !== "function") successCallback = function(){}; 376 | 377 | var remaining = data.length, i, l, insertData = []; 378 | if (remaining === 0) successCallback(); 379 | 380 | // Convert article array of objects to array of arrays 381 | for (i = 0, l = data.length; i < l; i = i + 1) 382 | insertData[i] = [JSON.stringify(data[i])]; 383 | __runQuery("INSERT INTO "+model+" (json) VALUES (?);", insertData, successCallback); 384 | }; 385 | 386 | // Delete all items from the database 387 | self.delete = function(model, successCallback) { 388 | if(typeof successCallback !== "function") successCallback = function(){}; 389 | __runQuery("DELETE FROM "+model, [], successCallback); 390 | }; 391 | 392 | // Get all data from the datastore 393 | self.select = function(model, successCallback) { 394 | __runQuery("SELECT json FROM "+model, [], function(res){ 395 | var r = []; 396 | for(var i = res.length; i--;) 397 | r.push(JSON.parse(res[i])); 398 | successCallback(r); 399 | }); 400 | }; 401 | 402 | } 403 | }; 404 | -------------------------------------------------------------------------------- /jSQL.min.js: -------------------------------------------------------------------------------- 1 | /*! jsql-official - v3.3.19 */ 2 | !function(){var isNode=!("undefined"==typeof module||!module.exports),jSQL=function(){"use strict";function jSQL_Error(e){this.error=e,this.stack=void 0;var t=new Error;t.stack&&(this.stack=t.stack),this.message=jSQL_Error.message_codes[e],this.toString=function(){return"jSQL Error #"+this.error+" - "+this.message}}function jSQL_Lexer_Error(e,t){var r=t.length>e+25?25:t.length-e,n=t.substr(e,r);this.error="0070",this.message="Unknown token near char "+e+" of "+t.length+' "'+n+'".',this.stack=void 0;var i=new Error;i.stack&&(this.stack=i.stack),this.toString=function(){return"jSQL Lexer Error #"+this.error+" - "+this.message}}function jSQL_Parse_Error(e,t){this.error="0071",this.message="Unexpected "+e.type+" ("+e.name+") at character "+e.input_pos+".",t&&(this.message+=" Expected "+t+"."),this.stack=void 0;var r=new Error;r.stack&&(this.stack=r.stack),this.toString=function(){return"jSQL Parse Error #"+this.error+" - "+this.message}}jSQL_Error.message_codes={"0001":"Corrupted function stored in data.","0003":"Invalid datatype definition.","0004":"DataType must have a `type` property.","0005":"DataType must have a `serialize` function.","0006":"DataType must have an `unserialize` function.","0007":"Unsupported data type.","0010":"Invalid constraint.","0011":"This table already has a primary key.","0012":"renameColumn expects and old column name and a new one, both must be strings.","0013":"Column does not exist.","0014":"Data must be an array.","0015":"Data not structured properly.","0016":"Cannot insert a null value in a primary column.","0017":"Primary Key violated.","0018":"Cannot insert a null value in a unique column.","0019":"Unique key violated.","0020":"Data type's serialize() method did not return a string.","0021":"Table does not exist.","0022":"Method does not apply to query type.","0023":"Fetch expects paramter one to be 'ASSOC', 'ARRAY', or undefined.","0024":"Expected number or quoted string.","0025":"Expected 'ORDER BY'.","0026":"Must call ORDER BY before using ASC.","0027":"Must call ORDER BY before using DESC.","0028":"Unintelligible query. Expected 'FROM'.","0029":"Unintelligible query. Expected 'TABLE'.","0030":"Unintelligible query. Expected 'INTO'.","0031":"Unintelligible query. Expected 'VALUES'.","0032":"Unintelligible query. Too many values.","0033":"Unintelligible query. Columns mismatch.","0034":"Invalid Column definition.","0035":"Unintelligible query. Expected 'NOT'.","0036":"Unintelligible query. Expected 'EXISTS'.","0037":"Unintelligible query. expected ')'.","0038":"Invalid Arg definition.","0039":"Unintelligible query. Expected 'SET'.","0040":"Unintelligible query. Expected 'FROM'.","0041":"Unintelligible query. WTF?","0042":"Must add a conditional before adding another 'Where' condition.","0043":"Column name must be a string.","0044":"Must add a 'where' clause before the 'equals' call.","0045":"Must add a 'where' clause before the 'preparedLike' call.","0046":"Must add a 'where' clause before the 'doesNotEqual' call.","0047":"Must add a 'where' clause before the 'lessThan' call.","0048":"Must add a 'where' clause before the 'greaterThan' call.","0049":"Must add a 'where' clause before the 'contains' call.","0050":"Must add a 'where' clause before the 'endsWith' call.","0051":"Must add a 'where' clause before the 'beginsWith' call.","0052":"Must use orderBy clause before using ASC.","0053":"Must use orderBy clause before using DESC.","0054":"Could not execute query.","0055":"Error creating table.","0056":"Error opening database.","0057":"indexedDB is not supported in this browser.","0058":"Could not add data after 10 seconds.","0059":"Error updating datastore version.","0060":"Could not connect to the indexedDB datastore.","0061":"Could not initiate a transaction.","0062":"Could not initiate a request.","0063":"Browser doesn't support Web SQL or IndexedDB.","0064":"Unable towrite to datastore file.","0065":"AUTO_INCREMENT column must be a key.","0066":"AUTO_INCREMENT column must be an INT type.","0067":"API is out of memory, cannot store more data.","0068":"Invalid ENUM value.","0069":"NUMERIC or INT type invalid or out of range.","0070":"Unknown Lexer Error.","0071":"Unknown Parser Error.","0072":"Inserting null into a non-null column."};var error_handler_function=function(){},mute_jsql_errors=!1;function _throw(e,t){throw!0!==t&&!0!==mute_jsql_errors&&error_handler_function(e),e}function onError(e){"function"==typeof e&&(error_handler_function=e)}function jSQLDataTypeList(){this.list=[{type:"NUMERIC",aliases:["NUMBER","DECIMAL","FLOAT"],serialize:function(e,t){return null===e&&(e=0),!isNaN(parseFloat(e))&&isFinite(e)?parseFloat(e):_throw(new jSQL_Error("0069"))},unserialize:function(e,t){return e||(e=0),!isNaN(parseFloat(e))&&isFinite(e)?parseFloat(e):_throw(new jSQL_Error("0069"))}},{type:"ENUM",serialize:function(e,t){if(null===e)return"jsqlNull";for(var r=t.length;r--;)if(e===removeQuotes(t[r]))return e;return _throw(new jSQL_Error("0068"))},unserialize:function(e,t){if("jsqlNull"===e)return null;for(var r=t.length;r--;)if(e===removeQuotes(t[r]))return e;return _throw(new jSQL_Error("0068"))}},{type:"TINYINT",serialize:function(e,t){return null===e&&(e=0),!isNaN(parseInt(e))&&isFinite(e)&&-128<=e&&e<=127?parseInt(e):0},unserialize:function(e,t){return e||(e=0),!isNaN(parseInt(e))&&isFinite(e)?parseInt(e):0}},{type:"SMALLINT",serialize:function(e,t){return null===e&&(e=0),!isNaN(parseInt(e))&&isFinite(e)&&-32768<=e&&e<=32767?parseInt(e):_throw(new jSQL_Error("0069"))},unserialize:function(e,t){return e||(e=0),!isNaN(parseInt(e))&&isFinite(e)?parseInt(e):_throw(new jSQL_Error("0069"))}},{type:"MEDIUMINT",serialize:function(e,t){return null===e&&(e=0),!isNaN(parseInt(e))&&isFinite(e)&&-8388608<=e&&e<=8388607?parseInt(e):_throw(new jSQL_Error("0069"))},unserialize:function(e,t){return e||(e=0),!isNaN(parseInt(e))&&isFinite(e)?parseInt(e):_throw(new jSQL_Error("0069"))}},{type:"INT",serialize:function(e,t){return null===e&&(e=0),!isNaN(parseInt(e))&&isFinite(e)&&-2147483648<=e&&e<=2147483647?parseInt(e):_throw(new jSQL_Error("0069"))},unserialize:function(e,t){return e||(e=0),!isNaN(parseInt(e))&&isFinite(e)?parseInt(e):_throw(new jSQL_Error("0069"))}},{type:"BIGINT",serialize:function(e,t){return null===e&&(e=0),!isNaN(parseInt(e))&&isFinite(e)&&-9007199254740991<=e&&e<=9007199254740991?parseInt(e):_throw(new jSQL_Error("0069"))},unserialize:function(e,t){return e||(e=0),!isNaN(parseInt(e))&&isFinite(e)?parseInt(e):_throw(new jSQL_Error("0069"))}},{type:"JSON",aliases:["ARRAY","OBJECT"],serialize:function(e){return null===e?"jsqlNull":"string"==typeof e?e:JSON.stringify(e)},unserialize:function(e){return"jsqlNull"===e?null:JSON.parse(e)}},{type:"FUNCTION",serialize:function(value){if(null===value)return"jsqlNull";if("function"!=typeof value){var f=null;try{eval("f = "+value)}catch(e){}"function"==typeof f?value=f:_throw(new jSQL_Error("0001"))}return"jSQLFunct-"+value.toString()},unserialize:function(value){if("jsqlNull"===value)return null;var p=value.split("-");if("jSQLFunct"!==p.shift())return _throw(new jSQL_Error("0001"));p=value.split("-"),p.shift();var f=null;try{eval("f = "+p.join("-"))}catch(e){}return"function"==typeof f?f:_throw(new jSQL_Error("0001"))}},{type:"BOOLEAN",aliases:["BOOL"],serialize:function(e){return null===e?"jsqlNull":!0===e||"TRUE"==e.toUpperCase()||1==e?"1":"0"},unserialize:function(e){return"jsqlNull"===e?null:!0===e||"TRUE"==e.toUpperCase()||1==e}},{type:"CHAR",serialize:function(e,t){return null===e?"jsqlNull":""+e},unserialize:function(e,t){if("jsqlNull"===e)return null;var r=t[0]>>0,n=" ";return e.length>r?e.substr(0,t[0]):((r-=e.length)>n.length&&(n+=n.repeat(r/n.length)),String(e)+n.slice(0,r))}},{type:"VARCHAR",aliases:["LONGTEXT","MEDIUMTEXT"],serialize:function(e,t){return null===e?"jsqlNull":""+e},unserialize:function(e,t){return"jsqlNull"===e?null:""+e}},{type:"DATE",serialize:function(e){return null===e?"jsqlNull":e instanceof Date?e.getTime():new Date(e).getTime()},unserialize:function(e){return"jsqlNull"===e?null:new Date(e)}},{type:"AMBI",serialize:function(e){return null===e?"jsqlNull":e instanceof Date?e.getTime():"function"==typeof e?"jSQLFunct-"+e.toString():!isNaN(parseFloat(e))&&isFinite(e)?e:""+e},unserialize:function(value){if("jsqlNull"===value)return null;if("string"==typeof value&&"jSQLFunct"===value.split("-")[0]){var p=value.split("-");p.shift();var f=null;try{eval("f = "+p.join("-"))}catch(e){}if("function"==typeof f)return f}return value}}],this.add=function(e){return"object"!=typeof e?_throw(new jSQL_Error("0003")):void 0===e.type?_throw(new jSQL_Error("0004")):"function"!=typeof e.serialize?_throw(new jSQL_Error("0005")):"function"!=typeof e.unserialize?_throw(new jSQL_Error("0006")):void this.list.push({type:e.type.toUpperCase(),aliases:Array.isArray(e.aliases)?e.aliases:[],serialize:e.serialize,unserialize:e.unserialize})},this.exists=function(e){e=e.toUpperCase();for(var t=this.list.length;t--;)if(this.list[t].type===e||void 0!==this.list[t].aliases&&-1=this.table.auto_inc_seq&&(this.table.auto_inc_seq=this.newvals[this.columns[o]]+1)),a[this.table.colmap[this.columns[o]]]=this.table.normalizeColumnStoreValue(this.columns[o],this.newvals[this.columns[o]]);var u=this.table.keys.primary.column,l=!1;if(!1!==u){var h;Array.isArray(u)||(u=[u]),l=[];for(var c=0;h=u[c];c++){var f=this.table.colmap[h];if(null===a[f])return!0===this.ignoreFlag?this:_throw(new jSQL_Error("0016"));l.push(a[f])}if(l=JSON.stringify(l),this.table.keys.primary.map.hasOwnProperty(l)&&this.table.keys.primary.map[l]!==s)return!0===this.ignoreFlag?this:_throw(new jSQL_Error("0017"))}for(var p,y=[],m=0;p=this.table.keys.unique[m];m++){for(var S=Array.isArray(p.column)?p.column:[p.column],d=[],E=0;g=S[E];E++){var L=this.table.colmap[g];if(null===a[L])return!0===this.ignoreFlag?this:_throw(new jSQL_Error("0018"));d.push(a[L])}if(d=JSON.stringify(d),p.map.hasOwnProperty(d)&&p.map[d]!==s)return!0===this.ignoreFlag?this:_throw(new jSQL_Error("0019"));y.push(d)}i.push({rowIndex:s,row:a,pk_vals:l,uni_vals:y})}for(t=0;t",value:e}),S.pendingColumn="",S)},S.contains=function(e){return""==S.pendingColumn?_throw(new jSQL_Error("0049")):(S.conditions.push({col:S.pendingColumn,type:"%%",value:e}),S.pendingColumn="",S)},S.endsWith=function(e){return""==S.pendingColumn?_throw(new jSQL_Error("0050")):(S.conditions.push({col:S.pendingColumn,type:"%-",value:e}),S.pendingColumn="",S)},S.beginsWith=function(e){return""==S.pendingColumn?_throw(new jSQL_Error("0051")):(S.conditions.push({col:S.pendingColumn,type:"-%",value:e}),S.pendingColumn="",S)},S.and=function(e){return S.where(e)},S.or=function(e){return S.finalConditions.push(S.conditions),S.conditions=[],S.where(e)},S.limit=function(e,t){return S.LIMIT=parseInt(e),void 0!==t&&(S.OFFSET=parseInt(t)),S},S.orderBy=function(e){return Array.isArray(e)||(e=[e]),S.sortColumn=e,S},S.asc=function(){return""==S.sortColumn?_throw(new jSQL_Error("0052")):(S.sortDirection="ASC",S)},S.desc=function(){return""==S.sortColumn?_throw(new jSQL_Error("0053")):(S.sortDirection="DESC",S)},S.execute=function(e){if(void 0===e&&(e=[]),0":(isNaN(parseFloat(l))||l<=o.value)&&(s=!1);break;case"<":(isNaN(parseFloat(l))||l>=o.value)&&(s=!1);break;case"=":l!=o.value&&(s=!1);break;case"!=":break;case"%%":l.indexOf(o.value)<0&&(s=!1);break;case"%-":l.indexOf(o.value)!=l.length-o.value.length&&(s=!1);break;case"-%":0!=l.indexOf(o.value)&&(s=!1)}if(!s)break}if(s){r=!0;break}}r&&e.push(t)}if(0s[n]?1:e(t+1)}(0)}),"DESC"==S.sortDirection&&e.reverse()),S.isDistinct){var h=[];for(t=0;tS.LIMIT&&(S.OFFSET>e.length&&(e=[]),S.LIMIT>e.length&&(S.LIMIT=e.length),e.length&&(e=e.slice(S.OFFSET,S.OFFSET+S.LIMIT))),e}}jSQLTable.prototype.initColumns=function(e,t){var r;for(this.columns=e,r=0;rthis.columns.length;)this.addColumn();for(;e.length=this.auto_inc_seq&&(this.auto_inc_seq=parseInt(r[n],10)+1)),r[n]=this.normalizeColumnStoreValue(this.columns[n],r[n]);if(!1===this.updateKeysOnInsert(r,t))return!1;this.data.push(r)},jSQLTable.prototype.updateKeysOnInsert=function(e,t){if(this.keys.primary.column){for(var r,n=Array.isArray(this.keys.primary.column)?this.keys.primary.column:[this.keys.primary.column],i=[],s=0;s/gi,type:"SYMBOL",name:"NOT EQUAL"},{pattern:/\(/gi,type:"SYMBOL",name:"LEFT PEREN"},{pattern:/\)/gi,type:"SYMBOL",name:"RIGHT PEREN"},{pattern:/,/gi,type:"SYMBOL",name:"COMMA"},{pattern:/\?/gi,type:"SYMBOL",name:"QUESTION MARK"},{pattern:/,/gi,type:"SYMBOL",name:"COMMA"},{pattern:/\*/gi,type:"SYMBOL",name:"ASTERISK"},{pattern:/;/gi,type:"SYMBOL",name:"SEMICOLON"},{pattern:/=/gi,type:"SYMBOL",name:"EQUALS"},{pattern:/>/gi,type:"SYMBOL",name:"GREATER THAN"},{pattern:/=n.length&&!s)return _throw(new jSQL_Error("0063"));if(-1===u.api_default_priority.indexOf(n[t]))return e(1+t);if(-1