human (Oct 15, 2024, 11:28 AM)
Based on this documentation, build me an artifact (no react) that loads the SQLite thing from a CDN and creates an in-memory SQLite database with an exciting example table relating to pelican sightings populated with some made up data for Half Moon Bay, California and then provides a textarea with a submit button where I can type in a SQL query where clicking the button will execute it and render a nicely styled mobile friendly HTML table with the results
paste.txt
@sqlite.org/sqlite-wasm - npm
===============
skip to:[content](https://www.npmjs.com/package/@sqlite.org/sqlite-wasm#main)[package search](https://www.npmjs.com/package/@sqlite.org/sqlite-wasm#search)[sign in](https://www.npmjs.com/package/@sqlite.org/sqlite-wasm#signin)
❤
* [Pro](https://www.npmjs.com/products/pro)
* [Teams](https://www.npmjs.com/products/teams)
* [Pricing](https://www.npmjs.com/products)
* [Documentation](https://docs.npmjs.com/)
npm
[](https://www.npmjs.com/)
Search
[Sign Up](https://www.npmjs.com/signup)[Sign In](https://www.npmjs.com/login)
@sqlite.org/sqlite-wasm

=============================================================================================================================================================================================
3.46.1-build4 • Public • Published a day ago
* [Readme](https://www.npmjs.com/package/@sqlite.org/sqlite-wasm?activeTab=readme)
* [Code Beta](https://www.npmjs.com/package/@sqlite.org/sqlite-wasm?activeTab=code)
* [0 Dependencies](https://www.npmjs.com/package/@sqlite.org/sqlite-wasm?activeTab=dependencies)
* [18 Dependents](https://www.npmjs.com/package/@sqlite.org/sqlite-wasm?activeTab=dependents)
* [52 Versions](https://www.npmjs.com/package/@sqlite.org/sqlite-wasm?activeTab=versions)
SQLite Wasm
===========
[](https://www.npmjs.com/package/@sqlite.org/sqlite-wasm#sqlite-wasm)
SQLite Wasm conveniently wrapped as an ES Module.
> \[!Warning\]
>
> This project wraps the code of [SQLite Wasm](https://sqlite.org/wasm/doc/trunk/index.md) with _no_ changes, apart from added TypeScript types. Please do _not_ file issues or feature requests regarding the underlying SQLite Wasm code here. Instead, please follow the [SQLite bug filing instructions](https://www.sqlite.org/src/wiki?name=Bug+Reports). Filing TypeScript type related issues and feature requests is fine.
Installation
------------
[](https://www.npmjs.com/package/@sqlite.org/sqlite-wasm#installation)
npm install @sqlite.org/sqlite-wasm
Usage
-----
[](https://www.npmjs.com/package/@sqlite.org/sqlite-wasm#usage)
There are three ways to use SQLite Wasm:
* [in the main thread with a wrapped worker](https://www.npmjs.com/package/@sqlite.org/sqlite-wasm#in-a-wrapped-worker-with-opfs-if-available) (🏆 preferred option)
* [in a worker](https://www.npmjs.com/package/@sqlite.org/sqlite-wasm#in-a-worker-with-opfs-if-available)
* [in the main thread](https://www.npmjs.com/package/@sqlite.org/sqlite-wasm#in-the-main-thread-without-opfs)
Only the worker versions allow you to use the origin private file system (OPFS) storage back-end.
### In a wrapped worker (with OPFS if available):
[](https://www.npmjs.com/package/@sqlite.org/sqlite-wasm#in-a-wrapped-worker-with-opfs-if-available)
> \[!Warning\]
>
> For this to work, you need to set the following headers on your server:
>
> `Cross-Origin-Opener-Policy: same-origin`
>
> `Cross-Origin-Embedder-Policy: require-corp`
import { sqlite3Worker1Promiser } from '@sqlite.org/sqlite-wasm';
const log \= console.log;
const error \= console.error;
const initializeSQLite \= async () \=\> {
try {
log('Loading and initializing SQLite3 module...');
const promiser \= await new Promise((resolve) \=\> {
const \_promiser \= sqlite3Worker1Promiser({
onready: () \=\> resolve(\_promiser),
});
});
log('Done initializing. Running demo...');
const configResponse \= await promiser('config-get', {});
log('Running SQLite3 version', configResponse.result.version.libVersion);
const openResponse \= await promiser('open', {
filename: 'file:mydb.sqlite3?vfs=opfs',
});
const { dbId } \= openResponse;
log(
'OPFS is available, created persisted database at',
openResponse.result.filename.replace(/^file:(.\*?)\\?vfs=opfs$/, '$1'),
);
// Your SQLite code here.
} catch (err) {
if (!(err instanceof Error)) {
err \= new Error(err.result.message);
}
error(err.name, err.message);
}
};
initializeSQLite();
The `promiser` object above implements the [Worker1 API](https://sqlite.org/wasm/doc/trunk/api-worker1.md#worker1-methods).
### In a worker (with OPFS if available):
[](https://www.npmjs.com/package/@sqlite.org/sqlite-wasm#in-a-worker-with-opfs-if-available)
> \[!Warning\]
>
> For this to work, you need to set the following headers on your server:
>
> `Cross-Origin-Opener-Policy: same-origin`
>
> `Cross-Origin-Embedder-Policy: require-corp`
// In \`main.js\`.
const worker \= new Worker('worker.js', { type: 'module' });
// In \`worker.js\`.
import sqlite3InitModule from '@sqlite.org/sqlite-wasm';
const log \= console.log;
const error \= console.error;
const start \= (sqlite3) \=\> {
log('Running SQLite3 version', sqlite3.version.libVersion);
const db \=
'opfs' in sqlite3
? new sqlite3.oo1.OpfsDb('/mydb.sqlite3')
: new sqlite3.oo1.DB('/mydb.sqlite3', 'ct');
log(
'opfs' in sqlite3
? \`OPFS is available, created persisted database at ${db.filename}\`
: \`OPFS is not available, created transient database ${db.filename}\`,
);
// Your SQLite code here.
};
const initializeSQLite \= async () \=\> {
try {
log('Loading and initializing SQLite3 module...');
const sqlite3 \= await sqlite3InitModule({ print: log, printErr: error });
log('Done initializing. Running demo...');
start(sqlite3);
} catch (err) {
error('Initialization error:', err.name, err.message);
}
};
initializeSQLite();
The `db` object above implements the [Object Oriented API #1](https://sqlite.org/wasm/doc/trunk/api-oo1.md).
### In the main thread (without OPFS):
[](https://www.npmjs.com/package/@sqlite.org/sqlite-wasm#in-the-main-thread-without-opfs)
import sqlite3InitModule from '@sqlite.org/sqlite-wasm';
const log \= console.log;
const error \= console.error;
const start \= (sqlite3) \=\> {
log('Running SQLite3 version', sqlite3.version.libVersion);
const db \= new sqlite3.oo1.DB('/mydb.sqlite3', 'ct');
// Your SQLite code here.
};
const initializeSQLite \= async () \=\> {
try {
log('Loading and initializing SQLite3 module...');
const sqlite3 \= await sqlite3InitModule({
print: log,
printErr: error,
});
log('Done initializing. Running demo...');
start(sqlite3);
} catch (err) {
error('Initialization error:', err.name, err.message);
}
};
initializeSQLite();
The `db` object above implements the [Object Oriented API #1](https://sqlite.org/wasm/doc/trunk/api-oo1.md).
Usage with vite
---------------
[](https://www.npmjs.com/package/@sqlite.org/sqlite-wasm#usage-with-vite)
If you are using [vite](https://vitejs.dev/), you need to add the following config option in `vite.config.js`:
import { defineConfig } from 'vite';
export default defineConfig({
server: {
headers: {
'Cross-Origin-Opener-Policy': 'same-origin',
'Cross-Origin-Embedder-Policy': 'require-corp',
},
},
optimizeDeps: {
exclude: \['@sqlite.org/sqlite-wasm'\],
},
});
Check out a [sample project](https://stackblitz.com/edit/vitejs-vite-ttrbwh?file=main.js) that shows this in action.
Demo
----
[](https://www.npmjs.com/package/@sqlite.org/sqlite-wasm#demo)
See the [demo](https://github.com/sqlite/sqlite-wasm/tree/main/demo) folder for examples of how to use this in the main thread and in a worker. (Note that the worker variant requires special HTTP headers, so it can't be hosted on GitHub Pages.) An example that shows how to use this with vite is available on [StackBlitz](https://stackblitz.com/edit/vitejs-vite-ttrbwh?file=main.js).
Projects using this package
---------------------------
[](https://www.npmjs.com/package/@sqlite.org/sqlite-wasm#projects-using-this-package)
See the list of [npm dependents](https://www.npmjs.com/browse/depended/@sqlite.org/sqlite-wasm) for this package.
Deploying a new version
-----------------------
[](https://www.npmjs.com/package/@sqlite.org/sqlite-wasm#deploying-a-new-version)
(These steps can only be executed by maintainers.)
1. Update the version number in `package.json` reflecting the current [SQLite version number](https://sqlite.org/download.html) and add a build identifier suffix like `-build1`. The complete version number should read something like `3.41.2-build1`.
2. Run `npm run build` to build the ES Module. This downloads the latest SQLite Wasm binary and builds the ES Module.
3. Run `npm run deploy` to commit the changes, push to GitHub, and publish the new version to npm.
License
-------
[](https://www.npmjs.com/package/@sqlite.org/sqlite-wasm#license)
Apache 2.0.
Acknowledgements
----------------
[](https://www.npmjs.com/package/@sqlite.org/sqlite-wasm#acknowledgements)
This project is based on [SQLite Wasm](https://sqlite.org/wasm), which it conveniently wraps as an ES Module and publishes to npm as [`@sqlite.org/sqlite-wasm`](https://www.npmjs.com/package/@sqlite.org/sqlite-wasm).
Readme
------
### Keywords
* [sqlite](https://www.npmjs.com/search?q=keywords:sqlite)
* [sqlite3](https://www.npmjs.com/search?q=keywords:sqlite3)
* [sqlite-wasm](https://www.npmjs.com/search?q=keywords:sqlite-wasm)
* [sqlite3-wasm](https://www.npmjs.com/search?q=keywords:sqlite3-wasm)
* [webassembly](https://www.npmjs.com/search?q=keywords:webassembly)
* [wasm](https://www.npmjs.com/search?q=keywords:wasm)
* [esm](https://www.npmjs.com/search?q=keywords:esm)
* [opfs](https://www.npmjs.com/search?q=keywords:opfs)
* [origin-private-file-system](https://www.npmjs.com/search?q=keywords:origin-private-file-system)
Package Sidebar
---------------
### Install
`npm i @sqlite.org/sqlite-wasm`
### Repository
[github.com/sqlite/sqlite-wasm](https://github.com/sqlite/sqlite-wasm)
### Homepage
[github.com/sqlite/sqlite-wasm#readme](https://github.com/sqlite/sqlite-wasm#readme)
### Weekly Downloads
6,901
### Version
3.46.1-build4
### License
Apache-2.0
### Unpacked Size
3.13 MB
### Total Files
15
### Issues
[1](https://github.com/sqlite/sqlite-wasm/issues)
### Pull Requests
[2](https://github.com/sqlite/sqlite-wasm/pulls)
### Last publish
a day ago
### Collaborators
* [](https://www.npmjs.com/~sgbeal)
* [](https://www.npmjs.com/~tomayac)
[**Try** on RunKit](https://runkit.com/npm/%40sqlite.org%2Fsqlite-wasm)
[**Report** malware](https://www.npmjs.com/support?inquire=security&security-inquire=malware&package=%40sqlite.org%2Fsqlite-wasm&version=3.46.1-build4)
Footer
------
[](https://github.com/npm)
[](https://github.com/)
### Support
* [Help](https://docs.npmjs.com/)
* [Advisories](https://github.com/advisories)
* [Status](http://status.npmjs.org/)
* [Contact npm](https://www.npmjs.com/support)
### Company
* [About](https://www.npmjs.com/about)
* [Blog](https://github.blog/tag/npm/)
* [Press](https://www.npmjs.com/press)
### Terms & Policies
* [Policies](https://www.npmjs.com/policies/)
* [Terms of Use](https://www.npmjs.com/policies/terms)
* [Code of Conduct](https://www.npmjs.com/policies/conduct)
* [Privacy](https://www.npmjs.com/policies/privacy)
assistant (Oct 15, 2024, 11:28 AM)
Certainly! I'll create an HTML artifact that loads SQLite from a CDN, sets up an in-memory database with a pelican sightings table, and provides a UI for executing SQL queries. Here's the implementation:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Pelican Sightings Query Tool</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/sql.js/1.8.0/sql-wasm.js"></script>
<style>
body {
font-family: Arial, sans-serif;
max-width: 800px;
margin: 0 auto;
padding: 20px;
line-height: 1.6;
}
textarea {
width: 100%;
height: 100px;
margin-bottom: 10px;
}
button {
background-color: #4CAF50;
border: none;
color: white;
padding: 10px 20px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin: 4px 2px;
cursor: pointer;
}
table {
border-collapse: collapse;
width: 100%;
margin-top: 20px;
}
th, td {
border: 1px solid #ddd;
padding: 8px;
text-align: left;
}
th {
background-color: #4CAF50;
color: white;
}
tr:nth-child(even) {
background-color: #f2f2f2;
}
</style>
</head>
<body>
<h1>Pelican Sightings in Half Moon Bay</h1>
<textarea id="query" placeholder="Enter your SQL query here...">SELECT * FROM pelican_sightings;</textarea>
<button onclick="executeQuery()">Execute Query</button>
<div id="result"></div>
<script>
let db;
initSqlJs({ locateFile: file => `https://cdnjs.cloudflare.com/ajax/libs/sql.js/1.8.0/${file}` }).then(function(SQL) {
db = new SQL.Database();
db.run(`
CREATE TABLE pelican_sightings (
id INTEGER PRIMARY KEY,
date TEXT,
location TEXT,
species TEXT,
count INTEGER
);
INSERT INTO pelican_sightings (date, location, species, count) VALUES
('2024-10-01', 'Miramar Beach', 'Brown Pelican', 12),
('2024-10-02', 'Pillar Point Harbor', 'California Brown Pelican', 8),
('2024-10-03', 'Half Moon Bay State Beach', 'American White Pelican', 3),
('2024-10-04', 'Dunes Beach', 'Brown Pelican', 15),
('2024-10-05', 'Poplar Beach', 'California Brown Pelican', 10);
`);
});
function executeQuery() {
const query = document.getElementById('query').value;
try {
const results = db.exec(query);
displayResults(results);
} catch (err) {
document.getElementById('result').innerHTML = `<p>Error: ${err.message}</p>`;
}
}
function displayResults(results) {
if (results.length === 0) {
document.getElementById('result').innerHTML = '<p>No results.</p>';
return;
}
let tableHtml = '<table><tr>';
results[0].columns.forEach(column => {
tableHtml += `<th>${column}</th>`;
});
tableHtml += '</tr>';
results[0].values.forEach(row => {
tableHtml += '<tr>';
row.forEach(cell => {
tableHtml += `<td>${cell}</td>`;
});
tableHtml += '</tr>';
});
tableHtml += '</table>';
document.getElementById('result').innerHTML = tableHtml;
}
</script>
</body>
</html>
This HTML file creates a simple web page that loads SQLite from a CDN, sets up an in-memory database with a pelican_sightings
table, and provides a textarea for entering SQL queries. Here's a breakdown of what it does:
- It loads the SQL.js library from a CDN.
- It creates a styled layout with a textarea for queries and a button to execute them.
- It initializes an SQLite database in memory and creates a
pelican_sightings
table with some sample data. - When the "Execute Query" button is clicked, it runs the SQL query entered in the textarea.
- The results are displayed in a nicely styled, mobile-friendly HTML table below the input area.
You can copy this HTML into a file and open it in a web browser to use the Pelican Sightings Query Tool. By default, it will display all records in the table. You can modify the query to filter, sort, or aggregate the data as needed.
For example, you could try these queries:
SELECT species, SUM(count) as total FROM pelican_sightings GROUP BY species;
SELECT * FROM pelican_sightings WHERE count > 10;
SELECT date, location, count FROM pelican_sightings ORDER BY count DESC LIMIT 3;
Feel free to ask if you'd like any modifications or explanations about this implementation!
human (Oct 15, 2024, 11:30 AM)
Error: db is undefined.
It should use the npm https://www.npmjs.com/package/@sqlite.org/sqlite-wasm package based on the docs I showed you, pick a CDN that can deliver those files
assistant (Oct 15, 2024, 11:30 AM)
I apologize for the confusion. You're right, and I should have used the package from the documentation you provided. Let's correct this and use the @sqlite.org/sqlite-wasm
package. We'll use jsDelivr as our CDN to deliver the files.
Here's the corrected and improved version:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Pelican Sightings Query Tool</title>
<script src="https://cdn.jsdelivr.net/npm/@sqlite.org/sqlite-wasm@3.46.1-build4/sqlite-wasm/jswasm/sqlite3.mjs" type="module"></script>
<style>
body {
font-family: Arial, sans-serif;
max-width: 800px;
margin: 0 auto;
padding: 20px;
line-height: 1.6;
}
textarea {
width: 100%;
height: 100px;
margin-bottom: 10px;
}
button {
background-color: #4CAF50;
border: none;
color: white;
padding: 10px 20px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin: 4px 2px;
cursor: pointer;
}
table {
border-collapse: collapse;
width: 100%;
margin-top: 20px;
}
th, td {
border: 1px solid #ddd;
padding: 8px;
text-align: left;
}
th {
background-color: #4CAF50;
color: white;
}
tr:nth-child(even) {
background-color: #f2f2f2;
}
</style>
</head>
<body>
<h1>Pelican Sightings in Half Moon Bay</h1>
<textarea id="query" placeholder="Enter your SQL query here...">SELECT * FROM pelican_sightings;</textarea>
<button onclick="executeQuery()">Execute Query</button>
<div id="result"></div>
<script type="module">
import sqlite3InitModule from 'https://cdn.jsdelivr.net/npm/@sqlite.org/sqlite-wasm@3.46.1-build4/sqlite-wasm/jswasm/sqlite3.mjs';
let db;
const initializeSQLite = async () => {
try {
const sqlite3 = await sqlite3InitModule({
print: console.log,
printErr: console.error,
});
console.log('Running SQLite version', sqlite3.version.libVersion);
db = new sqlite3.oo1.DB();
db.exec(`
CREATE TABLE pelican_sightings (
id INTEGER PRIMARY KEY,
date TEXT,
location TEXT,
species TEXT,
count INTEGER
);
INSERT INTO pelican_sightings (date, location, species, count) VALUES
('2024-10-01', 'Miramar Beach', 'Brown Pelican', 12),
('2024-10-02', 'Pillar Point Harbor', 'California Brown Pelican', 8),
('2024-10-03', 'Half Moon Bay State Beach', 'American White Pelican', 3),
('2024-10-04', 'Dunes Beach', 'Brown Pelican', 15),
('2024-10-05', 'Poplar Beach', 'California Brown Pelican', 10);
`);
console.log('Database initialized with sample data');
} catch (err) {
console.error('Initialization error:', err.message);
}
};
initializeSQLite();
window.executeQuery = () => {
const query = document.getElementById('query').value;
try {
const results = db.exec(query);
displayResults(results);
} catch (err) {
document.getElementById('result').innerHTML = `<p>Error: ${err.message}</p>`;
}
};
function displayResults(results) {
if (results.length === 0) {
document.getElementById('result').innerHTML = '<p>No results.</p>';
return;
}
let tableHtml = '<table><tr>';
results[0].columns.forEach(column => {
tableHtml += `<th>${column}</th>`;
});
tableHtml += '</tr>';
results[0].values.forEach(row => {
tableHtml += '<tr>';
row.forEach(cell => {
tableHtml += `<td>${cell}</td>`;
});
tableHtml += '</tr>';
});
tableHtml += '</table>';
document.getElementById('result').innerHTML = tableHtml;
}
</script>
</body>
</html>
This updated version uses the @sqlite.org/sqlite-wasm
package from jsDelivr CDN. Here are the key changes and improvements:
- We're now using the correct SQLite Wasm package as specified in the documentation you provided.
- The script is now a module, which is required for importing the SQLite Wasm module.
- We initialize the SQLite database asynchronously in the
initializeSQLite
function. - The database operations now use the Object Oriented API #1 (
oo1
) as mentioned in the documentation. - Error handling has been improved throughout the script.
To use this updated version:
- Copy the HTML into a file (e.g.,
index.html
). - Serve the file from a web server. Due to CORS restrictions, you can't just open the file directly in a browser.
- Open the page in a web browser that supports WebAssembly.
You can then use the textarea to enter SQL queries and execute them against the in-memory SQLite database containing the pelican sightings data.
Here are some example queries you can try:
SELECT species, SUM(count) as total FROM pelican_sightings GROUP BY species;
SELECT * FROM pelican_sightings WHERE count > 10;
SELECT date, location, count FROM pelican_sightings ORDER BY count DESC LIMIT 3;
This implementation should work correctly with the @sqlite.org/sqlite-wasm
package. Let me know if you need any further modifications or explanations!
human (Oct 15, 2024, 11:30 AM)
Error: db is undefined
assistant (Oct 15, 2024, 11:30 AM)
I apologize for the persistent error. You're right, and I see the issue now. The problem is that the executeQuery
function is being called before the database initialization is complete. Let's fix this by implementing a proper asynchronous flow and adding a loading state. Here's the corrected version:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Pelican Sightings Query Tool</title>
<script src="https://cdn.jsdelivr.net/npm/@sqlite.org/sqlite-wasm@3.46.1-build4/sqlite-wasm/jswasm/sqlite3.mjs" type="module"></script>
<style>
body {
font-family: Arial, sans-serif;
max-width: 800px;
margin: 0 auto;
padding: 20px;
line-height: 1.6;
}
textarea {
width: 100%;
height: 100px;
margin-bottom: 10px;
}
button {
background-color: #4CAF50;
border: none;
color: white;
padding: 10px 20px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin: 4px 2px;
cursor: pointer;
}
button:disabled {
background-color: #cccccc;
cursor: not-allowed;
}
table {
border-collapse: collapse;
width: 100%;
margin-top: 20px;
}
th, td {
border: 1px solid #ddd;
padding: 8px;
text-align: left;
}
th {
background-color: #4CAF50;
color: white;
}
tr:nth-child(even) {
background-color: #f2f2f2;
}
#loading {
display: none;
color: #4CAF50;
font-weight: bold;
}
</style>
</head>
<body>
<h1>Pelican Sightings in Half Moon Bay</h1>
<div id="loading">Loading SQLite and initializing database...</div>
<textarea id="query" placeholder="Enter your SQL query here...">SELECT * FROM pelican_sightings;</textarea>
<button id="executeButton" onclick="executeQuery()" disabled>Execute Query</button>
<div id="result"></div>
<script type="module">
import sqlite3InitModule from 'https://cdn.jsdelivr.net/npm/@sqlite.org/sqlite-wasm@3.46.1-build4/sqlite-wasm/jswasm/sqlite3.mjs';
let db;
const loadingElement = document.getElementById('loading');
const executeButton = document.getElementById('executeButton');
const initializeSQLite = async () => {
loadingElement.style.display = 'block';
try {
const sqlite3 = await sqlite3InitModule({
print: console.log,
printErr: console.error,
});
console.log('Running SQLite version', sqlite3.version.libVersion);
db = new sqlite3.oo1.DB();
db.exec(`
CREATE TABLE pelican_sightings (
id INTEGER PRIMARY KEY,
date TEXT,
location TEXT,
species TEXT,
count INTEGER
);
INSERT INTO pelican_sightings (date, location, species, count) VALUES
('2024-10-01', 'Miramar Beach', 'Brown Pelican', 12),
('2024-10-02', 'Pillar Point Harbor', 'California Brown Pelican', 8),
('2024-10-03', 'Half Moon Bay State Beach', 'American White Pelican', 3),
('2024-10-04', 'Dunes Beach', 'Brown Pelican', 15),
('2024-10-05', 'Poplar Beach', 'California Brown Pelican', 10);
`);
console.log('Database initialized with sample data');
executeButton.disabled = false;
} catch (err) {
console.error('Initialization error:', err.message);
document.getElementById('result').innerHTML = `<p>Error initializing database: ${err.message}</p>`;
} finally {
loadingElement.style.display = 'none';
}
};
initializeSQLite();
window.executeQuery = () => {
const query = document.getElementById('query').value;
try {
const results = db.exec(query);
displayResults(results);
} catch (err) {
document.getElementById('result').innerHTML = `<p>Error: ${err.message}</p>`;
}
};
function displayResults(results) {
if (results.length === 0) {
document.getElementById('result').innerHTML = '<p>No results.</p>';
return;
}
let tableHtml = '<table><tr>';
results[0].columns.forEach(column => {
tableHtml += `<th>${column}</th>`;
});
tableHtml += '</tr>';
results[0].values.forEach(row => {
tableHtml += '<tr>';
row.forEach(cell => {
tableHtml += `<td>${cell}</td>`;
});
tableHtml += '</tr>';
});
tableHtml += '</table>';
document.getElementById('result').innerHTML = tableHtml;
}
</script>
</body>
</html>
Key improvements in this version:
- Added a loading message that displays while SQLite is being initialized.
- The "Execute Query" button is disabled until the database is fully initialized.
- Improved error handling to show database initialization errors to the user.
- The
initializeSQLite
function now properly manages the loading state and button enablement.
To use this updated version:
- Copy the HTML into a file (e.g.,
index.html
). - Serve the file from a web server. Due to CORS restrictions, you can't just open the file directly in a browser.
- Open the page in a web browser that supports WebAssembly.
When you load the page, you'll see a loading message while SQLite initializes. Once it's ready, the "Execute Query" button will be enabled, and you can start running queries.
This implementation should resolve the "db is undefined" error and provide a better user experience. The database will be properly initialized before any queries can be executed.
You can try the same example queries as before:
SELECT species, SUM(count) as total FROM pelican_sightings GROUP BY species;
SELECT * FROM pelican_sightings WHERE count > 10;
SELECT date, location, count FROM pelican_sightings ORDER BY count DESC LIMIT 3;
Let me know if you encounter any further issues or if you need any additional modifications!
This didn't work. I had to fix the code to use
selectObjects
like this: