68 lines
1.7 KiB
TypeScript
68 lines
1.7 KiB
TypeScript
|
|
import { and, eq } from "drizzle-orm";
|
||
|
|
import type { PostgresJsDatabase } from "drizzle-orm/postgres-js";
|
||
|
|
|
||
|
|
import { PIPELINE_DEFAULT_ROLE_ROUTES } from "@tasks/shared/model-routing";
|
||
|
|
|
||
|
|
import type * as schema from "../schema/index";
|
||
|
|
import { modelProviders, roleModelRoutes } from "../schema/index";
|
||
|
|
|
||
|
|
type Database = PostgresJsDatabase<typeof schema>;
|
||
|
|
|
||
|
|
export type SeedDefaultRoleRoutesResult = {
|
||
|
|
inserted: number;
|
||
|
|
skipped: number;
|
||
|
|
};
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Inserts pipeline default role → alias routes for a workspace when matching
|
||
|
|
* provider aliases already exist. Does not create providers.
|
||
|
|
*/
|
||
|
|
export async function seedDefaultRoleRoutes(
|
||
|
|
db: Database,
|
||
|
|
workspaceId: string,
|
||
|
|
): Promise<SeedDefaultRoleRoutesResult> {
|
||
|
|
const providers = await db
|
||
|
|
.select({ id: modelProviders.id, alias: modelProviders.alias })
|
||
|
|
.from(modelProviders)
|
||
|
|
.where(eq(modelProviders.workspaceId, workspaceId));
|
||
|
|
|
||
|
|
const aliasToId = new Map(providers.map((row) => [row.alias, row.id]));
|
||
|
|
let inserted = 0;
|
||
|
|
let skipped = 0;
|
||
|
|
let sortOrder = 0;
|
||
|
|
|
||
|
|
for (const [roleId, alias] of Object.entries(PIPELINE_DEFAULT_ROLE_ROUTES)) {
|
||
|
|
const providerId = aliasToId.get(alias);
|
||
|
|
if (!providerId) {
|
||
|
|
skipped++;
|
||
|
|
continue;
|
||
|
|
}
|
||
|
|
|
||
|
|
const [existing] = await db
|
||
|
|
.select({ id: roleModelRoutes.id })
|
||
|
|
.from(roleModelRoutes)
|
||
|
|
.where(
|
||
|
|
and(
|
||
|
|
eq(roleModelRoutes.workspaceId, workspaceId),
|
||
|
|
eq(roleModelRoutes.roleId, roleId),
|
||
|
|
),
|
||
|
|
)
|
||
|
|
.limit(1);
|
||
|
|
|
||
|
|
if (existing) {
|
||
|
|
skipped++;
|
||
|
|
continue;
|
||
|
|
}
|
||
|
|
|
||
|
|
await db.insert(roleModelRoutes).values({
|
||
|
|
workspaceId,
|
||
|
|
roleId,
|
||
|
|
providerAliasId: providerId,
|
||
|
|
sortOrder: sortOrder++,
|
||
|
|
});
|
||
|
|
inserted++;
|
||
|
|
}
|
||
|
|
|
||
|
|
return { inserted, skipped };
|
||
|
|
}
|