import { sql, type SqlBool } from 'kysely' import type { Db } from '@protobase/query' import { encodeKey } from '@protobase/schema/internal' import type { Deps } from '../deps' import type { ScheduledDelete } from '../files/cleanup-schedule' import { badRequest, preconditionFailed } from '../problem' import { fetchRecord } from '../records' import { requireOperation, targetFilter, writableFields, type RequestAccess } from '../request-access' import { columnId, scopeConditions, tableId, whereClause } from '../sql-parts' import { tenantScope } from '../tenant' import { refuseUnknownField, validateBody } from '../validate-body' import { missing, shown, type WriteResult } from '../write-shared' import { applyUpdate, planUpdate, type UpdatePlan } from '../write-update' import { checkRankAfter } from '../rank-after' type Key = (string | number)[] /** A record a `reorder` or `move` numbered: as stored now, with its value of the order field before. */ export type NumberedResult = WriteResult & { previous: unknown } const checkViolation = '23514' const isDatabaseCode = (error: unknown, code: string) => error instanceof Error && (error as { code?: unknown }).code === code /** * Moves the affected rows out of the range in use, in one statement per 1,000 rows and without touching their ETags, so * the final positions can be written without any two rows colliding on a non-deferrable unique index: each lands on its * own value outside every one in use, so none collides on the way either. * First above the highest value in the column; when a check constraint refuses that, below the lowest (negative). * The first attempt runs in a savepoint, so a refusal costs nothing. */ const moveAside = async (trx: Db, access: RequestAccess, field: string, keys: Key[]) => { const { full } = access const column = columnId(full.fields[field]!) const tenant = tenantScope(access.entry, access.session)?.tenantValue const bounds = (await sql<{ high: number | null; low: number | null }>`select max(${column}) as high, min(${column}) as low from ${tableId(full)} as t`.execute(trx)).rows[0]! const keyRow = sql`(${sql.join(full.primaryKey.map((name) => columnId(full.fields[name]!)))})` const keyOf = (key: Key) => sql`(${sql.join(key.map((value) => sql`${value}`))})` // A statement moves 1,000 rows: each row looks its rank up among the statement's keys, and each key binds its values // twice and its rank once, far below Postgres's 65,535 parameters. A longer list goes in several statements, its // ranks counted over the whole list. const perStatement = 1000 // The row of rank n goes to `from` + n, or `from` - n going down. const assign = async (from: number, step: 1 | -1) => { for (let first = 0; first < keys.length; first += perStatement) { const part = keys.slice(first, first + perStatement) const ranks = sql.join(part.map((key, n) => sql`when ${keyRow} = ${keyOf(key)} then ${first + n}::bigint`), sql` `) const conditions = [...scopeConditions(full, tenant), sql`${keyRow} in (${sql.join(part.map(keyOf))})`] await sql`update ${tableId(full)} as t set ${column} = ${from}::bigint + ${step}::bigint * (case ${ranks} end)${whereClause(conditions)}`.execute(trx) } } await sql`savepoint reorder_aside`.execute(trx) try { await assign(Number(bounds.high ?? 0) + 1, 1) await sql`release savepoint reorder_aside`.execute(trx) } catch (error) { if (!isDatabaseCode(error, checkViolation)) throw error await sql`rollback to savepoint reorder_aside`.execute(trx) await assign(Math.min(Number(bounds.low ?? 0), 0) - 1, -1) } } /** Refuses ordering by `name` unless the caller may update records and write it, and it is an integer field. */ export const checkOrderField = (access: RequestAccess, name: string) => { requireOperation(access, 'update') const field = access.full.fields[name] // Refused exactly like any other field the caller cannot write (hidden, read-only or unknown). A write-only or sensitive // field is refused as unknown too: ordering by it would decide from, and report, stored values no response carries. if (!Object.hasOwn(access.model.fields, name)) refuseUnknownField(name) validateBody(access, 'update', { [name]: 1 }) if (field?.type !== 'integer' && field?.type !== 'bigint') throw badRequest('invalid-parameter', `"${name}" must be an integer field to order by`) if (!writableFields(access, 'update').includes(name)) throw badRequest('invalid-parameter', `"${name}" is read-only`) } /** * `reorder`: the listed records end up with `field` = `start`, `start` + 1, ... in the given order, `start` 1 unless * given, so a client sends only the stretch of a long list that moved. Only records whose value changes * are written, each as an ordinary update (validation, access, ETag, hooks); they are first moved aside (see `moveAside`) * so that a unique index such as (invoice_id, position) is never violated half way. Everything checks out before any row moves, * and with the position's `after` the new order must keep each record below the records it depends on (see `checkRankAfter`). * With `ranks`, the values of `field` the caller read for `keys`, a locked record holding another value is refused with 412. * The batch holds the field's order lock (see `lockOrders`). */ export const reorderIn = async (trx: Db, deps: Deps, access: RequestAccess, input: { field: string; keys: Key[]; etags: Record; start: number; ranks?: unknown[] }, removed: ScheduledDelete[]): Promise => { const { entry } = access checkOrderField(access, input.field) const names = input.keys.map((key) => encodeKey(key)) if (new Set(names).size !== names.length) throw badRequest('invalid-parameter', 'A record appears twice in keys') const tenant = tenantScope(entry, access.session)?.tenantValue const target = targetFilter(access, 'update') const current = await Promise.all(input.keys.map(async (key) => { const found = await fetchRecord(trx, entry, key, tenant, { deleted: 'hide', lock: true, ...(target && { filter: target }), etagFields: Object.keys(access.model.fields) }) if (!found) throw missing(entry) return found })) if (input.ranks?.some((rank, i) => String(current[i]!.record[input.field]) !== String(rank))) throw preconditionFailed('The list changed where the record was dropped') const changing = input.keys.flatMap((key, i) => (Number(current[i]!.record[input.field]) === input.start + i ? [] : [i])) const plans = new Map() for (const i of changing) { plans.set(i, await planUpdate(trx, access, input.keys[i]!, { [input.field]: input.start + i }, input.etags[names[i]!] ?? null)) } if (changing.length > 0) await moveAside(trx, access, input.field, changing.map((i) => input.keys[i]!)) const written = [] for (const [i, key] of input.keys.entries()) { const plan = plans.get(i) written.push(plan ? await applyUpdate(trx, deps, access, key, plan, removed) : current[i]!) } await checkRankAfter(trx, deps, access, input.field, changing.map((i) => ({ key: input.keys[i]!, before: current[i]!.record[input.field] }))) // Once every rank is final, so a lookup field never shows another record's rank on its way const results: NumberedResult[] = [] for (const [i, record] of written.entries()) results.push({ ...(await shown(trx, access, record)), previous: current[i]!.record[input.field] }) return results }