-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathangular-sql-storage.js
More file actions
289 lines (237 loc) · 7.79 KB
/
Copy pathangular-sql-storage.js
File metadata and controls
289 lines (237 loc) · 7.79 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
(function(angular) {
"use strict";
angular
.module('sf.sqlStorage', [
'LocalStorageModule',
]);
angular
.module('sf.sqlStorage')
.provider('sqlStorageMigrationService', _sqlStorageMigrationService);
function _sqlStorageMigrationService() {
sqlStorageMigrationService.$inject = ["$q", "$injector", "localStorageService"];
var updateMethods = {};
this.addUpdater = addUpdater;
this.$get = sqlStorageMigrationService;
function addUpdater(configMethod) {
updateMethods[configMethod.version] = configMethod.method;
}
// @ngInject
function sqlStorageMigrationService($q, $injector, localStorageService) {
var methods = {};
methods._database = null;
methods._updateMethods = updateMethods;
methods.updateManager = updateManager;
function updateManager(database, currentVersion) {
methods._database = database;
var DATABASE_VERSION_KEY = 'database_version';
var versions = Object.keys(methods._updateMethods)
.map(parseFloat)
.sort(function (a, b) { return a - b; })
.reduce(function (datas, updaterVersion) {
if(updaterVersion > currentVersion) {
datas.push(updaterVersion);
}
return datas;
}, []);
return versions.reduce(function(p, version) {
return p.then(function() {
return callMethod(version)
.then(function() {
return localStorageService.set(DATABASE_VERSION_KEY, version);
});
});
}, $q.when());
}
function callMethod(updateKey) {
return $injector.invoke(methods._updateMethods[updateKey], methods);
}
return methods;
}
}
_sqlStorageService.$inject = ["sqlStorageMigrationServiceProvider"];var DATABASE_VERSION_KEY = 'database_version';
angular
.module('sf.sqlStorage')
.provider('sqlStorageService', _sqlStorageService);
// @ngInject
function _sqlStorageService(sqlStorageMigrationServiceProvider) {
sqlStorageService.$inject = ["$q", "$window", "$log", "$injector", "localStorageService", "sqlStorageMigrationService"];
var _databaseName = 'database.db';
var _databaseVersion = 1;
var _databaseSchema = null;
var _databaseInstance = null;
this.$get = sqlStorageService;
this.setDatabaseConfig = setDatabaseConfig;
this.setDatabaseSchema = setDatabaseSchema;
this.setDatabaseInstance = setDatabaseInstance;
this.addUpdater = addUpdater;
function setDatabaseConfig(config) {
_databaseName = config.name;
_databaseVersion = config.version;
}
function setDatabaseSchema(databaseSchema) {
_databaseSchema = databaseSchema;
}
function setDatabaseInstance(databaseInstance) {
_databaseInstance = databaseInstance;
}
function addUpdater(configMethod) {
sqlStorageMigrationServiceProvider.addUpdater(configMethod);
}
// @ngInject
function sqlStorageService($q, $window, $log, $injector,
localStorageService, sqlStorageMigrationService) {
var methods = {};
var sqlInstance = null;
if(!_databaseSchema) {
$log.error('Please set a database configuration');
_databaseSchema = {};
}
methods.createPromise = null;
methods.tables = _databaseSchema.tables || {};
// Methods
methods.initDatabase = initDatabase;
methods.getDatabase = getDatabase;
methods.initTables = initTables;
methods.deleteDatas = deleteDatas;
methods.createTables = createTables;
methods.execute = execute;
/**
* Init database
* @return {Object} SQLite instance
*/
function initDatabase() {
sqlInstance = (_databaseInstance) ?
$injector.invoke(_databaseInstance) :
$window.openDatabase(_databaseName, '1.0', 'database', 200000);
return sqlInstance;
}
/**
* Get database instace
* @return {Object} SQLite instance
*/
function getDatabase() {
return (!sqlInstance) ? this.initDatabase() : sqlInstance;
}
/**
* Create tables
* @return {Object} SQLite instance
*/
function initTables() {
var _this = this;
var tables = this.tables;
if(this.createPromise) { return this.createPromise; }
this.createPromise = this.createTables(_databaseSchema.defaultFields, tables)
.then(createSucceed);
return this.createPromise;
function createSucceed() {
var database = _this.getDatabase();
var currentVersion = localStorageService.get(DATABASE_VERSION_KEY) || 0;
$log.debug('[Storage] Create DB SUCCESS');
return (currentVersion && currentVersion < _databaseVersion) ?
sqlStorageMigrationService.updateManager(database, currentVersion)
.then(function() { return database; })
.catch(function (err) {
$log.error(err);
return database;
}) :
saveDatabaseVersion();
function saveDatabaseVersion() {
localStorageService.set(DATABASE_VERSION_KEY, _databaseVersion);
return database;
}
}
}
/**
* Create table
* @param {Array} defaultFields - Fields for all tables
* @param {Object} tables - Tables definition
* @return {Promise} Tables create
*/
function createTables(defaultFields, tables) {
var _this = this;
var fields = (defaultFields || []).map(fieldConstruction);
var queries = Object.keys(tables).map(function(tableKey) {
var query = constructCreateQuery(tables[tableKey], fields);
return _this.execute(query);
});
return $q.all(queries);
}
/**
* Clear All datas
* @return {Object} promise of db clear
*/
function deleteDatas() {
var _this = this;
var tablesName = Object.keys(this.tables).map(function(tableKey) {
return _this.tables[tableKey].table_name;
});
// Databases
var queries = tablesName.map(function(tableName) {
var request = 'DROP TABLE IF EXISTS ' + tableName;
return _this.execute(request);
});
// Local Storage
localStorageService.clearAll();
return $q.all(queries).then(function(data) {
_this.createPromise = null;
$log.debug('[Storage] Drop DB SUCCESS');
return data;
});
}
//---------------
//
// HELPERS
//
//---------------
/**
* Make sqlLite request
*
* @param {String} query - SQL Query
* @param {[Array]} binding - Datas for querying
* @return {Promise} - Request result
*/
function execute(query, binding) {
var q = $q.defer();
var database = this.getDatabase();
database.transaction(function(tx) {
tx.executeSql(query, binding, function(sqlTx, result) {
q.resolve(result);
}, function(transaction, error) {
q.reject(error);
});
});
return q.promise;
}
/**
* Construct the create table query.
*
* @param {Object} table - Table definition
* @param {Array} fields - Default fields
* @return {String} - Create request
*/
function constructCreateQuery(table, fields) {
var indexedFields = table.indexed_fields || [];
var tableFields = fields.concat(indexedFields.map(fieldConstruction));
// var fields
return [
'CREATE TABLE IF NOT EXISTS',
table.table_name,
'(' + tableFields.join(', ') + ')',
].join(' ');
}
/**
* Create the definition of the field
*
* @param {Object} field - Field configuration
* @return {String} - Field definition
*/
function fieldConstruction(field) {
var fieldDefinition = [field.name, field.type];
if(field.unique) { fieldDefinition.push('UNIQUE'); }
if(field.primayKey) { fieldDefinition.push('PRIMARY KEY'); }
return fieldDefinition.join(' ');
}
return methods;
}
}
}(window.angular));

