@capacitor-community/sqlite 3.5.2-dev1 → 3.7.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.
@@ -338,11 +338,16 @@ class UtilsSQLite {
338
338
  const sqlStmts = sqlStmt.split(';');
339
339
  const resArr = [];
340
340
  for (const stmt of sqlStmts) {
341
- const trimStmt = stmt.trim().substring(0, 11).toUpperCase();
341
+ const trimStmt = stmt
342
+ .trim()
343
+ .substring(0, Math.min(stmt.trim().length, 11))
344
+ .toUpperCase();
342
345
  if (trimStmt === 'DELETE FROM' &&
343
346
  stmt.toLowerCase().includes('WHERE'.toLowerCase())) {
344
347
  const whereStmt = `${stmt.trim()};`;
348
+ console.log(`in utilsSQLite execute whereStmt ${whereStmt}`);
345
349
  const rStmt = await this.deleteSQL(mDB, whereStmt, []);
350
+ console.log(`in utilsSQLite execute rStmt ${rStmt}`);
346
351
  resArr.push(rStmt);
347
352
  }
348
353
  else {
@@ -351,12 +356,14 @@ class UtilsSQLite {
351
356
  }
352
357
  sqlStmt = resArr.join(';');
353
358
  }
359
+ console.log(`in utilsSQLite execute sqlStmt ${sqlStmt}`);
354
360
  await this.execDB(mDB, sqlStmt);
355
361
  changes = (await this.dbChanges(mDB)) - initChanges;
356
362
  return Promise.resolve(changes);
357
363
  }
358
364
  catch (err) {
359
- return Promise.reject(`Execute: ${err.message}`);
365
+ const msg = err.message ? err.message : err;
366
+ return Promise.reject(`Execute: ${msg}`);
360
367
  }
361
368
  }
