SQLite Bun: Transaction

Summary: in this tutorial, you will learn how to perform a transaction in an SQLite database using Bun.

Transactions allow you to execute multiple queries such that either all of them succeed or none do. In Bun, you use transaction() method of the Database object to create a transaction.

Creating tables

Step 1. Open your terminal and navigate to the project directory.

Step 2. Connect to the pub.db database using the sqlite3 shell.

Step 3. Create the books and book_authors tables:

CREATE TABLE books (
   id INTEGER PRIMARY KEY,
   title TEXT NOT NULL,
   isbn TEXT NOT NULL,
   publishedYear DATE NOT NULL
);

CREATE TABLE book_authors(
   bookId INTEGER,
   authorId INTEGER,
   PRIMARY KEY(bookId, authorId),
   FOREIGN KEY(bookId) REFERENCES books(id) ON DELETE CASCADE ON UPDATE CASCADE,
   FOREIGN KEY(authorId) REFERENCES authors(id) ON DELETE CASCADE ON UPDATE CASCADE
);Code language: SQL (Structured Query Language) (sql)

Here’s the updated database diagram: