Skip to content

Kysely adapter ​

@anievo-id/rbac-evolution-kysely stores roles and permissions through Kysely. One adapter works with every Kysely dialect. It also ships typed table interfaces and helpers that create the tables.

Dialect familyKysely dialectsStatus
PostgreSQLPostgresDialect (pg), PGlite (Kysely 0.29's PGliteDialect or kysely-pglite-dialect), Neon, postgres.js, ...Tested
MySQLMysqlDialect (mysql2), PlanetScale, ...Tested (MySQL 8)
SQLiteSqliteDialect (better-sqlite3), libsql / Turso, D1, Bun SQLite, ...Tested
SQL ServerMssqlDialect (tedious)Tested (SQL Server 2022)

MikroORM 7 runs on Kysely too: pass em.getKysely().

The adapter detects the dialect family from your Kysely instance. Third-party dialects that reuse Kysely's built-in adapters (nearly all of them) are detected too. If detection fails, pass { dialect } explicitly.

Install ​

bash
npm i @anievo-id/rbac-evolution @anievo-id/rbac-evolution-kysely kysely
bash
pnpm add @anievo-id/rbac-evolution @anievo-id/rbac-evolution-kysely kysely
bash
yarn add @anievo-id/rbac-evolution @anievo-id/rbac-evolution-kysely kysely
bash
bun add @anievo-id/rbac-evolution @anievo-id/rbac-evolution-kysely kysely

kysely 0.28 or 0.29 is a peer dependency. Install your database driver as usual.

KyselyNode.jsTypeScriptMigrator import
0.2922+5.4+kysely/migration
0.2820+5.0+kysely

The Node.js and TypeScript minimums of 0.29 are Kysely's own. 0.29 also ships ES modules only: from CommonJS, it needs a Node.js version that can require() ES modules (22.12 or later). Everything on this page works the same on both versions; only the migrator import differs.

Schema ​

The adapter uses the five tables described in the adapters overview, with the same storage conventions as the Prisma and Drizzle adapters. Tables created by the Drizzle adapter's SQL files or by drizzle-kit work as they are.

createRbacTables ​

ts
import { createRbacTables } from '@anievo-id/rbac-evolution-kysely'

await createRbacTables(db) // dialect detected from db
await createRbacTables(db, { dialect: 'mysql', prefix: 'rbac_' })

It creates the tables with their primary keys, unique constraints, foreign keys and indexes. Tables that already exist are skipped, so running it twice is harmless. dropRbacTables(db, { prefix? }) drops the tables.

With the Kysely migrator ​

rbacMigration(options?) returns an RbacMigration: a Kysely migration object (up creates the tables, down drops them). It has the same shape as Kysely's Migration type, so it works with the Migrator of 0.28 and 0.29.

Kysely 0.29 exports Migrator (and Migration, FileMigrationProvider, ...) from kysely/migration:

ts
import { Migrator } from 'kysely/migration' // Kysely 0.29

On 0.28, which has no kysely/migration, import them from kysely:

ts
import { Migrator } from 'kysely' // Kysely 0.28
import { rbacMigration } from '@anievo-id/rbac-evolution-kysely'

const migrator = new Migrator({
  db,
  provider: {
    async getMigrations() {
      return { '0001_rbac': rbacMigration(), ...yourMigrations }
    },
  },
})

await migrator.migrateToLatest()

If your migrations live in files (for example with kysely-ctl), call the helpers from one:

ts
// migrations/0001_rbac.ts
import type { Kysely } from 'kysely'
import { createRbacTables, dropRbacTables } from '@anievo-id/rbac-evolution-kysely'

export const up = (db: Kysely<any>) => createRbacTables(db)
export const down = (db: Kysely<any>) => dropRbacTables(db)

Table prefix ​

If your database already has a roles or permissions table, use a prefix. It is added to every table, constraint and index name:

ts
await createRbacTables(db, { prefix: 'rbac_' }) // rbac_permissions, rbac_roles, ...
const adapter = kyselyAdapter(db, { prefix: 'rbac_' })

Use the same prefix everywhere

The adapter reads the unprefixed tables unless you pass the same prefix to kyselyAdapter().

Column types ​

ColumnPostgreSQLMySQLSQLiteSQL Server
idserialinteger auto_incrementinteger autoincrementinteger identity
name, guard_name, subject_type, subject_id, team_idtextvarchar(255) utf8mb4, utf8mb4_bintextnvarchar(255), Latin1_General_100_BIN2
created_at, updated_attimestamptzdatetimeinteger (unix seconds)datetime2
expires_at (optional, expiry)timestamptzdatetime(3)integer (unix milliseconds)datetime2(3)

On MySQL and SQL Server the string columns use a binary collation (utf8mb4_bin, Latin1_General_100_BIN2), so 'Edit' and 'edit' are different names, as on PostgreSQL and SQLite.

SQL Server tables created before 0.6.6

Older versions created the SQL Server columns with the database's default collation, which is usually case-insensitive: 'Edit' and 'edit' were treated as the same name. createRbacTables skips tables that already exist, so recreate them (or change the column collation) to get case-sensitive names.

Expiry (1.2) ​

Temporary access stores when a role assignment or direct permission ends in a nullable expires_at column of model_has_roles and model_has_permissions. It is off by default: createRbacTables creates the 1.1 tables, and the adapter never selects or writes expires_at, so a 1.1 database keeps working after the upgrade, unchanged.

To turn it on in an existing app:

  1. Add the column with the migration helper, after your existing rbacMigration(). Existing rows get NULL, which means permanent:

    ts
    import { Migrator } from 'kysely' // on Kysely 0.29: from 'kysely/migration'
    import { rbacExpiryMigration, rbacMigration } from '@anievo-id/rbac-evolution-kysely'
    
    const migrator = new Migrator({
      db,
      provider: {
        async getMigrations() {
          return { '0001_rbac': rbacMigration(), '0002_rbac_expiry': rbacExpiryMigration(), ...yourMigrations }
        },
      },
    })
    
    await migrator.migrateToLatest()

    In a migration file, call the helpers yourself. Both skip tables that already have (or no longer have) the column, so they are safe to run twice:

    ts
    // migrations/0002_rbac_expiry.ts
    import type { Kysely } from 'kysely'
    import { addRbacExpiryColumns, dropRbacExpiryColumns } from '@anievo-id/rbac-evolution-kysely'
    
    export const up = (db: Kysely<any>) => addRbacExpiryColumns(db)
    export const down = (db: Kysely<any>) => dropRbacExpiryColumns(db) // the expiries are lost

    A new database can create the column right away with createRbacTables(db, { expiry: true }). All three take the same { dialect, prefix } options as createRbacTables.

  2. Create the adapter with the option:

    ts
    const adapter = kyselyAdapter(db, { expiry: true })

Without the option, an expiresAt throws EXPIRY_NOT_SUPPORTED and writes nothing. With the option but no column, every query on the link tables fails, so migrate first. RbacDatabase doesn't list expires_at; add it to your own table types if you query it.

Typing your Database ​

RbacDatabase describes the five tables. Extend it in your Kysely Database type to query them with full types:

ts
import type { RbacDatabase } from '@anievo-id/rbac-evolution-kysely'

interface Database extends RbacDatabase {
  users: UsersTable
}

// With a prefix, pass it as a type argument:
interface PrefixedDatabase extends RbacDatabase<'rbac_'> {
  users: UsersTable
}

The table interfaces are also exported one by one: PermissionsTable, RolesTable, RoleHasPermissionsTable, ModelHasRolesTable and ModelHasPermissionsTable. The adapter itself accepts any Kysely<DB>, so this step is optional.

Adapter ​

ts
kyselyAdapter(db, options?: { dialect?: RbacDialect; prefix?: string; expiry?: boolean }): KyselyRbacAdapter

RbacDialect is 'postgres' | 'mysql' | 'sqlite' | 'mssql'.

ts
import { createRbac } from '@anievo-id/rbac-evolution'
import { kyselyAdapter } from '@anievo-id/rbac-evolution-kysely'
import { Kysely, PostgresDialect } from 'kysely'
import pg from 'pg'

const db = new Kysely<Database>({
  dialect: new PostgresDialect({ pool: new pg.Pool({ connectionString: process.env.DATABASE_URL }) }),
})

export const rbac = createRbac({ adapter: kyselyAdapter(db) })
ts
import { createRbac } from '@anievo-id/rbac-evolution'
import { kyselyAdapter } from '@anievo-id/rbac-evolution-kysely'
import { Kysely, MysqlDialect } from 'kysely'
import { createPool } from 'mysql2'

const db = new Kysely<Database>({
  dialect: new MysqlDialect({ pool: createPool({ uri: process.env.DATABASE_URL }) }),
})

export const rbac = createRbac({ adapter: kyselyAdapter(db) })
ts
import { createRbac } from '@anievo-id/rbac-evolution'
import { kyselyAdapter } from '@anievo-id/rbac-evolution-kysely'
import SQLite from 'better-sqlite3'
import { Kysely, SqliteDialect } from 'kysely'

const db = new Kysely<Database>({
  dialect: new SqliteDialect({ database: new SQLite('local.db') }),
})

export const rbac = createRbac({ adapter: kyselyAdapter(db) })

From there it's the normal engine API:

ts
await rbac.createPermission('edit articles')
await rbac.createRole('writer')
await rbac.role('writer').givePermissionTo('edit articles')

const user = rbac.for({ type: 'user', id: 1 })
await user.assignRole('writer')
await user.can('edit articles') // true

Exports ​

ExportKind
kyselyAdapter(db, options?), KyselyRbacAdapterfunction / class
createRbacTables(db, options?), dropRbacTables(db, options?), rbacMigration(options?)functions
addRbacExpiryColumns(db, options?), dropRbacExpiryColumns(db, options?), rbacExpiryMigration(options?)functions
detectDialect(db), tableNames(options?)functions
RbacDatabase<Prefix>, PermissionsTable, RolesTable, RoleHasPermissionsTable, ModelHasRolesTable, ModelHasPermissionsTabletypes
RbacDialect, KyselyAdapterOptions, RbacMigration, RbacMigrationOptions, RbacTableOptions, RbacTableNames, RbacTimestamptypes

Behaviour notes ​

  • Ids. Role and permission ids are integers and come back as number. Reverse lookups (subjectsWithRole / subjectsWithPermission) return subject ids as strings.

  • Non-integer ids are ignored. If the engine passes an id that can't be an integer, the adapter drops it instead of throwing, because no row could match it anyway.

  • Idempotent attach. Every attach* method is a single statement that skips existing links:

    DialectStatement
    PostgreSQL, SQLiteINSERT ... ON CONFLICT DO NOTHING
    MySQLINSERT ... ON DUPLICATE KEY UPDATE role_id = role_id (a no-op; unlike INSERT IGNORE it doesn't hide other errors)
    SQL ServerINSERT ... SELECT ... WHERE NOT EXISTS, one row at a time; a duplicate-key error from a concurrent insert is ignored
  • New ids come from RETURNING on PostgreSQL and SQLite (3.35 or later), OUTPUT on SQL Server, and the driver's insert id on MySQL.

  • Link cleanup. deleteRole and deletePermission delete the link rows themselves before deleting the row, so cleanup works even when SQLite foreign keys are off (the default).

  • Timestamps. The adapter never writes or returns created_at / updated_at. They keep their default values.

  • Expiry writes. With { expiry: true }, an attach inserts the missing links with their expires_at, then updates expires_at of the links the exact subject already held (the latest call wins). pruneExpired() is one DELETE ... WHERE expires_at <= now per table. On SQLite the column holds unix milliseconds.

  • SQL Server is covered like the other dialects: the full conformance suite, including exact matching of names and subject ids, runs against SQL Server 2022 in CI. SQL Server ignores trailing spaces when it compares text; the adapter compares every row again in JavaScript, so this can't mix up subjects.

Transactions ​

A delete runs a few statements one after another, and they are not wrapped in a transaction. To make several RBAC changes atomic, build a short-lived adapter on a Kysely transaction:

ts
import { createRbac } from '@anievo-id/rbac-evolution'
import { kyselyAdapter } from '@anievo-id/rbac-evolution-kysely'

await db.transaction().execute(async (trx) => {
  const txRbac = createRbac({ adapter: kyselyAdapter(trx), cache: false })

  await txRbac.deleteRole('legacy-editor')
  await txRbac.for({ type: 'user', id: 1 }).syncRoles('writer')
})

// The main instance still holds cached lookups from before the transaction.
await rbac.forgetCachedPermissions()

TIP

cache: false on the transaction instance keeps uncommitted data out of any cache. After the commit, call forgetCachedPermissions() on your long-lived instance. See Cache.

Full API: reference

Released under the MIT License. Inspired by spatie/laravel-permission.