Skip to content

Commit

Permalink
Add transaction example
Browse files Browse the repository at this point in the history
  • Loading branch information
giovannibenussi committed Oct 16, 2024
1 parent 77aca8a commit 5a314e7
Show file tree
Hide file tree
Showing 5 changed files with 436 additions and 0 deletions.
1 change: 1 addition & 0 deletions examples/transactions/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
local.db
27 changes: 27 additions & 0 deletions examples/transactions/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# Local

This example demonstrates how to use transactions with libSQL.

## Install Dependencies

```bash
npm i
```

## Running

Execute the example:

```bash
node index.mjs
```

This example will:

1. Create a new table called `users`.
2. Start a transaction.
3. Insert multiple users within the transaction.
4. Demonstrate how to rollback a transaction.
5. Start another transaction.
6. Insert more users and commit the transaction.
7. Query and display the final state of the `users` table.
47 changes: 47 additions & 0 deletions examples/transactions/index.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import { createClient } from "@libsql/client";

const client = createClient({
url: "file:local.db",
});

await client.batch(
[
"DROP TABLE IF EXISTS users",
"CREATE TABLE users (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)",
"INSERT INTO users (name) VALUES ('Iku Turso')",
],
"write",
);

const names = ["John Doe", "Mary Smith", "Alice Jones", "Mark Taylor"];

try {
const transaction = await client.transaction("write");

for (const name of names) {
await transaction.execute({
sql: "INSERT INTO users (name) VALUES (?)",
args: [name],
});
}
await transaction.rollback();

const secondTransaction = await client.transaction("write");

for (const name of names) {
await secondTransaction.execute({
sql: "INSERT INTO users (name) VALUES (?)",
args: [name],
});
}

await secondTransaction.commit();
} catch (e) {
console.error(e);
await transaction.rollback();
await secondTransaction.rollback();
}

const result = await client.execute("SELECT * FROM users");

console.log("Users:", result.rows);
Loading

0 comments on commit 5a314e7

Please sign in to comment.