db-wrapper 0.0.7 → 0.0.9

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.
@@ -1,863 +1,495 @@
1
- import { __awaiter } from 'tslib';
1
+ import { __decorate, __awaiter } from 'tslib';
2
2
  import { Injectable, InjectionToken, NgModule } from '@angular/core';
3
3
 
4
- /**
5
- * @fileoverview added by tsickle
6
- * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
7
- */
8
- class WindowService {
9
- /**
10
- * @return {?}
11
- */
12
- get nativeWindow() {
13
- return _window();
14
- }
15
- }
16
- WindowService.decorators = [
17
- { type: Injectable }
18
- ];
19
- /**
20
- * @return {?}
21
- */
22
- function _window() {
23
- // Return the global native browser window object
24
- return typeof window !== 'undefined' ? window : undefined;
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;
25
15
  }
26
16
 
27
- /**
28
- * @fileoverview added by tsickle
29
- * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
30
- */
31
- class DbWrapperService {
32
- /**
33
- * @param {?} dbConfig
34
- * @param {?=} dbSchema
35
- */
36
- constructor(dbConfig, dbSchema) {
37
- this._dbName = dbConfig.dbName;
38
- this._location = dbConfig.location || 'default';
39
- this._iosDatabaseLocation = dbConfig.iosDatabaseLocation || 'Library';
40
- /** @type {?} */
41
- const window = (new WindowService()).nativeWindow;
42
- if (dbSchema) {
43
- this.schema = dbSchema;
44
- }
45
- this._readyPromise = new Promise((/**
46
- * @param {?} resolve
47
- * @param {?} reject
48
- * @return {?}
49
- */
50
- (resolve, reject) => {
51
- if (typeof window.cordova === 'undefined') {
52
- setTimeout((/**
53
- * @return {?}
54
- */
55
- () => {
56
- this.init(dbSchema).then((/**
57
- * @return {?}
58
- */
59
- () => {
60
- resolve();
61
- }))
62
- .catch((/**
63
- * @param {?} err
64
- * @return {?}
65
- */
66
- (err) => {
67
- reject(err);
68
- }));
69
- }), 500);
70
- }
71
- else {
72
- document.addEventListener('deviceready', (/**
73
- * @return {?}
74
- */
75
- () => {
76
- console.log('dbWrapper: device ready.');
77
- this.initDevice(dbSchema).then((/**
78
- * @return {?}
79
- */
80
- () => resolve())).catch((/**
81
- * @param {?} err
82
- * @return {?}
83
- */
84
- (err) => reject(err)));
85
- }));
86
- }
87
- }));
88
- }
89
- /**
90
- * @return {?}
91
- */
92
- ready() {
93
- return this._readyPromise;
94
- }
95
- /**
96
- * @param {?} dbSchema
97
- * @return {?}
98
- */
99
- initDevice(dbSchema) {
100
- /** @type {?} */
101
- const window = (new WindowService()).nativeWindow;
102
- return new Promise((/**
103
- * @param {?} resolve
104
- * @param {?} reject
105
- * @return {?}
106
- */
107
- (resolve, reject) => {
108
- this.db = window.sqlitePlugin.openDatabase({
109
- name: this._dbName,
110
- location: this._location,
111
- androidLockWorkaround: 1
112
- });
113
- if (dbSchema) {
114
- this.generate(dbSchema).catch((/**
115
- * @param {?} err
116
- * @return {?}
117
- */
118
- err => {
119
- reject(err);
120
- })).then((/**
121
- * @return {?}
122
- */
123
- () => { resolve(); }));
124
- }
125
- else {
126
- resolve();
127
- }
128
- }));
129
- }
130
- /**
131
- * @param {?} dbSchema
132
- * @return {?}
133
- */
134
- init(dbSchema) {
135
- /** @type {?} */
136
- const window = (new WindowService()).nativeWindow;
137
- return new Promise((/**
138
- * @param {?} resolve
139
- * @param {?} reject
140
- * @return {?}
141
- */
142
- (resolve, reject) => {
143
- this.db = window.openDatabase(this._dbName, '1.0', 'database', -1);
144
- if (dbSchema) {
145
- this.generate(dbSchema).catch((/**
146
- * @param {?} err
147
- * @return {?}
148
- */
149
- err => {
150
- reject(err);
151
- })).then((/**
152
- * @return {?}
153
- */
154
- () => {
155
- resolve();
156
- }));
157
- }
158
- else {
159
- resolve();
160
- }
161
- }));
162
- }
163
- /**
164
- * @param {?} schema
165
- * @return {?}
166
- */
167
- generate(schema) {
168
- /** @type {?} */
169
- const sentences = [];
170
- this.schema = schema;
171
- if (schema.tables) {
172
- schema.tables.forEach((/**
173
- * @param {?} table
174
- * @return {?}
175
- */
176
- table => {
177
- sentences.push(this.createTable(table));
178
- }));
179
- }
180
- if (schema.views) {
181
- schema.views.forEach((/**
182
- * @param {?} view
183
- * @return {?}
184
- */
185
- view => {
186
- sentences.push(this.createView(view));
187
- }));
188
- }
189
- if (sentences.length === 0) {
190
- throw new Error('Esquema de la base de datos vacia.');
191
- }
192
- return Promise.all(sentences);
193
- }
194
- /**
195
- * @param {?} table
196
- * @return {?}
197
- */
198
- createTable(table) {
199
- return __awaiter(this, void 0, void 0, function* () {
200
- /** @type {?} */
201
- let sql = '';
202
- /** @type {?} */
203
- let onConflictPrimary;
204
- /** @type {?} */
205
- const sentences = [];
206
- /** @type {?} */
207
- const newColumns = [];
208
- /** @type {?} */
209
- const tableDDL = yield this.tableExists(table.name);
210
- if (tableDDL) {
211
- table.columns.forEach((/**
212
- * @param {?} col
213
- * @return {?}
214
- */
215
- col => {
216
- if (!this.columnExists((/** @type {?} */ (tableDDL)), col.name)) {
217
- newColumns.push(this.addColumn(table.name, col));
218
- }
219
- }));
220
- }
221
- else {
222
- table.columns.forEach((/**
223
- * @param {?} col
224
- * @return {?}
225
- */
226
- col => {
227
- sentences.push(this.defColumn(col));
228
- }));
229
- }
230
- onConflictPrimary = 'on conflict fail';
231
- if (Array.isArray(table.primary)) {
232
- sentences.push(' CONSTRAINT identificador PRIMARY KEY (' + table.primary.join(',') + ') ' + onConflictPrimary);
233
- }
234
- if (typeof table.primary === 'string') {
235
- sentences.push(' CONSTRAINT identificador PRIMARY KEY (' + table.primary + ') ' + onConflictPrimary);
236
- }
237
- if (table.uniques) {
238
- table.uniques.forEach((/**
239
- * @param {?} uniq
240
- * @return {?}
241
- */
242
- uniq => {
243
- sentences.push(this.defUnique(uniq));
244
- }));
245
- }
246
- if (table.foreigns) {
247
- table.foreigns.forEach((/**
248
- * @param {?} fore
249
- * @return {?}
250
- */
251
- fore => {
252
- sentences.push(this.defForeign(fore));
253
- }));
254
- }
255
- if (tableDDL && newColumns.length !== 0) {
256
- return Promise.all(newColumns)
257
- .then((/**
258
- * @return {?}
259
- */
260
- () => { console.log(`Table ${table.name} altered.`); }))
261
- .catch((/**
262
- * @param {?} err
263
- * @return {?}
264
- */
265
- (err) => {
266
- console.error(`Table ${table.name}: ${err.message}`);
267
- throw new Error(`Table ${table.name}: ${err.message}`);
268
- }));
269
- }
270
- else if (!tableDDL) {
271
- sql = 'CREATE TABLE IF NOT EXISTS ' + table.name + ' (' + sentences.join(',') + ')';
272
- return this.query(sql)
273
- .then((/**
274
- * @return {?}
275
- */
276
- () => { console.log(`Table ${table.name} created.`); }))
277
- .catch((/**
278
- * @param {?} err
279
- * @return {?}
280
- */
281
- (err) => {
282
- console.error(`Table ${table.name}: ${err.message}`);
283
- throw new Error(`Table ${table.name}: ${err.message}`);
284
- }));
285
- }
286
- else {
287
- return Promise.resolve().then((/**
288
- * @return {?}
289
- */
290
- () => { console.log(`Table ${table.name} initialized.`); }));
291
- }
292
- });
293
- }
294
- /**
295
- * @param {?} view
296
- * @return {?}
297
- */
298
- createView(view) {
299
- /** @type {?} */
300
- let sql;
301
- sql = 'CREATE VIEW IF NOT EXISTS ' + view.name
302
- + ' AS ' + view.sql;
303
- return this.query(sql);
304
- }
305
- /**
306
- * @param {?} tableName
307
- * @return {?}
308
- */
309
- getSchemaTable(tableName) {
310
- /** @type {?} */
311
- let res;
312
- this.schema.tables.forEach((/**
313
- * @param {?} table
314
- * @return {?}
315
- */
316
- table => {
317
- if (table.name === tableName) {
318
- res = table;
319
- }
320
- }));
321
- return res;
322
- }
323
- /**
324
- * @param {?} table
325
- * @return {?}
326
- */
327
- getUniquesTable(table) {
328
- /** @type {?} */
329
- let res;
330
- table.uniques.forEach((/**
331
- * @param {?} uniq
332
- * @return {?}
333
- */
334
- uniq => {
335
- res[uniq.name] = uniq;
336
- }));
337
- return res;
338
- }
339
- /**
340
- * @param {?} query
341
- * @param {?=} bindings
342
- * @return {?}
343
- */
344
- query(query, bindings = []) {
345
- return new Promise((/**
346
- * @param {?} resolve
347
- * @param {?} reject
348
- * @return {?}
349
- */
350
- (resolve, reject) => {
351
- if (query.indexOf('select') === 0) {
352
- this.db.readTransaction((/**
353
- * @param {?} transaction
354
- * @return {?}
355
- */
356
- (transaction) => {
357
- transaction.executeSql(query, bindings, (/**
358
- * @param {?} transaction
359
- * @param {?} result
360
- * @return {?}
361
- */
362
- (transaction, result) => {
363
- resolve(result);
364
- }), (/**
365
- * @param {?} transaction
366
- * @param {?} error
367
- * @return {?}
368
- */
369
- (transaction, error) => {
370
- reject(error);
371
- }));
372
- }), (/**
373
- * @param {?} err
374
- * @return {?}
375
- */
376
- (err) => reject(err)));
377
- }
378
- else {
379
- this.db.transaction((/**
380
- * @param {?} transaction
381
- * @return {?}
382
- */
383
- (transaction) => {
384
- transaction.executeSql(query, bindings, (/**
385
- * @param {?} transaction
386
- * @param {?} result
387
- * @return {?}
388
- */
389
- (transaction, result) => {
390
- resolve(result);
391
- }), (/**
392
- * @param {?} transaction
393
- * @param {?} error
394
- * @return {?}
395
- */
396
- (transaction, error) => {
397
- reject(error);
398
- }));
399
- }), (/**
400
- * @param {?} err
401
- * @return {?}
402
- */
403
- (err) => reject(err)));
404
- }
405
- }));
406
- }
407
- /**
408
- * @param {?} query
409
- * @param {?=} bindings
410
- * @return {?}
411
- */
412
- Count(query, bindings = []) {
413
- return this.query(query, bindings).then((/**
414
- * @param {?} rows
415
- * @return {?}
416
- */
417
- rows => {
418
- return this.rowsCount(rows);
419
- }));
420
- }
421
- /**
422
- * @param {?} table
423
- * @param {?} bindings
424
- * @return {?}
425
- */
426
- insert(table, bindings) {
427
- /** @type {?} */
428
- let sql = '';
429
- /** @type {?} */
430
- let sqlBinds = [];
431
- /** @type {?} */
432
- let sqlKeys = [];
433
- /** @type {?} */
434
- let sqlValues = [];
435
- sql = sql + 'insert into ' + table + ' ';
436
- for (const index in bindings) {
437
- if (bindings.hasOwnProperty(index)) {
438
- sqlKeys.push(index);
439
- sqlValues.push(bindings[index]);
440
- sqlBinds.push('?');
441
- }
442
- }
443
- sql = sql + '(' + sqlKeys.join(',') + ') values (' + sqlBinds.join(',') + ')';
444
- return new Promise((/**
445
- * @param {?} resolve
446
- * @param {?} reject
447
- * @return {?}
448
- */
449
- (resolve, reject) => {
450
- this.db.transaction((/**
451
- * @param {?} transaction
452
- * @return {?}
453
- */
454
- transaction => {
455
- transaction.executeSql(sql, sqlValues, (/**
456
- * @param {?} transaction
457
- * @param {?} result
458
- * @return {?}
459
- */
460
- (transaction, result) => {
461
- resolve(result);
462
- }), (/**
463
- * @param {?} transaction
464
- * @param {?} error
465
- * @return {?}
466
- */
467
- (transaction, error) => {
468
- reject(error);
469
- }));
470
- }));
471
- }));
472
- }
473
- /**
474
- * @param {?} table
475
- * @param {?} bindings
476
- * @param {?} where
477
- * @return {?}
478
- */
479
- update(table, bindings, where) {
480
- /** @type {?} */
481
- let sql = '';
482
- /** @type {?} */
483
- let sqlBinds = [];
484
- /** @type {?} */
485
- let sqlKeys = [];
486
- /** @type {?} */
487
- let sqlValues = [];
488
- sql = sql + 'update ' + table + ' set ';
489
- for (let index in bindings) {
490
- if (bindings.hasOwnProperty(index)) {
491
- /** @type {?} */
492
- let newObj = bindings[index];
493
- if (typeof newObj === 'object' && newObj !== null) {
494
- sqlValues.push(newObj.value);
495
- if (newObj.ifnull) {
496
- sqlBinds.push(index + ' = ifnull( ' + index + ',0) + ?');
497
- }
498
- else if (newObj.operator) {
499
- sqlBinds.push(index + ' = ' + index + newObj.operator + ' ?');
500
- }
501
- else {
502
- sqlBinds.push(index + ' = ?');
503
- }
504
- }
505
- else {
506
- sqlBinds.push(index + ' = ?');
507
- sqlValues.push(bindings[index]);
508
- }
509
- }
510
- }
511
- for (let index in where) {
512
- if (where.hasOwnProperty(index)) {
513
- if (typeof where[index] === 'object' && where[index] !== null) {
514
- sqlKeys.push(index + ' ' + where[index].operator + ' ?');
515
- sqlValues.push(where[index].value);
516
- }
517
- else {
518
- sqlKeys.push(index + ' = ?');
519
- sqlValues.push(where[index]);
520
- }
521
- }
522
- }
523
- sql = sql + sqlBinds.join(',') + ' where ' + sqlKeys.join(' and ');
524
- return new Promise((/**
525
- * @param {?} resolve
526
- * @param {?} reject
527
- * @return {?}
528
- */
529
- (resolve, reject) => {
530
- this.db.transaction((/**
531
- * @param {?} transaction
532
- * @return {?}
533
- */
534
- transaction => {
535
- transaction.executeSql(sql, sqlValues, (/**
536
- * @param {?} transaction
537
- * @param {?} result
538
- * @return {?}
539
- */
540
- (transaction, result) => {
541
- resolve(result);
542
- }), (/**
543
- * @param {?} transaction
544
- * @param {?} error
545
- * @return {?}
546
- */
547
- (transaction, error) => {
548
- reject(error);
549
- }));
550
- }));
551
- }));
552
- }
553
- /**
554
- * @param {?} tables
555
- * @return {?}
556
- */
557
- dropTable(tables) {
558
- /** @type {?} */
559
- let cont = 1;
560
- cont = tables.length;
561
- return new Promise((/**
562
- * @param {?} resolve
563
- * @param {?} reject
564
- * @return {?}
565
- */
566
- (resolve, reject) => {
567
- tables.some((/**
568
- * @param {?} table
569
- * @return {?}
570
- */
571
- table => {
572
- if (cont !== 0) {
573
- this.query('DROP TABLE ' + table)
574
- .then((/**
575
- * @return {?}
576
- */
577
- () => {
578
- if (cont === 1) {
579
- resolve();
580
- }
581
- else {
582
- cont--;
583
- }
584
- }), (/**
585
- * @param {?} err
586
- * @return {?}
587
- */
588
- err => {
589
- cont = 0;
590
- reject(err);
591
- return true;
592
- }));
593
- return false;
594
- }
595
- }));
596
- }));
597
- }
598
- /**
599
- * @param {?} result
600
- * @return {?}
601
- */
602
- fetchAll(result) {
603
- /** @type {?} */
604
- let output = [];
605
- for (let i = 0; i < result.rows.length; i++) {
606
- output.push(result.rows.item(i));
607
- }
608
- return output;
609
- }
610
- /**
611
- * @param {?} result
612
- * @return {?}
613
- */
614
- fetch(result) {
615
- /** @type {?} */
616
- let objeto = undefined;
617
- /** @type {?} */
618
- let newObj = undefined;
619
- if (result.rows.length !== 0) {
620
- objeto = result.rows.item(0);
621
- newObj = {};
622
- /** @type {?} */
623
- const keys = Object.keys(objeto);
624
- for (let key in keys) {
625
- newObj[keys[key]] = objeto[keys[key]];
626
- }
627
- }
628
- return newObj;
629
- }
630
- /**
631
- * @param {?} result
632
- * @return {?}
633
- */
634
- rowsCount(result) {
635
- return result.rows.length;
636
- }
637
- /* Private */
638
- /**
639
- * @private
640
- * @param {?} col
641
- * @return {?}
642
- */
643
- defColumn(col) {
644
- /** @type {?} */
645
- let colSql;
646
- colSql = col.name + ' ' + col.type;
647
- if (!col.isNullable) {
648
- colSql += ' NOT NULL ';
649
- }
650
- if (col.default) {
651
- colSql += ' DEFAULT ' + col.default + ' ';
652
- }
653
- if (col.type === 'text' && col.length) {
654
- colSql += ` CONSTRAINT ${col.name}_length CHECK ( `;
655
- if (col.isNullable) {
656
- colSql += `${col.name} is null OR `;
657
- }
658
- colSql += `length(${col.name}) <= ${col.length} )`;
659
- }
660
- return colSql;
661
- }
662
- /**
663
- * @private
664
- * @param {?} unique
665
- * @return {?}
666
- */
667
- defUnique(unique) {
668
- /** @type {?} */
669
- let uniqSql;
670
- // depende del entorno, producción o desarrollo
671
- /** @type {?} */
672
- const onConflictUnique = 'on conflict fail';
673
- if (Array.isArray(unique.fields)) {
674
- uniqSql = ` CONSTRAINT ${unique.name} UNIQUE ( ${unique.fields.join(',')} ) ${onConflictUnique} `;
675
- }
676
- if (typeof unique.fields === 'string') {
677
- uniqSql = ` CONSTRAINT ${unique.name} UNIQUE ( ${unique.fields} ) ${onConflictUnique} `;
678
- }
679
- return uniqSql;
680
- }
681
- /**
682
- * @private
683
- * @param {?} fore
684
- * @return {?}
685
- */
686
- defForeign(fore) {
687
- /** @type {?} */
688
- let foreSql;
689
- if (Array.isArray(fore.foreignKey)) {
690
- foreSql = ` FOREIGN KEY ( ${fore.foreignKey.join(',')} ) `;
691
- }
692
- if (typeof fore.foreignKey === 'string') {
693
- foreSql = ` FOREIGN KEY ( ${fore.foreignKey} ) `;
694
- }
695
- if (Array.isArray(fore.primaryKey)) {
696
- foreSql = ` REFERENCES ${fore.referenceTable} ( ${fore.primaryKey.join(',')} ) `;
697
- }
698
- if (typeof fore.primaryKey === 'string') {
699
- foreSql = ` REFERENCES ${fore.referenceTable} ( ${fore.primaryKey} ) `;
700
- }
701
- return foreSql;
702
- }
703
- /**
704
- * @private
705
- * @param {?} table
706
- * @return {?}
707
- */
708
- tableExists(table) {
709
- return this.query('select sql from sqlite_master ' +
710
- 'where type=\'table\' and name=\'' + table + '\'')
711
- .then((/**
712
- * @param {?} result
713
- * @return {?}
714
- */
715
- result => {
716
- if (this.rowsCount(result) === 1) {
717
- return (/** @type {?} */ (((/** @type {?} */ (this.fetch(result)))).sql));
718
- }
719
- else {
720
- return false;
721
- }
722
- }));
723
- }
724
- /**
725
- * @private
726
- * @param {?} tableDDL
727
- * @param {?} column
728
- * @return {?}
729
- */
730
- columnExists(tableDDL, column) {
731
- if (tableDDL.indexOf(column) === -1) {
732
- return false;
733
- }
734
- else {
735
- return true;
736
- }
737
- }
738
- /**
739
- * @private
740
- * @param {?} table
741
- * @param {?} col
742
- * @return {?}
743
- */
744
- addColumn(table, col) {
745
- /** @type {?} */
746
- const colSql = this.defColumn(col);
747
- /** @type {?} */
748
- const query = 'alter TABLE ' + table + ' add COLUMN ' + colSql;
749
- return this.query(query);
750
- }
751
- }
752
- /** @type {?} */
753
- const DB_CONFIG = new InjectionToken('dbWrapperConfig');
754
- /** @type {?} */
755
- const DB_SCHEMA = new InjectionToken('dbWrapperSchema');
756
- /**
757
- * @return {?}
758
- */
759
- function getDefaultDbConfig() {
760
- return {
761
- dbName: 'db.sqlite',
762
- location: 'default',
763
- iosDatabaseLocation: 'Library'
764
- };
765
- }
766
- /**
767
- * @param {?} dbConfig
768
- * @param {?=} dbSchema
769
- * @return {?}
770
- */
771
- function provideDbWrapper(dbConfig, dbSchema) {
772
- /** @type {?} */
773
- const config = !!dbConfig ? dbConfig : getDefaultDbConfig();
774
- return new DbWrapperService(config, dbSchema);
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
+ this._androidDatabaseProvider = dbConfig.androidDatabaseProvider || 'default';
23
+ const window = (new WindowService()).nativeWindow;
24
+ if (dbSchema) {
25
+ this.schema = dbSchema;
26
+ }
27
+ this._readyPromise = new Promise((resolve, reject) => {
28
+ if (typeof window.cordova === 'undefined') {
29
+ setTimeout(() => {
30
+ this.init(dbSchema).then(() => {
31
+ resolve();
32
+ })
33
+ .catch((err) => {
34
+ reject(err);
35
+ });
36
+ }, 500);
37
+ }
38
+ else {
39
+ document.addEventListener('deviceready', () => {
40
+ console.log('dbWrapper: device ready.');
41
+ this.initDevice(dbSchema).then(() => resolve()).catch((err) => reject(err));
42
+ });
43
+ }
44
+ });
45
+ }
46
+ ready() {
47
+ return this._readyPromise;
48
+ }
49
+ initDevice(dbSchema) {
50
+ const window = (new WindowService()).nativeWindow;
51
+ return new Promise((resolve, reject) => {
52
+ this.db = window.sqlitePlugin.openDatabase({
53
+ name: this._dbName,
54
+ location: this._location,
55
+ androidLockWorkaround: 1,
56
+ androidDatabaseProvider: this._androidDatabaseProvider,
57
+ });
58
+ if (dbSchema) {
59
+ this.generate(dbSchema).catch(err => {
60
+ reject(err);
61
+ }).then(() => { resolve(); });
62
+ }
63
+ else {
64
+ resolve();
65
+ }
66
+ });
67
+ }
68
+ init(dbSchema) {
69
+ const window = (new WindowService()).nativeWindow;
70
+ return new Promise((resolve, reject) => {
71
+ this.db = window.openDatabase(this._dbName, '1.0', 'database', -1);
72
+ if (dbSchema) {
73
+ this.generate(dbSchema).catch(err => {
74
+ reject(err);
75
+ }).then(() => {
76
+ resolve();
77
+ });
78
+ }
79
+ else {
80
+ resolve();
81
+ }
82
+ });
83
+ }
84
+ generate(schema) {
85
+ const sentences = [];
86
+ this.schema = schema;
87
+ if (schema.tables) {
88
+ schema.tables.forEach(table => {
89
+ sentences.push(this.createTable(table));
90
+ });
91
+ }
92
+ if (schema.views) {
93
+ schema.views.forEach(view => {
94
+ sentences.push(this.createView(view));
95
+ });
96
+ }
97
+ if (sentences.length === 0) {
98
+ throw new Error('Esquema de la base de datos vacia.');
99
+ }
100
+ return Promise.all(sentences);
101
+ }
102
+ createTable(table) {
103
+ return __awaiter(this, void 0, void 0, function* () {
104
+ let sql = '', onConflictPrimary;
105
+ const sentences = [], newColumns = [];
106
+ const tableDDL = yield this._tableExists(table.name);
107
+ if (tableDDL) {
108
+ table.columns.forEach(col => {
109
+ if (!this._columnExists(tableDDL, col.name)) {
110
+ newColumns.push(this.addColumn(table.name, col));
111
+ }
112
+ });
113
+ }
114
+ else {
115
+ table.columns.forEach(col => {
116
+ sentences.push(this.defColumn(col));
117
+ });
118
+ }
119
+ onConflictPrimary = 'on conflict fail';
120
+ if (Array.isArray(table.primary)) {
121
+ sentences.push(' CONSTRAINT identificador PRIMARY KEY (' + table.primary.join(',') + ') ' + onConflictPrimary);
122
+ }
123
+ if (typeof table.primary === 'string') {
124
+ sentences.push(' CONSTRAINT identificador PRIMARY KEY (' + table.primary + ') ' + onConflictPrimary);
125
+ }
126
+ if (table.uniques) {
127
+ table.uniques.forEach(uniq => {
128
+ sentences.push(this.defUnique(uniq));
129
+ });
130
+ }
131
+ if (table.foreigns) {
132
+ table.foreigns.forEach(fore => {
133
+ sentences.push(this.defForeign(fore));
134
+ });
135
+ }
136
+ if (tableDDL && newColumns.length !== 0) {
137
+ return Promise.all(newColumns)
138
+ .then(() => { console.log(`Table ${table.name} altered.`); })
139
+ .catch((err) => {
140
+ console.error(`Table ${table.name}: ${err.message}`);
141
+ throw new Error(`Table ${table.name}: ${err.message}`);
142
+ });
143
+ }
144
+ else if (!tableDDL) {
145
+ sql = 'CREATE TABLE IF NOT EXISTS ' + table.name + ' (' + sentences.join(',') + ')';
146
+ return this.query(sql)
147
+ .then(() => { console.log(`Table ${table.name} created.`); })
148
+ .catch((err) => {
149
+ console.error(`Table ${table.name}: ${err.message}`);
150
+ throw new Error(`Table ${table.name}: ${err.message}`);
151
+ });
152
+ }
153
+ else {
154
+ return Promise.resolve().then(() => { console.log(`Table ${table.name} initialized.`); });
155
+ }
156
+ });
157
+ }
158
+ createView(view) {
159
+ let sql;
160
+ sql = 'CREATE VIEW IF NOT EXISTS ' + view.name
161
+ + ' AS ' + view.sql;
162
+ return this.query(sql);
163
+ }
164
+ getSchemaTable(tableName) {
165
+ let res;
166
+ this.schema.tables.forEach(table => {
167
+ if (table.name === tableName) {
168
+ res = table;
169
+ }
170
+ });
171
+ return res;
172
+ }
173
+ getUniquesTable(table) {
174
+ let res;
175
+ table.uniques.forEach(uniq => {
176
+ res[uniq.name] = uniq;
177
+ });
178
+ return res;
179
+ }
180
+ query(query, bindings = []) {
181
+ return new Promise((resolve, reject) => {
182
+ if (query.indexOf('select') === 0) {
183
+ this.db.readTransaction((transaction) => {
184
+ transaction.executeSql(query, bindings, (transaction, result) => {
185
+ resolve(result);
186
+ }, (transaction, error) => {
187
+ reject(error);
188
+ });
189
+ }, (err) => reject(err));
190
+ }
191
+ else {
192
+ this.db.transaction((transaction) => {
193
+ transaction.executeSql(query, bindings, (transaction, result) => {
194
+ resolve(result);
195
+ }, (transaction, error) => {
196
+ reject(error);
197
+ });
198
+ }, (err) => reject(err));
199
+ }
200
+ });
201
+ }
202
+ Count(query, bindings = []) {
203
+ return this.query(query, bindings).then(rows => {
204
+ return this.rowsCount(rows);
205
+ });
206
+ }
207
+ insert(table, bindings) {
208
+ let sql = '', sqlBinds = [], sqlKeys = [], sqlValues = [];
209
+ sql = sql + 'insert into ' + table + ' ';
210
+ for (const index in bindings) {
211
+ if (bindings.hasOwnProperty(index)) {
212
+ sqlKeys.push(index);
213
+ sqlValues.push(bindings[index]);
214
+ sqlBinds.push('?');
215
+ }
216
+ }
217
+ sql = sql + '(' + sqlKeys.join(',') + ') values (' + sqlBinds.join(',') + ')';
218
+ return new Promise((resolve, reject) => {
219
+ this.db.transaction(transaction => {
220
+ transaction.executeSql(sql, sqlValues, (transaction, result) => {
221
+ resolve(result);
222
+ }, (transaction, error) => {
223
+ reject(error);
224
+ });
225
+ });
226
+ });
227
+ }
228
+ update(table, bindings, where) {
229
+ let sql = '', sqlBinds = [], sqlKeys = [], sqlValues = [];
230
+ sql = sql + 'update ' + table + ' set ';
231
+ for (let index in bindings) {
232
+ if (bindings.hasOwnProperty(index)) {
233
+ let newObj = bindings[index];
234
+ if (typeof newObj === 'object' && newObj !== null) {
235
+ sqlValues.push(newObj.value);
236
+ if (newObj.ifnull) {
237
+ sqlBinds.push(index + ' = ifnull( ' + index + ',0) + ?');
238
+ }
239
+ else if (newObj.operator) {
240
+ sqlBinds.push(index + ' = ' + index + newObj.operator + ' ?');
241
+ }
242
+ else {
243
+ sqlBinds.push(index + ' = ?');
244
+ }
245
+ }
246
+ else {
247
+ sqlBinds.push(index + ' = ?');
248
+ sqlValues.push(bindings[index]);
249
+ }
250
+ }
251
+ }
252
+ for (let index in where) {
253
+ if (where.hasOwnProperty(index)) {
254
+ if (typeof where[index] === 'object' && where[index] !== null) {
255
+ sqlKeys.push(index + ' ' + where[index].operator + ' ?');
256
+ sqlValues.push(where[index].value);
257
+ }
258
+ else {
259
+ sqlKeys.push(index + ' = ?');
260
+ sqlValues.push(where[index]);
261
+ }
262
+ }
263
+ }
264
+ sql = sql + sqlBinds.join(',') + ' where ' + sqlKeys.join(' and ');
265
+ return new Promise((resolve, reject) => {
266
+ this.db.transaction(transaction => {
267
+ transaction.executeSql(sql, sqlValues, (transaction, result) => {
268
+ resolve(result);
269
+ }, (transaction, error) => {
270
+ reject(error);
271
+ });
272
+ });
273
+ });
274
+ }
275
+ dropTable(tables) {
276
+ let cont = 1;
277
+ cont = tables.length;
278
+ return new Promise((resolve, reject) => {
279
+ tables.some(table => {
280
+ if (cont !== 0) {
281
+ this.query('DROP TABLE ' + table)
282
+ .then(() => {
283
+ if (cont === 1) {
284
+ resolve();
285
+ }
286
+ else {
287
+ cont--;
288
+ }
289
+ }, err => {
290
+ cont = 0;
291
+ reject(err);
292
+ return true;
293
+ });
294
+ return false;
295
+ }
296
+ });
297
+ });
298
+ }
299
+ fetchAll(result) {
300
+ let output = [];
301
+ for (let i = 0; i < result.rows.length; i++) {
302
+ output.push(result.rows.item(i));
303
+ }
304
+ return output;
305
+ }
306
+ fetch(result) {
307
+ let objeto = undefined, newObj = undefined;
308
+ if (result.rows.length !== 0) {
309
+ objeto = result.rows.item(0);
310
+ newObj = {};
311
+ const keys = Object.keys(objeto);
312
+ for (let key in keys) {
313
+ newObj[keys[key]] = objeto[keys[key]];
314
+ }
315
+ }
316
+ return newObj;
317
+ }
318
+ rowsCount(result) {
319
+ return result.rows.length;
320
+ }
321
+ tableExists(table) {
322
+ return this.query('select sql from sqlite_master ' +
323
+ 'where type=\'table\' and name=\'' + table + '\'')
324
+ .then(result => (this.rowsCount(result) === 1));
325
+ }
326
+ columnExists(table, column) {
327
+ return this._tableExists(table)
328
+ .then((tableDDL) => {
329
+ if (tableDDL) {
330
+ return this._columnExists(tableDDL, column);
331
+ }
332
+ else {
333
+ return false;
334
+ }
335
+ });
336
+ }
337
+ /* Private */
338
+ defColumn(col) {
339
+ let colSql;
340
+ colSql = col.name + ' ' + col.type;
341
+ if (!col.isNullable) {
342
+ colSql += ' NOT NULL ';
343
+ }
344
+ if (col.default) {
345
+ colSql += ' DEFAULT ' + col.default + ' ';
346
+ }
347
+ if (col.type === 'text' && col.length) {
348
+ colSql += ` CONSTRAINT ${col.name}_length CHECK ( `;
349
+ if (col.isNullable) {
350
+ colSql += `${col.name} is null OR `;
351
+ }
352
+ colSql += `length(${col.name}) <= ${col.length} )`;
353
+ }
354
+ return colSql;
355
+ }
356
+ defUnique(unique) {
357
+ let uniqSql;
358
+ // depende del entorno, producción o desarrollo
359
+ const onConflictUnique = 'on conflict replace';
360
+ if (Array.isArray(unique.fields)) {
361
+ uniqSql = ` CONSTRAINT ${unique.name} UNIQUE ( ${unique.fields.join(',')} ) ${onConflictUnique} `;
362
+ }
363
+ if (typeof unique.fields === 'string') {
364
+ uniqSql = ` CONSTRAINT ${unique.name} UNIQUE ( ${unique.fields} ) ${onConflictUnique} `;
365
+ }
366
+ return uniqSql;
367
+ }
368
+ defForeign(fore) {
369
+ let foreSql;
370
+ if (Array.isArray(fore.foreignKey)) {
371
+ foreSql = ` FOREIGN KEY ( ${fore.foreignKey.join(',')} ) `;
372
+ }
373
+ if (typeof fore.foreignKey === 'string') {
374
+ foreSql = ` FOREIGN KEY ( ${fore.foreignKey} ) `;
375
+ }
376
+ if (Array.isArray(fore.primaryKey)) {
377
+ foreSql = ` REFERENCES ${fore.referenceTable} ( ${fore.primaryKey.join(',')} ) `;
378
+ }
379
+ if (typeof fore.primaryKey === 'string') {
380
+ foreSql = ` REFERENCES ${fore.referenceTable} ( ${fore.primaryKey} ) `;
381
+ }
382
+ return foreSql;
383
+ }
384
+ _tableExists(table) {
385
+ return this.query('select sql from sqlite_master ' +
386
+ 'where type=\'table\' and name=\'' + table + '\'')
387
+ .then(result => {
388
+ if (this.rowsCount(result) === 1) {
389
+ return this.fetch(result).sql;
390
+ }
391
+ else {
392
+ return false;
393
+ }
394
+ });
395
+ }
396
+ _columnExists(tableDDL, column) {
397
+ if (tableDDL.indexOf(column) === -1) {
398
+ return false;
399
+ }
400
+ else {
401
+ return true;
402
+ }
403
+ }
404
+ addColumn(table, col) {
405
+ const colSql = this.defColumn(col);
406
+ const query = 'alter TABLE ' + table + ' add COLUMN ' + colSql;
407
+ return this.query(query);
408
+ }
409
+ }
410
+ const DB_CONFIG = new InjectionToken('dbWrapperConfig');
411
+ const DB_SCHEMA = new InjectionToken('dbWrapperSchema');
412
+ function getDefaultDbConfig() {
413
+ return {
414
+ dbName: 'db.sqlite',
415
+ location: 'default',
416
+ iosDatabaseLocation: 'Library'
417
+ };
418
+ }
419
+ function provideDbWrapper(dbConfig, dbSchema) {
420
+ const config = !!dbConfig ? dbConfig : getDefaultDbConfig();
421
+ return new DbWrapperService(config, dbSchema);
775
422
  }
