tursodatabase / kysely-libsql

Kysely dialect for sqld
MIT License
48 stars 7 forks source link

Transactions don't work with Turso #11

Closed OultimoCoder closed 2 months ago

OultimoCoder commented 2 months ago

They work locally when running tests but as soon as I am running it with my turso db the simple transaction below will fail (the same code works with planetscale):

await db.transaction().execute(async (trx) => {
      const userId = await trx
        .insertInto('user')
        .values({
          id,
          name: providerUser._name,
          email: providerUser._email,
          is_email_verified: true,
          password: null,
          role: 'user'
        })
        .executeTakeFirstOrThrow()
      console.log('here')
      await trx
        .insertInto('authorisations')
        .values({
          user_id: id,
          provider_type: providerUser.providerType,
          provider_user_id: providerUser._id
        })
        .executeTakeFirstOrThrow()
      return userId
    })

The same error everytime:

        "LibsqlError: SCHEMA_MIGRATION_ERROR: Schema migration error: migration is invalid: it contains transaction items (BEGIN, COMMIT, SAVEPOINT...) which are not allowed. The migration is already run within a transaction"

I want to be clear I am 100% not running a migration whatsoever. This is a cloudflare worker endpoint all it does is instantiate a db and call this code.

import { LibsqlDialect } from '@libsql/kysely-libsql'
import { Kysely } from 'kysely'
import { ApiKeyTable } from '../tables/api-key.table'
import { AuthProviderTable } from '../tables/auth-provider.table'
import { PlatformTable } from '../tables/platform.table'
import { UserTable } from '../tables/user.table'
import { Config } from './config'

let dbClient: Kysely<Database>

export interface Database {
  user: UserTable
  authorisations: AuthProviderTable
  api_key: ApiKeyTable
  platform: PlatformTable
}

export const getDBClient = (config: Config): Kysely<Database> => {
  dbClient =
    dbClient ||
    new Kysely<Database>({
      dialect: new LibsqlDialect({
        url: config.turso.url,
        authToken: config.env === 'production' ? config.turso.token : undefined
      })
    })
  return dbClient
}

Any idea what's going on? I can't use this if i can't use transactions.

ottomated commented 2 months ago

Does it work in a simpler case like

await db.transaction().execute(async (tx) => {
  console.log(await sql`SELECT 1`.execute(tx));
});
OultimoCoder commented 2 months ago

This can be closed. This was me misunderstanding schema databases and using one instead of a normal one.