forked from AlaSQL/alasql
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path74update.js
86 lines (69 loc) · 2.26 KB
/
74update.js
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
/*
//
// UPDATE for Alasql.js
// Date: 03.11.2014
// (c) 2014, Andrey Gershun
//
*/
yy.Update = function (params) { return yy.extend(this, params); }
yy.Update.prototype.toString = function() {
var s = 'UPDATE '+this.table.toString();
if(this.columns) s += ' SET '+this.columns.toString();
if(this.where) s += ' WHERE '+this.where.toString();
return s;
}
yy.SetColumn = function (params) { return yy.extend(this, params); }
yy.SetColumn.prototype.toString = function() {
return this.columnid.toString() + '='+this.expression.toString();
}
yy.Update.prototype.compile = function (databaseid) {
// console.log(this);
databaseid = this.table.databaseid || databaseid;
var tableid = this.table.tableid;
if(this.where) {
var wherefn = new Function('r,params','return '+this.where.toJavaScript('r',''));
};
// Construct update function
var s = '';
this.columns.forEach(function(col){
s += 'r[\''+col.columnid+'\']='+col.expression.toJavaScript('r','')+';';
});
var assignfn = new Function('r,params',s);
var statement = function(params, cb) {
var db = alasql.databases[databaseid];
// console.log(db.engineid);
// console.log(db.engineid && alasql.engines[db.engineid].updateTable);
if(db.engineid && alasql.engines[db.engineid].updateTable) {
// console.log('updateTable');
return alasql.engines[db.engineid].updateTable(databaseid, tableid, assignfn, wherefn, params, cb);
}
if(alasql.autocommit && db.engineid) {
alasql.engines[db.engineid].loadTableData(databaseid,tableid);
}
var table = db.tables[tableid];
if(!table) {
throw new Error("Table '"+tableid+"' not exists")
}
// table.dirty = true;
var numrows = 0;
for(var i=0, ilen=table.data.length; i<ilen; i++) {
if(!wherefn || wherefn(table.data[i], params) ) {
if(table.update) {
table.update(assignfn, i, params);
} else {
assignfn(table.data[i], params);
}
numrows++;
}
};
if(alasql.autocommit && db.engineid) {
alasql.engines[db.engineid].saveTableData(databaseid,tableid);
}
if(cb) cb(numrows);
return numrows;
};
return statement;
};
yy.Update.prototype.execute = function (databaseid, params, cb) {
return this.compile(databaseid)(params,cb);
}