Skip to content

Close database connections referenced in transaction. #310

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 11 additions & 8 deletions examples/transactions/index.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -16,33 +16,36 @@ await client.batch(
const names = ["John Doe", "Mary Smith", "Alice Jones", "Mark Taylor"];

let transaction, secondTransaction;
try {
transaction = await client.transaction("write");

transaction = await client.transaction("write");
try{
for (const name of names) {
await transaction.execute({
sql: "INSERT INTO users (name) VALUES (?)",
args: [name],
});
}
await transaction.rollback();
}finally {
secondTransaction?.close();
}

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

secondTransaction = await client.transaction("write");
try{
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();
await secondTransaction.rollback();
}finally {
secondTransaction?.close();
}


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

console.log("Users:", result.rows);
17 changes: 15 additions & 2 deletions packages/libsql-client/src/sqlite3.ts
Original file line number Diff line number Diff line change
Expand Up @@ -247,11 +247,13 @@ export class Sqlite3Client implements Client {
export class Sqlite3Transaction implements Transaction {
#database: Database.Database;
#intMode: IntMode;
#dbClosed: boolean;

/** @private */
constructor(database: Database.Database, intMode: IntMode) {
this.#database = database;
this.#intMode = intMode;
this.#dbClosed = false;
}

async execute(stmt: InStatement): Promise<ResultSet>;
Expand Down Expand Up @@ -307,8 +309,19 @@ export class Sqlite3Transaction implements Transaction {
}

close(): void {
if (this.#database.inTransaction) {
executeStmt(this.#database, "ROLLBACK", this.#intMode);
try {
if (this.#database.inTransaction) {
executeStmt(this.#database, "ROLLBACK", this.#intMode);
}
} finally {
this.#dbClose();
}
}

#dbClose(): void {
if (!this.#dbClosed) {
this.#dbClosed = true;
this.#database.close();
}
}

Expand Down