-
Notifications
You must be signed in to change notification settings - Fork 689
Expand file tree
/
Copy path70insert.js
More file actions
executable file
·459 lines (421 loc) · 13.9 KB
/
70insert.js
File metadata and controls
executable file
·459 lines (421 loc) · 13.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
/*
//
// INSERT for Alasql.js
// Date: 03.11.2014
// (c) 2014, Andrey Gershun
//
*/
/* global yy alasql*/
yy.Insert = function (params) {
return Object.assign(this, params);
};
yy.Insert.prototype.toString = function () {
var s = 'INSERT ';
if (this.orreplace) s += 'OR REPLACE ';
if (this.replaceonly) s = 'REPLACE ';
if (this.ignore) s += 'IGNORE ';
s += 'INTO ' + this.into.toString();
if (this.columns) s += '(' + this.columns.toString() + ')';
if (this.values) {
var values = this.values.map(function (value) {
return '(' + value.toString() + ')';
});
s += ' VALUES ' + values.join(',');
}
if (this.select) s += ' ' + this.select.toString();
if (this.setcolumns) {
s += ' SET ';
s += this.setcolumns.map(col => col.toString()).join(', ');
}
if (this.output) {
s += ' OUTPUT ';
s += this.output.columns.map(col => col.toString()).join(', ');
if (this.output.intovar) {
s += ' INTO ' + this.output.method + this.output.intovar;
} else if (this.output.intotable) {
s += ' INTO ' + this.output.intotable.toString();
if (this.output.intocolumns) {
s += '(' + this.output.intocolumns.map(col => col.toString()).join(', ') + ')';
}
}
}
return s;
};
yy.Insert.prototype.toJS = function (context, tableid, defcols) {
// console.log('Expression',this);
// if(this.expression.reduced) return 'true';
// return this.expression.toJS(context, tableid, defcols);
// console.log('Select.toJS', 81, this.queriesidx);
// var s = 'this.queriesdata['+(this.queriesidx-1)+'][0]';
var s = 'this.queriesfn[' + (this.queriesidx - 1) + '](this.params,null,' + context + ')';
// s = '(console.log(this.queriesfn[0]),'+s+')';
// console.log(this,s);
return s;
};
yy.Insert.prototype.compile = function (databaseid) {
var self = this;
// Handle ParamValue (anonymous data table) - wrap execution
if (self.into instanceof yy.ParamValue) {
return yy.compileParamValue(self.into.param, 'INSERT', true, databaseid, self, 'into');
}
databaseid = self.into.databaseid || databaseid;
var db = alasql.databases[databaseid];
// console.log(self);
var tableid = self.into.tableid;
var table = db.tables[tableid];
if (!table) {
throw "Table '" + tableid + "' could not be found";
}
// Helper function to create error message for value/column count mismatch
var createValueCountMismatchError = function (valueCount, columnCount, columnType) {
return (
`The number of values (${valueCount}) does not match the number of ${columnType} (${columnCount}). ` +
'If using a subquery, use INSERT INTO ... SELECT instead of INSERT INTO ... VALUES (SELECT ...)'
);
};
// Check, if this dirty flag is required
var s = '';
var sw = '';
var s = "db.tables['" + tableid + "'].dirty=true;";
// aa = array to accumulate inserted rows (used for OUTPUT clause and concat to table.data)
var s3 = 'var a,aa=[],x;';
var s33;
// INSERT INTO table VALUES
if (this.values) {
if (this.exists) {
this.existsfn = this.exists.map(function (ex) {
var nq = ex.compile(databaseid);
nq.query.modifier = 'RECORDSET';
return nq;
});
}
if (this.queries) {
this.queriesfn = this.queries.map(function (q) {
var nq = q.compile(databaseid);
nq.query.modifier = 'RECORDSET';
return nq;
});
}
// console.log(1);
self.values.forEach(function (values) {
var ss = [];
// s += 'db.tables[\''+tableid+'\'].data.push({';
// s += '';
if (self.columns) {
// Validate that we have the right number of values for the columns
if (values.length !== self.columns.length) {
throw new Error(
createValueCountMismatchError(values.length, self.columns.length, 'columns')
);
}
self.columns.forEach(function (col, idx) {
//console.log(db.tables, tableid, table);
// ss.push(col.columnid +':'+ self.values[idx].value.toString());
// console.log(rec[f.name.value]);
// if(rec[f.name.value] == "NULL") rec[f.name.value] = undefined;
// if(table.xflds[f.name.value].dbtypeid == "INT") rec[f.name.value] = +rec[f.name.value]|0;
// else if(table.xflds[f.name.value].dbtypeid == "FLOAT") rec[f.name.value] = +rec[f.name.value];
var q = "'" + col.columnid + "':";
if (table.xcolumns && table.xcolumns[col.columnid]) {
if (
['INT', 'FLOAT', 'NUMBER', 'MONEY'].indexOf(table.xcolumns[col.columnid].dbtypeid) >=
0
) {
//q += ''
q += '(x=' + values[idx].toJS() + ',x==undefined?undefined:+x)';
} else if (alasql.fn[table.xcolumns[col.columnid].dbtypeid]) {
q += '(new ' + table.xcolumns[col.columnid].dbtypeid + '(';
q += values[idx].toJS();
q += '))';
} else {
q += values[idx].toJS();
}
} else {
q += values[idx].toJS();
}
ss.push(q);
});
} else {
// var table = db.tables[tableid];
// console.log('table1', db, self);
//console.log(111, table.columns);
//console.log(74,table);
if (Array.isArray(values) && table.columns && table.columns.length > 0) {
// Validate that we have the right number of values for the table columns
if (values.length !== table.columns.length) {
throw new Error(
createValueCountMismatchError(values.length, table.columns.length, 'table columns')
);
}
table.columns.forEach(function (col, idx) {
var q = "'" + col.columnid + "':";
// var val = values[idx].toJS();
if (['INT', 'FLOAT', 'NUMBER', 'MONEY'].indexOf(col.dbtypeid) >= 0) {
q += '+' + values[idx].toJS();
} else if (alasql.fn[col.dbtypeid]) {
q += '(new ' + col.dbtypeid + '(';
q += values[idx].toJS();
q += '))';
} else {
q += values[idx].toJS();
}
/*/*
// if(table.xcolumns && table.xcolumns[col.columnid] &&
// (table.xcolumns[col.columnid].dbtypeid == "DATE" ||
// table.xcolumns[col.columnid].dbtypeid == "DATETIME"
// )) {
// val = "(new Date("+val+"))";
// }
// || table.xcolumns[col.columnid].dbtypeid == "FLOAT"
// || table.xcolumns[col.columnid].dbtypeid == "NUMBER"
// || table.xcolumns[col.columnid].dbtypeid == "MONEY"
// )) q += '+';
// console.log(self.values[idx].toString());
//console.log(self);
// q += val;
// if(table.xcolumns && table.xcolumns[col.columnid] && table.xcolumns[col.columnid].dbtypeid == "INT") q += '|0';
*/
ss.push(q);
/*/*
// console.log(fld);
// TODO: type checking and conversions
// rec[fld.fldid] = eval(self.insertExpression[idx].toJS('',''));
// console.log(rec[fld.fldid]);
// if(rec[fld.fldid] == "NULL") rec[fld.fldid] = undefined;
// if(table.xflds[fld.fldid].dbtypeid == "INT") rec[fld.fldid] = +rec[fld.fldid]|0;
// else if(table.xflds[fld.fldid].dbtypeid == "FLOAT" || table.xflds[fld.fldid].dbtypeid == "MONEY" )
// rec[fld.fldid] = +rec[fld.fldid];
*/
});
} else {
// console.log(222,values);
// sw = 'var w='+JSONtoJS(values)+';for(var k in w){r[k]=w[k]};';
sw = JSONtoJS(values);
}
}
//console.log(ss);
if (db.tables[tableid].defaultfns) {
ss.unshift(db.tables[tableid].defaultfns);
}
if (sw) {
s += 'a=' + sw + ';';
} else {
s += 'a={' + ss.join(',') + '};';
}
// If this is a class
if (db.tables[tableid].isclass) {
s += "var db=alasql.databases['" + databaseid + "'];";
s += 'a.$class="' + tableid + '";';
s += 'a.$id=db.counter++;';
s += 'db.objects[a.$id]=a;';
}
// s += 'db.tables[\''+tableid+'\'].insert(r);';
if (db.tables[tableid].insert) {
s += "var db=alasql.databases['" + databaseid + "'];";
s +=
"var inserted=db.tables['" +
tableid +
"'].insert(a," +
(self.orreplace ? 'true' : 'false') +
',' +
(self.ignore ? 'true' : 'false') +
');';
// Track successful inserts (insert returns false when ignored)
if (self.ignore) {
s += 'if(inserted!==false){';
}
// Also push to aa for OUTPUT clause
if (self.output) {
s += 'aa.push(a);';
} else if (self.ignore) {
// For ignore mode without output, track successful insertions
s += 'aa.push(a);';
}
if (self.ignore) {
s += '}';
}
} else {
s += 'aa.push(a);';
}
});
s33 = s3 + s;
if (db.tables[tableid].insert) {
// s += 'alasql.databases[\''+databaseid+'\'].tables[\''+tableid+'\'].insert(r);';
} else {
s +=
"alasql.databases['" +
databaseid +
"'].tables['" +
tableid +
"'].data=" +
"alasql.databases['" +
databaseid +
"'].tables['" +
tableid +
"'].data.concat(aa);";
}
// Handle OUTPUT clause
if (self.output) {
s += 'var output = [];';
s += 'for(var i=0;i<aa.length;i++){';
s += 'var r = aa[i];';
s += 'var outputRow = {};';
// Process each output column
self.output.columns.forEach(function (col) {
if (col.columnid === '*') {
// For *, expand all properties
s += 'for(var key in r){ outputRow[key] = r[key]; }';
} else {
var colname = col.as || col.columnid;
// Direct property access for simple columns
s += "outputRow['" + colname + "']=r['" + col.columnid + "'];";
}
});
s += 'output.push(outputRow);';
s += '}';
s += 'return output;';
} else if (db.tables[tableid].insert) {
if (db.tables[tableid].isclass) {
s += 'return a.$id;';
} else {
// For IGNORE mode, return count of actually inserted rows
if (self.ignore) {
s += 'return aa.length;';
} else {
s += 'return ' + self.values.length;
}
}
} else {
// For IGNORE mode, return count of actually inserted rows
if (self.ignore) {
s += 'return aa.length;';
} else {
s += 'return ' + self.values.length;
}
}
//console.log(186,s3+s);
var insertfn = new Function('db, params, alasql', 'var y;' + s3 + s).bind(this);
// INSERT INTO table SELECT
} else if (this.select) {
this.select.modifier = 'RECORDSET';
if (this.queries) {
this.select.queries = this.queries;
}
var selectfn = this.select.compile(databaseid);
if (db.engineid && alasql.engines[db.engineid].intoTable) {
var statement = function (params, cb) {
var aa = selectfn(params);
var res = alasql.engines[db.engineid].intoTable(db.databaseid, tableid, aa.data, null, cb);
return res;
};
return statement;
} else {
// console.log(224,table.defaultfns);
var defaultfns =
'var defaults={' +
table.defaultfns +
'};for(var key in defaults){if(!(key in r)){r[key]=defaults[key]}}return r';
var defaultfn = new Function('r,db,params,alasql', defaultfns);
var insertfn = function (db, params, alasql) {
var res = selectfn(params).data;
var insertedRows = [];
if (db.tables[tableid].insert) {
// If insert() function exists (issue #92)
for (var i = 0, ilen = res.length; i < ilen; i++) {
var r = cloneDeep(res[i]);
defaultfn(r, db, params, alasql);
db.tables[tableid].insert(r, self.orreplace, self.ignore);
insertedRows.push(r);
}
} else {
insertedRows = res;
db.tables[tableid].data = db.tables[tableid].data.concat(res);
}
// Handle OUTPUT clause
if (self.output) {
var output = [];
for (var i = 0; i < insertedRows.length; i++) {
var r = insertedRows[i];
var outputRow = {};
self.output.columns.forEach(function (col) {
if (col.columnid === '*') {
// For *, expand all properties
for (var key in r) {
outputRow[key] = r[key];
}
} else {
var colname = col.as || col.columnid;
// Direct property access for simple columns
outputRow[colname] = r[col.columnid];
}
});
output.push(outputRow);
}
return output;
}
if (alasql.options.nocount) return;
else return res.length;
};
}
} else if (this.default) {
var insertfns = "db.tables['" + tableid + "'].data.push({" + table.defaultfns + '});return 1;';
var insertfn = new Function('db,params,alasql', insertfns);
} else if (this.setcolumns) {
// INSERT INTO table SET column = value - convert to VALUES equivalent
// Build column list and value expression list from SET columns
var columns = [];
var valueExprs = [];
this.setcolumns.forEach(function (setcol) {
columns.push(setcol.column);
valueExprs.push(setcol.expression);
});
// Temporarily transform to use VALUES path
var originalColumns = this.columns;
var originalValues = this.values;
this.columns = columns;
this.values = [valueExprs];
try {
// Reuse VALUES compilation logic by recursively calling compile
var compiledFn = yy.Insert.prototype.compile.call(this, databaseid);
return compiledFn;
} finally {
// Always restore original state
this.columns = originalColumns;
this.values = originalValues;
}
} else {
throw new Error('Wrong INSERT parameters');
}
// console.log(1,s);
// console.log(s33);
if (db.engineid && alasql.engines[db.engineid].intoTable && alasql.options.autocommit) {
var statement = function (params, cb) {
var aa = new Function('db,params,alasql', 'var y;' + s33 + 'return aa;')(db, params, alasql);
// console.log(s33);
var res = alasql.engines[db.engineid].intoTable(db.databaseid, tableid, aa, null, cb);
// if(cb) cb(res);
return res;
};
} else {
var statement = function (params, cb) {
//console.log(databaseid);
var db = alasql.databases[databaseid];
if (alasql.options.autocommit && db.engineid) {
alasql.engines[db.engineid].loadTableData(databaseid, tableid);
}
var res = insertfn(db, params, alasql);
if (alasql.options.autocommit && db.engineid) {
alasql.engines[db.engineid].saveTableData(databaseid, tableid);
}
// var res = insertfn(db, params);
if (alasql.options.nocount) res = undefined;
if (cb) cb(res);
return res;
};
}
return statement;
};
yy.Insert.prototype.execute = function (databaseid, params, cb) {
return this.compile(databaseid)(params, cb);
// throw new Error('Insert statement is should be compiled')
};