Files
MikrotikManager/backend/src/db/sqlite-import-control-writes.ts
T

62 lines
4.0 KiB
TypeScript

import type { Pool } from "pg"
import { withPartitionWrite, PartitionWriteError, isPartitionWriteOutcomeUnknown } from "../services/partition-write-transaction.js"
/** Uses the same
* admission already used by import batches, on the marker's actual backend. */
export async function writeSqliteImportMarker(pool: Pool, sqlitePath: string, sqliteSha256: string, reportJson: string): Promise<void> {
await withPartitionWrite(async ({ client }) => {
await client.query(`UPDATE data_migration
SET sqlite_imported_at = now(), sqlite_path = $1, sqlite_sha256 = $2, report_json = $3::jsonb
WHERE id = 1`, [sqlitePath, sqliteSha256, reportJson])
}, { connect: () => pool.connect() })
}
const identitySettings = `attribute.attidentity IN ('a', 'd') AND NOT attribute.attisdropped
AND settings.seqincrement = 1 AND settings.seqcache = 1 AND NOT settings.seqcycle`
export async function resetSqliteImportSequence(pool: Pool, table: string): Promise<"sequence-absent" | "sequence-set"> {
if (typeof table !== "string" || !/^[a-z_][a-z0-9_]{0,62}$/.test(table)) throw Error("Fixed importer relation identifier required")
const relation = `"public"."${table}"`
let sequenceMutationSent = false
try { return await withPartitionWrite(async ({ client }) => {
const { rows } = await client.query<{ sequence_oid: string | null; restartable: boolean }>(`SELECT
sequence_oid::text, (pg_catalog.pg_has_role(tbl.relowner, 'USAGE') AND ${identitySettings}) IS TRUE AS restartable
FROM pg_catalog.pg_class tbl
CROSS JOIN LATERAL (SELECT pg_catalog.pg_get_serial_sequence($1, 'id')::pg_catalog.regclass::oid AS sequence_oid) seq
JOIN pg_catalog.pg_attribute attribute ON attribute.attrelid = tbl.oid AND attribute.attname = 'id'
LEFT JOIN pg_catalog.pg_sequence settings ON settings.seqrelid = seq.sequence_oid
WHERE tbl.oid = $1::pg_catalog.regclass`, [relation])
if (rows.length !== 1) throw Error("Importer identity metadata unavailable")
const { sequence_oid: sequenceOid, restartable } = rows[0]
if (sequenceOid === null) return "sequence-absent" as const
if (!/^[1-9][0-9]{0,9}$/.test(sequenceOid)) throw Error("Importer sequence identity unavailable")
if (restartable) {
// Freeze the ID high-water mark, including direct writes to descendants.
await client.query(`LOCK TABLE ${relation} IN ACCESS EXCLUSIVE MODE`)
const { rows } = await client.query<{ restart: string }>(`SELECT (used.last_id::numeric + 1)::text AS restart
FROM pg_catalog.pg_attribute attribute
JOIN pg_catalog.pg_sequence settings
ON settings.seqrelid = pg_catalog.pg_get_serial_sequence($1, 'id')::pg_catalog.regclass
CROSS JOIN (SELECT GREATEST(COALESCE(MAX(id), 1), 1) AS last_id FROM ${relation}) used
WHERE attribute.attrelid = $1::pg_catalog.regclass AND attribute.attname = 'id'
AND settings.seqrelid = $2::pg_catalog.oid AND ${identitySettings}
AND used.last_id >= settings.seqmin AND used.last_id < settings.seqmax`, [relation, sequenceOid])
if (rows.length !== 1 || !/^[1-9][0-9]{0,18}$/.test(rows[0].restart)) {
throw Error("Unsupported or exhausted importer identity sequence")
}
await client.query(`ALTER TABLE ${relation} ALTER COLUMN id RESTART WITH ${rows[0].restart}`)
return "sequence-set" as const
}
// Legacy serial and grant-only callers can use setval without owning the table.
sequenceMutationSent = true
await client.query(`SELECT pg_catalog.setval($1::pg_catalog.oid::pg_catalog.regclass,
GREATEST(COALESCE((SELECT MAX(id) FROM ${relation}),1),1),true)`, [sequenceOid])
return "sequence-set" as const
}, { connect: () => pool.connect() }) }
catch (error) {
// The surrounding SQL transaction may be known rolled back, while setval
// was already visible. Never feed that case into known-failure/retry lanes.
if (sequenceMutationSent && !isPartitionWriteOutcomeUnknown(error)) throw new PartitionWriteError(true)
throw error
}
}