summaryrefslogtreecommitdiffstats
path: root/src/main/webapp/javascripts/libs/browserEngines/websql_driver.js
blob: d8b851986bb39e133bdbe8f513b38b45ab207c12 (plain)
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
define(["jQuery","BrowserEngines/sqlite_driver"], function ($,SQLite_driver) {
		
	var WebSQL_driver = function(){
		this.db = null;
		this.ddl = [];
		this.nativeSQLite = (window.openDatabase !== undefined);
		return this;
	};
	
	$.extend(WebSQL_driver.prototype,SQLite_driver.prototype); // inherit from parent class
	
	WebSQL_driver.prototype.buildSchema = function (args) {
	
		var _this = this; // preserve reference to current object through local closures
		
			try {
			
				if (_this.nativeSQLite)
				{
					_this.db = openDatabase(args["short_code"], '1.0', args["short_code"], args["ddl"].length * 1024);
	
					_this.db.transaction(function(tx){
						
						var statements = _this.splitStatement(args["ddl"],args["statement_separator"]);
						_this.ddl = statements;
						
						var currentStatement = 0;
						var statement = statements[currentStatement];
						
						var sequentiallyExecute = function(tx2, result){
							if (currentStatement < statements.length-1)
							{
								do {
									currentStatement++;													
									statement = statements[currentStatement];
								} while (currentStatement < statements.length-1 && statement.match(/^\s*$/));
								
								if (!statement.match(/^\s*$/)) {
									tx.executeSql(statement, [], sequentiallyExecute, handleFailure);
								}
								else
								{
									tx.executeSql("intentional failure used to rollback transaction");
									args["success"]();
								}
								
							}
							else
							{
								tx.executeSql("intentional failure used to rollback transaction");
								args["success"]();
							}
						};
						
						var handleFailure = function (tx2, result) {
							if (result.message != "not an error") // thank you safari, for this
							{
								args["error"](result.message);
							}
							else
							{
								args["success"]();
							}
							
							return true; // roll back transaction
						};
						
						if (statement) {
							tx.executeSql(statement, [], sequentiallyExecute, handleFailure);
						}
						else {
							args["success"]();
						}
					});
					
				}
				else
				{
					args["error"]("SQLite (WebSQL) not available in your browser. Try either using a webkit-based browser (such as Safari or Chrome) or using the SQLite (SQL.js) database type.")
				}
	
			}
			catch (e)
			{
				args["error"](e);
			}
	
		}
		
		
	WebSQL_driver.prototype.executeQuery = function (args) {
	
		var _this = this; // preserve reference to current object through local closures
			
			try {
				
				if (_this.db == null ) {
					throw("You need to build the schema before you can run a query.");
				}
				
				var returnSets = [];
				
				_this.db.transaction(function(tx){
	
					var sequentiallyExecute = function(tx2, result) {
								
						var thisSet = {
							"STATEMENT": statement, 
							"SUCCEEDED": true,
							"EXECUTIONTIME": (new Date()) - startTime,
							"RESULTS": {
								"COLUMNS": [],
								"DATA": []
							},
							"EXECUTIONPLAN": {
								"COLUMNS": [],
								"DATA": []
							}
						
						};
						
						for (var i = 0; i < result.rows.length; i++) {
							var rowVals = [];
							var item = result.rows.item(i);
							
							/* We can't be sure about the order of the columns returned, since they are returned as
							 * a simple unordered structure. So, we'll just take the order returned the from the first
							 * request, then just use that order for each row.
							 */
							if (i == 0) {
								for (col in item) {
									thisSet["RESULTS"]["COLUMNS"].push(col);
								}
							}
							
							for (var j = 0; j < thisSet["RESULTS"]["COLUMNS"].length; j++) {
								if (item[thisSet["RESULTS"]["COLUMNS"][j]] === null) {
									rowVals.push("(null)");
								} else {
									rowVals.push(item[thisSet["RESULTS"]["COLUMNS"][j]]);
								}
							}
							
							thisSet["RESULTS"]["DATA"].push(rowVals);
						}
						
						tx.executeSql("EXPLAIN QUERY PLAN " + statement, [], function (tx3, executionPlanResult) {
	
							for (var l = 0; l < executionPlanResult.rows.length; l++) {
								var rowVals = [];
								var item = executionPlanResult.rows.item(l);
								
								/* We can't be sure about the order of the columns returned, since they are returned as
								 * a simple unordered structure. So, we'll just take the order returned the from the first
								 * request, then just use that order for each row.
								 */
								if (l == 0) {
									for (col in item) {
										thisSet["EXECUTIONPLAN"]["COLUMNS"].push(col);
									}
								}
								
								for (var j = 0; j < thisSet["EXECUTIONPLAN"]["COLUMNS"].length; j++) {
									rowVals.push(item[thisSet["EXECUTIONPLAN"]["COLUMNS"][j]]);
								}
								
								thisSet["EXECUTIONPLAN"]["DATA"].push(rowVals);
							}
						
							if (currentStatement > _this.ddl.length-1)
								returnSets.push(thisSet);						
							
							// executeSQL runs asynchronously, so we have to make recursive calls to handle subsequent queries in order.
							if (currentStatement < (statements.length - 1)) 
							{
								do {
								currentStatement++;						
								statement = statements[currentStatement];
								} while (currentStatement < statements.length-1 && statement.match(/^\s*$/));
								
								if (! statement.match(/^\s*$/))
									tx.executeSql(statement, [], sequentiallyExecute, handleFailure);
								else
								{
									tx.executeSql("intentional failure used to rollback transaction");
									args["success"](returnSets);
								}
								
							}
							else
							{
								tx.executeSql("intentional failure used to rollback transaction");
								args["success"](returnSets);
							}
	
							
						},
						function(tx3, executionPlanResult){
							// if the explain failed, then just append the base set to the result and move on....
	
							if (currentStatement > _this.ddl.length-1)
								returnSets.push(thisSet);						
	
							// executeSQL runs asynchronously, so we have to make recursive calls to handle subsequent queries in order.
							if (currentStatement < (statements.length - 1)) 
							{
								do {
								currentStatement++;						
								statement = statements[currentStatement];
								} while (currentStatement < statements.length-1 && statement.match(/^\s*$/));
								
								if (! statement.match(/^\s*$/))
									tx.executeSql(statement, [], sequentiallyExecute, handleFailure);
								else
								{
									tx.executeSql("intentional failure used to rollback transaction");
									args["success"](returnSets);
								}
							}
							else
							{
								tx.executeSql("intentional failure used to rollback transaction");
								args["success"](returnSets);
							}
	
							
						});
						
					}
					
					var handleFailure = function (tx, result) {
						if (result.message != "not an error") // thank you safari, for this
						{
							var thisSet = {
								"SUCCEEDED": false,
								"EXECUTIONTIME": (new Date()) - startTime,
								"ERRORMESSAGE": result.message
							};
							returnSets.push(thisSet);
						}
						
						args["success"](returnSets); // 'success' - slightly confusing here, but in this context a failed query is still a valid result from the database
						return true; // roll back transaction 
					}
					
					var setArray = [], k, stop = false;
	
					var statements = _this.ddl.slice(0);
	
					$.each(_this.splitStatement(args["sql"],args["statement_separator"]), function (i, stmt) { statements.push(stmt); });
	
					var currentStatement = 0;
					var statement = statements[currentStatement];
					
					var startTime = new Date();
					
					/*
					 * executeSql runs asynchronously, so I impose a semblance of synchronous-ness via recursive calls
					 */
					tx.executeSql(statement, [], sequentiallyExecute, handleFailure);
					
	
	
				});
				
			}
			catch (e)
			{
				args["error"](e);
			}
			
			
		}
		
	return WebSQL_driver;
});