pg-meta-indexes.ts105 lines · main
1import { z } from 'zod'
2
3import { DEFAULT_SYSTEM_SCHEMAS } from './constants'
4import { filterByList } from './helpers'
5import { literal, safeSql, type SafeSqlFragment } from './pg-format'
6import { INDEXES_SQL } from './sql/indexes'
7
8const pgIndexZod = z.object({
9 id: z.number(),
10 table_id: z.number(),
11 schema: z.string(),
12 number_of_attributes: z.number(),
13 number_of_key_attributes: z.number(),
14 is_unique: z.boolean(),
15 is_primary: z.boolean(),
16 is_exclusion: z.boolean(),
17 is_immediate: z.boolean(),
18 is_clustered: z.boolean(),
19 is_valid: z.boolean(),
20 check_xmin: z.boolean(),
21 is_ready: z.boolean(),
22 is_live: z.boolean(),
23 is_replica_identity: z.boolean(),
24 key_attributes: z.array(z.number()),
25 collation: z.array(z.number()),
26 class: z.array(z.number()),
27 options: z.array(z.number()),
28 index_predicate: z.string().nullable(),
29 comment: z.string().nullable(),
30 index_definition: z.string(),
31 access_method: z.string(),
32 index_attributes: z.array(
33 z.object({
34 attribute_number: z.number(),
35 attribute_name: z.string(),
36 data_type: z.string(),
37 })
38 ),
39})
40
41const pgIndexArrayZod = z.array(pgIndexZod)
42const pgIndexOptionalZod = z.optional(pgIndexZod)
43
44function list({
45 includeSystemSchemas = false,
46 includedSchemas,
47 excludedSchemas,
48 limit,
49 offset,
50}: {
51 includeSystemSchemas?: boolean
52 includedSchemas?: string[]
53 excludedSchemas?: string[]
54 limit?: number
55 offset?: number
56} = {}): {
57 sql: SafeSqlFragment
58 zod: typeof pgIndexArrayZod
59} {
60 let sql = safeSql`
61 with indexes as (${INDEXES_SQL})
62 select *
63 from indexes
64 `
65 const filter = filterByList(
66 includedSchemas,
67 excludedSchemas,
68 !includeSystemSchemas ? DEFAULT_SYSTEM_SCHEMAS : undefined
69 )
70 if (filter) {
71 sql = safeSql`${sql} where schema ${filter}`
72 }
73 if (limit) {
74 sql = safeSql`${sql} limit ${literal(limit)}`
75 }
76 if (offset) {
77 sql = safeSql`${sql} offset ${literal(offset)}`
78 }
79 return {
80 sql,
81 zod: pgIndexArrayZod,
82 }
83}
84
85function retrieve({ id }: { id: number }): {
86 sql: SafeSqlFragment
87 zod: typeof pgIndexOptionalZod
88} {
89 const sql = safeSql`
90 with indexes as (${INDEXES_SQL})
91 select *
92 from indexes
93 where id = ${literal(id)};
94 `
95 return {
96 sql,
97 zod: pgIndexOptionalZod,
98 }
99}
100
101export default {
102 list,
103 retrieve,
104 zod: pgIndexZod,
105}