refactor: update

This commit is contained in:
Mauricio Siu
2025-02-15 20:06:33 -06:00
parent 8b71f963cc
commit 87b12ff6e9
9 changed files with 10740 additions and 84 deletions

View File

@@ -0,0 +1,2 @@
ALTER TABLE "project" ADD COLUMN "organizationId" text;--> statement-breakpoint
ALTER TABLE "project" ADD CONSTRAINT "project_organizationId_organization_id_fk" FOREIGN KEY ("organizationId") REFERENCES "public"."organization"("id") ON DELETE cascade ON UPDATE no action;

View File

@@ -0,0 +1,27 @@
-- Custom SQL migration file, put your code below! --
-- Primero, actualizamos los proyectos con la organización del usuario
UPDATE "project" p
SET "organizationId" = (
SELECT m."organization_id"
FROM "member" m
WHERE m."user_id" = p."userId"
AND m."role" = 'owner'
LIMIT 1
)
WHERE p."organizationId" IS NULL;
-- Verificamos que todos los proyectos tengan una organización
DO $$
BEGIN
IF EXISTS (
SELECT 1
FROM "project"
WHERE "organizationId" IS NULL
) THEN
RAISE EXCEPTION 'Hay proyectos sin organización asignada';
END IF;
END $$;
-- Hacemos organization_id NOT NULL después de la migración
ALTER TABLE "project"
ALTER COLUMN "organizationId" SET NOT NULL;

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -491,6 +491,20 @@
"when": 1739664410814, "when": 1739664410814,
"tag": "0069_broad_ken_ellis", "tag": "0069_broad_ken_ellis",
"breakpoints": true "breakpoints": true
},
{
"idx": 70,
"version": "7",
"when": 1739671371444,
"tag": "0070_dusty_wind_dancer",
"breakpoints": true
},
{
"idx": 71,
"version": "7",
"when": 1739671387634,
"tag": "0071_migrate-data-projects",
"breakpoints": true
} }
] ]
} }

View File

@@ -124,3 +124,27 @@ await db
.catch((error) => { .catch((error) => {
console.error(error); console.error(error);
}); });
await db
.transaction(async (db) => {
const projects = await db.query.projects.findMany({
with: {
user: {
with: {
organizations: true,
},
},
},
});
for (const project of projects) {
const user = await db.update(schema.projects).set({
organizationId: project.user.organizations[0]?.id || "",
});
}
})
.then(() => {
console.log("Migration finished");
})
.catch((error) => {
console.error(error);
});

View File

