teqo-backup/src/utilities/drizzleBulk.ts
Francisco Ignácio Fontoura Solla 8420969b4b Deliver A7 Fase 1 federal ranking aggregate and register simplify follow-ups.
Replace full Local API federal T1 loads with drizzle GROUP BY on nucleus detail, gate election reads via assertCanReadElectionData, and absorb post-simplify cleanup into the A7 plan and roadmap.
2026-07-19 16:57:08 -03:00

83 lines
2.7 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import 'server-only'
import { sql } from '@payloadcms/db-postgres'
import type { Payload } from 'payload'
export type DrizzleTables = Record<string, Record<string, unknown>>
type PayloadDbTables = {
tables: DrizzleTables
}
type PostgresExecuteDb = {
execute: (query: ReturnType<typeof sql>) => Promise<unknown>
}
/** ~15-16 columns × 500 ≈ 7500-8000 bind params — well under PG's 65535 param limit. */
export const INSERT_CHUNK_SIZE = 500
export const chunk = <T>(rows: readonly T[], size: number): T[][] => {
const out: T[][] = []
for (let i = 0; i < rows.length; i += size) out.push(rows.slice(i, i + size))
return out
}
export const getDrizzleTables = (payload: Pick<Payload, 'db'>): DrizzleTables =>
(payload.db as unknown as PayloadDbTables).tables
export const requireTable = (
tables: DrizzleTables,
name: string,
): Record<string, unknown> => {
const table = tables[name]
if (!table) throw new Error(`Tabela drizzle ausente: ${name}. Rode as migrations.`)
return table
}
/**
* Fails fast when a drizzle table's JS-level column scaffold has drifted from
* what a bulk insert assumes (e.g. `contactId` vs `contact`) — catches the bug
* class before a silent bad insert instead of a runtime SQL error mid-import.
*/
export const assertDrizzleColumns = (
table: Record<string, unknown>,
tableName: string,
expectedColumns: readonly string[],
): void => {
const missing = expectedColumns.filter((column) => !(column in table))
if (missing.length > 0) {
throw new Error(
`Tabela drizzle "${tableName}" não tem as colunas esperadas: ${missing.join(', ')}. ` +
'O bulk insert usaria nomes de coluna divergentes do schema atual.',
)
}
}
/** Normalizes a drizzle `execute()` result (bare array vs `{ rows }`) into row objects. */
export const drizzleResultRows = (result: unknown): Array<Record<string, unknown>> => {
if (Array.isArray(result)) return result as Array<Record<string, unknown>>
if (
typeof result === 'object' &&
result !== null &&
'rows' in result &&
Array.isArray((result as { rows: unknown }).rows)
) {
return (result as { rows: Array<Record<string, unknown>> }).rows
}
return []
}
/** Returns the pool drizzle client for read-only `execute` aggregates (non-transactional). */
export const requirePostgresDrizzle = (
payload: Pick<Payload, 'db'>,
contextLabel: string,
): PostgresExecuteDb => {
if (payload.db.name !== 'postgres') {
throw new Error(`${contextLabel} exige o adaptador PostgreSQL.`)
}
const drizzle = (payload.db as unknown as { drizzle?: PostgresExecuteDb }).drizzle
if (!drizzle || typeof drizzle.execute !== 'function') {
throw new Error(`A sessão PostgreSQL de ${contextLabel} não está disponível.`)
}
return drizzle
}