relq 1.0.1 → 1.0.3

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 (194) hide show
  1. package/dist/cjs/addon/buffer/index.cjs +1881 -0
  2. package/dist/cjs/addon/pg/index.cjs +4812 -0
  3. package/dist/cjs/addon/pg-cursor/index.cjs +1451 -0
  4. package/dist/cjs/addon/pg-format/index.cjs +2270 -0
  5. package/dist/cjs/cli/commands/add.cjs +430 -25
  6. package/dist/cjs/cli/commands/branch.cjs +131 -0
  7. package/dist/cjs/cli/commands/checkout.cjs +121 -0
  8. package/dist/cjs/cli/commands/cherry-pick.cjs +282 -0
  9. package/dist/cjs/cli/commands/commit.cjs +21 -29
  10. package/dist/cjs/cli/commands/diff.cjs +144 -69
  11. package/dist/cjs/cli/commands/export.cjs +70 -11
  12. package/dist/cjs/cli/commands/fetch.cjs +42 -18
  13. package/dist/cjs/cli/commands/generate.cjs +28 -54
  14. package/dist/cjs/cli/commands/history.cjs +19 -40
  15. package/dist/cjs/cli/commands/import.cjs +305 -41
  16. package/dist/cjs/cli/commands/init.cjs +69 -59
  17. package/dist/cjs/cli/commands/introspect.cjs +4 -8
  18. package/dist/cjs/cli/commands/log.cjs +84 -15
  19. package/dist/cjs/cli/commands/merge.cjs +207 -0
  20. package/dist/cjs/cli/commands/migrate.cjs +13 -26
  21. package/dist/cjs/cli/commands/pull.cjs +321 -95
  22. package/dist/cjs/cli/commands/push.cjs +228 -52
  23. package/dist/cjs/cli/commands/remote.cjs +17 -0
  24. package/dist/cjs/cli/commands/reset.cjs +148 -0
  25. package/dist/cjs/cli/commands/resolve.cjs +191 -0
  26. package/dist/cjs/cli/commands/rollback.cjs +17 -39
  27. package/dist/cjs/cli/commands/stash.cjs +152 -0
  28. package/dist/cjs/cli/commands/status.cjs +52 -9
  29. package/dist/cjs/cli/commands/sync.cjs +30 -50
  30. package/dist/cjs/cli/commands/tag.cjs +146 -0
  31. package/dist/cjs/cli/index.cjs +117 -10
  32. package/dist/cjs/cli/utils/change-tracker.cjs +107 -3
  33. package/dist/cjs/cli/utils/cli-utils.cjs +217 -0
  34. package/dist/cjs/cli/utils/commit-manager.cjs +3 -3
  35. package/dist/cjs/cli/utils/config-loader.cjs +34 -8
  36. package/dist/cjs/cli/utils/env-loader.cjs +3 -2
  37. package/dist/cjs/cli/utils/fast-introspect.cjs +110 -4
  38. package/dist/cjs/cli/utils/git-utils.cjs +42 -161
  39. package/dist/cjs/cli/utils/pool-manager.cjs +156 -0
  40. package/dist/cjs/cli/utils/project-root.cjs +107 -0
  41. package/dist/cjs/cli/utils/relqignore.cjs +297 -38
  42. package/dist/cjs/cli/utils/repo-manager.cjs +92 -3
  43. package/dist/cjs/cli/utils/schema-comparator.cjs +301 -11
  44. package/dist/cjs/cli/utils/schema-diff.cjs +202 -1
  45. package/dist/cjs/cli/utils/schema-hash.cjs +2 -1
  46. package/dist/cjs/cli/utils/schema-introspect.cjs +9 -5
  47. package/dist/cjs/cli/utils/snapshot-manager.cjs +1 -0
  48. package/dist/cjs/cli/utils/spinner.cjs +14 -106
  49. package/dist/cjs/cli/utils/sql-generator.cjs +2 -2
  50. package/dist/cjs/cli/utils/sql-parser.cjs +94 -7
  51. package/dist/cjs/cli/utils/type-generator.cjs +28 -16
  52. package/dist/cjs/condition/array-condition-builder.cjs +1 -1
  53. package/dist/cjs/condition/condition-collector.cjs +1 -1
  54. package/dist/cjs/condition/fulltext-condition-builder.cjs +1 -1
  55. package/dist/cjs/condition/geometric-condition-builder.cjs +1 -1
  56. package/dist/cjs/condition/jsonb-condition-builder.cjs +1 -1
  57. package/dist/cjs/condition/network-condition-builder.cjs +1 -1
  58. package/dist/cjs/condition/range-condition-builder.cjs +1 -1
  59. package/dist/cjs/copy/copy-builder.cjs +1 -1
  60. package/dist/cjs/core/query-builder.cjs +1 -1
  61. package/dist/cjs/core/relq-client.cjs +2 -2
  62. package/dist/cjs/count/count-builder.cjs +1 -1
  63. package/dist/cjs/cte/cte-builder.cjs +1 -1
  64. package/dist/cjs/delete/delete-builder.cjs +1 -1
  65. package/dist/cjs/function/create-function-builder.cjs +1 -1
  66. package/dist/cjs/functions/advanced-functions.cjs +1 -1
  67. package/dist/cjs/functions/case-builder.cjs +1 -1
  68. package/dist/cjs/functions/geometric-functions.cjs +1 -1
  69. package/dist/cjs/functions/network-functions.cjs +1 -1
  70. package/dist/cjs/functions/sql-functions.cjs +1 -1
  71. package/dist/cjs/indexing/create-index-builder.cjs +1 -1
  72. package/dist/cjs/indexing/drop-index-builder.cjs +1 -1
  73. package/dist/cjs/insert/conflict-builder.cjs +1 -1
  74. package/dist/cjs/insert/insert-builder.cjs +1 -1
  75. package/dist/cjs/maintenance/vacuum-builder.cjs +1 -1
  76. package/dist/cjs/pubsub/listen-notify-builder.cjs +1 -1
  77. package/dist/cjs/pubsub/listener-connection.cjs +2 -2
  78. package/dist/cjs/raw/raw-query-builder.cjs +1 -1
  79. package/dist/cjs/schema/schema-builder.cjs +1 -1
  80. package/dist/cjs/schema-definition/table-definition.cjs +1 -1
  81. package/dist/cjs/select/aggregate-builder.cjs +1 -1
  82. package/dist/cjs/select/select-builder.cjs +1 -1
  83. package/dist/cjs/sequence/sequence-builder.cjs +1 -1
  84. package/dist/cjs/table/alter-table-builder.cjs +1 -1
  85. package/dist/cjs/table/constraint-builder.cjs +1 -1
  86. package/dist/cjs/table/create-table-builder.cjs +1 -1
  87. package/dist/cjs/table/partition-builder.cjs +1 -1
  88. package/dist/cjs/table/truncate-builder.cjs +1 -1
  89. package/dist/cjs/transaction/transaction-builder.cjs +1 -1
  90. package/dist/cjs/trigger/create-trigger-builder.cjs +1 -1
  91. package/dist/cjs/update/array-update-builder.cjs +1 -1
  92. package/dist/cjs/update/update-builder.cjs +1 -1
  93. package/dist/cjs/utils/index.cjs +1 -1
  94. package/dist/cjs/view/create-view-builder.cjs +1 -1
  95. package/dist/cjs/window/window-builder.cjs +1 -1
  96. package/dist/config.d.ts +16 -25
  97. package/dist/esm/cli/commands/add.js +399 -27
  98. package/dist/esm/cli/commands/branch.js +95 -0
  99. package/dist/esm/cli/commands/checkout.js +85 -0
  100. package/dist/esm/cli/commands/cherry-pick.js +246 -0
  101. package/dist/esm/cli/commands/commit.js +22 -30
  102. package/dist/esm/cli/commands/diff.js +144 -69
  103. package/dist/esm/cli/commands/export.js +71 -12
  104. package/dist/esm/cli/commands/fetch.js +42 -18
  105. package/dist/esm/cli/commands/generate.js +28 -54
  106. package/dist/esm/cli/commands/history.js +11 -32
  107. package/dist/esm/cli/commands/import.js +306 -42
  108. package/dist/esm/cli/commands/init.js +65 -55
  109. package/dist/esm/cli/commands/introspect.js +4 -8
  110. package/dist/esm/cli/commands/log.js +78 -10
  111. package/dist/esm/cli/commands/merge.js +171 -0
  112. package/dist/esm/cli/commands/migrate.js +13 -26
  113. package/dist/esm/cli/commands/pull.js +313 -87
  114. package/dist/esm/cli/commands/push.js +223 -47
  115. package/dist/esm/cli/commands/remote.js +14 -0
  116. package/dist/esm/cli/commands/reset.js +112 -0
  117. package/dist/esm/cli/commands/resolve.js +155 -0
  118. package/dist/esm/cli/commands/rollback.js +17 -39
  119. package/dist/esm/cli/commands/stash.js +116 -0
  120. package/dist/esm/cli/commands/status.js +20 -10
  121. package/dist/esm/cli/commands/sync.js +30 -50
  122. package/dist/esm/cli/commands/tag.js +110 -0
  123. package/dist/esm/cli/index.js +118 -11
  124. package/dist/esm/cli/utils/change-tracker.js +107 -3
  125. package/dist/esm/cli/utils/cli-utils.js +169 -0
  126. package/dist/esm/cli/utils/commit-manager.js +3 -3
  127. package/dist/esm/cli/utils/config-loader.js +34 -8
  128. package/dist/esm/cli/utils/env-loader.js +3 -2
  129. package/dist/esm/cli/utils/fast-introspect.js +110 -4
  130. package/dist/esm/cli/utils/git-utils.js +2 -124
  131. package/dist/esm/cli/utils/pool-manager.js +114 -0
  132. package/dist/esm/cli/utils/project-root.js +69 -0
  133. package/dist/esm/cli/utils/relqignore.js +278 -37
  134. package/dist/esm/cli/utils/repo-manager.js +83 -3
  135. package/dist/esm/cli/utils/schema-comparator.js +301 -11
  136. package/dist/esm/cli/utils/schema-diff.js +202 -1
  137. package/dist/esm/cli/utils/schema-hash.js +2 -1
  138. package/dist/esm/cli/utils/schema-introspect.js +9 -5
  139. package/dist/esm/cli/utils/snapshot-manager.js +1 -0
  140. package/dist/esm/cli/utils/spinner.js +1 -101
  141. package/dist/esm/cli/utils/sql-generator.js +2 -2
  142. package/dist/esm/cli/utils/sql-parser.js +94 -7
  143. package/dist/esm/cli/utils/type-generator.js +28 -16
  144. package/dist/esm/condition/array-condition-builder.js +1 -1
  145. package/dist/esm/condition/condition-collector.js +1 -1
  146. package/dist/esm/condition/fulltext-condition-builder.js +1 -1
  147. package/dist/esm/condition/geometric-condition-builder.js +1 -1
  148. package/dist/esm/condition/jsonb-condition-builder.js +1 -1
  149. package/dist/esm/condition/network-condition-builder.js +1 -1
  150. package/dist/esm/condition/range-condition-builder.js +1 -1
  151. package/dist/esm/copy/copy-builder.js +1 -1
  152. package/dist/esm/core/query-builder.js +1 -1
  153. package/dist/esm/core/relq-client.js +2 -2
  154. package/dist/esm/count/count-builder.js +1 -1
  155. package/dist/esm/cte/cte-builder.js +1 -1
  156. package/dist/esm/delete/delete-builder.js +1 -1
  157. package/dist/esm/function/create-function-builder.js +1 -1
  158. package/dist/esm/functions/advanced-functions.js +1 -1
  159. package/dist/esm/functions/case-builder.js +1 -1
  160. package/dist/esm/functions/geometric-functions.js +1 -1
  161. package/dist/esm/functions/network-functions.js +1 -1
  162. package/dist/esm/functions/sql-functions.js +1 -1
  163. package/dist/esm/indexing/create-index-builder.js +1 -1
  164. package/dist/esm/indexing/drop-index-builder.js +1 -1
  165. package/dist/esm/insert/conflict-builder.js +1 -1
  166. package/dist/esm/insert/insert-builder.js +1 -1
  167. package/dist/esm/maintenance/vacuum-builder.js +1 -1
  168. package/dist/esm/pubsub/listen-notify-builder.js +1 -1
  169. package/dist/esm/pubsub/listener-connection.js +2 -2
  170. package/dist/esm/raw/raw-query-builder.js +1 -1
  171. package/dist/esm/schema/schema-builder.js +1 -1
  172. package/dist/esm/schema-definition/table-definition.js +1 -1
  173. package/dist/esm/select/aggregate-builder.js +1 -1
  174. package/dist/esm/select/select-builder.js +1 -1
  175. package/dist/esm/sequence/sequence-builder.js +1 -1
  176. package/dist/esm/table/alter-table-builder.js +1 -1
  177. package/dist/esm/table/constraint-builder.js +1 -1
  178. package/dist/esm/table/create-table-builder.js +1 -1
  179. package/dist/esm/table/partition-builder.js +1 -1
  180. package/dist/esm/table/truncate-builder.js +1 -1
  181. package/dist/esm/transaction/transaction-builder.js +1 -1
  182. package/dist/esm/trigger/create-trigger-builder.js +1 -1
  183. package/dist/esm/update/array-update-builder.js +1 -1
  184. package/dist/esm/update/update-builder.js +1 -1
  185. package/dist/esm/utils/index.js +1 -1
  186. package/dist/esm/view/create-view-builder.js +1 -1
  187. package/dist/esm/window/window-builder.js +1 -1
  188. package/dist/index.d.ts +25 -8
  189. package/dist/schema-builder.d.ts +16 -6
  190. package/package.json +1 -1
  191. /package/dist/{addons/buffer.js → esm/addon/buffer/index.js} +0 -0
  192. /package/dist/{addons/pg.js → esm/addon/pg/index.js} +0 -0
  193. /package/dist/{addons/pg-cursor.js → esm/addon/pg-cursor/index.js} +0 -0
  194. /package/dist/{addons/pg-format.js → esm/addon/pg-format/index.js} +0 -0
