Skip to content

Commit 7a80b50

Browse files
committed
Fix issue#520 and issue#521
1 parent e0466f4 commit 7a80b50

File tree

11 files changed

+181
-76
lines changed

11 files changed

+181
-76
lines changed

CHANGELOG.md

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,14 @@
1+
# 5.6.2 (2024-03-07)
2+
3+
### Added Features
4+
5+
- Include examples of SQLite comments in the API.md documentation
6+
7+
### Bug Fixes
8+
9+
- Fix Error in README.md with install instructions issue#520
10+
- Fix Unable to run executeSet on SQL with -- comments issue#521
11+
112
# 5.6.1 (2024-02-29)
213

314
### Bug Fixes

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ pnpm install --save sql.js
4848
npx cap sync
4949
```
5050

51-
then add plugin to main `capacitor.config.json` file:
51+
then add plugin to main `capacitor.config.ts` file:
5252

5353
```ts
5454
import { CapacitorConfig } from '@capacitor/cli';
0 Bytes
Binary file not shown.

android/src/main/java/com/getcapacitor/community/database/sqlite/SQLite/Database.java

Lines changed: 22 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -743,24 +743,40 @@ private JSObject getStmtAndRetColNames(String sqlStmt, String retMode) throws JS
743743
if (returningIndex != -1) {
744744
String substring = suffix.substring(returningIndex + "returning".length());
745745
String names = substring.trim();
746-
if (names.endsWith(";")) {
747-
retObj.put("names", names.substring(0, names.length() - 1));
748-
}
749-
}
746+
retObj.put("names", getNames(names));
747+
}
750748
}
751749
return retObj;
752750
}
753751

