db-wrapper 0.0.8 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/LICENSE +201 -201
  2. package/README.md +24 -24
  3. package/esm2020/db-wrapper.mjs +5 -0
  4. package/esm2020/lib/db-wrapper.models.mjs +45 -0
  5. package/esm2020/lib/db-wrapper.module.mjs +22 -0
  6. package/esm2020/lib/db-wrapper.service.mjs +405 -0
  7. package/esm2020/lib/window.service.mjs +17 -0
  8. package/esm2020/public-api.mjs +7 -0
  9. package/fesm2015/{db-wrapper.js → db-wrapper.mjs} +484 -479
  10. package/fesm2015/db-wrapper.mjs.map +1 -0
  11. package/fesm2020/db-wrapper.mjs +495 -0
  12. package/fesm2020/db-wrapper.mjs.map +1 -0
  13. package/{db-wrapper.d.ts → index.d.ts} +5 -4
  14. package/lib/db-wrapper.models.d.ts +119 -119
  15. package/lib/db-wrapper.module.d.ts +9 -5
  16. package/lib/db-wrapper.service.d.ts +39 -39
  17. package/lib/window.service.d.ts +6 -3
  18. package/package.json +24 -14
  19. package/public-api.d.ts +3 -3
  20. package/bundles/db-wrapper.umd.js +0 -752
  21. package/bundles/db-wrapper.umd.js.map +0 -1
  22. package/bundles/db-wrapper.umd.min.js +0 -16
  23. package/bundles/db-wrapper.umd.min.js.map +0 -1
  24. package/db-wrapper.metadata.json +0 -1
  25. package/esm2015/db-wrapper.js +0 -5
  26. package/esm2015/lib/db-wrapper.models.js +0 -45
  27. package/esm2015/lib/db-wrapper.module.js +0 -21
  28. package/esm2015/lib/db-wrapper.service.js +0 -408
  29. package/esm2015/lib/window.service.js +0 -16
  30. package/esm2015/public-api.js +0 -7
  31. package/esm5/db-wrapper.js +0 -5
  32. package/esm5/lib/db-wrapper.models.js +0 -45
  33. package/esm5/lib/db-wrapper.module.js +0 -25
  34. package/esm5/lib/db-wrapper.service.js +0 -434
  35. package/esm5/lib/window.service.js +0 -23
  36. package/esm5/public-api.js +0 -7
  37. package/fesm2015/db-wrapper.js.map +0 -1
  38. package/fesm5/db-wrapper.js +0 -529
  39. package/fesm5/db-wrapper.js.map +0 -1
@@ -1,493 +1,498 @@
1
- import { __decorate, __awaiter } from 'tslib';
1
+ import { __awaiter } from 'tslib';
2
+ import * as i0 from '@angular/core';
2
3
  import { Injectable, InjectionToken, NgModule } from '@angular/core';
3
4
 
4
- let WindowService = class WindowService {
5
- get nativeWindow() {
6
- return _window();
7
- }
8
- };
9
- WindowService = __decorate([
10
- Injectable()
11
- ], WindowService);
12
- function _window() {
13
- // Return the global native browser window object
14
- return typeof window !== 'undefined' ? window : undefined;
5
+ class WindowService {
6
+ get nativeWindow() {
7
+ return _window();
8
+ }
9
+ }
10
+ /** @nocollapse */ WindowService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.2.5", ngImport: i0, type: WindowService, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
11
+ /** @nocollapse */ WindowService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.2.5", ngImport: i0, type: WindowService });
12
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.2.5", ngImport: i0, type: WindowService, decorators: [{
13
+ type: Injectable
14
+ }] });
15
+ function _window() {
16
+ // Return the global native browser window object
17
+ return typeof window !== 'undefined' ? window : undefined;
15
18
  }
16
19
 
