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
This is the basic file structure of the project.
π¦ <project root>
β π src
β β π index.ts
β π .env
β π package.json
β π tsconfig.json
npm i waddler
npm i -D @types/bun
Create a .env
file in the root of your project and add your database connection variable:
DB_FILE_NAME=
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
Create a index.ts
file in the src
directory and initialize the connection:
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 });
(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();
})()
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-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();
To run a script with bun
, use the following command:
bun src/index.ts