@capacitor-community/sqlite 5.0.7-1 → 5.0.7-2

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.
@@ -9,9 +9,9 @@ var require$$3 = require('node-fetch');
9
9
  var require$$4 = require('os');
10
10
  var require$$5 = require('jszip');
11
11
  var require$$6 = require('electron');
12
- var require$$1$1 = require('better-sqlite3-multiple-ciphers');
13
- var require$$3$1 = require('electron-json-storage');
14
- var require$$1$2 = require('crypto');
12
+ var require$$3$1 = require('better-sqlite3-multiple-ciphers');
13
+ var require$$3$2 = require('electron-json-storage');
14
+ var require$$1$1 = require('crypto');
15
15
  var require$$2$1 = require('crypto-js');
16
16
 
17
17
  function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
@@ -23,9 +23,9 @@ var require$$3__default = /*#__PURE__*/_interopDefaultLegacy(require$$3);
23
23
  var require$$4__default = /*#__PURE__*/_interopDefaultLegacy(require$$4);
24
24
  var require$$5__default = /*#__PURE__*/_interopDefaultLegacy(require$$5);
25
25
  var require$$6__default = /*#__PURE__*/_interopDefaultLegacy(require$$6);
26
- var require$$1__default$1 = /*#__PURE__*/_interopDefaultLegacy(require$$1$1);
27
26
  var require$$3__default$1 = /*#__PURE__*/_interopDefaultLegacy(require$$3$1);
28
- var require$$1__default$2 = /*#__PURE__*/_interopDefaultLegacy(require$$1$2);
27
+ var require$$3__default$2 = /*#__PURE__*/_interopDefaultLegacy(require$$3$2);
28
+ var require$$1__default$1 = /*#__PURE__*/_interopDefaultLegacy(require$$1$1);
29
29
  var require$$2__default$1 = /*#__PURE__*/_interopDefaultLegacy(require$$2$1);
30
30
 
31
31
  var src = {};
@@ -48,6 +48,131 @@ var exportToJson = {};
48
48
 
49
49
  var utilsSQLite = {};
50
50
 
51
+ var utilsDelete = {};
52
+
53
+ Object.defineProperty(utilsDelete, "__esModule", { value: true });
54
+ utilsDelete.UtilsDelete = void 0;
55
+ class UtilsDeleteError {
56
+ constructor(message) {
57
+ this.message = message;
58
+ }
59
+ static upDateWhereForDefault(message) {
60
+ return new UtilsDeleteError(message);
61
+ }
62
+ static upDateWhereForRestrict(message) {
63
+ return new UtilsDeleteError(message);
64
+ }
65
+ static upDateWhereForCascade(message) {
66
+ return new UtilsDeleteError(message);
67
+ }
68
+ static executeUpdateForDelete(message) {
69
+ return new UtilsDeleteError(message);
70
+ }
71
+ }
72
+ class UtilsDelete {
73
+ getReferencedTableName(refValue) {
74
+ let tableName = '';
75
+ if (refValue.length > 0) {
76
+ const arr = refValue.split(new RegExp('REFERENCES', 'i'));
77
+ if (arr.length === 2) {
78
+ const oPar = arr[1].indexOf("(");
79
+ tableName = arr[1].substring(0, oPar).trim();
80
+ }
81
+ }
82
+ return tableName;
83
+ }
84
+ upDateWhereForDefault(withRefsNames, results) {
85
+ let setStmt = '';
86
+ let uWhereStmt = '';
87
+ try {
88
+ const key = results.key;
89
+ const cols = [];
90
+ for (const relItem of results.relatedItems) {
91
+ const mVal = relItem[key];
92
+ if (mVal !== undefined) {
93
+ cols.push(mVal);
94
+ }
95
+ }
96
+ // Create the set statement
97
+ for (const name of withRefsNames) {
98
+ setStmt += `${name} = NULL, `;
99
+ }
100
+ setStmt += 'sql_deleted = 0';
101
+ // Create the where statement
102
+ uWhereStmt = `WHERE ${key} IN (`;
103
+ for (const col of cols) {
104
+ uWhereStmt += `${col},`;
105
+ }
106
+ if (uWhereStmt.endsWith(',')) {
107
+ uWhereStmt = uWhereStmt.slice(0, -1);
108
+ }
109
+ uWhereStmt += ');';
110
+ }
111
+ catch (error) {
112
+ const msg = error.message ? error.message : error;
113
+ throw UtilsDeleteError.upDateWhereForDefault(msg);
114
+ }
115
+ return { setStmt, uWhereStmt };
116
+ }
117
+ upDateWhereForRestrict(results) {
118
+ try {
119
+ const setStmt = '';
120
+ const uWhereStmt = '';
121
+ if (results.relatedItems.length > 0) {
122
+ const msg = 'Restrict mode related items exist, please delete them first';
123
+ throw UtilsDeleteError.upDateWhereForRestrict(msg);
124
+ }
125
+ return { setStmt, uWhereStmt };
126
+ }
127
+ catch (error) {
128
+ const msg = error.message ? error.message : error;
129
+ throw UtilsDeleteError.upDateWhereForRestrict(msg);
130
+ }
131
+ }
132
+ upDateWhereForCascade(results) {
133
+ let setStmt = '';
134
+ let uWhereStmt = '';
135
+ try {
136
+ const key = results.key;
137
+ const cols = [];
138
+ for (const relItem of results.relatedItems) {
139
+ const mVal = relItem[key];
140
+ if (mVal !== undefined) {
141
+ cols.push(mVal);
142
+ }
143
+ }
144
+ setStmt += 'sql_deleted = 1';
145
+ // Create the where statement
146
+ uWhereStmt = `WHERE ${key} IN (`;
147
+ for (const col of cols) {
148
+ uWhereStmt += `${col},`;
149
+ }
150
+ if (uWhereStmt.endsWith(',')) {
151
+ uWhereStmt = uWhereStmt.slice(0, -1);
152
+ }
153
+ uWhereStmt += ');';
154
+ }
155
+ catch (error) {
156
+ const msg = error.message ? error.message : error;
157
+ throw UtilsDeleteError.upDateWhereForCascade(msg);
158
+ }
159
+ return { setStmt, uWhereStmt };
160
+ }
161
+ getCurrentTimeAsInteger() {
162
+ const currentTime = Math.floor(Date.now() / 1000);
163
+ return currentTime;
164
+ }
165
+ checkValuesMatch(array1, array2) {
166
+ for (const value of array1) {
167
+ if (!array2.includes(value)) {
168
+ return false;
169
+ }
170
+ }
171
+ return true;
172
+ }
173
+ }
174
+ utilsDelete.UtilsDelete = UtilsDelete;
175
+
51
176
  var utilsFile = {};
