Skip to content

chore(examples): always recreate the db connection #228

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Mar 13, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 15 additions & 37 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ jobs:
- name: Upload Code Coverage
uses: codecov/codecov-action@v4
env:
CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }}
CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }}

examples-test:
needs: code-test
Expand Down Expand Up @@ -123,21 +123,13 @@ jobs:
exit 1

- name: remove with-javascript-express
run: rm -rf examples/with-javascript-express
run: rm -rf examples/with-javascript-express/*

- name: node with-plain-javascript
working-directory: examples/with-plain-javascript
run: |
npm i
app_log=$(mktemp)
npm start > "$app_log" 2>&1 &

app_pid=$!
sleep 3
kill "$app_pid" 2>/dev/null

node_test=$(<"$app_log")
rm "$app_log"
node_test=$(npm start)

if [[ "$node_test" == *"Composer: 'Angus Young, Malcolm Young, Brian Johnson',"* ]]; then
echo "✅ node with-plain-javascript test passed"
Expand All @@ -152,15 +144,8 @@ jobs:
if [ "$RUNNER_OS" != "Windows" ]; then
bun i #re-installing dependencies in windows with bash causes a panic
fi
app_log=$(mktemp)
bun start > "$app_log" 2>&1 &

app_pid=$!
sleep 3
kill "$app_pid" 2>/dev/null

bun_test=$(<"$app_log")
rm "$app_log"

bun_test=$(bun start)

if [[ "$bun_test" == *"Composer: 'Angus Young, Malcolm Young, Brian Johnson',"* ]]; then
echo "✅ bun with-plain-javascript test passed"
Expand All @@ -172,15 +157,7 @@ jobs:
- name: deno with-plain-javascript
working-directory: examples/with-plain-javascript
run: |
app_log=$(mktemp)
deno run start > "$app_log" 2>&1 &

app_pid=$!
sleep 3
kill "$app_pid" 2>/dev/null

deno_test=$(<"$app_log")
rm "$app_log"
deno_test=$(deno run start)

if [[ "$deno_test" == *"Composer: 'Angus Young, Malcolm Young, Brian Johnson',"* ]]; then
echo "✅ deno with-plain-javascript test passed"
Expand All @@ -191,7 +168,7 @@ jobs:

- name: remove with-plain-javascript
if: matrix.os != 'windows-latest' #kill command doesn not work on windows with bash, we can skip this step
run: rm -rf examples/with-plain-javascript
run: rm -rf examples/with-plain-javascript/*

- name: node with-typescript-knex
working-directory: examples/with-typescript-knex
Expand Down Expand Up @@ -222,7 +199,7 @@ jobs:
exit 1

- name: remove with-typescript-knex
run: rm -rf examples/with-typescript-knex
run: rm -rf examples/with-typescript-knex/*

- name: node with-typescript-nextjs
working-directory: examples/with-typescript-nextjs
Expand Down Expand Up @@ -275,8 +252,7 @@ jobs:
exit 1

- name: remove with-typescript-nextjs
if: matrix.os != 'ubuntu-latest' #rm: cannot remove examples/with-typescript-nextjs: Directory not empty
run: rm -rf examples/with-typescript-nextjs
run: rm -rf examples/with-typescript-nextjs/*

- name: node with-javascript-vite
if: matrix.os != 'LinuxARM64'
Expand Down Expand Up @@ -305,7 +281,7 @@ jobs:
PW_DISABLE_TS_ESM: true

- name: remove with-javascript-vite
run: rm -rf examples/with-javascript-vite
run: rm -rf examples/with-javascript-vite/*

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

- name: remove with-javascript-browser
run: rm -rf examples/with-javascript-browser
run: rm -rf examples/with-javascript-browser/*

rn-ios-test:
needs: code-test
Expand Down Expand Up @@ -362,7 +338,8 @@ jobs:
xcode-version: 14.3

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

- name: install driver
working-directory: examples/with-typescript-react-native
Expand Down Expand Up @@ -489,7 +466,8 @@ jobs:
xcode-version: 14.3

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

- name: install driver
working-directory: examples/with-javascript-expo
Expand Down
45 changes: 20 additions & 25 deletions examples/with-javascript-browser/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -44,33 +44,28 @@ <h2 class="pb-4">Results:</h2>
messages.prepend(item);
};

// socket is connected the first time the sql button is clicked and stays connected until the page is refreshed
var database = null;

sendButton.addEventListener('click', () => {
if (!database || !database.isConnected()) {
// Get the input element by ID
var connectionStringinputElement = document.getElementById('connectionStringInput');
var connectionstring = connectionStringinputElement.value;
// connect via websocket to the gateway on the same server
const connectionConfig = {
gatewayUrl: `${window.location.protocol === 'https:' ? 'wss' : 'ws'
}://${window.location.hostname}:4000`,
connectionstring: connectionstring,
};
database = new window.sqlitecloud.Database(
connectionConfig,
(error) => {
if (error) {
database = null;
appendMessage(`connection error: ${error}`);
} else {
console.log('connected');
appendMessage(`connected`);
}
// Get the input element by ID
var connectionStringinputElement = document.getElementById('connectionStringInput');
var connectionstring = connectionStringinputElement.value;
// connect via websocket to the gateway on the same server
const connectionConfig = {
gatewayUrl: `${window.location.protocol === 'https:' ? 'wss' : 'ws'
}://${window.location.hostname}:4000`,
connectionstring: connectionstring,
};
var database = new window.sqlitecloud.Database(
connectionConfig,
(error) => {
if (error) {
database = null;
appendMessage(`connection error: ${error}`);
} else {
console.log('connected');
appendMessage(`connected`);
}
);
}
}
);

var messageInputElement = document.getElementById('messageInput');
const sql = messageInputElement.value;
Expand Down
6 changes: 5 additions & 1 deletion examples/with-javascript-expo/components/AddTaskModal.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,11 +29,15 @@ export default AddTaskModal = ({
};

const getTags = async () => {
let db = null;
try {
const tags = await getDbConnection().sql("SELECT * FROM tags");
db = getDbConnection();
const tags = await db.sql("SELECT * FROM tags");
setTagsList(tags);
} catch (error) {
console.error("Error getting tags", error);
} finally {
db?.close();
}
};

Expand Down
9 changes: 1 addition & 8 deletions examples/with-javascript-expo/db/dbConnection.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,7 @@
import { DATABASE_URL } from "@env";
import { Database } from "@sqlitecloud/drivers";

/**
* @type {Database}
*/
let database = null;

