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.

Normalize instances in db (#788)

Bogdan Chadkin1d457b5b9827
diff --git a/packages/prisma-client/prisma/migrations/20230115165217_tree_instances/migration.sql b/packages/prisma-client/prisma/migrations/20230115165217_tree_instances/migration.sql
new file mode 100644
index 0000000000..bdab3d8e6c
--- /dev/null
+++ b/packages/prisma-client/prisma/migrations/20230115165217_tree_instances/migration.sql
@@ -0,0 +1,2 @@
+-- AlterTable
+ALTER TABLE "Tree" ADD COLUMN "instances" TEXT NOT NULL DEFAULT '[]';
diff --git a/packages/prisma-client/prisma/migrations/20230115165314_tree_instances_data/migration.ts b/packages/prisma-client/prisma/migrations/20230115165314_tree_instances_data/migration.ts
new file mode 100644
index 0000000000..9322cb8067
--- /dev/null
+++ b/packages/prisma-client/prisma/migrations/20230115165314_tree_instances_data/migration.ts
@@ -0,0 +1,93 @@
+import { PrismaClient } from "./client";
+
+type Text = {
+ type: "text";
+ value: string;
+};
+
+type Id = {
+ type: "id";
+ value: string;
+};
+
+type Instance = {
+ type: "instance";
+ id: string;
+ component: string;
+ cssRules: Array<any>;
+ children: Array<Instance | Text>;
+};
+
+type InstancesItem = {
+ type: "instance";
+ id: string;
+ component: string;
+ children: Array<Id | Text>;
+};
+
+const convertTree = (instance: Instance, instances: InstancesItem[]) => {
+ const instancesItem: InstancesItem = {
+ type: "instance",
+ id: instance.id,
+ component: instance.component,
+ children: [],
+ };
+ instances.push(instancesItem);
+ for (const child of instance.children) {
+ if (child.type === "instance") {
+ convertTree(child, instances);
+ instancesItem.children.push({ type: "id", value: child.id });
+ } else {
+ instancesItem.children.push(child);
+ }
+ }
+};
+
+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) => {
+ let cursor: undefined | string = undefined;
+ let 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) {
+ try {
+ const root = JSON.parse(tree.root);
+ const instances: InstancesItem[] = [];
+ convertTree(root, instances);
+ tree.instances = JSON.stringify(instances);
+ } catch {
+ console.info(`Tree ${tree.id} cannot be converted`);
+ }
+ }
+ await Promise.all(
+ trees.map(({ id, instances }) =>
+ prisma.tree.update({ where: { id }, data: { instances } })
+ )
+ );
+ }
+ },
+ { timeout: 1000 * 60 * 5 }
+ );
+};
diff --git a/packages/prisma-client/prisma/migrations/20230115165314_tree_instances_data/schema.prisma b/packages/prisma-client/prisma/migrations/20230115165314_tree_instances_data/schema.prisma
new file mode 100644
index 0000000000..19f9697d95
--- /dev/null
+++ b/packages/prisma-client/prisma/migrations/20230115165314_tree_instances_data/schema.prisma
@@ -0,0 +1,109 @@
+// 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 = ["interactiveTransactions"]
+ 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[]
+}
+
+model Build {
+ id String @id @default(uuid())
+ createdAt DateTime @default(now())
+ pages String
+
+ project Project @relation(fields: [projectId], references: [id])
+ projectId String
+
+ isDev Boolean // exctly one is true per project
+ isProd Boolean // at most one is true per project (none if not published)
+
+ breakpoints Breakpoints?
+ designTokens DesignTokens?
+}
+
+model Tree {
+ id String @id @default(uuid())
+ root String
+ instances String @default("[]")
+ presetStyles String @default("[]")
+ styles String @default("[]")
+}
+
+model InstanceProps {
+ id String @id @default(uuid())
+ instanceId String
+ treeId String
+ props String @default("[]")
+}
+
+model Breakpoints {
+ build Build @relation(fields: [buildId], references: [id])
+ buildId String @id
+ values String @default("[]")
+}
+
+model DesignTokens {
+ build Build @relation(fields: [buildId], references: [id])
+ buildId String @id
+ value String @default("[]")
+}
diff --git a/packages/prisma-client/prisma/schema.prisma b/packages/prisma-client/prisma/schema.prisma
index 864d652783..19ba32c32b 100644
--- a/packages/prisma-client/prisma/schema.prisma
+++ b/packages/prisma-client/prisma/schema.prisma
@@ -79,6 +79,7 @@ model Build {
model Tree {
id String @id @default(uuid())
root String
+ instances String @default("[]")
presetStyles String @default("[]")
styles String @default("[]")
}
diff --git a/packages/project/src/db/tree.ts b/packages/project/src/db/tree.ts
index e8d2cc9c1e..c35ce5e7f6 100644
--- a/packages/project/src/db/tree.ts
+++ b/packages/project/src/db/tree.ts
@@ -1,41 +1,49 @@
+import { applyPatches, type Patch } from "immer";
+import { z } from "zod";
import {
type Tree,
type ComponentName,
+ type InstancesItem,
Instance,
- Text,
PresetStyles,
findMissingPresetStyles,
Styles,
+ Instances,
} from "@webstudio-is/react-sdk";
-import { applyPatches, type Patch } from "immer";
import {
prisma,
type Prisma,
type Tree as DbTree,
} from "@webstudio-is/prisma-client";
import { utils } from "../index";
-import { z } from "zod";
import { StylesDbIn, StylesDbOut } from "./styles";
-/**
- * validate/transform DB data schema to the client schema.
- */
-const InstanceDbOut = z.lazy(() =>
- z.object({
- type: z.literal("instance"),
- id: z.string(),
- component: z.string(),
- children: z.array(z.union([InstanceDbOut, Text])),
- cssRules: z.optional(z.unknown()),
- })
-) as z.ZodType<Instance>;
-
type TreeData = Omit<Tree, "id">;
+const normalizeTree = (instance: Instance, instances: InstancesItem[]) => {
+ const instancesItem: InstancesItem = {
+ type: "instance",
+ id: instance.id,
+ component: instance.component,
+ children: [],
+ };
+ instances.push(instancesItem);
+ for (const child of instance.children) {
+ if (child.type === "instance") {
+ normalizeTree(child, instances);
+ instancesItem.children.push({ type: "id", value: child.id });
+ } else {
+ instancesItem.children.push(child);
+ }
+ }
+};
+
export const createTree = (): TreeData => {
const root = utils.tree.createInstance({ component: "Body" });
const presetStyles = findMissingPresetStyles([], [root.component]);
const styles: Styles = [];
+ const instances: Instances = [];
+ normalizeTree(root, instances);
return {
root,
@@ -49,10 +57,13 @@ export const create = async (
client: Prisma.TransactionClient = prisma
): Promise<DbTree> => {
const root = Instance.parse(treeData.root);
+ const instances: Instances = [];
+ normalizeTree(root, instances);
return await client.tree.create({
data: {
- root: JSON.stringify(root),
+ root: "",
+ instances: JSON.stringify(instances),
presetStyles: JSON.stringify(treeData.presetStyles),
styles: JSON.stringify(await StylesDbIn.parseAsync(treeData.styles)),
},
@@ -63,16 +74,28 @@ export const deleteById = async (treeId: Tree["id"]): Promise<void> => {
await prisma.tree.delete({ where: { id: treeId } });
};
-const deleteCssRulesFromInstancesMutable = (instance: Instance) => {
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
- // @ts-ignore
- delete instance.cssRules;
-
- for (const child of instance.children) {
- if (child.type === "instance") {
- deleteCssRulesFromInstancesMutable(child);
- }
+const denormalizeTree = (instances: z.infer<typeof Instances>) => {
+ const instancesMap: Record<string, z.infer<typeof InstancesItem>> = {};
+ for (const instance of instances) {
+ instancesMap[instance.id] = instance;
}
+ const convertTree = (instance: z.infer<typeof InstancesItem>) => {
+ const legacyInstance: Instance = {
+ type: "instance",
+ id: instance.id,
+ component: instance.component as ComponentName,
+ children: [],
+ };
+ for (const child of instance.children) {
+ if (child.type === "id") {
+ legacyInstance.children.push(convertTree(instancesMap[child.value]));
+ } else {
+ legacyInstance.children.push(child);
+ }
+ }
+ return legacyInstance;
+ };
+ return convertTree(instances[0]);
};
export const loadById = async (
@@ -87,13 +110,8 @@ export const loadById = async (
return null;
}
- const dbRoot = JSON.parse(tree.root);
-
- const root = InstanceDbOut.parse(dbRoot);
-
- deleteCssRulesFromInstancesMutable(root);
-
- Instance.parse(root);
+ const instances = Instances.parse(JSON.parse(tree.instances));
+ const root = Instance.parse(denormalizeTree(instances));
const presetStyles = PresetStyles.parse(JSON.parse(tree.presetStyles));
const styles = Styles.parse(
@@ -146,10 +164,13 @@ export const patch = async (
const presetStyles = [...tree.presetStyles, ...missingPresetStyles];
const root = Instance.parse(clientRoot);
+ const instances: Instances = [];
+ normalizeTree(root, instances);
await prisma.tree.update({
data: {
- root: JSON.stringify(root),
+ root: "",
+ instances: JSON.stringify(instances),
presetStyles: JSON.stringify(presetStyles),
},
where: { id: treeId },
diff --git a/packages/react-sdk/src/db/instance.ts b/packages/react-sdk/src/db/instance.ts
index d32b23ace2..b72f5244f7 100644
--- a/packages/react-sdk/src/db/instance.ts
+++ b/packages/react-sdk/src/db/instance.ts
@@ -1,5 +1,5 @@
import { z } from "zod";
-import { ComponentName, getComponentNames } from "../components";
+import { type ComponentName, getComponentNames } from "../components";
// This should be used when passing a lot of data is potentially costly.
// For example, when passing data from an iframe.
@@ -8,11 +8,6 @@ export type BaseInstance = {
component: ComponentName;
};
-export type Text = {
- type: "text";
- value: string;
-};
-
export type Instance = BaseInstance & {
type: "instance";
children: Array<Instance | Text>;
@@ -25,12 +20,31 @@ export const toBaseInstance = (instance: Instance): BaseInstance => {
};
};
-export const Text = z.lazy(() =>
- z.object({
- type: z.literal("text"),
- value: z.string(),
- })
-);
+export const Text = z.object({
+ type: z.literal("text"),
+ value: z.string(),
+});
+
+export type Text = z.infer<typeof Text>;
+
+export const Id = z.object({
+ type: z.literal("id"),
+ value: z.string(),
+});
+export type Id = z.infer<typeof Id>;
+
+export const InstancesItem = z.object({
+ type: z.literal("instance"),
+ id: z.string(),
+ component: z.enum(getComponentNames() as [ComponentName]),
+ children: z.array(z.union([Id, Text])),
+});
+
+export type InstancesItem = z.infer<typeof InstancesItem>;
+
+export const Instances = z.array(InstancesItem);
+
+export type Instances = z.infer<typeof Instances>;
export const Instance: z.ZodType<Instance> = z.lazy(() =>
z.object({