| 80 | * @since 1.0.0 |
| 81 | */ |
| 82 | export const make = ( |
| 83 | options: SqliteClientConfig |
| 84 | ): Effect.Effect<SqliteClient, never, Scope.Scope | Reactivity.Reactivity> => |
| 85 | Effect.gen(function*() { |
| 86 | const compiler = Statement.makeCompilerSqlite(options.transformQueryNames) |
| 87 | const transformRows = options.transformResultNames ? |
| 88 | Statement.defaultTransforms( |
| 89 | options.transformResultNames |
| 90 | ).array : |
| 91 | undefined |
| 92 | |
| 93 | const makeConnection = Effect.gen(function*() { |
| 94 | const db = new Database(options.filename, { |
| 95 | readonly: options.readonly, |
| 96 | readwrite: options.readwrite ?? true, |
| 97 | create: options.create ?? true |
| 98 | } as any) |
| 99 | yield* Effect.addFinalizer(() => Effect.sync(() => db.close())) |
| 100 | |
| 101 | // match the better-sqlite3 default so concurrent writers wait for locks |
| 102 | db.run("PRAGMA busy_timeout = 5000;") |
| 103 | |
| 104 | if (options.disableWAL !== true) { |
| 105 | db.run("PRAGMA journal_mode = WAL;") |
| 106 | } |
| 107 | |
| 108 | const run = ( |
| 109 | sql: string, |
| 110 | params: ReadonlyArray<unknown> = [] |
| 111 | ) => |
| 112 | Effect.withFiberRuntime<Array<any>, SqlError>((fiber) => { |
| 113 | const useSafeIntegers = Context.get(fiber.currentContext, Client.SafeIntegers) |
| 114 | try { |
| 115 | const statement = db.query(sql) |
| 116 | // @ts-ignore bun-types missing safeIntegers method, fixed in https://github.com/oven-sh/bun/pull/26627 |
| 117 | statement.safeIntegers(useSafeIntegers) |
| 118 | return Effect.succeed((statement.all(...(params as any)) ?? []) as Array<any>) |
| 119 | } catch (cause) { |
| 120 | return Effect.fail(new SqlError({ cause, message: "Failed to execute statement" })) |
| 121 | } |
| 122 | }) |
| 123 | |
| 124 | const runValues = ( |
| 125 | sql: string, |
| 126 | params: ReadonlyArray<unknown> = [] |
| 127 | ) => |
| 128 | Effect.withFiberRuntime<Array<any>, SqlError>((fiber) => { |
| 129 | const useSafeIntegers = Context.get(fiber.currentContext, Client.SafeIntegers) |
| 130 | try { |
| 131 | const statement = db.query(sql) |
| 132 | // @ts-ignore bun-types missing safeIntegers method, fixed in https://github.com/oven-sh/bun/pull/26627 |
| 133 | statement.safeIntegers(useSafeIntegers) |
| 134 | return Effect.succeed((statement.values(...(params as any)) ?? []) as Array<any>) |
| 135 | } catch (cause) { |
| 136 | return Effect.fail(new SqlError({ cause, message: "Failed to execute statement" })) |
| 137 | } |
| 138 | }) |
| 139 | |