export default function getDbConnection() {
if (!database || !database.isConnected()) {
database = new Database(DATABASE_URL);
}
return database;
return new Database(DATABASE_URL);
}
95 changes: 45 additions & 50 deletions examples/with-javascript-expo/hooks/useCategories.js
Original file line number Diff line number Diff line change
@@ -1,78 +1,73 @@
import { useState, useEffect } from "react";
import getDbConnection from "../db/dbConnection";
import { useState, useEffect } from 'react'
import getDbConnection from '../db/dbConnection'

const useCategories = () => {
const [moreCategories, setMoreCategories] = useState(["Work", "Personal"]);
const [moreCategories, setMoreCategories] = useState(['Work', 'Personal'])

const getCategories = async () => {
let db = null;
try {
const tags = await getDbConnection().sql("SELECT * FROM tags");
const filteredTags = tags.filter((tag) => {
return tag["name"] !== "Work" && tag["name"] !== "Personal";
});
setMoreCategories((prevCategories) => [
...prevCategories,
...filteredTags.map((tag) => tag.name),
]);
db = getDbConnection();
const tags = await db.sql('SELECT * FROM tags')
const filteredTags = tags.filter(tag => {
return tag['name'] !== 'Work' && tag['name'] !== 'Personal'
})
setMoreCategories(prevCategories => [...prevCategories, ...filteredTags.map(tag => tag.name)])
} catch (error) {
console.error("Error getting tags/categories", error);
console.error('Error getting tags/categories', error)
}
};
}

const addCategory = async (newCategory) => {
const addCategory = async newCategory => {
let db = null;
try {
await getDbConnection().sql(
"INSERT INTO tags (name) VALUES (?) RETURNING *",
newCategory
);
setMoreCategories((prevCategories) => [...prevCategories, newCategory]);
db = getDbConnection();
await db.sql('INSERT INTO tags (name) VALUES (?) RETURNING *', newCategory)
setMoreCategories(prevCategories => [...prevCategories, newCategory])
} catch (error) {
console.error("Error adding category", error);
console.error('Error adding category', error)
} finally {
db?.close();
}
};
}

const initializeTables = async () => {
let db = null;
try {
const createTasksTable = await getDbConnection().sql(
"CREATE TABLE IF NOT EXISTS tasks (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, title TEXT NOT NULL, isCompleted INT NOT NULL);"
);
db = getDbConnection();
const createTasksTable = await db.sql(
'CREATE TABLE IF NOT EXISTS tasks (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, title TEXT NOT NULL, isCompleted INT NOT NULL);'
)

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

const createTagsTasksTable = await getDbConnection().sql(
"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));"
);
const createTagsTasksTable = await db.sql(
'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));'
)

if (
createTasksTable === "OK" &&
createTagsTable === "OK" &&
createTagsTasksTable === "OK"
) {
console.log("Successfully created tables");
if (createTasksTable === 'OK' && createTagsTable === 'OK' && createTagsTasksTable === 'OK') {
console.log('Successfully created tables')

await getDbConnection().sql("INSERT OR IGNORE INTO tags (name) VALUES (?)", "Work");
await getDbConnection().sql(
"INSERT OR IGNORE INTO tags (name) VALUES (?)",
"Personal"
);
getCategories();
await db.sql('INSERT OR IGNORE INTO tags (name) VALUES (?)', 'Work')
await db.sql('INSERT OR IGNORE INTO tags (name) VALUES (?)', 'Personal')
getCategories()
}
} catch (error) {
console.error("Error creating tables", error);
console.error('Error creating tables', error)
} finally {
db?.close();
}
};
}

useEffect(() => {
initializeTables();
}, []);
initializeTables()
}, [])

return {
moreCategories,
addCategory,
getCategories,
};
};
getCategories
}
}

export default useCategories;
export default useCategories
Loading
Loading