776
423
 
777
- /**
778
- * @fileoverview added by tsickle
779
- * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
780
- */
781
- class DbWrapperModule {
782
- /**
783
- * @param {?} dbConfig
784
- * @param {?=} schema
785
- * @return {?}
786
- */
787
- static forRoot(dbConfig, schema) {
788
- return {
789
- ngModule: DbWrapperModule,
790
- providers: [
791
- { provide: DB_CONFIG, useValue: dbConfig },
792
- { provide: DB_SCHEMA, useValue: schema },
793
- { provide: DbWrapperService, useFactory: provideDbWrapper, deps: [DB_CONFIG, DB_SCHEMA] }
794
- ]
795
- };
796
- }
797
- }
798
- DbWrapperModule.decorators = [
799
- { type: NgModule }
800
- ];
801
-
802
- /**
803
- * @fileoverview added by tsickle
804
- * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
805
- */
806
- /** @enum {string} */
807
- const DataType = {
808
- Integer: 'integer',
809
- Int: 'integer',
810
- TinyInt: 'integer',
811
- SmallInt: 'integer',
812
- BigInt: 'integer',
813
- Text: 'text',
814
- Char: 'text',
815
- NChar: 'text',
816
- VarChar: 'text',
817
- NVarChar: 'text',
818
- CLOB: 'text',
819
- BLOB: 'blob',
820
- Real: 'real',
821
- Double: 'real',
822
- Decimal: 'real',
823
- Float: 'real',
824
- Boolean: 'integer',
825
- DateTime: 'text',
826
- Date: 'text',
827
- };
828
- /** @enum {string} */
829
- const DefaultType = {
830
- Integer: '0',
831
- Int: '0',
832
- TinyInt: '0',
833
- SmallInt: '0',
834
- BigInt: '0',
835
- Text: '\'\'',
836
- Char: '\'\'',
837
- NChar: '\'\'',
838
- VarChar: '\'\'',
839
- NVarChar: '\'\'',
840
- CLOB: '\'\'',
841
- BLOB: '0',
842
- Real: '0.0',
843
- Double: '0.0',
844
- Decimal: '0.0',
845
- Float: '0.0',
846
- Boolean: '0',
847
- DateTime: '(datetime(\'now\', \'localtime\'))',
848
- Date: '(date(\'now\', \'localtime\'))',
424
+ var DbWrapperModule_1;
425
+ let DbWrapperModule = DbWrapperModule_1 = class DbWrapperModule {
426
+ static forRoot(dbConfig, schema) {
427
+ return {
428
+ ngModule: DbWrapperModule_1,
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
+ }
849
436
  };
437
+ DbWrapperModule = DbWrapperModule_1 = __decorate([
438
+ NgModule()
439
+ ], DbWrapperModule);
850
440
 
851
- /**
852
- * @fileoverview added by tsickle
853
- * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
854
- */
441
+ var DataType;
442
+ (function (DataType) {
443
+ DataType["Integer"] = "integer";
444
+ DataType["Int"] = "integer";
445
+ DataType["TinyInt"] = "integer";
446
+ DataType["SmallInt"] = "integer";
447
+ DataType["BigInt"] = "integer";
448
+ DataType["Text"] = "text";
449
+ DataType["Char"] = "text";
450
+ DataType["NChar"] = "text";
451
+ DataType["VarChar"] = "text";
452
+ DataType["NVarChar"] = "text";
453
+ DataType["CLOB"] = "text";
454
+ DataType["BLOB"] = "blob";
455
+ DataType["Real"] = "real";
456
+ DataType["Double"] = "real";
457
+ DataType["Decimal"] = "real";
458
+ DataType["Float"] = "real";
459
+ DataType["Boolean"] = "integer";
460
+ DataType["DateTime"] = "text";
461
+ DataType["Date"] = "text";
462
+ })(DataType || (DataType = {}));
463
+ var DefaultType;
464
+ (function (DefaultType) {
465
+ DefaultType["Integer"] = "0";
466
+ DefaultType["Int"] = "0";
467
+ DefaultType["TinyInt"] = "0";
468
+ DefaultType["SmallInt"] = "0";
469
+ DefaultType["BigInt"] = "0";
470
+ DefaultType["Text"] = "''";
471
+ DefaultType["Char"] = "''";
472
+ DefaultType["NChar"] = "''";
473
+ DefaultType["VarChar"] = "''";
474
+ DefaultType["NVarChar"] = "''";
475
+ DefaultType["CLOB"] = "''";
476
+ DefaultType["BLOB"] = "0";
477
+ DefaultType["Real"] = "0.0";
478
+ DefaultType["Double"] = "0.0";
479
+ DefaultType["Decimal"] = "0.0";
480
+ DefaultType["Float"] = "0.0";
481
+ DefaultType["Boolean"] = "0";
482
+ DefaultType["DateTime"] = "(datetime('now', 'localtime'))";
483
+ DefaultType["Date"] = "(date('now', 'localtime'))";
484
+ })(DefaultType || (DefaultType = {}));
855
485
 
856
- /**
857
- * @fileoverview added by tsickle
858
- * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
486
+ /*
487
+ * Public API Surface of db-wrapper
859
488
  */
860
489
 
861
- export { getDefaultDbConfig, provideDbWrapper, DbWrapperService, DB_CONFIG, DB_SCHEMA, DbWrapperModule, DataType, DefaultType };
490
+ /**
491
+ * Generated bundle index. Do not edit.
492
+ */
862
493
 
863
- //# sourceMappingURL=db-wrapper.js.map
494
+ export { DB_CONFIG, DB_SCHEMA, DataType, DbWrapperModule, DbWrapperService, DefaultType, getDefaultDbConfig, provideDbWrapper };
495
+ //# sourceMappingURL=db-wrapper.js.map