1 import { IndexTypes } from "@medusajs/framework/types"
2 import { SqlEntityManager } from "@medusajs/framework/mikro-orm/postgresql"
3 import { schemaObjectRepresentationPropertiesToOmit } from "@types"
4 import { getPivotTableName, normalizeTableName } from "./normalze-table-name"
5
6 export async function createPartitions(
7 schemaObjectRepresentation: IndexTypes.SchemaObjectRepresentation,
8 manager: SqlEntityManager
9 ): Promise<void> {
10 const activeSchema = manager.config.get("schema")
11 ? `"${manager.config.get("schema")}".`
12 : ""
13
14 const createdPartitions: Set<string> = new Set()
15 const partitions = Object.keys(schemaObjectRepresentation)
16 .filter(
17 (key) =>
18 !schemaObjectRepresentationPropertiesToOmit.includes(key) &&
19 schemaObjectRepresentation[key].listeners.length > 0
20 )
21 .map((key) => {
22 const cName = normalizeTableName(key)
23
24 if (createdPartitions.has(cName)) {
25 return []
26 }
27 createdPartitions.add(cName)
28
29 const part: string[] = []
30 part.push(
31 `CREATE TABLE IF NOT EXISTS ${activeSchema}cat_${cName} PARTITION OF ${activeSchema}index_data FOR VALUES IN ('${key}')`
32 )
33
34 for (const parent of schemaObjectRepresentation[key].parents) {
35 if (parent.isInverse) {
36 continue
37 }
38
39 const pName = getPivotTableName(`${parent.ref.entity}${key}`)
40
41 if (createdPartitions.has(pName)) {
42 continue
43 }
44 createdPartitions.add(pName)
45
46 part.push(
47 `CREATE TABLE IF NOT EXISTS ${activeSchema}${pName} PARTITION OF ${activeSchema}index_relation FOR VALUES IN ('${parent.ref.entity}-${key}')`
48 )
49 }
50 return part
51 })
52 .flat()
53
54 if (!partitions.length) {
55 return
56 }
57
58 await manager.execute(partitions.join("; "))
59
60 // Create indexes for each partition
61 const indexCreationCommands = Object.keys(schemaObjectRepresentation)
62 .filter(
63 (key) =>
64 !schemaObjectRepresentationPropertiesToOmit.includes(key) &&
65 schemaObjectRepresentation[key].listeners.length > 0
66 )
67 .map((key) => {
68 const cName = normalizeTableName(key)
69 const part: string[] = []
70
71 part.push(
72 `CREATE INDEX CONCURRENTLY IF NOT EXISTS "IDX_cat_${cName}_data_gin" ON ${activeSchema}cat_${cName} USING GIN ("data" jsonb_path_ops)`
73 )
74
75 part.push(
76 `CREATE INDEX CONCURRENTLY IF NOT EXISTS "IDX_cat_${cName}_id" ON ${activeSchema}cat_${cName} ("id")`
77 )
78
79 for (const parent of schemaObjectRepresentation[key].parents) {
80 if (parent.isInverse) {
81 continue
82 }
83
84 const pName = getPivotTableName(`${parent.ref.entity}${key}`)
85
86 part.push(
87 `CREATE INDEX CONCURRENTLY IF NOT EXISTS "IDX_${pName}_child_id" ON ${activeSchema}${pName} ("child_id")`
88 )
89 }
90
91 return part
92 })
93 .flat()
94
95 for (const cmd of indexCreationCommands) {
96 try {
97 await manager.execute(cmd)
98 } catch (error) {
99 console.error(`Failed to create index: ${error.message}`)
100 }
101 }
102
103 // Create count estimate function
104 await manager.execute(`
105 CREATE OR REPLACE FUNCTION count_estimate(query text) RETURNS bigint AS $$
106 DECLARE
107 plan jsonb;
108 BEGIN
109 EXECUTE 'EXPLAIN (FORMAT JSON) ' || query INTO plan;
110 RETURN (plan->0->'Plan'->>'Plan Rows')::bigint;
111 END;
112 $$ LANGUAGE plpgsql;
113 `)
114 }