(
adapter: ORMAdapter<S>,
options: ToORMOptions = {},
)
| 396 | } |
| 397 | |
| 398 | export function toORM<S extends AnySchema>( |
| 399 | adapter: ORMAdapter<S>, |
| 400 | options: ToORMOptions = {}, |
| 401 | ): AbstractQuery<S> { |
| 402 | const context = options.context ?? adapter.context; |
| 403 | const internal: ORMAdapter<S> = |
| 404 | context === adapter.context ? adapter : { ...adapter, context }; |
| 405 | |
| 406 | function toTable<TableName extends keyof S["tables"]>( |
| 407 | name: TableName, |
| 408 | ): S["tables"][TableName] { |
| 409 | const table = internal.tables[name]; |
| 410 | if (!table) throw new Error(`[FumaDB] Invalid table name ${String(name)}.`); |
| 411 | |
| 412 | return table; |
| 413 | } |
| 414 | |
| 415 | const query = { |
| 416 | internal, |
| 417 | async count(name, { where } = {}) { |
| 418 | const table = toTable(name); |
| 419 | let conditions = where ? buildCondition(table.columns, where) : undefined; |
| 420 | if (conditions === true) conditions = undefined; |
| 421 | if (conditions === false) return 0; |
| 422 | |
| 423 | const constrainedWhere = await applyReadPolicies(table, conditions, context); |
| 424 | if (constrainedWhere === false) return 0; |
| 425 | return await internal.count(table, { where: constrainedWhere }); |
| 426 | }, |
| 427 | async upsert(name, { where, ...options }) { |
| 428 | const table = toTable(name); |
| 429 | const conditions = where ? buildCondition(table.columns, where) : undefined; |
| 430 | if (conditions === false) return; |
| 431 | let compiledWhere: Condition | undefined | false = conditions === true ? undefined : conditions; |
| 432 | |
| 433 | compiledWhere = await applyUpdatePolicies( |
| 434 | table, |
| 435 | compiledWhere, |
| 436 | options.update, |
| 437 | context, |
| 438 | "upsert", |
| 439 | options.create, |
| 440 | ); |
| 441 | if (compiledWhere === false) return; |
| 442 | await runCreatePolicies(table, options.create, context); |
| 443 | await internal.upsert(table, { |
| 444 | where: compiledWhere, |
| 445 | ...options, |
| 446 | }); |
| 447 | }, |
| 448 | async upsertMany(name, { target, update, values }) { |
| 449 | const table = toTable(name); |
| 450 | if (values.length === 0) return; |
| 451 | if (target.length === 0) { |
| 452 | // oxlint-disable-next-line executor/no-try-catch-or-throw, executor/no-error-constructor -- boundary: public query rejects invalid upsert shape |
| 453 | throw new Error("[FumaDB] upsertMany requires at least one target column."); |
| 454 | } |
| 455 | if (update.length === 0) { |
no outgoing calls
no test coverage detected