@graphoria/server 0.1.5 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (135) hide show
  1. package/dist/src/analyzeQuery/resolveVariables.d.ts.map +1 -1
  2. package/dist/src/authentication/jwt.d.ts.map +1 -1
  3. package/dist/src/authentication/paseto.d.ts.map +1 -1
  4. package/dist/src/authentication/tokenRepository.d.ts +2 -1
  5. package/dist/src/authentication/tokenRepository.d.ts.map +1 -1
  6. package/dist/src/config/helpers/operationHelper.d.ts +60 -6
  7. package/dist/src/config/helpers/operationHelper.d.ts.map +1 -1
  8. package/dist/src/config/helpers/operationHelper.test.d.ts +2 -0
  9. package/dist/src/config/helpers/operationHelper.test.d.ts.map +1 -0
  10. package/dist/src/config/index.d.ts +65 -60
  11. package/dist/src/config/index.d.ts.map +1 -1
  12. package/dist/src/config/types/ai.d.ts +9 -3
  13. package/dist/src/config/types/ai.d.ts.map +1 -1
  14. package/dist/src/config/types/auth.d.ts +55 -15
  15. package/dist/src/config/types/auth.d.ts.map +1 -1
  16. package/dist/src/config/types/cron.d.ts +96 -2
  17. package/dist/src/config/types/cron.d.ts.map +1 -1
  18. package/dist/src/config/types/db.d.ts +102 -29
  19. package/dist/src/config/types/db.d.ts.map +1 -1
  20. package/dist/src/config/types/index.d.ts +1 -1
  21. package/dist/src/config/types/index.d.ts.map +1 -1
  22. package/dist/src/config/types/operation.d.ts +49 -17
  23. package/dist/src/config/types/operation.d.ts.map +1 -1
  24. package/dist/src/config/types/queue.d.ts +61 -14
  25. package/dist/src/config/types/queue.d.ts.map +1 -1
  26. package/dist/src/config/types/remote-rest.d.ts +10 -1
  27. package/dist/src/config/types/remote-rest.d.ts.map +1 -1
  28. package/dist/src/config/types/remote-schema.d.ts +13 -3
  29. package/dist/src/config/types/remote-schema.d.ts.map +1 -1
  30. package/dist/src/config/types/virtual-columns.d.ts +1 -1
  31. package/dist/src/config/types/virtual-columns.d.ts.map +1 -1
  32. package/dist/src/configuration/getSchemas/index.d.ts +6 -4
  33. package/dist/src/configuration/getSchemas/index.d.ts.map +1 -1
  34. package/dist/src/configuration/getSchemas/mergeEntities/index.d.ts +9 -2
  35. package/dist/src/configuration/getSchemas/mergeEntities/index.d.ts.map +1 -1
  36. package/dist/src/configuration/getSchemas/mergeEntities/index.test.d.ts +2 -0
  37. package/dist/src/configuration/getSchemas/mergeEntities/index.test.d.ts.map +1 -0
  38. package/dist/src/configuration/getSchemas/type-definition-generator/index.d.ts.map +1 -1
  39. package/dist/src/configuration/index.d.ts +5 -4
  40. package/dist/src/configuration/index.d.ts.map +1 -1
  41. package/dist/src/configuration/rest/generateOpenAPI.d.ts.map +1 -1
  42. package/dist/src/configuration/rest/handleRESTRequestFactory.d.ts.map +1 -1
  43. package/dist/src/configuration/rest/parseStringParams.d.ts +15 -0
  44. package/dist/src/configuration/rest/parseStringParams.d.ts.map +1 -0
  45. package/dist/src/configuration/rest/parseStringParams.test.d.ts +2 -0
  46. package/dist/src/configuration/rest/parseStringParams.test.d.ts.map +1 -0
  47. package/dist/src/databases/common.d.ts +9 -1
  48. package/dist/src/databases/common.d.ts.map +1 -1
  49. package/dist/src/databases/directives.d.ts.map +1 -1
  50. package/dist/src/databases/engines/mssql/connection.d.ts +1 -1
  51. package/dist/src/databases/engines/mssql/connection.d.ts.map +1 -1
  52. package/dist/src/databases/engines/mssql/getStructure.d.ts +1 -0
  53. package/dist/src/databases/engines/mssql/getStructure.d.ts.map +1 -1
  54. package/dist/src/databases/engines/mssql/query/index.d.ts.map +1 -1
  55. package/dist/src/databases/engines/mysql/connection.d.ts.map +1 -1
  56. package/dist/src/databases/engines/mysql/getStructure.d.ts +1 -0
  57. package/dist/src/databases/engines/mysql/getStructure.d.ts.map +1 -1
  58. package/dist/src/databases/engines/mysql/placeholders.d.ts +22 -0
  59. package/dist/src/databases/engines/mysql/placeholders.d.ts.map +1 -0
  60. package/dist/src/databases/engines/mysql/placeholders.test.d.ts +2 -0
  61. package/dist/src/databases/engines/mysql/placeholders.test.d.ts.map +1 -0
  62. package/dist/src/databases/engines/mysql/query/index.d.ts.map +1 -1
  63. package/dist/src/databases/engines/postgresql/getStructure.d.ts +1 -0
  64. package/dist/src/databases/engines/postgresql/getStructure.d.ts.map +1 -1
  65. package/dist/src/databases/engines/postgresql/query/index.d.ts.map +1 -1
  66. package/dist/src/databases/high-level-operations.d.ts +1 -0
  67. package/dist/src/databases/high-level-operations.d.ts.map +1 -1
  68. package/dist/src/databases/identifierMapping.test.d.ts +2 -0
  69. package/dist/src/databases/identifierMapping.test.d.ts.map +1 -0
  70. package/dist/src/databases/metadata/structure.d.ts +1 -0
  71. package/dist/src/databases/metadata/structure.d.ts.map +1 -1
  72. package/dist/src/databases/sqlTypeUtils.d.ts.map +1 -1
  73. package/dist/src/databases/transformers/data-transformers.d.ts +1 -0
  74. package/dist/src/databases/transformers/data-transformers.d.ts.map +1 -1
  75. package/dist/src/databases/transformers/genResolverName.d.ts.map +1 -1
  76. package/dist/src/databases/transformers/graphqlName.d.ts +23 -0
  77. package/dist/src/databases/transformers/graphqlName.d.ts.map +1 -0
  78. package/dist/src/databases/transformers/graphqlName.test.d.ts +2 -0
  79. package/dist/src/databases/transformers/graphqlName.test.d.ts.map +1 -0
  80. package/dist/src/singletons/env.d.ts +2 -2
  81. package/dist/src/types/env.d.ts +56 -56
  82. package/dist/src/types/resolver.d.ts +12 -2
  83. package/dist/src/types/resolver.d.ts.map +1 -1
  84. package/dist/src/types/zod/auth.d.ts +6 -6
  85. package/dist/src/types/zod/configuration.d.ts +52 -52
  86. package/dist/src/types/zod/configuration.d.ts.map +1 -1
  87. package/dist/src/types/zod/cron.d.ts +1 -1
  88. package/dist/src/types/zod/cron.d.ts.map +1 -1
  89. package/dist/src/types/zod/db.d.ts +21 -12
  90. package/dist/src/types/zod/db.d.ts.map +1 -1
  91. package/dist/src/types/zod/queue.d.ts +38 -38
  92. package/dist/src/types/zod/strict-keys.test.d.ts +2 -0
  93. package/dist/src/types/zod/strict-keys.test.d.ts.map +1 -0
  94. package/dist/tsconfig.tsbuildinfo +1 -1
  95. package/package.json +2 -2
  96. package/src/analyzeQuery/resolveVariables.ts +37 -7
  97. package/src/authentication/jwt.ts +3 -1
  98. package/src/authentication/paseto.ts +3 -1
  99. package/src/authentication/tokenRepository.ts +12 -4
  100. package/src/config/helpers/operationHelper.ts +146 -5
  101. package/src/config/index.ts +139 -62
  102. package/src/config/types/ai.ts +2 -2
  103. package/src/config/types/auth.ts +37 -6
  104. package/src/config/types/cron.ts +1 -1
  105. package/src/config/types/db.ts +10 -10
  106. package/src/config/types/index.ts +2 -0
  107. package/src/config/types/operation.ts +49 -9
  108. package/src/config/types/queue.ts +8 -8
  109. package/src/config/types/remote-rest.ts +1 -1
  110. package/src/config/types/remote-schema.ts +2 -2
  111. package/src/config/types/virtual-columns.ts +1 -1
  112. package/src/configuration/getSchemas/mergeEntities/index.ts +32 -1
  113. package/src/configuration/getSchemas/type-definition-generator/index.ts +23 -9
  114. package/src/configuration/rest/generateOpenAPI.ts +5 -9
  115. package/src/configuration/rest/handleRESTRequestFactory.ts +38 -14
  116. package/src/configuration/rest/parseStringParams.ts +92 -0
  117. package/src/databases/common.ts +163 -66
  118. package/src/databases/directives.ts +26 -8
  119. package/src/databases/engines/mssql/connection.ts +1 -1
  120. package/src/databases/engines/mssql/query/index.ts +47 -16
  121. package/src/databases/engines/mysql/auth.ts +2 -2
  122. package/src/databases/engines/mysql/connection.ts +5 -4
  123. package/src/databases/engines/mysql/getStructure.ts +61 -30
  124. package/src/databases/engines/mysql/placeholders.ts +84 -0
  125. package/src/databases/engines/mysql/query/index.ts +68 -10
  126. package/src/databases/engines/postgresql/query/index.ts +59 -7
  127. package/src/databases/high-level-operations.ts +2 -2
  128. package/src/databases/sqlTypeUtils.ts +3 -1
  129. package/src/databases/transformers/genResolverName.ts +3 -3
  130. package/src/databases/transformers/graphqlName.ts +28 -0
  131. package/src/subscriptions/strategies/index.ts +1 -1
  132. package/src/subscriptions/strategies/queue.ts +1 -1
  133. package/src/types/resolver.ts +17 -1
  134. package/src/types/zod/configuration.ts +1 -1
  135. package/src/types/zod/db.ts +4 -0
