Skip to content

Open source website builder and Webflow alternative. Webstudio is an advanced visual builder that connects to any headless CMS, supports all CSS properties, and can be hosted anywhere, including with us.

Add buildId and projectId relations to Tree table (#895)

Bogdan Chadkin6c4ea4652108
diff --git a/apps/designer/app/routes/rest/pages.$projectId.ts b/apps/designer/app/routes/rest/pages.$projectId.ts
index 635e47d793..b12f4693b5 100644
--- a/apps/designer/app/routes/rest/pages.$projectId.ts
+++ b/apps/designer/app/routes/rest/pages.$projectId.ts
@@ -55,7 +55,11 @@ const handlePut = async (
return makeFieldError("path", `Already used for "${existingPage.name}"`);
}
- const updatedBuild = await db.build.addPage(devBuild.id, data);
+ const updatedBuild = await db.build.addPage({
+ projectId,
+ buildId: devBuild.id,
+ data,
+ });
const newPage = utils.pages.findByIdOrPath(updatedBuild.pages, data.path);
diff --git a/packages/prisma-client/prisma/migrations/20230130121014_tree_relations/migration.sql b/packages/prisma-client/prisma/migrations/20230130121014_tree_relations/migration.sql
new file mode 100644
index 0000000000..b4d913b371
--- /dev/null
+++ b/packages/prisma-client/prisma/migrations/20230130121014_tree_relations/migration.sql
@@ -0,0 +1,9 @@
+-- AlterTable
+ALTER TABLE "Tree" ADD COLUMN "buildId" TEXT,
+ADD COLUMN "projectId" TEXT;
+
+-- AddForeignKey
+ALTER TABLE "Tree" ADD CONSTRAINT "Tree_projectId_fkey" FOREIGN KEY ("projectId") REFERENCES "Project"("id") ON DELETE SET NULL ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE "Tree" ADD CONSTRAINT "Tree_buildId_fkey" FOREIGN KEY ("buildId") REFERENCES "Build"("id") ON DELETE SET NULL ON UPDATE CASCADE;
diff --git a/packages/prisma-client/prisma/migrations/20230130121041_tree_relations_data/migration.ts b/packages/prisma-client/prisma/migrations/20230130121041_tree_relations_data/migration.ts
new file mode 100644
index 0000000000..92647f59f8
--- /dev/null
+++ b/packages/prisma-client/prisma/migrations/20230130121041_tree_relations_data/migration.ts
@@ -0,0 +1,115 @@
+import { PrismaClient } from "./client";
+
+type TreeId = string;
+type BuildId = string;
+type ProjectId = string;
+
+type Page = {
+ id: string;
+ name: string;
+ path: string;
+ title: string;
+ meta: any;
+ treeId: TreeId;
+};
+
+type Pages = {
+ homePage: Page;
+ pages: Page[];
+};
+
+export default async () => {
+ const client = new PrismaClient({
+ // Uncomment to see the queries in console as the migration runs
+ // log: ["query", "info", "warn", "error"],
+ });
+
+ await client.$transaction(
+ async (prisma) => {
+ const buildIdPerTreeId = new Map<TreeId, BuildId>();
+ const projectIdPerTreeId = new Map<TreeId, ProjectId>();
+
+ let cursor: undefined | string = undefined;
+ let hasNext = true;
+ while (hasNext) {
+ const chunkSize = 1000;
+ const builds = await prisma.build.findMany({
+ take: chunkSize,
+ orderBy: {
+ id: "asc",
+ },
+ ...(cursor
+ ? {
+ skip: 1, // Skip the cursor
+ cursor: { id: cursor },
+ }
+ : null),
+ });
+ cursor = builds.at(-1)?.id;
+ hasNext = builds.length === chunkSize;
+
+ for (const build of builds) {
+ try {
+ const pages: Pages = JSON.parse(build.pages);
+ buildIdPerTreeId.set(pages.homePage.treeId, build.id);
+ projectIdPerTreeId.set(pages.homePage.treeId, build.projectId);
+ for (const page of pages.pages) {
+ buildIdPerTreeId.set(page.treeId, build.id);
+ projectIdPerTreeId.set(page.treeId, build.projectId);
+ }
+ } catch {
+ console.info(`Build ${build.id} cannot be parsed`);
+ }
+ }
+ }
+
+ cursor = undefined;
+ hasNext = true;
+ while (hasNext) {
+ const chunkSize = 1000;
+ const trees = await prisma.tree.findMany({
+ take: chunkSize,
+ orderBy: {
+ id: "asc",
+ },
+ ...(cursor
+ ? {
+ skip: 1, // Skip the cursor
+ cursor: { id: cursor },
+ }
+ : null),
+ });
+ cursor = trees.at(-1)?.id;
+ hasNext = trees.length === chunkSize;
+
+ for (const tree of trees) {
+ const buildId = buildIdPerTreeId.get(tree.id);
+ const projectId = projectIdPerTreeId.get(tree.id);
+ if (buildId && projectId) {
+ tree.buildId = buildId;
+ tree.projectId = projectId;
+ }
+ }
+ await Promise.all(
+ trees.map(({ id, buildId, projectId }) =>
+ prisma.tree.update({ where: { id }, data: { buildId, projectId } })
+ )
+ );
+ }
+
+ await prisma.tree.deleteMany({
+ where: {
+ OR: [
+ {
+ buildId: { equals: null },
+ },
+ {
+ projectId: { equals: null },
+ },
+ ],
+ },
+ });
+ },
+ { timeout: 1000 * 60 * 5 }
+ );
+};
diff --git a/packages/prisma-client/prisma/migrations/20230130121041_tree_relations_data/schema.prisma b/packages/prisma-client/prisma/migrations/20230130121041_tree_relations_data/schema.prisma
new file mode 100644
index 0000000000..f2a23accc9
--- /dev/null
+++ b/packages/prisma-client/prisma/migrations/20230130121041_tree_relations_data/schema.prisma
@@ -0,0 +1,130 @@
+// DO NOT EDIT THIS FILE!
+// This is a copy of your schema.prisma that corresponds to the state of the database
+// when all migrations up until this one are applied.
+// It's used to generate a Prisma Client for the migration.
+
+// This is your Prisma schema file,
+// learn more about it in the docs: https://pris.ly/d/prisma-schema
+
+generator client {
+ provider = "prisma-client-js"
+ previewFeatures = ["views", "clientExtensions"]
+ output = "client"
+}
+
+datasource db {
+ provider = "postgres"
+ url = env("DATABASE_URL")
+}
+
+model Team {
+ id String @id @default(uuid())
+ users User[]
+}
+
+enum Location {
+ FS
+ REMOTE
+}
+
+enum UploadStatus {
+ UPLOADING
+ UPLOADED
+}
+
+model Asset {
+ id String @id @default(uuid())
+ projectId String
+ format String
+ size Int
+ name String
+ description String?
+ location Location
+ createdAt DateTime @default(now())
+ meta String @default("{}")
+ status UploadStatus @default(UPLOADED)
+}
+
+model User {
+ id String @id @default(uuid())
+ email String? @unique
+ provider String?
+ image String?
+ username String?
+ createdAt DateTime @default(now())
+ team Team? @relation(fields: [teamId], references: [id])
+ teamId String?
+ projects Project[]
+}
+
+model Project {
+ id String @id @default(uuid())
+ title String
+ domain String @unique
+ user User? @relation(fields: [userId], references: [id])
+ userId String?
+ build Build[]
+ trees Tree[]
+ isDeleted Boolean @default(false)
+}
+
+model Build {
+ id String @id @default(uuid())
+ createdAt DateTime @default(now())
+ pages String
+
+ project Project @relation(fields: [projectId], references: [id])
+ projectId String
+ trees Tree[]
+
+ isDev Boolean // exctly one is true per project
+ isProd Boolean // at most one is true per project (none if not published)
+
+ breakpoints Breakpoints?
+
+ styles String @default("[]")
+ styleSources String @default("[]")
+}
+
+model Tree {
+ id String @id @default(uuid())
+ project Project? @relation(fields: [projectId], references: [id])
+ projectId String?
+ build Build? @relation(fields: [buildId], references: [id])
+ buildId String?
+ root String
+ instances String @default("[]")
+ props String @default("[]")
+ styles String @default("[]")
+ styleSelections String @default("[]")
+}
+
+model Breakpoints {
+ build Build @relation(fields: [buildId], references: [id])
+ buildId String @id
+ values String @default("[]")
+}
+
+enum AuthorizationPermit {
+ VIEW
+ EDIT
+}
+
+model AuthorizationTokens {
+ id String @id @default(uuid())
+ // No relation to Project, as the Authorization system is not tied to a project
+ projectId String
+ token String
+ permit AuthorizationPermit
+ createdAt DateTime @default(now())
+}
+
+// Dashboard
+view DashboardProject {
+ id String @id @default(uuid())
+ title String
+ domain String
+ userId String?
+ isDeleted Boolean @default(false)
+ isPublished Boolean
+}
diff --git a/packages/prisma-client/prisma/migrations/20230130124937_tree_relations_not_null/migration.sql b/packages/prisma-client/prisma/migrations/20230130124937_tree_relations_not_null/migration.sql
new file mode 100644
index 0000000000..e33260af39
--- /dev/null
+++ b/packages/prisma-client/prisma/migrations/20230130124937_tree_relations_not_null/migration.sql
@@ -0,0 +1,15 @@
+-- DropForeignKey
+ALTER TABLE "Tree" DROP CONSTRAINT "Tree_buildId_fkey";
+
+-- DropForeignKey
+ALTER TABLE "Tree" DROP CONSTRAINT "Tree_projectId_fkey";
+
+-- AlterTable
+ALTER TABLE "Tree" ALTER COLUMN "buildId" SET NOT NULL,
+ALTER COLUMN "projectId" SET NOT NULL;
+
+-- AddForeignKey
+ALTER TABLE "Tree" ADD CONSTRAINT "Tree_projectId_fkey" FOREIGN KEY ("projectId") REFERENCES "Project"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE "Tree" ADD CONSTRAINT "Tree_buildId_fkey" FOREIGN KEY ("buildId") REFERENCES "Build"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
diff --git a/packages/prisma-client/prisma/schema.prisma b/packages/prisma-client/prisma/schema.prisma
index bfe0bef420..d55f11e6b2 100644
--- a/packages/prisma-client/prisma/schema.prisma
+++ b/packages/prisma-client/prisma/schema.prisma
@@ -59,6 +59,7 @@ model Project {
user User? @relation(fields: [userId], references: [id])
userId String?
build Build[]
+ trees Tree[]
isDeleted Boolean @default(false)
}
@@ -69,6 +70,7 @@ model Build {
project Project @relation(fields: [projectId], references: [id])
projectId String
+ trees Tree[]
isDev Boolean // exctly one is true per project
isProd Boolean // at most one is true per project (none if not published)
@@ -81,6 +83,10 @@ model Build {
model Tree {
id String @id @default(uuid())
+ project Project @relation(fields: [projectId], references: [id])
+ projectId String
+ build Build @relation(fields: [buildId], references: [id])
+ buildId String
root String
instances String @default("[]")
props String @default("[]")
diff --git a/packages/project-build/src/types.ts b/packages/project-build/src/types.ts
index 9123e9547b..63a144f06a 100644
--- a/packages/project-build/src/types.ts
+++ b/packages/project-build/src/types.ts
@@ -4,6 +4,8 @@ import type { Styles } from "./schema/styles";
export type Tree = {
id: string;
+ projectId: string;
+ buildId: string;
root: Instance;
props: Props;
styles: Styles;
diff --git a/packages/project/src/db/build.ts b/packages/project/src/db/build.ts
index 0ee617b2f0..a2c1c3e1f8 100644
--- a/packages/project/src/db/build.ts
+++ b/packages/project/src/db/build.ts
@@ -1,5 +1,10 @@
import { v4 as uuid } from "uuid";
-import { prisma, Build as DbBuild, Prisma } from "@webstudio-is/prisma-client";
+import {
+ prisma,
+ Build as DbBuild,
+ Prisma,
+ Project,
+} from "@webstudio-is/prisma-client";
import * as db from ".";
import { Build, Page, Pages } from "./schema";
import * as pagesUtils from "../shared/pages";
@@ -74,13 +79,20 @@ const updatePages = async (
return parseBuild(updatedBuild);
};
-export const addPage = async (
- buildId: Build["id"],
+export const addPage = async ({
+ projectId,
+ buildId,
+ data,
+}: {
+ projectId: Project["id"];
+ buildId: Build["id"];
data: Pick<Page, "name" | "path"> &
- Partial<Omit<Page, "id" | "treeId" | "name" | "path">>
-) => {
+ Partial<Omit<Page, "id" | "treeId" | "name" | "path">>;
+}) => {
return updatePages(buildId, async (currentPages) => {
- const tree = await db.tree.create(db.tree.createTree());
+ const tree = await db.tree.create(
+ db.tree.createTree({ projectId, buildId })
+ );
return {
homePage: currentPages.homePage,
@@ -151,8 +163,14 @@ export const deletePage = async (buildId: Build["id"], pageId: Page["id"]) => {
});
};
-const createPages = async (client: Prisma.TransactionClient = prisma) => {
- const tree = await db.tree.create(db.tree.createTree(), client);
+const createPages = async (
+ { projectId, buildId }: { projectId: Project["id"]; buildId: Build["id"] },
+ client: Prisma.TransactionClient = prisma
+) => {
+ const tree = await db.tree.create(
+ db.tree.createTree({ projectId, buildId }),
+ client
+ );
return Pages.parse({
homePage: {
id: uuid(),
@@ -232,9 +250,18 @@ export async function create(
? (await db.breakpoints.load(sourceBuild.id)).values
: db.breakpoints.createValues();
+ const build = await client.build.create({
+ data: {
+ projectId,
+ pages: JSON.stringify([]),
+ isDev: env === "dev",
+ isProd: env === "prod",
+ },
+ });
+
const pages =
sourceBuild === undefined
- ? await createPages(client)
+ ? await createPages({ projectId, buildId: build.id }, client)
: await clonePages(sourceBuild.pages, client);
if (env === "prod") {
@@ -244,12 +271,12 @@ export async function create(
});
}
- const build = await client.build.create({
+ await client.build.update({
+ where: {
+ id: build.id,
+ },
data: {
- projectId,
pages: JSON.stringify(pages),
- isDev: env === "dev",
- isProd: env === "prod",
},
});
diff --git a/packages/project/src/db/tree.ts b/packages/project/src/db/tree.ts
index d03d0493c4..125e2072be 100644
--- a/packages/project/src/db/tree.ts
+++ b/packages/project/src/db/tree.ts
@@ -42,7 +42,13 @@ const normalizeTree = (instance: Instance, instances: InstancesItem[]) => {
}
};
-export const createTree = (): TreeData => {
+export const createTree = ({
+ projectId,
+ buildId,
+}: {
+ projectId: string;
+ buildId: string;
+}): TreeData => {
const root = utils.tree.createInstance({ component: "Body" });
const styles: Styles = [];
const instances: Instances = [];
@@ -50,6 +56,8 @@ export const createTree = (): TreeData => {
const props: Props = [];
return {
+ projectId,
+ buildId,
root,
props,
styles,
@@ -66,6 +74,8 @@ export const create = async (
return await client.tree.create({
data: {
+ projectId: treeData.projectId,
+ buildId: treeData.buildId,
root: "",
instances: JSON.stringify(instances),
props: serializeProps(treeData.props),