generate-tenancy-schema.ts 1.4 KB

123456789101112131415161718192021222324252627282930313233
  1. /**
  2. * Writes src/lib/backup/tenancy-schema.ts from the Prisma schema. Run after a
  3. * schema change: `npx tsx scripts/generate-tenancy-schema.ts`. The test in
  4. * src/__tests__/lib/backup/tenancy-schema.test.ts fails until it is run.
  5. */
  6. import { execFileSync } from 'node:child_process'
  7. import { readdirSync, readFileSync, writeFileSync } from 'node:fs'
  8. import path from 'node:path'
  9. import { parseSchemaGraph } from '../src/lib/backup/schema-graph'
  10. const root = process.cwd()
  11. const dir = path.join(root, 'prisma', 'schema')
  12. const schema = readdirSync(dir)
  13. .filter((name) => name.endsWith('.prisma'))
  14. .sort()
  15. .map((name) => readFileSync(path.join(dir, name), 'utf-8'))
  16. .join('\n')
  17. const graph = parseSchemaGraph(schema)
  18. const source = `// Generated from prisma/schema by scripts/generate-tenancy-schema.ts. Do not edit.
  19. import type { SchemaGraph } from './schema-graph'
  20. /**
  21. * Which models carry an organisation, which columns are foreign keys and how
  22. * a child model reaches its workshop. What the restore's tenancy guard reads.
  23. */
  24. export const TENANCY_SCHEMA: SchemaGraph = ${JSON.stringify(graph, null, 2)}
  25. `
  26. const target = path.join(root, 'src/lib/backup/tenancy-schema.ts')
  27. writeFileSync(target, source)
  28. // Written the way the repository formats TypeScript, so `npm run check` is quiet.
  29. execFileSync('npx', ['biome', 'format', '--write', target], { stdio: 'inherit' })
  30. console.log(`tenancy-schema.ts: ${Object.keys(graph).length} models`)