Skip to content

Commit 8dc11fd

Browse files
committed
chore: add pos to db with trigger
1 parent 169e6e6 commit 8dc11fd

File tree

3 files changed

+39
-0
lines changed

3 files changed

+39
-0
lines changed
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
-- AlterTable
2+
ALTER TABLE "Resource" ADD COLUMN "pos" DECIMAL(1000,95);
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
-- NOTE: this is a custo migration to add a db trigger on
2+
-- insertion of any `null` values into the `Resource`.`pos` row
3+
CREATE OR REPLACE FUNCTION set_default_pos()
4+
RETURNS TRIGGER AS $$
5+
BEGIN
6+
-- Check if the parent resource is of type 'Folder'
7+
IF EXISTS (
8+
SELECT 1
9+
FROM "Resource"
10+
WHERE "id" = NEW."parentId"
11+
AND "type" = 'Folder'
12+
) THEN
13+
-- If the pos is NULL, calculate the next available pos for this parentId
14+
IF NEW."pos" IS NULL THEN
15+
SELECT COALESCE(MAX("pos"), 0) + 1
16+
INTO NEW."pos"
17+
FROM "Resource"
18+
WHERE "parentId" = NEW."parentId";
19+
END IF;
20+
END IF;
21+
22+
-- Return the modified row
23+
RETURN NEW;
24+
END;
25+
$$ LANGUAGE plpgsql;
26+
27+
CREATE TRIGGER set_pos_default
28+
BEFORE INSERT ON "Resource"
29+
FOR EACH ROW
30+
EXECUTE FUNCTION set_default_pos();

apps/studio/prisma/schema.prisma

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,13 @@ model Resource {
6868
state ResourceState? @default(Draft)
6969
type ResourceType
7070
71+
// NOTE: refer to the postgres docs here
72+
// https://www.postgresql.org/docs/current/datatype-numeric.html#DATATYPE-NUMERIC-TABLE
73+
// this creates a numeric type that has a scale of 1000 (can store up to 1000 digits)
74+
// of which 96 are after the decimal point.
75+
// This means that our users can create up to 10e5 pages (probably way more than required)
76+
pos Decimal? @db.Decimal(1000, 95)
77+
7178
createdAt DateTime @default(now())
7279
updatedAt DateTime @default(now()) @updatedAt
7380
ResourcePermission ResourcePermission[]

0 commit comments

Comments
 (0)