@@ -1,51 +1,423 @@
1
- import { colors } from "../utils/spinner.js";
2
- import { isInitialized, getUnstagedChanges, getStagedChanges, stageChanges, } from "../utils/repo-manager.js";
1
+ import * as fs from 'fs';
2
+ import { colors, fatal, warning } from "../utils/spinner.js";
3
+ import { loadRelqignore, isIgnored, } from "../utils/relqignore.js";
4
+ import { loadConfig } from "../../config/config.js";
5
+ import * as path from 'path';
6
+ import { isInitialized, loadSnapshot, getUnstagedChanges, getStagedChanges, stageChanges, detectFileChanges, addUnstagedChanges, clearUnstagedChanges, } from "../utils/repo-manager.js";
3
7
  import { getChangeDisplayName } from "../utils/change-tracker.js";
8
+ import { compareSchemas } from "../utils/schema-comparator.js";
9
+ function parseSchemaFileForComparison(schemaPath) {
10
+ if (!fs.existsSync(schemaPath)) {
11
+ return null;
12
+ }
13
+ const content = fs.readFileSync(schemaPath, 'utf-8');
14
+ const tables = [];
15
+ const tableStartRegex = /defineTable\s*\(\s*['"]([^'"]+)['"],\s*\{/g;
16
+ let tableStartMatch;
17
+ while ((tableStartMatch = tableStartRegex.exec(content)) !== null) {
18
+ const tableName = tableStartMatch[1];
19
+ const startIdx = tableStartMatch.index + tableStartMatch[0].length;
20
+ let braceCount = 1;
21
+ let endIdx = startIdx;
22
+ while (braceCount > 0 && endIdx < content.length) {
23
+ const char = content[endIdx];
24
+ if (char === '{')
25
+ braceCount++;
26
+ else if (char === '}')
27
+ braceCount--;
28
+ endIdx++;
29
+ }
30
+ const columnsBlock = content.substring(startIdx, endIdx - 1);
31
+ let optionsBlock = '';
32
+ const afterColumns = content.substring(endIdx);
33
+ const optionsMatch = afterColumns.match(/^\s*,\s*\{/);
34
+ if (optionsMatch) {
35
+ const optStart = endIdx + optionsMatch[0].length;
36
+ braceCount = 1;
37
+ let optEnd = optStart;
38
+ while (braceCount > 0 && optEnd < content.length) {
39
+ const char = content[optEnd];
40
+ if (char === '{')
41
+ braceCount++;
42
+ else if (char === '}')
43
+ braceCount--;
44
+ optEnd++;
45
+ }
46
+ optionsBlock = content.substring(optStart, optEnd - 1);
47
+ }
48
+ const columns = [];
49
+ const constraints = [];
50
+ const tsToDbNameMap = new Map();
51
+ const lines = columnsBlock.split('\n');
52
+ let currentColDef = '';
53
+ for (const line of lines) {
54
+ const trimmed = line.trim();
55
+ if (trimmed.startsWith('//') || trimmed.startsWith('/*') || trimmed.startsWith('*'))
56
+ continue;
57
+ currentColDef += ' ' + trimmed;
58
+ if (trimmed.endsWith(',') || trimmed.endsWith(')')) {
59
+ const colDef = currentColDef.trim();
60
+ currentColDef = '';
61
+ const typePattern = 'varchar|text|uuid|integer|bigint|boolean|timestamp|date|jsonb|json|numeric|serial|bigserial|smallserial|tsvector|smallint|real|doublePrecision|char|inet|cidr|macaddr|macaddr8|interval|time|point|line|lseg|box|path|polygon|circle|bytea|bit|varbit|money|xml|oid';
62
+ const colMatch = colDef.match(new RegExp(`^(\\w+):\\s*(${typePattern})`));
63
+ if (!colMatch)
64
+ continue;
65
+ const tsName = colMatch[1];
66
+ const type = colMatch[2];
67
+ const explicitNameMatch = colDef.match(new RegExp(`${type}\\s*\\(['\"]([^'"]+)['\"]`));
68
+ const dbColName = explicitNameMatch ? explicitNameMatch[1] : tsName;
69
+ tsToDbNameMap.set(tsName, dbColName);
70
+ let defaultValue = null;
71
+ const isJsonbColumn = type === 'jsonb' || type === 'json';
72
+ const isArrayColumn = colDef.includes('.array()');
73
+ const bigintMatch = colDef.match(/\.default\(\s*BigInt\(\s*(-?\d+)\s*\)\s*\)/);
74
+ if (bigintMatch) {
75
+ defaultValue = bigintMatch[1];
76
+ }
77
+ const funcDefaultMatch = !defaultValue && colDef.match(/\.default\(\s*(genRandomUuid|now|currentDate|currentTimestamp|emptyArray|emptyObject)\s*\(\s*\)\s*\)/);
78
+ if (funcDefaultMatch) {
79
+ const funcName = funcDefaultMatch[1];
80
+ if (funcName === 'emptyArray') {
81
+ defaultValue = isJsonbColumn ? "'[]'::jsonb" : "'{}'::text[]";
82
+ }
83
+ else if (funcName === 'emptyObject') {
84
+ defaultValue = "'{}'::jsonb";
85
+ }
86
+ else {
87
+ const funcToSql = {
88
+ 'genRandomUuid': 'gen_random_uuid()',
89
+ 'now': 'now()',
90
+ 'currentDate': 'CURRENT_DATE',
91
+ 'currentTimestamp': 'CURRENT_TIMESTAMP',
92
+ };
93
+ defaultValue = funcToSql[funcName] || `${funcName}()`;
94
+ }
95
+ }
96
+ else {
97
+ const strDefaultMatch = colDef.match(/\.default\(\s*(['"])([^'"]*)\1\s*\)/);
98
+ if (strDefaultMatch) {
99
+ defaultValue = strDefaultMatch[2];
100
+ }
101
+ else {
102
+ const boolDefaultMatch = colDef.match(/\.default\(\s*(true|false)\s*\)/);
103
+ if (boolDefaultMatch) {
104
+ defaultValue = boolDefaultMatch[1];
105
+ }
106
+ else {
107
+ const numDefaultMatch = colDef.match(/\.default\(\s*(-?\d+(?:\.\d+)?)\s*\)/);
108
+ if (numDefaultMatch) {
109
+ defaultValue = numDefaultMatch[1];
110
+ }
111
+ else {
112
+ const jsonObjMatch = colDef.match(/\.default\(\s*(\{[^}]+\})\s*\)/);
113
+ if (jsonObjMatch) {
114
+ defaultValue = `'${jsonObjMatch[1]}'::jsonb`;
115
+ }
116
+ else {
117
+ const arrayLiteralMatch = colDef.match(/\.default\(\s*(\[[^\]]+\])\s*\)/);
118
+ if (arrayLiteralMatch) {
119
+ const arrayStr = arrayLiteralMatch[1];
120
+ defaultValue = `'${arrayStr}'::jsonb`;
121
+ }
122
+ }
123
+ }
124
+ }
125
+ }
126
+ }
127
+ if (colDef.includes('.check(')) {
128
+ const checkValuesMatch = colDef.match(/\.check\(([^)]+)\)/);
129
+ if (checkValuesMatch) {
130
+ const valuesStr = checkValuesMatch[1];
131
+ const values = valuesStr.match(/['"]([^'"]+)['"]/g)?.map(v => v.replace(/['"]/g, '')) || [];
132
+ if (values.length > 0) {
133
+ const constraintName = `${tableName}_${dbColName}_check`;
134
+ constraints.push({
135
+ name: constraintName,
136
+ type: 'CHECK',
137
+ columns: [dbColName],
138
+ definition: '',
139
+ });
140
+ }
141
+ }
142
+ }
143
+ let comment = null;
144
+ const commentMatch = colDef.match(/\.comment\(\s*(['"])([^'"]*)\1\s*\)/);
145
+ if (commentMatch) {
146
+ comment = commentMatch[2];
147
+ }
148
+ if (colDef.includes('.identity()')) {
149
+ defaultValue = defaultValue || 'GENERATED BY DEFAULT AS IDENTITY';
150
+ }
151
+ const isArray = colDef.includes('.array()');
152
+ columns.push({
153
+ name: dbColName,
154
+ dataType: isArray ? `${type}[]` : type,
155
+ isNullable: !colDef.includes('.notNull()') && !colDef.includes('.primaryKey()'),
156
+ defaultValue,
157
+ isPrimaryKey: colDef.includes('.primaryKey()'),
158
+ isUnique: colDef.includes('.unique()'),
159
+ maxLength: null,
160
+ precision: null,
161
+ scale: null,
162
+ references: null,
163
+ comment,
164
+ });
165
+ }
166
+ }
167
+ const indexes = [];
168
+ const indexRegex = /index\s*\(\s*['"]([^'"]+)['"]\s*\)\.on\(([^)]+)\)/g;
169
+ let idxMatch;
170
+ while ((idxMatch = indexRegex.exec(optionsBlock)) !== null) {
171
+ const indexName = idxMatch[1];
172
+ const indexCols = idxMatch[2].split(',').map(c => {
173
+ const tsColName = c.trim().replace(/table\.\s*/, '');
174
+ return tsToDbNameMap.get(tsColName) || tsColName;
175
+ });
176
+ const isUnique = optionsBlock.includes(`index('${indexName}')`) &&
177
+ optionsBlock.substring(optionsBlock.indexOf(`index('${indexName}')`)).split('\n')[0].includes('.unique()');
178
+ indexes.push({
179
+ name: indexName,
180
+ columns: indexCols,
181
+ isUnique: isUnique,
182
+ isPrimary: false,
183
+ type: 'btree',
184
+ definition: '',
185
+ whereClause: null,
186
+ expression: null,
187
+ });
188
+ }
189
+ const checkRegexLegacy = /check\s*\(\s*['"]([^'"]+)['"]\s*,\s*sql`([^`]+)`\s*\)/g;
190
+ let tableCheckMatch;
191
+ while ((tableCheckMatch = checkRegexLegacy.exec(optionsBlock)) !== null) {
192
+ constraints.push({
193
+ name: tableCheckMatch[1],
194
+ type: 'CHECK',
195
+ columns: [],
196
+ definition: tableCheckMatch[2].trim(),
197
+ });
198
+ }
199
+ const checkRegexNew = /check\.constraint\s*\(\s*['"]([^'"]+)['"]/g;
200
+ let newCheckMatch;
201
+ while ((newCheckMatch = checkRegexNew.exec(optionsBlock)) !== null) {
202
+ const constraintName = newCheckMatch[1];
203
+ if (!constraints.some(c => c.name === constraintName)) {
204
+ constraints.push({
205
+ name: constraintName,
206
+ type: 'CHECK',
207
+ columns: [],
208
+ definition: '',
209
+ });
210
+ }
211
+ }
212
+ const checkConstraintsBlockMatch = optionsBlock.match(/checkConstraints:\s*\([^)]+\)\s*=>\s*\[([^\]]+)\]/s);
213
+ if (checkConstraintsBlockMatch) {
214
+ const checkBlock = checkConstraintsBlockMatch[1];
215
+ const constraintNameMatches = checkBlock.matchAll(/check\.constraint\s*\(\s*['"]([^'"]+)['"]/g);
216
+ for (const match of constraintNameMatches) {
217
+ const constraintName = match[1];
218
+ if (!constraints.some(c => c.name === constraintName)) {
219
+ constraints.push({
220
+ name: constraintName,
221
+ type: 'CHECK',
222
+ columns: [],
223
+ definition: '',
224
+ });
225
+ }
226
+ }
227
+ }
228
+ let partitionType;
229
+ let partitionKey;
230
+ const partitionByMatch = optionsBlock.match(/partitionBy:\s*\([^)]+\)\s*=>\s*\w+\.(list|range|hash)\(([^)]+)\)/i);
231
+ if (partitionByMatch) {
232
+ partitionType = partitionByMatch[1].toUpperCase();
233
+ const tsPartitionKey = partitionByMatch[2].replace(/table\./, '').trim();
234
+ const dbPartitionKey = tsToDbNameMap.get(tsPartitionKey) || tsPartitionKey;
235
+ partitionKey = [dbPartitionKey];
236
+ }
237
+ tables.push({
238
+ name: tableName,
239
+ schema: 'public',
240
+ columns,
241
+ indexes,
242
+ constraints,
243
+ rowCount: 0,
244
+ isPartitioned: !!partitionType,
245
+ partitionType,
246
+ partitionKey,
247
+ });
248
+ }
249
+ const enums = [];
250
+ const enumRegex = /defineEnum\s*\(\s*['"]([^'"]+)['"]\s*,\s*\[([^\]]+)\]/g;
251
+ let enumMatch;
252
+ while ((enumMatch = enumRegex.exec(content)) !== null) {
253
+ const enumName = enumMatch[1];
254
+ const valuesStr = enumMatch[2];
255
+ const values = valuesStr.match(/['"]([^'"]+)['"]/g)?.map(v => v.replace(/['"]/g, '')) || [];
256
+ enums.push({ name: enumName, values });
257
+ }
258
+ const extensions = [];
259
+ const singleExtMatch = content.match(/pgExtensions\s*\(\s*['"]([^'"]+)['"]\s*\)/);
260
+ if (singleExtMatch) {
261
+ extensions.push(singleExtMatch[1]);
262
+ }
263
+ else {
264
+ const arrayExtMatch = content.match(/pgExtensions\s*\(\s*\[([^\]]+)\]/);
265
+ if (arrayExtMatch) {
266
+ const extList = arrayExtMatch[1].match(/['"]([^'"]+)['"]/g);
267
+ if (extList) {
268
+ extList.forEach(e => extensions.push(e.replace(/['"]/g, '')));
269
+ }
270
+ }
271
+ }
272
+ return {
273
+ tables,
274
+ enums,
275
+ domains: [],
276
+ compositeTypes: [],
277
+ sequences: [],
278
+ collations: [],
279
+ functions: [],
280
+ triggers: [],
281
+ policies: [],
282
+ partitions: [],
283
+ foreignServers: [],
284
+ foreignTables: [],
285
+ extensions,
286
+ };
287
+ }
288
+ function snapshotToDatabaseSchema(snapshot) {
289
+ const tables = (snapshot.tables || []).map(t => ({
290
+ name: t.name,
291
+ schema: t.schema || 'public',
292
+ columns: (t.columns || []).map(c => ({
293
+ name: c.name,
294
+ dataType: c.type || 'text',
295
+ isNullable: c.nullable !== false,
296
+ defaultValue: c.default || null,
297
+ isPrimaryKey: c.primaryKey || false,
298
+ isUnique: c.unique || false,
299
+ maxLength: null,
300
+ precision: null,
301
+ scale: null,
302
+ references: null,
303
+ comment: c.comment || null,
304
+ })),
305
+ indexes: (t.indexes || []).map(i => ({
306
+ name: i.name,
307
+ columns: Array.isArray(i.columns) ? i.columns : [i.columns],
308
+ isUnique: i.unique || false,
309
+ isPrimary: false,
310
+ type: i.type || 'btree',
311
+ definition: i.definition || '',
312
+ whereClause: i.whereClause || null,
313
+ expression: null,
314
+ })),
315
+ constraints: (t.constraints || []).map(c => ({
316
+ name: c.name,
317
+ type: c.type,
318
+ columns: c.columns || [],
319
+ definition: c.definition || '',
320
+ })),
321
+ rowCount: 0,
322
+ isPartitioned: t.isPartitioned || false,
323
+ partitionType: t.partitionType,
324
+ partitionKey: t.partitionKey ? (Array.isArray(t.partitionKey) ? t.partitionKey : [t.partitionKey]) : undefined,
325
+ }));
326
+ return {
327
+ tables,
328
+ enums: (snapshot.enums || []).map(e => ({ name: e.name, values: e.values })),
329
+ domains: [],
330
+ compositeTypes: [],
331
+ sequences: [],
332
+ collations: [],
333
+ functions: [],
334
+ triggers: [],
335
+ policies: [],
336
+ partitions: [],
337
+ foreignServers: [],
338
+ foreignTables: [],
339
+ extensions: (snapshot.extensions || []).map(e => typeof e === 'string' ? e : e.name),
340
+ };
341
+ }
4
342
  export async function addCommand(context) {
5
- const { args } = context;
6
- const projectRoot = process.cwd();
343
+ const { args, projectRoot } = context;
7
344
  console.log('');
8
345
  if (!isInitialized(projectRoot)) {
9
- console.log(`${colors.red('error:')} relq not initialized`);
10
- console.log('');
11
- console.log(`${colors.muted('Run')} ${colors.cyan('relq init')} ${colors.muted('first.')}`);
12
- return;
346
+ fatal('not a relq repository (or any parent directories): .relq', `Run ${colors.cyan('relq init')} to initialize.`);
13
347
  }
14
- const unstaged = getUnstagedChanges(projectRoot);
348
+ const ignorePatterns = loadRelqignore(projectRoot);
349
+ const config = await loadConfig();
350
+ const schemaPathRaw = typeof config.schema === 'string' ? config.schema : './db/schema.ts';
351
+ const schemaPath = path.resolve(projectRoot, schemaPathRaw);
352
+ const fileChange = detectFileChanges(schemaPath, projectRoot);
353
+ if (fileChange) {
354
+ const currentSchema = parseSchemaFileForComparison(schemaPath);
355
+ const snapshot = loadSnapshot(projectRoot);
356
+ if (currentSchema && snapshot) {
357
+ const snapshotAsDbSchema = snapshotToDatabaseSchema(snapshot);
358
+ const schemaChanges = compareSchemas(snapshotAsDbSchema, currentSchema);
359
+ if (schemaChanges.length > 0) {
360
+ clearUnstagedChanges(projectRoot);
361
+ addUnstagedChanges(schemaChanges, projectRoot);
362
+ }
363
+ else {
364
+ const existingUnstaged = getUnstagedChanges(projectRoot);
365
+ const hasFileChange = existingUnstaged.some(c => c.objectType === 'SCHEMA_FILE');
366
+ if (!hasFileChange) {
367
+ addUnstagedChanges([fileChange], projectRoot);
368
+ }
369
+ }
370
+ }
371
+ }
372
+ const allUnstaged = getUnstagedChanges(projectRoot);
15
373
  const staged = getStagedChanges(projectRoot);
374
+ const unstaged = allUnstaged.filter(change => {
375
+ const objectType = change.objectType;
376
+ const result = isIgnored(objectType, change.objectName, change.parentName || null, ignorePatterns);
377
+ if (result.ignored) {
378
+ return false;
379
+ }
380
+ if (['FUNCTION', 'PROCEDURE'].includes(change.objectType) && !config.includeFunctions) {
381
+ return false;
382
+ }
383
+ if (change.objectType === 'TRIGGER' && !config.includeTriggers) {
384
+ return false;
385
+ }
386
+ if (['VIEW', 'MATERIALIZED_VIEW'].includes(change.objectType) && !config.includeViews) {
387
+ return false;
388
+ }
389
+ if (change.objectType === 'FOREIGN_TABLE' && !config.includeFDW) {
390
+ return false;
391
+ }
392
+ return true;
393
+ });
394
+ const filteredCount = allUnstaged.length - unstaged.length;
16
395
  if (unstaged.length === 0) {
17
396
  if (staged.length > 0) {
18
- console.log(`${colors.green('✓')} All changes are already staged`);
397
+ console.log('All changes are already staged');
19
398
  console.log(`${colors.muted(`${staged.length} change(s) ready to commit`)}`);
20
399
  console.log('');
21
- console.log(`${colors.muted('Run')} ${colors.cyan('relq commit -m "message"')} ${colors.muted('to commit.')}`);
400
+ console.log(`hint: run 'relq commit -m "message"' to commit`);
401
+ }
402
+ else if (filteredCount > 0) {
403
+ console.log('No stageable changes');
404
+ console.log(`${colors.muted(`${filteredCount} change(s) filtered by .relqignore or config`)}`);
22
405
  }
23
406
  else {
24
- console.log(`${colors.green('✓')} No changes to stage`);
25
- console.log(`${colors.muted('Run')} ${colors.cyan('relq pull')} ${colors.muted('or')} ${colors.cyan('relq import')} ${colors.muted('to detect changes.')}`);
407
+ console.log('No changes to stage');
408
+ console.log(`hint: run 'relq pull' or 'relq import' to detect changes`);
26
409
  }
27
410
  console.log('');
28
411
  return;
29
412
  }
30
413
  const patterns = args.length > 0 ? args : ['.'];
31
- const addAll = patterns.includes('.') || patterns.includes('*');
32
- console.log(`${colors.cyan('Unstaged changes:')} ${unstaged.length}`);
33
- console.log('');
34
- for (const change of unstaged) {
35
- const display = getChangeDisplayName(change);
36
- const color = change.type === 'CREATE' ? colors.green :
37
- change.type === 'DROP' ? colors.red :
38
- colors.yellow;
39
- console.log(` ${color(display)}`);
40
- }
41
- console.log('');
42
414
  const stagedNow = stageChanges(patterns, projectRoot);
43
415
  if (stagedNow.length === 0) {
44
- console.log(`${colors.yellow('⚠')} No changes matched the pattern(s): ${patterns.join(', ')}`);
416
+ warning(`No changes matched the pattern(s): ${patterns.join(', ')}`);
45
417
  console.log('');
46
418
  return;
47
419
  }
48
- console.log(`${colors.green('✓')} Staged ${stagedNow.length} change(s):`);
420
+ console.log(`Staged ${stagedNow.length} change(s):`);
49
421
  console.log('');
50
422
  for (const change of stagedNow) {
51
423
  const display = getChangeDisplayName(change);
@@ -60,7 +432,7 @@ export async function addCommand(context) {
60
432
  console.log(`${colors.muted(`${remainingUnstaged.length} change(s) still unstaged`)}`);
61
433
  console.log('');
62
434
  }
63
- console.log(`${colors.muted('Run')} ${colors.cyan('relq commit -m "message"')} ${colors.muted('to commit.')}`);
435
+ console.log(`hint: run 'relq commit -m "message"' to commit`);
64
436
  console.log('');
65
437
  }
66
438
  export function getRelatedChanges(tableName, changes) {
@@ -0,0 +1,95 @@
1
+ import * as fs from 'fs';
2
+ import * as path from 'path';
3
+ import { colors, fatal } from "../utils/spinner.js";
4
+ import { isInitialized, getHead } from "../utils/repo-manager.js";
5
+ function loadBranchState(projectRoot) {
6
+ const branchPath = path.join(projectRoot, '.relq', 'branches.json');
7
+ if (fs.existsSync(branchPath)) {
8
+ return JSON.parse(fs.readFileSync(branchPath, 'utf-8'));
9
+ }
10
+ const head = getHead(projectRoot);
11
+ return {
12
+ current: 'main',
13
+ branches: { main: head || '' }
14
+ };
15
+ }
16
+ function saveBranchState(state, projectRoot) {
17
+ const branchPath = path.join(projectRoot, '.relq', 'branches.json');
18
+ fs.writeFileSync(branchPath, JSON.stringify(state, null, 2));
19
+ }
20
+ export async function branchCommand(context) {
21
+ const { args, flags, projectRoot } = context;
22
+ console.log('');
23
+ if (!isInitialized(projectRoot)) {
24
+ fatal('not a relq repository (or any parent directories): .relq', `Run ${colors.cyan('relq init')} to initialize.`);
25
+ }
26
+ const state = loadBranchState(projectRoot);
27
+ const deleteFlag = flags['d'] === true || flags['delete'] === true;
28
+ const renameFlag = flags['m'] === true || flags['move'] === true;
29
+ if (deleteFlag) {
30
+ const branchName = args[0];
31
+ if (!branchName) {
32
+ fatal('Please specify branch name', `Usage: ${colors.cyan('relq branch -d <name>')}`);
33
+ }
34
+ if (branchName === state.current) {
35
+ fatal(`Cannot delete the branch '${branchName}' which you are currently on`);
36
+ }
37
+ if (!state.branches[branchName]) {
38
+ fatal(`Branch '${branchName}' not found`, `Use ${colors.cyan('relq branch')} to list available branches.`);
39
+ }
40
+ delete state.branches[branchName];
41
+ saveBranchState(state, projectRoot);
42
+ console.log(`Deleted branch '${branchName}'`);
43
+ console.log('');
44
+ return;
45
+ }
46
+ if (renameFlag) {
47
+ const oldName = args[0];
48
+ const newName = args[1];
49
+ if (!oldName || !newName) {
50
+ fatal('Missing arguments', `Usage: ${colors.cyan('relq branch -m <old> <new>')}`);
51
+ }
52
+ if (!state.branches[oldName]) {
53
+ fatal(`Branch '${oldName}' not found`, `Use ${colors.cyan('relq branch')} to list available branches.`);
54
+ }
55
+ if (state.branches[newName]) {
56
+ fatal(`A branch named '${newName}' already exists`);
57
+ }
58
+ state.branches[newName] = state.branches[oldName];
59
+ delete state.branches[oldName];
60
+ if (state.current === oldName)
61
+ state.current = newName;
62
+ saveBranchState(state, projectRoot);
63
+ console.log(`Renamed '${oldName}' to '${newName}'`);
64
+ console.log('');
65
+ return;
66
+ }
67
+ if (args[0]) {
68
+ const branchName = args[0];
69
+ if (state.branches[branchName]) {
70
+ fatal(`A branch named '${branchName}' already exists`);
71
+ }
72
+ const head = getHead(projectRoot);
73
+ if (!head) {
74
+ fatal('No commits yet', `Run ${colors.cyan('relq pull')} or ${colors.cyan('relq import')} first.`);
75
+ }
76
+ state.branches[branchName] = head;
77
+ saveBranchState(state, projectRoot);
78
+ console.log(`Created branch '${branchName}'`);
79
+ console.log('');
80
+ return;
81
+ }
82
+ const branches = Object.keys(state.branches).sort();
83
+ if (branches.length === 0) {
84
+ console.log(`${colors.muted('No branches.')}`);
85
+ return;
86
+ }
87
+ for (const name of branches) {
88
+ const isCurrent = name === state.current;
89
+ const prefix = isCurrent ? colors.green('* ') : ' ';
90
+ const branchName = isCurrent ? colors.green(name) : name;
91
+ console.log(`${prefix}${branchName}`);
92
+ }
93
+ console.log('');
94
+ }
95
+ export default branchCommand;
@@ -0,0 +1,85 @@
1
+ import * as fs from 'fs';
2
+ import * as path from 'path';
3
+ import { fatal, error, hint } from "../utils/cli-utils.js";
4
+ import { isInitialized, getHead, setHead, loadCommit, saveSnapshot, getStagedChanges, getUnstagedChanges, } from "../utils/repo-manager.js";
5
+ function loadBranchState(projectRoot) {
6
+ const branchPath = path.join(projectRoot, '.relq', 'branches.json');
7
+ if (fs.existsSync(branchPath)) {
8
+ return JSON.parse(fs.readFileSync(branchPath, 'utf-8'));
9
+ }
10
+ const head = getHead(projectRoot);
11
+ return { current: 'main', branches: { main: head || '' } };
12
+ }
13
+ function saveBranchState(state, projectRoot) {
14
+ const branchPath = path.join(projectRoot, '.relq', 'branches.json');
15
+ fs.writeFileSync(branchPath, JSON.stringify(state, null, 2));
16
+ }
17
+ export async function checkoutCommand(context) {
18
+ const { args, flags, projectRoot } = context;
19
+ console.log('');
20
+ if (!isInitialized(projectRoot)) {
21
+ fatal('not a relq repository (or any parent directories): .relq', "run 'relq init' to initialize");
22
+ }
23
+ const createBranch = flags['b'] === true;
24
+ const branchName = args[0];
25
+ if (!branchName) {
26
+ error('please specify a branch');
27
+ console.log("usage: relq checkout <branch>");
28
+ console.log(" relq checkout -b <new-branch>");
29
+ return;
30
+ }
31
+ const staged = getStagedChanges(projectRoot);
32
+ const unstaged = getUnstagedChanges(projectRoot);
33
+ if (staged.length > 0 || unstaged.length > 0) {
34
+ error('you have uncommitted changes');
35
+ hint("run 'relq commit -m <message>' to commit");
36
+ hint("run 'relq stash' to stash changes");
37
+ return;
38
+ }
39
+ const state = loadBranchState(projectRoot);
40
+ if (createBranch) {
41
+ if (state.branches[branchName]) {
42
+ fatal(`branch '${branchName}' already exists`);
43
+ }
44
+ const head = getHead(projectRoot);
45
+ if (!head) {
46
+ fatal('no commits yet', "run 'relq pull' or 'relq import' first");
47
+ }
48
+ state.branches[branchName] = head;
49
+ state.current = branchName;
50
+ saveBranchState(state, projectRoot);
51
+ console.log(`Switched to a new branch '${branchName}'`);
52
+ return;
53
+ }
54
+ if (!state.branches[branchName]) {
55
+ error(`pathspec '${branchName}' did not match any branch known to relq`);
56
+ console.log('Available branches:');
57
+ for (const name of Object.keys(state.branches)) {
58
+ console.log(` ${name}`);
59
+ }
60
+ return;
61
+ }
62
+ if (state.current === branchName) {
63
+ console.log(`Already on '${branchName}'`);
64
+ console.log('');
65
+ return;
66
+ }
67
+ const currentHead = getHead(projectRoot);
68
+ if (currentHead) {
69
+ state.branches[state.current] = currentHead;
70
+ }
71
+ const targetHash = state.branches[branchName];
72
+ const targetCommit = loadCommit(targetHash, projectRoot);
73
+ if (!targetCommit) {
74
+ fatal('cannot find commit for branch');
75
+ }
76
+ if (targetCommit.schema) {
77
+ saveSnapshot(targetCommit.schema, projectRoot);
78
+ }
79
+ setHead(targetHash, projectRoot);
80
+ state.current = branchName;
81
+ saveBranchState(state, projectRoot);
82
+ console.log(`Switched to branch '${branchName}'`);
83
+ console.log('');
84
+ }
85
+ export default checkoutCommand;