Skip to content

Commit 9688b36

Browse files
Merge pull request #228 from sqlitecloud/example-db-connection
chore(examples): always recreate the db connection
2 parents 306dc1a + 193fb7d commit 9688b36

File tree

13 files changed

+177
-168
lines changed

13 files changed

+177
-168
lines changed

.github/workflows/test.yml

Lines changed: 15 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ jobs:
3939
- name: Upload Code Coverage
4040
uses: codecov/codecov-action@v4
4141
env:
42-
CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }}
42+
CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }}
4343

4444
examples-test:
4545
needs: code-test
@@ -123,21 +123,13 @@ jobs:
123123
exit 1
124124
125125
- name: remove with-javascript-express
126-
run: rm -rf examples/with-javascript-express
126+
run: rm -rf examples/with-javascript-express/*
127127

128128
- name: node with-plain-javascript
129129
working-directory: examples/with-plain-javascript
130130
run: |
131131
npm i
132-
app_log=$(mktemp)
133-
npm start > "$app_log" 2>&1 &
134-
135-
app_pid=$!
136-
sleep 3
137-
kill "$app_pid" 2>/dev/null
138-
139-
node_test=$(<"$app_log")
140-
rm "$app_log"
132+
node_test=$(npm start)
141133
142134
if [[ "$node_test" == *"Composer: 'Angus Young, Malcolm Young, Brian Johnson',"* ]]; then
143135
echo "✅ node with-plain-javascript test passed"
@@ -152,15 +144,8 @@ jobs:
152144
if [ "$RUNNER_OS" != "Windows" ]; then
153145
bun i #re-installing dependencies in windows with bash causes a panic
154146
fi
155-
app_log=$(mktemp)
156-
bun start > "$app_log" 2>&1 &
157-
158-
app_pid=$!
159-
sleep 3
160-
kill "$app_pid" 2>/dev/null
161-
162-
bun_test=$(<"$app_log")
163-
rm "$app_log"
147+
148+
bun_test=$(bun start)
164149
165150
if [[ "$bun_test" == *"Composer: 'Angus Young, Malcolm Young, Brian Johnson',"* ]]; then
166151
echo "✅ bun with-plain-javascript test passed"
@@ -172,15 +157,7 @@ jobs:
172157
- name: deno with-plain-javascript
173158
working-directory: examples/with-plain-javascript
174159
run: |
175-
app_log=$(mktemp)
176-
deno run start > "$app_log" 2>&1 &
177-
178-
app_pid=$!
179-
sleep 3
180-
kill "$app_pid" 2>/dev/null
181-
182-
deno_test=$(<"$app_log")
183-
rm "$app_log"
160+
deno_test=$(deno run start)
184161
185162
if [[ "$deno_test" == *"Composer: 'Angus Young, Malcolm Young, Brian Johnson',"* ]]; then
186163
echo "✅ deno with-plain-javascript test passed"
@@ -191,7 +168,7 @@ jobs:
191168
192169
- name: remove with-plain-javascript
193170
if: matrix.os != 'windows-latest' #kill command doesn not work on windows with bash, we can skip this step
194-
run: rm -rf examples/with-plain-javascript
171+
run: rm -rf examples/with-plain-javascript/*
195172

196173
- name: node with-typescript-knex
197174
working-directory: examples/with-typescript-knex
@@ -222,7 +199,7 @@ jobs:
222199
exit 1
223200
224201
- name: remove with-typescript-knex
225-
run: rm -rf examples/with-typescript-knex
202+
run: rm -rf examples/with-typescript-knex/*
226203

227204
- name: node with-typescript-nextjs
228205
working-directory: examples/with-typescript-nextjs
@@ -275,8 +252,7 @@ jobs:
275252
exit 1
276253
277254
- name: remove with-typescript-nextjs
278-
if: matrix.os != 'ubuntu-latest' #rm: cannot remove examples/with-typescript-nextjs: Directory not empty
279-
run: rm -rf examples/with-typescript-nextjs
255+
run: rm -rf examples/with-typescript-nextjs/*
280256

281257
- name: node with-javascript-vite
282258
if: matrix.os != 'LinuxARM64'
@@ -305,7 +281,7 @@ jobs:
305281
PW_DISABLE_TS_ESM: true
306282

307283
- name: remove with-javascript-vite
308-
run: rm -rf examples/with-javascript-vite
284+
run: rm -rf examples/with-javascript-vite/*
309285

310286
- name: node with-javascript-browser
311287
if: matrix.os != 'LinuxARM64'
@@ -326,7 +302,7 @@ jobs:
326302
command: cd examples/with-javascript-browser && deno --allow-all test.cjs
327303

328304
- name: remove with-javascript-browser
329-
run: rm -rf examples/with-javascript-browser
305+
run: rm -rf examples/with-javascript-browser/*
330306

331307
rn-ios-test:
332308
needs: code-test
@@ -362,7 +338,8 @@ jobs:
362338
xcode-version: 14.3
363339

364340
- name: build driver
365-
run: npm i && npm run build && echo "DRIVER=$(npm pack --json | jq '.[0].filename')" >> $GITHUB_ENV
341+
# distutils is required for the driver build (dep. `node-gyp`) and it was removed since python 3.13
342+
run: brew install python-setuptools && npm i && npm run build && echo "DRIVER=$(npm pack --json | jq '.[0].filename')" >> $GITHUB_ENV
366343

367344
- name: install driver
368345
working-directory: examples/with-typescript-react-native
@@ -489,7 +466,8 @@ jobs:
489466
xcode-version: 14.3
490467

491468
- name: build driver
492-
run: npm i && npm run build && echo "DRIVER=$(npm pack --json | jq '.[0].filename')" >> $GITHUB_ENV
469+
# distutils is required for the driver build (dep. `node-gyp`) and it was removed since python 3.13
470+
run: brew install python-setuptools && npm i && npm run build && echo "DRIVER=$(npm pack --json | jq '.[0].filename')" >> $GITHUB_ENV
493471

494472
- name: install driver
495473
working-directory: examples/with-javascript-expo

examples/with-javascript-browser/index.html

Lines changed: 20 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -44,33 +44,28 @@ <h2 class="pb-4">Results:</h2>
4444
messages.prepend(item);
4545
};
4646

47-
// socket is connected the first time the sql button is clicked and stays connected until the page is refreshed
48-
var database = null;
49-
5047
sendButton.addEventListener('click', () => {
51-
if (!database || !database.isConnected()) {
52-
// Get the input element by ID
53-
var connectionStringinputElement = document.getElementById('connectionStringInput');
54-
var connectionstring = connectionStringinputElement.value;
55-
// connect via websocket to the gateway on the same server
56-
const connectionConfig = {
57-
gatewayUrl: `${window.location.protocol === 'https:' ? 'wss' : 'ws'
58-
}://${window.location.hostname}:4000`,
59-
connectionstring: connectionstring,
60-
};
61-
database = new window.sqlitecloud.Database(
62-
connectionConfig,
63-
(error) => {
64-
if (error) {
65-
database = null;
66-
appendMessage(`connection error: ${error}`);
67-
} else {
68-
console.log('connected');
69-
appendMessage(`connected`);
70-
}
48+
// Get the input element by ID
49+
var connectionStringinputElement = document.getElementById('connectionStringInput');
50+
var connectionstring = connectionStringinputElement.value;
51+
// connect via websocket to the gateway on the same server
52+
const connectionConfig = {
53+
gatewayUrl: `${window.location.protocol === 'https:' ? 'wss' : 'ws'
54+
}://${window.location.hostname}:4000`,
55+
connectionstring: connectionstring,
56+
};
57+
var database = new window.sqlitecloud.Database(
58+
connectionConfig,
59+
(error) => {
60+
if (error) {
61+
database = null;
62+
appendMessage(`connection error: ${error}`);
63+
} else {
64+
console.log('connected');
65+
appendMessage(`connected`);
7166
}
72-
);
73-
}
67+
}
68+
);
7469

7570
var messageInputElement = document.getElementById('messageInput');
7671
const sql = messageInputElement.value;

examples/with-javascript-expo/components/AddTaskModal.js

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,11 +29,15 @@ export default AddTaskModal = ({
2929
};
3030

3131
const getTags = async () => {
32+
let db = null;
3233
try {
33-
const tags = await getDbConnection().sql("SELECT * FROM tags");
34+
db = getDbConnection();
35+
const tags = await db.sql("SELECT * FROM tags");
3436
setTagsList(tags);
3537
} catch (error) {
3638
console.error("Error getting tags", error);
39+
} finally {
40+
db?.close();
3741
}
3842
};
3943

Lines changed: 1 addition & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,7 @@
11
import { DATABASE_URL } from "@env";
22
import { Database } from "@sqlitecloud/drivers";
33

4-
/**
5-
* @type {Database}
6-
*/
7-
let database = null;
84