752+
private String getNames(String input) {
753+
int indexSemicolon = input.indexOf(";");
754+
int indexDoubleDash = input.indexOf("--");
755+
int indexCommentStart = input.indexOf("/*");
756+
757+
// Find the minimum index among them
758+
int minIndex = input.length();
759+
if (indexSemicolon != -1) {
760+
minIndex = Math.min(minIndex, indexSemicolon);
761+
}
762+
if (indexDoubleDash != -1) {
763+
minIndex = Math.min(minIndex, indexDoubleDash);
764+
}
765+
if (indexCommentStart != -1) {
766+
minIndex = Math.min(minIndex, indexCommentStart);
767+
}
768+
return input.substring(0, minIndex).trim();
769+
}
754770
private JSObject isReturning(String sqlStmt) {
755771
JSObject retObj = new JSObject();
756772

757-
String stmt = sqlStmt.replace("\n", "").trim();
773+
String stmt = sqlStmt.trim();
758774
if (stmt.endsWith(";")) {
759775
// Remove the suffix
760776
stmt = stmt.substring(0, stmt.length() - 1).trim();
761777
}
762778
retObj.put("isReturning", false);
763-
retObj.put("stmt", stmt);
779+
retObj.put("stmt", sqlStmt);
764780
retObj.put("names", "");
765781

766782
switch (stmt.substring(0, Math.min(stmt.length(), 6)).toUpperCase()) {

docs/API.md

Lines changed: 61 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@ The plugin add a suffix "SQLite" and an extension ".db" to the database name giv
4747

4848
- for sharing databases between users:
4949

50-
```
50+
```ts
5151
plugins: {
5252
CapacitorSQLite: {
5353
electronMacLocation: "/YOUR_DATABASES_PATH",
@@ -95,6 +95,66 @@ The plugin add a suffix "SQLite" and an extension ".db" to the database name giv
9595
9696
- see [Comments within SQL](https://www.techonthenet.com/sqlite/comments.php)
9797
98+
- Some examples
99+
100+
```ts
101+
const setContacts: Array<capSQLiteSet> = [
102+
{ statement:"INSERT INTO contacts /* Contact Simpson */ (name,FirstName,email,company,age,MobileNumber) VALUES (?,?,?,?,?,?);",
103+
values:["Simpson","Tom","Simpson@example.com",,69,"4405060708"]
104+
},
105+
{ statement:"INSERT INTO contacts /* three more contacts */ (name,FirstName,email,company,age,MobileNumber) VALUES (?,?,?,?,?,?) -- Add Jones, Whiteley and Brown;",
106+
values:[
107+
["Jones","David","Jones@example.com",,42.1,"4404030201"],
108+
["Whiteley","Dave","Whiteley@example.com",,45.3,"4405162732"],
109+
["Brown","John","Brown@example.com",,35,"4405243853"]
110+
]
111+
},
112+
{ statement:"UPDATE contacts SET age = ? , MobileNumber = ? WHERE id = ? -- Update Jones Contact;",
113+
values:[51.4,"4404030202",6]
114+
}
115+
];
116+
const setMessages: Array<capSQLiteSet> = [
117+
{ statement:`
118+
/* Define the messages table */
119+
CREATE TABLE IF NOT EXISTS messages (
120+
id INTEGER PRIMARY KEY NOT NULL,
121+
contactid INTEGER, -- key to contacts(id)
122+
title TEXT NOT NULL,
123+
body TEXT NOT NULL,
124+
last_modified INTEGER DEFAULT (strftime('%s', 'now')),
125+
FOREIGN KEY (contactid) REFERENCES contacts(id) ON DELETE SET DEFAULT
126+
);`,
127+
values:[]
128+
},
129+
];
130+
131+
let insertQuery = 'INSERT INTO contacts (name,FirstName,email,company,age,MobileNumber) VALUES (?, ?, ?, ?, ?, ?) -- Add Sue Hellen;';
132+
let bindValues = ["Hellen","Sue","sue.hellen@example.com",,42,"4406050807"];
133+
let ret = await db.run(insertQuery, bindValues);
134+
console.log(`>>> run ret 1: ${JSON.stringify(ret)}`)
135+
insertQuery = `INSERT INTO contacts /* some contacts */ (name,FirstName,email,company,age,MobileNumber) VALUES
136+
('Doe','John','john.doe@example.com', 'IBM', 30, '4403050926'), -- add Doe
137+
('Watson','Dave','dave.watson@example.com','Apple', 30, '4407050932') /* add Watson */,
138+
('Smith', 'Jane', 'jane.smith@example.com', 'IBM', 27, '33607556142') /* Add Smith */-- End of add contact;`;
139+
bindValues = [];
140+
ret = await db.run(insertQuery, bindValues);
141+
console.log(`>>> run ret 2: ${JSON.stringify(ret)}`)
142+
143+
let selectQuery = "SELECT * /* all columns */ FROM contacts WHERE company = 'IBM' -- for company IBM;";
144+
145+
ret = await db.query(selectQuery);
146+
console.log(`>>> query "IBM" ret: ${JSON.stringify(ret)}`)
147+
148+
ret = await db.executeSet(setContacts);
149+
console.log(`>>> executeSet 1 ret: ${JSON.stringify(ret)}`)
150+
151+
selectQuery = "SELECT email /* only email */ FROM contacts WHERE company ISNULL -- for company not given;";
152+
153+
154+
ret = await db.executeSet(setMessages);
155+
console.log(`>>> executeSet 2 ret: ${JSON.stringify(ret)}`)
156+
```
157+
98158
## Unexpected behaviours
99159
100160
Unexpected or erroneous behaviour users of this library have encountered.

electron/src/electron-utils/utilsSQLite.ts

Lines changed: 28 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -347,7 +347,7 @@ export class UtilsSQLite {
347347
isSQL92: boolean,
348348
): string {
349349
// split the statements in an array of statement
350-
let sqlStmt = sql.replace(/\n/g, '');
350+
let sqlStmt = sql /*.replace(/\n/g, '')*/;
351351
// deal with trigger
352352
sqlStmt = sqlStmt.replace(/end;/g, 'END;');
353353
sqlStmt = sqlStmt.replace(/;END;/g, '&END;');
@@ -398,7 +398,7 @@ export class UtilsSQLite {
398398
}
399399
resArr.push(rStmt);
400400
}
401-
sqlStmt = resArr.join(';');
401+
sqlStmt = resArr.join(';\n');
402402
return sqlStmt;
403403
}
404404
/**
@@ -510,7 +510,7 @@ export class UtilsSQLite {
510510
const msg = 'PrepareRun';
511511

512512
const stmtType: string = statement
513-
.replace(/\n/g, '')
513+
// .replace(/\n/g, '')
514514
.trim()
515515
.substring(0, 6)
516516
.toUpperCase();
@@ -1227,7 +1227,7 @@ export class UtilsSQLite {
12271227
stmt: string;
12281228
suffix: string;
12291229
} {
1230-
let stmt = sqlStmt.replace(/\n/g, '').trim();
1230+
let stmt = sqlStmt.trim();
12311231

12321232
if (stmt.endsWith(';')) {
12331233
stmt = stmt.slice(0, -1).trim();
@@ -1323,16 +1323,35 @@ export class UtilsSQLite {
13231323
const substring = suffix.slice(returningIndex + 9); // 9 is the length of "returning"
13241324

13251325
const names = substring.trim();
1326-
if (names.endsWith(';')) {
1327-
retObj.names = names.slice(0, -1);
1328-
} else {
1329-
retObj.names = names;
1330-
}
1326+
retObj.names = this.getNames(names);
13311327
}
13321328
}
13331329

13341330
return retObj;
13351331
}
1332+
private getNames(input: string): string {
1333+
// Find the index of the first occurrence of ";", "--", or "/*"
1334+
const indexSemicolon = input.indexOf(';');
1335+
const indexDoubleDash = input.indexOf('--');
1336+
const indexCommentStart = input.indexOf('/*');
1337+
1338+
// Find the minimum index among them
1339+
let minIndex = input.length;
1340+
if (indexSemicolon !== -1) {
1341+
minIndex = Math.min(minIndex, indexSemicolon);
1342+
}
1343+
if (indexDoubleDash !== -1) {
1344+
minIndex = Math.min(minIndex, indexDoubleDash);
1345+
}
1346+
if (indexCommentStart !== -1) {
1347+
minIndex = Math.min(minIndex, indexCommentStart);
1348+
}
1349+
1350+
// Extract substring up to the minimum index
1351+
const colnames = input.substring(0, minIndex).trim();
1352+
return colnames;
1353+
}
1354+
13361355
private getTableName(sqlStatement: string): string | null {
13371356
const patterns: { [key: string]: RegExp } = {
13381357
insert: /INSERT\s+INTO\s+(\w+)/i,

electron/src/electron-utils/utilsSqlstatement.ts

Lines changed: 0 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -128,35 +128,6 @@ export class UtilsSQLStatement {
128128
return lines.join(' ');
129129
}
130130

131-
public getStmtAndRetColNames(
132-
sqlStmt: string,
133-
retMode: string,
134-
): { stmt: string; names: string } {
135-
const retWord = 'RETURNING';
136-
const retStmtNames: { stmt: string; names: string } = {
137-
stmt: sqlStmt,
138-
names: '',
139-
};
140-
141-
const retWordIndex = sqlStmt.toUpperCase().indexOf(retWord);
142-
if (retWordIndex !== -1) {
143-
const prefix = sqlStmt.substring(0, retWordIndex);
144-
retStmtNames.stmt = `${prefix};`;
145-
146-
if (retMode.substring(0, 2) === 'wA') {
147-
const suffix = sqlStmt.substring(retWordIndex + retWord.length);
148-
const names = suffix.trim();
149-
if (names.endsWith(';')) {
150-
retStmtNames.names = names.substring(0, names.length - 1);
151-
} else {
152-
retStmtNames.names = names;
153-
}
154-
}
155-
}
156-
157-
return retStmtNames;
158-
}
159-
160131
public extractCombinedPrimaryKey(whereClause: string): string[][] | null {
161132
const pattern = /WHERE\s*\((.+?)\)\s*(?:=|IN)\s*\((.+?)\)/g;
162133
const regex = new RegExp(pattern);

ios/Plugin/Utils/UtilsSQLCipher.swift

Lines changed: 18 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -463,7 +463,7 @@ class UtilsSQLCipher {
463463
retMode = "wA\(retMode)"
464464
}
465465
}
466-
if (retMode == "no" || retMode.prefix(2) == "wA")/* && isReturning*/ {
466+
if (retMode == "no" || retMode.prefix(2) == "wA") {
467467
let stmtNames = UtilsSQLStatement
468468
.getStmtAndRetColNames(sqlStmt: sqlStmt,
469469
retMode: retMode)
@@ -834,6 +834,12 @@ class UtilsSQLCipher {
834834
return Int(sqlite3_total_changes(mDB))
835835
}
836836

837+
// MARK: - dbLastId
838+
839+
class func dbLastId(mDB: OpaquePointer?) -> Int64 {
840+
return Int64(sqlite3_last_insert_rowid(mDB))
841+
}
842+
837843
// MARK: - Execute
838844

839845
// swiftlint:disable function_body_length
@@ -970,17 +976,17 @@ class UtilsSQLCipher {
970976
}
971977
}
972978
} else {
973-
let resp = try UtilsSQLCipher
974-
.prepareSQL(mDB: mDB, sql: sql, values: values,
975-
fromJson: false, returnMode: returnMode)
976-
lastId = resp.0
977-
respSet = resp.1
978-
if lastId == -1 {
979-
let message: String = "lastId < 0"
980-
throw UtilsSQLCipherError.executeSet(
981-
message: message)
982-
}
983-
response = addToResponse(response: response, respSet: respSet)
979+
let resp = try UtilsSQLCipher
980+
.prepareSQL(mDB: mDB, sql: sql, values: values,
981+
fromJson: false, returnMode: returnMode)
982+
lastId = resp.0
983+
respSet = resp.1
984+
if lastId == -1 {
985+
let message: String = "lastId < 0"
986+
throw UtilsSQLCipherError.executeSet(
987+
message: message)
988+
}
989+
response = addToResponse(response: response, respSet: respSet)
984990
}
985991
}
986992

ios/Plugin/Utils/UtilsSQLStatement.swift

Lines changed: 31 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -326,8 +326,7 @@ class UtilsSQLStatement {
326326
// MARK: - isReturning
327327

328328
class func isReturning(sqlStmt: String) -> (Bool, String, String) {
329-
var stmt = sqlStmt.replacingOccurrences(of: "\n", with: "")
330-
.trimmingCharacters(in: .whitespacesAndNewlines)
329+
var stmt = sqlStmt.trimmingCharacters(in: .whitespacesAndNewlines)
331330
if stmt.hasSuffix(";") {
332331
// Remove the suffix
333332
stmt = String(stmt.dropLast())
@@ -360,10 +359,10 @@ class UtilsSQLStatement {
360359
if substringAfterValues.lowercased().contains("returning") {
361360
return (true, stmtString, resultString)
362361
} else {
363-
return (false, stmt, "")
362+
return (false, sqlStmt, "")
364363
}
365364
}
366-
return (false, stmt, "")
365+
return (false, sqlStmt, "")
367366

368367
case "DELETE", "UPDATE":
369368
let words = stmt.components(separatedBy: .whitespacesAndNewlines)
@@ -391,11 +390,11 @@ class UtilsSQLStatement {
391390

392391
return (true, joinedWords, joinedReturningString)
393392
} else {
394-
return (false, stmt, "")
393+
return (false, sqlStmt, "")
395394
}
396395

397396
default:
398-
return (false, stmt, "")
397+
return (false, sqlStmt, "")
399398
}
400399

401400
}
@@ -425,14 +424,37 @@ class UtilsSQLStatement {
425424

426425
let names =
427426
"\(substring)".trimmingLeadingAndTrailingSpaces()
428-
if names.suffix(1) == ";" {
429-
retStmtNames["names"] = String(names.dropLast())
430-
}
427+
retStmtNames["names"] = getNames(from: names)
431428
}
432429
}
433430
return retStmtNames
434431
}
435432

433+
// MARK: - getNames
434+
435+
class func getNames(from input: String) -> String {
436+
// Find the index of the first occurrence of ";", "--", or "/*"
437+
let indexSemicolon = input.firstIndex(of: ";")
438+
let indexDoubleDash = input.range(of: "--")
439+
let indexCommentStart = input.range(of: "/*")
440+
441+
// Find the minimum index among them
442+
var minIndex = input.endIndex
443+
if let index = indexSemicolon {
444+
minIndex = min(minIndex, index)
445+
}
446+
if let index = indexDoubleDash?.lowerBound {
447+
minIndex = min(minIndex, index)
448+
}
449+
if let index = indexCommentStart?.lowerBound {
450+
minIndex = min(minIndex, index)
451+
}
452+
453+
// Extract substring up to the minimum index
454+
let colnames = String(input[..<minIndex]).trimmingCharacters(in: .whitespacesAndNewlines)
455+
return colnames
456+
}
457+
436458
// MARK: - extractCombinedPrimaryKey
437459

438460
class func extractCombinedPrimaryKey(from whereClause: String)

0 commit comments

Comments
 (0)