Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(schemas): add user tenantId foreign key constraint #6644

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { sql } from '@silverhand/slonik';

import type { AlterationScript } from '../lib/types/alteration.js';

const alteration: AlterationScript = {
up: async (pool) => {
await pool.query(sql`
alter table users
add constraint users__tenant_id__id unique (tenant_id, id);
`);

await pool.query(sql`
alter table organization_user_relations
add constraint organization_user_relations__user_id__fk
foreign key (tenant_id, user_id) references users (tenant_id, id) on update cascade on delete cascade;
`);

await pool.query(sql`
drop index users__id;
`);
},
down: async (pool) => {
await pool.query(sql`
create index users__id on users (id);
`);

await pool.query(sql`
alter table organization_user_relations
drop constraint organization_user_relations__user_id__fk;
`);

await pool.query(sql`
alter table users
drop constraint users__tenant_id__id;
`);
},
};

export default alteration;
4 changes: 3 additions & 1 deletion packages/schemas/tables/organization_user_relations.sql
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,7 @@ create table organization_user_relations (
references organizations (id) on update cascade on delete cascade,
user_id varchar(21) not null
references users (id) on update cascade on delete cascade,
primary key (tenant_id, organization_id, user_id)
primary key (tenant_id, organization_id, user_id),
/** Ensures that the user is a member of the organization. */
foreign key (tenant_id, user_id) references users (tenant_id, id) on update cascade on delete cascade
);
4 changes: 3 additions & 1 deletion packages/schemas/tables/users.sql
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,9 @@ create table users (
constraint users__primary_email
unique (tenant_id, primary_email),
constraint users__primary_phone
unique (tenant_id, primary_phone)
unique (tenant_id, primary_phone),
constraint users__tenant_id__id
unique (tenant_id, id)
);

create index users__id
Expand Down
Loading