95
export default function getDbConnection() {
10-
if (!database || !database.isConnected()) {
11-
database = new Database(DATABASE_URL);
12-
}
13-
return database;
6+
return new Database(DATABASE_URL);
147
}
Lines changed: 45 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -1,78 +1,73 @@
1-
import { useState, useEffect } from "react";
2-
import getDbConnection from "../db/dbConnection";
1+
import { useState, useEffect } from 'react'
2+
import getDbConnection from '../db/dbConnection'
33

44
const useCategories = () => {
5-
const [moreCategories, setMoreCategories] = useState(["Work", "Personal"]);
5+
const [moreCategories, setMoreCategories] = useState(['Work', 'Personal'])
66

77
const getCategories = async () => {
8+
let db = null;
89
try {
9-
const tags = await getDbConnection().sql("SELECT * FROM tags");
10-
const filteredTags = tags.filter((tag) => {
11-
return tag["name"] !== "Work" && tag["name"] !== "Personal";
12-
});
13-
setMoreCategories((prevCategories) => [
14-
...prevCategories,
15-
...filteredTags.map((tag) => tag.name),
16-
]);
10+
db = getDbConnection();
11+
const tags = await db.sql('SELECT * FROM tags')
12+
const filteredTags = tags.filter(tag => {
13+
return tag['name'] !== 'Work' && tag['name'] !== 'Personal'
14+
})
15+
setMoreCategories(prevCategories => [...prevCategories, ...filteredTags.map(tag => tag.name)])
1716
} catch (error) {
18-
console.error("Error getting tags/categories", error);
17+
console.error('Error getting tags/categories', error)
1918
}
20-
};
19+
}
2120