362
369
  /**
@@ -368,7 +375,8 @@ class UtilsSQLite {
368
375
  return new Promise((resolve, reject) => {
369
376
  mDB.exec(sql, async (err) => {
370
377
  if (err) {
371
- reject(`Execute: ${err.message}: `);
378
+ console.log(`in execDB err: ${JSON.stringify(err)}`);
379
+ reject(`Execute: ${err}: `);
372
380
  }
373
381
  resolve();
374
382
  });
@@ -440,9 +448,12 @@ class UtilsSQLite {
440
448
  async runExec(db, stmt, values = []) {
441
449
  return new Promise((resolve, reject) => {
442
450
  if (values != null && values.length > 0) {
451
+ console.log(`in runExec stmt: ${stmt} values: ${values}`);
443
452
  db.run(stmt, values, (err) => {
444
453
  if (err) {
445
- reject(err.message);
454
+ console.log(`in runExec err1: ${JSON.stringify(err)}`);
455
+ const msg = err.message ? err.message : err;
456
+ reject(msg);
446
457
  }
447
458
  else {
448
459
  resolve();
@@ -452,7 +463,9 @@ class UtilsSQLite {
452
463
  else {
453
464
  db.exec(stmt, (err) => {
454
465
  if (err) {
455
- reject(err.message);
466
+ console.log(`in runExec err2: ${JSON.stringify(err)}`);
467
+ const msg = err.message ? err.message : err;
468
+ reject(msg);
456
469
  }
457
470
  else {
458
471
  resolve();
@@ -499,13 +512,14 @@ class UtilsSQLite {
499
512
  .substring('DELETE FROM'.length)
500
513
  .trim();
501
514
  sqlStmt = `UPDATE ${tableName} SET sql_deleted = 1 ${clauseStmt}`;
515
+ console.log(`in deleteSQL sqlStmt: ${sqlStmt}`);
502
516
  // Find REFERENCES if any and update the sql_deleted column
503
517
  await this.findReferencesAndUpdate(db, tableName, clauseStmt, values);
504
518
  }
505
519
  return sqlStmt;
506
520
  }
507
521
  catch (err) {
508
- return Promise.reject(`DeleteSL: ${err}`);
522
+ return Promise.reject(`DeleteSQL: ${err}`);
509
523
  }
510
524
  }
511
525
  /**
@@ -519,27 +533,70 @@ class UtilsSQLite {
519
533
  async findReferencesAndUpdate(db, tableName, whereStmt, values) {
520
534
  try {
521
535
  const references = await this.getReferences(db, tableName);
536
+ if (references.length <= 0) {
537
+ return;
538
+ }
539
+ const tableNameWithRefs = references.pop();
540
+ console.log(`references: ${references}`);
541
+ console.log(`tableNameWithRefs: ${tableNameWithRefs}`);
522
542
  for (const refe of references) {
523
543
  // get the tableName of the reference
524
- const refTable = await this.getReferenceTableName(refe.sql);
544
+ const refTable = await this.getReferenceTableName(refe);
525
545
  if (refTable.length <= 0) {
526
546
  continue;
527
547
  }
528
- // get the columnName
529
- const colName = await this.getReferenceColumnName(refe.sql);
530
- if (colName.length <= 0) {
548
+ console.log(`refTable: ${refTable}`);
549
+ // get the with references columnName
550
+ const withRefsNames = await this.getWithRefsColumnName(refe);
551
+ console.log(`withRefsNames: ${withRefsNames}`);
552
+ if (withRefsNames.length <= 0) {
553
+ continue;
554
+ }
555
+ // get the referenced columnName
556
+ const colNames = await this.getReferencedColumnName(refe);
557
+ console.log(`colNames: ${colNames}`);
558
+ if (colNames.length <= 0) {
531
559
  continue;
532
560
  }
533
561
  // update the where clause
534
- const uWhereStmt = await this.updateWhere(whereStmt, colName);
562
+ const uWhereStmt = await this.updateWhere(whereStmt, withRefsNames, colNames);
563
+ console.log(`whereStmt: ${whereStmt}`);
564
+ console.log(`uWhereStmt: ${uWhereStmt}`);
535
565
  if (uWhereStmt.length <= 0) {
536
566
  continue;
537
567
  }
568
+ let updTableName = tableNameWithRefs;
569
+ let updColNames = colNames;
570
+ if (tableNameWithRefs === tableName) {
571
+ updTableName = refTable;
572
+ updColNames = withRefsNames;
573
+ }
574
+ console.log(`updTableName: ${updTableName}`);
575
+ console.log(`updColNames: ${updColNames}`);
538
576
  //update sql_deleted for this reference
539
- const stmt = `UPDATE ${refTable} SET sql_deleted = 1 ${uWhereStmt}`;
577
+ const stmt = 'UPDATE ' + updTableName + ' SET sql_deleted = 1 ' + uWhereStmt;
578
+ console.log(`stmt: ${stmt}`);
579
+ console.log(`values: ${values}`);
540
580
  if (values != null && values.length > 0) {
541
581
  const mVal = await this.replaceUndefinedByNull(values);
542
- await db.run(stmt, mVal);
582
+ let arrVal = whereStmt.split('?');
583
+ if (arrVal[arrVal.length - 1] === ';')
584
+ arrVal = arrVal.slice(0, -1);
585
+ console.log(`arrVal: ${arrVal}`);
586
+ const selValues = [];
587
+ for (const [j, val] of arrVal.entries()) {
588
+ console.log(`j: ${j} val: ${val}`);
589
+ for (const updVal of updColNames) {
590
+ const idxVal = val.indexOf(updVal);
591
+ console.log(`updVal: ${updVal} idxVal ${idxVal}`);
592
+ if (idxVal > -1) {
593
+ selValues.push(mVal[j]);
594
+ }
595
+ }
596
+ }
597
+ console.log(`*** stmt: ${selValues}`);
598
+ console.log(`*** selValues: ${selValues}`);
599
+ await db.run(stmt, selValues);
543
600
  }
544
601
  else {
545
602
  await db.exec(stmt);
@@ -558,51 +615,120 @@ class UtilsSQLite {
558
615
  }
559
616
  async getReferenceTableName(refValue) {
560
617
  let tableName = '';
561
- if (refValue.length > 0 &&
562
- refValue.substring(0, 12).toLowerCase() === 'CREATE TABLE'.toLowerCase()) {
563
- const oPar = refValue.indexOf('(');
564
- tableName = refValue.substring(13, oPar).trim();
618
+ if (refValue.length > 0) {
619
+ const arr = refValue.split(new RegExp('REFERENCES', 'i'));
620
+ if (arr.length === 2) {
621
+ const oPar = arr[1].indexOf('(');
622
+ tableName = arr[1].substring(0, oPar).trim();
623
+ }
565
624
  }
566
625
  return tableName;
567
626
  }
568
- async getReferenceColumnName(refValue) {
569
- let colName = '';
627
+ async getReferencedColumnName(refValue) {
628
+ let colNames = [];
570
629
  if (refValue.length > 0) {
571
- const index = refValue
572
- .toLowerCase()
573
- .indexOf('FOREIGN KEY'.toLowerCase());
574
- const stmt = refValue.substring(index + 12);
575
- const oPar = stmt.indexOf('(');
576
- const cPar = stmt.indexOf(')');
577
- colName = stmt.substring(oPar + 1, cPar).trim();
630
+ const arr = refValue.split(new RegExp('REFERENCES', 'i'));
631
+ if (arr.length === 2) {
632
+ const oPar = arr[1].indexOf('(');
633
+ const cPar = arr[1].indexOf(')');
634
+ const colStr = arr[1].substring(oPar + 1, cPar).trim();
635
+ colNames = colStr.split(',');
636
+ }
637
+ }
638
+ return colNames;
639
+ }
640
+ async getWithRefsColumnName(refValue) {
641
+ let colNames = [];
642
+ if (refValue.length > 0) {
643
+ const arr = refValue.split(new RegExp('REFERENCES', 'i'));
644
+ if (arr.length === 2) {
645
+ const oPar = arr[0].indexOf('(');
646
+ const cPar = arr[0].indexOf(')');
647
+ const colStr = arr[0].substring(oPar + 1, cPar).trim();
648
+ colNames = colStr.split(',');
649
+ }
578
650
  }
579
- return colName;
651
+ return colNames;
580
652
  }
581
- async updateWhere(whStmt, colName) {
653
+ async updateWhere(whStmt, withRefsNames, colNames) {
582
654
  let whereStmt = '';
583
655
  if (whStmt.length > 0) {
584
656
  const index = whStmt.toLowerCase().indexOf('WHERE'.toLowerCase());
585
657
  const stmt = whStmt.substring(index + 6);
586
- const fEqual = stmt.indexOf('=');
587
- const whereColName = stmt.substring(0, fEqual).trim();
588
- whereStmt = whStmt.replace(whereColName, colName);
658
+ if (withRefsNames.length === colNames.length) {
659
+ for (let i = 0; i < withRefsNames.length; i++) {
660
+ let colType = 'withRefsNames';
661
+ let idx = stmt.indexOf(withRefsNames[i]);
662
+ if (idx === -1) {
663
+ idx = stmt.indexOf(colNames[i]);
664
+ colType = 'colNames';
665
+ }
666
+ if (idx > -1) {
667
+ let valStr = '';
668
+ const fEqual = stmt.indexOf('=', idx);
669
+ if (fEqual > -1) {
670
+ const iAnd = stmt.indexOf('AND', fEqual);
671
+ const ilAnd = stmt.indexOf('and', fEqual);
672
+ if (iAnd > -1) {
673
+ valStr = stmt.substring(fEqual + 1, iAnd - 1).trim();
674
+ }
675
+ else if (ilAnd > -1) {
676
+ valStr = stmt.substring(fEqual + 1, ilAnd - 1).trim();
677
+ }
678
+ else {
679
+ valStr = stmt.substring(fEqual + 1, stmt.length).trim();
680
+ }
681
+ if (i > 0) {
682
+ whereStmt += ' AND ';
683
+ }
684
+ if (colType === 'withRefsNames') {
685
+ whereStmt += `${colNames[i]} = ${valStr}`;
686
+ }
687
+ else {
688
+ whereStmt += `${withRefsNames[i]} = ${valStr}`;
689
+ }
690
+ }
691
+ }
692
+ }
693
+ whereStmt = 'WHERE ' + whereStmt;
694
+ }
589
695
  }
590
696
  return whereStmt;
591
697
  }
592
698
  async getReferences(db, tableName) {
593
699
  const sqlStmt = 'SELECT sql FROM sqlite_master ' +
594
- "WHERE sql LIKE('%REFERENCES%') AND " +
700
+ "WHERE sql LIKE('%FOREIGN KEY%') AND sql LIKE('%REFERENCES%') AND " +
595
701
  "sql LIKE('%" +
596
702
  tableName +
597
703
  "%') AND sql LIKE('%ON DELETE%');";
598
704
  try {
599
705
  const res = await this.queryAll(db, sqlStmt, []);
600
- return Promise.resolve(res);
706
+ // get the reference's string(s)
707
+ let retRefs = [];
708
+ if (res.length > 0) {
709
+ retRefs = await this.getRefs(res[0].sql);
710
+ }
711
+ return Promise.resolve(retRefs);
601
712
  }
602
713
  catch (err) {
603
714
  return Promise.reject(new Error(`getReferences: ${err.message}`));
604
715
  }
605
716
  }
717
+ async getRefs(str) {
718
+ const retRefs = [];
719
+ const arrFor = str.split(new RegExp('FOREIGN KEY', 'i'));
720
+ // Loop through Foreign Keys
721
+ for (let i = 1; i < arrFor.length; i++) {
722
+ retRefs.push(arrFor[i].split(new RegExp('ON DELETE', 'i'))[0].trim());
723
+ }
724
+ // find table name with references
725
+ if (str.substring(0, 12).toLowerCase() === 'CREATE TABLE'.toLowerCase()) {
726
+ const oPar = str.indexOf('(');
727
+ const tableName = str.substring(13, oPar).trim();
728
+ retRefs.push(tableName);
729
+ }
730
+ return retRefs;
731
+ }
606
732
  /**
607
733
  * QueryAll
608
734
  * @param mDB
@@ -3509,7 +3635,7 @@ class Database {
3509
3635
  }
3510
3636
  }
3511
3637
  else {
3512
- throw new Error('No last_modified column in tables');
3638
+ throw new Error('No last_modified/sql_deleted columns in tables');
3513
3639
  }
3514
3640
  }
3515
3641
  else {
@@ -3768,7 +3894,10 @@ class Database {
3768
3894
  inJson.mode = mode;
3769
3895
  this.ensureDatabaseIsOpen();
3770
3896
  try {
3771
- await this.exportToJsonUtil.setLastExportDate(this.database, new Date().toISOString());
3897
+ const isTable = await this.jsonUtil.isTableExists(this.database, this._isDbOpen, 'sync_table');
3898
+ if (isTable) {
3899
+ await this.exportToJsonUtil.setLastExportDate(this.database, new Date().toISOString());
3900
+ }
3772
3901
  const jsonResult = await this.exportToJsonUtil.createExportObject(this.database, inJson);
3773
3902
  const keys = Object.keys(jsonResult);
3774
3903
  if (keys.length === 0) {
@@ -4187,7 +4316,7 @@ class CapacitorSQLite {
4187
4316
  return;
4188
4317
  }
4189
4318
  else {
4190
- throw new Error('CopyFromAssets: assets/databases folder does not exist');
4319
+ throw new Error(`CopyFromAssets: assets/databases folder does not exist:[${assetsDbPath}]`);
4191
4320
  }
4192
4321
  }
4193
4322
  async getDatabaseList() {
@@ -4199,7 +4328,7 @@ class CapacitorSQLite {
4199
4328
  return { values: files };
4200
4329
  }
4201
4330
  else {
4202
- throw new Error(`isTableExists: No databases found`);
4331
+ throw new Error(`isTableExists: No databases found in [${pathDatabase}]`);
4203
4332
  }
4204
4333
  }
4205
4334
  async checkConnectionsConsistency(options) {
@@ -4322,6 +4451,10 @@ class CapacitorSQLite {
4322
4451
  console.log(`${JSON.stringify(options)}`);
4323
4452
  throw new Error('Method not implemented.');
4324
4453
  }
4454
+ async moveDatabasesAndAddSuffix(options) {
4455
+ console.log(`${JSON.stringify(options)}`);
4456
+ throw new Error('Method not implemented.');
4457
+ }
4325
4458
  async getUrl() {
4326
4459
  throw new Error('Method not implemented.');
4327
4460
  }