(attribute: ModelAttributeColumnOptions, tableName: string)
| 656 | `ALTER TABLE "${schemaName}"."${tableName}" DROP CONSTRAINT IF EXISTS ${fkConstraint};`; |
| 657 | |
| 658 | export 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 |
| 693 | export const dropIndexQuery = (schema: string, hashedIndexName: string): string => |
no test coverage detected