Repository: nodejs/node
Pull request: sqlite: add getter to detect transactions

This commit adds an `isTransaction` getter to the `DatabaseSync` class for determining if the database is currently within a transaction.

Fixes: https://github.com/nodejs/node/issues/57922

<!--
Before submitting a pull request, please read:

- the CONTRIBUTING guide at https://github.com/nodejs/node/blob/HEAD/CONTRIBUTING.md
- the commit message formatting guidelines at
  https://github.com/nodejs/node/blob/HEAD/doc/contributing/pull-requests.md#commit-message-guidelines

For code changes:
1. Include tests for any bug fixes or new features.
2. Update documentation if relevant.
3. Ensure that `make -j4 test` (UNIX), or `vcbuild test` (Windows) passes.

If you believe this PR should be highlighted in the Node.js CHANGELOG
please add the `notable-change` label.

Developer's Certificate of Origin 1.1

By making a contribution to this project, I certify that:

(a) The contribution was created in whole or in part by me and I
    have the right to submit it under the open source license
    indicated in the file; or

(b) The contribution is based upon previous work that, to the best
    of my knowledge, is covered under an appropriate open source
    license and I have the right under that license to submit that
    work with modifications, whether created in whole or in part
    by me, under the same open source license (unless I am
    permitted to submit under a different license), as indicated
    in the file; or

(c) The contribution was provided directly to me by some other
    person who certified (a), (b) or (c) and I have not modified
    it.

(d) I understand and agree that this project and the contribution
    are public and that a record of the contribution (including all
    personal information I submit with it, including my sign-off) is
    maintained indefinitely and may be redistributed consistent with
    this project or the open source license(s) involved.
-->


Changed files:
filename: doc/api/sqlite.md
patch: @@ -291,6 +291,15 @@ added: v23.11.0
 
 * {boolean} Whether the database is currently open or not.
 
+### `database.isTransaction`
+
+<!-- YAML
+added: REPLACEME
+-->
+
+* {boolean} Whether the database is currently within a transaction. This method
+  is a wrapper around [`sqlite3_get_autocommit()`][].
+
 ### `database.open()`
 
 <!-- YAML
@@ -839,6 +848,7 @@ resolution handler passed to [`database.applyChangeset()`][]. See also
 [`sqlite3_create_window_function()`]: https://www.sqlite.org/c3ref/create_function.html
 [`sqlite3_exec()`]: https://www.sqlite.org/c3ref/exec.html
 [`sqlite3_expanded_sql()`]: https://www.sqlite.org/c3ref/expanded_sql.html
+[`sqlite3_get_autocommit()`]: https://sqlite.org/c3ref/get_autocommit.html
 [`sqlite3_last_insert_rowid()`]: https://www.sqlite.org/c3ref/last_insert_rowid.html
 [`sqlite3_load_extension()`]: https://www.sqlite.org/c3ref/load_extension.html
 [`sqlite3_prepare_v2()`]: https://www.sqlite.org/c3ref/prepare.html

filename: src/node_sqlite.cc
patch: @@ -979,6 +979,15 @@ void DatabaseSync::IsOpenGetter(const FunctionCallbackInfo<Value>& args) {
   args.GetReturnValue().Set(db->IsOpen());
 }
 
+void DatabaseSync::IsTransactionGetter(
+    const FunctionCallbackInfo<Value>& args) {
+  DatabaseSync* db;
+  ASSIGN_OR_RETURN_UNWRAP(&db, args.This());
+  Environment* env = Environment::GetCurrent(args);
+  THROW_AND_RETURN_ON_BAD_STATE(env, !db->IsOpen(), "database is not open");
+  args.GetReturnValue().Set(sqlite3_get_autocommit(db->connection_) == 0);
+}
+
 void DatabaseSync::Close(const FunctionCallbackInfo<Value>& args) {
   DatabaseSync* db;
   ASSIGN_OR_RETURN_UNWRAP(&db, args.This());
@@ -2623,6 +2632,10 @@ static void Initialize(Local<Object> target,
                           db_tmpl,
                           FIXED_ONE_BYTE_STRING(isolate, "isOpen"),
                           DatabaseSync::IsOpenGetter);
+  SetSideEffectFreeGetter(isolate,
+                          db_tmpl,
+                          FIXED_ONE_BYTE_STRING(isolate, "isTransaction"),
+                          DatabaseSync::IsTransactionGetter);
   SetConstructorFunction(context, target, "DatabaseSync", db_tmpl);
   SetConstructorFunction(context,
                          target,

filename: src/node_sqlite.h
patch: @@ -61,6 +61,8 @@ class DatabaseSync : public BaseObject {
   static void New(const v8::FunctionCallbackInfo<v8::Value>& args);
   static void Open(const v8::FunctionCallbackInfo<v8::Value>& args);
   static void IsOpenGetter(const v8::FunctionCallbackInfo<v8::Value>& args);
+  static void IsTransactionGetter(
+      const v8::FunctionCallbackInfo<v8::Value>& args);
   static void Close(const v8::FunctionCallbackInfo<v8::Value>& args);
   static void Prepare(const v8::FunctionCallbackInfo<v8::Value>& args);
   static void Exec(const v8::FunctionCallbackInfo<v8::Value>& args);

filename: test/parallel/test-sqlite-database-sync.js
patch: @@ -324,3 +324,40 @@ suite('DatabaseSync.prototype.exec()', () => {
     });
   });
 });
+
+suite('DatabaseSync.prototype.isTransaction', () => {
+  test('correctly detects a committed transaction', (t) => {
+    const db = new DatabaseSync(':memory:');
+
+    t.assert.strictEqual(db.isTransaction, false);
+    db.exec('BEGIN');
+    t.assert.strictEqual(db.isTransaction, true);
+    db.exec('CREATE TABLE foo (id INTEGER PRIMARY KEY)');
+    t.assert.strictEqual(db.isTransaction, true);
+    db.exec('COMMIT');
+    t.assert.strictEqual(db.isTransaction, false);
+  });
+
+  test('correctly detects a rolled back transaction', (t) => {
+    const db = new DatabaseSync(':memory:');
+
+    t.assert.strictEqual(db.isTransaction, false);
+    db.exec('BEGIN');
+    t.assert.strictEqual(db.isTransaction, true);
+    db.exec('CREATE TABLE foo (id INTEGER PRIMARY KEY)');
+    t.assert.strictEqual(db.isTransaction, true);
+    db.exec('ROLLBACK');
+    t.assert.strictEqual(db.isTransaction, false);
+  });
+
+  test('throws if database is not open', (t) => {
+    const db = new DatabaseSync(nextDb(), { open: false });
+
+    t.assert.throws(() => {
+      return db.isTransaction;
+    }, {
+      code: 'ERR_INVALID_STATE',
+      message: /database is not open/,
+    });
+  });
+});