Skip to content
This repository has been archived by the owner on Sep 30, 2024. It is now read-only.

Commit

Permalink
fix: Fix foreign key scripting (#40)
Browse files Browse the repository at this point in the history
Closes #39
  • Loading branch information
Jaxelr authored and justinlettau committed Sep 11, 2018
1 parent b1aa336 commit c7a48ca
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 9 deletions.
2 changes: 2 additions & 0 deletions src/interfaces.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,8 @@ export interface SqlForeignKey {
name: string;
schema: string;
table: string;
parent_schema: string;
parent_table: string;
delete_referential_action: number;
update_referential_action: number;
}
Expand Down
19 changes: 12 additions & 7 deletions src/sql/script.ts
Original file line number Diff line number Diff line change
Expand Up @@ -147,15 +147,19 @@ export function table(
output += EOL;
});

output += ')';

output += EOL;
output += EOL;

// foreign keys
foreignKeys
.filter(x => x.object_id === item.object_id)
.forEach(fk => {
output += ' ' + foreignKey(fk);
output += EOL;
});
.filter(x => x.object_id === item.object_id)
.forEach(fk => {
output += foreignKey(fk);
output += EOL;
});

output += ')';
output += EOL;
output += EOL;

Expand Down Expand Up @@ -325,10 +329,11 @@ function primaryKey(item: SqlPrimaryKey): string {
*/
function foreignKey(item: SqlForeignKey): string {
const objectId: string = `${item.schema}].[${item.table}`;
const parentObjectId: string = `${item.parent_schema}].[${item.parent_table}`;

let output: string = `alter table [${objectId}] with ${item.is_not_trusted ? 'nocheck' : 'check'}`;
output += ` add constraint [${item.name}] foreign key([${item.column}])`;
output += ` references [${objectId}] ([${item.reference}])`;
output += ` references [${parentObjectId}] ([${item.reference}])`;

switch (item.delete_referential_action) {
case 1:
Expand Down
7 changes: 5 additions & 2 deletions src/sql/sys.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,14 +72,16 @@ export const primaryKeyRead: string = `
*/
export const foreignKeyRead: string = `
select
ro.object_id,
po.object_id,
k.constraint_object_id,
fk.is_not_trusted,
c.name as [column],
rc.name as [reference],
fk.name,
schema_name(ro.schema_id) as [schema],
ro.name as [table],
po.name as [table],
schema_name(ro.schema_id) as [parent_schema],
ro.name as [parent_table],
fk.delete_referential_action,
fk.update_referential_action
from
Expand All @@ -88,6 +90,7 @@ export const foreignKeyRead: string = `
join sys.columns c on c.object_id = k.parent_object_id and c.column_id = k.parent_column_id
join sys.foreign_keys fk on fk.object_id = k.constraint_object_id
join sys.objects ro on ro.object_id = fk.referenced_object_id
join sys.objects po on po.object_id = fk.parent_object_id
`;

/**
Expand Down

0 comments on commit c7a48ca

Please sign in to comment.