@@ -1,96 +1,77 @@
import { import { pgTable, text, integer, timestamp, boolean } from "drizzle-orm/pg-core";
boolean,
integer, export const users_temp = pgTable("users_temp", {
pgTable, id: text("id").primaryKey(),
text, name: text('name').notNull(),
timestamp, email: text('email').notNull().unique(),
} from "drizzle-orm/pg-core"; emailVerified: boolean('email_verified').notNull(),
image: text('image'),
export const user = pgTable("user", { createdAt: timestamp('created_at').notNull(),
id: text("id").primaryKey(), updatedAt: timestamp('updated_at').notNull(),
name: text("name").notNull(), role: text('role').notNull(),
email: text("email").notNull().unique(), ownerId: text('owner_id').notNull()
emailVerified: boolean("email_verified").notNull(), });
image: text("image"),
createdAt: timestamp("created_at").notNull(),
updatedAt: timestamp("updated_at").notNull(),
});
export const session = pgTable("session", { export const session = pgTable("session", {
id: text("id").primaryKey(), id: text("id").primaryKey(),
expiresAt: timestamp("expires_at").notNull(), expiresAt: timestamp('expires_at').notNull(),
token: text("token").notNull().unique(), token: text('token').notNull().unique(),
createdAt: timestamp("created_at").notNull(), createdAt: timestamp('created_at').notNull(),
updatedAt: timestamp("updated_at").notNull(), updatedAt: timestamp('updated_at').notNull(),
ipAddress: text("ip_address"), ipAddress: text('ip_address'),
userAgent: text("user_agent"), userAgent: text('user_agent'),
userId: text("user_id") userId: text('user_id').notNull().references(()=> users_temp.id, { onDelete: 'cascade' }),
.notNull() activeOrganizationId: text('active_organization_id')
.references(() => user.id), });
activeOrganizationId: text("active_organization_id"),
});
export const account = pgTable("account", { export const account = pgTable("account", {
id: text("id").primaryKey(), id: text("id").primaryKey(),
accountId: text("account_id").notNull(), accountId: text('account_id').notNull(),
providerId: text("provider_id").notNull(), providerId: text('provider_id').notNull(),
userId: text("user_id") userId: text('user_id').notNull().references(()=> users_temp.id, { onDelete: 'cascade' }),
.notNull() accessToken: text('access_token'),
.references(() => user.id), refreshToken: text('refresh_token'),
accessToken: text("access_token"), idToken: text('id_token'),
refreshToken: text("refresh_token"), accessTokenExpiresAt: timestamp('access_token_expires_at'),
idToken: text("id_token"), refreshTokenExpiresAt: timestamp('refresh_token_expires_at'),
accessTokenExpiresAt: timestamp("access_token_expires_at"), scope: text('scope'),
refreshTokenExpiresAt: timestamp("refresh_token_expires_at"), password: text('password'),
scope: text("scope"), createdAt: timestamp('created_at').notNull(),
password: text("password"), updatedAt: timestamp('updated_at').notNull()
createdAt: timestamp("created_at").notNull(), });
updatedAt: timestamp("updated_at").notNull(),
});
export const verification = pgTable("verification", { export const verification = pgTable("verification", {
id: text("id").primaryKey(), id: text("id").primaryKey(),
identifier: text("identifier").notNull(), identifier: text('identifier').notNull(),
value: text("value").notNull(), value: text('value').notNull(),
expiresAt: timestamp("expires_at").notNull(), expiresAt: timestamp('expires_at').notNull(),
createdAt: timestamp("created_at"), createdAt: timestamp('created_at'),
updatedAt: timestamp("updated_at"), updatedAt: timestamp('updated_at')
}); });
export const organization = pgTable("organization", { export const organization = pgTable("organization", {
id: text("id").primaryKey(), id: text("id").primaryKey(),
name: text("name").notNull(), name: text('name').notNull(),
slug: text("slug").unique(), slug: text('slug').unique(),
logo: text("logo"), logo: text('logo'),
createdAt: timestamp("created_at").notNull(), createdAt: timestamp('created_at').notNull(),
metadata: text("metadata"), metadata: text('metadata')
ownerId: text("owner_id") });
.notNull()
.references(() => user.userId),
});
export const member = pgTable("member", { export const member = pgTable("member", {
id: text("id").primaryKey(), id: text("id").primaryKey(),
organizationId: text("organization_id") organizationId: text('organization_id').notNull().references(()=> organization.id, { onDelete: 'cascade' }),
.notNull() userId: text('user_id').notNull().references(()=> user.id, { onDelete: 'cascade' }),
.references(() => organization.id), role: text('role').notNull(),
userId: text("user_id") createdAt: timestamp('created_at').notNull()
.notNull() });
.references(() => user.userId),
role: text("role").notNull(),
createdAt: timestamp("created_at").notNull(),
});
export const invitation = pgTable("invitation", { export const invitation = pgTable("invitation", {
id: text("id").primaryKey(), id: text("id").primaryKey(),
organizationId: text("organization_id") organizationId: text('organization_id').notNull().references(()=> organization.id, { onDelete: 'cascade' }),
.notNull() email: text('email').notNull(),
.references(() => organization.id), role: text('role'),
email: text("email").notNull(), status: text('status').notNull(),
role: text("role"), expiresAt: timestamp('expires_at').notNull(),
status: text("status").notNull(), inviterId: text('inviter_id').notNull().references(()=> user.id, { onDelete: 'cascade' })
expiresAt: timestamp("expires_at").notNull(), });
inviterId: text("inviter_id")
.notNull()
.references(() => user.userId),
});

View File

@@ -14,6 +14,7 @@ import { mysql } from "./mysql";
import { postgres } from "./postgres"; import { postgres } from "./postgres";
import { redis } from "./redis"; import { redis } from "./redis";
import { users, users_temp } from "./user"; import { users, users_temp } from "./user";
import { organization } from "./account";
export const projects = pgTable("project", { export const projects = pgTable("project", {
projectId: text("projectId") projectId: text("projectId")
@@ -31,6 +32,9 @@ export const projects = pgTable("project", {
userId: text("userId") userId: text("userId")
.notNull() .notNull()
.references(() => users_temp.id, { onDelete: "cascade" }), .references(() => users_temp.id, { onDelete: "cascade" }),
organizationId: text("organizationId")
// .notNull()
.references(() => organization.id, { onDelete: "cascade" }),
env: text("env").notNull().default(""), env: text("env").notNull().default(""),
}); });
@@ -42,6 +46,10 @@ export const projectRelations = relations(projects, ({ many, one }) => ({
mongo: many(mongo), mongo: many(mongo),
redis: many(redis), redis: many(redis),
compose: many(compose), compose: many(compose),
user: one(users_temp, {
fields: [projects.userId],
references: [users_temp.id],
}),
// user: one(user, { // user: one(user, {
// fields: [projects.userId], // fields: [projects.userId],
// references: [user.id], // references: [user.id],

View File

@@ -14,6 +14,7 @@ import { account, organization } from "./account";
import { admins } from "./admin"; import { admins } from "./admin";
import { auth } from "./auth"; import { auth } from "./auth";
import { certificateType } from "./shared"; import { certificateType } from "./shared";
import { projects } from "./project";
/** /**
* This is an example of how to use the multi-project schema feature of Drizzle ORM. Use the same * This is an example of how to use the multi-project schema feature of Drizzle ORM. Use the same
* database instance for multiple projects. * database instance for multiple projects.
@@ -199,6 +200,7 @@ export const usersRelations = relations(users_temp, ({ one, many }) => ({
// fields: [users.adminId], // fields: [users.adminId],
// references: [admins.adminId], // references: [admins.adminId],
// }), // }),
projects: many(projects),
})); }));
const createSchema = createInsertSchema(users_temp, { const createSchema = createInsertSchema(users_temp, {