Skip to content

Commit 5fd7c19

Browse files
author
Daniele Briggi
committed
chore(examples): always recreate the db connection
1 parent 306dc1a commit 5fd7c19

File tree

8 files changed

+86
-70
lines changed

8 files changed

+86
-70
lines changed

examples/with-javascript-browser/index.html

+20-25
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+
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;
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
}

examples/with-javascript-express/app.js

+12-3
Original file line numberDiff line numberDiff line change
@@ -14,9 +14,18 @@ app.use(express.json())
1414

1515
/* http://localhost:3001/ returns chinook tracks as json */
1616
app.get('/', async function (req, res, next) {
17-
var database = new sqlitecloud.Database(DATABASE_URL)
18-
var tracks = await database.sql('USE DATABASE chinook.sqlite; SELECT * FROM tracks LIMIT 20;')
19-
res.send({ tracks })
17+
var database = null
18+
try {
19+
database = new sqlitecloud.Database(DATABASE_URL)
20+
var tracks = await database.sql('USE DATABASE chinook.sqlite; SELECT * FROM tracks LIMIT 20;')
21+
res.send({ tracks })
22+
} catch (error) {
23+
res.send({ error: error.message })
24+
} finally {
25+
if (database) {
26+
database.close()
27+
}
28+
}
2029
})
2130

2231
const port = process.env.PORT || 3000

examples/with-javascript-vite/src/App.jsx

+17-19
Original file line numberDiff line numberDiff line change
@@ -1,30 +1,28 @@
11
import { useEffect, useState } from "react";
22
import { Database } from "@sqlitecloud/drivers";
33

4-
let db = null
5-
6-
function getDatabase() {
7-
if (!db || !db.isConnected()) {
8-
db = new Database(import.meta.env.VITE_DATABASE_URL);
9-
}
10-
11-
return db;
12-
}
13-
144

155
function App() {
166
const [data, setData] = useState([]);
177

188
const getAlbums = async () => {
19-
const result = await getDatabase().sql(`
20-
USE DATABASE chinook.sqlite;
21-
SELECT albums.AlbumId as id, albums.Title as title, artists.name as artist
22-
FROM albums
23-
INNER JOIN artists
24-
WHERE artists.ArtistId = albums.ArtistId
25-
LIMIT 20;
26-
`);
27-
setData(result);
9+
let database = null;
10+
try {
11+
database = new Database(import.meta.env.VITE_DATABASE_URL)
12+
const result = await database.sql(`
13+
USE DATABASE chinook.sqlite;
14+
SELECT albums.AlbumId as id, albums.Title as title, artists.name as artist
15+
FROM albums
16+
INNER JOIN artists
17+
WHERE artists.ArtistId = albums.ArtistId
18+
LIMIT 20;
19+
`);
20+
setData(result);
21+
} catch (error) {
22+
console.error("Error getting albums", error);
23+
} finally {
24+
database.close();
25+
}
2826
};
2927

3028
useEffect(() => {

examples/with-plain-javascript/app.js

+12-5
Original file line numberDiff line numberDiff line change
@@ -9,12 +9,19 @@ var DATABASE_URL = process.env.DATABASE_URL
99
console.assert(DATABASE_URL, 'DATABASE_URL environment variable not set in .env')
1010

1111
async function selectTracks() {
12-
// create a connection with sqlitecloud
13-
var database = new sqlitecloud.Database(DATABASE_URL)
12+
var database = null
13+
try {
14+
// create a connection with sqlitecloud
15+
database = new sqlitecloud.Database(DATABASE_URL)
1416

15-
// run async query
16-
var tracks = await database.sql('USE DATABASE chinook.sqlite; SELECT * FROM tracks LIMIT 20;')
17-
console.log(`selectTracks returned:`, tracks)
17+
// run async query
18+
var tracks = await database.sql('USE DATABASE chinook.sqlite; SELECT * FROM tracks LIMIT 20;')
19+
console.log(`selectTracks returned:`, tracks)
20+
} catch (error) {
21+
console.error(`selectTracks error:`, error)
22+
} finally {
23+
database.close()
24+
}
1825

1926
// You can also use all the regular sqlite3 api with callbacks, see:
2027
// https://docs.sqlitecloud.io/docs/sdk/js/intro

examples/with-typescript-nextjs/app/api/hello/route.ts

+12-5
Original file line numberDiff line numberDiff line change
@@ -12,11 +12,18 @@ console.assert(DATABASE_URL, 'Please configure a .env file with DATABASE_URL poi
1212
// route for /api/hello
1313
export async function GET(request: NextRequest) {
1414
// connect to database using connection string provided in https://dashboard.sqlitecloud.io/
15-
const database = new Database(DATABASE_URL)
15+
let database
16+
try {
17+
database = new Database(DATABASE_URL)
1618

17-
// retrieve rows from chinook database using a plain SQL query
18-
const tracks = await database.sql('USE DATABASE chinook.sqlite; SELECT * FROM tracks LIMIT 20;')
19+
// retrieve rows from chinook database using a plain SQL query
20+
const tracks = await database.sql('USE DATABASE chinook.sqlite; SELECT * FROM tracks LIMIT 20;')
1921

20-
// return as json response
21-
return NextResponse.json<{ data: any }>({ data: tracks })
22+
// return as json response
23+
return NextResponse.json<{ data: any }>({ data: tracks })
24+
} catch (error) {
25+
return NextResponse.json({ error }, { status: 500 })
26+
} finally {
27+
database?.close()
28+
}
2229
}

examples/with-typescript-react-native/App.tsx

+11-4
Original file line numberDiff line numberDiff line change
@@ -8,12 +8,19 @@ export default function App() {
88

99
useEffect(() => {
1010
async function getAlbums() {
11-
const db = new Database(`${DATABASE_URL}`);
11+
let db
12+
try {
13+
db = new Database(`${DATABASE_URL}`);
1214

13-
const result =
14-
await db.sql('USE DATABASE chinook.sqlite; SELECT albums.AlbumId as id, albums.Title as title, artists.name as artist FROM albums INNER JOIN artists WHERE artists.ArtistId = albums.ArtistId LIMIT 20;');
15+
const result =
16+
await db.sql('USE DATABASE chinook.sqlite; SELECT albums.AlbumId as id, albums.Title as title, artists.name as artist FROM albums INNER JOIN artists WHERE artists.ArtistId = albums.ArtistId LIMIT 20;');
1517

16-
setAlbums(result);
18+
setAlbums(result);
19+
} catch (error) {
20+
console.error(error);
21+
} finally {
22+
db?.close();
23+
}
1724
}
1825

1926
getAlbums();

package.json

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "@sqlitecloud/drivers",
3-
"version": "1.0.422",
3+
"version": "1.0.435",
44
"description": "SQLiteCloud drivers for Typescript/Javascript in edge, web and node clients",
55
"main": "./lib/index.js",
66
"types": "./lib/index.d.ts",

0 commit comments

Comments
 (0)