52
177
 
53
178
  Object.defineProperty(utilsFile, "__esModule", { value: true });
@@ -653,14 +778,259 @@ class UtilsFile {
653
778
  }
654
779
  utilsFile.UtilsFile = UtilsFile;
655
780
 
781
+ var utilsSqlstatement = {};
782
+
783
+ Object.defineProperty(utilsSqlstatement, "__esModule", { value: true });
784
+ utilsSqlstatement.UtilsSQLStatement = void 0;
785
+ class UtilsSQLStatement {
786
+ constructor() {
787
+ this.replaceString = (originalStr, searchStr, replaceStr) => {
788
+ const range = originalStr.indexOf(searchStr);
789
+ if (range !== -1) {
790
+ const modifiedStr = originalStr.substring(0, range) + replaceStr + originalStr.substring(range + searchStr.length);
791
+ return modifiedStr;
792
+ }
793
+ return originalStr;
794
+ };
795
+ }
796
+ extractTableName(statement) {
797
+ const pattern = /(?:INSERT\s+INTO|UPDATE|DELETE\s+FROM)\s+([^\s]+)/i;
798
+ const match = statement.match(pattern);
799
+ if (match?.[1]) {
800
+ const tableName = match[1];
801
+ return tableName;
802
+ }
803
+ return null;
804
+ }
805
+ extractWhereClause(statement) {
806
+ const pattern = /WHERE(.+?)(?:ORDER\s+BY|LIMIT|$)/i;
807
+ const match = statement.match(pattern);
808
+ if (match?.[1]) {
809
+ const whereClause = match[1].trim();
810
+ return whereClause;
811
+ }
812
+ return null;
813
+ }
814
+ addPrefixToWhereClause(whereClause, colNames, refNames, prefix) {
815
+ let columnValuePairs;
816
+ if (whereClause.includes("AND")) {
817
+ // Split the WHERE clause based on the "AND" keyword
818
+ const subSequenceArray = whereClause.split("AND");
819
+ console.log(" whereClause", whereClause);
820
+ console.log(" subSequenceArray", subSequenceArray);
821
+ columnValuePairs = subSequenceArray.map((pair) => pair.trim());
822
+ }
823
+ else {
824
+ columnValuePairs = [whereClause];
825
+ }
826
+ console.log(" columnValuePairs", columnValuePairs);
827
+ const modifiedPairs = columnValuePairs.map((pair) => {
828
+ const match = pair.match(/(\w+)\s*(=|IN|BETWEEN|LIKE)\s*(.+)/);
829
+ if (!match) {
830
+ return pair;
831
+ }
832
+ const column = match[1].trim();
833
+ const operator = match[2].trim();
834
+ const value = match[3].trim();
835
+ let newColumn = column;
836
+ const index = this.findIndexOfStringInArray(column, refNames);
837
+ if (index !== -1) {
838
+ newColumn = this.getStringAtIndex(colNames, index);
839
+ }
840
+ const modifiedColumn = `${prefix}${newColumn}`;
841
+ const ret = `${modifiedColumn} ${operator} ${value}`;
842
+ return ret;
843
+ });
844
+ return modifiedPairs.join(" AND ");
845
+ }
846
+ findIndexOfStringInArray(target, array) {
847
+ return array.indexOf(target);
848
+ }
849
+ getStringAtIndex(array, index) {
850
+ if (index >= 0 && index < array.length) {
851
+ return array[index];
852
+ }
853
+ else {
854
+ return undefined;
855
+ }
856
+ }
857
+ extractForeignKeyInfo(sqlStatement) {
858
+ // Define the regular expression pattern for extracting the FOREIGN KEY clause
859
+ const foreignKeyPattern = /\bFOREIGN\s+KEY\s*\(([^)]+)\)\s+REFERENCES\s+(\w+)\s*\(([^)]+)\)\s+(ON\s+DELETE\s+(RESTRICT|CASCADE|SET\s+NULL|SET\s+DEFAULT|NO\s+ACTION))?/;
860
+ const matches = sqlStatement.match(foreignKeyPattern);
861
+ if (matches) {
862
+ const foreignKeyInfo = {
863
+ forKeys: matches[1].split(",").map(key => key.trim()),
864
+ tableName: matches[2],
865
+ refKeys: matches[3].split(",").map(key => key.trim()),
866
+ action: matches[5] ? matches[5] : "NO ACTION"
867
+ };
868
+ return foreignKeyInfo;
869
+ }
870
+ else {
871
+ throw new Error("extractForeignKeyInfo: No FOREIGN KEY found");
872
+ }
873
+ }
874
+ extractColumnNames(whereClause) {
875
+ const regex = /\b(\w+)\s*(?=[=<>])|(?<=\()\s*(\w+),\s*(\w+)\s*(?=\))|(?<=\bIN\s*\(VALUES\s*\().*?(?=\))|(?<=\bIN\s*\().*?(?=\))|(?<=\bBETWEEN\s*).*?(?=\bAND\b)|(?<=\bLIKE\s*')\w+|\bAND\b/g;
876
+ const matches = whereClause.matchAll(regex);
877
+ const columnNames = [];
878
+ let andGroup = [];
879
+ for (const match of matches) {
880
+ if (match[0] === 'AND') {
881
+ columnNames.push(...andGroup);
882
+ andGroup = [];
883
+ }
884
+ else if (match[1]) {
885
+ andGroup.push(match[1]);
886
+ }
887
+ else if (match[2] && match[3]) {
888
+ andGroup.push(match[2]);
889
+ andGroup.push(match[3]);
890
+ }
891
+ else if (match[0]) {
892
+ const values = match[0]
893
+ .replace(/[()']/g, '') // Remove parentheses and single quotes
894
+ .split(',')
895
+ .map(value => value.trim());
896
+ andGroup.push(...values);
897
+ }
898
+ }
899
+ columnNames.push(...andGroup);
900
+ return columnNames;
901
+ }
902
+ flattenMultilineString(input) {
903
+ const lines = input.split(/\r?\n/);
904
+ return lines.join(" ");
905
+ }
906
+ getStmtAndRetColNames(sqlStmt, retMode) {
907
+ const retWord = "RETURNING";
908
+ const retStmtNames = { stmt: sqlStmt, names: "" };
909
+ const retWordIndex = sqlStmt.toUpperCase().indexOf(retWord);
910
+ if (retWordIndex !== -1) {
911
+ const prefix = sqlStmt.substring(0, retWordIndex);
912
+ retStmtNames.stmt = `${prefix};`;
913
+ if (retMode.substring(0, 2) === "wA") {
914
+ const suffix = sqlStmt.substring(retWordIndex + retWord.length);
915
+ const names = suffix.trim();
916
+ if (names.endsWith(";")) {
917
+ retStmtNames.names = names.substring(0, names.length - 1);
918
+ }
919
+ else {
920
+ retStmtNames.names = names;
921
+ }
922
+ }
923
+ }
924
+ return retStmtNames;
925
+ }
926
+ extractCombinedPrimaryKey(whereClause) {
927
+ const pattern = /WHERE\s*\((.+?)\)\s*(?:=|IN)\s*\((.+?)\)/g;
928
+ const regex = new RegExp(pattern);
929
+ const matches = whereClause.matchAll(regex);
930
+ const primaryKeySets = [];
931
+ for (const match of matches) {
932
+ const keysString = match[1].trim();
933
+ const keys = keysString.split(",").map((key) => key.trim());
934
+ primaryKeySets.push(keys);
935
+ }
936
+ return primaryKeySets.length === 0 ? null : primaryKeySets;
937
+ }
938
+ getWhereStmtForCombinedPK(whStmt, withRefs, colNames, keys) {
939
+ let retWhere = whStmt;
940
+ for (const grpKeys of keys) {
941
+ const repKeys = grpKeys.join(",") === withRefs.join(",") ? colNames : withRefs;
942
+ for (const [index, key] of grpKeys.entries()) {
943
+ retWhere = this.replaceAllString(retWhere, key, repKeys[index]);
944
+ }
945
+ }
946
+ return retWhere;
947
+ }
948
+ replaceAllString(originalStr, searchStr, replaceStr) {
949
+ return originalStr.split(searchStr).join(replaceStr);
950
+ }
951
+ indicesOf(str, searchStr, fromIndex = 0) {
952
+ // Helper function to find indices of a substring within a string
953
+ const indices = [];
954
+ let currentIndex = str.indexOf(searchStr, fromIndex);
955
+ while (currentIndex !== -1) {
956
+ indices.push(currentIndex);
957
+ currentIndex = str.indexOf(searchStr, currentIndex + 1);
958
+ }
959
+ return indices;
960
+ }
961
+ getWhereStmtForNonCombinedPK(whStmt, withRefs, colNames) {
962
+ let whereStmt = "";
963
+ let stmt = whStmt.substring(6);
964
+ for (let idx = 0; idx < withRefs.length; idx++) {
965
+ let colType = "withRefsNames";
966
+ let idxs = this.indicesOf(stmt, withRefs[idx]);
967
+ if (idxs.length === 0) {
968
+ idxs = this.indicesOf(stmt, colNames[idx]);
969
+ colType = "colNames";
970
+ }
971
+ if (idxs.length > 0) {
972
+ let valStr = "";
973
+ const indicesEqual = this.indicesOf(stmt, "=", idxs[0]);
974
+ if (indicesEqual.length > 0) {
975
+ const indicesAnd = this.indicesOf(stmt, "AND", indicesEqual[0]);
976
+ if (indicesAnd.length > 0) {
977
+ valStr = stmt.substring(indicesEqual[0] + 1, indicesAnd[0] - 1);
978
+ stmt = stmt.substring(indicesAnd[0] + 3);
979
+ }
980
+ else {
981
+ valStr = stmt.substring(indicesEqual[0] + 1);
982
+ }
983
+ if (idx > 0) {
984
+ whereStmt += " AND ";
985
+ }
986
+ if (colType === "withRefsNames") {
987
+ whereStmt += colNames[idx] + " = " + valStr;
988
+ }
989
+ else {
990
+ whereStmt += withRefs[idx] + " = " + valStr;
991
+ }
992
+ }
993
+ }
994
+ }
995
+ whereStmt = "WHERE " + whereStmt;
996
+ return whereStmt;
997
+ }
998
+ updateWhere(whStmt, withRefs, colNames) {
999
+ let whereStmt = "";
1000
+ if (whStmt.length <= 0) {
1001
+ return whereStmt;
1002
+ }
1003
+ if (whStmt.toUpperCase().substring(0, 5) !== "WHERE") {
1004
+ return whereStmt;
1005
+ }
1006
+ if (withRefs.length === colNames.length) {
1007
+ // get whereStmt for primary combined key
1008
+ const keys = this.extractCombinedPrimaryKey(whStmt);
1009
+ if (keys) {
1010
+ whereStmt = this.getWhereStmtForCombinedPK(whStmt, withRefs, colNames, keys);
1011
+ }
1012
+ else {
1013
+ // get for non primary combined key
1014
+ whereStmt = this.getWhereStmtForNonCombinedPK(whStmt, withRefs, colNames);
1015
+ }
1016
+ }
1017
+ return whereStmt;
1018
+ }
1019
+ }
1020
+ utilsSqlstatement.UtilsSQLStatement = UtilsSQLStatement;
1021
+
656
1022
  Object.defineProperty(utilsSQLite, "__esModule", { value: true });
657
1023
  utilsSQLite.UtilsSQLite = void 0;
1024
+ const utilsDelete_1 = utilsDelete;
658
1025
  const utilsFile_1$4 = utilsFile;
1026
+ const utilsSqlstatement_1 = utilsSqlstatement;
659
1027
  //const SQLITE_OPEN_READONLY = 1;
660
1028
  class UtilsSQLite {
661
1029
  constructor() {
662
1030
  this.fileUtil = new utilsFile_1$4.UtilsFile();
663
- this.BCSQLite3 = require$$1__default$1["default"];
1031
+ this.statUtil = new utilsSqlstatement_1.UtilsSQLStatement();
1032
+ this.delUtil = new utilsDelete_1.UtilsDelete();
1033
+ this.BCSQLite3 = require$$3__default$1["default"];
664
1034
  }
665
1035
  /**
666
1036
  * OpenOrCreateDatabase
@@ -1229,17 +1599,39 @@ class UtilsSQLite {
1229
1599
  try {
1230
1600
  const isLast = this.isLastModified(mDB, true);
1231
1601
  const isDel = this.isSqlDeleted(mDB, true);
1232
- if (isLast && isDel) {
1233
- // Replace DELETE by UPDATE and set sql_deleted to 1
1234
- const wIdx = statement.toUpperCase().indexOf('WHERE');
1235
- const preStmt = statement.substring(0, wIdx - 1);
1236
- const clauseStmt = statement.substring(wIdx, statement.length);
1237
- const tableName = preStmt
1238
- .substring('DELETE FROM'.length)
1239
- .trim();
1240
- sqlStmt = `UPDATE ${tableName} SET sql_deleted = 1 ${clauseStmt}`;
1241
- // Find REFERENCES if any and update the sql_deleted column
1242
- this.findReferencesAndUpdate(mDB, tableName, clauseStmt, values);
1602
+ if (!isLast || !isDel) {
1603
+ return sqlStmt;
1604
+ }
1605
+ // Replace DELETE by UPDATE
1606
+ // set sql_deleted to 1 and the last_modified to
1607
+ // timenow
1608
+ const whereClause = this.statUtil.extractWhereClause(sqlStmt);
1609
+ if (!whereClause) {
1610
+ const msg = 'deleteSQL: cannot find a WHERE clause';
1611
+ throw new Error(`${msg}`);
1612
+ }
1613
+ const tableName = this.statUtil.extractTableName(sqlStmt);
1614
+ if (!tableName) {
1615
+ const msg = 'deleteSQL: cannot find a WHERE clause';
1616
+ throw new Error(`${msg}`);
1617
+ }
1618
+ const colNames = this.statUtil.extractColumnNames(whereClause);
1619
+ if (colNames.length === 0) {
1620
+ const msg = 'deleteSQL: Did not find column names in the WHERE Statement';
1621
+ throw new Error(`${msg}`);
1622
+ }
1623
+ const setStmt = 'sql_deleted = 1';
1624
+ // Find REFERENCES if any and update the sql_deleted
1625
+ // column
1626
+ const hasToUpdate = this.findReferencesAndUpdate(mDB, tableName, whereClause, colNames, values);
1627
+ if (hasToUpdate) {
1628
+ const whereStmt = whereClause.endsWith(';')
1629
+ ? whereClause.slice(0, -1)
1630
+ : whereClause;
1631
+ sqlStmt = `UPDATE ${tableName} SET ${setStmt} WHERE ${whereStmt} AND sql_deleted = 0;`;
1632
+ }
1633
+ else {
1634
+ sqlStmt = '';
1243
1635
  }
1244
1636
  return sqlStmt;
1245
1637
  }
@@ -1253,192 +1645,183 @@ class UtilsSQLite {
1253
1645
  * @param mDB
1254
1646
  * @param tableName
1255
1647
  * @param whereStmt
1648
+ * @param initColNames
1256
1649
  * @param values
1257
1650
  * @returns
1258
1651
  */
1259
- findReferencesAndUpdate(mDB, tableName, whereStmt, values) {
1260
- const msg = 'FindReferencesAndUpdate';
1652
+ findReferencesAndUpdate(mDB, tableName, whereStmt, initColNames, values) {
1261
1653
  try {
1262
- const references = this.getReferences(mDB, tableName);
1654
+ const retBool = true;
1655
+ const result = this.getReferences(mDB, tableName);
1656
+ const references = result.retRefs;
1657
+ const tableNameWithRefs = result.tableWithRefs;
1263
1658
  if (references.length <= 0) {
1264
- return;
1265
- }
1266
- const tableNameWithRefs = references.pop();
1267
- for (const refe of references) {
1268
- // get the tableName of the reference
1269
- const refTable = this.getReferenceTableName(refe);
1270
- if (refTable.length <= 0) {
1271
- continue;
1272
- }
1273
- // get the with references columnName
1274
- const withRefsNames = this.getWithRefsColumnName(refe);
1275
- if (withRefsNames.length <= 0) {
1659
+ return retBool;
1660
+ }
1661
+ if (tableName === tableNameWithRefs) {
1662
+ return retBool;
1663
+ }
1664
+ // Loop through references
1665
+ for (const ref of references) {
1666
+ // Extract the FOREIGN KEY constraint info from the ref statement
1667
+ const foreignKeyInfo = this.statUtil.extractForeignKeyInfo(ref);
1668
+ // Get the tableName of the references
1669
+ const refTable = foreignKeyInfo.tableName;
1670
+ if (refTable === '' || refTable !== tableName) {
1276
1671
  continue;
1277
1672
  }
1278
- // get the referenced columnName
1279
- const colNames = this.getReferencedColumnName(refe);
1280
- if (colNames.length <= 0) {
1281
- continue;
1673
+ // Get the with ref column names
1674
+ const withRefsNames = foreignKeyInfo.forKeys;
1675
+ // Get the column names
1676
+ const colNames = foreignKeyInfo.refKeys;
1677
+ if (colNames.length !== withRefsNames.length) {
1678
+ const msg = "findReferencesAndUpdate: mismatch length";
1679
+ throw new Error(msg);
1282
1680
  }
1283
- // update the where clause
1284
- const uWhereStmt = this.updateWhere(whereStmt, withRefsNames, colNames);
1285
- if (uWhereStmt.length <= 0) {
1681
+ const action = foreignKeyInfo.action;
1682
+ if (action === 'NO_ACTION') {
1286
1683
  continue;
1287
1684
  }
1288
- let updTableName = tableNameWithRefs;
1289
- let updColNames = colNames;
1290
- if (tableNameWithRefs === tableName) {
1291
- updTableName = refTable;
1292
- updColNames = withRefsNames;
1293
- }
1294
- //update sql_deleted for this reference
1295
- const stmt = 'UPDATE ' + updTableName + ' SET sql_deleted = 1 ' + uWhereStmt;
1296
- const selValues = [];
1297
- if (values.length > 0) {
1298
- const mVal = this.replaceUndefinedByNull(values);
1299
- let arrVal = whereStmt.split('?');
1300
- if (arrVal[arrVal.length - 1] === ';')
1301
- arrVal = arrVal.slice(0, -1);
1302
- for (const [j, val] of arrVal.entries()) {
1303
- for (const updVal of updColNames) {
1304
- const idxVal = val.indexOf(updVal);
1305
- if (idxVal > -1) {
1306
- selValues.push(mVal[j]);
1307
- }
1685
+ const updTableName = tableNameWithRefs;
1686
+ const updColNames = withRefsNames;
1687
+ let results = {
1688
+ uWhereStmt: '',
1689
+ setStmt: '',
1690
+ };
1691
+ if (!this.delUtil.checkValuesMatch(withRefsNames, initColNames)) {
1692
+ // Case: no match
1693
+ // Search for related items in tableName
1694
+ const result = this.searchForRelatedItems(mDB, updTableName, tableName, whereStmt, withRefsNames, colNames, values);
1695
+ if (result.relatedItems.length === 0 && result.key.length <= 0) {
1696
+ continue;
1697
+ }
1698
+ if (updTableName !== tableName) {
1699
+ switch (action) {
1700
+ case 'RESTRICT':
1701
+ results = this.delUtil.upDateWhereForRestrict(result);
1702
+ break;
1703
+ case 'CASCADE':
1704
+ results = this.delUtil.upDateWhereForCascade(result);
1705
+ break;
1706
+ default:
1707
+ results = this.delUtil.upDateWhereForDefault(withRefsNames, result);
1708
+ break;
1308
1709
  }
1309
1710
  }
1310
1711
  }
1311
- const ret = this.runExec(mDB, stmt, selValues, 'no');
1312
- const lastId = ret.lastInsertRowid;
1313
- if (lastId == -1) {
1314
- const msg = `UPDATE sql_deleted failed for references table: ${refTable}`;
1315
- throw new Error(`findReferencesAndUpdate: ${msg}`);
1712
+ else {
1713
+ throw new Error('Not implemented. Please transfer your example to the maintener');
1714
+ }
1715
+ if (results.setStmt.length > 0 &&
1716
+ results.uWhereStmt.length > 0) {
1717
+ this.executeUpdateForDelete(mDB, updTableName, results.uWhereStmt, results.setStmt, updColNames, values);
1316
1718
  }
1317
1719
  }
1318
- return;
1720
+ return retBool;
1319
1721
  }
1320
- catch (err) {
1321
- const errmsg = err.message ? err.message : err;
1322
- throw new Error(`${msg} ${errmsg}`);
1722
+ catch (error) {
1723
+ const msg = error.message ? error.message : error;
1724
+ throw new Error(msg);
1323
1725
  }
1324
1726
  }
1325
- getReferenceTableName(refValue) {
1326
- let tableName = '';
1327
- if (refValue.length > 0) {
1328
- const arr = refValue.split(new RegExp('REFERENCES', 'i'));
1329
- if (arr.length === 2) {
1330
- const oPar = arr[1].indexOf('(');
1331
- tableName = arr[1].substring(0, oPar).trim();
1727
+ /**
1728
+ * getReferences
1729
+ * @param db
1730
+ * @param tableName
1731
+ * @returns
1732
+ */
1733
+ getReferences(db, tableName) {
1734
+ const sqlStmt = "SELECT sql FROM sqlite_master " +
1735
+ "WHERE sql LIKE('%FOREIGN KEY%') AND sql LIKE('%REFERENCES%') AND " +
1736
+ "sql LIKE('%" + tableName + "%') AND sql LIKE('%ON DELETE%');";
1737
+ try {
1738
+ const res = this.queryAll(db, sqlStmt, []);
1739
+ // get the reference's string(s)
1740
+ let retRefs = [];
1741
+ let tableWithRefs = "";
1742
+ if (res.length > 0) {
1743
+ const result = this.getRefs(res[0].sql);
1744
+ retRefs = result.foreignKeys;
1745
+ tableWithRefs = result.tableName;
1332
1746
  }
1747
+ return { tableWithRefs: tableWithRefs, retRefs: retRefs };
1748
+ }
1749
+ catch (err) {
1750
+ const error = err.message ? err.message : err;
1751
+ const msg = `getReferences: ${error}`;
1752
+ throw new Error(msg);
1333
1753
  }
1334
- return tableName;
1335
1754
  }
1336
- getReferencedColumnName(refValue) {
1337
- let colNames = [];
1338
- if (refValue.length > 0) {
1339
- const arr = refValue.split(new RegExp('REFERENCES', 'i'));
1340
- if (arr.length === 2) {
1341
- const oPar = arr[1].indexOf('(');
1342
- const cPar = arr[1].indexOf(')');
1343
- const colStr = arr[1].substring(oPar + 1, cPar).trim();
1344
- colNames = colStr.split(',');
1755
+ /**
1756
+ * getRefs
1757
+ * @param sqlStatement
1758
+ * @returns
1759
+ */
1760
+ getRefs(sqlStatement) {
1761
+ let tableName = '';
1762
+ const foreignKeys = [];
1763
+ const statement = this.statUtil.flattenMultilineString(sqlStatement);
1764
+ try {
1765
+ // Regular expression pattern to match the table name
1766
+ const tableNamePattern = /CREATE\s+TABLE\s+(\w+)\s+\(/;
1767
+ const tableNameMatch = statement.match(tableNamePattern);
1768
+ if (tableNameMatch) {
1769
+ tableName = tableNameMatch[1];
1345
1770
  }
1771
+ // Regular expression pattern to match the FOREIGN KEY constraints
1772
+ const foreignKeyPattern = /FOREIGN\s+KEY\s+\([^)]+\)\s+REFERENCES\s+(\w+)\s*\([^)]+\)\s+ON\s+DELETE\s+(CASCADE|RESTRICT|SET\s+DEFAULT|SET\s+NULL|NO\s+ACTION)/g;
1773
+ const foreignKeyMatches = statement.matchAll(foreignKeyPattern);
1774
+ for (const foreignKeyMatch of foreignKeyMatches) {
1775
+ const foreignKey = foreignKeyMatch[0];
1776
+ foreignKeys.push(foreignKey);
1777
+ }
1778
+ }
1779
+ catch (error) {
1780
+ const msg = `getRefs: Error creating regular expression: ${error}`;
1781
+ throw new Error(msg);
1346
1782
  }
1347
- return colNames;
1783
+ return { tableName, foreignKeys };
1348
1784
  }
1349
- getWithRefsColumnName(refValue) {
1350
- let colNames = [];
1351
- if (refValue.length > 0) {
1352
- const arr = refValue.split(new RegExp('REFERENCES', 'i'));
1353
- if (arr.length === 2) {
1354
- const oPar = arr[0].indexOf('(');
1355
- const cPar = arr[0].indexOf(')');
1356
- const colStr = arr[0].substring(oPar + 1, cPar).trim();
1357
- colNames = colStr.split(',');
1358
- }
1359
- }
1360
- return colNames;
1361
- }
1362
- updateWhere(whStmt, withRefsNames, colNames) {
1363
- let whereStmt = '';
1364
- if (whStmt.length > 0) {
1365
- const index = whStmt.toLowerCase().indexOf('WHERE'.toLowerCase());
1366
- const stmt = whStmt.substring(index + 6);
1367
- if (withRefsNames.length === colNames.length) {
1368
- for (let i = 0; i < withRefsNames.length; i++) {
1369
- let colType = 'withRefsNames';
1370
- let idx = stmt.indexOf(withRefsNames[i]);
1371
- if (idx === -1) {
1372
- idx = stmt.indexOf(colNames[i]);
1373
- colType = 'colNames';
1374
- }
1375
- if (idx > -1) {
1376
- let valStr = '';
1377
- const fEqual = stmt.indexOf('=', idx);
1378
- if (fEqual > -1) {
1379
- const iAnd = stmt.indexOf('AND', fEqual);
1380
- const ilAnd = stmt.indexOf('and', fEqual);
1381
- if (iAnd > -1) {
1382
- valStr = stmt.substring(fEqual + 1, iAnd - 1).trim();
1383
- }
1384
- else if (ilAnd > -1) {
1385
- valStr = stmt.substring(fEqual + 1, ilAnd - 1).trim();
1386
- }
1387
- else {
1388
- valStr = stmt.substring(fEqual + 1, stmt.length).trim();
1389
- }
1390
- if (i > 0) {
1391
- whereStmt += ' AND ';
1392
- }
1393
- if (colType === 'withRefsNames') {
1394
- whereStmt += `${colNames[i]} = ${valStr}`;
1395
- }
1396
- else {
1397
- whereStmt += `${withRefsNames[i]} = ${valStr}`;
1398
- }
1785
+ /**
1786
+ * executeUpdateForDelete
1787
+ * @param mDB
1788
+ * @param tableName
1789
+ * @param whereStmt
1790
+ * @param setStmt
1791
+ * @param colNames
1792
+ * @param values
1793
+ */
1794
+ executeUpdateForDelete(mDB, tableName, whereStmt, setStmt, colNames, values) {
1795
+ try {
1796
+ let lastId = -1;
1797
+ // Update sql_deleted for this references
1798
+ const stmt = `UPDATE ${tableName} SET ${setStmt} ${whereStmt}`;
1799
+ const selValues = [];
1800
+ if (values.length > 0) {
1801
+ const arrVal = whereStmt.split('?');
1802
+ if (arrVal[arrVal.length - 1] === ';') {
1803
+ arrVal.pop();
1804
+ }
1805
+ for (let jdx = 0; jdx < arrVal.length; jdx++) {
1806
+ for (const updVal of colNames) {
1807
+ const indices = this.statUtil.indicesOf(arrVal[jdx], updVal);
1808
+ if (indices.length > 0) {
1809
+ selValues.push(values[jdx]);
1399
1810
  }
1400
1811
  }
1401
1812
  }
1402
- whereStmt = 'WHERE ' + whereStmt;
1403
1813
  }
1404
- }
1405
- return whereStmt;
1406
- }
1407
- getReferences(mDB, tableName) {
1408
- const msg = 'GetReferences';
1409
- const sqlStmt = 'SELECT sql FROM sqlite_master ' +
1410
- "WHERE sql LIKE('%FOREIGN KEY%') AND sql LIKE('%REFERENCES%') AND " +
1411
- "sql LIKE('%" +
1412
- tableName +
1413
- "%') AND sql LIKE('%ON DELETE%');";
1414
- try {
1415
- const res = this.queryAll(mDB, sqlStmt, []);
1416
- // get the reference's string(s)
1417
- let retRefs = [];
1418
- if (res.length > 0) {
1419
- retRefs = this.getRefs(res[0].sql);
1814
+ const retObj = this.runExec(mDB, stmt, selValues, 'no');
1815
+ lastId = retObj["lastInsertRowid"];
1816
+ if (lastId === -1) {
1817
+ const msg = `UPDATE sql_deleted failed for table: ${tableName}`;
1818
+ throw new Error(msg);
1420
1819
  }
1421
- return retRefs;
1422
- }
1423
- catch (err) {
1424
- const errmsg = err.message ? err.message : err;
1425
- throw new Error(`${msg} ${errmsg}`);
1426
- }
1427
- }
1428
- getRefs(str) {
1429
- const retRefs = [];
1430
- const arrFor = str.split(new RegExp('FOREIGN KEY', 'i'));
1431
- // Loop through Foreign Keys
1432
- for (let i = 1; i < arrFor.length; i++) {
1433
- retRefs.push(arrFor[i].split(new RegExp('ON DELETE', 'i'))[0].trim());
1434
1820
  }
1435
- // find table name with references
1436
- if (str.substring(0, 12).toLowerCase() === 'CREATE TABLE'.toLowerCase()) {
1437
- const oPar = str.indexOf('(');
1438
- const tableName = str.substring(13, oPar).trim();
1439
- retRefs.push(tableName);
1821
+ catch (error) {
1822
+ const msg = error.message ? error.message : error;
1823
+ throw new Error(msg);
1440
1824
  }
1441
- return retRefs;
1442
1825
  }
1443
1826
  /**
1444
1827
  * QueryAll
@@ -1657,6 +2040,42 @@ class UtilsSQLite {
1657
2040
  throw new Error(`${msg} ${errmsg}`);
1658
2041
  }
1659
2042
  }
2043
+ searchForRelatedItems(mDB, updTableName, tableName, whStmt, withRefsNames, colNames, values) {
2044
+ const relatedItems = [];
2045
+ let key = "";
2046
+ const t1Names = withRefsNames.map((name) => `t1.${name}`);
2047
+ const t2Names = colNames.map((name) => `t2.${name}`);
2048
+ console.log(" whStmt ", whStmt);
2049
+ console.log(" t1Names ", t1Names);
2050
+ console.log(" t2Names ", t2Names);
2051
+ try {
2052
+ // addPrefix to the whereClause and swap colNames with withRefsNames
2053
+ let whereClause = this.statUtil
2054
+ .addPrefixToWhereClause(whStmt, colNames, withRefsNames, "t2.");
2055
+ // look at the whereclause and change colNames with withRefsNames
2056
+ if (whereClause.endsWith(";")) {
2057
+ whereClause = whereClause.slice(0, -1);
2058
+ }
2059
+ console.log(" whereClause ", whereClause);
2060
+ const resultString = t1Names
2061
+ .map((t1, index) => `${t1} = ${t2Names[index]}`)
2062
+ .join(" AND ");
2063
+ const sql = `SELECT t1.rowid FROM ${updTableName} t1 ` +
2064
+ `JOIN ${tableName} t2 ON ${resultString} ` +
2065
+ `WHERE ${whereClause} AND t1.sql_deleted = 0;`;
2066
+ console.log(" sql ", sql);
2067
+ const vals = this.queryAll(mDB, sql, values);
2068
+ if (vals.length > 0) {
2069
+ key = (Object.keys(vals[0]))[0];
2070
+ relatedItems.push(...vals);
2071
+ }
2072
+ return { key: key, relatedItems: relatedItems };
2073
+ }
2074
+ catch (error) {
2075
+ const msg = error.message ? error.message : error;
2076
+ throw new Error(msg);
2077
+ }
2078
+ }
1660
2079
  cleanStatement(stmt) {
1661
2080
  let sql = '';
1662
2081
  if (stmt.toLowerCase().includes('INSERT INTO'.toLowerCase()) ||
@@ -3562,7 +3981,7 @@ class UtilsSecret {
3562
3981
  this.globalUtil = new GlobalSQLite_1$2.GlobalSQLite();
3563
3982
  this.sqliteUtil = new utilsSQLite_1$4.UtilsSQLite();
3564
3983
  this.fileUtil = new utilsFile_1$3.UtilsFile();
3565
- this.storage = require$$3__default$1["default"];
3984
+ this.storage = require$$3__default$2["default"];
3566
3985
  }
3567
3986
  isSecretStored() {
3568
3987
  const secret = this.getPassphrase();
@@ -3689,7 +4108,7 @@ class UtilsJsonEncryption {
3689
4108
  constructor() {
3690
4109
  this.fileSecret = new utilsSecret_1$2.UtilsSecret();
3691
4110
  this.SALT = 'jeep_capacitor_sqlite';
3692
- this.Crypto = require$$1__default$2["default"];
4111
+ this.Crypto = require$$1__default$1["default"];
3693
4112
  this.CryptoJS = require$$2__default$1["default"];
3694
4113
  }
3695
4114
  /**
@@ -4391,9 +4810,9 @@ class CapacitorSQLite {
4391
4810
  this.versionUpgrades = {};
4392
4811
  this.databases = {};
4393
4812
  this.fileUtil = new utilsFile_1.UtilsFile();
4813
+ this.sqliteUtil = new utilsSQLite_1.UtilsSQLite();
4394
4814
  this.jsonUtil = new utilsJson_1.UtilsJson();
4395
4815
  this.jsonEncryptUtil = new utilsJsonEncryption_1.UtilsJsonEncryption();
4396
- this.sqliteUtil = new utilsSQLite_1.UtilsSQLite();
4397
4816
  this.secretUtil = new utilsSecret_1.UtilsSecret();
4398
4817
  this.globalUtil = new GlobalSQLite_1.GlobalSQLite();
4399
4818
  this.isEncryption = this.fileUtil.getIsEncryption();