Can SQLite and SQL Server share the same data access code?

May 14, 2025

When an administrator clicks “Delete user,” the backend has to change two tables. One stores users; the other stores their permissions. If clearing the permissions succeeds but deleting the user fails, the page will still show an account that has lost all its permissions. When I added a SQL Server backend to my asset management tool, I wanted the same rule as in the SQLite version: both deletes take effect together, and if either fails, undo any changes already made. Databases call such a group of operations a transaction.1

This business logic can be shared. To produce the same result on both databases, the driver has to answer two questions for it: are the two statements still in the same transaction, and how many users did the last statement actually delete?

Which DELETE result counts?

Suppose user 42 has never been assigned any permissions. It's perfectly normal for zero rows in the permissions table to match the first delete. The second delete should match one row in the users table. Only when the administrator tries again should the second delete return zero rows. For this endpoint, I want the first attempt to succeed and the second to return 404, telling the caller the user no longer exists.1

Extracting that rule might look like the following. This is an example interface adapted from the project requirements. By convention here, withTransaction commits after the callback returns normally and rolls back on an exception. It only passes the result or exception to its caller after the transaction has finished.

class UserNotFound extends Error {}

async function deleteUser(store, userId) {
  await store.withTransaction(async (tx) => {
    await tx.deletePrivileges(userId);
    const deletedUsers = await tx.deleteUserRow(userId);
    if (deletedUsers === 0) {
      throw new UserNotFound();
    }
  });
}

The route only needs to map UserNotFound to 404 and report success once deleteUser returns normally. If deleting a user later requires cleaning up another related table, that step can join the same callback. The tx passed to the callback uses only the connection acquired for the transaction, so the caller needn't know which driver is underneath.

What does each driver have to do?

Here's the same delete operation in two Node.js drivers. Binding a parameter means handing the user ID to the driver as a separate value so that the same statement can handle different users.1234

OperationSQLite (node-sqlite3)SQL Server (node-mssql)
Put both deletes in one transactionExecute BEGIN, both deletes, and COMMIT on the same connection. On failure execute ROLLBACK on that connection.Create a sql.Transaction from the pool and call begin(). Create a request() from that transaction for each delete, and finish with commit() or rollback().
Supply an ID to a deleteUse WHERE user_id = ? in SQL and bind the parameter array [userId].Use WHERE user_id = @userId and call .input('userId', userId) on the request.
Read the number of users deletedRead this.changes in the ordinary function callback for this db.run().In the same SQL batch, the project immediately executes SELECT @@ROWCOUNT AS count, then reads result.recordset[0].count.

There's an easy-to-miss condition on the SQLite side. If all requests share one connection, request A might execute BEGIN and wait for the next callback while request B submits a statement on that same connection. To keep the transaction exclusive to A, queue other requests until the whole transaction finishes, or lend A a dedicated connection and return it after commit or rollback. The SQL Server driver documentation states its contract directly: “all your requests are executed on one connection”. After begin(), the transaction holds one pooled connection and subsequent statements must create their requests through that transaction. Both drivers can provide the same guarantee to the layer above.3 Why two SQLite requests can collide in the same transaction

How do we know both implementations mean the same thing by a successful deletion?

I'd give both backends the same initial data and check three outcomes. A user with no permissions should still be deleted successfully. Deleting the same ID again should return 404. If the second delete fails, both the user and the original permissions should remain. For the last case, query both tables again. Seeing an error from the API doesn't tell you whether the first delete was undone.

I reran the old controller with sqlite3@5.1.7 and an in-memory database. Deleting the same ID twice returned success both times. The second DELETE already used an ordinary function callback, but its condition was self.changes === 0. Here self refers to the controller, whereas the driver supplies the row count on the statement object, this, inside the callback. The second delete really affected zero rows, but the code skipped the 404 branch. With the driver's return normalized to deletedUsers as above, that detail needs handling only once in the SQLite implementation.12

The SQL Server version explicitly rolls back and returns 404 when the user row count is zero. It also illustrates a step worth handling separately: after committing, it queried the permissions table again for logging. In this version, a logging query error would enter the transaction failure path, even though the deletion was already committed and rollback was too late. In a shared interface, I'd end the delete operation at successful commit and give the logging query its own error handling.1

Which layer did I actually share at the time?

AssetMan shared the Express routes. On startup the service selected either a SQLite or SQL Server controller based on DB_TYPE. When an administrator called DELETE /user/:id, either way the route called controller.deleteUser(req, res). This preserved the frontend and authorization interface and let both implementations keep their familiar driver patterns during the port. The cost was concrete: when I added user permissions later, both controllers needed a permission cleanup step and separate handling for 404s and rollbacks. On May 14 I committed a change specifically to bring the two into line. On May 21 the backend removed the MSSQL implementation.516

If I had to maintain both for the long term, I'd start by sharing the delete sequence above and leaving parameter binding, connections, and row counts to the drivers. Another option is an object-relational mapper (ORM) supporting both databases, which supplies transaction and delete interfaces. Take Prisma, which I researched: the business code calls only the generated client. What connects to SQLite or SQL Server underneath and whether the application must install another driver depends on the Prisma version and configuration. There's a concrete example in the Prisma section of my local database comparison.

When choosing, actually run the “zero permissions, one user” and “second delete fails” cases. They tell you more than checking a support matrix. If your input is already a collection of Oracle SQL statements, the question is instead how to translate existing queries into statements the target database can execute. See How can existing Oracle SQL be converted to MySQL?

Footnotes

  1. CaiBorui [S2thend]. (2025, May 14). Sync implementations of MS SQL Server controller with SQLite controllers [Git commit 197c6ba]. GitHub. SQLite deleteUser · SQL Server deleteUser. ↩ ↩2 ↩3 ↩4 ↩5 ↩6

  2. node-sqlite3 contributors. (n.d.). API, Database#run, callback. GitHub Wiki. Which object holds changes for DELETE. ↩ ↩2

  3. node-mssql contributors. (n.d.). node-mssql (v11.0.1), Transaction. GitHub. How a transaction acquires and releases a connection. ↩ ↩2

  4. Microsoft. (n.d.). @@ROWCOUNT (Transact-SQL), Remarks. Microsoft Learn. Rows affected by the preceding statement. ↩

  5. CaiBorui [S2thend]. (2025, May 14). AssetMan, backend/app.js [Git snapshot 197c6ba]. GitHub. Choosing the controller at startup · Delete-user route. ↩

  6. CaiBorui [S2thend]. (2025, May 21). Remove MSSQL from backend [Git commit 7302f8f]. GitHub. Removing the SQL Server implementation. ↩

© 2025 borui. All rights reserved. This content may be freely reproduced, displayed, modified, or distributed with proper attribution to borui and a link to the article: borui (2025-05-14). Can SQLite and SQL Server share the same data access code?. https://caiborui.com/blog/2025-05-14-zh-sqlite-sql-server-shared-data-access-entrans

@misc{borui2025-bb324cac,
  author = {borui},
  title = {{Can SQLite and SQL Server share the same data access code?}},
  year = {2025},
  publisher = {borui's blog},
  url = {https://caiborui.com/blog/2025-05-14-zh-sqlite-sql-server-shared-data-access-entrans}
}