Hyperlinkv0.8.0-beta.28

SqliteClient

(options: SqliteClientConfig): Effect.Effect<
  SqliteClient,
  never,
  Scope.Scope | Reactivity.Reactivity
>

Creates a scoped node SQLite client from the supplied configuration, using a single serialized connection with WAL enabled by default and exposing SQLite-specific export, backup, and loadExtension operations.

constructors
export const make = (
  options: SqliteClientConfig
): Effect.Effect<SqliteClient, never, Scope.Scope | Reactivity.Reactivity> =>
  Effect.gen(function*() {
    const compiler = Statement.makeCompilerSqlite(options.transformQueryNames)
    const transformRows = options.transformResultNames ?
      Statement.defaultTransforms(
        options.transformResultNames
      ).array :
      undefined

    const makeConnection = Effect.gen(function*() {
      const scope = yield* Effect.scope
      const db = new DatabaseSync(options.filename, {
        readOnly: options.readonly ?? false,
        allowExtension: true
      })
      yield* Scope.addFinalizer(scope, Effect.sync(() => db.close()))
      db.enableLoadExtension(false)

      if (options.disableWAL !== true) {
        db.exec("PRAGMA journal_mode = WAL")
      }

      const prepareCache = yield* Cache.make({
        capacity: options.prepareCacheSize ?? 200,
        timeToLive: options.prepareCacheTTL ?? Duration.minutes(10),
        lookup: (sql: string) =>
          Effect.try({
            try: () => db.prepare(sql),
            catch: (cause) => new SqlError({ reason: classifyError(cause, "Failed to prepare statement", "prepare") })
          })
      })

      const runStatement = (
        statement: StatementSync,
        params: ReadonlyArray<unknown>,
        raw: boolean
      ) =>
        Effect.withFiber<ReadonlyArray<any>, SqlError>((fiber) => {
          const useSafeIntegers = Context.get(fiber.context, Client.SafeIntegers)
          return Effect.try({
            try: () => {
              statement.setReadBigInts(useSafeIntegers)
              if (statement.columns().length > 0) {
                return statement.all(...(params as Array<any>)) as ReadonlyArray<any>
              }
              const result = statement.run(...(params as Array<any>))
              return raw ? { changes: result.changes, lastInsertRowid: result.lastInsertRowid } as any : []
            },
            catch: (cause) => new SqlError({ reason: classifyError(cause, "Failed to execute statement", "execute") })
          })
        })

      const runStatementValues = (
        statement: StatementSync,
        params: ReadonlyArray<unknown>
      ) =>
        Effect.withFiber<ReadonlyArray<ReadonlyArray<unknown>>, SqlError>((fiber) => {
          const useSafeIntegers = Context.get(fiber.context, Client.SafeIntegers)
          return Effect.try({
            try: () => {
              statement.setReadBigInts(useSafeIntegers)
              if (statement.columns().length > 0) {
                return statement.all(...(params as Array<any>)) as unknown as ReadonlyArray<ReadonlyArray<unknown>>
              }
              statement.run(...(params as Array<any>))
              return []
            },
            catch: (cause) => new SqlError({ reason: classifyError(cause, "Failed to execute statement", "execute") })
          })
        })

      const runStatementValuesUnprepared = (
        statement: StatementSync,
        params: ReadonlyArray<unknown>
      ) =>
        Effect.withFiber<ReadonlyArray<ReadonlyArray<unknown>>, SqlError>((fiber) => {
          const useSafeIntegers = Context.get(fiber.context, Client.SafeIntegers)
          return Effect.try({
            try: () => {
              statement.setReadBigInts(useSafeIntegers)
              statement.setReturnArrays(true)
              if (statement.columns().length > 0) {
                return statement.all(...(params as Array<any>)) as unknown as ReadonlyArray<ReadonlyArray<unknown>>
              }
              statement.run(...(params as Array<any>))
              return []
            },
            catch: (cause) => new SqlError({ reason: classifyError(cause, "Failed to execute statement", "execute") })
          })
        })

      const run = (
        sql: string,
        params: ReadonlyArray<unknown>,
        raw = false
      ) =>
        Effect.flatMap(
          Cache.get(prepareCache, sql),
          (s) => runStatement(s, params, raw)
        )

      const runValues = (
        sql: string,
        params: ReadonlyArray<unknown>
      ) =>
        Effect.acquireUseRelease(
          Cache.get(prepareCache, sql),
          (statement) => {
            statement.setReturnArrays(true)
            return runStatementValues(statement, params)
          },
          (statement) => Effect.sync(() => statement.setReturnArrays(false))
        )

      const runValuesUnprepared = (
        sql: string,
        params: ReadonlyArray<unknown>
      ) => runStatementValuesUnprepared(db.prepare(sql), params)

      return identity<SqliteConnection>({
        execute(sql, params, transformRows) {
          return transformRows
            ? Effect.map(run(sql, params), transformRows)
            : run(sql, params)
        },
        executeRaw(sql, params) {
          return run(sql, params, true)
        },
        executeValues(sql, params) {
          return runValues(sql, params)
        },
        executeValuesUnprepared(sql, params) {
          return runValuesUnprepared(sql, params)
        },
        executeUnprepared(sql, params, transformRows) {
          const effect = runStatement(db.prepare(sql), params ?? [], false)
          return transformRows ? Effect.map(effect, transformRows) : effect
        },
        executeStream(_sql, _params) {
          return Stream.die("executeStream not implemented")
        },
        backup(destination) {
          return Effect.suspend(() => {
            let totalPages = 0
            return Effect.tryPromise({
              try: () =>
                backupDatabase(db, destination, {
                  progress: (progress) => {
                    totalPages = progress.totalPages
                  }
                }).then((pages): BackupMetadata => ({ totalPages: totalPages || pages, remainingPages: 0 })),
              catch: (cause) => new SqlError({ reason: classifyError(cause, "Failed to backup database", "backup") })
            })
          })
        },
        loadExtension(path) {
          return Effect.acquireUseRelease(
            Effect.sync(() => db.enableLoadExtension(true)),
            () =>
              Effect.try({
                try: () => db.loadExtension(path),
                catch: (cause) =>
                  new SqlError({ reason: classifyError(cause, "Failed to load extension", "loadExtension") })
              }),
            () => Effect.sync(() => db.enableLoadExtension(false))
          )
        }
      })
    })

    const semaphore = yield* Semaphore.make(1)
    const connection = yield* makeConnection

    const acquirer = semaphore.withPermits(1)(Effect.succeed(connection))
    const transactionAcquirer = Effect.uninterruptibleMask((restore) => {
      const fiber = Fiber.getCurrent()!
      const scope = Context.getUnsafe(fiber.context, Scope.Scope)
      return Effect.as(
        Effect.tap(
          restore(semaphore.take(1)),
          () => Scope.addFinalizer(scope, semaphore.release(1))
        ),
        connection
      )
    })

    return Object.assign(
      (yield* Client.make({
        acquirer,
        compiler,
        transactionAcquirer,
        spanAttributes: [
          ...(options.spanAttributes ? Object.entries(options.spanAttributes) : []),
          [ATTR_DB_SYSTEM_NAME, "sqlite"]
        ],
        transformRows
      })) as SqliteClient,
      {
        [TypeId]: TypeId as TypeId,
        config: options,
        backup: (destination: string) => Effect.flatMap(acquirer, (_) => _.backup(destination)),
        loadExtension: (path: string) => Effect.flatMap(acquirer, (_) => _.loadExtension(path))
      }
    )
  })
Referenced by 2 symbols