Get Started with Waddler and Bun:SQLite

This guide assumes familiarity with:
  • bun - javaScript all-in-one toolkit - read here
  • bun:sqlite - native implementation of a high-performance SQLite3 driver - read here

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:

DB_FILE_NAME=
important

For example, if you want to create an SQLite database file in the root of your project for testing purposes, you can use this example:

DB_FILE_NAME=mydb.sqlite

Step 3 - Connect Waddler to the database

Create a index.ts file in the src directory and initialize the connection:

bun:sqlite
bun:sqlite with config
import 'dotenv/config';
import { waddler } from 'waddler/bun-sqlite';

const sql = waddler(process.env.DB_FILE_NAME!);
// You can also provide waddler with no value, an empty string, or ":memory:" to use an in-memory database.
// const sql = waddler();

If you need to provide your existing driver:

import 'dotenv/config';
import { waddler } from 'waddler/bun-sqlite';
import { Database } from 'bun:sqlite';

const client = new Database(process.env.DB_FILE_NAME!);
// You can also provide new Database constructor with no value, an empty string, or ":memory:" to use an in-memory database.
// const client = new Database();

const sql = waddler({ client });

Step 4 - Create a table

(async () => {
  await sql.unsafe(`create table if not exists users (
    id    integer primary key autoincrement,
    name  text    not null,
    age   integer not null,
    email text    not null unique
    );
  `).run();
})()

Step 5 - Seed and Query the database

Let’s update the src/index.ts file with queries to create, read, update, and delete users

src/index.ts
import 'dotenv/config';
import { waddler } from 'waddler/bun-sqlite';
  
const sql = waddler();

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