feat(environment): implement environment management with create, duplicate, and delete functionalities; add environment schema and database migrations

This commit is contained in:
Mauricio Siu
2025-09-01 17:36:27 -06:00
parent fd199fdcc0
commit 6fc325fe95
23 changed files with 14108 additions and 82 deletions

View File

@@ -0,0 +1,387 @@
import { zodResolver } from "@hookform/resolvers/zod";
import { Copy, Plus, Settings, Trash2 } from "lucide-react";
import { useState } from "react";
import { useForm } from "react-hook-form";
import { toast } from "sonner";
import { z } from "zod";
import { DateTooltip } from "@/components/shared/date-tooltip";
import { DialogAction } from "@/components/shared/dialog-action";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog";
import {
Form,
FormControl,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { api } from "@/utils/api";
const createEnvironmentSchema = z.object({
name: z.string().min(1, "Environment name is required"),
description: z.string().optional(),
});
const duplicateEnvironmentSchema = z.object({
name: z.string().min(1, "Environment name is required"),
description: z.string().optional(),
});
type CreateEnvironment = z.infer<typeof createEnvironmentSchema>;
type DuplicateEnvironment = z.infer<typeof duplicateEnvironmentSchema>;
interface Props {
projectId: string;
children?: React.ReactNode;
}
export const EnvironmentManagement = ({ projectId, children }: Props) => {
const [isOpen, setIsOpen] = useState(false);
const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false);
const [isDuplicateDialogOpen, setIsDuplicateDialogOpen] = useState(false);
const [selectedEnvironmentId, setSelectedEnvironmentId] =
useState<string>("");
const utils = api.useUtils();
// Queries
const { data: environments, isLoading: environmentsLoading } =
api.environment.byProjectId.useQuery(
{ projectId },
{ enabled: !!projectId },
);
// Mutations
const createEnvironmentMutation = api.environment.create.useMutation();
const duplicateEnvironmentMutation = api.environment.duplicate.useMutation();
const deleteEnvironmentMutation = api.environment.remove.useMutation();
// Forms
const createForm = useForm<CreateEnvironment>({
defaultValues: {
name: "",
description: "",
},
resolver: zodResolver(createEnvironmentSchema),
});
const duplicateForm = useForm<DuplicateEnvironment>({
defaultValues: {
name: "",
description: "",
},
resolver: zodResolver(duplicateEnvironmentSchema),
});
const onCreateSubmit = async (formData: CreateEnvironment) => {
try {
await createEnvironmentMutation.mutateAsync({
...formData,
projectId,
});
toast.success("Environment created successfully");
utils.environment.byProjectId.invalidate({ projectId });
setIsCreateDialogOpen(false);
createForm.reset();
} catch (error) {
toast.error("Error creating environment");
}
};
const onDuplicateSubmit = async (formData: DuplicateEnvironment) => {
if (!selectedEnvironmentId) return;
try {
await duplicateEnvironmentMutation.mutateAsync({
environmentId: selectedEnvironmentId,
name: formData.name,
description: formData.description,
});
toast.success("Environment duplicated successfully");
utils.environment.byProjectId.invalidate({ projectId });
setIsDuplicateDialogOpen(false);
duplicateForm.reset();
setSelectedEnvironmentId("");
} catch (error) {
toast.error("Error duplicating environment");
}
};
const handleDeleteEnvironment = async (environmentId: string) => {
try {
await deleteEnvironmentMutation.mutateAsync({ environmentId });
toast.success("Environment deleted successfully");
utils.environment.byProjectId.invalidate({ projectId });
} catch (error) {
toast.error("Error deleting environment");
}
};
const handleDuplicateClick = (
environmentId: string,
environmentName: string,
) => {
setSelectedEnvironmentId(environmentId);
duplicateForm.setValue("name", `${environmentName} (copy)`);
setIsDuplicateDialogOpen(true);
};
return (
<>
<Dialog open={isOpen} onOpenChange={setIsOpen}>
<DialogTrigger asChild>
{children ?? (
<Button variant="outline">
<Settings className="h-4 w-4 mr-2" />
Environments
</Button>
)}
</DialogTrigger>
<DialogContent className="sm:max-w-4xl">
<DialogHeader>
<DialogTitle>Environment Management</DialogTitle>
<DialogDescription>
Manage project environments. Each environment can have its own
configuration and settings.
</DialogDescription>
</DialogHeader>
<div className="space-y-4">
<div className="flex justify-between items-center">
<h3 className="text-lg font-medium">Project Environments</h3>
<Button
onClick={() => setIsCreateDialogOpen(true)}
className="flex items-center gap-2"
>
<Plus className="h-4 w-4" />
Create Environment
</Button>
</div>
{environmentsLoading ? (
<div className="flex justify-center py-8">
<div className="text-sm text-muted-foreground">
Loading environments...
</div>
</div>
) : environments && environments.length > 0 ? (
<div className="space-y-3">
{environments.map((env) => (
<div
key={env.environmentId}
className="flex items-center justify-between p-4 border rounded-lg"
>
<div className="space-y-1">
<div className="flex items-center gap-2">
<h4 className="font-medium">{env.name}</h4>
{env.name === "production" && (
<Badge variant="default">Default</Badge>
)}
</div>
{env.description && (
<p className="text-sm text-muted-foreground">
{env.description}
</p>
)}
<DateTooltip date={env.createdAt}>
<span className="text-xs text-muted-foreground">
Created
</span>
</DateTooltip>
</div>
<div className="flex items-center gap-2">
<Button
variant="outline"
size="sm"
onClick={() =>
handleDuplicateClick(env.environmentId, env.name)
}
>
<Copy className="h-4 w-4" />
</Button>
{env.name !== "production" && (
<DialogAction
title="Delete Environment"
description={`Are you sure you want to delete the "${env.name}" environment? This action cannot be undone.`}
type="destructive"
onClick={() =>
handleDeleteEnvironment(env.environmentId)
}
>
<Button variant="outline" size="sm">
<Trash2 className="h-4 w-4" />
</Button>
</DialogAction>
)}
</div>
</div>
))}
</div>
) : (
<div className="text-center py-8">
<div className="text-sm text-muted-foreground">
No environments found. The production environment should be
created automatically.
</div>
</div>
)}
</div>
</DialogContent>
</Dialog>
{/* Create Environment Dialog */}
<Dialog open={isCreateDialogOpen} onOpenChange={setIsCreateDialogOpen}>
<DialogContent>
<DialogHeader>
<DialogTitle>Create New Environment</DialogTitle>
<DialogDescription>
Create a new environment for this project.
</DialogDescription>
</DialogHeader>
<Form {...createForm}>
<form
onSubmit={createForm.handleSubmit(onCreateSubmit)}
className="space-y-4"
>
<FormField
control={createForm.control}
name="name"
render={({ field }) => (
<FormItem>
<FormLabel>Environment Name</FormLabel>
<FormControl>
<Input
placeholder="e.g., staging, development"
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={createForm.control}
name="description"
render={({ field }) => (
<FormItem>
<FormLabel>Description (Optional)</FormLabel>
<FormControl>
<Textarea
placeholder="Describe this environment..."
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<DialogFooter>
<Button
type="button"
variant="outline"
onClick={() => setIsCreateDialogOpen(false)}
>
Cancel
</Button>
<Button
type="submit"
isLoading={createEnvironmentMutation.isLoading}
>
Create Environment
</Button>
</DialogFooter>
</form>
</Form>
</DialogContent>
</Dialog>
{/* Duplicate Environment Dialog */}
<Dialog
open={isDuplicateDialogOpen}
onOpenChange={setIsDuplicateDialogOpen}
>
<DialogContent>
<DialogHeader>
<DialogTitle>Duplicate Environment</DialogTitle>
<DialogDescription>
Create a copy of the selected environment.
</DialogDescription>
</DialogHeader>
<Form {...duplicateForm}>
<form
onSubmit={duplicateForm.handleSubmit(onDuplicateSubmit)}
className="space-y-4"
>
<FormField
control={duplicateForm.control}
name="name"
render={({ field }) => (
<FormItem>
<FormLabel>New Environment Name</FormLabel>
<FormControl>
<Input placeholder="e.g., staging-copy" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={duplicateForm.control}
name="description"
render={({ field }) => (
<FormItem>
<FormLabel>Description (Optional)</FormLabel>
<FormControl>
<Textarea
placeholder="Describe this environment..."
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<DialogFooter>
<Button
type="button"
variant="outline"
onClick={() => {
setIsDuplicateDialogOpen(false);
setSelectedEnvironmentId("");
duplicateForm.reset();
}}
>
Cancel
</Button>
<Button
type="submit"
isLoading={duplicateEnvironmentMutation.isLoading}
>
Duplicate Environment
</Button>
</DialogFooter>
</form>
</Form>
</DialogContent>
</Dialog>
</>
);
};

View File

@@ -0,0 +1,26 @@
CREATE TABLE "environment" (
"environmentId" text PRIMARY KEY NOT NULL,
"name" text NOT NULL,
"description" text,
"createdAt" text NOT NULL,
"projectId" text NOT NULL
);
--> statement-breakpoint
ALTER TABLE "environment" ADD CONSTRAINT "environment_projectId_project_projectId_fk" FOREIGN KEY ("projectId") REFERENCES "public"."project"("projectId") ON DELETE cascade ON UPDATE no action;
-- Insertar un ambiente "production" para cada proyecto existente
INSERT INTO "environment" ("environmentId", "name", "description", "createdAt", "projectId")
SELECT
-- Generar un ID único para cada ambiente usando el projectId como base
'env_prod_' || "projectId" || '_' || EXTRACT(EPOCH FROM NOW())::text,
'production',
'Production environment',
NOW()::text,
"projectId"
FROM "project"
WHERE "projectId" NOT IN (
SELECT DISTINCT "projectId"
FROM "environment"
WHERE "name" = 'production'
);

View File

@@ -0,0 +1,111 @@
-- Step 1: Add environmentId columns as nullable first
ALTER TABLE "application" ADD COLUMN "environmentId" text;--> statement-breakpoint
ALTER TABLE "compose" ADD COLUMN "environmentId" text;--> statement-breakpoint
ALTER TABLE "mariadb" ADD COLUMN "environmentId" text;--> statement-breakpoint
ALTER TABLE "mongo" ADD COLUMN "environmentId" text;--> statement-breakpoint
ALTER TABLE "mysql" ADD COLUMN "environmentId" text;--> statement-breakpoint
ALTER TABLE "postgres" ADD COLUMN "environmentId" text;--> statement-breakpoint
ALTER TABLE "redis" ADD COLUMN "environmentId" text;--> statement-breakpoint
-- Step 2: Create production environment for each project that doesn't have one
-- INSERT INTO "environment" ("environmentId", "name", "description", "createdAt", "projectId")
-- SELECT
-- 'env_prod_' || p."projectId" || '_' || EXTRACT(EPOCH FROM NOW())::text,
-- 'production',
-- 'Production environment',
-- NOW()::text,
-- p."projectId"
-- FROM "project" p
-- WHERE NOT EXISTS (
-- SELECT 1 FROM "environment" e
-- WHERE e."projectId" = p."projectId" AND e."name" = 'production'
-- );--> statement-breakpoint
-- Step 3: Update all services to point to their project's production environment
-- Update applications
UPDATE "application"
SET "environmentId" = (
SELECT e."environmentId"
FROM "environment" e
WHERE e."projectId" = "application"."projectId"
AND e."name" = 'production'
LIMIT 1
);--> statement-breakpoint
-- Update compose
UPDATE "compose"
SET "environmentId" = (
SELECT e."environmentId"
FROM "environment" e
WHERE e."projectId" = "compose"."projectId"
AND e."name" = 'production'
LIMIT 1
);--> statement-breakpoint
-- Update mariadb
UPDATE "mariadb"
SET "environmentId" = (
SELECT e."environmentId"
FROM "environment" e
WHERE e."projectId" = "mariadb"."projectId"
AND e."name" = 'production'
LIMIT 1
);--> statement-breakpoint
-- Update mongo
UPDATE "mongo"
SET "environmentId" = (
SELECT e."environmentId"
FROM "environment" e
WHERE e."projectId" = "mongo"."projectId"
AND e."name" = 'production'
LIMIT 1
);--> statement-breakpoint
-- Update mysql
UPDATE "mysql"
SET "environmentId" = (
SELECT e."environmentId"
FROM "environment" e
WHERE e."projectId" = "mysql"."projectId"
AND e."name" = 'production'
LIMIT 1
);--> statement-breakpoint
-- Update postgres
UPDATE "postgres"
SET "environmentId" = (
SELECT e."environmentId"
FROM "environment" e
WHERE e."projectId" = "postgres"."projectId"
AND e."name" = 'production'
LIMIT 1
);--> statement-breakpoint
-- Update redis
UPDATE "redis"
SET "environmentId" = (
SELECT e."environmentId"
FROM "environment" e
WHERE e."projectId" = "redis"."projectId"
AND e."name" = 'production'
LIMIT 1
);--> statement-breakpoint
-- Step 4: Make environmentId columns NOT NULL
ALTER TABLE "application" ALTER COLUMN "environmentId" SET NOT NULL;--> statement-breakpoint
ALTER TABLE "compose" ALTER COLUMN "environmentId" SET NOT NULL;--> statement-breakpoint
ALTER TABLE "mariadb" ALTER COLUMN "environmentId" SET NOT NULL;--> statement-breakpoint
ALTER TABLE "mongo" ALTER COLUMN "environmentId" SET NOT NULL;--> statement-breakpoint
ALTER TABLE "mysql" ALTER COLUMN "environmentId" SET NOT NULL;--> statement-breakpoint
ALTER TABLE "postgres" ALTER COLUMN "environmentId" SET NOT NULL;--> statement-breakpoint
ALTER TABLE "redis" ALTER COLUMN "environmentId" SET NOT NULL;--> statement-breakpoint
-- Step 5: Add foreign key constraints
ALTER TABLE "application" ADD CONSTRAINT "application_environmentId_environment_environmentId_fk" FOREIGN KEY ("environmentId") REFERENCES "public"."environment"("environmentId") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "compose" ADD CONSTRAINT "compose_environmentId_environment_environmentId_fk" FOREIGN KEY ("environmentId") REFERENCES "public"."environment"("environmentId") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "mariadb" ADD CONSTRAINT "mariadb_environmentId_environment_environmentId_fk" FOREIGN KEY ("environmentId") REFERENCES "public"."environment"("environmentId") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "mongo" ADD CONSTRAINT "mongo_environmentId_environment_environmentId_fk" FOREIGN KEY ("environmentId") REFERENCES "public"."environment"("environmentId") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "mysql" ADD CONSTRAINT "mysql_environmentId_environment_environmentId_fk" FOREIGN KEY ("environmentId") REFERENCES "public"."environment"("environmentId") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "postgres" ADD CONSTRAINT "postgres_environmentId_environment_environmentId_fk" FOREIGN KEY ("environmentId") REFERENCES "public"."environment"("environmentId") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "redis" ADD CONSTRAINT "redis_environmentId_environment_environmentId_fk" FOREIGN KEY ("environmentId") REFERENCES "public"."environment"("environmentId") ON DELETE cascade ON UPDATE no action;

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -750,6 +750,20 @@
"when": 1754912062243,
"tag": "0106_purple_maggott",
"breakpoints": true
},
{
"idx": 107,
"version": "7",
"when": 1756766249772,
"tag": "0107_charming_chimera",
"breakpoints": true
},
{
"idx": 108,
"version": "7",
"when": 1756767917601,
"tag": "0108_keen_doctor_faustus",
"breakpoints": true
}
]
}

View File

@@ -32,6 +32,7 @@ import { AddCompose } from "@/components/dashboard/project/add-compose";
import { AddDatabase } from "@/components/dashboard/project/add-database";
import { AddTemplate } from "@/components/dashboard/project/add-template";
import { DuplicateProject } from "@/components/dashboard/project/duplicate-project";
import { EnvironmentManagement } from "@/components/dashboard/project/environment-management";
import { ProjectEnvironment } from "@/components/dashboard/projects/project-environment";
import {
MariadbIcon,
@@ -46,7 +47,6 @@ import { BreadcrumbSidebar } from "@/components/shared/breadcrumb-sidebar";
import { DateTooltip } from "@/components/shared/date-tooltip";
import { DialogAction } from "@/components/shared/dialog-action";
import { StatusTooltip } from "@/components/shared/status-tooltip";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import {
Card,
@@ -721,6 +721,9 @@ const Project = (
<ProjectEnvironment projectId={projectId}>
<Button variant="outline">Project Environment</Button>
</ProjectEnvironment>
<EnvironmentManagement projectId={projectId}>
<Button variant="outline">Environments</Button>
</EnvironmentManagement>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button>

View File

@@ -11,6 +11,7 @@ import { deploymentRouter } from "./routers/deployment";
import { destinationRouter } from "./routers/destination";
import { dockerRouter } from "./routers/docker";
import { domainRouter } from "./routers/domain";
import { environmentRouter } from "./routers/environment";
import { gitProviderRouter } from "./routers/git-provider";
import { giteaRouter } from "./routers/gitea";
import { githubRouter } from "./routers/github";
@@ -84,6 +85,7 @@ export const appRouter = createTRPCRouter({
schedule: scheduleRouter,
rollback: rollbackRouter,
volumeBackups: volumeBackupsRouter,
environment: environmentRouter,
});
// export type definition of API

View File

@@ -0,0 +1,113 @@
import {
createEnvironment,
deleteEnvironment,
duplicateEnvironment,
findEnvironmentById,
findEnvironmentsByProjectId,
updateEnvironmentById,
} from "@dokploy/server";
import { TRPCError } from "@trpc/server";
import { z } from "zod";
import { createTRPCRouter, protectedProcedure } from "@/server/api/trpc";
import {
apiCreateEnvironment,
apiDuplicateEnvironment,
apiFindOneEnvironment,
apiRemoveEnvironment,
apiUpdateEnvironment,
} from "@/server/db/schema";
export const environmentRouter = createTRPCRouter({
create: protectedProcedure
.input(apiCreateEnvironment)
.mutation(async ({ input }) => {
try {
// Check if user has access to the project
// This would typically involve checking project ownership/membership
// For now, we'll use a basic organization check
const environment = await createEnvironment(input);
return environment;
} catch (error) {
throw new TRPCError({
code: "BAD_REQUEST",
message: `Error creating the environment: ${error instanceof Error ? error.message : error}`,
cause: error,
});
}
}),
one: protectedProcedure
.input(apiFindOneEnvironment)
.query(async ({ input }) => {
try {
const environment = await findEnvironmentById(input.environmentId);
return environment;
} catch (error) {
throw new TRPCError({
code: "NOT_FOUND",
message: "Environment not found",
});
}
}),
byProjectId: protectedProcedure
.input(z.object({ projectId: z.string() }))
.query(async ({ input }) => {
try {
const environments = await findEnvironmentsByProjectId(input.projectId);
return environments;
} catch (error) {
throw new TRPCError({
code: "BAD_REQUEST",
message: `Error fetching environments: ${error instanceof Error ? error.message : error}`,
});
}
}),
remove: protectedProcedure
.input(apiRemoveEnvironment)
.mutation(async ({ input }) => {
try {
const deletedEnvironment = await deleteEnvironment(input.environmentId);
return deletedEnvironment;
} catch (error) {
throw new TRPCError({
code: "BAD_REQUEST",
message: `Error deleting the environment: ${error instanceof Error ? error.message : error}`,
});
}
}),
update: protectedProcedure
.input(apiUpdateEnvironment)
.mutation(async ({ input }) => {
try {
const { environmentId, ...updateData } = input;
const environment = await updateEnvironmentById(
environmentId,
updateData,
);
return environment;
} catch (error) {
throw new TRPCError({
code: "BAD_REQUEST",
message: `Error updating the environment: ${error instanceof Error ? error.message : error}`,
});
}
}),
duplicate: protectedProcedure
.input(apiDuplicateEnvironment)
.mutation(async ({ input }) => {
try {
const duplicatedEnvironment = await duplicateEnvironment(input);
return duplicatedEnvironment;
} catch (error) {
throw new TRPCError({
code: "BAD_REQUEST",
message: `Error duplicating the environment: ${error instanceof Error ? error.message : error}`,
});
}
}),
});

View File

@@ -117,29 +117,42 @@ export const projectRouter = createTRPCRouter({
eq(projects.organizationId, ctx.session.activeOrganizationId),
),
with: {
applications: {
where: buildServiceFilter(
applications.applicationId,
accessedServices,
),
},
compose: {
where: buildServiceFilter(compose.composeId, accessedServices),
},
mariadb: {
where: buildServiceFilter(mariadb.mariadbId, accessedServices),
},
mongo: {
where: buildServiceFilter(mongo.mongoId, accessedServices),
},
mysql: {
where: buildServiceFilter(mysql.mysqlId, accessedServices),
},
postgres: {
where: buildServiceFilter(postgres.postgresId, accessedServices),
},
redis: {
where: buildServiceFilter(redis.redisId, accessedServices),
environments: {
with: {
applications: {
where: buildServiceFilter(
applications.applicationId,
accessedServices,
),
},
compose: {
where: buildServiceFilter(
compose.composeId,
accessedServices,
),
},
mariadb: {
where: buildServiceFilter(
mariadb.mariadbId,
accessedServices,
),
},
mongo: {
where: buildServiceFilter(mongo.mongoId, accessedServices),
},
mysql: {
where: buildServiceFilter(mysql.mysqlId, accessedServices),
},
postgres: {
where: buildServiceFilter(
postgres.postgresId,
accessedServices,
),
},
redis: {
where: buildServiceFilter(redis.redisId, accessedServices),
},
},
},
},
});
@@ -182,31 +195,38 @@ export const projectRouter = createTRPCRouter({
eq(projects.organizationId, ctx.session.activeOrganizationId),
),
with: {
applications: {
where: buildServiceFilter(
applications.applicationId,
accessedServices,
),
with: { domains: true },
},
mariadb: {
where: buildServiceFilter(mariadb.mariadbId, accessedServices),
},
mongo: {
where: buildServiceFilter(mongo.mongoId, accessedServices),
},
mysql: {
where: buildServiceFilter(mysql.mysqlId, accessedServices),
},
postgres: {
where: buildServiceFilter(postgres.postgresId, accessedServices),
},
redis: {
where: buildServiceFilter(redis.redisId, accessedServices),
},
compose: {
where: buildServiceFilter(compose.composeId, accessedServices),
with: { domains: true },
environments: {
with: {
applications: {
where: buildServiceFilter(
applications.applicationId,
accessedServices,
),
with: { domains: true },
},
mariadb: {
where: buildServiceFilter(mariadb.mariadbId, accessedServices),
},
mongo: {
where: buildServiceFilter(mongo.mongoId, accessedServices),
},
mysql: {
where: buildServiceFilter(mysql.mysqlId, accessedServices),
},
postgres: {
where: buildServiceFilter(
postgres.postgresId,
accessedServices,
),
},
redis: {
where: buildServiceFilter(redis.redisId, accessedServices),
},
compose: {
where: buildServiceFilter(compose.composeId, accessedServices),
with: { domains: true },
},
},
},
},
orderBy: desc(projects.createdAt),
@@ -215,19 +235,23 @@ export const projectRouter = createTRPCRouter({
return await db.query.projects.findMany({
with: {
applications: {
environments: {
with: {
domains: true,
},
},
mariadb: true,
mongo: true,
mysql: true,
postgres: true,
redis: true,
compose: {
with: {
domains: true,
applications: {
with: {
domains: true,
},
},
mariadb: true,
mongo: true,
mysql: true,
postgres: true,
redis: true,
compose: {
with: {
domains: true,
},
},
},
},
},

View File

@@ -13,6 +13,7 @@ import { z } from "zod";
import { bitbucket } from "./bitbucket";
import { deployments } from "./deployment";
import { domains } from "./domain";
import { environments } from "./environment";
import { gitea } from "./gitea";
import { github } from "./github";
import { gitlab } from "./gitlab";
@@ -182,6 +183,9 @@ export const applications = pgTable("application", {
projectId: text("projectId")
.notNull()
.references(() => projects.projectId, { onDelete: "cascade" }),
environmentId: text("environmentId")
.notNull()
.references(() => environments.environmentId, { onDelete: "cascade" }),
githubId: text("githubId").references(() => github.githubId, {
onDelete: "set null",
}),
@@ -206,6 +210,10 @@ export const applicationsRelations = relations(
fields: [applications.projectId],
references: [projects.projectId],
}),
environment: one(environments, {
fields: [applications.environmentId],
references: [environments.environmentId],
}),
deployments: many(deployments),
customGitSSHKey: one(sshKeys, {
fields: [applications.customGitSSHKeyId],
@@ -274,6 +282,7 @@ const createSchema = createInsertSchema(applications, {
customGitUrl: z.string().optional(),
buildPath: z.string().optional(),
projectId: z.string(),
environmentId: z.string(),
sourceType: z
.enum(["github", "docker", "git", "gitlab", "bitbucket", "gitea", "drop"])
.optional(),
@@ -318,6 +327,7 @@ export const apiCreateApplication = createSchema.pick({
appName: true,
description: true,
projectId: true,
environmentId: true,
serverId: true,
});

View File

@@ -7,6 +7,7 @@ import { backups } from "./backups";
import { bitbucket } from "./bitbucket";
import { deployments } from "./deployment";
import { domains } from "./domain";
import { environments } from "./environment";
import { gitea } from "./gitea";
import { github } from "./github";
import { gitlab } from "./gitlab";
@@ -87,6 +88,9 @@ export const compose = pgTable("compose", {
projectId: text("projectId")
.notNull()
.references(() => projects.projectId, { onDelete: "cascade" }),
environmentId: text("environmentId")
.notNull()
.references(() => environments.environmentId, { onDelete: "cascade" }),
createdAt: text("createdAt")
.notNull()
.$defaultFn(() => new Date().toISOString()),
@@ -113,6 +117,10 @@ export const composeRelations = relations(compose, ({ one, many }) => ({
fields: [compose.projectId],
references: [projects.projectId],
}),
environment: one(environments, {
fields: [compose.environmentId],
references: [environments.environmentId],
}),
deployments: many(deployments),
mounts: many(mounts),
customGitSSHKey: one(sshKeys, {
@@ -150,6 +158,7 @@ const createSchema = createInsertSchema(compose, {
env: z.string().optional(),
composeFile: z.string().optional(),
projectId: z.string(),
environmentId: z.string(),
customGitSSHKeyId: z.string().optional(),
command: z.string().optional(),
composePath: z.string().min(1),
@@ -161,6 +170,7 @@ export const apiCreateCompose = createSchema.pick({
name: true,
description: true,
projectId: true,
environmentId: true,
composeType: true,
appName: true,
serverId: true,
@@ -170,6 +180,7 @@ export const apiCreateCompose = createSchema.pick({
export const apiCreateComposeByTemplate = createSchema
.pick({
projectId: true,
environmentId: true,
})
.extend({
id: z.string().min(1),

View File

@@ -0,0 +1,84 @@
import { relations } from "drizzle-orm";
import { pgTable, text } from "drizzle-orm/pg-core";
import { createInsertSchema } from "drizzle-zod";
import { nanoid } from "nanoid";
import { z } from "zod";
import { applications } from "./application";
import { compose } from "./compose";
import { mariadb } from "./mariadb";
import { mongo } from "./mongo";
import { mysql } from "./mysql";
import { postgres } from "./postgres";
import { projects } from "./project";
import { redis } from "./redis";
export const environments = pgTable("environment", {
environmentId: text("environmentId")
.notNull()
.primaryKey()
.$defaultFn(() => nanoid()),
name: text("name").notNull(),
description: text("description"),
createdAt: text("createdAt")
.notNull()
.$defaultFn(() => new Date().toISOString()),
projectId: text("projectId")
.notNull()
.references(() => projects.projectId, { onDelete: "cascade" }),
});
export const environmentRelations = relations(
environments,
({ one, many }) => ({
project: one(projects, {
fields: [environments.projectId],
references: [projects.projectId],
}),
applications: many(applications),
mariadb: many(mariadb),
postgres: many(postgres),
mysql: many(mysql),
redis: many(redis),
mongo: many(mongo),
compose: many(compose),
}),
);
const createSchema = createInsertSchema(environments, {
environmentId: z.string().min(1),
name: z.string().min(1),
description: z.string().optional(),
});
export const apiCreateEnvironment = createSchema.pick({
name: true,
description: true,
projectId: true,
});
export const apiFindOneEnvironment = createSchema
.pick({
environmentId: true,
})
.required();
export const apiRemoveEnvironment = createSchema
.pick({
environmentId: true,
})
.required();
export const apiUpdateEnvironment = createSchema.partial().extend({
environmentId: z.string().min(1),
});
export const apiDuplicateEnvironment = createSchema
.pick({
environmentId: true,
name: true,
description: true,
})
.required({
environmentId: true,
name: true,
});

View File

@@ -8,6 +8,7 @@ export * from "./compose";
export * from "./deployment";
export * from "./destination";
export * from "./domain";
export * from "./environment";
export * from "./git-provider";
export * from "./gitea";
export * from "./github";

View File

@@ -4,6 +4,7 @@ import { createInsertSchema } from "drizzle-zod";
import { nanoid } from "nanoid";
import { z } from "zod";
import { backups } from "./backups";
import { environments } from "./environment";
import { mounts } from "./mount";
import { projects } from "./project";
import { server } from "./server";
@@ -69,6 +70,9 @@ export const mariadb = pgTable("mariadb", {
projectId: text("projectId")
.notNull()
.references(() => projects.projectId, { onDelete: "cascade" }),
environmentId: text("environmentId")
.notNull()
.references(() => environments.environmentId, { onDelete: "cascade" }),
serverId: text("serverId").references(() => server.serverId, {
onDelete: "cascade",
}),
@@ -79,6 +83,10 @@ export const mariadbRelations = relations(mariadb, ({ one, many }) => ({
fields: [mariadb.projectId],
references: [projects.projectId],
}),
environment: one(environments, {
fields: [mariadb.environmentId],
references: [environments.environmentId],
}),
backups: many(backups),
mounts: many(mounts),
server: one(server, {
@@ -116,6 +124,7 @@ const createSchema = createInsertSchema(mariadb, {
cpuReservation: z.string().optional(),
cpuLimit: z.string().optional(),
projectId: z.string(),
environmentId: z.string(),
applicationStatus: z.enum(["idle", "running", "done", "error"]),
externalPort: z.number(),
description: z.string().optional(),
@@ -137,6 +146,7 @@ export const apiCreateMariaDB = createSchema
dockerImage: true,
databaseRootPassword: true,
projectId: true,
environmentId: true,
description: true,
databaseName: true,
databaseUser: true,

View File

@@ -4,6 +4,7 @@ import { createInsertSchema } from "drizzle-zod";
import { nanoid } from "nanoid";
import { z } from "zod";
import { backups } from "./backups";
import { environments } from "./environment";
import { mounts } from "./mount";
import { projects } from "./project";
import { server } from "./server";
@@ -65,6 +66,9 @@ export const mongo = pgTable("mongo", {
projectId: text("projectId")
.notNull()
.references(() => projects.projectId, { onDelete: "cascade" }),
environmentId: text("environmentId")
.notNull()
.references(() => environments.environmentId, { onDelete: "cascade" }),
serverId: text("serverId").references(() => server.serverId, {
onDelete: "cascade",
}),
@@ -76,6 +80,10 @@ export const mongoRelations = relations(mongo, ({ one, many }) => ({
fields: [mongo.projectId],
references: [projects.projectId],
}),
environment: one(environments, {
fields: [mongo.environmentId],
references: [environments.environmentId],
}),
backups: many(backups),
mounts: many(mounts),
server: one(server, {
@@ -105,6 +113,7 @@ const createSchema = createInsertSchema(mongo, {
cpuReservation: z.string().optional(),
cpuLimit: z.string().optional(),
projectId: z.string(),
environmentId: z.string(),
applicationStatus: z.enum(["idle", "running", "done", "error"]),
externalPort: z.number(),
description: z.string().optional(),
@@ -126,6 +135,7 @@ export const apiCreateMongo = createSchema
appName: true,
dockerImage: true,
projectId: true,
environmentId: true,
description: true,
databaseUser: true,
databasePassword: true,

View File

@@ -4,6 +4,7 @@ import { createInsertSchema } from "drizzle-zod";
import { nanoid } from "nanoid";
import { z } from "zod";
import { backups } from "./backups";
import { environments } from "./environment";
import { mounts } from "./mount";
import { projects } from "./project";
import { server } from "./server";
@@ -67,6 +68,9 @@ export const mysql = pgTable("mysql", {
projectId: text("projectId")
.notNull()
.references(() => projects.projectId, { onDelete: "cascade" }),
environmentId: text("environmentId")
.notNull()
.references(() => environments.environmentId, { onDelete: "cascade" }),
serverId: text("serverId").references(() => server.serverId, {
onDelete: "cascade",
}),
@@ -77,6 +81,10 @@ export const mysqlRelations = relations(mysql, ({ one, many }) => ({
fields: [mysql.projectId],
references: [projects.projectId],
}),
environment: one(environments, {
fields: [mysql.environmentId],
references: [environments.environmentId],
}),
backups: many(backups),
mounts: many(mounts),
server: one(server, {
@@ -134,6 +142,7 @@ export const apiCreateMySql = createSchema
appName: true,
dockerImage: true,
projectId: true,
environmentId: true,
description: true,
databaseName: true,
databaseUser: true,

View File

@@ -4,6 +4,7 @@ import { createInsertSchema } from "drizzle-zod";
import { nanoid } from "nanoid";
import { z } from "zod";
import { backups } from "./backups";
import { environments } from "./environment";
import { mounts } from "./mount";
import { projects } from "./project";
import { server } from "./server";
@@ -67,6 +68,9 @@ export const postgres = pgTable("postgres", {
projectId: text("projectId")
.notNull()
.references(() => projects.projectId, { onDelete: "cascade" }),
environmentId: text("environmentId")
.notNull()
.references(() => environments.environmentId, { onDelete: "cascade" }),
serverId: text("serverId").references(() => server.serverId, {
onDelete: "cascade",
}),
@@ -77,6 +81,10 @@ export const postgresRelations = relations(postgres, ({ one, many }) => ({
fields: [postgres.projectId],
references: [projects.projectId],
}),
environment: one(environments, {
fields: [postgres.environmentId],
references: [environments.environmentId],
}),
backups: many(backups),
mounts: many(mounts),
server: one(server, {
@@ -105,6 +113,7 @@ const createSchema = createInsertSchema(postgres, {
cpuReservation: z.string().optional(),
cpuLimit: z.string().optional(),
projectId: z.string(),
environmentId: z.string(),
applicationStatus: z.enum(["idle", "running", "done", "error"]),
externalPort: z.number(),
createdAt: z.string(),
@@ -129,6 +138,7 @@ export const apiCreatePostgres = createSchema
databasePassword: true,
dockerImage: true,
projectId: true,
environmentId: true,
description: true,
serverId: true,
})

View File

@@ -4,13 +4,7 @@ import { createInsertSchema } from "drizzle-zod";
import { nanoid } from "nanoid";
import { z } from "zod";
import { organization } from "./account";
import { applications } from "./application";
import { compose } from "./compose";
import { mariadb } from "./mariadb";
import { mongo } from "./mongo";
import { mysql } from "./mysql";
import { postgres } from "./postgres";
import { redis } from "./redis";
import { environments } from "./environment";
export const projects = pgTable("project", {
projectId: text("projectId")
@@ -30,13 +24,7 @@ export const projects = pgTable("project", {
});
export const projectRelations = relations(projects, ({ many, one }) => ({
mysql: many(mysql),
postgres: many(postgres),
mariadb: many(mariadb),
applications: many(applications),
mongo: many(mongo),
redis: many(redis),
compose: many(compose),
environments: many(environments),
organization: one(organization, {
fields: [projects.organizationId],
references: [organization.id],

View File

@@ -3,6 +3,7 @@ import { integer, json, pgTable, text } from "drizzle-orm/pg-core";
import { createInsertSchema } from "drizzle-zod";
import { nanoid } from "nanoid";
import { z } from "zod";
import { environments } from "./environment";
import { mounts } from "./mount";
import { projects } from "./project";
import { server } from "./server";
@@ -63,6 +64,9 @@ export const redis = pgTable("redis", {
projectId: text("projectId")
.notNull()
.references(() => projects.projectId, { onDelete: "cascade" }),
environmentId: text("environmentId")
.notNull()
.references(() => environments.environmentId, { onDelete: "cascade" }),
serverId: text("serverId").references(() => server.serverId, {
onDelete: "cascade",
}),
@@ -73,6 +77,10 @@ export const redisRelations = relations(redis, ({ one, many }) => ({
fields: [redis.projectId],
references: [projects.projectId],
}),
environment: one(environments, {
fields: [redis.environmentId],
references: [environments.environmentId],
}),
mounts: many(mounts),
server: one(server, {
fields: [redis.serverId],
@@ -94,6 +102,7 @@ const createSchema = createInsertSchema(redis, {
cpuReservation: z.string().optional(),
cpuLimit: z.string().optional(),
projectId: z.string(),
environmentId: z.string(),
applicationStatus: z.enum(["idle", "running", "done", "error"]),
externalPort: z.number(),
description: z.string().optional(),
@@ -115,6 +124,7 @@ export const apiCreateRedis = createSchema
databasePassword: true,
dockerImage: true,
projectId: true,
environmentId: true,
description: true,
serverId: true,
})

View File

@@ -16,6 +16,7 @@ export * from "./services/deployment";
export * from "./services/destination";
export * from "./services/docker";
export * from "./services/domain";
export * from "./services/environment";
export * from "./services/git-provider";
export * from "./services/gitea";
export * from "./services/github";

View File

@@ -0,0 +1,113 @@
import { db } from "@dokploy/server/db";
import {
type apiCreateEnvironment,
type apiDuplicateEnvironment,
environments,
} from "@dokploy/server/db/schema";
import { TRPCError } from "@trpc/server";
import { eq } from "drizzle-orm";
export type Environment = typeof environments.$inferSelect;
export const createEnvironment = async (
input: typeof apiCreateEnvironment._type,
) => {
const newEnvironment = await db
.insert(environments)
.values({
...input,
})
.returning()
.then((value) => value[0]);
if (!newEnvironment) {
throw new TRPCError({
code: "BAD_REQUEST",
message: "Error creating the environment",
});
}
return newEnvironment;
};
export const findEnvironmentById = async (environmentId: string) => {
const environment = await db.query.environments.findFirst({
where: eq(environments.environmentId, environmentId),
});
if (!environment) {
throw new TRPCError({
code: "NOT_FOUND",
message: "Environment not found",
});
}
return environment;
};
export const findEnvironmentsByProjectId = async (projectId: string) => {
const projectEnvironments = await db.query.environments.findMany({
where: eq(environments.projectId, projectId),
orderBy: (environments, { asc }) => [asc(environments.createdAt)],
});
return projectEnvironments;
};
export const deleteEnvironment = async (environmentId: string) => {
const environment = await db
.delete(environments)
.where(eq(environments.environmentId, environmentId))
.returning()
.then((value) => value[0]);
return environment;
};
export const updateEnvironmentById = async (
environmentId: string,
environmentData: Partial<Environment>,
) => {
const result = await db
.update(environments)
.set({
...environmentData,
})
.where(eq(environments.environmentId, environmentId))
.returning()
.then((res) => res[0]);
return result;
};
export const duplicateEnvironment = async (
input: typeof apiDuplicateEnvironment._type,
) => {
// Find the original environment
const originalEnvironment = await findEnvironmentById(input.environmentId);
// Create a new environment with the provided name and description
const newEnvironment = await db
.insert(environments)
.values({
name: input.name,
description: input.description || originalEnvironment.description,
projectId: originalEnvironment.projectId,
})
.returning()
.then((value) => value[0]);
if (!newEnvironment) {
throw new TRPCError({
code: "BAD_REQUEST",
message: "Error duplicating the environment",
});
}
return newEnvironment;
};
export const createProductionEnvironment = async (projectId: string) => {
return createEnvironment({
name: "production",
description: "Production environment",
projectId,
});
};

View File

@@ -11,6 +11,7 @@ import {
} from "@dokploy/server/db/schema";
import { TRPCError } from "@trpc/server";
import { eq } from "drizzle-orm";
import { createProductionEnvironment } from "./environment";
export type Project = typeof projects.$inferSelect;
@@ -34,6 +35,14 @@ export const createProject = async (
});
}
// Automatically create a production environment
try {
await createProductionEnvironment(newProject.projectId);
} catch (error) {
console.error("Error creating production environment:", error);
// Don't fail project creation if environment creation fails
}
return newProject;
};
@@ -41,13 +50,17 @@ export const findProjectById = async (projectId: string) => {
const project = await db.query.projects.findFirst({
where: eq(projects.projectId, projectId),
with: {
applications: true,
mariadb: true,
mongo: true,
mysql: true,
postgres: true,
redis: true,
compose: true,
environments: {
with: {
applications: true,
mariadb: true,
mongo: true,
mysql: true,
postgres: true,
redis: true,
compose: true,
},
},
},
});
if (!project) {