MCPcopy Create free account
hub / github.com/subquery/subql / generateForeignKeyQuery

Function generateForeignKeyQuery

packages/node-core/src/db/sync-helper.ts:658–690  ·  view source on GitHub ↗
(attribute: ModelAttributeColumnOptions, tableName: string)

Source from the content-addressed store, hash-verified

656 `ALTER TABLE "${schemaName}"."${tableName}" DROP CONSTRAINT IF EXISTS ${fkConstraint};`;
657
658export function generateForeignKeyQuery(attribute: ModelAttributeColumnOptions, tableName: string): string | void {
659 const references = attribute?.references as ModelAttributeColumnReferencesOptions;
660 if (!references) {
661 return;
662 }
663 const foreignTable = references.model as TableNameWithSchema;
664 assert(attribute.field, 'Missing field on attribute');
665 const fkey = getFkConstraint(tableName, attribute.field);
666 let query = `
667 DO $$
668 BEGIN
669 ALTER TABLE "${foreignTable.schema}"."${tableName}"
670 ADD
671 CONSTRAINT ${fkey}
672 FOREIGN KEY (${attribute.field})
673 REFERENCES "${foreignTable.schema}"."${foreignTable.tableName}" (${references.key})`;
674 if (attribute.onDelete) {
675 query += ` ON DELETE ${attribute.onDelete}`;
676 }
677 if (attribute.onUpdate) {
678 query += ` ON UPDATE ${attribute.onUpdate}`;
679 }
680 if (references.deferrable) {
681 query += ` DEFERRABLE`;
682 }
683 query += `;
684 EXCEPTION
685 WHEN duplicate_object THEN
686 RAISE NOTICE 'Constraint already exists. Ignoring...';
687 END$$;
688`;
689 return `${query.trim()};`;
690}
691
692// indexes
693export const dropIndexQuery = (schema: string, hashedIndexName: string): string =>

Callers 1

Calls 1

getFkConstraintFunction · 0.85

Tested by

no test coverage detected