In version 1.2.0
, Bun has issues with executing concurrent statements, which may lead to errors if you try to run several queries simultaneously.
Weβve created a github issue that you can track. Once itβs fixed, you should no longer encounter any such errors on Bunβs SQL side
Get Started with Waddler and Bun:SQLite
This guide assumes familiarity with:
WARNING
Basic file structure
This is the basic file structure of the project.
π¦ <project root>
β π src
β β π index.ts
β π .env
β π package.json
β π tsconfig.json
Step 1 - Install required packages
npm
yarn
pnpm
bun
npm i waddler
npm i -D @types/bun
Step 2 - Setup connection variables
Create a .env
file in the root of your project and add your database connection variable:
DATABASE_URL=
Step 3 - Connect Waddler to the database
Create a index.ts
file in the src
directory and initialize the connection:
bun sql
bun sql with config
import 'dotenv/config';
import { waddler } from 'waddler/bun-sql';
const sql = waddler(process.env.DATABASE_URL!);
If you need to provide your existing driver:
import 'dotenv/config';
import { waddler } from 'waddler/bun-sql';
import { SQL } from 'bun';
const client = new SQL(process.env.DATABASE_URL!);
await client.connect();
const sql = waddler({ client });
Step 4 - Create a table
(async () => {
await sql.unsafe(`create table users (
id integer primary key generated always as identity,
name varchar(255) not null,
age integer not null,
email varchar(255) not null unique
);
`);
})()
Step 5 - Seed and Query the database
Letβs update the src/index.ts
file with queries to create, read, update, and delete users
import 'dotenv/config';
import { waddler } from 'waddler/bun-sql';
const sql = waddler(undefined);
async function main() {
const user = [
'John',
30,
'[email protected]',
];
await sql`insert into ${sql.identifier('users')} values ${sql.values([[sql.default, ...user]])};`;
console.log('New user created!')
const users = await sql`select * from ${sql.identifier('users')};`;
console.log('Getting all users from the database: ', users)
/*
const users: {
id: number;
name: string;
age: number;
email: string;
}[]
*/
await sql`update ${sql.identifier('users')} set age = ${31} where email = ${user[2]};`;
console.log('User info updated!')
await sql`delete from ${sql.identifier('users')} where email = ${user[2]};`;
console.log('User deleted!')
}
main();
Step 6 - Run index.ts file
To run a script with bun
, use the following command:
bun src/index.ts