17
- class DbWrapperService {
18
- constructor(dbConfig, dbSchema) {
19
- this._dbName = dbConfig.dbName;
20
- this._location = dbConfig.location || 'default';
21
- this._iosDatabaseLocation = dbConfig.iosDatabaseLocation || 'Library';
22
- const window = (new WindowService()).nativeWindow;
23
- if (dbSchema) {
24
- this.schema = dbSchema;
25
- }
26
- this._readyPromise = new Promise((resolve, reject) => {
27
- if (typeof window.cordova === 'undefined') {
28
- setTimeout(() => {
29
- this.init(dbSchema).then(() => {
30
- resolve();
31
- })
32
- .catch((err) => {
33
- reject(err);
34
- });
35
- }, 500);
36
- }
37
- else {
38
- document.addEventListener('deviceready', () => {
39
- console.log('dbWrapper: device ready.');
40
- this.initDevice(dbSchema).then(() => resolve()).catch((err) => reject(err));
41
- });
42
- }
43
- });
44
- }
45
- ready() {
46
- return this._readyPromise;
47
- }
48
- initDevice(dbSchema) {
49
- const window = (new WindowService()).nativeWindow;
50
- return new Promise((resolve, reject) => {
51
- this.db = window.sqlitePlugin.openDatabase({
52
- name: this._dbName,
53
- location: this._location,
54
- androidLockWorkaround: 1
55
- });
56
- if (dbSchema) {
57
- this.generate(dbSchema).catch(err => {
58
- reject(err);
59
- }).then(() => { resolve(); });
60
- }
61
- else {
62
- resolve();
63
- }
64
- });
65
- }
66
- init(dbSchema) {
67
- const window = (new WindowService()).nativeWindow;
68
- return new Promise((resolve, reject) => {
69
- this.db = window.openDatabase(this._dbName, '1.0', 'database', -1);
70
- if (dbSchema) {
71
- this.generate(dbSchema).catch(err => {
72
- reject(err);
73
- }).then(() => {
74
- resolve();
75
- });
76
- }
77
- else {
78
- resolve();
79
- }
80
- });
81
- }
82
- generate(schema) {
83
- const sentences = [];
84
- this.schema = schema;
85
- if (schema.tables) {
86
- schema.tables.forEach(table => {
87
- sentences.push(this.createTable(table));
88
- });
89
- }
90
- if (schema.views) {
91
- schema.views.forEach(view => {
92
- sentences.push(this.createView(view));
93
- });
94
- }
95
- if (sentences.length === 0) {
96
- throw new Error('Esquema de la base de datos vacia.');
97
- }
98
- return Promise.all(sentences);
99
- }
100
- createTable(table) {
101
- return __awaiter(this, void 0, void 0, function* () {
102
- let sql = '', onConflictPrimary;
103
- const sentences = [], newColumns = [];
104
- const tableDDL = yield this._tableExists(table.name);
105
- if (tableDDL) {
106
- table.columns.forEach(col => {
107
- if (!this._columnExists(tableDDL, col.name)) {
108
- newColumns.push(this.addColumn(table.name, col));
109
- }
110
- });
111
- }
112
- else {
113
- table.columns.forEach(col => {
114
- sentences.push(this.defColumn(col));
115
- });
116
- }
117
- onConflictPrimary = 'on conflict fail';
118
- if (Array.isArray(table.primary)) {
119
- sentences.push(' CONSTRAINT identificador PRIMARY KEY (' + table.primary.join(',') + ') ' + onConflictPrimary);
120
- }
121
- if (typeof table.primary === 'string') {
122
- sentences.push(' CONSTRAINT identificador PRIMARY KEY (' + table.primary + ') ' + onConflictPrimary);
123
- }
124
- if (table.uniques) {
125
- table.uniques.forEach(uniq => {
126
- sentences.push(this.defUnique(uniq));
127
- });
128
- }
129
- if (table.foreigns) {
130
- table.foreigns.forEach(fore => {
131
- sentences.push(this.defForeign(fore));
132
- });
133
- }
134
- if (tableDDL && newColumns.length !== 0) {
135
- return Promise.all(newColumns)
136
- .then(() => { console.log(`Table ${table.name} altered.`); })
137
- .catch((err) => {
138
- console.error(`Table ${table.name}: ${err.message}`);
139
- throw new Error(`Table ${table.name}: ${err.message}`);
140
- });
141
- }
142
- else if (!tableDDL) {
143
- sql = 'CREATE TABLE IF NOT EXISTS ' + table.name + ' (' + sentences.join(',') + ')';
144
- return this.query(sql)
145
- .then(() => { console.log(`Table ${table.name} created.`); })
146
- .catch((err) => {
147
- console.error(`Table ${table.name}: ${err.message}`);
148
- throw new Error(`Table ${table.name}: ${err.message}`);
149
- });
150
- }
151
- else {
152
- return Promise.resolve().then(() => { console.log(`Table ${table.name} initialized.`); });
153
- }
154
- });
155
- }
156
- createView(view) {
157
- let sql;
158
- sql = 'CREATE VIEW IF NOT EXISTS ' + view.name
159
- + ' AS ' + view.sql;
160
- return this.query(sql);
161
- }
162
- getSchemaTable(tableName) {
163
- let res;
164
- this.schema.tables.forEach(table => {
165
- if (table.name === tableName) {
166
- res = table;
167
- }
168
- });
169
- return res;
170
- }
171
- getUniquesTable(table) {
172
- let res;
173
- table.uniques.forEach(uniq => {
174
- res[uniq.name] = uniq;
175
- });
176
- return res;
177
- }
178
- query(query, bindings = []) {
179
- return new Promise((resolve, reject) => {
180
- if (query.indexOf('select') === 0) {
181
- this.db.readTransaction((transaction) => {
182
- transaction.executeSql(query, bindings, (transaction, result) => {
183
- resolve(result);
184
- }, (transaction, error) => {
185
- reject(error);
186
- });
187
- }, (err) => reject(err));
188
- }
189
- else {
190
- this.db.transaction((transaction) => {
191
- transaction.executeSql(query, bindings, (transaction, result) => {
192
- resolve(result);
193
- }, (transaction, error) => {
194
- reject(error);
195
- });
196
- }, (err) => reject(err));
197
- }
198
- });
199
- }
200
- Count(query, bindings = []) {
201
- return this.query(query, bindings).then(rows => {
202
- return this.rowsCount(rows);
203
- });
204
- }
205
- insert(table, bindings) {
206
- let sql = '', sqlBinds = [], sqlKeys = [], sqlValues = [];
207
- sql = sql + 'insert into ' + table + ' ';
208
- for (const index in bindings) {
209
- if (bindings.hasOwnProperty(index)) {
210
- sqlKeys.push(index);
211
- sqlValues.push(bindings[index]);
212
- sqlBinds.push('?');
213
- }
214
- }
215
- sql = sql + '(' + sqlKeys.join(',') + ') values (' + sqlBinds.join(',') + ')';
216
- return new Promise((resolve, reject) => {
217
- this.db.transaction(transaction => {
218
- transaction.executeSql(sql, sqlValues, (transaction, result) => {
219
- resolve(result);
220
- }, (transaction, error) => {
221
- reject(error);
222
- });
223
- });
224
- });
225
- }
226
- update(table, bindings, where) {
227
- let sql = '', sqlBinds = [], sqlKeys = [], sqlValues = [];
228
- sql = sql + 'update ' + table + ' set ';
229
- for (let index in bindings) {
230
- if (bindings.hasOwnProperty(index)) {
231
- let newObj = bindings[index];
232
- if (typeof newObj === 'object' && newObj !== null) {
233
- sqlValues.push(newObj.value);
234
- if (newObj.ifnull) {
235
- sqlBinds.push(index + ' = ifnull( ' + index + ',0) + ?');
236
- }
237
- else if (newObj.operator) {
238
- sqlBinds.push(index + ' = ' + index + newObj.operator + ' ?');
239
- }
240
- else {
241
- sqlBinds.push(index + ' = ?');
242
- }
243
- }
244
- else {
245
- sqlBinds.push(index + ' = ?');
246
- sqlValues.push(bindings[index]);
247
- }
248
- }
249
- }
250
- for (let index in where) {
251
- if (where.hasOwnProperty(index)) {
252
- if (typeof where[index] === 'object' && where[index] !== null) {
253
- sqlKeys.push(index + ' ' + where[index].operator + ' ?');
254
- sqlValues.push(where[index].value);
255
- }
256
- else {
257
- sqlKeys.push(index + ' = ?');
258
- sqlValues.push(where[index]);
259
- }
260
- }
261
- }
262
- sql = sql + sqlBinds.join(',') + ' where ' + sqlKeys.join(' and ');
263
- return new Promise((resolve, reject) => {
264
- this.db.transaction(transaction => {
265
- transaction.executeSql(sql, sqlValues, (transaction, result) => {
266
- resolve(result);
267
- }, (transaction, error) => {
268
- reject(error);
269
- });
270
- });
271
- });
272
- }
273
- dropTable(tables) {
274
- let cont = 1;
275
- cont = tables.length;
276
- return new Promise((resolve, reject) => {
277
- tables.some(table => {
278
- if (cont !== 0) {
279
- this.query('DROP TABLE ' + table)
280
- .then(() => {
281
- if (cont === 1) {
282
- resolve();
283
- }
284
- else {
285
- cont--;
286
- }
287
- }, err => {
288
- cont = 0;
289
- reject(err);
290
- return true;
291
- });
292
- return false;
293
- }
294
- });
295
- });
296
- }
297
- fetchAll(result) {
298
- let output = [];
299
- for (let i = 0; i < result.rows.length; i++) {
300
- output.push(result.rows.item(i));
301
- }
302
- return output;
303
- }
304
- fetch(result) {
305
- let objeto = undefined, newObj = undefined;
306
- if (result.rows.length !== 0) {
307
- objeto = result.rows.item(0);
308
- newObj = {};
309
- const keys = Object.keys(objeto);
310
- for (let key in keys) {
311
- newObj[keys[key]] = objeto[keys[key]];
312
- }
313
- }
314
- return newObj;
315
- }
316
- rowsCount(result) {
317
- return result.rows.length;
318
- }
319
- tableExists(table) {
320
- return this.query('select sql from sqlite_master ' +
321
- 'where type=\'table\' and name=\'' + table + '\'')
322
- .then(result => (this.rowsCount(result) === 1));
323
- }
324
- columnExists(table, column) {
325
- return this._tableExists(table)
326
- .then((tableDDL) => {
327
- if (tableDDL) {
328
- return this._columnExists(tableDDL, column);
329
- }
330
- else {
331
- return false;
332
- }
333
- });
334
- }
335
- /* Private */
336
- defColumn(col) {
337
- let colSql;
338
- colSql = col.name + ' ' + col.type;
339
- if (!col.isNullable) {
340
- colSql += ' NOT NULL ';
341
- }
342
- if (col.default) {
343
- colSql += ' DEFAULT ' + col.default + ' ';
344
- }
345
- if (col.type === 'text' && col.length) {
346
- colSql += ` CONSTRAINT ${col.name}_length CHECK ( `;
347
- if (col.isNullable) {
348
- colSql += `${col.name} is null OR `;
349
- }
350
- colSql += `length(${col.name}) <= ${col.length} )`;
351
- }
352
- return colSql;
353
- }
354
- defUnique(unique) {
355
- let uniqSql;
356
- // depende del entorno, producción o desarrollo
357
- const onConflictUnique = 'on conflict replace';
358
- if (Array.isArray(unique.fields)) {
359
- uniqSql = ` CONSTRAINT ${unique.name} UNIQUE ( ${unique.fields.join(',')} ) ${onConflictUnique} `;
360
- }
361
- if (typeof unique.fields === 'string') {
362
- uniqSql = ` CONSTRAINT ${unique.name} UNIQUE ( ${unique.fields} ) ${onConflictUnique} `;
363
- }
364
- return uniqSql;
365
- }
366
- defForeign(fore) {
367
- let foreSql;
368
- if (Array.isArray(fore.foreignKey)) {
369
- foreSql = ` FOREIGN KEY ( ${fore.foreignKey.join(',')} ) `;
370
- }
371
- if (typeof fore.foreignKey === 'string') {
372
- foreSql = ` FOREIGN KEY ( ${fore.foreignKey} ) `;
373
- }
374
- if (Array.isArray(fore.primaryKey)) {
375
- foreSql = ` REFERENCES ${fore.referenceTable} ( ${fore.primaryKey.join(',')} ) `;
376
- }
377
- if (typeof fore.primaryKey === 'string') {
378
- foreSql = ` REFERENCES ${fore.referenceTable} ( ${fore.primaryKey} ) `;
379
- }
380
- return foreSql;
381
- }
382
- _tableExists(table) {
383
- return this.query('select sql from sqlite_master ' +
384
- 'where type=\'table\' and name=\'' + table + '\'')
385
- .then(result => {
386
- if (this.rowsCount(result) === 1) {
387
- return this.fetch(result).sql;
388
- }
389
- else {
390
- return false;
391
- }
392
- });
393
- }
394
- _columnExists(tableDDL, column) {
395
- if (tableDDL.indexOf(column) === -1) {
396
- return false;
397
- }
398
- else {
399
- return true;
400
- }
401
- }
402
- addColumn(table, col) {
403
- const colSql = this.defColumn(col);
404
- const query = 'alter TABLE ' + table + ' add COLUMN ' + colSql;
405
- return this.query(query);
406
- }
407
- }
408
- const DB_CONFIG = new InjectionToken('dbWrapperConfig');
409
- const DB_SCHEMA = new InjectionToken('dbWrapperSchema');
410
- function getDefaultDbConfig() {
411
- return {
412
- dbName: 'db.sqlite',
413
- location: 'default',
414
- iosDatabaseLocation: 'Library'
415
- };
416
- }
417
- function provideDbWrapper(dbConfig, dbSchema) {
418
- const config = !!dbConfig ? dbConfig : getDefaultDbConfig();
419
- return new DbWrapperService(config, dbSchema);
20
+ class DbWrapperService {
21
+ constructor(dbConfig, dbSchema) {
22
+ this._dbName = dbConfig.dbName;
23
+ this._location = dbConfig.location || 'default';
24
+ this._iosDatabaseLocation = dbConfig.iosDatabaseLocation || 'Library';
25
+ const window = (new WindowService()).nativeWindow;
26
+ if (dbSchema) {
27
+ this.schema = dbSchema;
28
+ }
29
+ this._readyPromise = new Promise((resolve, reject) => {
30
+ if (typeof window.cordova === 'undefined') {
31
+ setTimeout(() => {
32
+ this.init(dbSchema).then(() => {
33
+ resolve();
34
+ })
35
+ .catch((err) => {
36
+ reject(err);
37
+ });
38
+ }, 500);
39
+ }
40
+ else {
41
+ document.addEventListener('deviceready', () => {
42
+ console.log('dbWrapper: device ready.');
43
+ this.initDevice(dbSchema).then(() => resolve()).catch((err) => reject(err));
44
+ });
45
+ }
46
+ });
47
+ }
48
+ ready() {
49
+ return this._readyPromise;
50
+ }
51
+ initDevice(dbSchema) {
52
+ const window = (new WindowService()).nativeWindow;
53
+ return new Promise((resolve, reject) => {
54
+ this.db = window.sqlitePlugin.openDatabase({
55
+ name: this._dbName,
56
+ location: this._location,
57
+ androidLockWorkaround: 1
58
+ });
59
+ if (dbSchema) {
60
+ this.generate(dbSchema).catch(err => {
61
+ reject(err);
62
+ }).then(() => { resolve(); });
63
+ }
64
+ else {
65
+ resolve();
66
+ }
67
+ });
68
+ }
69
+ init(dbSchema) {
70
+ const window = (new WindowService()).nativeWindow;
71
+ return new Promise((resolve, reject) => {
72
+ this.db = window.openDatabase(this._dbName, '1.0', 'database', -1);
73
+ if (dbSchema) {
74
+ this.generate(dbSchema).catch(err => {
75
+ reject(err);
76
+ }).then(() => {
77
+ resolve();
78
+ });
79
+ }
80
+ else {
81
+ resolve();
82
+ }
83
+ });
84
+ }
85
+ generate(schema) {
86
+ const sentences = [];
87
+ this.schema = schema;
88
+ if (schema.tables) {
89
+ schema.tables.forEach(table => {
90
+ sentences.push(this.createTable(table));
91
+ });
92
+ }
93
+ if (schema.views) {
94
+ schema.views.forEach(view => {
95
+ sentences.push(this.createView(view));
96
+ });
97
+ }
98
+ if (sentences.length === 0) {
99
+ throw new Error('Esquema de la base de datos vacia.');
100
+ }
101
+ return Promise.all(sentences);
102
+ }
103
+ createTable(table) {
104
+ return __awaiter(this, void 0, void 0, function* () {
105
+ let sql = '', onConflictPrimary;
106
+ const sentences = [], newColumns = [];
107
+ const tableDDL = yield this._tableExists(table.name);
108
+ if (tableDDL) {
109
+ table.columns.forEach(col => {
110
+ if (!this._columnExists(tableDDL, col.name)) {
111
+ newColumns.push(this.addColumn(table.name, col));
112
+ }
113
+ });
114
+ }
115
+ else {
116
+ table.columns.forEach(col => {
117
+ sentences.push(this.defColumn(col));
118
+ });
119
+ }
120
+ onConflictPrimary = 'on conflict fail';
121
+ if (Array.isArray(table.primary)) {
122
+ sentences.push(' CONSTRAINT identificador PRIMARY KEY (' + table.primary.join(',') + ') ' + onConflictPrimary);
123
+ }
124
+ if (typeof table.primary === 'string') {
125
+ sentences.push(' CONSTRAINT identificador PRIMARY KEY (' + table.primary + ') ' + onConflictPrimary);
126
+ }
127
+ if (table.uniques) {
128
+ table.uniques.forEach(uniq => {
129
+ sentences.push(this.defUnique(uniq));
130
+ });
131
+ }
132
+ if (table.foreigns) {
133
+ table.foreigns.forEach(fore => {
134
+ sentences.push(this.defForeign(fore));
135
+ });
136
+ }
137
+ if (tableDDL && newColumns.length !== 0) {
138
+ return Promise.all(newColumns)
139
+ .then(() => { console.log(`Table ${table.name} altered.`); })
140
+ .catch((err) => {
141
+ console.error(`Table ${table.name}: ${err.message}`);
142
+ throw new Error(`Table ${table.name}: ${err.message}`);
143
+ });
144
+ }
145
+ else if (!tableDDL) {
146
+ sql = 'CREATE TABLE IF NOT EXISTS ' + table.name + ' (' + sentences.join(',') + ')';
147
+ return this.query(sql)
148
+ .then(() => { console.log(`Table ${table.name} created.`); })
149
+ .catch((err) => {
150
+ console.error(`Table ${table.name}: ${err.message}`);
151
+ throw new Error(`Table ${table.name}: ${err.message}`);
152
+ });
153
+ }
154
+ else {
155
+ return Promise.resolve().then(() => { console.log(`Table ${table.name} initialized.`); });
156
+ }
157
+ });
158
+ }
159
+ createView(view) {
160
+ let sql;
161
+ sql = 'CREATE VIEW IF NOT EXISTS ' + view.name
162
+ + ' AS ' + view.sql;
163
+ return this.query(sql);
164
+ }
165
+ getSchemaTable(tableName) {
166
+ let res;
167
+ this.schema.tables.forEach(table => {
168
+ if (table.name === tableName) {
169
+ res = table;
170
+ }
171
+ });
172
+ return res;
173
+ }
174
+ getUniquesTable(table) {
175
+ let res;
176
+ table.uniques.forEach(uniq => {
177
+ res[uniq.name] = uniq;
178
+ });
179
+ return res;
180
+ }
181
+ query(query, bindings = []) {
182
+ return new Promise((resolve, reject) => {
183
+ if (query.indexOf('select') === 0) {
184
+ this.db.readTransaction((transaction) => {
185
+ transaction.executeSql(query, bindings, (transaction, result) => {
186
+ resolve(result);
187
+ }, (transaction, error) => {
188
+ reject(error);
189
+ });
190
+ }, (err) => reject(err));
191
+ }
192
+ else {
193
+ this.db.transaction((transaction) => {
194
+ transaction.executeSql(query, bindings, (transaction, result) => {
195
+ resolve(result);
196
+ }, (transaction, error) => {
197
+ reject(error);
198
+ });
199
+ }, (err) => reject(err));
200
+ }
201
+ });
202
+ }
203
+ Count(query, bindings = []) {
204
+ return this.query(query, bindings).then(rows => {
205
+ return this.rowsCount(rows);
206
+ });
207
+ }
208
+ insert(table, bindings) {
209
+ let sql = '', sqlBinds = [], sqlKeys = [], sqlValues = [];
210
+ sql = sql + 'insert into ' + table + ' ';
211
+ for (const index in bindings) {
212
+ if (bindings.hasOwnProperty(index)) {
213
+ sqlKeys.push(index);
214
+ sqlValues.push(bindings[index]);
215
+ sqlBinds.push('?');
216
+ }
217
+ }
218
+ sql = sql + '(' + sqlKeys.join(',') + ') values (' + sqlBinds.join(',') + ')';
219
+ return new Promise((resolve, reject) => {
220
+ this.db.transaction(transaction => {
221
+ transaction.executeSql(sql, sqlValues, (transaction, result) => {
222
+ resolve(result);
223
+ }, (transaction, error) => {
224
+ reject(error);
225
+ });
226
+ });
227
+ });
228
+ }
229
+ update(table, bindings, where) {
230
+ let sql = '', sqlBinds = [], sqlKeys = [], sqlValues = [];
231
+ sql = sql + 'update ' + table + ' set ';
232
+ for (let index in bindings) {
233
+ if (bindings.hasOwnProperty(index)) {
234
+ let newObj = bindings[index];
235
+ if (typeof newObj === 'object' && newObj !== null) {
236
+ sqlValues.push(newObj.value);
237
+ if (newObj.ifnull) {
238
+ sqlBinds.push(index + ' = ifnull( ' + index + ',0) + ?');
239
+ }
240
+ else if (newObj.operator) {
241
+ sqlBinds.push(index + ' = ' + index + newObj.operator + ' ?');
242
+ }
243
+ else {
244
+ sqlBinds.push(index + ' = ?');
245
+ }
246
+ }
247
+ else {
248
+ sqlBinds.push(index + ' = ?');
249
+ sqlValues.push(bindings[index]);
250
+ }
251
+ }
252
+ }
253
+ for (let index in where) {
254
+ if (where.hasOwnProperty(index)) {
255
+ if (typeof where[index] === 'object' && where[index] !== null) {
256
+ sqlKeys.push(index + ' ' + where[index].operator + ' ?');
257
+ sqlValues.push(where[index].value);
258
+ }
259
+ else {
260
+ sqlKeys.push(index + ' = ?');
261
+ sqlValues.push(where[index]);
262
+ }
263
+ }
264
+ }
265
+ sql = sql + sqlBinds.join(',') + ' where ' + sqlKeys.join(' and ');
266
+ return new Promise((resolve, reject) => {
267
+ this.db.transaction(transaction => {
268
+ transaction.executeSql(sql, sqlValues, (transaction, result) => {
269
+ resolve(result);
270
+ }, (transaction, error) => {
271
+ reject(error);
272
+ });
273
+ });
274
+ });
275
+ }
276
+ dropTable(tables) {
277
+ let cont = 1;
278
+ cont = tables.length;
279
+ return new Promise((resolve, reject) => {
280
+ tables.some(table => {
281
+ if (cont !== 0) {
282
+ this.query('DROP TABLE ' + table)
283
+ .then(() => {
284
+ if (cont === 1) {
285
+ resolve();
286
+ }
287
+ else {
288
+ cont--;
289
+ }
290
+ }, err => {
291
+ cont = 0;
292
+ reject(err);
293
+ return true;
294
+ });
295
+ return false;
296
+ }
297
+ });
298
+ });
299
+ }
300
+ fetchAll(result) {
301
+ let output = [];
302
+ for (let i = 0; i < result.rows.length; i++) {
303
+ output.push(result.rows.item(i));
304
+ }
305
+ return output;
306
+ }
307
+ fetch(result) {
308
+ let objeto = undefined, newObj = undefined;
309
+ if (result.rows.length !== 0) {
310
+ objeto = result.rows.item(0);
311
+ newObj = {};
312
+ const keys = Object.keys(objeto);
313
+ for (let key in keys) {
314
+ newObj[keys[key]] = objeto[keys[key]];
315
+ }
316
+ }
317
+ return newObj;
318
+ }
319
+ rowsCount(result) {
320
+ return result.rows.length;
321
+ }
322
+ tableExists(table) {
323
+ return this.query('select sql from sqlite_master ' +
324
+ 'where type=\'table\' and name=\'' + table + '\'')
325
+ .then(result => (this.rowsCount(result) === 1));
326
+ }
327
+ columnExists(table, column) {
328
+ return this._tableExists(table)
329
+ .then((tableDDL) => {
330
+ if (tableDDL) {
331
+ return this._columnExists(tableDDL, column);
332
+ }
333
+ else {
334
+ return false;
335
+ }
336
+ });
337
+ }
338
+ /* Private */
339
+ defColumn(col) {
340
+ let colSql;
341
+ colSql = col.name + ' ' + col.type;
342
+ if (!col.isNullable) {
343
+ colSql += ' NOT NULL ';
344
+ }
345
+ if (col.default) {
346
+ colSql += ' DEFAULT ' + col.default + ' ';
347
+ }
348
+ if (col.type === 'text' && col.length) {
349
+ colSql += ` CONSTRAINT ${col.name}_length CHECK ( `;
350
+ if (col.isNullable) {
351
+ colSql += `${col.name} is null OR `;
352
+ }
353
+ colSql += `length(${col.name}) <= ${col.length} )`;
354
+ }
355
+ return colSql;
356
+ }
357
+ defUnique(unique) {
358
+ let uniqSql;
359
+ // depende del entorno, producción o desarrollo
360
+ const onConflictUnique = 'on conflict replace';
361
+ if (Array.isArray(unique.fields)) {
362
+ uniqSql = ` CONSTRAINT ${unique.name} UNIQUE ( ${unique.fields.join(',')} ) ${onConflictUnique} `;
363
+ }
364
+ if (typeof unique.fields === 'string') {
365
+ uniqSql = ` CONSTRAINT ${unique.name} UNIQUE ( ${unique.fields} ) ${onConflictUnique} `;
366
+ }
367
+ return uniqSql;
368
+ }
369
+ defForeign(fore) {
370
+ let foreSql;
371
+ if (Array.isArray(fore.foreignKey)) {
372
+ foreSql = ` FOREIGN KEY ( ${fore.foreignKey.join(',')} ) `;
373
+ }
374
+ if (typeof fore.foreignKey === 'string') {
375
+ foreSql = ` FOREIGN KEY ( ${fore.foreignKey} ) `;
376
+ }
377
+ if (Array.isArray(fore.primaryKey)) {
378
+ foreSql = ` REFERENCES ${fore.referenceTable} ( ${fore.primaryKey.join(',')} ) `;
379
+ }
380
+ if (typeof fore.primaryKey === 'string') {
381
+ foreSql = ` REFERENCES ${fore.referenceTable} ( ${fore.primaryKey} ) `;
382
+ }
383
+ return foreSql;
384
+ }
385
+ _tableExists(table) {
386
+ return this.query('select sql from sqlite_master ' +
387
+ 'where type=\'table\' and name=\'' + table + '\'')
388
+ .then(result => {
389
+ if (this.rowsCount(result) === 1) {
390
+ return this.fetch(result).sql;
391
+ }
392
+ else {
393
+ return false;
394
+ }
395
+ });
396
+ }
397
+ _columnExists(tableDDL, column) {
398
+ if (tableDDL.indexOf(column) === -1) {
399
+ return false;
400
+ }
401
+ else {
402
+ return true;
403
+ }
404
+ }
405
+ addColumn(table, col) {
406
+ const colSql = this.defColumn(col);
407
+ const query = 'alter TABLE ' + table + ' add COLUMN ' + colSql;
408
+ return this.query(query);
409
+ }
410
+ }
411
+ const DB_CONFIG = new InjectionToken('dbWrapperConfig');
412
+ const DB_SCHEMA = new InjectionToken('dbWrapperSchema');
413
+ function getDefaultDbConfig() {
414
+ return {
415
+ dbName: 'db.sqlite',
416
+ location: 'default',
417
+ iosDatabaseLocation: 'Library'
418
+ };
419
+ }
420
+ function provideDbWrapper(dbConfig, dbSchema) {
421
+ const config = !!dbConfig ? dbConfig : getDefaultDbConfig();
422
+ return new DbWrapperService(config, dbSchema);
420
423
  }
421
424
 
422
- var DbWrapperModule_1;
423
- let DbWrapperModule = DbWrapperModule_1 = class DbWrapperModule {
424
- static forRoot(dbConfig, schema) {
425
- return {
426
- ngModule: DbWrapperModule_1,
427
- providers: [
428
- { provide: DB_CONFIG, useValue: dbConfig },
429
- { provide: DB_SCHEMA, useValue: schema },
430
- { provide: DbWrapperService, useFactory: provideDbWrapper, deps: [DB_CONFIG, DB_SCHEMA] }
431
- ]
432
- };
433
- }
434
- };
435
- DbWrapperModule = DbWrapperModule_1 = __decorate([
436
- NgModule()
437
- ], DbWrapperModule);
425
+ class DbWrapperModule {
426
+ static forRoot(dbConfig, schema) {
427
+ return {
428
+ ngModule: DbWrapperModule,
429
+ providers: [
430
+ { provide: DB_CONFIG, useValue: dbConfig },
431
+ { provide: DB_SCHEMA, useValue: schema },
432
+ { provide: DbWrapperService, useFactory: provideDbWrapper, deps: [DB_CONFIG, DB_SCHEMA] }
433
+ ]
434
+ };
435
+ }
436
+ }
437
+ /** @nocollapse */ DbWrapperModule.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.2.5", ngImport: i0, type: DbWrapperModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule });
438
+ /** @nocollapse */ DbWrapperModule.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "15.2.5", ngImport: i0, type: DbWrapperModule });
439
+ /** @nocollapse */ DbWrapperModule.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "15.2.5", ngImport: i0, type: DbWrapperModule });
440
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.2.5", ngImport: i0, type: DbWrapperModule, decorators: [{
441
+ type: NgModule
442
+ }] });
438
443
 
439
- var DataType;
440
- (function (DataType) {
441
- DataType["Integer"] = "integer";
442
- DataType["Int"] = "integer";
443
- DataType["TinyInt"] = "integer";
444
- DataType["SmallInt"] = "integer";
445
- DataType["BigInt"] = "integer";
446
- DataType["Text"] = "text";
447
- DataType["Char"] = "text";
448
- DataType["NChar"] = "text";
449
- DataType["VarChar"] = "text";
450
- DataType["NVarChar"] = "text";
451
- DataType["CLOB"] = "text";
452
- DataType["BLOB"] = "blob";
453
- DataType["Real"] = "real";
454
- DataType["Double"] = "real";
455
- DataType["Decimal"] = "real";
456
- DataType["Float"] = "real";
457
- DataType["Boolean"] = "integer";
458
- DataType["DateTime"] = "text";
459
- DataType["Date"] = "text";
460
- })(DataType || (DataType = {}));
461
- var DefaultType;
462
- (function (DefaultType) {
463
- DefaultType["Integer"] = "0";
464
- DefaultType["Int"] = "0";
465
- DefaultType["TinyInt"] = "0";
466
- DefaultType["SmallInt"] = "0";
467
- DefaultType["BigInt"] = "0";
468
- DefaultType["Text"] = "''";
469
- DefaultType["Char"] = "''";
470
- DefaultType["NChar"] = "''";
471
- DefaultType["VarChar"] = "''";
472
- DefaultType["NVarChar"] = "''";
473
- DefaultType["CLOB"] = "''";
474
- DefaultType["BLOB"] = "0";
475
- DefaultType["Real"] = "0.0";
476
- DefaultType["Double"] = "0.0";
477
- DefaultType["Decimal"] = "0.0";
478
- DefaultType["Float"] = "0.0";
479
- DefaultType["Boolean"] = "0";
480
- DefaultType["DateTime"] = "(datetime('now', 'localtime'))";
481
- DefaultType["Date"] = "(date('now', 'localtime'))";
444
+ var DataType;
445
+ (function (DataType) {
446
+ DataType["Integer"] = "integer";
447
+ DataType["Int"] = "integer";
448
+ DataType["TinyInt"] = "integer";
449
+ DataType["SmallInt"] = "integer";
450
+ DataType["BigInt"] = "integer";
451
+ DataType["Text"] = "text";
452
+ DataType["Char"] = "text";
453
+ DataType["NChar"] = "text";
454
+ DataType["VarChar"] = "text";
455
+ DataType["NVarChar"] = "text";
456
+ DataType["CLOB"] = "text";
457
+ DataType["BLOB"] = "blob";
458
+ DataType["Real"] = "real";
459
+ DataType["Double"] = "real";
460
+ DataType["Decimal"] = "real";
461
+ DataType["Float"] = "real";
462
+ DataType["Boolean"] = "integer";
463
+ DataType["DateTime"] = "text";
464
+ DataType["Date"] = "text";
465
+ })(DataType || (DataType = {}));
466
+ var DefaultType;
467
+ (function (DefaultType) {
468
+ DefaultType["Integer"] = "0";
469
+ DefaultType["Int"] = "0";
470
+ DefaultType["TinyInt"] = "0";
471
+ DefaultType["SmallInt"] = "0";
472
+ DefaultType["BigInt"] = "0";
473
+ DefaultType["Text"] = "''";
474
+ DefaultType["Char"] = "''";
475
+ DefaultType["NChar"] = "''";
476
+ DefaultType["VarChar"] = "''";
477
+ DefaultType["NVarChar"] = "''";
478
+ DefaultType["CLOB"] = "''";
479
+ DefaultType["BLOB"] = "0";
480
+ DefaultType["Real"] = "0.0";
481
+ DefaultType["Double"] = "0.0";
482
+ DefaultType["Decimal"] = "0.0";
483
+ DefaultType["Float"] = "0.0";
484
+ DefaultType["Boolean"] = "0";
485
+ DefaultType["DateTime"] = "(datetime('now', 'localtime'))";
486
+ DefaultType["Date"] = "(date('now', 'localtime'))";
482
487
  })(DefaultType || (DefaultType = {}));
483
488
 
484
- /*
485
- * Public API Surface of db-wrapper
489
+ /*
490
+ * Public API Surface of db-wrapper
486
491
  */
487
492
 
488
- /**
489
- * Generated bundle index. Do not edit.
493
+ /**
494
+ * Generated bundle index. Do not edit.
490
495
  */
491
496
 
492
497
  export { DB_CONFIG, DB_SCHEMA, DataType, DbWrapperModule, DbWrapperService, DefaultType, getDefaultDbConfig, provideDbWrapper };
493
- //# sourceMappingURL=db-wrapper.js.map
498
+ //# sourceMappingURL=db-wrapper.mjs.map