introspectron 0.2.12 → 2.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/process.js ADDED
@@ -0,0 +1,282 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.introspectionResultsFromRaw = void 0;
4
+ // @ts-nocheck
5
+ const utils_1 = require("./utils");
6
+ const removeQuotes = (str) => {
7
+ const trimmed = str.trim();
8
+ if (trimmed[0] === '"') {
9
+ if (trimmed[trimmed.length - 1] !== '"') {
10
+ throw new Error(`We failed to parse a quoted identifier '${str}'. Please avoid putting quotes or commas in smart comment identifiers (or file a PR to fix the parser).`);
11
+ }
12
+ return trimmed.substr(1, trimmed.length - 2);
13
+ }
14
+ else {
15
+ // PostgreSQL lower-cases unquoted columns, so we should too.
16
+ return trimmed.toLowerCase();
17
+ }
18
+ };
19
+ const parseSqlColumnArray = (str) => {
20
+ if (!str) {
21
+ throw new Error(`Cannot parse '${str}'`);
22
+ }
23
+ const parts = str.split(',');
24
+ return parts.map(removeQuotes);
25
+ };
26
+ const parseSqlColumnString = (str) => {
27
+ if (!str) {
28
+ throw new Error(`Cannot parse '${str}'`);
29
+ }
30
+ return removeQuotes(str);
31
+ };
32
+ function parseConstraintSpec(rawSpec) {
33
+ const [spec, ...tagComponents] = rawSpec.split(/\|/);
34
+ const parsed = (0, utils_1.parseTags)(tagComponents.join('\n'));
35
+ return {
36
+ spec,
37
+ tags: parsed.tags,
38
+ description: parsed.text
39
+ };
40
+ }
41
+ function smartCommentConstraints(introspectionResults) {
42
+ const attributesByNames = (tbl, cols, debugStr) => {
43
+ const attributes = introspectionResults.attribute
44
+ .filter((a) => a.classId === tbl.id)
45
+ .sort((a, b) => a.num - b.num);
46
+ if (!cols) {
47
+ const pk = introspectionResults.constraint.find((c) => c.classId == tbl.id && c.type === 'p');
48
+ if (pk) {
49
+ return pk.keyAttributeNums.map((n) => attributes.find((a) => a.num === n));
50
+ }
51
+ else {
52
+ throw new Error(`No columns specified for '${tbl.namespaceName}.${tbl.name}' (oid: ${tbl.id}) and no PK found (${debugStr}).`);
53
+ }
54
+ }
55
+ return cols.map((colName) => {
56
+ const attr = attributes.find((a) => a.name === colName);
57
+ if (!attr) {
58
+ throw new Error(`Could not find attribute '${colName}' in '${tbl.namespaceName}.${tbl.name}'`);
59
+ }
60
+ return attr;
61
+ });
62
+ };
63
+ // First: primary keys
64
+ introspectionResults.class.forEach((klass) => {
65
+ const namespace = introspectionResults.namespace.find((n) => n.id === klass.namespaceId);
66
+ if (!namespace) {
67
+ return;
68
+ }
69
+ if (klass.tags.primaryKey) {
70
+ if (typeof klass.tags.primaryKey !== 'string') {
71
+ throw new Error(`@primaryKey configuration of '${klass.namespaceName}.${klass.name}' is invalid; please specify just once "@primaryKey col1,col2"`);
72
+ }
73
+ const { spec: pkSpec, tags, description } = parseConstraintSpec(klass.tags.primaryKey);
74
+ const columns = parseSqlColumnArray(pkSpec);
75
+ const attributes = attributesByNames(klass, columns, `@primaryKey ${klass.tags.primaryKey}`);
76
+ attributes.forEach((attr) => {
77
+ attr.tags.notNull = true;
78
+ });
79
+ const keyAttributeNums = attributes.map((a) => a.num);
80
+ // Now we need to fake a constraint for this:
81
+ const fakeConstraint = {
82
+ kind: 'constraint',
83
+ isFake: true,
84
+ isIndexed: true, // otherwise it gets ignored by ignoreIndexes
85
+ id: Math.random(),
86
+ name: `FAKE_${klass.namespaceName}_${klass.name}_primaryKey`,
87
+ type: 'p', // primary key
88
+ classId: klass.id,
89
+ foreignClassId: null,
90
+ comment: null,
91
+ description,
92
+ keyAttributeNums,
93
+ foreignKeyAttributeNums: null,
94
+ tags
95
+ };
96
+ introspectionResults.constraint.push(fakeConstraint);
97
+ }
98
+ });
99
+ // Now primary keys are in place, we can apply foreign keys
100
+ introspectionResults.class.forEach((klass) => {
101
+ const namespace = introspectionResults.namespace.find((n) => n.id === klass.namespaceId);
102
+ if (!namespace) {
103
+ return;
104
+ }
105
+ const getType = () => introspectionResults.type.find((t) => t.id === klass.typeId);
106
+ const foreignKey = klass.tags.foreignKey || getType().tags.foreignKey;
107
+ if (foreignKey) {
108
+ const foreignKeys = typeof foreignKey === 'string' ? [foreignKey] : foreignKey;
109
+ if (!Array.isArray(foreignKeys)) {
110
+ throw new Error(`Invalid foreign key smart comment specified on '${klass.namespaceName}.${klass.name}'`);
111
+ }
112
+ foreignKeys.forEach((fkSpecRaw, index) => {
113
+ if (typeof fkSpecRaw !== 'string') {
114
+ throw new Error(`Invalid foreign key spec (${index}) on '${klass.namespaceName}.${klass.name}'`);
115
+ }
116
+ const { spec: fkSpec, tags, description } = parseConstraintSpec(fkSpecRaw);
117
+ const matches = fkSpec.match(/^\(([^()]+)\) references ([^().]+)(?:\.([^().]+))?(?:\s*\(([^()]+)\))?$/i);
118
+ if (!matches) {
119
+ throw new Error(`Invalid foreignKey syntax for '${klass.namespaceName}.${klass.name}'; expected something like "(col1,col2) references schema.table (c1, c2)", you passed '${fkSpecRaw}'`);
120
+ }
121
+ const [, rawColumns, rawSchemaOrTable, rawTableOnly, rawForeignColumns] = matches;
122
+ const rawSchema = rawTableOnly
123
+ ? rawSchemaOrTable
124
+ : `"${klass.namespaceName}"`;
125
+ const rawTable = rawTableOnly || rawSchemaOrTable;
126
+ const columns = parseSqlColumnArray(rawColumns);
127
+ const foreignSchema = parseSqlColumnString(rawSchema);
128
+ const foreignTable = parseSqlColumnString(rawTable);
129
+ const foreignColumns = rawForeignColumns
130
+ ? parseSqlColumnArray(rawForeignColumns)
131
+ : null;
132
+ const foreignKlass = introspectionResults.class.find((k) => k.name === foreignTable && k.namespaceName === foreignSchema);
133
+ if (!foreignKlass) {
134
+ throw new Error(`@foreignKey smart comment referenced non-existant table/view '${foreignSchema}'.'${foreignTable}'. Note that this reference must use *database names* (i.e. it does not respect @name). (${fkSpecRaw})`);
135
+ }
136
+ const foreignNamespace = introspectionResults.namespace.find((n) => n.id === foreignKlass.namespaceId);
137
+ if (!foreignNamespace) {
138
+ return;
139
+ }
140
+ const keyAttributeNums = attributesByNames(klass, columns, `@foreignKey ${fkSpecRaw}`).map((a) => a.num);
141
+ const foreignKeyAttributeNums = attributesByNames(foreignKlass, foreignColumns, `@foreignKey ${fkSpecRaw}`).map((a) => a.num);
142
+ // Now we need to fake a constraint for this:
143
+ const fakeConstraint = {
144
+ kind: 'constraint',
145
+ isFake: true,
146
+ isIndexed: true, // otherwise it gets ignored by ignoreIndexes
147
+ id: Math.random(),
148
+ name: `FAKE_${klass.namespaceName}_${klass.name}_foreignKey_${index}`,
149
+ type: 'f', // foreign key
150
+ classId: klass.id,
151
+ foreignClassId: foreignKlass.id,
152
+ comment: null,
153
+ description,
154
+ keyAttributeNums,
155
+ foreignKeyAttributeNums,
156
+ tags
157
+ };
158
+ introspectionResults.constraint.push(fakeConstraint);
159
+ });
160
+ }
161
+ });
162
+ }
163
+ const introspectionResultsFromRaw = (rawResults, pgAugmentIntrospectionResults) => {
164
+ const introspectionResultsByKind = (0, utils_1.deepClone)(rawResults);
165
+ const xByY = (arrayOfX, attrKey) => arrayOfX.reduce((memo, x) => {
166
+ memo[x[attrKey]] = x;
167
+ return memo;
168
+ }, {});
169
+ const xByYAndZ = (arrayOfX, attrKey, attrKey2) => arrayOfX.reduce((memo, x) => {
170
+ if (!memo[x[attrKey]])
171
+ memo[x[attrKey]] = {};
172
+ memo[x[attrKey]][x[attrKey2]] = x;
173
+ return memo;
174
+ }, {});
175
+ introspectionResultsByKind.namespaceById = xByY(introspectionResultsByKind.namespace, 'id');
176
+ introspectionResultsByKind.classById = xByY(introspectionResultsByKind.class, 'id');
177
+ introspectionResultsByKind.typeById = xByY(introspectionResultsByKind.type, 'id');
178
+ introspectionResultsByKind.attributeByClassIdAndNum = xByYAndZ(introspectionResultsByKind.attribute, 'classId', 'num');
179
+ introspectionResultsByKind.extensionById = xByY(introspectionResultsByKind.extension, 'id');
180
+ const relate = (array, newAttr, lookupAttr, lookup, missingOk = false) => {
181
+ array.forEach((entry) => {
182
+ const key = entry[lookupAttr];
183
+ if (Array.isArray(key)) {
184
+ entry[newAttr] = key
185
+ .map((innerKey) => {
186
+ const result = lookup[innerKey];
187
+ if (innerKey && !result) {
188
+ if (missingOk) {
189
+ return;
190
+ }
191
+ throw new Error(`Could not look up '${newAttr}' by '${lookupAttr}' ('${innerKey}') on '${JSON.stringify(entry)}'`);
192
+ }
193
+ return result;
194
+ })
195
+ .filter((_) => _);
196
+ }
197
+ else {
198
+ const result = lookup[key];
199
+ if (key && !result) {
200
+ if (missingOk) {
201
+ return;
202
+ }
203
+ throw new Error(`Could not look up '${newAttr}' by '${lookupAttr}' on '${JSON.stringify(entry)}'`);
204
+ }
205
+ entry[newAttr] = result;
206
+ }
207
+ });
208
+ };
209
+ const augment = (introspectionResults) => {
210
+ [pgAugmentIntrospectionResults, smartCommentConstraints].forEach((fn) => fn ? fn(introspectionResults) : null);
211
+ };
212
+ augment(introspectionResultsByKind);
213
+ relate(introspectionResultsByKind.class, 'namespace', 'namespaceId', introspectionResultsByKind.namespaceById, true // Because it could be a type defined in a different namespace - which is fine so long as we don't allow querying it directly
214
+ );
215
+ relate(introspectionResultsByKind.class, 'type', 'typeId', introspectionResultsByKind.typeById);
216
+ relate(introspectionResultsByKind.attribute, 'class', 'classId', introspectionResultsByKind.classById);
217
+ relate(introspectionResultsByKind.attribute, 'type', 'typeId', introspectionResultsByKind.typeById);
218
+ relate(introspectionResultsByKind.procedure, 'namespace', 'namespaceId', introspectionResultsByKind.namespaceById);
219
+ relate(introspectionResultsByKind.type, 'class', 'classId', introspectionResultsByKind.classById, true);
220
+ relate(introspectionResultsByKind.type, 'domainBaseType', 'domainBaseTypeId', introspectionResultsByKind.typeById, true // Because not all types are domains
221
+ );
222
+ relate(introspectionResultsByKind.type, 'arrayItemType', 'arrayItemTypeId', introspectionResultsByKind.typeById, true // Because not all types are arrays
223
+ );
224
+ relate(introspectionResultsByKind.constraint, 'class', 'classId', introspectionResultsByKind.classById);
225
+ relate(introspectionResultsByKind.constraint, 'foreignClass', 'foreignClassId', introspectionResultsByKind.classById, true // Because many constraints don't apply to foreign classes
226
+ );
227
+ relate(introspectionResultsByKind.extension, 'namespace', 'namespaceId', introspectionResultsByKind.namespaceById, true // Because the extension could be a defined in a different namespace
228
+ );
229
+ relate(introspectionResultsByKind.extension, 'configurationClasses', 'configurationClassIds', introspectionResultsByKind.classById, true // Because the configuration table could be a defined in a different namespace
230
+ );
231
+ relate(introspectionResultsByKind.index, 'class', 'classId', introspectionResultsByKind.classById);
232
+ // Reverse arrayItemType -> arrayType
233
+ introspectionResultsByKind.type.forEach((type) => {
234
+ if (type.arrayItemType) {
235
+ type.arrayItemType.arrayType = type;
236
+ }
237
+ });
238
+ // Table/type columns / constraints
239
+ introspectionResultsByKind.class.forEach((klass) => {
240
+ klass.attributes = introspectionResultsByKind.attribute.filter((attr) => attr.classId === klass.id);
241
+ klass.canUseAsterisk = !klass.attributes.some((attr) => attr.columnLevelSelectGrant);
242
+ klass.constraints = introspectionResultsByKind.constraint.filter((constraint) => constraint.classId === klass.id);
243
+ klass.foreignConstraints = introspectionResultsByKind.constraint.filter((constraint) => constraint.foreignClassId === klass.id);
244
+ klass.primaryKeyConstraint = klass.constraints.find((constraint) => constraint.type === 'p');
245
+ });
246
+ // Constraint attributes
247
+ introspectionResultsByKind.constraint.forEach((constraint) => {
248
+ if (constraint.keyAttributeNums && constraint.class) {
249
+ constraint.keyAttributes = constraint.keyAttributeNums.map((nr) => constraint.class.attributes.find((attr) => attr.num === nr));
250
+ }
251
+ else {
252
+ constraint.keyAttributes = [];
253
+ }
254
+ if (constraint.foreignKeyAttributeNums && constraint.foreignClass) {
255
+ constraint.foreignKeyAttributes = constraint.foreignKeyAttributeNums.map((nr) => constraint.foreignClass.attributes.find((attr) => attr.num === nr));
256
+ }
257
+ else {
258
+ constraint.foreignKeyAttributes = [];
259
+ }
260
+ });
261
+ // Detect which columns and constraints are indexed
262
+ introspectionResultsByKind.index.forEach((index) => {
263
+ const columns = index.attributeNums.map((nr) => index.class.attributes.find((attr) => attr.num === nr));
264
+ // Indexed column (for orderBy / filter):
265
+ if (columns[0]) {
266
+ columns[0].isIndexed = true;
267
+ }
268
+ if (columns[0] && columns.length === 1 && index.isUnique) {
269
+ columns[0].isUnique = true;
270
+ }
271
+ // Indexed constraints (for reverse relations):
272
+ index.class.constraints
273
+ .filter((constraint) => constraint.type === 'f')
274
+ .forEach((constraint) => {
275
+ if (constraint.keyAttributeNums.every((nr, idx) => index.attributeNums[idx] === nr)) {
276
+ constraint.isIndexed = true;
277
+ }
278
+ });
279
+ });
280
+ return introspectionResultsByKind;
281
+ };
282
+ exports.introspectionResultsFromRaw = introspectionResultsFromRaw;
package/query.d.ts ADDED
@@ -0,0 +1 @@
1
+ export declare const makeIntrospectionQuery: (serverVersionNum: any, options?: {}) => string;