22-
const addCategory = async (newCategory) => {
21+
const addCategory = async newCategory => {
22+
let db = null;
2323
try {
24-
await getDbConnection().sql(
25-
"INSERT INTO tags (name) VALUES (?) RETURNING *",
26-
newCategory
27-
);
28-
setMoreCategories((prevCategories) => [...prevCategories, newCategory]);
24+
db = getDbConnection();
25+
await db.sql('INSERT INTO tags (name) VALUES (?) RETURNING *', newCategory)
26+
setMoreCategories(prevCategories => [...prevCategories, newCategory])
2927
} catch (error) {
30-
console.error("Error adding category", error);
28+
console.error('Error adding category', error)
29+
} finally {
30+
db?.close();
3131
}
32-
};
32+
}
3333

3434
const initializeTables = async () => {
35+
let db = null;
3536
try {
36-
const createTasksTable = await getDbConnection().sql(
37-
"CREATE TABLE IF NOT EXISTS tasks (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, title TEXT NOT NULL, isCompleted INT NOT NULL);"
38-
);
37+
db = getDbConnection();
38+
const createTasksTable = await db.sql(
39+
'CREATE TABLE IF NOT EXISTS tasks (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, title TEXT NOT NULL, isCompleted INT NOT NULL);'
40+
)
3941

40-
const createTagsTable = await getDbConnection().sql(
41-
"CREATE TABLE IF NOT EXISTS tags (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, UNIQUE(name));"
42-
);
42+
const createTagsTable = await db.sql('CREATE TABLE IF NOT EXISTS tags (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, UNIQUE(name));')
4343

44-
const createTagsTasksTable = await getDbConnection().sql(
45-
"CREATE TABLE IF NOT EXISTS tasks_tags (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, task_id INTEGER NOT NULL, tag_id INTEGER NOT NULL, FOREIGN KEY (task_id) REFERENCES tasks(id), FOREIGN KEY (tag_id) REFERENCES tags(id));"
46-
);
44+
const createTagsTasksTable = await db.sql(
45+
'CREATE TABLE IF NOT EXISTS tasks_tags (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, task_id INTEGER NOT NULL, tag_id INTEGER NOT NULL, FOREIGN KEY (task_id) REFERENCES tasks(id), FOREIGN KEY (tag_id) REFERENCES tags(id));'
46+
)
4747

48-
if (
49-
createTasksTable === "OK" &&
50-
createTagsTable === "OK" &&
51-
createTagsTasksTable === "OK"
52-
) {
53-
console.log("Successfully created tables");
48+
if (createTasksTable === 'OK' && createTagsTable === 'OK' && createTagsTasksTable === 'OK') {
49+
console.log('Successfully created tables')
5450

55-
await getDbConnection().sql("INSERT OR IGNORE INTO tags (name) VALUES (?)", "Work");
56-
await getDbConnection().sql(
57-
"INSERT OR IGNORE INTO tags (name) VALUES (?)",
58-
"Personal"
59-
);
60-
getCategories();
51+
await db.sql('INSERT OR IGNORE INTO tags (name) VALUES (?)', 'Work')
52+
await db.sql('INSERT OR IGNORE INTO tags (name) VALUES (?)', 'Personal')
53+
getCategories()
6154
}
6255
} catch (error) {
63-
console.error("Error creating tables", error);
56+
console.error('Error creating tables', error)
57+
} finally {
58+
db?.close();
6459
}
65-
};
60+
}
6661

6762
useEffect(() => {
68-
initializeTables();
69-
}, []);
63+
initializeTables()
64+
}, [])
7065

7166
return {
7267
moreCategories,
7368
addCategory,
74-
getCategories,
75-
};
76-
};
69+
getCategories
70+
}
71+
}
7772

78-
export default useCategories;
73+
export default useCategories

0 commit comments

Comments
 (0)