relq 1.0.0
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.
- package/LICENSE +21 -0
- package/README.md +862 -0
- package/dist/addons/buffer.js +1869 -0
- package/dist/addons/pg-cursor.js +1425 -0
- package/dist/addons/pg-format.js +2248 -0
- package/dist/addons/pg.js +4790 -0
- package/dist/bin/relq.js +2 -0
- package/dist/cjs/cache/index.cjs +9 -0
- package/dist/cjs/cache/query-cache.cjs +311 -0
- package/dist/cjs/cli/commands/add.cjs +82 -0
- package/dist/cjs/cli/commands/commit.cjs +145 -0
- package/dist/cjs/cli/commands/diff.cjs +84 -0
- package/dist/cjs/cli/commands/export.cjs +333 -0
- package/dist/cjs/cli/commands/fetch.cjs +59 -0
- package/dist/cjs/cli/commands/generate.cjs +242 -0
- package/dist/cjs/cli/commands/history.cjs +165 -0
- package/dist/cjs/cli/commands/import.cjs +524 -0
- package/dist/cjs/cli/commands/init.cjs +437 -0
- package/dist/cjs/cli/commands/introspect.cjs +142 -0
- package/dist/cjs/cli/commands/log.cjs +62 -0
- package/dist/cjs/cli/commands/migrate.cjs +167 -0
- package/dist/cjs/cli/commands/pull.cjs +410 -0
- package/dist/cjs/cli/commands/push.cjs +165 -0
- package/dist/cjs/cli/commands/rollback.cjs +169 -0
- package/dist/cjs/cli/commands/status.cjs +110 -0
- package/dist/cjs/cli/commands/sync.cjs +79 -0
- package/dist/cjs/cli/index.cjs +275 -0
- package/dist/cjs/cli/utils/change-tracker.cjs +446 -0
- package/dist/cjs/cli/utils/commit-manager.cjs +239 -0
- package/dist/cjs/cli/utils/config-loader.cjs +127 -0
- package/dist/cjs/cli/utils/env-loader.cjs +62 -0
- package/dist/cjs/cli/utils/fast-introspect.cjs +398 -0
- package/dist/cjs/cli/utils/git-utils.cjs +404 -0
- package/dist/cjs/cli/utils/migration-generator.cjs +269 -0
- package/dist/cjs/cli/utils/relqignore.cjs +114 -0
- package/dist/cjs/cli/utils/repo-manager.cjs +515 -0
- package/dist/cjs/cli/utils/schema-comparator.cjs +313 -0
- package/dist/cjs/cli/utils/schema-diff.cjs +284 -0
- package/dist/cjs/cli/utils/schema-hash.cjs +108 -0
- package/dist/cjs/cli/utils/schema-introspect.cjs +455 -0
- package/dist/cjs/cli/utils/snapshot-manager.cjs +223 -0
- package/dist/cjs/cli/utils/spinner.cjs +108 -0
- package/dist/cjs/cli/utils/sql-generator.cjs +520 -0
- package/dist/cjs/cli/utils/sql-parser.cjs +999 -0
- package/dist/cjs/cli/utils/type-generator.cjs +2061 -0
- package/dist/cjs/condition/array-condition-builder.cjs +503 -0
- package/dist/cjs/condition/array-numeric-condition-builder.cjs +186 -0
- package/dist/cjs/condition/array-specialized-condition-builder.cjs +206 -0
- package/dist/cjs/condition/array-string-condition-builder.cjs +146 -0
- package/dist/cjs/condition/base-condition-builder.cjs +2 -0
- package/dist/cjs/condition/condition-collector.cjs +284 -0
- package/dist/cjs/condition/fulltext-condition-builder.cjs +61 -0
- package/dist/cjs/condition/geometric-condition-builder.cjs +208 -0
- package/dist/cjs/condition/index.cjs +25 -0
- package/dist/cjs/condition/jsonb-condition-builder.cjs +160 -0
- package/dist/cjs/condition/network-condition-builder.cjs +230 -0
- package/dist/cjs/condition/range-condition-builder.cjs +82 -0
- package/dist/cjs/config/config.cjs +190 -0
- package/dist/cjs/config/index.cjs +9 -0
- package/dist/cjs/constants/pg-values.cjs +68 -0
- package/dist/cjs/copy/copy-builder.cjs +316 -0
- package/dist/cjs/copy/index.cjs +6 -0
- package/dist/cjs/core/query-builder.cjs +440 -0
- package/dist/cjs/core/relq-client.cjs +1831 -0
- package/dist/cjs/core/typed-kuery-client.cjs +2 -0
- package/dist/cjs/count/count-builder.cjs +88 -0
- package/dist/cjs/count/index.cjs +5 -0
- package/dist/cjs/cte/cte-builder.cjs +89 -0
- package/dist/cjs/cte/index.cjs +5 -0
- package/dist/cjs/ddl/function.cjs +48 -0
- package/dist/cjs/ddl/index.cjs +7 -0
- package/dist/cjs/ddl/sql.cjs +54 -0
- package/dist/cjs/delete/delete-builder.cjs +135 -0
- package/dist/cjs/delete/index.cjs +5 -0
- package/dist/cjs/errors/relq-errors.cjs +329 -0
- package/dist/cjs/examples/fulltext-search-test.cjs +122 -0
- package/dist/cjs/explain/explain-builder.cjs +99 -0
- package/dist/cjs/explain/index.cjs +5 -0
- package/dist/cjs/function/create-function-builder.cjs +196 -0
- package/dist/cjs/function/index.cjs +6 -0
- package/dist/cjs/functions/advanced-functions.cjs +241 -0
- package/dist/cjs/functions/case-builder.cjs +66 -0
- package/dist/cjs/functions/geometric-functions.cjs +104 -0
- package/dist/cjs/functions/index.cjs +184 -0
- package/dist/cjs/functions/network-functions.cjs +86 -0
- package/dist/cjs/functions/sql-functions.cjs +431 -0
- package/dist/cjs/index.cjs +164 -0
- package/dist/cjs/indexing/create-index-builder.cjs +187 -0
- package/dist/cjs/indexing/drop-index-builder.cjs +89 -0
- package/dist/cjs/indexing/index-types.cjs +2 -0
- package/dist/cjs/indexing/index.cjs +8 -0
- package/dist/cjs/insert/conflict-builder.cjs +173 -0
- package/dist/cjs/insert/index.cjs +5 -0
- package/dist/cjs/insert/insert-builder.cjs +254 -0
- package/dist/cjs/introspect/index.cjs +229 -0
- package/dist/cjs/maintenance/index.cjs +6 -0
- package/dist/cjs/maintenance/vacuum-builder.cjs +166 -0
- package/dist/cjs/pubsub/index.cjs +7 -0
- package/dist/cjs/pubsub/listen-notify-builder.cjs +57 -0
- package/dist/cjs/pubsub/listener-connection.cjs +180 -0
- package/dist/cjs/raw/index.cjs +5 -0
- package/dist/cjs/raw/raw-query-builder.cjs +27 -0
- package/dist/cjs/schema/index.cjs +15 -0
- package/dist/cjs/schema/schema-builder.cjs +1167 -0
- package/dist/cjs/schema-builder.cjs +21 -0
- package/dist/cjs/schema-definition/column-types.cjs +829 -0
- package/dist/cjs/schema-definition/index.cjs +62 -0
- package/dist/cjs/schema-definition/introspection.cjs +620 -0
- package/dist/cjs/schema-definition/partitions.cjs +129 -0
- package/dist/cjs/schema-definition/pg-enum.cjs +76 -0
- package/dist/cjs/schema-definition/pg-function.cjs +91 -0
- package/dist/cjs/schema-definition/pg-sequence.cjs +56 -0
- package/dist/cjs/schema-definition/pg-trigger.cjs +108 -0
- package/dist/cjs/schema-definition/relations.cjs +98 -0
- package/dist/cjs/schema-definition/sql-expressions.cjs +202 -0
- package/dist/cjs/schema-definition/table-definition.cjs +636 -0
- package/dist/cjs/select/aggregate-builder.cjs +179 -0
- package/dist/cjs/select/index.cjs +5 -0
- package/dist/cjs/select/select-builder.cjs +233 -0
- package/dist/cjs/sequence/index.cjs +7 -0
- package/dist/cjs/sequence/sequence-builder.cjs +264 -0
- package/dist/cjs/table/alter-table-builder.cjs +146 -0
- package/dist/cjs/table/constraint-builder.cjs +102 -0
- package/dist/cjs/table/create-table-builder.cjs +248 -0
- package/dist/cjs/table/index.cjs +17 -0
- package/dist/cjs/table/partition-builder.cjs +131 -0
- package/dist/cjs/table/truncate-builder.cjs +70 -0
- package/dist/cjs/transaction/index.cjs +6 -0
- package/dist/cjs/transaction/transaction-builder.cjs +78 -0
- package/dist/cjs/trigger/create-trigger-builder.cjs +174 -0
- package/dist/cjs/trigger/index.cjs +6 -0
- package/dist/cjs/types/aggregate-types.cjs +2 -0
- package/dist/cjs/types/config-types.cjs +40 -0
- package/dist/cjs/types/inference-types.cjs +18 -0
- package/dist/cjs/types/pagination-types.cjs +7 -0
- package/dist/cjs/types/result-types.cjs +2 -0
- package/dist/cjs/types/schema-types.cjs +2 -0
- package/dist/cjs/types/subscription-types.cjs +2 -0
- package/dist/cjs/types.cjs +2 -0
- package/dist/cjs/update/array-update-builder.cjs +205 -0
- package/dist/cjs/update/index.cjs +13 -0
- package/dist/cjs/update/update-builder.cjs +195 -0
- package/dist/cjs/utils/case-converter.cjs +58 -0
- package/dist/cjs/utils/environment-detection.cjs +120 -0
- package/dist/cjs/utils/index.cjs +10 -0
- package/dist/cjs/utils/pool-defaults.cjs +106 -0
- package/dist/cjs/utils/type-coercion.cjs +118 -0
- package/dist/cjs/view/create-view-builder.cjs +180 -0
- package/dist/cjs/view/index.cjs +7 -0
- package/dist/cjs/window/index.cjs +5 -0
- package/dist/cjs/window/window-builder.cjs +80 -0
- package/dist/config.cjs +1 -0
- package/dist/config.d.ts +655 -0
- package/dist/config.js +1 -0
- package/dist/esm/cache/index.js +1 -0
- package/dist/esm/cache/query-cache.js +303 -0
- package/dist/esm/cli/commands/add.js +78 -0
- package/dist/esm/cli/commands/commit.js +109 -0
- package/dist/esm/cli/commands/diff.js +81 -0
- package/dist/esm/cli/commands/export.js +297 -0
- package/dist/esm/cli/commands/fetch.js +56 -0
- package/dist/esm/cli/commands/generate.js +206 -0
- package/dist/esm/cli/commands/history.js +129 -0
- package/dist/esm/cli/commands/import.js +488 -0
- package/dist/esm/cli/commands/init.js +401 -0
- package/dist/esm/cli/commands/introspect.js +106 -0
- package/dist/esm/cli/commands/log.js +59 -0
- package/dist/esm/cli/commands/migrate.js +131 -0
- package/dist/esm/cli/commands/pull.js +374 -0
- package/dist/esm/cli/commands/push.js +129 -0
- package/dist/esm/cli/commands/rollback.js +133 -0
- package/dist/esm/cli/commands/status.js +107 -0
- package/dist/esm/cli/commands/sync.js +76 -0
- package/dist/esm/cli/index.js +240 -0
- package/dist/esm/cli/utils/change-tracker.js +405 -0
- package/dist/esm/cli/utils/commit-manager.js +191 -0
- package/dist/esm/cli/utils/config-loader.js +86 -0
- package/dist/esm/cli/utils/env-loader.js +57 -0
- package/dist/esm/cli/utils/fast-introspect.js +362 -0
- package/dist/esm/cli/utils/git-utils.js +347 -0
- package/dist/esm/cli/utils/migration-generator.js +263 -0
- package/dist/esm/cli/utils/relqignore.js +74 -0
- package/dist/esm/cli/utils/repo-manager.js +444 -0
- package/dist/esm/cli/utils/schema-comparator.js +307 -0
- package/dist/esm/cli/utils/schema-diff.js +276 -0
- package/dist/esm/cli/utils/schema-hash.js +69 -0
- package/dist/esm/cli/utils/schema-introspect.js +418 -0
- package/dist/esm/cli/utils/snapshot-manager.js +179 -0
- package/dist/esm/cli/utils/spinner.js +101 -0
- package/dist/esm/cli/utils/sql-generator.js +504 -0
- package/dist/esm/cli/utils/sql-parser.js +992 -0
- package/dist/esm/cli/utils/type-generator.js +2058 -0
- package/dist/esm/condition/array-condition-builder.js +495 -0
- package/dist/esm/condition/array-numeric-condition-builder.js +182 -0
- package/dist/esm/condition/array-specialized-condition-builder.js +200 -0
- package/dist/esm/condition/array-string-condition-builder.js +142 -0
- package/dist/esm/condition/base-condition-builder.js +1 -0
- package/dist/esm/condition/condition-collector.js +275 -0
- package/dist/esm/condition/fulltext-condition-builder.js +53 -0
- package/dist/esm/condition/geometric-condition-builder.js +200 -0
- package/dist/esm/condition/index.js +7 -0
- package/dist/esm/condition/jsonb-condition-builder.js +152 -0
- package/dist/esm/condition/network-condition-builder.js +222 -0
- package/dist/esm/condition/range-condition-builder.js +74 -0
- package/dist/esm/config/config.js +150 -0
- package/dist/esm/config/index.js +1 -0
- package/dist/esm/constants/pg-values.js +63 -0
- package/dist/esm/copy/copy-builder.js +308 -0
- package/dist/esm/copy/index.js +1 -0
- package/dist/esm/core/query-builder.js +426 -0
- package/dist/esm/core/relq-client.js +1791 -0
- package/dist/esm/core/typed-kuery-client.js +1 -0
- package/dist/esm/count/count-builder.js +81 -0
- package/dist/esm/count/index.js +1 -0
- package/dist/esm/cte/cte-builder.js +82 -0
- package/dist/esm/cte/index.js +1 -0
- package/dist/esm/ddl/function.js +45 -0
- package/dist/esm/ddl/index.js +2 -0
- package/dist/esm/ddl/sql.js +51 -0
- package/dist/esm/delete/delete-builder.js +128 -0
- package/dist/esm/delete/index.js +1 -0
- package/dist/esm/errors/relq-errors.js +310 -0
- package/dist/esm/examples/fulltext-search-test.js +117 -0
- package/dist/esm/explain/explain-builder.js +95 -0
- package/dist/esm/explain/index.js +1 -0
- package/dist/esm/function/create-function-builder.js +188 -0
- package/dist/esm/function/index.js +1 -0
- package/dist/esm/functions/advanced-functions.js +231 -0
- package/dist/esm/functions/case-builder.js +58 -0
- package/dist/esm/functions/geometric-functions.js +97 -0
- package/dist/esm/functions/index.js +171 -0
- package/dist/esm/functions/network-functions.js +79 -0
- package/dist/esm/functions/sql-functions.js +421 -0
- package/dist/esm/index.js +34 -0
- package/dist/esm/indexing/create-index-builder.js +180 -0
- package/dist/esm/indexing/drop-index-builder.js +81 -0
- package/dist/esm/indexing/index-types.js +1 -0
- package/dist/esm/indexing/index.js +2 -0
- package/dist/esm/insert/conflict-builder.js +162 -0
- package/dist/esm/insert/index.js +1 -0
- package/dist/esm/insert/insert-builder.js +247 -0
- package/dist/esm/introspect/index.js +224 -0
- package/dist/esm/maintenance/index.js +1 -0
- package/dist/esm/maintenance/vacuum-builder.js +158 -0
- package/dist/esm/pubsub/index.js +1 -0
- package/dist/esm/pubsub/listen-notify-builder.js +48 -0
- package/dist/esm/pubsub/listener-connection.js +173 -0
- package/dist/esm/raw/index.js +1 -0
- package/dist/esm/raw/raw-query-builder.js +20 -0
- package/dist/esm/schema/index.js +1 -0
- package/dist/esm/schema/schema-builder.js +1150 -0
- package/dist/esm/schema-builder.js +2 -0
- package/dist/esm/schema-definition/column-types.js +738 -0
- package/dist/esm/schema-definition/index.js +10 -0
- package/dist/esm/schema-definition/introspection.js +614 -0
- package/dist/esm/schema-definition/partitions.js +123 -0
- package/dist/esm/schema-definition/pg-enum.js +70 -0
- package/dist/esm/schema-definition/pg-function.js +85 -0
- package/dist/esm/schema-definition/pg-sequence.js +50 -0
- package/dist/esm/schema-definition/pg-trigger.js +102 -0
- package/dist/esm/schema-definition/relations.js +90 -0
- package/dist/esm/schema-definition/sql-expressions.js +193 -0
- package/dist/esm/schema-definition/table-definition.js +630 -0
- package/dist/esm/select/aggregate-builder.js +172 -0
- package/dist/esm/select/index.js +1 -0
- package/dist/esm/select/select-builder.js +226 -0
- package/dist/esm/sequence/index.js +1 -0
- package/dist/esm/sequence/sequence-builder.js +255 -0
- package/dist/esm/table/alter-table-builder.js +138 -0
- package/dist/esm/table/constraint-builder.js +95 -0
- package/dist/esm/table/create-table-builder.js +241 -0
- package/dist/esm/table/index.js +5 -0
- package/dist/esm/table/partition-builder.js +121 -0
- package/dist/esm/table/truncate-builder.js +63 -0
- package/dist/esm/transaction/index.js +1 -0
- package/dist/esm/transaction/transaction-builder.js +70 -0
- package/dist/esm/trigger/create-trigger-builder.js +166 -0
- package/dist/esm/trigger/index.js +1 -0
- package/dist/esm/types/aggregate-types.js +1 -0
- package/dist/esm/types/config-types.js +36 -0
- package/dist/esm/types/inference-types.js +12 -0
- package/dist/esm/types/pagination-types.js +4 -0
- package/dist/esm/types/result-types.js +1 -0
- package/dist/esm/types/schema-types.js +1 -0
- package/dist/esm/types/subscription-types.js +1 -0
- package/dist/esm/types.js +1 -0
- package/dist/esm/update/array-update-builder.js +192 -0
- package/dist/esm/update/index.js +2 -0
- package/dist/esm/update/update-builder.js +188 -0
- package/dist/esm/utils/case-converter.js +55 -0
- package/dist/esm/utils/environment-detection.js +113 -0
- package/dist/esm/utils/index.js +2 -0
- package/dist/esm/utils/pool-defaults.js +100 -0
- package/dist/esm/utils/type-coercion.js +110 -0
- package/dist/esm/view/create-view-builder.js +171 -0
- package/dist/esm/view/index.js +1 -0
- package/dist/esm/window/index.js +1 -0
- package/dist/esm/window/window-builder.js +73 -0
- package/dist/index.cjs +1 -0
- package/dist/index.d.ts +10341 -0
- package/dist/index.js +1 -0
- package/dist/schema-builder.cjs +1 -0
- package/dist/schema-builder.d.ts +2272 -0
- package/dist/schema-builder.js +1 -0
- package/package.json +55 -0
|
@@ -0,0 +1,2061 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.generateTypeScript = generateTypeScript;
|
|
4
|
+
const EXCLUDED_TABLES = ['_relq_migrations', 'relq_migrations'];
|
|
5
|
+
const EXCLUDED_FUNCTIONS = [
|
|
6
|
+
'armor', 'dearmor', 'crypt', 'decrypt', 'encrypt', 'digest', 'hmac',
|
|
7
|
+
'gen_salt', 'gen_random_bytes', 'gen_random_uuid', 'pgp_', 'decrypt_iv',
|
|
8
|
+
'encrypt_iv'
|
|
9
|
+
];
|
|
10
|
+
function toCamelCase(str) {
|
|
11
|
+
const cleaned = str.replace(/^[_0-9]+/, '');
|
|
12
|
+
return cleaned
|
|
13
|
+
.split('_')
|
|
14
|
+
.map((word, i) => i === 0 ? word.toLowerCase() : word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
|
|
15
|
+
.join('');
|
|
16
|
+
}
|
|
17
|
+
function toPascalCase(str) {
|
|
18
|
+
const cleaned = str.replace(/^[_0-9]+/, '');
|
|
19
|
+
return cleaned
|
|
20
|
+
.split('_')
|
|
21
|
+
.map(word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
|
|
22
|
+
.join('');
|
|
23
|
+
}
|
|
24
|
+
function inferTsTypeFromSqlType(sqlType) {
|
|
25
|
+
const normalized = sqlType.toLowerCase().replace(/\([^)]*\)/g, '').trim();
|
|
26
|
+
if (['integer', 'int', 'int4', 'smallint', 'int2', 'bigint', 'int8',
|
|
27
|
+
'numeric', 'decimal', 'real', 'float4', 'float8', 'double precision',
|
|
28
|
+
'float', 'money'].includes(normalized)) {
|
|
29
|
+
return 'number';
|
|
30
|
+
}
|
|
31
|
+
if (['boolean', 'bool'].includes(normalized)) {
|
|
32
|
+
return 'boolean';
|
|
33
|
+
}
|
|
34
|
+
if (['timestamp', 'timestamptz', 'date', 'time', 'timetz'].includes(normalized)) {
|
|
35
|
+
return 'Date';
|
|
36
|
+
}
|
|
37
|
+
if (['inet', 'cidr', 'macaddr', 'macaddr8'].includes(normalized)) {
|
|
38
|
+
return 'string';
|
|
39
|
+
}
|
|
40
|
+
if (normalized === 'uuid') {
|
|
41
|
+
return 'string';
|
|
42
|
+
}
|
|
43
|
+
return 'string';
|
|
44
|
+
}
|
|
45
|
+
function generateColumnBuilderFromType(sqlType) {
|
|
46
|
+
const normalized = sqlType.toLowerCase().trim();
|
|
47
|
+
const paramMatch = normalized.match(/^([a-z_][a-z0-9_\s]*?)(?:\s*\(([^)]+)\))?$/i);
|
|
48
|
+
if (!paramMatch)
|
|
49
|
+
return `text()`;
|
|
50
|
+
const baseType = paramMatch[1].trim();
|
|
51
|
+
const params = paramMatch[2];
|
|
52
|
+
if (['integer', 'int', 'int4'].includes(baseType)) {
|
|
53
|
+
return 'integer()';
|
|
54
|
+
}
|
|
55
|
+
if (['smallint', 'int2'].includes(baseType)) {
|
|
56
|
+
return 'smallint()';
|
|
57
|
+
}
|
|
58
|
+
if (['bigint', 'int8'].includes(baseType)) {
|
|
59
|
+
return 'bigint()';
|
|
60
|
+
}
|
|
61
|
+
if (baseType === 'numeric' || baseType === 'decimal') {
|
|
62
|
+
if (params) {
|
|
63
|
+
const [precision, scale] = params.split(',').map(s => s.trim());
|
|
64
|
+
if (scale) {
|
|
65
|
+
return `numeric().precision(${precision}).scale(${scale})`;
|
|
66
|
+
}
|
|
67
|
+
return `numeric().precision(${precision})`;
|
|
68
|
+
}
|
|
69
|
+
return 'numeric()';
|
|
70
|
+
}
|
|
71
|
+
if (['real', 'float4'].includes(baseType)) {
|
|
72
|
+
return 'real()';
|
|
73
|
+
}
|
|
74
|
+
if (['float8', 'double precision'].includes(baseType)) {
|
|
75
|
+
return 'doublePrecision()';
|
|
76
|
+
}
|
|
77
|
+
if (baseType === 'text') {
|
|
78
|
+
return 'text()';
|
|
79
|
+
}
|
|
80
|
+
if (baseType === 'varchar' || baseType === 'character varying') {
|
|
81
|
+
if (params) {
|
|
82
|
+
return `varchar().length(${params})`;
|
|
83
|
+
}
|
|
84
|
+
return 'varchar()';
|
|
85
|
+
}
|
|
86
|
+
if (baseType === 'char' || baseType === 'character' || baseType === 'bpchar') {
|
|
87
|
+
if (params) {
|
|
88
|
+
return `char().length(${params})`;
|
|
89
|
+
}
|
|
90
|
+
return 'char()';
|
|
91
|
+
}
|
|
92
|
+
if (baseType === 'citext') {
|
|
93
|
+
return 'citext()';
|
|
94
|
+
}
|
|
95
|
+
if (baseType === 'boolean' || baseType === 'bool') {
|
|
96
|
+
return 'boolean()';
|
|
97
|
+
}
|
|
98
|
+
if (baseType === 'uuid') {
|
|
99
|
+
return 'uuid()';
|
|
100
|
+
}
|
|
101
|
+
if (baseType === 'inet') {
|
|
102
|
+
return 'inet()';
|
|
103
|
+
}
|
|
104
|
+
if (baseType === 'timestamp' || baseType === 'timestamptz') {
|
|
105
|
+
return 'timestamp().withTimezone()';
|
|
106
|
+
}
|
|
107
|
+
if (baseType === 'date') {
|
|
108
|
+
return 'date()';
|
|
109
|
+
}
|
|
110
|
+
if (baseType === 'time' || baseType === 'timetz') {
|
|
111
|
+
return 'time()';
|
|
112
|
+
}
|
|
113
|
+
if (baseType === 'jsonb') {
|
|
114
|
+
return 'jsonb()';
|
|
115
|
+
}
|
|
116
|
+
if (baseType === 'json') {
|
|
117
|
+
return 'json()';
|
|
118
|
+
}
|
|
119
|
+
if (baseType === 'bytea') {
|
|
120
|
+
return 'bytea()';
|
|
121
|
+
}
|
|
122
|
+
return 'text()';
|
|
123
|
+
}
|
|
124
|
+
function convertSqlCheckToTypedExpr(check) {
|
|
125
|
+
const trimmed = check.trim();
|
|
126
|
+
const betweenExact = trimmed.match(/^VALUE\s+BETWEEN\s+(\S+)\s+AND\s+(\S+)$/i);
|
|
127
|
+
if (betweenExact) {
|
|
128
|
+
return `value.between('${betweenExact[1]}', '${betweenExact[2]}')`;
|
|
129
|
+
}
|
|
130
|
+
if (/\sAND\s/i.test(trimmed) && !/\bBETWEEN\b/i.test(trimmed)) {
|
|
131
|
+
const parts = splitCheckByAnd(trimmed);
|
|
132
|
+
if (parts.length > 1) {
|
|
133
|
+
const parsedParts = parts.map(p => convertSqlCheckToTypedExpr(p.trim()));
|
|
134
|
+
return parsedParts.reduce((acc, part, idx) => {
|
|
135
|
+
if (idx === 0)
|
|
136
|
+
return part;
|
|
137
|
+
return `${acc}.and(${part})`;
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
const regexMatch = trimmed.match(/^VALUE\s+~\*\s+'([^']+)'$/i);
|
|
142
|
+
if (regexMatch) {
|
|
143
|
+
const regex = regexMatch[1].replace(/\\/g, '\\\\').replace(/'/g, "\\'");
|
|
144
|
+
return `value.matches('${regex}')`;
|
|
145
|
+
}
|
|
146
|
+
const csRegexMatch = trimmed.match(/^VALUE\s+~\s+'([^']+)'$/i);
|
|
147
|
+
if (csRegexMatch) {
|
|
148
|
+
const regex = csRegexMatch[1].replace(/\\/g, '\\\\').replace(/'/g, "\\'");
|
|
149
|
+
return `value.matchesCaseSensitive('${regex}')`;
|
|
150
|
+
}
|
|
151
|
+
const gtMatch = trimmed.match(/^VALUE\s*>\s*([^\s]+)$/i);
|
|
152
|
+
if (gtMatch) {
|
|
153
|
+
return `value.gt('${gtMatch[1]}')`;
|
|
154
|
+
}
|
|
155
|
+
const gteMatch = trimmed.match(/^VALUE\s*>=\s*([^\s]+)$/i);
|
|
156
|
+
if (gteMatch) {
|
|
157
|
+
return `value.gte('${gteMatch[1]}')`;
|
|
158
|
+
}
|
|
159
|
+
const ltMatch = trimmed.match(/^VALUE\s*<\s*([^\s]+)$/i);
|
|
160
|
+
if (ltMatch) {
|
|
161
|
+
return `value.lt('${ltMatch[1]}')`;
|
|
162
|
+
}
|
|
163
|
+
const lteMatch = trimmed.match(/^VALUE\s*<=\s*([^\s]+)$/i);
|
|
164
|
+
if (lteMatch) {
|
|
165
|
+
return `value.lte('${lteMatch[1]}')`;
|
|
166
|
+
}
|
|
167
|
+
const eqMatch = trimmed.match(/^VALUE\s*=\s*(.+)$/i);
|
|
168
|
+
if (eqMatch) {
|
|
169
|
+
const val = eqMatch[1].trim();
|
|
170
|
+
if (val.startsWith("'") && val.endsWith("'")) {
|
|
171
|
+
return `value.eq(${val})`;
|
|
172
|
+
}
|
|
173
|
+
return `value.eq('${val}')`;
|
|
174
|
+
}
|
|
175
|
+
const lengthLte = trimmed.match(/^LENGTH\s*\(\s*VALUE\s*\)\s*<=\s*(\d+)$/i);
|
|
176
|
+
if (lengthLte) {
|
|
177
|
+
return `value.lengthLte(${lengthLte[1]})`;
|
|
178
|
+
}
|
|
179
|
+
const lengthGte = trimmed.match(/^LENGTH\s*\(\s*VALUE\s*\)\s*>=\s*(\d+)$/i);
|
|
180
|
+
if (lengthGte) {
|
|
181
|
+
return `value.lengthGte(${lengthGte[1]})`;
|
|
182
|
+
}
|
|
183
|
+
const lengthLt = trimmed.match(/^LENGTH\s*\(\s*VALUE\s*\)\s*<\s*(\d+)$/i);
|
|
184
|
+
if (lengthLt) {
|
|
185
|
+
return `value.lengthLt(${lengthLt[1]})`;
|
|
186
|
+
}
|
|
187
|
+
const lengthGt = trimmed.match(/^LENGTH\s*\(\s*VALUE\s*\)\s*>\s*(\d+)$/i);
|
|
188
|
+
if (lengthGt) {
|
|
189
|
+
return `value.lengthGt(${lengthGt[1]})`;
|
|
190
|
+
}
|
|
191
|
+
const lengthEq = trimmed.match(/^LENGTH\s*\(\s*VALUE\s*\)\s*=\s*(\d+)$/i);
|
|
192
|
+
if (lengthEq) {
|
|
193
|
+
return `value.lengthEq(${lengthEq[1]})`;
|
|
194
|
+
}
|
|
195
|
+
const notLike = trimmed.match(/^VALUE\s+NOT\s+LIKE\s+'([^']+)'$/i);
|
|
196
|
+
if (notLike) {
|
|
197
|
+
return `value.notLike('${notLike[1].replace(/'/g, "\\'")}')`;
|
|
198
|
+
}
|
|
199
|
+
const like = trimmed.match(/^VALUE\s+LIKE\s+'([^']+)'$/i);
|
|
200
|
+
if (like) {
|
|
201
|
+
return `value.like('${like[1].replace(/'/g, "\\'")}')`;
|
|
202
|
+
}
|
|
203
|
+
const inMatch = trimmed.match(/^VALUE\s+IN\s*\(([^)]+)\)$/i);
|
|
204
|
+
if (inMatch) {
|
|
205
|
+
return `value.in([${inMatch[1]}])`;
|
|
206
|
+
}
|
|
207
|
+
const notInMatch = trimmed.match(/^VALUE\s+NOT\s+IN\s*\(([^)]+)\)$/i);
|
|
208
|
+
if (notInMatch) {
|
|
209
|
+
return `value.notIn([${notInMatch[1]}])`;
|
|
210
|
+
}
|
|
211
|
+
const escapedCheck = check.replace(/'/g, "\\'");
|
|
212
|
+
return `value.matches('${escapedCheck}')`;
|
|
213
|
+
}
|
|
214
|
+
function splitCheckByAnd(expr) {
|
|
215
|
+
const parts = [];
|
|
216
|
+
let current = '';
|
|
217
|
+
let depth = 0;
|
|
218
|
+
let inQuote = false;
|
|
219
|
+
let quoteChar = '';
|
|
220
|
+
let i = 0;
|
|
221
|
+
while (i < expr.length) {
|
|
222
|
+
const char = expr[i];
|
|
223
|
+
if (!inQuote) {
|
|
224
|
+
if (char === "'" || char === '"') {
|
|
225
|
+
inQuote = true;
|
|
226
|
+
quoteChar = char;
|
|
227
|
+
current += char;
|
|
228
|
+
}
|
|
229
|
+
else if (char === '(' || char === '[') {
|
|
230
|
+
depth++;
|
|
231
|
+
current += char;
|
|
232
|
+
}
|
|
233
|
+
else if (char === ')' || char === ']') {
|
|
234
|
+
depth--;
|
|
235
|
+
current += char;
|
|
236
|
+
}
|
|
237
|
+
else if (depth === 0 && expr.substring(i).toUpperCase().startsWith(' AND ')) {
|
|
238
|
+
if (current.trim()) {
|
|
239
|
+
parts.push(current.trim());
|
|
240
|
+
}
|
|
241
|
+
current = '';
|
|
242
|
+
i += 5;
|
|
243
|
+
continue;
|
|
244
|
+
}
|
|
245
|
+
else {
|
|
246
|
+
current += char;
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
else {
|
|
250
|
+
current += char;
|
|
251
|
+
if (char === quoteChar && expr[i - 1] !== '\\') {
|
|
252
|
+
inQuote = false;
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
i++;
|
|
256
|
+
}
|
|
257
|
+
if (current.trim()) {
|
|
258
|
+
parts.push(current.trim());
|
|
259
|
+
}
|
|
260
|
+
return parts;
|
|
261
|
+
}
|
|
262
|
+
function getColumnType(col, enumNames, domainNames, compositeNames) {
|
|
263
|
+
let pgType = col.dataType.toLowerCase();
|
|
264
|
+
const isArray = pgType.startsWith('_') || pgType.endsWith('[]');
|
|
265
|
+
if (pgType.startsWith('_')) {
|
|
266
|
+
pgType = pgType.slice(1);
|
|
267
|
+
}
|
|
268
|
+
if (pgType.endsWith('[]')) {
|
|
269
|
+
pgType = pgType.slice(0, -2);
|
|
270
|
+
}
|
|
271
|
+
const paramMatch = pgType.match(/^([a-z_]+)(?:\(([^)]+)\))?$/);
|
|
272
|
+
const baseType = paramMatch ? paramMatch[1] : pgType;
|
|
273
|
+
const paramsStr = paramMatch ? paramMatch[2] : null;
|
|
274
|
+
if (enumNames && enumNames.has(baseType)) {
|
|
275
|
+
const enumVarName = toCamelCase(baseType) + 'Enum';
|
|
276
|
+
let typeFunc = `${enumVarName}()`;
|
|
277
|
+
if (isArray) {
|
|
278
|
+
typeFunc += '.array()';
|
|
279
|
+
}
|
|
280
|
+
return typeFunc;
|
|
281
|
+
}
|
|
282
|
+
if (compositeNames && compositeNames.has(baseType)) {
|
|
283
|
+
const compositeVarName = toCamelCase(baseType) + 'Composite';
|
|
284
|
+
let typeFunc = `${compositeVarName}()`;
|
|
285
|
+
if (isArray) {
|
|
286
|
+
typeFunc += '.array()';
|
|
287
|
+
}
|
|
288
|
+
return typeFunc;
|
|
289
|
+
}
|
|
290
|
+
if (domainNames && domainNames.has(baseType)) {
|
|
291
|
+
const domainVarName = toCamelCase(baseType) + 'Domain';
|
|
292
|
+
let typeFunc = `${domainVarName}()`;
|
|
293
|
+
if (isArray) {
|
|
294
|
+
typeFunc += '.array()';
|
|
295
|
+
}
|
|
296
|
+
return typeFunc;
|
|
297
|
+
}
|
|
298
|
+
let length = col.maxLength;
|
|
299
|
+
let precision = col.precision;
|
|
300
|
+
let scale = col.scale;
|
|
301
|
+
if (paramsStr) {
|
|
302
|
+
const params = paramsStr.split(',').map(p => p.trim());
|
|
303
|
+
if (params.length === 1 && !isNaN(Number(params[0]))) {
|
|
304
|
+
length = Number(params[0]);
|
|
305
|
+
}
|
|
306
|
+
else if (params.length === 2) {
|
|
307
|
+
precision = Number(params[0]);
|
|
308
|
+
scale = Number(params[1]);
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
const colWithParams = { ...col, maxLength: length, precision, scale };
|
|
312
|
+
let typeFunc = getTypeFunctionBase(baseType, colWithParams);
|
|
313
|
+
if (isArray) {
|
|
314
|
+
typeFunc += '.array()';
|
|
315
|
+
}
|
|
316
|
+
return typeFunc;
|
|
317
|
+
}
|
|
318
|
+
function getTypeFunctionBase(pgType, col) {
|
|
319
|
+
if (['int4', 'integer'].includes(pgType))
|
|
320
|
+
return 'integer()';
|
|
321
|
+
if (['int2', 'smallint'].includes(pgType))
|
|
322
|
+
return 'smallint()';
|
|
323
|
+
if (['int8', 'bigint'].includes(pgType))
|
|
324
|
+
return 'bigint()';
|
|
325
|
+
if (['serial', 'serial4'].includes(pgType))
|
|
326
|
+
return 'serial()';
|
|
327
|
+
if (['serial2', 'smallserial'].includes(pgType))
|
|
328
|
+
return 'smallserial()';
|
|
329
|
+
if (['serial8', 'bigserial'].includes(pgType))
|
|
330
|
+
return 'bigserial()';
|
|
331
|
+
if (['float4', 'real'].includes(pgType))
|
|
332
|
+
return 'real()';
|
|
333
|
+
if (['float8', 'double precision'].includes(pgType))
|
|
334
|
+
return 'doublePrecision()';
|
|
335
|
+
if (pgType === 'numeric' || pgType === 'decimal') {
|
|
336
|
+
if (col.precision && col.scale) {
|
|
337
|
+
return `numeric().precision(${col.precision}).scale(${col.scale})`;
|
|
338
|
+
}
|
|
339
|
+
else if (col.precision) {
|
|
340
|
+
return `numeric().precision(${col.precision})`;
|
|
341
|
+
}
|
|
342
|
+
return 'numeric()';
|
|
343
|
+
}
|
|
344
|
+
if (pgType === 'text')
|
|
345
|
+
return 'text()';
|
|
346
|
+
if (pgType === 'varchar' || pgType === 'character varying') {
|
|
347
|
+
return col.maxLength ? `varchar().length(${col.maxLength})` : 'varchar()';
|
|
348
|
+
}
|
|
349
|
+
if (pgType === 'char' || pgType === 'character' || pgType === 'bpchar') {
|
|
350
|
+
return col.maxLength ? `char().length(${col.maxLength})` : 'char()';
|
|
351
|
+
}
|
|
352
|
+
if (pgType === 'boolean' || pgType === 'bool')
|
|
353
|
+
return 'boolean()';
|
|
354
|
+
if (pgType === 'uuid')
|
|
355
|
+
return 'uuid()';
|
|
356
|
+
if (pgType === 'jsonb')
|
|
357
|
+
return 'jsonb()';
|
|
358
|
+
if (pgType === 'json')
|
|
359
|
+
return 'json()';
|
|
360
|
+
if (pgType === 'timestamp')
|
|
361
|
+
return 'timestamp()';
|
|
362
|
+
if (pgType === 'timestamptz')
|
|
363
|
+
return 'timestamp().withTimezone()';
|
|
364
|
+
if (pgType === 'date')
|
|
365
|
+
return 'date()';
|
|
366
|
+
if (pgType === 'time')
|
|
367
|
+
return 'time()';
|
|
368
|
+
if (pgType === 'timetz')
|
|
369
|
+
return 'time().withTimezone()';
|
|
370
|
+
if (pgType === 'interval')
|
|
371
|
+
return 'interval()';
|
|
372
|
+
if (pgType === 'bytea')
|
|
373
|
+
return 'bytea()';
|
|
374
|
+
if (pgType === 'inet')
|
|
375
|
+
return 'inet()';
|
|
376
|
+
if (pgType === 'cidr')
|
|
377
|
+
return 'cidr()';
|
|
378
|
+
if (pgType === 'macaddr')
|
|
379
|
+
return 'macaddr()';
|
|
380
|
+
if (pgType === 'vector') {
|
|
381
|
+
return col.maxLength ? `vector().dimensions(${col.maxLength})` : 'vector()';
|
|
382
|
+
}
|
|
383
|
+
if (pgType === 'tsvector')
|
|
384
|
+
return 'tsvector()';
|
|
385
|
+
if (pgType === 'tsquery')
|
|
386
|
+
return 'tsquery()';
|
|
387
|
+
if (pgType === 'citext')
|
|
388
|
+
return 'citext()';
|
|
389
|
+
if (pgType === 'hstore')
|
|
390
|
+
return 'hstore()';
|
|
391
|
+
if (pgType === 'ltree')
|
|
392
|
+
return 'ltree()';
|
|
393
|
+
if (pgType === 'lquery')
|
|
394
|
+
return 'lquery()';
|
|
395
|
+
if (pgType === 'ltxtquery')
|
|
396
|
+
return 'ltxtquery()';
|
|
397
|
+
if (pgType === 'cube')
|
|
398
|
+
return 'cube()';
|
|
399
|
+
if (pgType === 'semver')
|
|
400
|
+
return 'semver()';
|
|
401
|
+
return 'text()';
|
|
402
|
+
}
|
|
403
|
+
function parseGeneratedExpression(expr, camelCase) {
|
|
404
|
+
expr = expr.trim();
|
|
405
|
+
if (expr.startsWith('(') && expr.endsWith(')')) {
|
|
406
|
+
expr = expr.slice(1, -1).trim();
|
|
407
|
+
}
|
|
408
|
+
const arithmeticResult = parseArithmeticExpression(expr, camelCase);
|
|
409
|
+
if (arithmeticResult) {
|
|
410
|
+
return arithmeticResult;
|
|
411
|
+
}
|
|
412
|
+
const functionResult = parseFunctionExpression(expr, camelCase);
|
|
413
|
+
if (functionResult) {
|
|
414
|
+
return functionResult;
|
|
415
|
+
}
|
|
416
|
+
if (/^[a-z_][a-z0-9_]*$/i.test(expr)) {
|
|
417
|
+
const colName = camelCase ? toCamelCase(expr) : expr;
|
|
418
|
+
return `table.${colName}`;
|
|
419
|
+
}
|
|
420
|
+
const colMatch = expr.match(/[a-z_][a-z0-9_]*/i);
|
|
421
|
+
if (colMatch) {
|
|
422
|
+
const colName = camelCase ? toCamelCase(colMatch[0]) : colMatch[0];
|
|
423
|
+
return `table.${colName}`;
|
|
424
|
+
}
|
|
425
|
+
return `table.id /* TODO: Fix expression: ${expr.replace(/\*\//g, '* /')} */`;
|
|
426
|
+
}
|
|
427
|
+
function parseArithmeticExpression(expr, camelCase) {
|
|
428
|
+
const tokens = [];
|
|
429
|
+
const operators = [];
|
|
430
|
+
let current = '';
|
|
431
|
+
let parenDepth = 0;
|
|
432
|
+
let inQuote = false;
|
|
433
|
+
let quoteChar = '';
|
|
434
|
+
for (let i = 0; i < expr.length; i++) {
|
|
435
|
+
const char = expr[i];
|
|
436
|
+
const nextChar = i + 1 < expr.length ? expr[i + 1] : '';
|
|
437
|
+
if (!inQuote && (char === "'" || char === '"')) {
|
|
438
|
+
inQuote = true;
|
|
439
|
+
quoteChar = char;
|
|
440
|
+
current += char;
|
|
441
|
+
}
|
|
442
|
+
else if (inQuote && char === quoteChar) {
|
|
443
|
+
inQuote = false;
|
|
444
|
+
current += char;
|
|
445
|
+
}
|
|
446
|
+
else if (inQuote) {
|
|
447
|
+
current += char;
|
|
448
|
+
}
|
|
449
|
+
else if (char === '(') {
|
|
450
|
+
parenDepth++;
|
|
451
|
+
current += char;
|
|
452
|
+
}
|
|
453
|
+
else if (char === ')') {
|
|
454
|
+
parenDepth--;
|
|
455
|
+
current += char;
|
|
456
|
+
}
|
|
457
|
+
else if (parenDepth === 0 && char === '|' && nextChar === '|') {
|
|
458
|
+
if (current.trim()) {
|
|
459
|
+
tokens.push(current.trim());
|
|
460
|
+
}
|
|
461
|
+
operators.push('||');
|
|
462
|
+
current = '';
|
|
463
|
+
i++;
|
|
464
|
+
}
|
|
465
|
+
else if (parenDepth === 0 && ['+', '-', '*', '/'].includes(char)) {
|
|
466
|
+
if (char === '-' && current.trim() === '') {
|
|
467
|
+
current += char;
|
|
468
|
+
}
|
|
469
|
+
else {
|
|
470
|
+
if (current.trim()) {
|
|
471
|
+
tokens.push(current.trim());
|
|
472
|
+
}
|
|
473
|
+
operators.push(char);
|
|
474
|
+
current = '';
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
else {
|
|
478
|
+
current += char;
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
if (current.trim()) {
|
|
482
|
+
tokens.push(current.trim());
|
|
483
|
+
}
|
|
484
|
+
if (tokens.length < 2 || operators.length < 1) {
|
|
485
|
+
return null;
|
|
486
|
+
}
|
|
487
|
+
let result = parseSimpleTerm(tokens[0], camelCase);
|
|
488
|
+
if (!result)
|
|
489
|
+
return null;
|
|
490
|
+
for (let i = 0; i < operators.length; i++) {
|
|
491
|
+
const nextTerm = parseSimpleTerm(tokens[i + 1], camelCase);
|
|
492
|
+
if (!nextTerm)
|
|
493
|
+
return null;
|
|
494
|
+
const method = operatorToMethod(operators[i]);
|
|
495
|
+
result = `${result}.${method}(${nextTerm})`;
|
|
496
|
+
}
|
|
497
|
+
return result;
|
|
498
|
+
}
|
|
499
|
+
function operatorToMethod(op) {
|
|
500
|
+
switch (op) {
|
|
501
|
+
case '+': return 'add';
|
|
502
|
+
case '-': return 'subtract';
|
|
503
|
+
case '*': return 'multiply';
|
|
504
|
+
case '/': return 'divide';
|
|
505
|
+
case '||': return 'concat';
|
|
506
|
+
default: return 'add';
|
|
507
|
+
}
|
|
508
|
+
}
|
|
509
|
+
function parseSimpleTerm(term, camelCase) {
|
|
510
|
+
term = term.trim();
|
|
511
|
+
term = term.replace(/::[\w\s\[\]]+$/gi, '').trim();
|
|
512
|
+
if (term.startsWith("'") && term.endsWith("'")) {
|
|
513
|
+
return term;
|
|
514
|
+
}
|
|
515
|
+
if (/^-?\d+(\.\d+)?$/.test(term)) {
|
|
516
|
+
return term;
|
|
517
|
+
}
|
|
518
|
+
if (/^[a-z_][a-z0-9_]*$/i.test(term)) {
|
|
519
|
+
const colName = camelCase ? toCamelCase(term) : term;
|
|
520
|
+
return `table.${colName}`;
|
|
521
|
+
}
|
|
522
|
+
if (term.startsWith('"') && term.endsWith('"')) {
|
|
523
|
+
const name = term.slice(1, -1);
|
|
524
|
+
const colName = camelCase ? toCamelCase(name) : name;
|
|
525
|
+
return `table.${colName}`;
|
|
526
|
+
}
|
|
527
|
+
const funcResult = parseFunctionExpression(term, camelCase);
|
|
528
|
+
if (funcResult) {
|
|
529
|
+
return funcResult;
|
|
530
|
+
}
|
|
531
|
+
if (term.startsWith('(') && term.endsWith(')')) {
|
|
532
|
+
const inner = term.slice(1, -1);
|
|
533
|
+
const arithmeticResult = parseArithmeticExpression(inner, camelCase);
|
|
534
|
+
if (arithmeticResult) {
|
|
535
|
+
return `(${arithmeticResult})`;
|
|
536
|
+
}
|
|
537
|
+
const simpleResult = parseSimpleTerm(inner, camelCase);
|
|
538
|
+
if (simpleResult) {
|
|
539
|
+
return simpleResult;
|
|
540
|
+
}
|
|
541
|
+
}
|
|
542
|
+
const arithmeticResult = parseArithmeticExpression(term, camelCase);
|
|
543
|
+
if (arithmeticResult) {
|
|
544
|
+
return arithmeticResult;
|
|
545
|
+
}
|
|
546
|
+
return null;
|
|
547
|
+
}
|
|
548
|
+
function parseFunctionExpression(expr, camelCase) {
|
|
549
|
+
const funcMatch = expr.match(/^([a-z_][a-z0-9_]*)\s*\((.+)\)$/i);
|
|
550
|
+
if (!funcMatch)
|
|
551
|
+
return null;
|
|
552
|
+
const funcName = funcMatch[1].toLowerCase();
|
|
553
|
+
const argsStr = funcMatch[2];
|
|
554
|
+
const args = parseArguments(argsStr);
|
|
555
|
+
switch (funcName) {
|
|
556
|
+
case 'coalesce': {
|
|
557
|
+
const parsedArgs = args.map(a => parseSimpleTerm(a.trim(), camelCase) || a.trim());
|
|
558
|
+
return `F.coalesce(${parsedArgs.join(', ')})`;
|
|
559
|
+
}
|
|
560
|
+
case 'nullif': {
|
|
561
|
+
const parsedArgs = args.map(a => parseSimpleTerm(a.trim(), camelCase) || a.trim());
|
|
562
|
+
return `F.nullif(${parsedArgs.join(', ')})`;
|
|
563
|
+
}
|
|
564
|
+
case 'lower': {
|
|
565
|
+
const arg = parseSimpleTerm(args[0]?.trim() || '', camelCase);
|
|
566
|
+
return arg ? `F.lower(${arg})` : null;
|
|
567
|
+
}
|
|
568
|
+
case 'upper': {
|
|
569
|
+
const arg = parseSimpleTerm(args[0]?.trim() || '', camelCase);
|
|
570
|
+
return arg ? `F.upper(${arg})` : null;
|
|
571
|
+
}
|
|
572
|
+
case 'trim': {
|
|
573
|
+
const arithmetic = parseArithmeticExpression(args[0]?.trim() || '', camelCase);
|
|
574
|
+
if (arithmetic) {
|
|
575
|
+
return `F.trim(${arithmetic})`;
|
|
576
|
+
}
|
|
577
|
+
const arg = parseSimpleTerm(args[0]?.trim() || '', camelCase);
|
|
578
|
+
return arg ? `F.trim(${arg})` : null;
|
|
579
|
+
}
|
|
580
|
+
case 'length': {
|
|
581
|
+
const arg = parseSimpleTerm(args[0]?.trim() || '', camelCase);
|
|
582
|
+
return arg ? `F.length(${arg})` : null;
|
|
583
|
+
}
|
|
584
|
+
case 'abs': {
|
|
585
|
+
const arg = parseSimpleTerm(args[0]?.trim() || '', camelCase);
|
|
586
|
+
return arg ? `F.abs(${arg})` : null;
|
|
587
|
+
}
|
|
588
|
+
case 'ceil':
|
|
589
|
+
case 'ceiling': {
|
|
590
|
+
const arg = parseSimpleTerm(args[0]?.trim() || '', camelCase);
|
|
591
|
+
return arg ? `F.ceil(${arg})` : null;
|
|
592
|
+
}
|
|
593
|
+
case 'floor': {
|
|
594
|
+
const arg = parseSimpleTerm(args[0]?.trim() || '', camelCase);
|
|
595
|
+
return arg ? `F.floor(${arg})` : null;
|
|
596
|
+
}
|
|
597
|
+
case 'round': {
|
|
598
|
+
const arg = parseSimpleTerm(args[0]?.trim() || '', camelCase);
|
|
599
|
+
const decimals = args[1]?.trim();
|
|
600
|
+
if (decimals) {
|
|
601
|
+
return arg ? `F.round(${arg}, ${decimals})` : null;
|
|
602
|
+
}
|
|
603
|
+
return arg ? `F.round(${arg})` : null;
|
|
604
|
+
}
|
|
605
|
+
case 'concat': {
|
|
606
|
+
const parsedArgs = args.map(a => {
|
|
607
|
+
const trimmed = a.trim();
|
|
608
|
+
if (trimmed.startsWith("'") && trimmed.endsWith("'")) {
|
|
609
|
+
return trimmed;
|
|
610
|
+
}
|
|
611
|
+
return parseSimpleTerm(trimmed, camelCase) || trimmed;
|
|
612
|
+
});
|
|
613
|
+
return `F.concat(${parsedArgs.join(', ')})`;
|
|
614
|
+
}
|
|
615
|
+
case 'greatest': {
|
|
616
|
+
const parsedArgs = args.map(a => parseSimpleTerm(a.trim(), camelCase) || a.trim());
|
|
617
|
+
return `F.greatest(${parsedArgs.join(', ')})`;
|
|
618
|
+
}
|
|
619
|
+
case 'least': {
|
|
620
|
+
const parsedArgs = args.map(a => parseSimpleTerm(a.trim(), camelCase) || a.trim());
|
|
621
|
+
return `F.least(${parsedArgs.join(', ')})`;
|
|
622
|
+
}
|
|
623
|
+
case 'md5': {
|
|
624
|
+
const arg = parseSimpleTerm(args[0]?.trim() || '', camelCase);
|
|
625
|
+
return arg ? `F.md5(${arg})` : null;
|
|
626
|
+
}
|
|
627
|
+
default:
|
|
628
|
+
return null;
|
|
629
|
+
}
|
|
630
|
+
}
|
|
631
|
+
function parseArguments(argsStr) {
|
|
632
|
+
const args = [];
|
|
633
|
+
let current = '';
|
|
634
|
+
let parenDepth = 0;
|
|
635
|
+
for (const char of argsStr) {
|
|
636
|
+
if (char === '(') {
|
|
637
|
+
parenDepth++;
|
|
638
|
+
current += char;
|
|
639
|
+
}
|
|
640
|
+
else if (char === ')') {
|
|
641
|
+
parenDepth--;
|
|
642
|
+
current += char;
|
|
643
|
+
}
|
|
644
|
+
else if (char === ',' && parenDepth === 0) {
|
|
645
|
+
args.push(current);
|
|
646
|
+
current = '';
|
|
647
|
+
}
|
|
648
|
+
else {
|
|
649
|
+
current += char;
|
|
650
|
+
}
|
|
651
|
+
}
|
|
652
|
+
if (current) {
|
|
653
|
+
args.push(current);
|
|
654
|
+
}
|
|
655
|
+
return args;
|
|
656
|
+
}
|
|
657
|
+
function formatDefaultValue(val, col, domainMap) {
|
|
658
|
+
if (!val)
|
|
659
|
+
return null;
|
|
660
|
+
const cleaned = val.replace(/::[\w\s\[\]]+$/gi, '').trim();
|
|
661
|
+
if (cleaned.startsWith('nextval('))
|
|
662
|
+
return null;
|
|
663
|
+
if (cleaned.toLowerCase().includes('gen_random_uuid') && col.isPrimaryKey) {
|
|
664
|
+
return null;
|
|
665
|
+
}
|
|
666
|
+
if (cleaned.toLowerCase() === 'true')
|
|
667
|
+
return 'true';
|
|
668
|
+
if (cleaned.toLowerCase() === 'false')
|
|
669
|
+
return 'false';
|
|
670
|
+
let baseDataType = col.dataType.toLowerCase().replace(/\([^)]*\)$/, '').trim();
|
|
671
|
+
if (domainMap && domainMap.has(baseDataType)) {
|
|
672
|
+
baseDataType = domainMap.get(baseDataType).toLowerCase().replace(/\([^)]*\)$/, '').trim();
|
|
673
|
+
}
|
|
674
|
+
const isNumeric = ['numeric', 'decimal'].includes(baseDataType);
|
|
675
|
+
const isBigInt = ['int8', 'bigint'].includes(baseDataType);
|
|
676
|
+
if (/^-?\d+$/.test(cleaned)) {
|
|
677
|
+
if (isNumeric) {
|
|
678
|
+
return `'${cleaned}'`;
|
|
679
|
+
}
|
|
680
|
+
else if (isBigInt) {
|
|
681
|
+
return `BigInt(${cleaned})`;
|
|
682
|
+
}
|
|
683
|
+
return cleaned;
|
|
684
|
+
}
|
|
685
|
+
if (/^-?\d+\.\d+$/.test(cleaned)) {
|
|
686
|
+
return isNumeric ? `'${cleaned}'` : cleaned;
|
|
687
|
+
}
|
|
688
|
+
if (cleaned.toLowerCase() === 'gen_random_uuid()')
|
|
689
|
+
return 'genRandomUuid()';
|
|
690
|
+
if (cleaned.toLowerCase() === 'uuid_generate_v4()')
|
|
691
|
+
return 'genRandomUuid()';
|
|
692
|
+
if (cleaned.toLowerCase() === 'now()')
|
|
693
|
+
return 'now()';
|
|
694
|
+
if (cleaned.toLowerCase() === 'current_timestamp')
|
|
695
|
+
return 'now()';
|
|
696
|
+
if (cleaned.toLowerCase() === 'current_date')
|
|
697
|
+
return 'currentDate()';
|
|
698
|
+
if (cleaned === "'{}'") {
|
|
699
|
+
const isArray = col.dataType.endsWith('[]') || col.dataType.startsWith('_');
|
|
700
|
+
if (isArray)
|
|
701
|
+
return 'emptyArray()';
|
|
702
|
+
return 'emptyObject()';
|
|
703
|
+
}
|
|
704
|
+
if (cleaned === "'[]'" || cleaned === 'ARRAY[]')
|
|
705
|
+
return 'emptyArray()';
|
|
706
|
+
const pgArrayMatch = cleaned.match(/^'?\{([^}]*)\}'?$/);
|
|
707
|
+
if (pgArrayMatch) {
|
|
708
|
+
const contents = pgArrayMatch[1];
|
|
709
|
+
if (contents === '') {
|
|
710
|
+
return 'emptyArray()';
|
|
711
|
+
}
|
|
712
|
+
const values = contents.split(',').map(v => {
|
|
713
|
+
const trimmed = v.trim();
|
|
714
|
+
if (trimmed.startsWith('"') && trimmed.endsWith('"')) {
|
|
715
|
+
return `'${trimmed.slice(1, -1)}'`;
|
|
716
|
+
}
|
|
717
|
+
return `'${trimmed}'`;
|
|
718
|
+
});
|
|
719
|
+
return `[${values.join(', ')}]`;
|
|
720
|
+
}
|
|
721
|
+
if (cleaned.startsWith('ARRAY[')) {
|
|
722
|
+
const arrayContent = cleaned.match(/ARRAY\[([^\]]*)\]/i);
|
|
723
|
+
if (arrayContent && arrayContent[1]) {
|
|
724
|
+
const values = arrayContent[1].split(',').map(v => {
|
|
725
|
+
const trimmed = v.trim();
|
|
726
|
+
if (/^-?\d+(\.\d+)?$/.test(trimmed)) {
|
|
727
|
+
return trimmed;
|
|
728
|
+
}
|
|
729
|
+
if (/^(true|false)$/i.test(trimmed)) {
|
|
730
|
+
return trimmed.toLowerCase();
|
|
731
|
+
}
|
|
732
|
+
if (/^null$/i.test(trimmed)) {
|
|
733
|
+
return 'null';
|
|
734
|
+
}
|
|
735
|
+
const unquoted = trimmed.replace(/^'|'$/g, '');
|
|
736
|
+
return `'${unquoted}'`;
|
|
737
|
+
});
|
|
738
|
+
return `[${values.join(', ')}]`;
|
|
739
|
+
}
|
|
740
|
+
return 'emptyArray()';
|
|
741
|
+
}
|
|
742
|
+
const isJsonColumn = col.dataType.toLowerCase().includes('json');
|
|
743
|
+
if (isJsonColumn && cleaned.startsWith("'") && cleaned.endsWith("'")) {
|
|
744
|
+
const jsonStr = cleaned.slice(1, -1).replace(/''/g, "'");
|
|
745
|
+
try {
|
|
746
|
+
const parsed = JSON.parse(jsonStr);
|
|
747
|
+
return JSON.stringify(parsed);
|
|
748
|
+
}
|
|
749
|
+
catch {
|
|
750
|
+
}
|
|
751
|
+
}
|
|
752
|
+
if (cleaned.startsWith("'") && cleaned.endsWith("'")) {
|
|
753
|
+
const str = cleaned.slice(1, -1).replace(/'/g, "\\'");
|
|
754
|
+
return `'${str}'`;
|
|
755
|
+
}
|
|
756
|
+
return null;
|
|
757
|
+
}
|
|
758
|
+
function generateColumnDef(col, seenColumns, camelCase = true, checkValues, enumNames, domainNames, compositeNames, domainMap) {
|
|
759
|
+
if (seenColumns.has(col.name)) {
|
|
760
|
+
return null;
|
|
761
|
+
}
|
|
762
|
+
seenColumns.add(col.name);
|
|
763
|
+
const colType = getColumnType(col, enumNames, domainNames, compositeNames);
|
|
764
|
+
let propName;
|
|
765
|
+
let typeCall;
|
|
766
|
+
if (camelCase) {
|
|
767
|
+
propName = toCamelCase(col.name);
|
|
768
|
+
if (propName !== col.name) {
|
|
769
|
+
typeCall = injectColumnName(colType, col.name);
|
|
770
|
+
}
|
|
771
|
+
else {
|
|
772
|
+
typeCall = colType;
|
|
773
|
+
}
|
|
774
|
+
}
|
|
775
|
+
else {
|
|
776
|
+
propName = col.name;
|
|
777
|
+
typeCall = colType;
|
|
778
|
+
}
|
|
779
|
+
const parts = [typeCall];
|
|
780
|
+
if (checkValues && checkValues.length > 0) {
|
|
781
|
+
const quotedValues = checkValues.map(v => `'${v}'`).join(', ');
|
|
782
|
+
parts.push(`.check(${quotedValues})`);
|
|
783
|
+
}
|
|
784
|
+
if (col.isPrimaryKey) {
|
|
785
|
+
parts.push('.primaryKey()');
|
|
786
|
+
}
|
|
787
|
+
if (!col.isNullable && !col.isPrimaryKey && !col.isGenerated) {
|
|
788
|
+
parts.push('.notNull()');
|
|
789
|
+
}
|
|
790
|
+
if (col.isUnique && !col.isPrimaryKey) {
|
|
791
|
+
parts.push('.unique()');
|
|
792
|
+
}
|
|
793
|
+
if (col.isGenerated && col.generationExpression) {
|
|
794
|
+
const typedExpr = parseGeneratedExpression(col.generationExpression, camelCase);
|
|
795
|
+
parts.push(`.generatedAlwaysAs((table, F) => ${typedExpr})`);
|
|
796
|
+
}
|
|
797
|
+
else {
|
|
798
|
+
const defaultVal = formatDefaultValue(col.defaultValue, col, domainMap);
|
|
799
|
+
if (defaultVal) {
|
|
800
|
+
parts.push(`.default(${defaultVal})`);
|
|
801
|
+
}
|
|
802
|
+
}
|
|
803
|
+
if (col.references) {
|
|
804
|
+
let refStr = `.references(() => ${toCamelCase(col.references.table)}.${toCamelCase(col.references.column)})`;
|
|
805
|
+
if (col.references.onDelete && col.references.onDelete !== 'NO ACTION') {
|
|
806
|
+
refStr = `.references(() => ${toCamelCase(col.references.table)}.${toCamelCase(col.references.column)}, { onDelete: '${col.references.onDelete.toLowerCase()}' })`;
|
|
807
|
+
}
|
|
808
|
+
if (col.references.onUpdate && col.references.onUpdate !== 'NO ACTION') {
|
|
809
|
+
if (col.references.onDelete && col.references.onDelete !== 'NO ACTION') {
|
|
810
|
+
refStr = `.references(() => ${toCamelCase(col.references.table)}.${toCamelCase(col.references.column)}, { onDelete: '${col.references.onDelete.toLowerCase()}', onUpdate: '${col.references.onUpdate.toLowerCase()}' })`;
|
|
811
|
+
}
|
|
812
|
+
else {
|
|
813
|
+
refStr = `.references(() => ${toCamelCase(col.references.table)}.${toCamelCase(col.references.column)}, { onUpdate: '${col.references.onUpdate.toLowerCase()}' })`;
|
|
814
|
+
}
|
|
815
|
+
}
|
|
816
|
+
parts.push(refStr);
|
|
817
|
+
}
|
|
818
|
+
const columnLine = `${propName}: ${parts.join('')}`;
|
|
819
|
+
if (col.comment) {
|
|
820
|
+
const safeComment = col.comment.replace(/\*\//g, '* /');
|
|
821
|
+
return ` /** ${safeComment} */\n ${columnLine}`;
|
|
822
|
+
}
|
|
823
|
+
return ` ${columnLine}`;
|
|
824
|
+
}
|
|
825
|
+
function injectColumnName(typeCall, columnName) {
|
|
826
|
+
return typeCall.replace(/^(\w+)(<[^>]+>)?\(\)/, `$1$2('${columnName}')`);
|
|
827
|
+
}
|
|
828
|
+
function generateIndexes(indexes, columnNames, camelCase = true) {
|
|
829
|
+
const nonPkIndexes = indexes.filter(idx => !idx.isPrimary);
|
|
830
|
+
if (nonPkIndexes.length === 0) {
|
|
831
|
+
return null;
|
|
832
|
+
}
|
|
833
|
+
let usesExpressions = false;
|
|
834
|
+
const indexLines = nonPkIndexes.map(idx => {
|
|
835
|
+
let columnsArr;
|
|
836
|
+
if (Array.isArray(idx.columns)) {
|
|
837
|
+
columnsArr = idx.columns;
|
|
838
|
+
}
|
|
839
|
+
else if (typeof idx.columns === 'string') {
|
|
840
|
+
const cleaned = idx.columns.replace(/^\{|\}$/g, '');
|
|
841
|
+
columnsArr = cleaned.split(',').map(s => s.trim()).filter(Boolean);
|
|
842
|
+
}
|
|
843
|
+
else {
|
|
844
|
+
columnsArr = [];
|
|
845
|
+
}
|
|
846
|
+
const hasExpression = idx.expression || idx.definition?.includes('(');
|
|
847
|
+
const sqlFunctions = new Set(['lower', 'upper', 'coalesce', 'concat', 'to_tsvector', 'toTsvector',
|
|
848
|
+
'plainto_tsquery', 'ts_rank', 'substring', 'trim', 'length', 'position', 'replace', 'left', 'right',
|
|
849
|
+
'english', 'simple', 'german', 'french', 'spanish', 'now', 'current_timestamp', 'current_date']);
|
|
850
|
+
const validColumns = columnsArr.filter(c => {
|
|
851
|
+
const trimmed = c.trim().toLowerCase();
|
|
852
|
+
if (!trimmed || !/^[a-zA-Z_]/.test(trimmed))
|
|
853
|
+
return false;
|
|
854
|
+
if (sqlFunctions.has(trimmed))
|
|
855
|
+
return false;
|
|
856
|
+
return columnNames.some(cn => cn.toLowerCase() === trimmed || toCamelCase(cn).toLowerCase() === trimmed);
|
|
857
|
+
});
|
|
858
|
+
if (validColumns.length === 0 && hasExpression) {
|
|
859
|
+
usesExpressions = true;
|
|
860
|
+
const expr = idx.expression || extractExpressionFromDef(idx.definition);
|
|
861
|
+
if (expr) {
|
|
862
|
+
const parsedExpr = parseIndexExpression(expr, camelCase);
|
|
863
|
+
let line;
|
|
864
|
+
if (parsedExpr) {
|
|
865
|
+
line = ` index('${idx.name}').expression(exp => ${parsedExpr})`;
|
|
866
|
+
}
|
|
867
|
+
else {
|
|
868
|
+
const escapedExpr = expr.replace(/'/g, "\\'").replace(/\n/g, ' ');
|
|
869
|
+
line = ` index('${idx.name}').expression(exp => exp.raw('${escapedExpr}'))`;
|
|
870
|
+
}
|
|
871
|
+
if (idx.isUnique)
|
|
872
|
+
line += '.unique()';
|
|
873
|
+
if (idx.type && idx.type !== 'btree')
|
|
874
|
+
line += `.using('${idx.type.toUpperCase()}')`;
|
|
875
|
+
if (idx.operatorClasses && idx.operatorClasses.length > 0) {
|
|
876
|
+
line += `.opclass('${idx.operatorClasses[0]}')`;
|
|
877
|
+
}
|
|
878
|
+
if (idx.whereClause) {
|
|
879
|
+
const whereCallback = parseWhereClause(idx.whereClause, camelCase);
|
|
880
|
+
line += `.where(${whereCallback})`;
|
|
881
|
+
}
|
|
882
|
+
return line;
|
|
883
|
+
}
|
|
884
|
+
return null;
|
|
885
|
+
}
|
|
886
|
+
if (validColumns.length === 0)
|
|
887
|
+
return null;
|
|
888
|
+
const cols = validColumns.map(c => {
|
|
889
|
+
const propName = camelCase ? toCamelCase(c) : c;
|
|
890
|
+
return `table.${propName}`;
|
|
891
|
+
}).join(', ');
|
|
892
|
+
let line = ` index('${idx.name}').on(${cols})`;
|
|
893
|
+
if (idx.isUnique) {
|
|
894
|
+
line += '.unique()';
|
|
895
|
+
}
|
|
896
|
+
if (idx.type && idx.type !== 'btree') {
|
|
897
|
+
line += `.using('${idx.type.toUpperCase()}')`;
|
|
898
|
+
}
|
|
899
|
+
if (idx.operatorClasses && idx.operatorClasses.length > 0) {
|
|
900
|
+
line += `.opclass('${idx.operatorClasses[0]}')`;
|
|
901
|
+
}
|
|
902
|
+
if (idx.whereClause) {
|
|
903
|
+
const whereCallback = parseWhereClause(idx.whereClause, camelCase);
|
|
904
|
+
line += `.where(${whereCallback})`;
|
|
905
|
+
}
|
|
906
|
+
return line;
|
|
907
|
+
}).filter(Boolean);
|
|
908
|
+
if (indexLines.length === 0)
|
|
909
|
+
return null;
|
|
910
|
+
if (usesExpressions) {
|
|
911
|
+
return ` (table, index, F) => [\n${indexLines.join(',\n')},\n ]`;
|
|
912
|
+
}
|
|
913
|
+
else {
|
|
914
|
+
return ` (table, index) => [\n${indexLines.join(',\n')},\n ]`;
|
|
915
|
+
}
|
|
916
|
+
}
|
|
917
|
+
function extractExpressionFromDef(definition) {
|
|
918
|
+
if (!definition)
|
|
919
|
+
return null;
|
|
920
|
+
const onMatch = definition.match(/\bON\s+\w+\s*(?:USING\s+\w+\s*)?\(/i);
|
|
921
|
+
if (!onMatch)
|
|
922
|
+
return null;
|
|
923
|
+
const startIdx = onMatch.index + onMatch[0].length;
|
|
924
|
+
let depth = 1;
|
|
925
|
+
let endIdx = startIdx;
|
|
926
|
+
for (let i = startIdx; i < definition.length && depth > 0; i++) {
|
|
927
|
+
if (definition[i] === '(')
|
|
928
|
+
depth++;
|
|
929
|
+
else if (definition[i] === ')')
|
|
930
|
+
depth--;
|
|
931
|
+
if (depth > 0)
|
|
932
|
+
endIdx = i + 1;
|
|
933
|
+
}
|
|
934
|
+
const expr = definition.slice(startIdx, endIdx).trim();
|
|
935
|
+
return expr || null;
|
|
936
|
+
}
|
|
937
|
+
function parseIndexExpression(expr, camelCase) {
|
|
938
|
+
expr = expr.trim();
|
|
939
|
+
const tsvectorMatch = expr.match(/^to_tsvector\s*\(\s*'([^']+)'\s*,\s*(.+)\s*\)$/i);
|
|
940
|
+
if (tsvectorMatch) {
|
|
941
|
+
const config = tsvectorMatch[1];
|
|
942
|
+
const innerExpr = tsvectorMatch[2].trim();
|
|
943
|
+
const parsedInner = parseIndexExpressionPart(innerExpr, camelCase);
|
|
944
|
+
if (parsedInner) {
|
|
945
|
+
return `exp.toTsvector('${config}', ${parsedInner})`;
|
|
946
|
+
}
|
|
947
|
+
}
|
|
948
|
+
const lowerMatch = expr.match(/^LOWER\s*\(\s*([a-z_][a-z0-9_]*)(?:::TEXT)?\s*\)$/i);
|
|
949
|
+
if (lowerMatch) {
|
|
950
|
+
const col = camelCase ? toCamelCase(lowerMatch[1]) : lowerMatch[1];
|
|
951
|
+
return `exp.lower(exp.col('${col}'))`;
|
|
952
|
+
}
|
|
953
|
+
const upperMatch = expr.match(/^UPPER\s*\(\s*([a-z_][a-z0-9_]*)(?:::TEXT)?\s*\)$/i);
|
|
954
|
+
if (upperMatch) {
|
|
955
|
+
const col = camelCase ? toCamelCase(upperMatch[1]) : upperMatch[1];
|
|
956
|
+
return `exp.upper(exp.col('${col}'))`;
|
|
957
|
+
}
|
|
958
|
+
const orderedColMatch = expr.match(/^([a-z_][a-z0-9_]*)\s+(DESC|ASC)(?:\s+NULLS\s+(FIRST|LAST))?$/i);
|
|
959
|
+
if (orderedColMatch) {
|
|
960
|
+
const col = camelCase ? toCamelCase(orderedColMatch[1]) : orderedColMatch[1];
|
|
961
|
+
const order = orderedColMatch[2].toLowerCase();
|
|
962
|
+
const nulls = orderedColMatch[3]?.toLowerCase();
|
|
963
|
+
let result = `exp.col('${col}')`;
|
|
964
|
+
if (order === 'desc') {
|
|
965
|
+
result += '.desc()';
|
|
966
|
+
}
|
|
967
|
+
else {
|
|
968
|
+
result += '.asc()';
|
|
969
|
+
}
|
|
970
|
+
if (nulls === 'last') {
|
|
971
|
+
result += '.nullsLast()';
|
|
972
|
+
}
|
|
973
|
+
else if (nulls === 'first') {
|
|
974
|
+
result += '.nullsFirst()';
|
|
975
|
+
}
|
|
976
|
+
return result;
|
|
977
|
+
}
|
|
978
|
+
if (/^[a-z_][a-z0-9_]*$/i.test(expr)) {
|
|
979
|
+
const col = camelCase ? toCamelCase(expr) : expr;
|
|
980
|
+
return `exp.col('${col}')`;
|
|
981
|
+
}
|
|
982
|
+
return null;
|
|
983
|
+
}
|
|
984
|
+
function parseIndexExpressionPart(expr, camelCase) {
|
|
985
|
+
expr = expr.trim();
|
|
986
|
+
if (expr.includes(' || ')) {
|
|
987
|
+
const parts = splitByConcatOperator(expr);
|
|
988
|
+
if (parts.length > 1) {
|
|
989
|
+
const parsedParts = parts.map(p => parseIndexExpressionPart(p.trim(), camelCase));
|
|
990
|
+
if (parsedParts.every(p => p !== null)) {
|
|
991
|
+
return `exp.concat(${parsedParts.join(', ')})`;
|
|
992
|
+
}
|
|
993
|
+
}
|
|
994
|
+
}
|
|
995
|
+
const coalesceMatch = expr.match(/^COALESCE\s*\(\s*([^,]+)\s*,\s*(.+)\s*\)$/i);
|
|
996
|
+
if (coalesceMatch) {
|
|
997
|
+
const firstArg = coalesceMatch[1].trim();
|
|
998
|
+
const defaultArg = coalesceMatch[2].trim();
|
|
999
|
+
let parsedFirst = null;
|
|
1000
|
+
const colCastMatch = firstArg.match(/^([a-z_][a-z0-9_]*)::TEXT$/i);
|
|
1001
|
+
if (colCastMatch) {
|
|
1002
|
+
const col = camelCase ? toCamelCase(colCastMatch[1]) : colCastMatch[1];
|
|
1003
|
+
parsedFirst = `exp.asText(exp.col('${col}'))`;
|
|
1004
|
+
}
|
|
1005
|
+
else if (/^[a-z_][a-z0-9_]*$/i.test(firstArg)) {
|
|
1006
|
+
const col = camelCase ? toCamelCase(firstArg) : firstArg;
|
|
1007
|
+
parsedFirst = `exp.col('${col}')`;
|
|
1008
|
+
}
|
|
1009
|
+
if (parsedFirst) {
|
|
1010
|
+
if (defaultArg === "''" || defaultArg === "''") {
|
|
1011
|
+
return `exp.coalesce(${parsedFirst}, '')`;
|
|
1012
|
+
}
|
|
1013
|
+
if (/^'[^']*'$/.test(defaultArg)) {
|
|
1014
|
+
return `exp.coalesce(${parsedFirst}, ${defaultArg})`;
|
|
1015
|
+
}
|
|
1016
|
+
}
|
|
1017
|
+
}
|
|
1018
|
+
const colCastMatch = expr.match(/^([a-z_][a-z0-9_]*)::TEXT$/i);
|
|
1019
|
+
if (colCastMatch) {
|
|
1020
|
+
const col = camelCase ? toCamelCase(colCastMatch[1]) : colCastMatch[1];
|
|
1021
|
+
return `exp.asText(exp.col('${col}'))`;
|
|
1022
|
+
}
|
|
1023
|
+
if (/^[a-z_][a-z0-9_]*$/i.test(expr)) {
|
|
1024
|
+
const col = camelCase ? toCamelCase(expr) : expr;
|
|
1025
|
+
return `exp.col('${col}')`;
|
|
1026
|
+
}
|
|
1027
|
+
if (/^'[^']*'$/.test(expr)) {
|
|
1028
|
+
return expr;
|
|
1029
|
+
}
|
|
1030
|
+
return null;
|
|
1031
|
+
}
|
|
1032
|
+
function splitByConcatOperator(expr) {
|
|
1033
|
+
const parts = [];
|
|
1034
|
+
let current = '';
|
|
1035
|
+
let parenDepth = 0;
|
|
1036
|
+
for (let i = 0; i < expr.length; i++) {
|
|
1037
|
+
const char = expr[i];
|
|
1038
|
+
if (char === '(') {
|
|
1039
|
+
parenDepth++;
|
|
1040
|
+
current += char;
|
|
1041
|
+
}
|
|
1042
|
+
else if (char === ')') {
|
|
1043
|
+
parenDepth--;
|
|
1044
|
+
current += char;
|
|
1045
|
+
}
|
|
1046
|
+
else if (parenDepth === 0 && expr.slice(i, i + 4) === ' || ') {
|
|
1047
|
+
if (current.trim()) {
|
|
1048
|
+
parts.push(current.trim());
|
|
1049
|
+
}
|
|
1050
|
+
current = '';
|
|
1051
|
+
i += 3;
|
|
1052
|
+
}
|
|
1053
|
+
else {
|
|
1054
|
+
current += char;
|
|
1055
|
+
}
|
|
1056
|
+
}
|
|
1057
|
+
if (current.trim()) {
|
|
1058
|
+
parts.push(current.trim());
|
|
1059
|
+
}
|
|
1060
|
+
return parts;
|
|
1061
|
+
}
|
|
1062
|
+
function parseWhereValue(value, camelCase) {
|
|
1063
|
+
value = value.trim();
|
|
1064
|
+
if (/^'.*'$/.test(value)) {
|
|
1065
|
+
return value;
|
|
1066
|
+
}
|
|
1067
|
+
if (/^-?\d+(\.\d+)?$/.test(value)) {
|
|
1068
|
+
return value;
|
|
1069
|
+
}
|
|
1070
|
+
if (/^TRUE$/i.test(value)) {
|
|
1071
|
+
return 'true';
|
|
1072
|
+
}
|
|
1073
|
+
if (/^FALSE$/i.test(value)) {
|
|
1074
|
+
return 'false';
|
|
1075
|
+
}
|
|
1076
|
+
if (/^NOW\(\)$/i.test(value)) {
|
|
1077
|
+
return 'w.now()';
|
|
1078
|
+
}
|
|
1079
|
+
if (/^CURRENT_DATE$/i.test(value)) {
|
|
1080
|
+
return 'w.currentDate()';
|
|
1081
|
+
}
|
|
1082
|
+
if (/^CURRENT_TIMESTAMP$/i.test(value)) {
|
|
1083
|
+
return 'w.currentTimestamp()';
|
|
1084
|
+
}
|
|
1085
|
+
const dateIntervalMatch = value.match(/^(CURRENT_DATE|CURRENT_TIMESTAMP|NOW\(\))\s*\+\s*INTERVAL\s*'([^']+)'$/i);
|
|
1086
|
+
if (dateIntervalMatch) {
|
|
1087
|
+
const dateFn = dateIntervalMatch[1].toUpperCase();
|
|
1088
|
+
const interval = dateIntervalMatch[2];
|
|
1089
|
+
if (dateFn === 'CURRENT_DATE') {
|
|
1090
|
+
return `w.currentDate().plus(w.interval('${interval}'))`;
|
|
1091
|
+
}
|
|
1092
|
+
else if (dateFn === 'CURRENT_TIMESTAMP') {
|
|
1093
|
+
return `w.currentTimestamp().plus(w.interval('${interval}'))`;
|
|
1094
|
+
}
|
|
1095
|
+
else {
|
|
1096
|
+
return `w.now().plus(w.interval('${interval}'))`;
|
|
1097
|
+
}
|
|
1098
|
+
}
|
|
1099
|
+
const dateMinusIntervalMatch = value.match(/^(CURRENT_DATE|CURRENT_TIMESTAMP|NOW\(\))\s*-\s*INTERVAL\s*'([^']+)'$/i);
|
|
1100
|
+
if (dateMinusIntervalMatch) {
|
|
1101
|
+
const dateFn = dateMinusIntervalMatch[1].toUpperCase();
|
|
1102
|
+
const interval = dateMinusIntervalMatch[2];
|
|
1103
|
+
if (dateFn === 'CURRENT_DATE') {
|
|
1104
|
+
return `w.currentDate().minus(w.interval('${interval}'))`;
|
|
1105
|
+
}
|
|
1106
|
+
else if (dateFn === 'CURRENT_TIMESTAMP') {
|
|
1107
|
+
return `w.currentTimestamp().minus(w.interval('${interval}'))`;
|
|
1108
|
+
}
|
|
1109
|
+
else {
|
|
1110
|
+
return `w.now().minus(w.interval('${interval}'))`;
|
|
1111
|
+
}
|
|
1112
|
+
}
|
|
1113
|
+
if (/^[a-z_][a-z0-9_]*$/i.test(value)) {
|
|
1114
|
+
const valCol = camelCase ? toCamelCase(value) : value;
|
|
1115
|
+
return `table.${valCol}`;
|
|
1116
|
+
}
|
|
1117
|
+
return null;
|
|
1118
|
+
}
|
|
1119
|
+
function parseSingleCondition(clause, camelCase) {
|
|
1120
|
+
clause = clause.trim();
|
|
1121
|
+
while (clause.startsWith('(') && clause.endsWith(')')) {
|
|
1122
|
+
let depth = 0;
|
|
1123
|
+
let matched = true;
|
|
1124
|
+
for (let i = 0; i < clause.length - 1; i++) {
|
|
1125
|
+
if (clause[i] === '(')
|
|
1126
|
+
depth++;
|
|
1127
|
+
else if (clause[i] === ')')
|
|
1128
|
+
depth--;
|
|
1129
|
+
if (depth === 0 && i < clause.length - 1) {
|
|
1130
|
+
matched = false;
|
|
1131
|
+
break;
|
|
1132
|
+
}
|
|
1133
|
+
}
|
|
1134
|
+
if (matched) {
|
|
1135
|
+
clause = clause.slice(1, -1).trim();
|
|
1136
|
+
}
|
|
1137
|
+
else {
|
|
1138
|
+
break;
|
|
1139
|
+
}
|
|
1140
|
+
}
|
|
1141
|
+
const isNullMatch = clause.match(/^([a-z_][a-z0-9_]*)\s+IS\s+NULL$/i);
|
|
1142
|
+
if (isNullMatch) {
|
|
1143
|
+
const col = camelCase ? toCamelCase(isNullMatch[1]) : isNullMatch[1];
|
|
1144
|
+
return `w.col(table.${col}).isNull()`;
|
|
1145
|
+
}
|
|
1146
|
+
const isNotNullMatch = clause.match(/^([a-z_][a-z0-9_]*)\s+IS\s+NOT\s+NULL$/i);
|
|
1147
|
+
if (isNotNullMatch) {
|
|
1148
|
+
const col = camelCase ? toCamelCase(isNotNullMatch[1]) : isNotNullMatch[1];
|
|
1149
|
+
return `w.col(table.${col}).isNotNull()`;
|
|
1150
|
+
}
|
|
1151
|
+
const notInMatch = clause.match(/^([a-z_][a-z0-9_]*)\s+NOT\s+IN\s*\((.+)\)$/i);
|
|
1152
|
+
if (notInMatch) {
|
|
1153
|
+
const col = camelCase ? toCamelCase(notInMatch[1]) : notInMatch[1];
|
|
1154
|
+
const valuesStr = notInMatch[2];
|
|
1155
|
+
const values = valuesStr.match(/'[^']*'/g)?.join(', ') || valuesStr;
|
|
1156
|
+
return `w.col(table.${col}).notIn([${values}])`;
|
|
1157
|
+
}
|
|
1158
|
+
const inMatch = clause.match(/^([a-z_][a-z0-9_]*)\s+IN\s*\((.+)\)$/i);
|
|
1159
|
+
if (inMatch) {
|
|
1160
|
+
const col = camelCase ? toCamelCase(inMatch[1]) : inMatch[1];
|
|
1161
|
+
const valuesStr = inMatch[2];
|
|
1162
|
+
const values = valuesStr.match(/'[^']*'/g)?.join(', ') || valuesStr;
|
|
1163
|
+
return `w.col(table.${col}).in([${values}])`;
|
|
1164
|
+
}
|
|
1165
|
+
const comparisonMatch = clause.match(/^([a-z_][a-z0-9_]*)\s*(<=?|>=?|<>|!=|=)\s*(.+)$/i);
|
|
1166
|
+
if (comparisonMatch) {
|
|
1167
|
+
const col = camelCase ? toCamelCase(comparisonMatch[1]) : comparisonMatch[1];
|
|
1168
|
+
const op = comparisonMatch[2];
|
|
1169
|
+
const value = comparisonMatch[3].trim();
|
|
1170
|
+
let method;
|
|
1171
|
+
switch (op) {
|
|
1172
|
+
case '=':
|
|
1173
|
+
method = 'eq';
|
|
1174
|
+
break;
|
|
1175
|
+
case '<>':
|
|
1176
|
+
case '!=':
|
|
1177
|
+
method = 'neq';
|
|
1178
|
+
break;
|
|
1179
|
+
case '<':
|
|
1180
|
+
method = 'lt';
|
|
1181
|
+
break;
|
|
1182
|
+
case '<=':
|
|
1183
|
+
method = 'lte';
|
|
1184
|
+
break;
|
|
1185
|
+
case '>':
|
|
1186
|
+
method = 'gt';
|
|
1187
|
+
break;
|
|
1188
|
+
case '>=':
|
|
1189
|
+
method = 'gte';
|
|
1190
|
+
break;
|
|
1191
|
+
default: method = 'eq';
|
|
1192
|
+
}
|
|
1193
|
+
const parsedValue = parseWhereValue(value, camelCase);
|
|
1194
|
+
if (parsedValue === null) {
|
|
1195
|
+
return null;
|
|
1196
|
+
}
|
|
1197
|
+
return `w.col(table.${col}).${method}(${parsedValue})`;
|
|
1198
|
+
}
|
|
1199
|
+
const likeMatch = clause.match(/^([a-z_][a-z0-9_]*)\s+LIKE\s+('.+')$/i);
|
|
1200
|
+
if (likeMatch) {
|
|
1201
|
+
const col = camelCase ? toCamelCase(likeMatch[1]) : likeMatch[1];
|
|
1202
|
+
return `w.col(table.${col}).like(${likeMatch[2]})`;
|
|
1203
|
+
}
|
|
1204
|
+
const ilikeMatch = clause.match(/^([a-z_][a-z0-9_]*)\s+ILIKE\s+('.+')$/i);
|
|
1205
|
+
if (ilikeMatch) {
|
|
1206
|
+
const col = camelCase ? toCamelCase(ilikeMatch[1]) : ilikeMatch[1];
|
|
1207
|
+
return `w.col(table.${col}).ilike(${ilikeMatch[2]})`;
|
|
1208
|
+
}
|
|
1209
|
+
const betweenMatch = clause.match(/^([a-z_][a-z0-9_]*)\s+BETWEEN\s+(.+)\s+AND\s+(.+)$/i);
|
|
1210
|
+
if (betweenMatch) {
|
|
1211
|
+
const col = camelCase ? toCamelCase(betweenMatch[1]) : betweenMatch[1];
|
|
1212
|
+
const min = parseWhereValue(betweenMatch[2].trim(), camelCase);
|
|
1213
|
+
const max = parseWhereValue(betweenMatch[3].trim(), camelCase);
|
|
1214
|
+
if (min && max) {
|
|
1215
|
+
return `w.col(table.${col}).between(${min}, ${max})`;
|
|
1216
|
+
}
|
|
1217
|
+
}
|
|
1218
|
+
return null;
|
|
1219
|
+
}
|
|
1220
|
+
function splitByOperator(clause, operator) {
|
|
1221
|
+
const parts = [];
|
|
1222
|
+
let current = '';
|
|
1223
|
+
let parenDepth = 0;
|
|
1224
|
+
let i = 0;
|
|
1225
|
+
while (i < clause.length) {
|
|
1226
|
+
const char = clause[i];
|
|
1227
|
+
if (char === '(') {
|
|
1228
|
+
parenDepth++;
|
|
1229
|
+
current += char;
|
|
1230
|
+
i++;
|
|
1231
|
+
}
|
|
1232
|
+
else if (char === ')') {
|
|
1233
|
+
parenDepth--;
|
|
1234
|
+
current += char;
|
|
1235
|
+
i++;
|
|
1236
|
+
}
|
|
1237
|
+
else if (parenDepth === 0) {
|
|
1238
|
+
const remaining = clause.slice(i);
|
|
1239
|
+
const match = remaining.match(new RegExp(`^\\s+${operator}\\s+`, 'i'));
|
|
1240
|
+
if (match) {
|
|
1241
|
+
if (current.trim()) {
|
|
1242
|
+
parts.push(current.trim());
|
|
1243
|
+
}
|
|
1244
|
+
current = '';
|
|
1245
|
+
i += match[0].length;
|
|
1246
|
+
}
|
|
1247
|
+
else {
|
|
1248
|
+
current += char;
|
|
1249
|
+
i++;
|
|
1250
|
+
}
|
|
1251
|
+
}
|
|
1252
|
+
else {
|
|
1253
|
+
current += char;
|
|
1254
|
+
i++;
|
|
1255
|
+
}
|
|
1256
|
+
}
|
|
1257
|
+
if (current.trim()) {
|
|
1258
|
+
parts.push(current.trim());
|
|
1259
|
+
}
|
|
1260
|
+
return parts.length > 1 ? parts : null;
|
|
1261
|
+
}
|
|
1262
|
+
function parseCompoundCondition(clause, camelCase) {
|
|
1263
|
+
clause = clause.trim();
|
|
1264
|
+
while (clause.startsWith('(') && clause.endsWith(')')) {
|
|
1265
|
+
let depth = 0;
|
|
1266
|
+
let matched = true;
|
|
1267
|
+
for (let i = 0; i < clause.length - 1; i++) {
|
|
1268
|
+
if (clause[i] === '(')
|
|
1269
|
+
depth++;
|
|
1270
|
+
else if (clause[i] === ')')
|
|
1271
|
+
depth--;
|
|
1272
|
+
if (depth === 0 && i < clause.length - 1) {
|
|
1273
|
+
matched = false;
|
|
1274
|
+
break;
|
|
1275
|
+
}
|
|
1276
|
+
}
|
|
1277
|
+
if (matched) {
|
|
1278
|
+
clause = clause.slice(1, -1).trim();
|
|
1279
|
+
}
|
|
1280
|
+
else {
|
|
1281
|
+
break;
|
|
1282
|
+
}
|
|
1283
|
+
}
|
|
1284
|
+
const orParts = splitByOperator(clause, 'OR');
|
|
1285
|
+
if (orParts && orParts.length > 1) {
|
|
1286
|
+
const parsedParts = orParts.map(p => parseCompoundCondition(p, camelCase));
|
|
1287
|
+
if (parsedParts.every(p => p !== null)) {
|
|
1288
|
+
const chained = parsedParts.reduce((acc, part, i) => i === 0 ? part : `${acc}.or(${part})`);
|
|
1289
|
+
return chained;
|
|
1290
|
+
}
|
|
1291
|
+
return null;
|
|
1292
|
+
}
|
|
1293
|
+
const andParts = splitByOperator(clause, 'AND');
|
|
1294
|
+
if (andParts && andParts.length > 1) {
|
|
1295
|
+
const parsedParts = andParts.map(p => parseCompoundCondition(p, camelCase));
|
|
1296
|
+
if (parsedParts.every(p => p !== null)) {
|
|
1297
|
+
const chained = parsedParts.reduce((acc, part, i) => i === 0 ? part : `${acc}.and(${part})`);
|
|
1298
|
+
return chained;
|
|
1299
|
+
}
|
|
1300
|
+
return null;
|
|
1301
|
+
}
|
|
1302
|
+
return parseSingleCondition(clause, camelCase);
|
|
1303
|
+
}
|
|
1304
|
+
function parseWhereClause(whereClause, camelCase) {
|
|
1305
|
+
const result = parseCompoundCondition(whereClause, camelCase);
|
|
1306
|
+
if (result) {
|
|
1307
|
+
return `(w) => ${result}`;
|
|
1308
|
+
}
|
|
1309
|
+
throw new Error(`Unable to parse WHERE clause: ${whereClause}`);
|
|
1310
|
+
}
|
|
1311
|
+
function parseCheckExpression(expr, camelCase) {
|
|
1312
|
+
expr = expr.trim();
|
|
1313
|
+
while (expr.startsWith('(') && expr.endsWith(')')) {
|
|
1314
|
+
let depth = 0;
|
|
1315
|
+
let matched = true;
|
|
1316
|
+
for (let i = 0; i < expr.length - 1; i++) {
|
|
1317
|
+
if (expr[i] === '(')
|
|
1318
|
+
depth++;
|
|
1319
|
+
else if (expr[i] === ')')
|
|
1320
|
+
depth--;
|
|
1321
|
+
if (depth === 0 && i < expr.length - 1) {
|
|
1322
|
+
matched = false;
|
|
1323
|
+
break;
|
|
1324
|
+
}
|
|
1325
|
+
}
|
|
1326
|
+
if (matched) {
|
|
1327
|
+
expr = expr.slice(1, -1).trim();
|
|
1328
|
+
}
|
|
1329
|
+
else {
|
|
1330
|
+
break;
|
|
1331
|
+
}
|
|
1332
|
+
}
|
|
1333
|
+
const orParts = splitCheckByOperator(expr, 'OR');
|
|
1334
|
+
if (orParts && orParts.length > 1) {
|
|
1335
|
+
const parsedParts = orParts.map(p => parseCheckExpression(p, camelCase));
|
|
1336
|
+
if (parsedParts.every(p => p !== null)) {
|
|
1337
|
+
return parsedParts.reduce((acc, part, i) => i === 0 ? part : `${acc}.or(${part})`);
|
|
1338
|
+
}
|
|
1339
|
+
return null;
|
|
1340
|
+
}
|
|
1341
|
+
const andParts = splitCheckByOperator(expr, 'AND');
|
|
1342
|
+
if (andParts && andParts.length > 1) {
|
|
1343
|
+
const parsedParts = andParts.map(p => parseCheckExpression(p, camelCase));
|
|
1344
|
+
if (parsedParts.every(p => p !== null)) {
|
|
1345
|
+
return parsedParts.reduce((acc, part, i) => i === 0 ? part : `${acc}.and(${part})`);
|
|
1346
|
+
}
|
|
1347
|
+
return null;
|
|
1348
|
+
}
|
|
1349
|
+
const isNullMatch = expr.match(/^([a-z_][a-z0-9_]*)\s+IS\s+NULL$/i);
|
|
1350
|
+
if (isNullMatch) {
|
|
1351
|
+
const col = camelCase ? toCamelCase(isNullMatch[1]) : isNullMatch[1];
|
|
1352
|
+
return `table.${col}.isNull()`;
|
|
1353
|
+
}
|
|
1354
|
+
const isNotNullMatch = expr.match(/^([a-z_][a-z0-9_]*)\s+IS\s+NOT\s+NULL$/i);
|
|
1355
|
+
if (isNotNullMatch) {
|
|
1356
|
+
const col = camelCase ? toCamelCase(isNotNullMatch[1]) : isNotNullMatch[1];
|
|
1357
|
+
return `table.${col}.isNotNull()`;
|
|
1358
|
+
}
|
|
1359
|
+
const betweenMatch = expr.match(/^([a-z_][a-z0-9_]*)\s+BETWEEN\s+(.+)\s+AND\s+(.+)$/i);
|
|
1360
|
+
if (betweenMatch) {
|
|
1361
|
+
const col = camelCase ? toCamelCase(betweenMatch[1]) : betweenMatch[1];
|
|
1362
|
+
const min = parseCheckValue(betweenMatch[2].trim(), camelCase);
|
|
1363
|
+
const max = parseCheckValue(betweenMatch[3].trim(), camelCase);
|
|
1364
|
+
if (min && max) {
|
|
1365
|
+
return `table.${col}.between(${min}, ${max})`;
|
|
1366
|
+
}
|
|
1367
|
+
}
|
|
1368
|
+
const inMatch = expr.match(/^([a-z_][a-z0-9_]*)\s+IN\s*\(([^)]+)\)$/i);
|
|
1369
|
+
if (inMatch) {
|
|
1370
|
+
const col = camelCase ? toCamelCase(inMatch[1]) : inMatch[1];
|
|
1371
|
+
const values = inMatch[2].split(',').map(v => v.trim());
|
|
1372
|
+
return `table.${col}.in([${values.join(', ')}])`;
|
|
1373
|
+
}
|
|
1374
|
+
const notInMatch = expr.match(/^([a-z_][a-z0-9_]*)\s+NOT\s+IN\s*\(([^)]+)\)$/i);
|
|
1375
|
+
if (notInMatch) {
|
|
1376
|
+
const col = camelCase ? toCamelCase(notInMatch[1]) : notInMatch[1];
|
|
1377
|
+
const values = notInMatch[2].split(',').map(v => v.trim());
|
|
1378
|
+
return `table.${col}.notIn([${values.join(', ')}])`;
|
|
1379
|
+
}
|
|
1380
|
+
const regexMatch = expr.match(/^([a-z_][a-z0-9_]*)\s+(~\*|~)\s+'([^']+)'$/i);
|
|
1381
|
+
if (regexMatch) {
|
|
1382
|
+
const col = camelCase ? toCamelCase(regexMatch[1]) : regexMatch[1];
|
|
1383
|
+
const pattern = regexMatch[3].replace(/\\/g, '\\\\').replace(/'/g, "\\'");
|
|
1384
|
+
const method = regexMatch[2] === '~*' ? 'matchesInsensitive' : 'matches';
|
|
1385
|
+
return `table.${col}.${method}('${pattern}')`;
|
|
1386
|
+
}
|
|
1387
|
+
const lengthMatch = expr.match(/^LENGTH\(([a-z_][a-z0-9_]*)(?:::TEXT)?\)\s*(<=?|>=?|<>|!=|=)\s*(\d+)$/i);
|
|
1388
|
+
if (lengthMatch) {
|
|
1389
|
+
const col = camelCase ? toCamelCase(lengthMatch[1]) : lengthMatch[1];
|
|
1390
|
+
const op = lengthMatch[2];
|
|
1391
|
+
const value = lengthMatch[3];
|
|
1392
|
+
const method = op === '>=' ? 'gte' : op === '<=' ? 'lte' : op === '>' ? 'gt' : op === '<' ? 'lt' : op === '=' ? 'eq' : 'neq';
|
|
1393
|
+
return `table.${col}.asText().length().${method}(${value})`;
|
|
1394
|
+
}
|
|
1395
|
+
const absMatch = expr.match(/^ABS\(([a-z_][a-z0-9_]*)\)\s*(<=?|>=?|<>|!=|=)\s*(.+)$/i);
|
|
1396
|
+
if (absMatch) {
|
|
1397
|
+
const col = camelCase ? toCamelCase(absMatch[1]) : absMatch[1];
|
|
1398
|
+
const op = absMatch[2];
|
|
1399
|
+
const value = parseCheckValue(absMatch[3].trim(), camelCase);
|
|
1400
|
+
if (value) {
|
|
1401
|
+
const method = op === '>=' ? 'gte' : op === '<=' ? 'lte' : op === '>' ? 'gt' : op === '<' ? 'lt' : op === '=' ? 'eq' : 'neq';
|
|
1402
|
+
return `table.${col}.abs().${method}(${value})`;
|
|
1403
|
+
}
|
|
1404
|
+
}
|
|
1405
|
+
const arithmeticMatch = expr.match(/^([a-z_][a-z0-9_]*)\s*([+\-])\s*([a-z_][a-z0-9_]*)\s*(<=?|>=?|<>|!=|=)\s*(.+)$/i);
|
|
1406
|
+
if (arithmeticMatch) {
|
|
1407
|
+
const col1 = camelCase ? toCamelCase(arithmeticMatch[1]) : arithmeticMatch[1];
|
|
1408
|
+
const op = arithmeticMatch[2];
|
|
1409
|
+
const col2 = camelCase ? toCamelCase(arithmeticMatch[3]) : arithmeticMatch[3];
|
|
1410
|
+
const cmpOp = arithmeticMatch[4];
|
|
1411
|
+
const value = parseCheckValue(arithmeticMatch[5].trim(), camelCase);
|
|
1412
|
+
if (value) {
|
|
1413
|
+
const arithMethod = op === '+' ? 'plus' : 'minus';
|
|
1414
|
+
const cmpMethod = cmpOp === '>=' ? 'gte' : cmpOp === '<=' ? 'lte' : cmpOp === '>' ? 'gt' : cmpOp === '<' ? 'lt' : cmpOp === '=' ? 'eq' : 'neq';
|
|
1415
|
+
return `table.${col1}.${arithMethod}(table.${col2}).${cmpMethod}(${value})`;
|
|
1416
|
+
}
|
|
1417
|
+
}
|
|
1418
|
+
const comparisonMatch = expr.match(/^([a-z_][a-z0-9_]*)\s*(<=?|>=?|<>|!=|=)\s*(.+)$/i);
|
|
1419
|
+
if (comparisonMatch) {
|
|
1420
|
+
const col = camelCase ? toCamelCase(comparisonMatch[1]) : comparisonMatch[1];
|
|
1421
|
+
const op = comparisonMatch[2];
|
|
1422
|
+
const value = parseCheckValue(comparisonMatch[3].trim(), camelCase);
|
|
1423
|
+
if (value) {
|
|
1424
|
+
const method = op === '>=' ? 'gte' : op === '<=' ? 'lte' : op === '>' ? 'gt' : op === '<' ? 'lt' : op === '=' ? 'eq' : 'neq';
|
|
1425
|
+
return `table.${col}.${method}(${value})`;
|
|
1426
|
+
}
|
|
1427
|
+
}
|
|
1428
|
+
return null;
|
|
1429
|
+
}
|
|
1430
|
+
function parseCheckValue(value, camelCase) {
|
|
1431
|
+
value = value.trim();
|
|
1432
|
+
if (/^-?\d+(\.\d+)?$/.test(value)) {
|
|
1433
|
+
return value;
|
|
1434
|
+
}
|
|
1435
|
+
if (/^TRUE$/i.test(value))
|
|
1436
|
+
return 'true';
|
|
1437
|
+
if (/^FALSE$/i.test(value))
|
|
1438
|
+
return 'false';
|
|
1439
|
+
if (/^'.*'$/.test(value)) {
|
|
1440
|
+
return value;
|
|
1441
|
+
}
|
|
1442
|
+
if (/^NULL$/i.test(value)) {
|
|
1443
|
+
return 'null';
|
|
1444
|
+
}
|
|
1445
|
+
if (/^[a-z_][a-z0-9_]*$/i.test(value)) {
|
|
1446
|
+
const col = camelCase ? toCamelCase(value) : value;
|
|
1447
|
+
return `table.${col}`;
|
|
1448
|
+
}
|
|
1449
|
+
return null;
|
|
1450
|
+
}
|
|
1451
|
+
function splitCheckByOperator(expr, operator) {
|
|
1452
|
+
if (operator === 'AND' && /\bBETWEEN\b.*\bAND\b/i.test(expr)) {
|
|
1453
|
+
const betweenMatch = expr.match(/^([a-z_][a-z0-9_]*)\s+BETWEEN\s+\S+\s+AND\s+\S+$/i);
|
|
1454
|
+
if (betweenMatch) {
|
|
1455
|
+
return null;
|
|
1456
|
+
}
|
|
1457
|
+
}
|
|
1458
|
+
const parts = [];
|
|
1459
|
+
let current = '';
|
|
1460
|
+
let parenDepth = 0;
|
|
1461
|
+
let i = 0;
|
|
1462
|
+
while (i < expr.length) {
|
|
1463
|
+
const char = expr[i];
|
|
1464
|
+
if (char === '(') {
|
|
1465
|
+
parenDepth++;
|
|
1466
|
+
current += char;
|
|
1467
|
+
i++;
|
|
1468
|
+
}
|
|
1469
|
+
else if (char === ')') {
|
|
1470
|
+
parenDepth--;
|
|
1471
|
+
current += char;
|
|
1472
|
+
i++;
|
|
1473
|
+
}
|
|
1474
|
+
else if (parenDepth === 0) {
|
|
1475
|
+
const remaining = expr.slice(i);
|
|
1476
|
+
const match = remaining.match(new RegExp(`^\\s+${operator}\\s+`, 'i'));
|
|
1477
|
+
if (match) {
|
|
1478
|
+
if (operator === 'AND' && /\bBETWEEN\s+\S+$/i.test(current.trim())) {
|
|
1479
|
+
current += match[0];
|
|
1480
|
+
i += match[0].length;
|
|
1481
|
+
continue;
|
|
1482
|
+
}
|
|
1483
|
+
if (current.trim()) {
|
|
1484
|
+
parts.push(current.trim());
|
|
1485
|
+
}
|
|
1486
|
+
current = '';
|
|
1487
|
+
i += match[0].length;
|
|
1488
|
+
}
|
|
1489
|
+
else {
|
|
1490
|
+
current += char;
|
|
1491
|
+
i++;
|
|
1492
|
+
}
|
|
1493
|
+
}
|
|
1494
|
+
else {
|
|
1495
|
+
current += char;
|
|
1496
|
+
i++;
|
|
1497
|
+
}
|
|
1498
|
+
}
|
|
1499
|
+
if (current.trim()) {
|
|
1500
|
+
parts.push(current.trim());
|
|
1501
|
+
}
|
|
1502
|
+
return parts.length > 1 ? parts : null;
|
|
1503
|
+
}
|
|
1504
|
+
function generateCheckConstraints(constraints, camelCase) {
|
|
1505
|
+
const checkConstraints = constraints.filter(c => {
|
|
1506
|
+
if (c.type !== 'CHECK')
|
|
1507
|
+
return false;
|
|
1508
|
+
if (/::text\s*=\s*ANY/i.test(c.definition))
|
|
1509
|
+
return false;
|
|
1510
|
+
return true;
|
|
1511
|
+
});
|
|
1512
|
+
if (checkConstraints.length === 0)
|
|
1513
|
+
return null;
|
|
1514
|
+
const lines = [];
|
|
1515
|
+
for (const check of checkConstraints) {
|
|
1516
|
+
let expr = check.definition.trim();
|
|
1517
|
+
const checkMatch = expr.match(/CHECK\s*\(/i);
|
|
1518
|
+
if (checkMatch && checkMatch.index !== undefined) {
|
|
1519
|
+
const startIdx = checkMatch.index + checkMatch[0].length;
|
|
1520
|
+
let depth = 1;
|
|
1521
|
+
let endIdx = startIdx;
|
|
1522
|
+
for (let i = startIdx; i < expr.length && depth > 0; i++) {
|
|
1523
|
+
if (expr[i] === '(')
|
|
1524
|
+
depth++;
|
|
1525
|
+
else if (expr[i] === ')')
|
|
1526
|
+
depth--;
|
|
1527
|
+
if (depth === 0)
|
|
1528
|
+
endIdx = i;
|
|
1529
|
+
}
|
|
1530
|
+
if (endIdx > startIdx) {
|
|
1531
|
+
expr = expr.substring(startIdx, endIdx).trim();
|
|
1532
|
+
}
|
|
1533
|
+
}
|
|
1534
|
+
else if (expr.startsWith('(') && expr.endsWith(')')) {
|
|
1535
|
+
expr = expr.slice(1, -1).trim();
|
|
1536
|
+
}
|
|
1537
|
+
const parsed = parseCheckExpression(expr, camelCase);
|
|
1538
|
+
if (parsed) {
|
|
1539
|
+
lines.push(` check.constraint('${check.name}', ${parsed})`);
|
|
1540
|
+
}
|
|
1541
|
+
}
|
|
1542
|
+
if (lines.length === 0)
|
|
1543
|
+
return null;
|
|
1544
|
+
return `(table, check) => [\n${lines.join(',\n')},\n ]`;
|
|
1545
|
+
}
|
|
1546
|
+
function generateDefineTable(table, camelCase = true, childPartitions, enumNames, domainNames, compositeNames, domainMap) {
|
|
1547
|
+
const tableName = toCamelCase(table.name);
|
|
1548
|
+
const seenColumns = new Set();
|
|
1549
|
+
const checkConstraints = (table.constraints || []).filter(c => c.type === 'CHECK');
|
|
1550
|
+
const columnChecks = new Map();
|
|
1551
|
+
for (const check of checkConstraints) {
|
|
1552
|
+
const enumMatch = check.definition.match(/\((\w+)\)::text\s*=\s*ANY\s*\(\s*(?:ARRAY\[)?([^\]]+)\]/i);
|
|
1553
|
+
if (enumMatch) {
|
|
1554
|
+
const colName = enumMatch[1];
|
|
1555
|
+
const valuesStr = enumMatch[2];
|
|
1556
|
+
const values = valuesStr
|
|
1557
|
+
.match(/'([^']+)'/g)
|
|
1558
|
+
?.map(v => v.replace(/'/g, '')) || [];
|
|
1559
|
+
if (values.length > 0) {
|
|
1560
|
+
columnChecks.set(colName.toLowerCase(), values);
|
|
1561
|
+
}
|
|
1562
|
+
}
|
|
1563
|
+
}
|
|
1564
|
+
const columns = table.columns
|
|
1565
|
+
.map(col => generateColumnDef(col, seenColumns, camelCase, columnChecks.get(col.name.toLowerCase()), enumNames, domainNames, compositeNames, domainMap))
|
|
1566
|
+
.filter(Boolean);
|
|
1567
|
+
const columnNames = Array.from(seenColumns);
|
|
1568
|
+
const indexesFn = table.indexes ? generateIndexes(table.indexes, columnNames, camelCase) : null;
|
|
1569
|
+
const checkConstraintsFn = table.constraints ? generateCheckConstraints(table.constraints, camelCase) : null;
|
|
1570
|
+
const hasPartition = table.isPartitioned && table.partitionType && table.partitionKey?.length;
|
|
1571
|
+
const hasChildPartitions = childPartitions && childPartitions.length > 0;
|
|
1572
|
+
if (hasPartition || indexesFn || hasChildPartitions || checkConstraintsFn) {
|
|
1573
|
+
const parts = [];
|
|
1574
|
+
if (hasPartition) {
|
|
1575
|
+
let rawPartitionKey = table.partitionKey || [];
|
|
1576
|
+
if (typeof rawPartitionKey === 'string') {
|
|
1577
|
+
rawPartitionKey = rawPartitionKey
|
|
1578
|
+
.replace(/^\{|\}$/g, '')
|
|
1579
|
+
.split(',')
|
|
1580
|
+
.map(k => k.trim())
|
|
1581
|
+
.filter(Boolean);
|
|
1582
|
+
}
|
|
1583
|
+
if (!Array.isArray(rawPartitionKey)) {
|
|
1584
|
+
rawPartitionKey = [String(rawPartitionKey)];
|
|
1585
|
+
}
|
|
1586
|
+
const cleanedPartitionKey = rawPartitionKey.map((k) => {
|
|
1587
|
+
return k.replace(/^\{|\}$/g, '').trim();
|
|
1588
|
+
}).filter(Boolean);
|
|
1589
|
+
const partitionCol = camelCase ? toCamelCase(cleanedPartitionKey[0]) : cleanedPartitionKey[0];
|
|
1590
|
+
const partitionTypeLC = (table.partitionType || 'LIST').toLowerCase();
|
|
1591
|
+
if (partitionTypeLC === 'hash') {
|
|
1592
|
+
parts.push(` partitionBy: (table, p) => p.hash(table.${partitionCol}, 4)`);
|
|
1593
|
+
}
|
|
1594
|
+
else {
|
|
1595
|
+
parts.push(` partitionBy: (table, p) => p.${partitionTypeLC}(table.${partitionCol})`);
|
|
1596
|
+
}
|
|
1597
|
+
}
|
|
1598
|
+
if (hasChildPartitions && childPartitions) {
|
|
1599
|
+
const partitionLines = childPartitions.map(cp => {
|
|
1600
|
+
const bound = cp.partitionBound || '';
|
|
1601
|
+
if (bound.includes('DEFAULT')) {
|
|
1602
|
+
return ` partition('${cp.name}').default()`;
|
|
1603
|
+
}
|
|
1604
|
+
const listMatch = bound.match(/IN\s*\(([^)]+)\)/i);
|
|
1605
|
+
if (listMatch) {
|
|
1606
|
+
const valuesStr = listMatch[1];
|
|
1607
|
+
const values = valuesStr.match(/'([^']+)'/g)?.map((v) => v.replace(/'/g, '')) || [];
|
|
1608
|
+
return ` partition('${cp.name}').in([${values.map((v) => `'${v}'`).join(', ')}])`;
|
|
1609
|
+
}
|
|
1610
|
+
const rangeMatch = bound.match(/FROM\s*\(([^)]+)\)\s*TO\s*\(([^)]+)\)/i);
|
|
1611
|
+
if (rangeMatch) {
|
|
1612
|
+
const from = rangeMatch[1].replace(/'/g, '').trim();
|
|
1613
|
+
const to = rangeMatch[2].replace(/'/g, '').trim();
|
|
1614
|
+
return ` partition('${cp.name}').from('${from}').to('${to}')`;
|
|
1615
|
+
}
|
|
1616
|
+
const hashMatch = bound.match(/MODULUS\s+(\d+),\s*REMAINDER\s+(\d+)/i);
|
|
1617
|
+
if (hashMatch) {
|
|
1618
|
+
const remainder = parseInt(hashMatch[2], 10);
|
|
1619
|
+
return ` partition('${cp.name}').remainder(${remainder})`;
|
|
1620
|
+
}
|
|
1621
|
+
return ` // Unknown partition: ${cp.name} - ${bound}`;
|
|
1622
|
+
});
|
|
1623
|
+
parts.push(` partitions: (partition) => [\n${partitionLines.join(',\n')},\n ]`);
|
|
1624
|
+
}
|
|
1625
|
+
if (checkConstraintsFn) {
|
|
1626
|
+
parts.push(` checkConstraints: ${checkConstraintsFn.trim()}`);
|
|
1627
|
+
}
|
|
1628
|
+
if (indexesFn) {
|
|
1629
|
+
parts.push(` indexes: ${indexesFn.trim()}`);
|
|
1630
|
+
}
|
|
1631
|
+
const jsDoc = table.comment ? `/**\n * ${table.comment.replace(/\*\//g, '* /')}\n */\n` : '';
|
|
1632
|
+
return `${jsDoc}export const ${tableName} = defineTable('${table.name}', {
|
|
1633
|
+
${columns.join(',\n')},
|
|
1634
|
+
}, {
|
|
1635
|
+
${parts.join(',\n')},
|
|
1636
|
+
})`;
|
|
1637
|
+
}
|
|
1638
|
+
const jsDoc = table.comment ? `/**\n * ${table.comment.replace(/\*\//g, '* /')}\n */\n` : '';
|
|
1639
|
+
return `${jsDoc}export const ${tableName} = defineTable('${table.name}', {
|
|
1640
|
+
${columns.join(',\n')},
|
|
1641
|
+
})`;
|
|
1642
|
+
}
|
|
1643
|
+
function generateTypeScript(schema, options = {}) {
|
|
1644
|
+
const { includeDefineTables = true, includeSchema = true, includeFunctions = true, includeTriggers = true, camelCase = true, importPath = 'relq/schema-builder', } = options;
|
|
1645
|
+
const partitionTableNames = new Set(schema.partitions.map((p) => p.name.toLowerCase()));
|
|
1646
|
+
const tables = schema.tables.filter(t => !EXCLUDED_TABLES.includes(t.name.toLowerCase()) &&
|
|
1647
|
+
!partitionTableNames.has(t.name.toLowerCase()));
|
|
1648
|
+
const parts = [
|
|
1649
|
+
'/**',
|
|
1650
|
+
' * Auto-generated by Relq CLI',
|
|
1651
|
+
` * Generated at: ${new Date().toISOString()}`,
|
|
1652
|
+
' * DO NOT EDIT - changes will be overwritten',
|
|
1653
|
+
' */',
|
|
1654
|
+
'',
|
|
1655
|
+
];
|
|
1656
|
+
const imports = new Set(['defineTable']);
|
|
1657
|
+
for (const table of tables) {
|
|
1658
|
+
for (const col of table.columns) {
|
|
1659
|
+
const rawType = col.dataType.toLowerCase().replace(/^_/, '');
|
|
1660
|
+
const pgType = rawType.replace(/\([^)]*\)$/, '').trim();
|
|
1661
|
+
if (['int4', 'integer'].includes(pgType))
|
|
1662
|
+
imports.add('integer');
|
|
1663
|
+
else if (['int2', 'smallint'].includes(pgType))
|
|
1664
|
+
imports.add('smallint');
|
|
1665
|
+
else if (['int8', 'bigint'].includes(pgType))
|
|
1666
|
+
imports.add('bigint');
|
|
1667
|
+
else if (['serial', 'serial4'].includes(pgType))
|
|
1668
|
+
imports.add('serial');
|
|
1669
|
+
else if (['serial8', 'bigserial'].includes(pgType))
|
|
1670
|
+
imports.add('bigserial');
|
|
1671
|
+
else if (['float4', 'real'].includes(pgType))
|
|
1672
|
+
imports.add('real');
|
|
1673
|
+
else if (['float8', 'double precision'].includes(pgType))
|
|
1674
|
+
imports.add('doublePrecision');
|
|
1675
|
+
else if (pgType === 'numeric' || pgType === 'decimal')
|
|
1676
|
+
imports.add('numeric');
|
|
1677
|
+
else if (pgType === 'text')
|
|
1678
|
+
imports.add('text');
|
|
1679
|
+
else if (pgType === 'varchar' || pgType === 'character varying')
|
|
1680
|
+
imports.add('varchar');
|
|
1681
|
+
else if (pgType === 'char' || pgType === 'character' || pgType === 'bpchar')
|
|
1682
|
+
imports.add('char');
|
|
1683
|
+
else if (pgType === 'boolean' || pgType === 'bool')
|
|
1684
|
+
imports.add('boolean');
|
|
1685
|
+
else if (pgType === 'uuid')
|
|
1686
|
+
imports.add('uuid');
|
|
1687
|
+
else if (pgType === 'jsonb')
|
|
1688
|
+
imports.add('jsonb');
|
|
1689
|
+
else if (pgType === 'json')
|
|
1690
|
+
imports.add('json');
|
|
1691
|
+
else if (pgType === 'timestamp' || pgType === 'timestamptz')
|
|
1692
|
+
imports.add('timestamp');
|
|
1693
|
+
else if (pgType === 'date')
|
|
1694
|
+
imports.add('date');
|
|
1695
|
+
else if (pgType === 'time' || pgType === 'timetz')
|
|
1696
|
+
imports.add('time');
|
|
1697
|
+
else if (pgType === 'interval')
|
|
1698
|
+
imports.add('interval');
|
|
1699
|
+
else if (pgType === 'bytea')
|
|
1700
|
+
imports.add('bytea');
|
|
1701
|
+
else if (pgType === 'inet')
|
|
1702
|
+
imports.add('inet');
|
|
1703
|
+
else if (pgType === 'tsvector')
|
|
1704
|
+
imports.add('tsvector');
|
|
1705
|
+
else if (pgType === 'tsquery')
|
|
1706
|
+
imports.add('tsquery');
|
|
1707
|
+
else if (pgType === 'vector')
|
|
1708
|
+
imports.add('vector');
|
|
1709
|
+
else if (pgType === 'citext')
|
|
1710
|
+
imports.add('citext');
|
|
1711
|
+
else if (pgType === 'hstore')
|
|
1712
|
+
imports.add('hstore');
|
|
1713
|
+
else if (pgType === 'ltree')
|
|
1714
|
+
imports.add('ltree');
|
|
1715
|
+
else if (pgType === 'lquery')
|
|
1716
|
+
imports.add('lquery');
|
|
1717
|
+
else if (pgType === 'ltxtquery')
|
|
1718
|
+
imports.add('ltxtquery');
|
|
1719
|
+
else if (pgType === 'cube')
|
|
1720
|
+
imports.add('cube');
|
|
1721
|
+
else
|
|
1722
|
+
imports.add('text');
|
|
1723
|
+
if (col.defaultValue) {
|
|
1724
|
+
const d = col.defaultValue.toLowerCase();
|
|
1725
|
+
if (d.includes('gen_random_uuid') || d.includes('uuid_generate')) {
|
|
1726
|
+
imports.add('genRandomUuid');
|
|
1727
|
+
}
|
|
1728
|
+
if (d.includes('now()') || d.includes('current_timestamp'))
|
|
1729
|
+
imports.add('now');
|
|
1730
|
+
if (d.includes('current_date'))
|
|
1731
|
+
imports.add('currentDate');
|
|
1732
|
+
const isArrayType = col.dataType.endsWith('[]') || col.dataType.startsWith('_');
|
|
1733
|
+
if (d.includes("'{}'")) {
|
|
1734
|
+
if (isArrayType) {
|
|
1735
|
+
imports.add('emptyArray');
|
|
1736
|
+
}
|
|
1737
|
+
else {
|
|
1738
|
+
imports.add('emptyObject');
|
|
1739
|
+
}
|
|
1740
|
+
}
|
|
1741
|
+
if (d.includes("'[]'") || d.includes('array[]'))
|
|
1742
|
+
imports.add('emptyArray');
|
|
1743
|
+
}
|
|
1744
|
+
}
|
|
1745
|
+
}
|
|
1746
|
+
const userFunctions = schema.functions?.filter((f) => !f.name.startsWith('pg_') &&
|
|
1747
|
+
!EXCLUDED_FUNCTIONS.some(ex => f.name.startsWith(ex) || f.name === ex)) || [];
|
|
1748
|
+
if (includeFunctions && userFunctions.length > 0) {
|
|
1749
|
+
imports.add('pgFunction');
|
|
1750
|
+
}
|
|
1751
|
+
if (includeTriggers && schema.triggers && schema.triggers.length > 0) {
|
|
1752
|
+
imports.add('pgTrigger');
|
|
1753
|
+
}
|
|
1754
|
+
if (schema.sequences && schema.sequences.length > 0) {
|
|
1755
|
+
imports.add('pgSequence');
|
|
1756
|
+
}
|
|
1757
|
+
if (schema.enums && schema.enums.length > 0) {
|
|
1758
|
+
imports.add('pgEnum');
|
|
1759
|
+
}
|
|
1760
|
+
if (schema.domains && schema.domains.length > 0) {
|
|
1761
|
+
imports.add('pgDomain');
|
|
1762
|
+
for (const domainDef of schema.domains) {
|
|
1763
|
+
const rawType = domainDef.baseType.toLowerCase().replace(/^_/, '');
|
|
1764
|
+
const pgType = rawType.replace(/\([^)]*\)$/, '').trim();
|
|
1765
|
+
if (['int4', 'integer'].includes(pgType))
|
|
1766
|
+
imports.add('integer');
|
|
1767
|
+
else if (['int2', 'smallint'].includes(pgType))
|
|
1768
|
+
imports.add('smallint');
|
|
1769
|
+
else if (['int8', 'bigint'].includes(pgType))
|
|
1770
|
+
imports.add('bigint');
|
|
1771
|
+
else if (['float4', 'real'].includes(pgType))
|
|
1772
|
+
imports.add('real');
|
|
1773
|
+
else if (['float8', 'double precision'].includes(pgType))
|
|
1774
|
+
imports.add('doublePrecision');
|
|
1775
|
+
else if (pgType === 'numeric' || pgType === 'decimal')
|
|
1776
|
+
imports.add('numeric');
|
|
1777
|
+
else if (pgType === 'text')
|
|
1778
|
+
imports.add('text');
|
|
1779
|
+
else if (pgType === 'varchar' || pgType === 'character varying')
|
|
1780
|
+
imports.add('varchar');
|
|
1781
|
+
else if (pgType === 'char' || pgType === 'character' || pgType === 'bpchar')
|
|
1782
|
+
imports.add('char');
|
|
1783
|
+
else if (pgType === 'boolean' || pgType === 'bool')
|
|
1784
|
+
imports.add('boolean');
|
|
1785
|
+
else if (pgType === 'uuid')
|
|
1786
|
+
imports.add('uuid');
|
|
1787
|
+
else if (pgType === 'inet')
|
|
1788
|
+
imports.add('inet');
|
|
1789
|
+
else if (pgType === 'citext')
|
|
1790
|
+
imports.add('citext');
|
|
1791
|
+
}
|
|
1792
|
+
}
|
|
1793
|
+
if (schema.compositeTypes && schema.compositeTypes.length > 0) {
|
|
1794
|
+
imports.add('pgComposite');
|
|
1795
|
+
for (const composite of schema.compositeTypes) {
|
|
1796
|
+
for (const attr of composite.attributes || []) {
|
|
1797
|
+
const rawType = attr.type.toLowerCase().replace(/^_/, '');
|
|
1798
|
+
const pgType = rawType.replace(/\([^)]*\)$/, '').trim();
|
|
1799
|
+
if (['int4', 'integer'].includes(pgType))
|
|
1800
|
+
imports.add('integer');
|
|
1801
|
+
else if (['int2', 'smallint'].includes(pgType))
|
|
1802
|
+
imports.add('smallint');
|
|
1803
|
+
else if (['int8', 'bigint'].includes(pgType))
|
|
1804
|
+
imports.add('bigint');
|
|
1805
|
+
else if (['float4', 'real'].includes(pgType))
|
|
1806
|
+
imports.add('real');
|
|
1807
|
+
else if (['float8', 'double precision'].includes(pgType))
|
|
1808
|
+
imports.add('doublePrecision');
|
|
1809
|
+
else if (pgType === 'numeric' || pgType === 'decimal')
|
|
1810
|
+
imports.add('numeric');
|
|
1811
|
+
else if (pgType === 'text')
|
|
1812
|
+
imports.add('text');
|
|
1813
|
+
else if (pgType === 'varchar' || pgType === 'character varying')
|
|
1814
|
+
imports.add('varchar');
|
|
1815
|
+
else if (pgType === 'char' || pgType === 'character' || pgType === 'bpchar')
|
|
1816
|
+
imports.add('char');
|
|
1817
|
+
else if (pgType === 'boolean' || pgType === 'bool')
|
|
1818
|
+
imports.add('boolean');
|
|
1819
|
+
else if (pgType === 'uuid')
|
|
1820
|
+
imports.add('uuid');
|
|
1821
|
+
else if (pgType === 'jsonb')
|
|
1822
|
+
imports.add('jsonb');
|
|
1823
|
+
else if (pgType === 'json')
|
|
1824
|
+
imports.add('json');
|
|
1825
|
+
else if (pgType === 'timestamp' || pgType === 'timestamptz')
|
|
1826
|
+
imports.add('timestamp');
|
|
1827
|
+
else if (pgType === 'date')
|
|
1828
|
+
imports.add('date');
|
|
1829
|
+
else if (pgType === 'time' || pgType === 'timetz')
|
|
1830
|
+
imports.add('time');
|
|
1831
|
+
else if (pgType === 'inet')
|
|
1832
|
+
imports.add('inet');
|
|
1833
|
+
}
|
|
1834
|
+
}
|
|
1835
|
+
}
|
|
1836
|
+
if (schema.extensions && schema.extensions.length > 0) {
|
|
1837
|
+
imports.add('pgExtensions');
|
|
1838
|
+
}
|
|
1839
|
+
parts.push(`import {`);
|
|
1840
|
+
parts.push(` ${Array.from(imports).sort().join(',\n ')},`);
|
|
1841
|
+
parts.push(`} from '${importPath}';`);
|
|
1842
|
+
parts.push('');
|
|
1843
|
+
if (schema.enums && schema.enums.length > 0) {
|
|
1844
|
+
parts.push('// ============================================');
|
|
1845
|
+
parts.push('// Enum Definitions');
|
|
1846
|
+
parts.push('// ============================================');
|
|
1847
|
+
parts.push('');
|
|
1848
|
+
for (const enumDef of schema.enums) {
|
|
1849
|
+
const enumName = toCamelCase(enumDef.name) + 'Enum';
|
|
1850
|
+
const values = enumDef.values.map((v) => `'${v}'`).join(', ');
|
|
1851
|
+
parts.push(`export const ${enumName} = pgEnum('${enumDef.name}', [${values}]);`);
|
|
1852
|
+
}
|
|
1853
|
+
parts.push('');
|
|
1854
|
+
}
|
|
1855
|
+
if (schema.domains && schema.domains.length > 0) {
|
|
1856
|
+
parts.push('// ============================================');
|
|
1857
|
+
parts.push('// Domain Type Definitions');
|
|
1858
|
+
parts.push('// ============================================');
|
|
1859
|
+
parts.push('');
|
|
1860
|
+
for (const domainDef of schema.domains) {
|
|
1861
|
+
const domainName = toCamelCase(domainDef.name) + 'Domain';
|
|
1862
|
+
const columnBuilderCall = generateColumnBuilderFromType(domainDef.baseType);
|
|
1863
|
+
if (domainDef.check) {
|
|
1864
|
+
const checkExpr = convertSqlCheckToTypedExpr(domainDef.check);
|
|
1865
|
+
parts.push(`export const ${domainName} = pgDomain('${domainDef.name}',`);
|
|
1866
|
+
parts.push(` ${columnBuilderCall},`);
|
|
1867
|
+
parts.push(` (value) => [${checkExpr}]`);
|
|
1868
|
+
parts.push(`);`);
|
|
1869
|
+
}
|
|
1870
|
+
else {
|
|
1871
|
+
parts.push(`export const ${domainName} = pgDomain('${domainDef.name}', ${columnBuilderCall});`);
|
|
1872
|
+
}
|
|
1873
|
+
}
|
|
1874
|
+
parts.push('');
|
|
1875
|
+
}
|
|
1876
|
+
if (schema.compositeTypes && schema.compositeTypes.length > 0) {
|
|
1877
|
+
parts.push('// ============================================');
|
|
1878
|
+
parts.push('// Composite Type Definitions');
|
|
1879
|
+
parts.push('// ============================================');
|
|
1880
|
+
parts.push('');
|
|
1881
|
+
for (const compDef of schema.compositeTypes) {
|
|
1882
|
+
const compName = toCamelCase(compDef.name) + 'Composite';
|
|
1883
|
+
const fields = (compDef.attributes || [])
|
|
1884
|
+
.map((attr) => {
|
|
1885
|
+
const fieldName = toCamelCase(attr.name);
|
|
1886
|
+
const fieldType = getColumnType({ name: attr.name, dataType: attr.type });
|
|
1887
|
+
return ` ${fieldName}: ${fieldType}`;
|
|
1888
|
+
})
|
|
1889
|
+
.join(',\n');
|
|
1890
|
+
if (fields) {
|
|
1891
|
+
parts.push(`export const ${compName} = pgComposite('${compDef.name}', {`);
|
|
1892
|
+
parts.push(fields);
|
|
1893
|
+
parts.push('});');
|
|
1894
|
+
}
|
|
1895
|
+
else {
|
|
1896
|
+
parts.push(`export const ${compName} = pgComposite('${compDef.name}', {});`);
|
|
1897
|
+
}
|
|
1898
|
+
}
|
|
1899
|
+
parts.push('');
|
|
1900
|
+
}
|
|
1901
|
+
if (includeDefineTables) {
|
|
1902
|
+
parts.push('// ============================================');
|
|
1903
|
+
parts.push('// Table Definitions');
|
|
1904
|
+
parts.push('// ============================================');
|
|
1905
|
+
parts.push('');
|
|
1906
|
+
const enumNames = new Set((schema.enums || []).map((e) => e.name.toLowerCase()));
|
|
1907
|
+
const domainNames = new Set((schema.domains || []).map((d) => d.name.toLowerCase()));
|
|
1908
|
+
const compositeNames = new Set((schema.compositeTypes || []).map((c) => c.name.toLowerCase()));
|
|
1909
|
+
const domainMap = new Map((schema.domains || []).map((d) => [d.name.toLowerCase(), d.baseType]));
|
|
1910
|
+
for (const table of tables) {
|
|
1911
|
+
const childPartitions = schema.partitions.filter((p) => p.parentTable === table.name);
|
|
1912
|
+
parts.push(generateDefineTable(table, camelCase, childPartitions, enumNames, domainNames, compositeNames, domainMap));
|
|
1913
|
+
parts.push('');
|
|
1914
|
+
}
|
|
1915
|
+
}
|
|
1916
|
+
parts.push('// ============================================');
|
|
1917
|
+
parts.push('// Type Exports');
|
|
1918
|
+
parts.push('// ============================================');
|
|
1919
|
+
parts.push('');
|
|
1920
|
+
for (const table of tables) {
|
|
1921
|
+
const tableName = toCamelCase(table.name);
|
|
1922
|
+
const typeName = toPascalCase(table.name);
|
|
1923
|
+
parts.push(`export type ${typeName} = typeof ${tableName}.$inferSelect;`);
|
|
1924
|
+
parts.push(`export type New${typeName} = typeof ${tableName}.$inferInsert;`);
|
|
1925
|
+
}
|
|
1926
|
+
parts.push('');
|
|
1927
|
+
if (schema.sequences && schema.sequences.length > 0) {
|
|
1928
|
+
parts.push('// ============================================');
|
|
1929
|
+
parts.push('// Database Sequences');
|
|
1930
|
+
parts.push('// ============================================');
|
|
1931
|
+
parts.push('');
|
|
1932
|
+
for (const seq of schema.sequences) {
|
|
1933
|
+
const seqName = toCamelCase(seq.name);
|
|
1934
|
+
const opts = [];
|
|
1935
|
+
if (seq.dataType) {
|
|
1936
|
+
opts.push(` as: '${seq.dataType}'`);
|
|
1937
|
+
}
|
|
1938
|
+
if (seq.start !== undefined) {
|
|
1939
|
+
opts.push(` start: ${seq.start}`);
|
|
1940
|
+
}
|
|
1941
|
+
if (seq.increment !== undefined) {
|
|
1942
|
+
opts.push(` increment: ${seq.increment}`);
|
|
1943
|
+
}
|
|
1944
|
+
if (seq.minValue !== undefined) {
|
|
1945
|
+
opts.push(` minValue: ${seq.minValue === null ? 'null' : seq.minValue}`);
|
|
1946
|
+
}
|
|
1947
|
+
if (seq.maxValue !== undefined) {
|
|
1948
|
+
opts.push(` maxValue: ${seq.maxValue === null ? 'null' : seq.maxValue}`);
|
|
1949
|
+
}
|
|
1950
|
+
if (seq.cache !== undefined) {
|
|
1951
|
+
opts.push(` cache: ${seq.cache}`);
|
|
1952
|
+
}
|
|
1953
|
+
if (seq.cycle !== undefined) {
|
|
1954
|
+
opts.push(` cycle: ${seq.cycle}`);
|
|
1955
|
+
}
|
|
1956
|
+
if (seq.ownedBy) {
|
|
1957
|
+
opts.push(` ownedBy: '${seq.ownedBy}'`);
|
|
1958
|
+
}
|
|
1959
|
+
if (opts.length > 0) {
|
|
1960
|
+
parts.push(`export const ${seqName} = pgSequence('${seq.name}', {`);
|
|
1961
|
+
parts.push(opts.join(',\n') + ',');
|
|
1962
|
+
parts.push(`});`);
|
|
1963
|
+
}
|
|
1964
|
+
else {
|
|
1965
|
+
parts.push(`export const ${seqName} = pgSequence('${seq.name}');`);
|
|
1966
|
+
}
|
|
1967
|
+
parts.push('');
|
|
1968
|
+
}
|
|
1969
|
+
}
|
|
1970
|
+
if (includeFunctions && schema.functions && schema.functions.length > 0) {
|
|
1971
|
+
const userFunctions = schema.functions.filter(f => !f.name.startsWith('pg_') &&
|
|
1972
|
+
!EXCLUDED_FUNCTIONS.some(ex => f.name.startsWith(ex) || f.name === ex));
|
|
1973
|
+
if (userFunctions.length > 0) {
|
|
1974
|
+
parts.push('// ============================================');
|
|
1975
|
+
parts.push('// Database Functions');
|
|
1976
|
+
parts.push('// ============================================');
|
|
1977
|
+
parts.push('');
|
|
1978
|
+
for (const func of userFunctions) {
|
|
1979
|
+
const funcName = toCamelCase(func.name);
|
|
1980
|
+
const escapedDefinition = func.definition
|
|
1981
|
+
.replace(/\\/g, '\\\\')
|
|
1982
|
+
.replace(/`/g, '\\`')
|
|
1983
|
+
.replace(/\${/g, '\\${');
|
|
1984
|
+
const argsStr = func.argTypes && func.argTypes.length > 0
|
|
1985
|
+
? func.argTypes.map((arg, i) => `{ name: 'arg${i}', type: '${arg}' }`).join(', ')
|
|
1986
|
+
: '';
|
|
1987
|
+
if (func.comment) {
|
|
1988
|
+
const safeComment = func.comment.replace(/\*\//g, '* /');
|
|
1989
|
+
parts.push(`/**\n * ${safeComment}\n */`);
|
|
1990
|
+
}
|
|
1991
|
+
parts.push(`export const ${funcName} = pgFunction('${func.name}', {`);
|
|
1992
|
+
if (argsStr) {
|
|
1993
|
+
parts.push(` args: [${argsStr}],`);
|
|
1994
|
+
}
|
|
1995
|
+
parts.push(` returns: '${func.returnType}',`);
|
|
1996
|
+
parts.push(` language: '${func.language}',`);
|
|
1997
|
+
parts.push(` raw: \`${escapedDefinition}\`,`);
|
|
1998
|
+
parts.push(`});`);
|
|
1999
|
+
parts.push('');
|
|
2000
|
+
}
|
|
2001
|
+
}
|
|
2002
|
+
}
|
|
2003
|
+
if (includeTriggers && schema.triggers && schema.triggers.length > 0) {
|
|
2004
|
+
const tableNames = new Set(tables.map(t => t.name.toLowerCase()));
|
|
2005
|
+
const validTriggers = schema.triggers.filter((t) => tableNames.has(t.tableName.toLowerCase()) &&
|
|
2006
|
+
!partitionTableNames.has(t.tableName.toLowerCase()));
|
|
2007
|
+
if (validTriggers.length > 0) {
|
|
2008
|
+
parts.push('// ============================================');
|
|
2009
|
+
parts.push('// Database Triggers');
|
|
2010
|
+
parts.push('// ============================================');
|
|
2011
|
+
parts.push('');
|
|
2012
|
+
const seenTriggerNames = new Set();
|
|
2013
|
+
for (const trigger of validTriggers) {
|
|
2014
|
+
const tableCamel = toCamelCase(trigger.tableName);
|
|
2015
|
+
const funcCamel = toCamelCase(trigger.functionName);
|
|
2016
|
+
let triggerName = toCamelCase(trigger.name);
|
|
2017
|
+
if (seenTriggerNames.has(triggerName)) {
|
|
2018
|
+
triggerName = `${triggerName}_${tableCamel}`;
|
|
2019
|
+
}
|
|
2020
|
+
seenTriggerNames.add(triggerName);
|
|
2021
|
+
const timing = (trigger.timing || 'AFTER').toUpperCase();
|
|
2022
|
+
const event = (trigger.event || 'INSERT').toUpperCase();
|
|
2023
|
+
const timingProp = timing === 'BEFORE' ? 'before' :
|
|
2024
|
+
timing === 'INSTEAD OF' ? 'insteadOf' : 'after';
|
|
2025
|
+
if (trigger.comment) {
|
|
2026
|
+
const safeComment = trigger.comment.replace(/\*\//g, '* /');
|
|
2027
|
+
parts.push(`/**\n * ${safeComment}\n */`);
|
|
2028
|
+
}
|
|
2029
|
+
parts.push(`export const ${triggerName} = pgTrigger('${trigger.name}', {`);
|
|
2030
|
+
parts.push(` on: ${tableCamel},`);
|
|
2031
|
+
parts.push(` ${timingProp}: '${event}',`);
|
|
2032
|
+
parts.push(` forEachRow: true,`);
|
|
2033
|
+
parts.push(` execute: ${funcCamel},`);
|
|
2034
|
+
parts.push(`});`);
|
|
2035
|
+
parts.push('');
|
|
2036
|
+
}
|
|
2037
|
+
}
|
|
2038
|
+
}
|
|
2039
|
+
if (includeSchema) {
|
|
2040
|
+
parts.push('// ============================================');
|
|
2041
|
+
parts.push('// Schema Export');
|
|
2042
|
+
parts.push('// ============================================');
|
|
2043
|
+
parts.push('');
|
|
2044
|
+
const tableRefs = tables.map(t => ` ${toCamelCase(t.name)},`).join('\n');
|
|
2045
|
+
parts.push('export const schema = {');
|
|
2046
|
+
parts.push(tableRefs);
|
|
2047
|
+
parts.push('} as const;');
|
|
2048
|
+
parts.push('');
|
|
2049
|
+
const schemaTypes = tables.map(t => ` ${toCamelCase(t.name)}: typeof ${toCamelCase(t.name)};`).join('\n');
|
|
2050
|
+
parts.push('export type DatabaseSchema = {');
|
|
2051
|
+
parts.push(schemaTypes);
|
|
2052
|
+
parts.push('};');
|
|
2053
|
+
}
|
|
2054
|
+
if (schema.extensions && schema.extensions.length > 0) {
|
|
2055
|
+
parts.push('');
|
|
2056
|
+
parts.push('// Enabled Extensions');
|
|
2057
|
+
const extArgs = schema.extensions.map((e) => `'${e}'`).join(', ');
|
|
2058
|
+
parts.push(`export const enabledExtensions = pgExtensions(${extArgs});`);
|
|
2059
|
+
}
|
|
2060
|
+
return parts.join('\n');
|
|
2061
|
+
}
|