@@ -16,26 +16,32 @@ import {
16
16
  isAggregationField,
17
17
  isSingleQuery,
18
18
  processFieldSelectionsMSSQL,
19
+ sqlColumnName,
19
20
  wrapIdentifierMSSQL,
20
21
  } from "../../../common";
21
22
 
23
+ import { applyDirectives } from "../../../directives";
24
+
22
25
  // FOR JSON PATH uses the unbracketed alias as the JSON key, so bracket-quoting
23
26
  // (required for reserved words like PRINT) never leaks into results.
24
27
 
25
28
  // Generate CTE for aggregations
26
29
  const buildAggregationCTE = (
30
+ entities: MergedEntities,
31
+ tableName: string,
27
32
  groupByInfo: GroupByInfo,
28
33
  dottedQuotedName: string,
29
34
  tableAlias: string,
30
35
  whereClause: string,
31
36
  ): string => {
32
37
  const { groupByFields, aggregations, cteAlias } = groupByInfo;
38
+ const sqlName = (fieldName: string) => sqlColumnName(entities, tableName, fieldName);
33
39
 
34
40
  const selectClauses: string[] = [];
35
41
 
36
42
  // Add group by fields
37
43
  groupByFields.forEach((field) => {
38
- selectClauses.push(`${tableAlias}.${wrapIdentifierMSSQL(field)}`);
44
+ selectClauses.push(`${tableAlias}.${wrapIdentifierMSSQL(sqlName(field))}`);
39
45
  });
40
46
 
41
47
  // Add aggregations
@@ -44,13 +50,17 @@ const buildAggregationCTE = (
44
50
  selectClauses.push(`COUNT(*) AS ${agg.alias}`);
45
51
  } else {
46
52
  const func = agg.name.toUpperCase();
47
- selectClauses.push(
48
- `${func}(${tableAlias}.${wrapIdentifierMSSQL(agg.fieldName)}) AS ${agg.alias}`,
49
- );
53
+ // SQL Server's AVG over an integer column is integer division — AVG of
54
+ // 1, 5, 5, 2 is 3, not 3.25 so the average has to be taken on a float.
55
+ const operand =
56
+ agg.name === "avg"
57
+ ? `CAST(${tableAlias}.${wrapIdentifierMSSQL(sqlName(agg.fieldName))} AS FLOAT)`
58
+ : `${tableAlias}.${wrapIdentifierMSSQL(sqlName(agg.fieldName))}`;
59
+ selectClauses.push(`${func}(${operand}) AS ${agg.alias}`);
50
60
  }
51
61
  });
