-
Notifications
You must be signed in to change notification settings - Fork 2.8k
/
utils.js
661 lines (610 loc) · 18.3 KB
/
utils.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
import {
TABLE_ENUMS_SUPPORT,
CUSTOM_GRAPHQL_FIELDS_SUPPORT,
READ_ONLY_RUN_SQL_QUERIES,
checkFeatureSupport,
} from '../../../helpers/versionUtils';
export const INTEGER = 'integer';
export const SERIAL = 'serial';
export const BIGINT = 'bigint';
export const BIGSERIAL = 'bigserial';
export const UUID = 'uuid';
export const JSONDTYPE = 'json';
export const JSONB = 'jsonb';
export const TIMESTAMP = 'timestamp with time zone';
export const TIME = 'time with time zone';
export const NUMERIC = 'numeric';
export const DATE = 'date';
export const TIMETZ = 'timetz';
export const BOOLEAN = 'boolean';
export const TEXT = 'text';
export const getPlaceholder = type => {
switch (type) {
case TIMESTAMP:
return new Date().toISOString();
case DATE:
return new Date().toISOString().slice(0, 10);
case TIME:
const time = new Date().toISOString().slice(11, 19);
return `${time}Z or ${time}+05:30`;
case JSONDTYPE:
return '{"name": "foo"} or [12, "bar"]';
case JSONB:
return '{"name": "foo"} or [12, "bar"]';
case BOOLEAN:
return '';
default:
return type;
}
};
export const tabNameMap = {
browse: 'Browse Rows',
insert: 'Insert Row',
edit: 'Edit Row',
modify: 'Modify',
relationships: 'Relationships',
permissions: 'Permissions',
};
export const ordinalColSort = (a, b) => {
if (a.ordinal_position < b.ordinal_position) {
return -1;
}
if (a.ordinal_position > b.ordinal_position) {
return 1;
}
return 0;
};
const findFKConstraint = (curTable, column) => {
const fkConstraints = curTable.foreign_key_constraints;
return fkConstraints.find(
fk =>
Object.keys(fk.column_mapping).length === column.length &&
Object.keys(fk.column_mapping).join(',') === column.join(',')
);
};
const findOppFKConstraint = (curTable, column) => {
const fkConstraints = curTable.opp_foreign_key_constraints;
return fkConstraints.find(
fk =>
Object.keys(fk.column_mapping).length === column.length &&
Object.keys(fk.column_mapping).join(',') === column.join(',')
);
};
export const findTableFromRel = (schemas, curTable, rel) => {
let rTable = null;
let rSchema = 'public';
// for view
if (rel.rel_def.manual_configuration !== undefined) {
rTable = rel.rel_def.manual_configuration.remote_table;
if (rTable.schema) {
rSchema = rTable.schema;
rTable = rTable.name;
}
}
// for table
if (rel.rel_def.foreign_key_constraint_on !== undefined) {
// for object relationship
if (rel.rel_type === 'object') {
const column = [rel.rel_def.foreign_key_constraint_on];
const fkc = findFKConstraint(curTable, column);
if (fkc) {
rTable = fkc.ref_table;
rSchema = fkc.ref_table_table_schema;
}
}
// for array relationship
if (rel.rel_type === 'array') {
rTable = rel.rel_def.foreign_key_constraint_on.table;
if (rTable.schema) {
rSchema = rTable.schema;
rTable = rTable.name;
}
}
}
return schemas.find(
x => x.table_name === rTable && x.table_schema === rSchema
);
};
export const findAllFromRel = (schemas, curTable, rel) => {
const relMeta = {
relName: rel.rel_name,
lTable: rel.table_name,
lSchema: rel.table_schema,
isObjRel: rel.rel_type === 'object',
lcol: null,
rcol: null,
rTable: null,
rSchema: null,
};
// for view
if (rel.rel_def.manual_configuration !== undefined) {
const rTableConfig = rel.rel_def.manual_configuration.remote_table;
if (rTableConfig.schema) {
relMeta.rTable = rTableConfig.name;
relMeta.rSchema = rTableConfig.schema;
} else {
relMeta.rTable = rTableConfig;
relMeta.rSchema = 'public';
}
const columnMapping = rel.rel_def.manual_configuration.column_mapping;
relMeta.lcol = Object.keys(columnMapping);
relMeta.rcol = relMeta.lcol.map(column => columnMapping[column]);
}
// for table
const foreignKeyConstraintOn = rel.rel_def.foreign_key_constraint_on;
if (foreignKeyConstraintOn !== undefined) {
// for object relationship
if (rel.rel_type === 'object') {
relMeta.lcol = [foreignKeyConstraintOn];
const fkc = findFKConstraint(curTable, relMeta.lcol);
if (fkc) {
relMeta.rTable = fkc.ref_table;
relMeta.rSchema = fkc.ref_table_table_schema;
relMeta.rcol = [fkc.column_mapping[relMeta.lcol]];
}
}
// for array relationship
if (rel.rel_type === 'array') {
relMeta.rcol = [foreignKeyConstraintOn.column];
const rTableConfig = foreignKeyConstraintOn.table;
if (rTableConfig.schema) {
relMeta.rTable = rTableConfig.name;
relMeta.rSchema = rTableConfig.schema;
} else {
relMeta.rTable = rTableConfig;
relMeta.rSchema = 'public';
}
const rfkc = findOppFKConstraint(curTable, relMeta.rcol);
relMeta.lcol = [rfkc.column_mapping[relMeta.rcol]];
}
}
return relMeta;
};
export const getIngForm = string => {
return (
(string[string.length - 1] === 'e'
? string.slice(0, string.length - 1)
: string) + 'ing'
);
};
export const getEdForm = string => {
return (
(string[string.length - 1] === 'e'
? string.slice(0, string.length - 1)
: string) + 'ed'
);
};
export const escapeRegExp = string => {
return string.replace(/([.*+?^${}()|[\]\\])/g, '\\$1');
};
export const getTableName = t => {
const typ = typeof t;
if (typ === 'string') {
return t;
} else if (typ === 'object') {
return 'name' in t ? t.name : '';
}
return '';
};
export const fetchTrackedTableListQuery = options => {
const query = {
type: 'select',
args: {
table: {
name: 'hdb_table',
schema: 'hdb_catalog',
},
columns: [
'table_schema',
'table_name',
{
name: 'primary_key',
columns: ['*'],
},
{
name: 'relationships',
columns: ['*'],
},
{
name: 'permissions',
columns: ['*'],
},
{
name: 'unique_constraints',
columns: ['*'],
},
{
name: 'check_constraints',
columns: ['*'],
order_by: {
column: 'constraint_name',
type: 'asc',
},
},
],
order_by: [{ column: 'table_name', type: 'asc' }],
},
};
if (checkFeatureSupport(TABLE_ENUMS_SUPPORT)) {
query.args.columns.push('is_enum');
}
if (checkFeatureSupport(CUSTOM_GRAPHQL_FIELDS_SUPPORT)) {
query.args.columns.push('configuration');
}
if (
(options.schemas && options.schemas.length !== 0) ||
(options.tables && options.tables.length !== 0)
) {
query.where = {
$or: [],
};
}
if (options.schemas) {
options.schemas.forEach(schemaName => {
query.where.$or.push({
table_schema: schemaName,
});
});
}
if (options.tables) {
options.tables.forEach(tableInfo => {
query.where.$or.push({
table_schema: tableInfo.table_schema,
table_name: tableInfo.table_name,
});
});
}
return query;
};
const generateWhereClause = options => {
let whereClause = '';
const whereCondtions = [];
if (options.schemas) {
options.schemas.forEach(schemaName => {
whereCondtions.push(`(ist.table_schema='${schemaName}')`);
});
}
if (options.tables) {
options.tables.forEach(tableInfo => {
whereCondtions.push(
`(ist.table_schema='${tableInfo.table_schema}' and ist.table_name='${
tableInfo.table_name
}')`
);
});
}
if (whereCondtions.length > 0) {
whereClause = 'where';
}
whereCondtions.forEach((whereInfo, index) => {
whereClause = whereClause + ` ${whereInfo}`;
if (index + 1 !== whereCondtions.length) {
whereClause = whereClause + ' or';
}
});
return whereClause;
};
export const fetchTrackedTableFkQuery = options => {
const whereQuery = generateWhereClause(options);
const runSql = `select
COALESCE(
json_agg(
row_to_json(info)
),
'[]' :: JSON
) AS tables
FROM
(
select
hdb_fkc.*,
fk_ref_table.table_name IS NOT NULL AS is_ref_table_tracked
from
hdb_catalog.hdb_table AS ist
JOIN hdb_catalog.hdb_foreign_key_constraint AS hdb_fkc ON hdb_fkc.table_schema = ist.table_schema
and hdb_fkc.table_name = ist.table_name
LEFT OUTER JOIN hdb_catalog.hdb_table AS fk_ref_table ON fk_ref_table.table_schema = hdb_fkc.ref_table_table_schema
and fk_ref_table.table_name = hdb_fkc.ref_table
${whereQuery}
) as info
`;
return {
type: 'run_sql',
args: {
sql: runSql,
read_only: checkFeatureSupport(READ_ONLY_RUN_SQL_QUERIES) ? true : false,
},
};
};
export const fetchTrackedTableReferencedFkQuery = options => {
const whereQuery = generateWhereClause(options);
const runSql = `select
COALESCE(
json_agg(
row_to_json(info)
),
'[]' :: JSON
) AS tables
FROM
(
select DISTINCT ON (hdb_fkc.constraint_oid)
hdb_fkc.*,
fk_ref_table.table_name IS NOT NULL AS is_table_tracked,
hdb_uc.constraint_name IS NOT NULL AS is_unique
from
hdb_catalog.hdb_table AS ist
JOIN hdb_catalog.hdb_foreign_key_constraint AS hdb_fkc ON hdb_fkc.ref_table_table_schema = ist.table_schema
and hdb_fkc.ref_table = ist.table_name
LEFT OUTER JOIN hdb_catalog.hdb_table AS fk_ref_table ON fk_ref_table.table_schema = hdb_fkc.table_schema
and fk_ref_table.table_name = hdb_fkc.table_name
LEFT OUTER JOIN hdb_catalog.hdb_unique_constraint AS hdb_uc ON hdb_uc.table_schema = hdb_fkc.table_schema
and hdb_uc.table_name = hdb_fkc.table_name and ARRAY(select json_array_elements_text(hdb_uc.columns) ORDER BY json_array_elements_text) = ARRAY(select json_object_keys(hdb_fkc.column_mapping) ORDER BY json_object_keys)
${whereQuery}
) as info
`;
return {
type: 'run_sql',
args: {
sql: runSql,
read_only: checkFeatureSupport(READ_ONLY_RUN_SQL_QUERIES) ? true : false,
},
};
};
export const fetchTableListQuery = options => {
const whereQuery = generateWhereClause(options);
// TODO: optimise this. Multiple OUTER JOINS causes data bloating
const runSql = `
select
COALESCE(
json_agg(
row_to_json(info)
),
'[]' :: JSON
) AS tables
FROM
(
select
ist.table_schema,
ist.table_name,
ist.table_type,
obj_description(
(
quote_ident(ist.table_schema) || '.' || quote_ident(ist.table_name)
):: regclass,
'pg_class'
) AS comment,
COALESCE(json_agg(
DISTINCT row_to_json(is_columns) :: JSONB || jsonb_build_object(
'comment',
(
SELECT
pg_catalog.col_description(
c.oid, is_columns.ordinal_position :: int
)
FROM
pg_catalog.pg_class c
WHERE
c.oid = (quote_ident(ist.table_schema) || '.' || quote_ident(ist.table_name)):: regclass :: oid
AND c.relname = is_columns.table_name
)
)
) FILTER (WHERE is_columns.column_name IS NOT NULL), '[]' :: JSON) AS columns,
COALESCE(json_agg(
DISTINCT row_to_json(is_triggers) :: JSONB || jsonb_build_object(
'comment',
(
SELECT description FROM pg_description JOIN pg_trigger ON pg_description.objoid = pg_trigger.oid
WHERE
tgname = is_triggers.trigger_name
AND tgrelid = (quote_ident(is_triggers.event_object_schema) || '.' || quote_ident(is_triggers.event_object_table)):: regclass :: oid
)
)
) FILTER (WHERE is_triggers.trigger_name IS NOT NULL), '[]' :: JSON) AS triggers,
row_to_json(is_views) AS view_info
FROM
information_schema.tables AS ist
LEFT OUTER JOIN information_schema.columns AS is_columns ON
is_columns.table_schema = ist.table_schema
AND is_columns.table_name = ist.table_name
LEFT OUTER JOIN information_schema.views AS is_views ON is_views.table_schema = ist.table_schema
AND is_views.table_name = ist.table_name
LEFT OUTER JOIN information_schema.triggers AS is_triggers ON
is_triggers.event_object_schema = ist.table_schema AND
is_triggers.event_object_table = ist.table_name
${whereQuery}
GROUP BY
ist.table_schema,
ist.table_name,
ist.table_type,
is_views.*
) AS info
`;
return {
type: 'run_sql',
args: {
sql: runSql,
read_only: checkFeatureSupport(READ_ONLY_RUN_SQL_QUERIES) ? true : false,
},
};
};
export const mergeLoadSchemaData = (
infoSchemaTableData,
hdbTableData,
fkData,
refFkData
) => {
const _mergedTableData = [];
infoSchemaTableData.forEach(infoSchemaTableInfo => {
const _tableSchema = infoSchemaTableInfo.table_schema;
const _tableName = infoSchemaTableInfo.table_name;
const trackedTableInfo = hdbTableData.find(
t => t.table_schema === _tableSchema && t.table_name === _tableName
);
const _isTableTracked = trackedTableInfo ? true : false;
const _columns = infoSchemaTableInfo.columns;
const _comment = infoSchemaTableInfo.comment;
const _tableType = infoSchemaTableInfo.table_type;
const _triggers = infoSchemaTableInfo.triggers; // TODO: get from v1/query
const _viewInfo = infoSchemaTableInfo.view_info; // TODO: get from v1/query
let _primaryKey = null;
let _relationships = [];
let _permissions = [];
let _uniqueConstraints = [];
let _fkConstraints = [];
let _refFkConstraints = [];
let _isEnum = false;
let _checkConstraints = [];
let _configuration = {};
if (_isTableTracked) {
_primaryKey = trackedTableInfo.primary_key;
_relationships = trackedTableInfo.relationships;
_permissions = trackedTableInfo.permissions;
_uniqueConstraints = trackedTableInfo.unique_constraints;
_isEnum = trackedTableInfo.is_enum;
_checkConstraints = trackedTableInfo.check_constraints;
_configuration = trackedTableInfo.configuration;
_fkConstraints = fkData.filter(
fk => fk.table_schema === _tableSchema && fk.table_name === _tableName
);
_refFkConstraints = refFkData.filter(
fk =>
fk.ref_table_table_schema === _tableSchema &&
fk.ref_table === _tableName
);
}
const _mergedInfo = {
table_schema: _tableSchema,
table_name: _tableName,
table_type: _tableType,
is_table_tracked: _isTableTracked,
columns: _columns,
comment: _comment,
triggers: _triggers,
primary_key: _primaryKey,
relationships: _relationships,
permissions: _permissions,
unique_constraints: _uniqueConstraints,
check_constraints: _checkConstraints,
foreign_key_constraints: _fkConstraints,
opp_foreign_key_constraints: _refFkConstraints,
view_info: _viewInfo,
is_enum: _isEnum,
configuration: _configuration,
};
_mergedTableData.push(_mergedInfo);
});
return _mergedTableData;
};
export const commonDataTypes = [
{
name: 'Integer',
value: 'integer',
description: 'signed four-byte integer',
hasuraDatatype: 'integer',
},
{
name: 'Integer (auto-increment)',
value: 'serial',
description: 'autoincrementing four-byte integer',
hasuraDatatype: null,
},
{
name: 'Text',
value: 'text',
description: 'variable-length character string',
hasuraDatatype: 'text',
},
{
name: 'Boolean',
value: 'boolean',
description: 'logical Boolean (true/false)',
hasuraDatatype: 'boolean',
},
{
name: 'Numeric',
value: 'numeric',
description: 'exact numeric of selected precision',
hasuraDatatype: 'numeric',
},
{
name: 'Timestamp',
value: 'timestamptz',
description: 'date and time, including time zone',
hasuraDatatype: 'timestamp with time zone',
},
{
name: 'Time',
value: 'timetz',
description: 'time of day (no time zone)',
hasuraDatatype: 'time with time zone',
},
{
name: 'Date',
value: 'date',
description: 'calendar date (year, month, day)',
hasuraDatatype: 'date',
},
{
name: 'UUID',
value: 'uuid',
description: 'universal unique identifier',
hasuraDatatype: 'uuid',
},
{
name: 'JSONB',
value: 'jsonb',
description: 'binary format JSON data',
hasuraDatatype: 'jsonb',
},
{
name: 'Big Integer',
value: 'bigint',
description: 'signed eight-byte integer',
hasuraDatatype: 'bigint',
},
{
name: 'Big Integer (auto-increment)',
value: 'bigserial',
description: 'autoincrementing eight-byte integer',
hasuraDatatype: null,
},
];
/*
* Fetch non-composite types, primitive types like text, varchar etc,
* Filter types whose typename is unknown and type category is not 'Pseudo' and it is valid and available to be used
* */
export const fetchColumnTypesQuery = `
SELECT
string_agg(t.typname, ',') as "Type Name",
string_agg(pg_catalog.format_type(t.oid, NULL), ',') as "Display Name",
string_agg(coalesce(pg_catalog.obj_description(t.oid, 'pg_type'), ''), ':') as "Descriptions",
t.typcategory
FROM pg_catalog.pg_type t
LEFT JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace
WHERE (t.typrelid = 0 OR (SELECT c.relkind = 'c' FROM pg_catalog.pg_class c WHERE c.oid = t.typrelid))
AND NOT EXISTS(SELECT 1 FROM pg_catalog.pg_type el WHERE el.oid = t.typelem AND el.typarray = t.oid)
AND pg_catalog.pg_type_is_visible(t.oid)
AND t.typname != 'unknown'
AND t.typcategory != 'P'
GROUP BY t.typcategory;`;
export const fetchColumnDefaultFunctions = (schema = 'public') => `
SELECT string_agg(pgp.proname, ','),
t.typname as "Type"
from pg_proc pgp
JOIN pg_type t
ON pgp.prorettype = t.oid
JOIN pg_namespace pgn
ON pgn.oid = pgp.pronamespace
WHERE (t.typrelid = 0 OR (SELECT c.relkind = 'c' FROM pg_catalog.pg_class c WHERE c.oid = t.typrelid))
AND NOT EXISTS(SELECT 1 FROM pg_catalog.pg_type el WHERE el.oid = t.typelem AND el.typarray = t.oid)
AND pg_catalog.pg_type_is_visible(t.oid)
AND t.typname != 'unknown'
AND t.typcategory != 'P'
AND (array_length(pgp.proargtypes, 1) = 0)
AND ( pgn.nspname = '${schema}' OR pgn.nspname = 'pg_catalog' )
AND pgp.proretset=false
GROUP BY t.typname
ORDER BY t.typname ASC;
`;
const postgresFunctionTester = /.*\(\)$/gm;
export const isPostgresFunction = str =>
new RegExp(postgresFunctionTester).test(str);