( options: SqliteClientConfig )
| 137 | * @since 4.0.0 |
| 138 | */ |
| 139 | export const make = ( |
| 140 | options: SqliteClientConfig |
| 141 | ): Effect.Effect<SqliteClient & Client.SqlClient, SqlError, Scope.Scope | Reactivity.Reactivity> => |
| 142 | Effect.gen(function*() { |
| 143 | const compiler = Statement.makeCompilerSqlite(options.transformQueryNames) |
| 144 | const transformRows = options.transformResultNames ? |
| 145 | Statement.defaultTransforms( |
| 146 | options.transformResultNames |
| 147 | ).array : |
| 148 | undefined |
| 149 | |
| 150 | const makeConnection = Effect.gen(function*() { |
| 151 | const db = yield* Effect.acquireRelease( |
| 152 | Effect.try({ |
| 153 | try: () => |
| 154 | new DatabaseSync(options.filename, { |
| 155 | readOnly: options.readonly ?? false, |
| 156 | allowExtension: true |
| 157 | }), |
| 158 | catch: (cause) => new SqlError({ reason: classifyError(cause, "Failed to open database", "connect") }) |
| 159 | }), |
| 160 | (db) => Effect.sync(() => db.close()) |
| 161 | ) |
| 162 | setLoadExtensionEnabled(db, false) |
| 163 | const busyTimeout = Math.min( |
| 164 | MAX_BUSY_TIMEOUT, |
| 165 | Math.max(0, Math.round(Duration.toMillis(options.busyTimeout ?? Duration.seconds(5)))) |
| 166 | ) |
| 167 | const exec = (sql: string) => |
| 168 | Effect.try({ |
| 169 | try: () => db.exec(sql), |
| 170 | catch: (cause) => new SqlError({ reason: classifyError(cause, "Failed to configure database", "connect") }) |
| 171 | }) |
| 172 | yield* exec(`PRAGMA busy_timeout = ${busyTimeout}`) |
| 173 | |
| 174 | if (options.disableWAL !== true && !options.readonly) { |
| 175 | // Switching to WAL can fail with SQLITE_BUSY without invoking the busy |
| 176 | // handler, so retry it until busyTimeout has elapsed. Each attempt's |
| 177 | // native busy wait is limited to the remaining time. |
| 178 | // Deno's `exec` errors omit `errcode`, so run the pragma as a prepared |
| 179 | // statement to keep SQLITE_BUSY retryable. |
| 180 | const enableWAL = Effect.try({ |
| 181 | try: () => db.prepare("PRAGMA journal_mode = WAL").get(), |
| 182 | catch: (cause) => new SqlError({ reason: classifyError(cause, "Failed to configure database", "connect") }) |
| 183 | }) |
| 184 | const deadline = (yield* Clock.monotonicTimeNanos) + BigInt(busyTimeout) * NANOS_PER_MILLI |
| 185 | const remainingMillis = Effect.map( |
| 186 | Clock.monotonicTimeNanos, |
| 187 | (now) => Math.max(0, Number((deadline - now) / NANOS_PER_MILLI)) |
| 188 | ) |
| 189 | yield* remainingMillis.pipe( |
| 190 | Effect.flatMap((remaining) => exec(`PRAGMA busy_timeout = ${remaining}`)), |
| 191 | Effect.andThen(enableWAL), |
| 192 | Effect.retry({ |
| 193 | while: (error) => |
| 194 | error.reason._tag === "LockTimeoutError" && Effect.map(remainingMillis, (remaining) => remaining > 0), |
| 195 | schedule: Schedule.spaced("10 millis") |
| 196 | }) |
no test coverage detected