52
62
 
53
- const groupByClause = `GROUP BY ${groupByFields.map((field) => `${tableAlias}.${wrapIdentifierMSSQL(field)}`).join(", ")}`;
63
+ const groupByClause = `GROUP BY ${groupByFields.map((field) => `${tableAlias}.${wrapIdentifierMSSQL(sqlName(field))}`).join(", ")}`;
54
64
 
55
65
  return `${cteAlias} AS (
56
66
  SELECT
@@ -64,6 +74,7 @@ const buildAggregationCTE = (
64
74
  // Build the main query for grouped results
65
75
  const buildGroupedQuery = (
66
76
  entities: MergedEntities,
77
+ variablesDefinition: VariableDefinition[],
67
78
  field: SelectionAnalysis,
68
79
  groupByInfo: GroupByInfo,
69
80
  dottedQuotedName: string,
@@ -73,15 +84,22 @@ const buildGroupedQuery = (
73
84
  const { groupByFields, aggregations, hasItems, keyResolved, hasKey, keys, cteAlias } =
74
85
  groupByInfo;
75
86
 
87
+ const sqlName = (fieldName: string) => sqlColumnName(entities, field.name, fieldName);
88
+
76
89
  const selectClauses: string[] = [];
77
90
 
78
91
  if (hasKey) {
79
92
  // Add key object with group by fields
80
93
  const keyFields = keys
81
- .map(
82
- (field) =>
83
- `${cteAlias}.${wrapIdentifierMSSQL(field.name)} AS ${wrapIdentifierMSSQL(field.alias || field.name)}`,
84
- )
94
+ .map((key) => {
95
+ const selector = applyDirectives(
96
+ `${cteAlias}.${wrapIdentifierMSSQL(sqlName(key.name))}`,
97
+ key.directives,
98
+ "mssql",
99
+ variablesDefinition,
100
+ );
101
+ return `${selector} AS ${wrapIdentifierMSSQL(key.alias || key.name)}`;
102
+ })
85
103
  .join(", ");
86
104
 
87
105
  selectClauses.push(
@@ -107,16 +125,21 @@ const buildGroupedQuery = (
107
125
  if (itemsSelection?.selections) {
108
126
  const itemFields = itemsSelection.selections
109
127
  .filter((sel) => !isAggregationField(sel.name) && sel.name !== "items")
110
- .map(
111
- (sel) =>
112
- `${tableAlias}.${wrapIdentifierMSSQL(sel.name)} AS ${wrapIdentifierMSSQL(sel.alias || sel.name)}`,
113
- )
128
+ .map((sel) => {
129
+ const selector = applyDirectives(
130
+ `${tableAlias}.${wrapIdentifierMSSQL(sqlName(sel.name))}`,
131
+ sel.directives,
132
+ "mssql",
133
+ variablesDefinition,
134
+ );
135
+ return `${selector} AS ${wrapIdentifierMSSQL(sel.alias || sel.name)}`;
136
+ })
114
137
  .join(", ");
115
138
 
116
139
  if (itemFields) {
117
140
  const joinConditions = groupByFields.map(
118
- (field) =>
119
- `${tableAlias}.${wrapIdentifierMSSQL(field)} = ${cteAlias}.${wrapIdentifierMSSQL(field)}`,
141
+ (groupByField) =>
142
+ `${tableAlias}.${wrapIdentifierMSSQL(sqlName(groupByField))} = ${cteAlias}.${wrapIdentifierMSSQL(sqlName(groupByField))}`,
120
143
  );
121
144
 
122
145
  selectClauses.push(`JSON_QUERY(ISNULL((
@@ -195,7 +218,14 @@ export const generateSQL = (
195
218
  {},
196
219
  );
197
220
 
198
- const cte = buildAggregationCTE(groupByInfo, dottedQuotedName, tableAlias, whereClause);
221
+ const cte = buildAggregationCTE(
222
+ entities,
223
+ field.name,
224
+ groupByInfo,
225
+ dottedQuotedName,
226
+ tableAlias,
227
+ whereClause,
228
+ );
199
229
  ctes.push(cte);
200
230
  }
201
231
 
@@ -265,6 +295,7 @@ export const buildSQLForField = (
265
295
  // Handle GROUP BY aggregation query
266
296
  const mainQuery = buildGroupedQuery(
267
297
  entities,
298
+ variablesDefinition,
268
299
  field,
269
300
  groupByInfo,
270
301
  dottedQuotedName,
@@ -41,7 +41,7 @@ export const checkUserCredentials = async (
41
41
  const schema = assertSafeIdentifier(auth.schema!, "schema");
42
42
 
43
43
  const result = await pool.unsafe<UserRecord[]>(
44
- `SELECT * FROM \`${schema}\`.\`user\` WHERE username = $1 AND is_active = TRUE`,
44
+ `SELECT * FROM \`${schema}\`.\`user\` WHERE username = ? AND is_active = TRUE`,
45
45
  [username],
46
46
  );
47
47
 
@@ -94,7 +94,7 @@ export const insertAuthUser = async (
94
94
 
95
95
  await pool.unsafe(
96
96
  `INSERT INTO \`${schema}\`.\`user\` (username, password, role, is_active, claims)
97
- VALUES ($1, $2, $3, TRUE, $4)`,
97
+ VALUES (?, ?, ?, TRUE, ?)`,
98
98
  [input.username, hashed, input.role, JSON.stringify(input.claims ?? {})],
99
99
  );
100
100
  };
@@ -6,6 +6,7 @@ import type { Database } from "../../../types/configuration";
6
6
  import type { ProcedureResolver } from "../../../types/db";
7
7
 
8
8
  import { databasesConnections } from "../../../singletons/databases";
9
+ import { toMySQLPlaceholders } from "./placeholders";
9
10
 
10
11
  export const getPool = async (db: Database) => {
11
12
  const opts = db.connectionOptions as BunSQLConnectionOptions | undefined;
@@ -42,10 +43,10 @@ export const executeQueryFactory =
42
43
  ) => {
43
44
  const pool = singleQuery ? await getPool(db) : await getPoolSingleton(db);
44
45
 
45
- const result = await pool.unsafe<T>(
46
- query,
47
- variablesDefinition.map((v) => values[v.name]),
48
- );
46
+ // Bun's MySQL adapter binds `?` positionally; the builders emit `$n`.
47
+ const bound = toMySQLPlaceholders(query, variablesDefinition, values);
48
+
49
+ const result = await pool.unsafe<T>(bound.query, bound.params);
49
50
 
50
51
  if (singleQuery) {
51
52
  await pool.close();
@@ -3,8 +3,23 @@ import type { Database } from "../../../types/configuration";
3
3
  import { DatabaseStructureZod } from "../../../types/zod/db";
4
4
  import { executeQueryJSONSingle } from "./connection";
5
5
 
6
+ /**
7
+ * Ordering carried out of SQL and restored here: JSON_ARRAYAGG accepts no
8
+ * ORDER BY. GROUP_CONCAT does, but silently truncates at group_concat_max_len
9
+ * (1024 bytes by default), which any table past ~10 columns exceeds — the JSON
10
+ * is then cut mid-object and CAST(... AS JSON) fails.
11
+ */
12
+ type Ordered = { ordinalPosition?: number };
13
+ type RawForeignKey = { fkName?: string; columns: Ordered[] };
14
+ type RawStructure = {
15
+ tables?: { columns?: Ordered[]; foreignKeys?: RawForeignKey[] }[];
16
+ storedProcedures?: { parameters?: Ordered[] }[];
17
+ };
18
+
19
+ const byOrdinal = (a: Ordered, b: Ordered) => (a.ordinalPosition ?? 0) - (b.ordinalPosition ?? 0);
20
+
6
21
  export const getDatabaseStructure = async (db: Database) => {
7
- const res = await executeQueryJSONSingle(
22
+ const res = await executeQueryJSONSingle<RawStructure>(
8
23
  `
9
24
  SELECT JSON_OBJECT(
10
25
  'tables', JSON_ARRAYAGG(
@@ -31,7 +46,7 @@ export const getDatabaseStructure = async (db: Database) => {
31
46
  )
32
47
  )
33
48
  FROM information_schema.routines r
34
-
49
+
35
50
  -- Parameters
36
51
  LEFT JOIN LATERAL (
37
52
  SELECT JSON_ARRAYAGG(
@@ -40,16 +55,16 @@ export const getDatabaseStructure = async (db: Database) => {
40
55
  'dataType', p.data_type,
41
56
  'maxLength', COALESCE(p.character_maximum_length, 0),
42
57
  'precision', COALESCE(p.numeric_precision, 0),
43
- 'scale', COALESCE(p.numeric_scale, 0)
58
+ 'scale', COALESCE(p.numeric_scale, 0),
59
+ 'ordinalPosition', p.ordinal_position
44
60
  )
45
61
  ) AS param_array
46
62
  FROM information_schema.parameters p
47
63
  WHERE p.specific_name = r.specific_name
48
64
  AND p.specific_schema = r.routine_schema
49
65
  AND p.parameter_name IS NOT NULL
50
- ORDER BY p.ordinal_position
51
66
  ) params ON true
52
-
67
+
53
68
  WHERE r.routine_type IN ('FUNCTION', 'PROCEDURE')
54
69
  AND r.routine_schema NOT IN ('mysql', 'information_schema', 'performance_schema', 'sys')
55
70
  ),
@@ -58,22 +73,20 @@ export const getDatabaseStructure = async (db: Database) => {
58
73
  ) as json_result
59
74
  FROM (
60
75
  SELECT table_schema, table_name, table_type
61
- FROM information_schema.tables
76
+ FROM information_schema.tables
62
77
  WHERE table_type IN ('BASE TABLE', 'VIEW')
63
78
  AND table_schema NOT IN ('mysql', 'information_schema', 'performance_schema', 'sys')
64
79
  ) t
65
80
  LEFT JOIN LATERAL (
66
- -- build an ordered JSON array of columns using GROUP_CONCAT
67
- SELECT IFNULL(
68
- CAST(CONCAT('[', GROUP_CONCAT(
69
- JSON_OBJECT(
70
- 'name', isc.column_name,
71
- 'dataType', isc.data_type,
72
- 'isNullable', CASE WHEN isc.is_nullable = 'YES' THEN true ELSE false END,
73
- 'collation', isc.collation_name,
74
- 'description', NULL
75
- ) ORDER BY isc.ordinal_position SEPARATOR ','), ']') AS JSON),
76
- JSON_ARRAY()
81
+ SELECT JSON_ARRAYAGG(
82
+ JSON_OBJECT(
83
+ 'name', isc.column_name,
84
+ 'dataType', isc.data_type,
85
+ 'isNullable', CASE WHEN isc.is_nullable = 'YES' THEN true ELSE false END,
86
+ 'collation', isc.collation_name,
87
+ 'description', NULL,
88
+ 'ordinalPosition', isc.ordinal_position
89
+ )
77
90
  ) AS columns
78
91
  FROM information_schema.columns isc
79
92
  WHERE isc.table_schema = t.table_schema
@@ -81,26 +94,28 @@ export const getDatabaseStructure = async (db: Database) => {
81
94
  ) col ON TRUE
82
95
  LEFT JOIN LATERAL (
83
96
  -- aggregate FKs: first aggregate columns per constraint, then aggregate constraints
84
- SELECT IFNULL(
85
- CAST(CONCAT('[', GROUP_CONCAT(
86
- JSON_OBJECT(
87
- 'schema', fk_sub.referenced_table_schema,
88
- 'name', fk_sub.referenced_table_name,
89
- 'columns', fk_sub.columns_arr
90
- ) ORDER BY fk_sub.fk_name SEPARATOR ','), ']') AS JSON),
91
- JSON_ARRAY()
97
+ SELECT JSON_ARRAYAGG(
98
+ JSON_OBJECT(
99
+ 'schema', fk_sub.referenced_table_schema,
100
+ 'name', fk_sub.referenced_table_name,
101
+ 'columns', fk_sub.columns_arr,
102
+ 'fkName', fk_sub.fk_name
103
+ )
92
104
  ) AS fk_agg
93
105
  FROM (
94
- SELECT
106
+ SELECT
95
107
  kcu.constraint_name AS fk_name,
96
108
  kcu.table_schema,
97
109
  kcu.table_name,
98
110
  kcu.referenced_table_schema,
99
111
  kcu.referenced_table_name,
100
- CAST(CONCAT('[', GROUP_CONCAT(
101
- JSON_OBJECT('source', kcu.column_name, 'target', kcu.referenced_column_name)
102
- ORDER BY kcu.ordinal_position SEPARATOR ','
103
- ), ']') AS JSON) AS columns_arr
112
+ JSON_ARRAYAGG(
113
+ JSON_OBJECT(
114
+ 'source', kcu.column_name,
115
+ 'target', kcu.referenced_column_name,
116
+ 'ordinalPosition', kcu.ordinal_position
117
+ )
118
+ ) AS columns_arr
104
119
  FROM information_schema.key_column_usage kcu
105
120
  WHERE kcu.referenced_table_schema IS NOT NULL
106
121
  AND kcu.table_schema = t.table_schema
@@ -113,5 +128,21 @@ export const getDatabaseStructure = async (db: Database) => {
113
128
  db,
114
129
  );
115
130
 
131
+ for (const table of res.tables ?? []) {
132
+ table.columns?.sort(byOrdinal);
133
+ table.foreignKeys?.sort((a, b) => (a.fkName ?? "").localeCompare(b.fkName ?? ""));
134
+
135
+ // TableRelationshipZod is strict, so the ordering keys must go before parsing.
136
+ for (const foreignKey of table.foreignKeys ?? []) {
137
+ foreignKey.columns.sort(byOrdinal);
138
+ for (const column of foreignKey.columns) delete column.ordinalPosition;
139
+ delete foreignKey.fkName;
140
+ }
141
+ }
142
+
143
+ for (const storedProcedure of res.storedProcedures ?? []) {
144
+ storedProcedure.parameters?.sort(byOrdinal);
145
+ }
146
+
116
147
  return DatabaseStructureZod.parse(res);
117
148
  };
@@ -0,0 +1,84 @@
1
+ import type { VariableDefinition } from "../../../analyzeQuery/types";
2
+
3
+ /**
4
+ * Rewrites the builder's PostgreSQL-style `$n` placeholders to MySQL's `?`.
5
+ *
6
+ * The query builders are shared across engines and number placeholders by index
7
+ * into `variablesDefinition`. Bun's MySQL adapter binds `?` by position of
8
+ * occurrence in the statement text, and the two orders do not match: the WHERE
9
+ * string is interpolated into more than one sub-statement on the aggregate path,
10
+ * nested subqueries are built before the outer WHERE is appended, and a single
11
+ * directive can emit `$2` before `$1` and `$1` twice. Rewriting here — the one
12
+ * point where the finished statement and its values meet — makes text order the
13
+ * binding order by construction.
14
+ *
15
+ * The scan skips quoted runs because generated SQL does carry `$n` inside string
16
+ * literals: a config-supplied relationship condition value is interpolated as a
17
+ * literal, and introspected identifiers may contain `$`.
18
+ */
19
+ export const toMySQLPlaceholders = (
20
+ query: string,
21
+ variablesDefinition: VariableDefinition[] = [],
22
+ values: Record<string, unknown> = {},
23
+ ): { query: string; params: unknown[] } => {
24
+ const params: unknown[] = [];
25
+ let rewritten = "";
26
+ let index = 0;
27
+
28
+ while (index < query.length) {
29
+ const char = query[index]!;
30
+
31
+ if (char === "'" || char === '"' || char === "`") {
32
+ const start = index;
33
+ index++;
34
+
35
+ while (index < query.length) {
36
+ // Backslash escapes apply inside string literals but never inside a
37
+ // backtick-quoted identifier, where the only escape is a doubled tick.
38
+ if (char !== "`" && query[index] === "\\") {
39
+ index += 2;
40
+ continue;
41
+ }
42
+ if (query[index] === char) {
43
+ if (query[index + 1] === char) {
44
+ index += 2;
45
+ continue;
46
+ }
47
+ index++;
48
+ break;
49
+ }
50
+ index++;
51
+ }
52
+
53
+ rewritten += query.slice(start, index);
54
+ continue;
55
+ }
56
+
57
+ if (char === "$") {
58
+ const match = /^\$(\d+)/.exec(query.slice(index));
59
+
60
+ if (match) {
61
+ const position = Number(match[1]);
62
+ const definition = variablesDefinition[position - 1];
63
+
64
+ if (!definition) {
65
+ throw new Error(
66
+ `MySQL query references $${position} but only ${variablesDefinition.length} variable${
67
+ variablesDefinition.length === 1 ? " is" : "s are"
68
+ } defined`,
69
+ );
70
+ }
71
+
72
+ params.push(values[definition.name]);
73
+ rewritten += "?";
74
+ index += match[0].length;
75
+ continue;
76
+ }
77
+ }
78
+
79
+ rewritten += char;
80
+ index++;
81
+ }
82
+
83
+ return { query: rewritten, params };
84
+ };
@@ -16,23 +16,29 @@ import {
16
16
  isAggregationField,
17
17
  isSingleQuery,
18
18
  processFieldSelectionsMySQL,
19
+ sqlColumnName,
19
20
  wrapIdentifierMySQL,
20
21
  } from "../../../common";
21
22
 
23
+ import { applyDirectives } from "../../../directives";
24
+
22
25
  // Generate CTE for aggregations
23
26
  const buildAggregationCTE = (
27
+ entities: MergedEntities,
28
+ tableName: string,
24
29
  groupByInfo: GroupByInfo,
25
30
  dottedQuotedName: string,
26
31
  tableAlias: string,
27
32
  whereClause: string,
28
33
  ): string => {
29
34
  const { groupByFields, aggregations, cteAlias } = groupByInfo;
35
+ const sqlName = (fieldName: string) => sqlColumnName(entities, tableName, fieldName);
30
36
 
31
37
  const selectClauses: string[] = [];
32
38
 
33
39
  // Add group by fields
34
40
  groupByFields.forEach((field) => {
35
- selectClauses.push(`${tableAlias}.${wrapIdentifierMySQL(field)}`);
41
+ selectClauses.push(`${tableAlias}.${wrapIdentifierMySQL(sqlName(field))}`);
36
42
  });
37
43
 
38
44
  // Add aggregations
@@ -42,12 +48,12 @@ const buildAggregationCTE = (
42
48
  } else {
43
49
  const func = agg.name.toUpperCase();
44
50
  selectClauses.push(
45
- `${func}(${tableAlias}.${wrapIdentifierMySQL(agg.fieldName)}) AS ${agg.alias}`,
51
+ `${func}(${tableAlias}.${wrapIdentifierMySQL(sqlName(agg.fieldName))}) AS ${agg.alias}`,
46
52
  );
47
53
  }
48
54
  });
49
55
 
50
- const groupByClause = `GROUP BY ${groupByFields.map((field) => `${tableAlias}.${wrapIdentifierMySQL(field)}`).join(", ")}`;
56
+ const groupByClause = `GROUP BY ${groupByFields.map((field) => `${tableAlias}.${wrapIdentifierMySQL(sqlName(field))}`).join(", ")}`;
51
57
 
52
58
  return `${cteAlias} AS (
53
59
  SELECT
@@ -61,6 +67,7 @@ const buildAggregationCTE = (
61
67
  // Build the main query for grouped results
62
68
  const buildGroupedQuery = (
63
69
  entities: MergedEntities,
70
+ variablesDefinition: VariableDefinition[],
64
71
  field: SelectionAnalysis,
65
72
  groupByInfo: GroupByInfo,
66
73
  dottedQuotedName: string,
@@ -70,12 +77,22 @@ const buildGroupedQuery = (
70
77
  const { groupByFields, aggregations, hasItems, keyResolved, hasKey, keys, cteAlias } =
71
78
  groupByInfo;
72
79
 
80
+ const sqlName = (fieldName: string) => sqlColumnName(entities, field.name, fieldName);
81
+
73
82
  const selectClauses: string[] = [];
74
83
 
75
84
  if (hasKey) {
76
85
  // Add key object with group by fields
77
86
  const keyFields = keys
78
- .map((key) => `'${key.alias || key.name}', ${cteAlias}.${wrapIdentifierMySQL(key.name)}`)
87
+ .map((key) => {
88
+ const selector = applyDirectives(
89
+ `${cteAlias}.${wrapIdentifierMySQL(sqlName(key.name))}`,
90
+ key.directives,
91
+ "mysql",
92
+ variablesDefinition,
93
+ );
94
+ return `'${key.alias || key.name}', ${selector}`;
95
+ })
79
96
  .join(", ");
80
97
 
81
98
  selectClauses.push(`'${keyResolved}', JSON_OBJECT(${keyFields})`);
@@ -99,13 +116,21 @@ const buildGroupedQuery = (
99
116
  if (itemsSelection?.selections) {
100
117
  const itemFields = itemsSelection.selections
101
118
  .filter((sel) => !isAggregationField(sel.name) && sel.name !== "items")
102
- .map((sel) => `'${sel.alias || sel.name}', ${tableAlias}.${wrapIdentifierMySQL(sel.name)}`)
119
+ .map((sel) => {
120
+ const selector = applyDirectives(
121
+ `${tableAlias}.${wrapIdentifierMySQL(sqlName(sel.name))}`,
122
+ sel.directives,
123
+ "mysql",
124
+ variablesDefinition,
125
+ );
126
+ return `'${sel.alias || sel.name}', ${selector}`;
127
+ })
103
128
  .join(", ");
104
129
 
105
130
  if (itemFields) {
106
131
  const joinConditions = groupByFields.map(
107
- (field) =>
108
- `${tableAlias}.${wrapIdentifierMySQL(field)} = ${cteAlias}.${wrapIdentifierMySQL(field)}`,
132
+ (groupByField) =>
133
+ `${tableAlias}.${wrapIdentifierMySQL(sqlName(groupByField))} = ${cteAlias}.${wrapIdentifierMySQL(sqlName(groupByField))}`,
109
134
  );
110
135
 
111
136
  const whereConditions = whereClause
@@ -175,7 +200,14 @@ export const generateSQL = (
175
200
  {},
176
201
  );
177
202
 
178
- const cte = buildAggregationCTE(groupByInfo, dottedQuotedName, tableAlias, whereClause);
203
+ const cte = buildAggregationCTE(
204
+ entities,
205
+ field.name,
206
+ groupByInfo,
207
+ dottedQuotedName,
208
+ tableAlias,
209
+ whereClause,
210
+ );
179
211
  ctes.push(cte);
180
212
  }
181
213
 
@@ -244,6 +276,7 @@ export const buildSQLForField = (
244
276
  // Handle GROUP BY aggregation query
245
277
  const mainQuery = buildGroupedQuery(
246
278
  entities,
279
+ variablesDefinition,
247
280
  field,
248
281
  groupByInfo,
249
282
  dottedQuotedName,
@@ -277,16 +310,41 @@ export const buildSQLForField = (
277
310
  ([name, selector]) => `'${name}', ${selector}`,
278
311
  );
279
312
 
280
- const fromClause = `FROM ${dottedQuotedName} ${tableAlias}${withoutArrayWrapper ? " LIMIT 1" : ""}`;
313
+ const fromClause = `FROM ${dottedQuotedName} ${tableAlias}`;
281
314
 
282
315
  const orderByClause = buildOrderByClauseMySQL(entities, field, tableAlias);
283
316
  const paginationClause = buildPaginationClauseMySQL(field, variablesDefinition);
284
317
 
285
318
  const isArraySelection = !!field.isArray && !withoutArrayWrapper;
286
319
 
320
+ // JSON_ARRAYAGG accepts no ORDER BY of its own and collapses the rows before
321
+ // LIMIT can trim them, so both ordering and pagination have to happen in a
322
+ // derived table that the aggregate then reads.
323
+ if (isArraySelection && (orderByClause || paginationClause)) {
324
+ const pageAlias = `${tableAlias}_page`;
325
+ // A nested selection is correlated to its parent through the where clause,
326
+ // and a plain derived table may not carry an outer reference. LATERAL lifts
327
+ // that restriction — MySQL 8.0.14 and newer. Unordered, unpaginated nested
328
+ // selections never take this branch, so older servers keep working for them.
329
+ const lateral = parentTableName ? "LATERAL " : "";
330
+
331
+ // NO_MERGE is load-bearing, not a hint about performance: without it MySQL
332
+ // merges the derived table into the outer query and discards its ORDER BY,
333
+ // so the array comes back in storage order. A LIMIT blocks the merge on its
334
+ // own, which is why only the unpaginated ordering was affected.
335
+ return `
336
+ COALESCE((
337
+ SELECT /*+ NO_MERGE(${pageAlias}) */ JSON_ARRAYAGG(${pageAlias}.obj)
338
+ FROM ${lateral}(
339
+ SELECT JSON_OBJECT(${selectList}) AS obj ${fromClause} ${whereClause} ${orderByClause} ${paginationClause}
340
+ ) ${pageAlias}
341
+ ), JSON_ARRAY())
342
+ `;
343
+ }
344
+
287
345
  return `
288
346
  COALESCE((
289
- SELECT ${isArraySelection ? `JSON_ARRAYAGG(JSON_OBJECT(${selectList}))` : `JSON_OBJECT(${selectList})`} ${fromClause} ${orderByClause} ${whereClause} ${paginationClause ? ` ${paginationClause}` : ""}
347
+ SELECT ${isArraySelection ? `JSON_ARRAYAGG(JSON_OBJECT(${selectList}))` : `JSON_OBJECT(${selectList})`} ${fromClause} ${whereClause} ${orderByClause}${withoutArrayWrapper ? " LIMIT 1" : ""}
290
348
  ), ${isArraySelection ? "JSON_ARRAY()" : "null"})
291
349
  `;
292
350
  };