admindb 2.0.0 → 2.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/dist/app.d.ts +1 -69
- package/dist/app.js +1 -257
- package/dist/auth/config.d.ts +1 -19
- package/dist/auth/config.js +1 -147
- package/dist/auth/crypto.d.ts +1 -27
- package/dist/auth/crypto.js +1 -133
- package/dist/auth/index.d.ts +1 -5
- package/dist/auth/index.js +1 -22
- package/dist/auth/middleware.d.ts +1 -14
- package/dist/auth/middleware.js +1 -100
- package/dist/auth/routes.d.ts +1 -7
- package/dist/auth/routes.js +1 -78
- package/dist/auth/types.d.ts +1 -35
- package/dist/auth/types.js +1 -11
- package/dist/cli/args.d.ts +1 -45
- package/dist/cli/args.js +1 -328
- package/dist/cli/config.d.ts +1 -56
- package/dist/cli/config.js +1 -133
- package/dist/cli/index.d.ts +1 -4
- package/dist/cli/index.js +1 -21
- package/dist/cli/runner.d.ts +1 -1
- package/dist/cli/runner.js +1 -222
- package/dist/cli.d.ts +1 -2
- package/dist/cli.js +1 -5
- package/dist/data/datasets.d.ts +1 -17
- package/dist/data/datasets.js +1 -133
- package/dist/data/detector.d.ts +1 -30
- package/dist/data/detector.js +1 -472
- package/dist/data/engine.d.ts +1 -10
- package/dist/data/engine.js +1 -211
- package/dist/data/index.d.ts +1 -5
- package/dist/data/index.js +1 -22
- package/dist/data/strategies.d.ts +1 -30
- package/dist/data/strategies.js +1 -343
- package/dist/data/types.d.ts +1 -73
- package/dist/data/types.js +1 -8
- package/dist/db/database.d.ts +1 -119
- package/dist/db/database.js +1 -471
- package/dist/db/export.d.ts +1 -12
- package/dist/db/export.js +1 -42
- package/dist/db/filters.d.ts +1 -22
- package/dist/db/filters.js +1 -158
- package/dist/db/index.d.ts +1 -8
- package/dist/db/index.js +1 -25
- package/dist/db/introspection.d.ts +1 -6
- package/dist/db/introspection.js +1 -172
- package/dist/db/manager.d.ts +1 -81
- package/dist/db/manager.js +1 -397
- package/dist/db/migrations.d.ts +1 -5
- package/dist/db/migrations.js +1 -110
- package/dist/db/postgres.d.ts +1 -85
- package/dist/db/postgres.js +1 -745
- package/dist/db/types.d.ts +1 -206
- package/dist/db/types.js +1 -7
- package/dist/index.d.ts +1 -23
- package/dist/index.js +1 -66
- package/dist/public/js/api.js +1 -47
- package/dist/public/js/app.js +1 -262
- package/dist/public/js/browse.js +1 -1371
- package/dist/public/js/databases.js +1 -235
- package/dist/public/js/designer.js +1 -243
- package/dist/public/js/forms.js +1 -826
- package/dist/public/js/icons.js +1 -51
- package/dist/public/js/inspector.js +1 -638
- package/dist/public/js/query.js +1 -322
- package/dist/public/js/schema.js +1 -432
- package/dist/public/js/seed.js +1 -1090
- package/dist/routes/api/helpers.d.ts +1 -42
- package/dist/routes/api/helpers.js +1 -133
- package/dist/routes/api/import-export.d.ts +1 -3
- package/dist/routes/api/import-export.js +1 -85
- package/dist/routes/api/index.d.ts +1 -4
- package/dist/routes/api/index.js +1 -37
- package/dist/routes/api/query.d.ts +1 -3
- package/dist/routes/api/query.js +1 -76
- package/dist/routes/api/rows.d.ts +1 -3
- package/dist/routes/api/rows.js +1 -373
- package/dist/routes/api/seed.d.ts +1 -3
- package/dist/routes/api/seed.js +1 -82
- package/dist/routes/api/tables.d.ts +1 -3
- package/dist/routes/api/tables.js +1 -160
- package/dist/routes/databases.d.ts +1 -26
- package/dist/routes/databases.js +1 -230
- package/dist/routes/index.d.ts +1 -3
- package/dist/routes/index.js +1 -20
- package/dist/routes/pages.d.ts +1 -9
- package/dist/routes/pages.js +1 -382
- package/dist/serverless.d.ts +1 -40
- package/dist/serverless.js +1 -210
- package/dist/sql/classifier.d.ts +1 -19
- package/dist/sql/classifier.js +1 -37
- package/dist/sql/generator.d.ts +1 -78
- package/dist/sql/generator.js +1 -308
- package/dist/sql/index.d.ts +1 -2
- package/dist/sql/index.js +1 -19
- package/dist/types/api.d.ts +1 -412
- package/dist/types/api.js +1 -9
- package/dist/utils/colors.d.ts +1 -40
- package/dist/utils/colors.js +1 -64
- package/dist/utils/common.d.ts +1 -50
- package/dist/utils/common.js +1 -229
- package/dist/utils/csv.d.ts +1 -15
- package/dist/utils/csv.js +1 -80
- package/dist/utils/datatype.d.ts +1 -49
- package/dist/utils/datatype.js +1 -222
- package/dist/utils/icons.d.ts +1 -11
- package/dist/utils/icons.js +1 -72
- package/dist/utils/index.d.ts +1 -4
- package/dist/utils/index.js +1 -21
- package/dist/utils/logger.d.ts +1 -10
- package/dist/utils/logger.js +1 -40
- package/dist/views/layouts/main.hbs +8 -5
- package/dist/views/pages/databases.hbs +0 -18
- package/dist/views/pages/designer.hbs +22 -17
- package/dist/views/pages/error.hbs +0 -2
- package/dist/views/pages/form.hbs +0 -5
- package/dist/views/pages/home.hbs +0 -8
- package/dist/views/pages/login.hbs +0 -13
- package/dist/views/pages/query.hbs +0 -9
- package/dist/views/pages/schema.hbs +0 -20
- package/dist/views/pages/seed.hbs +0 -31
- package/dist/views/pages/table.hbs +0 -14
- package/dist/views/partials/icon.hbs +0 -1
- package/dist/views/partials/navbar.hbs +0 -6
- package/dist/views/partials/sidebar.hbs +0 -8
- package/docs/API.md +144 -0
- package/docs/EXAMPLES.md +576 -0
- package/docs/SECURITY.md +265 -0
- package/package.json +7 -2
- package/dist/app.js.map +0 -1
- package/dist/auth/config.js.map +0 -1
- package/dist/auth/crypto.js.map +0 -1
- package/dist/auth/index.js.map +0 -1
- package/dist/auth/middleware.js.map +0 -1
- package/dist/auth/routes.js.map +0 -1
- package/dist/auth/types.js.map +0 -1
- package/dist/cli/args.js.map +0 -1
- package/dist/cli/config.js.map +0 -1
- package/dist/cli/index.js.map +0 -1
- package/dist/cli/runner.js.map +0 -1
- package/dist/cli.js.map +0 -1
- package/dist/data/datasets.js.map +0 -1
- package/dist/data/detector.js.map +0 -1
- package/dist/data/engine.js.map +0 -1
- package/dist/data/index.js.map +0 -1
- package/dist/data/strategies.js.map +0 -1
- package/dist/data/types.js.map +0 -1
- package/dist/db/database.js.map +0 -1
- package/dist/db/export.js.map +0 -1
- package/dist/db/filters.js.map +0 -1
- package/dist/db/index.js.map +0 -1
- package/dist/db/introspection.js.map +0 -1
- package/dist/db/manager.js.map +0 -1
- package/dist/db/migrations.js.map +0 -1
- package/dist/db/postgres.js.map +0 -1
- package/dist/db/types.js.map +0 -1
- package/dist/index.js.map +0 -1
- package/dist/public/css/input.css +0 -302
- package/dist/routes/api/helpers.js.map +0 -1
- package/dist/routes/api/import-export.js.map +0 -1
- package/dist/routes/api/index.js.map +0 -1
- package/dist/routes/api/query.js.map +0 -1
- package/dist/routes/api/rows.js.map +0 -1
- package/dist/routes/api/seed.js.map +0 -1
- package/dist/routes/api/tables.js.map +0 -1
- package/dist/routes/databases.js.map +0 -1
- package/dist/routes/index.js.map +0 -1
- package/dist/routes/pages.js.map +0 -1
- package/dist/serverless.js.map +0 -1
- package/dist/sql/classifier.js.map +0 -1
- package/dist/sql/generator.js.map +0 -1
- package/dist/sql/index.js.map +0 -1
- package/dist/types/api.js.map +0 -1
- package/dist/utils/colors.js.map +0 -1
- package/dist/utils/common.js.map +0 -1
- package/dist/utils/csv.js.map +0 -1
- package/dist/utils/datatype.js.map +0 -1
- package/dist/utils/icons.js.map +0 -1
- package/dist/utils/index.js.map +0 -1
- package/dist/utils/logger.js.map +0 -1
package/dist/data/detector.js
CHANGED
|
@@ -1,472 +1 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.normName = void 0;
|
|
4
|
-
exports.isTimestampName = isTimestampName;
|
|
5
|
-
exports.findInMap = findInMap;
|
|
6
|
-
exports.extractCheckExprs = extractCheckExprs;
|
|
7
|
-
exports.parseChecks = parseChecks;
|
|
8
|
-
exports.detectPlan = detectPlan;
|
|
9
|
-
exports.buildColumnConfigs = buildColumnConfigs;
|
|
10
|
-
exports.sanitizeColumnPlan = sanitizeColumnPlan;
|
|
11
|
-
const strategies_1 = require("./strategies");
|
|
12
|
-
const normName = (s) => String(s).toLowerCase().replace(/[^a-z0-9]/g, '');
|
|
13
|
-
exports.normName = normName;
|
|
14
|
-
function isTimestampName(name) {
|
|
15
|
-
return (/created|updated|modified|registered|joined|timestamp|lastused|lastseen|lastlogin|lastactivity|accessed|viewed|visited|^ts$/.test(name) ||
|
|
16
|
-
/^(created|updated|deleted|archived|occurred|started|ended|expires|published|processed|completed|inserted|requested|resolved|used|seen|accessed|viewed|visited|logged|active)at$/.test(name));
|
|
17
|
-
}
|
|
18
|
-
function findInMap(map, colName) {
|
|
19
|
-
if (map.has(colName))
|
|
20
|
-
return map.get(colName);
|
|
21
|
-
const lower = colName.toLowerCase();
|
|
22
|
-
for (const [k, v] of map.entries()) {
|
|
23
|
-
if (k.toLowerCase() === lower)
|
|
24
|
-
return v;
|
|
25
|
-
}
|
|
26
|
-
return undefined;
|
|
27
|
-
}
|
|
28
|
-
function extractCheckExprs(sql) {
|
|
29
|
-
const out = [];
|
|
30
|
-
const re = /CHECK\s*\(/gi;
|
|
31
|
-
let m;
|
|
32
|
-
while ((m = re.exec(sql))) {
|
|
33
|
-
let depth = 1;
|
|
34
|
-
let i = m.index + m[0].length;
|
|
35
|
-
const start = i;
|
|
36
|
-
while (i < sql.length && depth > 0) {
|
|
37
|
-
const ch = sql[i];
|
|
38
|
-
if (ch === "'") {
|
|
39
|
-
i += 1;
|
|
40
|
-
while (i < sql.length) {
|
|
41
|
-
if (sql[i] === "'") {
|
|
42
|
-
if (sql[i + 1] === "'")
|
|
43
|
-
i += 2;
|
|
44
|
-
else {
|
|
45
|
-
i += 1;
|
|
46
|
-
break;
|
|
47
|
-
}
|
|
48
|
-
}
|
|
49
|
-
else
|
|
50
|
-
i += 1;
|
|
51
|
-
}
|
|
52
|
-
continue;
|
|
53
|
-
}
|
|
54
|
-
if (ch === '"' || ch === '`' || ch === '[') {
|
|
55
|
-
const close = ch === '[' ? ']' : ch;
|
|
56
|
-
i += 1;
|
|
57
|
-
while (i < sql.length && sql[i] !== close) {
|
|
58
|
-
if (sql[i] === close && sql[i + 1] === close)
|
|
59
|
-
i += 2;
|
|
60
|
-
else
|
|
61
|
-
i += 1;
|
|
62
|
-
}
|
|
63
|
-
i += 1;
|
|
64
|
-
continue;
|
|
65
|
-
}
|
|
66
|
-
if (ch === '(')
|
|
67
|
-
depth += 1;
|
|
68
|
-
else if (ch === ')') {
|
|
69
|
-
depth -= 1;
|
|
70
|
-
if (depth === 0)
|
|
71
|
-
break;
|
|
72
|
-
}
|
|
73
|
-
i += 1;
|
|
74
|
-
}
|
|
75
|
-
out.push(sql.slice(start, i));
|
|
76
|
-
}
|
|
77
|
-
return out;
|
|
78
|
-
}
|
|
79
|
-
function parseChecks(sql) {
|
|
80
|
-
const info = {
|
|
81
|
-
columnAllowed: new Map(),
|
|
82
|
-
columnRange: new Map(),
|
|
83
|
-
jsonAllowed: new Map(),
|
|
84
|
-
ordering: new Map(),
|
|
85
|
-
};
|
|
86
|
-
if (!sql)
|
|
87
|
-
return info;
|
|
88
|
-
const setOrdering = (col, other, key, orEqual) => {
|
|
89
|
-
const c = info.ordering.get(col) ?? {};
|
|
90
|
-
c[key] = { column: other, orEqual };
|
|
91
|
-
info.ordering.set(col, c);
|
|
92
|
-
};
|
|
93
|
-
const setColumnAllowed = (col, vals) => {
|
|
94
|
-
if (!col || !vals.length)
|
|
95
|
-
return;
|
|
96
|
-
const existing = findInMap(info.columnAllowed, col);
|
|
97
|
-
if (existing) {
|
|
98
|
-
for (const v of vals)
|
|
99
|
-
if (!existing.includes(v))
|
|
100
|
-
existing.push(v);
|
|
101
|
-
}
|
|
102
|
-
else {
|
|
103
|
-
info.columnAllowed.set(col, [...vals]);
|
|
104
|
-
}
|
|
105
|
-
};
|
|
106
|
-
for (const expr of extractCheckExprs(sql)) {
|
|
107
|
-
// 1. JSON whitelists
|
|
108
|
-
const jw1 = /(?:"([^"]+)"|`([^`]+)`|\[([^\]]+)\]|([A-Za-z_][A-Za-z0-9_]*))\s*(?:->>|->)\s*'([^']+)'\s*\)*\s*IN\s*\(([^)]*)\)/gi;
|
|
109
|
-
const jw2 = /json_extract\s*\(\s*(?:"([^"]+)"|`([^`]+)`|\[([^\]]+)\]|([A-Za-z_][A-Za-z0-9_]*))\s*,\s*'(?:\$\??|\.)?\.?([^']+)'\s*\)\s*\)*\s*IN\s*\(([^)]*)\)/gi;
|
|
110
|
-
for (const re of [jw1, jw2]) {
|
|
111
|
-
let m;
|
|
112
|
-
while ((m = re.exec(expr))) {
|
|
113
|
-
const col = m[1] || m[2] || m[3] || m[4];
|
|
114
|
-
const key = m[5];
|
|
115
|
-
const inContent = m[6];
|
|
116
|
-
const strValues = (inContent.match(/'(?:[^']|'')*'/g) ?? []).map((s) => s.slice(1, -1).replace(/''/g, "'"));
|
|
117
|
-
const values = strValues.length ? strValues : (inContent.match(/-?\b\d+(?:\.\d+)?\b/g) ?? []);
|
|
118
|
-
if (values.length && col && key) {
|
|
119
|
-
const byCol = findInMap(info.jsonAllowed, col) ?? new Map();
|
|
120
|
-
byCol.set(key, values);
|
|
121
|
-
info.jsonAllowed.set(col, byCol);
|
|
122
|
-
}
|
|
123
|
-
}
|
|
124
|
-
}
|
|
125
|
-
// 2. Direct column IN lists
|
|
126
|
-
const colIn = /(?:^|[^(->>\w])(?:\(\s*)?(?:(?:lower|upper|trim|coalesce)\s*\(\s*)?(?:"([^"]+)"|`([^`]+)`|\[([^\]]+)\]|([A-Za-z_][A-Za-z0-9_]*))(?:\s*,\s*[^)]+)?\s*\)?\s*\)?\s*IN\s*\(([^)]*)\)/gi;
|
|
127
|
-
let mColIn;
|
|
128
|
-
while ((mColIn = colIn.exec(expr))) {
|
|
129
|
-
const col = mColIn[1] || mColIn[2] || mColIn[3] || mColIn[4];
|
|
130
|
-
if (!col || ['json_extract', 'strftime', 'datetime', 'date', 'length', 'typeof'].includes(col.toLowerCase()))
|
|
131
|
-
continue;
|
|
132
|
-
const matchPos = mColIn.index;
|
|
133
|
-
if (expr.slice(Math.max(0, matchPos - 5), matchPos).includes('->'))
|
|
134
|
-
continue;
|
|
135
|
-
const inContent = mColIn[5];
|
|
136
|
-
const strValues = (inContent.match(/'(?:[^']|'')*'/g) ?? []).map((s) => s.slice(1, -1).replace(/''/g, "'"));
|
|
137
|
-
const values = strValues.length ? strValues : (inContent.match(/-?\b\d+(?:\.\d+)?\b/g) ?? []);
|
|
138
|
-
if (values.length)
|
|
139
|
-
setColumnAllowed(col, values);
|
|
140
|
-
}
|
|
141
|
-
// 3. Direct column equality
|
|
142
|
-
const eqOr = /(?:"([^"]+)"|`([^`]+)`|\[([^\]]+)\]|([A-Za-z_][A-Za-z0-9_]*))\s*=\s*'((?:[^']|'')*)'/gi;
|
|
143
|
-
let mEq;
|
|
144
|
-
const eqByCol = new Map();
|
|
145
|
-
while ((mEq = eqOr.exec(expr))) {
|
|
146
|
-
const col = mEq[1] || mEq[2] || mEq[3] || mEq[4];
|
|
147
|
-
const val = mEq[5].replace(/''/g, "'");
|
|
148
|
-
if (col && !['json_extract', 'lower', 'upper', 'trim', 'strftime', 'datetime'].includes(col.toLowerCase())) {
|
|
149
|
-
const cur = eqByCol.get(col) ?? [];
|
|
150
|
-
if (!cur.includes(val))
|
|
151
|
-
cur.push(val);
|
|
152
|
-
eqByCol.set(col, cur);
|
|
153
|
-
}
|
|
154
|
-
}
|
|
155
|
-
for (const [col, vals] of eqByCol.entries())
|
|
156
|
-
setColumnAllowed(col, vals);
|
|
157
|
-
// 4. Numeric range constraints
|
|
158
|
-
const numCmp1 = /(?:"([^"]+)"|`([^`]+)`|\[([^\]]+)\]|([A-Za-z_][A-Za-z0-9_]*))\s*(>=|>|<=|<)\s*(-?\d+(?:\.\d+)?)/g;
|
|
159
|
-
let mNum1;
|
|
160
|
-
while ((mNum1 = numCmp1.exec(expr))) {
|
|
161
|
-
const col = mNum1[1] || mNum1[2] || mNum1[3] || mNum1[4];
|
|
162
|
-
const op = mNum1[5];
|
|
163
|
-
const val = Number(mNum1[6]);
|
|
164
|
-
if (col && Number.isFinite(val) && !['json_extract', 'length', 'strftime', 'datetime'].includes(col.toLowerCase())) {
|
|
165
|
-
const cur = findInMap(info.columnRange, col) ?? {};
|
|
166
|
-
if (op === '>=' || op === '>')
|
|
167
|
-
cur.min = cur.min != null ? Math.max(cur.min, op === '>' ? val + 1 : val) : (op === '>' ? val + 1 : val);
|
|
168
|
-
else
|
|
169
|
-
cur.max = cur.max != null ? Math.min(cur.max, op === '<' ? val - 1 : val) : (op === '<' ? val - 1 : val);
|
|
170
|
-
info.columnRange.set(col, cur);
|
|
171
|
-
}
|
|
172
|
-
}
|
|
173
|
-
// 5. Column ordering
|
|
174
|
-
const ord = /(?:"([^"]+)"|`([^`]+)`|\[([^\]]+)\]|([A-Za-z_][A-Za-z0-9_]*))\s*(>=|<=|>|<)\s*(?:"([^"]+)"|`([^`]+)`|\[([^\]]+)\]|([A-Za-z_][A-Za-z0-9_]*))/g;
|
|
175
|
-
let m2;
|
|
176
|
-
while ((m2 = ord.exec(expr))) {
|
|
177
|
-
const a = m2[1] || m2[2] || m2[3] || m2[4];
|
|
178
|
-
const op = m2[5];
|
|
179
|
-
const b = m2[6] || m2[7] || m2[8] || m2[9];
|
|
180
|
-
if (!a || !b || /^\d+$/.test(a) || /^\d+$/.test(b))
|
|
181
|
-
continue;
|
|
182
|
-
if (['json_extract', 'strftime', 'datetime', 'date', 'length'].includes(a.toLowerCase()))
|
|
183
|
-
continue;
|
|
184
|
-
if (['json_extract', 'strftime', 'datetime', 'date', 'length'].includes(b.toLowerCase()))
|
|
185
|
-
continue;
|
|
186
|
-
if (op === '>' || op === '>=') {
|
|
187
|
-
setOrdering(a, b, 'after', op === '>=');
|
|
188
|
-
setOrdering(b, a, 'before', op === '>=');
|
|
189
|
-
}
|
|
190
|
-
else {
|
|
191
|
-
setOrdering(a, b, 'before', op === '<=');
|
|
192
|
-
setOrdering(b, a, 'after', op === '<=');
|
|
193
|
-
}
|
|
194
|
-
}
|
|
195
|
-
}
|
|
196
|
-
return info;
|
|
197
|
-
}
|
|
198
|
-
const isHashName = (name) => /^(hash|digest|secret|passphrase)$|tokenhash|passwordhash|passhash|accesskey|apikey|api_key|secretkey|clientsecret|appsecret|appid|privatekey|publickey/.test(name);
|
|
199
|
-
const isTokenName = (name) => /^prefix$|tokenprefix|(code|ref|reference|sku|ticketno|ticketnum|orderno|order_no|trackingno|trackingnum|invno|invoiceno|serialno)$/.test(name);
|
|
200
|
-
function isJsonColumn(col, hasJsonIndex) {
|
|
201
|
-
if (!(0, strategies_1.isTextishType)(col.type))
|
|
202
|
-
return false;
|
|
203
|
-
if (hasJsonIndex)
|
|
204
|
-
return true;
|
|
205
|
-
const dflt = String(col.dflt_value ?? '').trim();
|
|
206
|
-
if (dflt.startsWith('{') || dflt.startsWith("'{\""))
|
|
207
|
-
return true;
|
|
208
|
-
const name = (0, exports.normName)(col.name);
|
|
209
|
-
return /^(permissions|settings|config|configuration|preferences|prefs|metadata|meta|attributes|payload|options|allowedapps|socialaccounts|positions|fcmtokens|fcm_tokens|scopes|profile|json|jsonb)$/.test(name) ||
|
|
210
|
-
/(^|_)(settings|config|configuration|permissions|prefs|metadata|attributes|payload|options|allowedapps|scopes|profile)$/.test(name);
|
|
211
|
-
}
|
|
212
|
-
function extractJsonColumns(sql) {
|
|
213
|
-
const out = [];
|
|
214
|
-
const push = (col, key) => {
|
|
215
|
-
let entry = out.find((e) => e.col === col);
|
|
216
|
-
if (!entry) {
|
|
217
|
-
entry = { col, keys: [] };
|
|
218
|
-
out.push(entry);
|
|
219
|
-
}
|
|
220
|
-
if (key) {
|
|
221
|
-
const last = key.split('.').pop().replace(/[\[\]"]/g, '');
|
|
222
|
-
if (last && !entry.keys.includes(last))
|
|
223
|
-
entry.keys.push(last);
|
|
224
|
-
}
|
|
225
|
-
};
|
|
226
|
-
const arrow = /"([^"]+)"\s*(?:->>|->)\s*'([^']+)'|([A-Za-z_][A-Za-z0-9_]*)\s*(?:->>|->)\s*'([^']+)'/g;
|
|
227
|
-
let m;
|
|
228
|
-
while ((m = arrow.exec(sql)))
|
|
229
|
-
push(m[1] || m[3], m[2] || m[4]);
|
|
230
|
-
const jx = /json_extract\s*\(\s*(?:"([^"]+)"|([A-Za-z_][A-Za-z0-9_]*))\s*,\s*'(?:\$\??|\.)?\.?([^']+)'/g;
|
|
231
|
-
while ((m = jx.exec(sql)))
|
|
232
|
-
push(m[1] || m[2], m[3]);
|
|
233
|
-
return out;
|
|
234
|
-
}
|
|
235
|
-
/** Name heuristics pattern table for text-ish columns. */
|
|
236
|
-
const TEXT_PATTERNS = [
|
|
237
|
-
[/avatar|picture|photo|image|img|thumbnail|icon|logo/, () => ({ strategy: 'avatar' })],
|
|
238
|
-
[/company|organization|org|firm|corp|employer|agency/, () => ({ strategy: 'company' })],
|
|
239
|
-
[/job|title|role|position|occupation|profession/, () => ({ strategy: 'job' })],
|
|
240
|
-
[/currency|curr|currencycode/, () => ({ strategy: 'currency' })],
|
|
241
|
-
[/countrycode|countryiso|isocountry|cca2/, () => ({ strategy: 'countryCode' })],
|
|
242
|
-
[/state|province|region/, (n) => (/status|statement/.test(n) ? { strategy: 'status' } : { strategy: 'state' })],
|
|
243
|
-
[/status|stage|phase|state/, () => ({ strategy: 'status' })],
|
|
244
|
-
[/color|colour|theme|hexcolor/, () => ({ strategy: 'color', format: 'hex' })],
|
|
245
|
-
[/mac|macaddress|hwaddr/, () => ({ strategy: 'mac' })],
|
|
246
|
-
[/creditcard|cardnumber|cardno|ccnumber|ccno/, () => ({ strategy: 'creditCard' })],
|
|
247
|
-
[/slug|permalink|handle|alias/, () => ({ strategy: 'slug' })],
|
|
248
|
-
[/(lastname|surname|familyname)/, () => ({ strategy: 'last' })],
|
|
249
|
-
[/email|mail/, () => ({ strategy: 'email' })],
|
|
250
|
-
[/(username|login|handle|nick|nickname|account|user)/, () => ({ strategy: 'username' })],
|
|
251
|
-
[/(phone|mobile|telephone|cell|fax)/, () => ({ strategy: 'phone' })],
|
|
252
|
-
[/city|town/, () => ({ strategy: 'city' })],
|
|
253
|
-
[/country|nation/, () => ({ strategy: 'country' })],
|
|
254
|
-
[/postal|zip/, () => ({ strategy: 'postal' })],
|
|
255
|
-
[/address|street|addr/, () => ({ strategy: 'address' })],
|
|
256
|
-
[/url|website|site|link|homepage|href/, () => ({ strategy: 'url' })],
|
|
257
|
-
[/domain|host/, () => ({ strategy: 'domain' })],
|
|
258
|
-
[/^ip$|ipaddr|ipv4|ip_address/, () => ({ strategy: 'ip' })],
|
|
259
|
-
[/bio|about|overview|article|body|post|story/, () => ({ strategy: 'paragraph' })],
|
|
260
|
-
[/description|content|comment|message|note|summary|details|remarks/, () => ({ strategy: 'sentence', minLen: 1, maxLen: 2 })],
|
|
261
|
-
[/title|subject|category|type|tag|label/, () => ({ strategy: 'words', minLen: 1, maxLen: 3 })],
|
|
262
|
-
];
|
|
263
|
-
function detectPlan(col, fk) {
|
|
264
|
-
const type = (col.type || '').toUpperCase();
|
|
265
|
-
const rawName = col.name.toLowerCase();
|
|
266
|
-
const name = (0, exports.normName)(col.name);
|
|
267
|
-
if (fk)
|
|
268
|
-
return { strategy: 'fk' };
|
|
269
|
-
if (col.pk) {
|
|
270
|
-
if (type.startsWith('INT') || type === 'SERIAL' || type === 'BIGSERIAL')
|
|
271
|
-
return { strategy: 'skip' };
|
|
272
|
-
if (type === 'TEXT' || type === 'BLOB' || type === 'UUID')
|
|
273
|
-
return { strategy: 'uuid' };
|
|
274
|
-
return { strategy: 'skip' };
|
|
275
|
-
}
|
|
276
|
-
if (type === 'UUID')
|
|
277
|
-
return { strategy: 'uuid' };
|
|
278
|
-
if (type === 'JSON' || type === 'JSONB')
|
|
279
|
-
return { strategy: 'json' };
|
|
280
|
-
if (type === 'INET')
|
|
281
|
-
return { strategy: 'ip' };
|
|
282
|
-
if (type === 'BOOLEAN' || type === 'BOOL')
|
|
283
|
-
return { strategy: 'bool' };
|
|
284
|
-
if (type === 'BYTEA' || type === 'BLOB')
|
|
285
|
-
return { strategy: 'bytes', minLen: 8, maxLen: 32 };
|
|
286
|
-
if ((type.startsWith('INT') || type.startsWith('INTEGER')) && /(^|_)(is|has|can|should|did)_|_flag$|active|enabled|verified|published|deleted|archived|paid|completed|approved/.test(rawName)) {
|
|
287
|
-
return { strategy: 'bool' };
|
|
288
|
-
}
|
|
289
|
-
if (type === 'DATE' || /^date|birthdate|dob|birthday/.test(rawName)) {
|
|
290
|
-
return name.includes('birth') ? { strategy: 'date', from: '1950-01-01', to: '2000-12-31' } : { strategy: 'date', from: '2020-01-01', to: '2026-12-31' };
|
|
291
|
-
}
|
|
292
|
-
if (type === 'DATETIME' || type === 'TIMESTAMP' || isTimestampName(name)) {
|
|
293
|
-
return { strategy: 'datetime', from: '2024-01-01T00:00:00', to: '2026-12-31T23:59:59' };
|
|
294
|
-
}
|
|
295
|
-
if (type === 'TIME' || name === 'time')
|
|
296
|
-
return { strategy: 'time' };
|
|
297
|
-
if (type.startsWith('INTEGER') && /(timestamp|epoch|unix|createdtime|updatedtime)/.test(name)) {
|
|
298
|
-
return { strategy: 'timestampUnix', format: 'sec' };
|
|
299
|
-
}
|
|
300
|
-
if (/^(lat|latitude)$/.test(name))
|
|
301
|
-
return { strategy: 'latitude' };
|
|
302
|
-
if (/^(lng|lon|longitude)$/.test(name))
|
|
303
|
-
return { strategy: 'longitude' };
|
|
304
|
-
if (type.startsWith('INTEGER')) {
|
|
305
|
-
if (name.includes('year'))
|
|
306
|
-
return { strategy: 'int', min: 1990, max: 2026 };
|
|
307
|
-
if (name.includes('age'))
|
|
308
|
-
return { strategy: 'int', min: 18, max: 90 };
|
|
309
|
-
if (/(count|quantity|qty|stock|views|likes|total|num|number)$/.test(name))
|
|
310
|
-
return { strategy: 'int', min: 0, max: 100000 };
|
|
311
|
-
if (name.includes('rating') || name.includes('score'))
|
|
312
|
-
return { strategy: 'int', min: 1, max: 5 };
|
|
313
|
-
if (/(order|rank|position|seq|sequence|priority|sort|step)$/.test(name))
|
|
314
|
-
return { strategy: 'sequence', start: 1, step: 1 };
|
|
315
|
-
return { strategy: 'int', min: 1, max: 1000 };
|
|
316
|
-
}
|
|
317
|
-
if (type === 'REAL' || type.includes('DECIMAL') || type.includes('NUMERIC') || type.includes('FLOAT') || type.includes('DOUBLE')) {
|
|
318
|
-
if (/(price|cost|amount|total|salary|balance|fee|charge|budget)/.test(name))
|
|
319
|
-
return { strategy: 'decimal', min: 1, max: 5000, precision: 2 };
|
|
320
|
-
if (name.includes('rating'))
|
|
321
|
-
return { strategy: 'decimal', min: 1, max: 5, precision: 1 };
|
|
322
|
-
return { strategy: 'decimal', min: 1, max: 1000, precision: 2 };
|
|
323
|
-
}
|
|
324
|
-
if (type === 'BLOB')
|
|
325
|
-
return { strategy: 'bytes', minLen: 8, maxLen: 32 };
|
|
326
|
-
// Explicit text heuristics checked in exact order
|
|
327
|
-
if (/currency|curr|currencycode/.test(name))
|
|
328
|
-
return { strategy: 'currency' };
|
|
329
|
-
if (/countrycode|countryiso|isocountry|cca2/.test(name))
|
|
330
|
-
return { strategy: 'countryCode' };
|
|
331
|
-
if (/state|province|region/.test(name) && !/status|statement/.test(name))
|
|
332
|
-
return { strategy: 'state' };
|
|
333
|
-
if (/status|stage|phase|state/.test(name))
|
|
334
|
-
return { strategy: 'status' };
|
|
335
|
-
if (/color|colour|theme|hexcolor/.test(name))
|
|
336
|
-
return { strategy: 'color', format: 'hex' };
|
|
337
|
-
if (/mac|macaddress|hwaddr/.test(name))
|
|
338
|
-
return { strategy: 'mac' };
|
|
339
|
-
if (/creditcard|cardnumber|cardno|ccnumber|ccno/.test(name))
|
|
340
|
-
return { strategy: 'creditCard' };
|
|
341
|
-
if (/slug|permalink|handle|alias/.test(name))
|
|
342
|
-
return { strategy: 'slug' };
|
|
343
|
-
if (isHashName(name))
|
|
344
|
-
return { strategy: 'hash', minLen: 32, maxLen: 64 };
|
|
345
|
-
if (isTokenName(name))
|
|
346
|
-
return { strategy: 'token', minLen: 6, maxLen: 12 };
|
|
347
|
-
if (/uuid|guid/.test(name) || name === 'id' || name === 'uid' || name === 'key')
|
|
348
|
-
return { strategy: 'uuid' };
|
|
349
|
-
if (name.includes('first') && name.includes('name'))
|
|
350
|
-
return { strategy: 'first' };
|
|
351
|
-
if (/(lastname|surname|familyname)/.test(name) || (name.includes('last') && name.includes('name')))
|
|
352
|
-
return { strategy: 'last' };
|
|
353
|
-
if (name === 'name' || name === 'fullname' || (name.includes('full') && name.includes('name')))
|
|
354
|
-
return { strategy: 'fullname' };
|
|
355
|
-
for (const [pattern, createPlan] of TEXT_PATTERNS) {
|
|
356
|
-
if (pattern.test(name))
|
|
357
|
-
return createPlan(name);
|
|
358
|
-
}
|
|
359
|
-
return { strategy: 'words', minLen: 1, maxLen: 4 };
|
|
360
|
-
}
|
|
361
|
-
function buildColumnConfigs(info) {
|
|
362
|
-
const fkByColumn = new Map(info.foreignKeys.map((fk) => [fk.from, fk]));
|
|
363
|
-
const uniqueCols = new Set();
|
|
364
|
-
const jsonIndexKeys = new Map();
|
|
365
|
-
for (const ix of info.indexes ?? []) {
|
|
366
|
-
if (ix.unique && ix.columns.length === 1 && ix.columns[0])
|
|
367
|
-
uniqueCols.add(ix.columns[0]);
|
|
368
|
-
if (ix.sql && /json_extract|->>|->\s*'|json_/i.test(ix.sql)) {
|
|
369
|
-
for (const { col, keys } of extractJsonColumns(ix.sql)) {
|
|
370
|
-
if (!col)
|
|
371
|
-
continue;
|
|
372
|
-
const merged = new Set([...(jsonIndexKeys.get(col) ?? []), ...keys]);
|
|
373
|
-
if (merged.size)
|
|
374
|
-
jsonIndexKeys.set(col, [...merged]);
|
|
375
|
-
}
|
|
376
|
-
}
|
|
377
|
-
}
|
|
378
|
-
const checkInfo = parseChecks(info.sql ?? null);
|
|
379
|
-
return info.columns.map((col) => {
|
|
380
|
-
const fk = fkByColumn.get(col.name) ?? null;
|
|
381
|
-
const strategies = (0, strategies_1.strategiesFor)(col, fk);
|
|
382
|
-
const unique = uniqueCols.has(col.name);
|
|
383
|
-
let defaultPlan = detectPlan(col, fk);
|
|
384
|
-
if (defaultPlan.strategy !== 'fk' && !col.pk && isJsonColumn(col, jsonIndexKeys.has(col.name))) {
|
|
385
|
-
const keys = jsonIndexKeys.get(col.name);
|
|
386
|
-
const useKeys = keys && keys.length ? keys : ['scope', 'enabled', 'allowedApps'];
|
|
387
|
-
const allowed = findInMap(checkInfo.jsonAllowed, col.name);
|
|
388
|
-
const jsonValues = {};
|
|
389
|
-
if (allowed) {
|
|
390
|
-
for (const k of useKeys) {
|
|
391
|
-
const vals = allowed.get(k);
|
|
392
|
-
if (vals && vals.length)
|
|
393
|
-
jsonValues[k] = vals;
|
|
394
|
-
}
|
|
395
|
-
}
|
|
396
|
-
defaultPlan = {
|
|
397
|
-
strategy: 'json',
|
|
398
|
-
jsonKeys: useKeys,
|
|
399
|
-
...(Object.keys(jsonValues).length ? { jsonValues } : {}),
|
|
400
|
-
};
|
|
401
|
-
}
|
|
402
|
-
const colAllowed = findInMap(checkInfo.columnAllowed, col.name);
|
|
403
|
-
if (colAllowed && colAllowed.length > 0 && defaultPlan.strategy !== 'fk' && !col.pk) {
|
|
404
|
-
defaultPlan = colAllowed.length === 1 ? { strategy: 'fixed', value: colAllowed[0] } : { strategy: 'list', values: [...colAllowed] };
|
|
405
|
-
}
|
|
406
|
-
const colRange = findInMap(checkInfo.columnRange, col.name);
|
|
407
|
-
if (colRange && (defaultPlan.strategy === 'int' || defaultPlan.strategy === 'decimal')) {
|
|
408
|
-
if (colRange.min != null)
|
|
409
|
-
defaultPlan.min = colRange.min;
|
|
410
|
-
if (colRange.max != null)
|
|
411
|
-
defaultPlan.max = colRange.max;
|
|
412
|
-
}
|
|
413
|
-
if (!strategies.some((s) => s.id === defaultPlan.strategy) || (!col.pk && col.notnull && col.dflt_value == null && (defaultPlan.strategy === 'skip' || defaultPlan.strategy === 'null'))) {
|
|
414
|
-
defaultPlan = (0, strategies_1.fallbackPlanFor)(col);
|
|
415
|
-
}
|
|
416
|
-
return {
|
|
417
|
-
name: col.name,
|
|
418
|
-
type: col.type,
|
|
419
|
-
pk: col.pk > 0,
|
|
420
|
-
notnull: !!col.notnull,
|
|
421
|
-
hasDefault: col.dflt_value != null,
|
|
422
|
-
unique,
|
|
423
|
-
fk,
|
|
424
|
-
strategies,
|
|
425
|
-
defaultPlan,
|
|
426
|
-
};
|
|
427
|
-
});
|
|
428
|
-
}
|
|
429
|
-
const STR_PLAN_KEYS = ['value', 'from', 'to', 'prefix', 'suffix', 'pattern', 'format'];
|
|
430
|
-
const NUM_PLAN_KEYS = ['min', 'max', 'precision', 'minLen', 'maxLen', 'nullPct', 'start', 'step'];
|
|
431
|
-
function sanitizeColumnPlan(raw) {
|
|
432
|
-
if (!raw || typeof raw !== 'object')
|
|
433
|
-
return null;
|
|
434
|
-
const r = raw;
|
|
435
|
-
if (typeof r.strategy !== 'string' || !r.strategy)
|
|
436
|
-
return null;
|
|
437
|
-
const out = { strategy: r.strategy };
|
|
438
|
-
if (r.values !== undefined && r.values !== null && Array.isArray(r.values)) {
|
|
439
|
-
out.values = r.values.map((x) => String(x));
|
|
440
|
-
}
|
|
441
|
-
if (r.jsonKeys !== undefined && r.jsonKeys !== null) {
|
|
442
|
-
const rawKeys = Array.isArray(r.jsonKeys) ? r.jsonKeys.map(String) : String(r.jsonKeys).split(/[,;]/);
|
|
443
|
-
out.jsonKeys = rawKeys.map((s) => s.trim()).filter(Boolean);
|
|
444
|
-
}
|
|
445
|
-
for (const key of STR_PLAN_KEYS) {
|
|
446
|
-
if (r[key] !== undefined && r[key] !== null) {
|
|
447
|
-
out[key] = String(r[key]);
|
|
448
|
-
}
|
|
449
|
-
}
|
|
450
|
-
for (const key of NUM_PLAN_KEYS) {
|
|
451
|
-
if (r[key] !== undefined && r[key] !== null) {
|
|
452
|
-
const n = Number(r[key]);
|
|
453
|
-
if (Number.isFinite(n)) {
|
|
454
|
-
out[key] = n;
|
|
455
|
-
}
|
|
456
|
-
}
|
|
457
|
-
}
|
|
458
|
-
if (r.jsonValues && typeof r.jsonValues === 'object' && !Array.isArray(r.jsonValues)) {
|
|
459
|
-
const jv = {};
|
|
460
|
-
for (const [k, vals] of Object.entries(r.jsonValues)) {
|
|
461
|
-
if (Array.isArray(vals)) {
|
|
462
|
-
const cleaned = vals.map((x) => String(x).trim()).filter(Boolean);
|
|
463
|
-
if (cleaned.length)
|
|
464
|
-
jv[k] = cleaned;
|
|
465
|
-
}
|
|
466
|
-
}
|
|
467
|
-
if (Object.keys(jv).length)
|
|
468
|
-
out.jsonValues = jv;
|
|
469
|
-
}
|
|
470
|
-
return out;
|
|
471
|
-
}
|
|
472
|
-
//# sourceMappingURL=detector.js.map
|
|
1
|
+
Object.defineProperty(exports,"__esModule",{value:!0}),exports.normName=void 0,exports.isTimestampName=isTimestampName,exports.findInMap=findInMap,exports.extractCheckExprs=extractCheckExprs,exports.parseChecks=parseChecks,exports.detectPlan=detectPlan,exports.buildColumnConfigs=function(info){const fkByColumn=new Map(info.foreignKeys.map(fk=>[fk.from,fk])),uniqueCols=new Set,jsonIndexKeys=new Map;for(const ix of info.indexes??[])if(ix.unique&&1===ix.columns.length&&ix.columns[0]&&uniqueCols.add(ix.columns[0]),ix.sql&&/json_extract|->>|->\s*'|json_/i.test(ix.sql))for(const{col:col,keys:keys}of extractJsonColumns(ix.sql)){if(!col)continue;const merged=new Set([...jsonIndexKeys.get(col)??[],...keys]);merged.size&&jsonIndexKeys.set(col,[...merged])}const checkInfo=parseChecks(info.sql??null);return info.columns.map(col=>{const fk=fkByColumn.get(col.name)??null,strategies=(0,strategies_1.strategiesFor)(col,fk),unique=uniqueCols.has(col.name);let defaultPlan=detectPlan(col,fk);if("fk"!==defaultPlan.strategy&&!col.pk&&function(col,hasJsonIndex){if(!(0,strategies_1.isTextishType)(col.type))return!1;if(hasJsonIndex)return!0;const dflt=String(col.dflt_value??"").trim();if(dflt.startsWith("{")||dflt.startsWith("'{\""))return!0;const name=(0,exports.normName)(col.name);return/^(permissions|settings|config|configuration|preferences|prefs|metadata|meta|attributes|payload|options|allowedapps|socialaccounts|positions|fcmtokens|fcm_tokens|scopes|profile|json|jsonb)$/.test(name)||/(^|_)(settings|config|configuration|permissions|prefs|metadata|attributes|payload|options|allowedapps|scopes|profile)$/.test(name)}(col,jsonIndexKeys.has(col.name))){const keys=jsonIndexKeys.get(col.name),useKeys=keys&&keys.length?keys:["scope","enabled","allowedApps"],allowed=findInMap(checkInfo.jsonAllowed,col.name),jsonValues={};if(allowed)for(const k of useKeys){const vals=allowed.get(k);vals&&vals.length&&(jsonValues[k]=vals)}defaultPlan={strategy:"json",jsonKeys:useKeys,...Object.keys(jsonValues).length?{jsonValues:jsonValues}:{}}}const colAllowed=findInMap(checkInfo.columnAllowed,col.name);colAllowed&&colAllowed.length>0&&"fk"!==defaultPlan.strategy&&!col.pk&&(defaultPlan=1===colAllowed.length?{strategy:"fixed",value:colAllowed[0]}:{strategy:"list",values:[...colAllowed]});const colRange=findInMap(checkInfo.columnRange,col.name);return!colRange||"int"!==defaultPlan.strategy&&"decimal"!==defaultPlan.strategy||(null!=colRange.min&&(defaultPlan.min=colRange.min),null!=colRange.max&&(defaultPlan.max=colRange.max)),strategies.some(s=>s.id===defaultPlan.strategy)&&(col.pk||!col.notnull||null!=col.dflt_value||"skip"!==defaultPlan.strategy&&"null"!==defaultPlan.strategy)||(defaultPlan=(0,strategies_1.fallbackPlanFor)(col)),{name:col.name,type:col.type,pk:col.pk>0,notnull:!!col.notnull,hasDefault:null!=col.dflt_value,unique:unique,fk:fk,strategies:strategies,defaultPlan:defaultPlan}})},exports.sanitizeColumnPlan=function(raw){if(!raw||"object"!=typeof raw)return null;const r=raw;if("string"!=typeof r.strategy||!r.strategy)return null;const out={strategy:r.strategy};void 0!==r.values&&null!==r.values&&Array.isArray(r.values)&&(out.values=r.values.map(x=>String(x)));if(void 0!==r.jsonKeys&&null!==r.jsonKeys){const rawKeys=Array.isArray(r.jsonKeys)?r.jsonKeys.map(String):String(r.jsonKeys).split(/[,;]/);out.jsonKeys=rawKeys.map(s=>s.trim()).filter(Boolean)}for(const key of STR_PLAN_KEYS)void 0!==r[key]&&null!==r[key]&&(out[key]=String(r[key]));for(const key of NUM_PLAN_KEYS)if(void 0!==r[key]&&null!==r[key]){const n=Number(r[key]);Number.isFinite(n)&&(out[key]=n)}if(r.jsonValues&&"object"==typeof r.jsonValues&&!Array.isArray(r.jsonValues)){const jv={};for(const[k,vals]of Object.entries(r.jsonValues))if(Array.isArray(vals)){const cleaned=vals.map(x=>String(x).trim()).filter(Boolean);cleaned.length&&(jv[k]=cleaned)}Object.keys(jv).length&&(out.jsonValues=jv)}return out};const strategies_1=require("./strategies");function isTimestampName(name){return/created|updated|modified|registered|joined|timestamp|lastused|lastseen|lastlogin|lastactivity|accessed|viewed|visited|^ts$/.test(name)||/^(created|updated|deleted|archived|occurred|started|ended|expires|published|processed|completed|inserted|requested|resolved|used|seen|accessed|viewed|visited|logged|active)at$/.test(name)}function findInMap(map,colName){if(map.has(colName))return map.get(colName);const lower=colName.toLowerCase();for(const[k,v]of map.entries())if(k.toLowerCase()===lower)return v}function extractCheckExprs(sql){const out=[],re=/CHECK\s*\(/gi;let m;for(;m=re.exec(sql);){let depth=1,i=m.index+m[0].length;const start=i;for(;i<sql.length&&depth>0;){const ch=sql[i];if("'"!==ch){if('"'===ch||"`"===ch||"["===ch){const close="["===ch?"]":ch;for(i+=1;i<sql.length&&sql[i]!==close;)sql[i]===close&&sql[i+1]===close?i+=2:i+=1;i+=1;continue}if("("===ch)depth+=1;else if(")"===ch&&(depth-=1,0===depth))break;i+=1}else for(i+=1;i<sql.length;)if("'"===sql[i]){if("'"!==sql[i+1]){i+=1;break}i+=2}else i+=1}out.push(sql.slice(start,i))}return out}function parseChecks(sql){const info={columnAllowed:new Map,columnRange:new Map,jsonAllowed:new Map,ordering:new Map};if(!sql)return info;const setOrdering=(col,other,key,orEqual)=>{const c=info.ordering.get(col)??{};c[key]={column:other,orEqual:orEqual},info.ordering.set(col,c)},setColumnAllowed=(col,vals)=>{if(!col||!vals.length)return;const existing=findInMap(info.columnAllowed,col);if(existing)for(const v of vals)existing.includes(v)||existing.push(v);else info.columnAllowed.set(col,[...vals])};for(const expr of extractCheckExprs(sql)){const jw1=/(?:"([^"]+)"|`([^`]+)`|\[([^\]]+)\]|([A-Za-z_][A-Za-z0-9_]*))\s*(?:->>|->)\s*'([^']+)'\s*\)*\s*IN\s*\(([^)]*)\)/gi,jw2=/json_extract\s*\(\s*(?:"([^"]+)"|`([^`]+)`|\[([^\]]+)\]|([A-Za-z_][A-Za-z0-9_]*))\s*,\s*'(?:\$\??|\.)?\.?([^']+)'\s*\)\s*\)*\s*IN\s*\(([^)]*)\)/gi;for(const re of[jw1,jw2]){let m;for(;m=re.exec(expr);){const col=m[1]||m[2]||m[3]||m[4],key=m[5],inContent=m[6],strValues=(inContent.match(/'(?:[^']|'')*'/g)??[]).map(s=>s.slice(1,-1).replace(/''/g,"'")),values=strValues.length?strValues:inContent.match(/-?\b\d+(?:\.\d+)?\b/g)??[];if(values.length&&col&&key){const byCol=findInMap(info.jsonAllowed,col)??new Map;byCol.set(key,values),info.jsonAllowed.set(col,byCol)}}}const colIn=/(?:^|[^(->>\w])(?:\(\s*)?(?:(?:lower|upper|trim|coalesce)\s*\(\s*)?(?:"([^"]+)"|`([^`]+)`|\[([^\]]+)\]|([A-Za-z_][A-Za-z0-9_]*))(?:\s*,\s*[^)]+)?\s*\)?\s*\)?\s*IN\s*\(([^)]*)\)/gi;let mColIn;for(;mColIn=colIn.exec(expr);){const col=mColIn[1]||mColIn[2]||mColIn[3]||mColIn[4];if(!col||["json_extract","strftime","datetime","date","length","typeof"].includes(col.toLowerCase()))continue;const matchPos=mColIn.index;if(expr.slice(Math.max(0,matchPos-5),matchPos).includes("->"))continue;const inContent=mColIn[5],strValues=(inContent.match(/'(?:[^']|'')*'/g)??[]).map(s=>s.slice(1,-1).replace(/''/g,"'")),values=strValues.length?strValues:inContent.match(/-?\b\d+(?:\.\d+)?\b/g)??[];values.length&&setColumnAllowed(col,values)}const eqOr=/(?:"([^"]+)"|`([^`]+)`|\[([^\]]+)\]|([A-Za-z_][A-Za-z0-9_]*))\s*=\s*'((?:[^']|'')*)'/gi;let mEq;const eqByCol=new Map;for(;mEq=eqOr.exec(expr);){const col=mEq[1]||mEq[2]||mEq[3]||mEq[4],val=mEq[5].replace(/''/g,"'");if(col&&!["json_extract","lower","upper","trim","strftime","datetime"].includes(col.toLowerCase())){const cur=eqByCol.get(col)??[];cur.includes(val)||cur.push(val),eqByCol.set(col,cur)}}for(const[col,vals]of eqByCol.entries())setColumnAllowed(col,vals);const numCmp1=/(?:"([^"]+)"|`([^`]+)`|\[([^\]]+)\]|([A-Za-z_][A-Za-z0-9_]*))\s*(>=|>|<=|<)\s*(-?\d+(?:\.\d+)?)/g;let mNum1;for(;mNum1=numCmp1.exec(expr);){const col=mNum1[1]||mNum1[2]||mNum1[3]||mNum1[4],op=mNum1[5],val=Number(mNum1[6]);if(col&&Number.isFinite(val)&&!["json_extract","length","strftime","datetime"].includes(col.toLowerCase())){const cur=findInMap(info.columnRange,col)??{};">="===op||">"===op?cur.min=null!=cur.min?Math.max(cur.min,">"===op?val+1:val):">"===op?val+1:val:cur.max=null!=cur.max?Math.min(cur.max,"<"===op?val-1:val):"<"===op?val-1:val,info.columnRange.set(col,cur)}}const ord=/(?:"([^"]+)"|`([^`]+)`|\[([^\]]+)\]|([A-Za-z_][A-Za-z0-9_]*))\s*(>=|<=|>|<)\s*(?:"([^"]+)"|`([^`]+)`|\[([^\]]+)\]|([A-Za-z_][A-Za-z0-9_]*))/g;let m2;for(;m2=ord.exec(expr);){const a=m2[1]||m2[2]||m2[3]||m2[4],op=m2[5],b=m2[6]||m2[7]||m2[8]||m2[9];a&&b&&!/^\d+$/.test(a)&&!/^\d+$/.test(b)&&(["json_extract","strftime","datetime","date","length"].includes(a.toLowerCase())||["json_extract","strftime","datetime","date","length"].includes(b.toLowerCase())||(">"===op||">="===op?(setOrdering(a,b,"after",">="===op),setOrdering(b,a,"before",">="===op)):(setOrdering(a,b,"before","<="===op),setOrdering(b,a,"after","<="===op))))}}return info}exports.normName=s=>String(s).toLowerCase().replace(/[^a-z0-9]/g,"");const isHashName=name=>/^(hash|digest|secret|passphrase)$|tokenhash|passwordhash|passhash|accesskey|apikey|api_key|secretkey|clientsecret|appsecret|appid|privatekey|publickey/.test(name),isTokenName=name=>/^prefix$|tokenprefix|(code|ref|reference|sku|ticketno|ticketnum|orderno|order_no|trackingno|trackingnum|invno|invoiceno|serialno)$/.test(name);function extractJsonColumns(sql){const out=[],push=(col,key)=>{let entry=out.find(e=>e.col===col);if(entry||(entry={col:col,keys:[]},out.push(entry)),key){const last=key.split(".").pop().replace(/[\[\]"]/g,"");last&&!entry.keys.includes(last)&&entry.keys.push(last)}},arrow=/"([^"]+)"\s*(?:->>|->)\s*'([^']+)'|([A-Za-z_][A-Za-z0-9_]*)\s*(?:->>|->)\s*'([^']+)'/g;let m;for(;m=arrow.exec(sql);)push(m[1]||m[3],m[2]||m[4]);const jx=/json_extract\s*\(\s*(?:"([^"]+)"|([A-Za-z_][A-Za-z0-9_]*))\s*,\s*'(?:\$\??|\.)?\.?([^']+)'/g;for(;m=jx.exec(sql);)push(m[1]||m[2],m[3]);return out}const TEXT_PATTERNS=[[/avatar|picture|photo|image|img|thumbnail|icon|logo/,()=>({strategy:"avatar"})],[/company|organization|org|firm|corp|employer|agency/,()=>({strategy:"company"})],[/job|title|role|position|occupation|profession/,()=>({strategy:"job"})],[/currency|curr|currencycode/,()=>({strategy:"currency"})],[/countrycode|countryiso|isocountry|cca2/,()=>({strategy:"countryCode"})],[/state|province|region/,n=>/status|statement/.test(n)?{strategy:"status"}:{strategy:"state"}],[/status|stage|phase|state/,()=>({strategy:"status"})],[/color|colour|theme|hexcolor/,()=>({strategy:"color",format:"hex"})],[/mac|macaddress|hwaddr/,()=>({strategy:"mac"})],[/creditcard|cardnumber|cardno|ccnumber|ccno/,()=>({strategy:"creditCard"})],[/slug|permalink|handle|alias/,()=>({strategy:"slug"})],[/(lastname|surname|familyname)/,()=>({strategy:"last"})],[/email|mail/,()=>({strategy:"email"})],[/(username|login|handle|nick|nickname|account|user)/,()=>({strategy:"username"})],[/(phone|mobile|telephone|cell|fax)/,()=>({strategy:"phone"})],[/city|town/,()=>({strategy:"city"})],[/country|nation/,()=>({strategy:"country"})],[/postal|zip/,()=>({strategy:"postal"})],[/address|street|addr/,()=>({strategy:"address"})],[/url|website|site|link|homepage|href/,()=>({strategy:"url"})],[/domain|host/,()=>({strategy:"domain"})],[/^ip$|ipaddr|ipv4|ip_address/,()=>({strategy:"ip"})],[/bio|about|overview|article|body|post|story/,()=>({strategy:"paragraph"})],[/description|content|comment|message|note|summary|details|remarks/,()=>({strategy:"sentence",minLen:1,maxLen:2})],[/title|subject|category|type|tag|label/,()=>({strategy:"words",minLen:1,maxLen:3})]];function detectPlan(col,fk){const type=(col.type||"").toUpperCase(),rawName=col.name.toLowerCase(),name=(0,exports.normName)(col.name);if(fk)return{strategy:"fk"};if(col.pk)return type.startsWith("INT")||"SERIAL"===type||"BIGSERIAL"===type?{strategy:"skip"}:"TEXT"===type||"BLOB"===type||"UUID"===type?{strategy:"uuid"}:{strategy:"skip"};if("UUID"===type)return{strategy:"uuid"};if("JSON"===type||"JSONB"===type)return{strategy:"json"};if("INET"===type)return{strategy:"ip"};if("BOOLEAN"===type||"BOOL"===type)return{strategy:"bool"};if("BYTEA"===type||"BLOB"===type)return{strategy:"bytes",minLen:8,maxLen:32};if((type.startsWith("INT")||type.startsWith("INTEGER"))&&/(^|_)(is|has|can|should|did)_|_flag$|active|enabled|verified|published|deleted|archived|paid|completed|approved/.test(rawName))return{strategy:"bool"};if("DATE"===type||/^date|birthdate|dob|birthday/.test(rawName))return name.includes("birth")?{strategy:"date",from:"1950-01-01",to:"2000-12-31"}:{strategy:"date",from:"2020-01-01",to:"2026-12-31"};if("DATETIME"===type||"TIMESTAMP"===type||isTimestampName(name))return{strategy:"datetime",from:"2024-01-01T00:00:00",to:"2026-12-31T23:59:59"};if("TIME"===type||"time"===name)return{strategy:"time"};if(type.startsWith("INTEGER")&&/(timestamp|epoch|unix|createdtime|updatedtime)/.test(name))return{strategy:"timestampUnix",format:"sec"};if(/^(lat|latitude)$/.test(name))return{strategy:"latitude"};if(/^(lng|lon|longitude)$/.test(name))return{strategy:"longitude"};if(type.startsWith("INTEGER"))return name.includes("year")?{strategy:"int",min:1990,max:2026}:name.includes("age")?{strategy:"int",min:18,max:90}:/(count|quantity|qty|stock|views|likes|total|num|number)$/.test(name)?{strategy:"int",min:0,max:1e5}:name.includes("rating")||name.includes("score")?{strategy:"int",min:1,max:5}:/(order|rank|position|seq|sequence|priority|sort|step)$/.test(name)?{strategy:"sequence",start:1,step:1}:{strategy:"int",min:1,max:1e3};if("REAL"===type||type.includes("DECIMAL")||type.includes("NUMERIC")||type.includes("FLOAT")||type.includes("DOUBLE"))return/(price|cost|amount|total|salary|balance|fee|charge|budget)/.test(name)?{strategy:"decimal",min:1,max:5e3,precision:2}:name.includes("rating")?{strategy:"decimal",min:1,max:5,precision:1}:{strategy:"decimal",min:1,max:1e3,precision:2};if("BLOB"===type)return{strategy:"bytes",minLen:8,maxLen:32};if(/currency|curr|currencycode/.test(name))return{strategy:"currency"};if(/countrycode|countryiso|isocountry|cca2/.test(name))return{strategy:"countryCode"};if(/state|province|region/.test(name)&&!/status|statement/.test(name))return{strategy:"state"};if(/status|stage|phase|state/.test(name))return{strategy:"status"};if(/color|colour|theme|hexcolor/.test(name))return{strategy:"color",format:"hex"};if(/mac|macaddress|hwaddr/.test(name))return{strategy:"mac"};if(/creditcard|cardnumber|cardno|ccnumber|ccno/.test(name))return{strategy:"creditCard"};if(/slug|permalink|handle|alias/.test(name))return{strategy:"slug"};if(isHashName(name))return{strategy:"hash",minLen:32,maxLen:64};if(isTokenName(name))return{strategy:"token",minLen:6,maxLen:12};if(/uuid|guid/.test(name)||"id"===name||"uid"===name||"key"===name)return{strategy:"uuid"};if(name.includes("first")&&name.includes("name"))return{strategy:"first"};if(/(lastname|surname|familyname)/.test(name)||name.includes("last")&&name.includes("name"))return{strategy:"last"};if("name"===name||"fullname"===name||name.includes("full")&&name.includes("name"))return{strategy:"fullname"};for(const[pattern,createPlan]of TEXT_PATTERNS)if(pattern.test(name))return createPlan(name);return{strategy:"words",minLen:1,maxLen:4}}const STR_PLAN_KEYS=["value","from","to","prefix","suffix","pattern","format"],NUM_PLAN_KEYS=["min","max","precision","minLen","maxLen","nullPct","start","step"];
|
package/dist/data/engine.d.ts
CHANGED
|
@@ -1,10 +1 @@
|
|
|
1
|
-
import type {
|
|
2
|
-
import { type ColumnGeneratorConfig, type ColumnPlan, type GenerateResult } from './types';
|
|
3
|
-
/**
|
|
4
|
-
* Generate `count` rows for a table with structured previews.
|
|
5
|
-
*/
|
|
6
|
-
export declare function generateRows(db: IDatabase, info: TableInfoData, configs: ColumnGeneratorConfig[], count: number, plan?: Record<string, ColumnPlan>): Promise<GenerateResult>;
|
|
7
|
-
/**
|
|
8
|
-
* Render generated rows as a sequence of INSERT statements for preview.
|
|
9
|
-
*/
|
|
10
|
-
export declare function buildSeedInsertSql(table: string, rows: WhereClause[][]): string;
|
|
1
|
+
import type {IDatabase,TableInfoData,WhereClause} from '../db/index';import{type ColumnGeneratorConfig,type ColumnPlan,type GenerateResult} from './types';export declare function generateRows(db:IDatabase,info:TableInfoData,configs:ColumnGeneratorConfig[],count:number,plan?:Record<string,ColumnPlan>):Promise<GenerateResult>;export declare function buildSeedInsertSql(table:string,rows:WhereClause[][]):string;
|