/kysely-sqlcommenter

SqlCommenter plugin for Kysely

Primary LanguageTypeScriptMIT LicenseMIT

Kysely SqlCommnenter

SqlCommenter plugin for Kysely

Getting started

npm install kysely-sqlcommenter

SqlCommenterPlugin does not change the API of Kysely. You can only provide it callback for getting the metadata for the comment. AsyncLocalStorage or any alternative is needed.

Initialize the AsyncLocalStorage:

import { AsyncLocalStorage } from 'node:async_hooks'
import { SqlCommentLike } from 'kysely-sqlcommenter'

const asyncLocalStorage = new AsyncLocalStorage<SqlCommentLike>()

Register the SqlCommenterPlugin using the asyncLocalStorage in callback:

import { SqlCommenterPlugin } from 'kysely-sqlcommenter'

const db = new Kysely<DB>({
  // ... kysely config
  plugins: [
    // Provide callback
    new SqlCommenterPlugin(() => asyncLocalStorage.getStore()),
  ],
})

Create a root middleware, register the root span with storage via asyncLocalStorage.run. Everything in the callstack of this next will have access to a shared copy of the storage (new calls will have exclusive storage). You can initialize it with a value.

app.use((req, res, next) => {
  asyncLocalStorage.run({ controller: req.path }, next)
})

Any kysely calls will have the appropriate SqlComment

db.selectFrom('cats').select(['id', 'name'])
// select "id", "name" from "cats" /*controller='cats'*/

See the full working example for express here, including concurrency demo and adjusting the comment in other middleware.

Progress

  • Tests, examples, integration tests
  • SqlCommenter spec tests
  • Callback API + Examples with CLS
  • Builder API (not really a priority with the amount of hacking needed)
  • CI
  • Query support (assume only DML, other are not useful)

References