Create values helper & fix video join insertion

This commit is contained in:
Zoe Roux 2025-01-26 21:18:07 +01:00
parent a216fd0d67
commit 2588eef23b
No known key found for this signature in database
2 changed files with 32 additions and 7 deletions

View File

@ -6,7 +6,7 @@ import {
entryVideoJoint as entryVideoJoin, entryVideoJoint as entryVideoJoin,
videos, videos,
} from "~/db/schema"; } from "~/db/schema";
import { conflictUpdateAllExcept } from "~/db/utils"; import { conflictUpdateAllExcept, values } from "~/db/utils";
import type { SeedEntry } from "~/models/entry"; import type { SeedEntry } from "~/models/entry";
import { processOptImage } from "../images"; import { processOptImage } from "../images";
import { guessNextRefresh } from "../refresh"; import { guessNextRefresh } from "../refresh";
@ -83,15 +83,15 @@ export const insertEntries = async (
const hasRenderingQ = db const hasRenderingQ = db
.select() .select()
.from(entryVideoJoin) .from(entryVideoJoin)
.where(eq(entryVideoJoin.entry, sql`vids.entryPk`)); .where(eq(entryVideoJoin.entry, sql`vids.entryPk::integer`));
const retVideos = await db const retVideos = await db
.insert(entryVideoJoin) .insert(entryVideoJoin)
.select( .select(
db db
.select({ .select({
entry: sql<number>`vids.entryPk`.as("entry"), entry: sql<number>`vids.entryPk::integer`.as("entry"),
video: videos.pk, video: sql`${videos.pk}`.as("video"),
slug: sql<string>` slug: sql<string>`
concat( concat(
${show.slug}::text, ${show.slug}::text,
@ -101,11 +101,14 @@ export const insertEntries = async (
) )
`.as("slug"), `.as("slug"),
}) })
.from(sql`values(${vids}) as vids(videoId, entryPk)`) .from(values(vids).as("vids"))
.innerJoin(videos, eq(videos.id, sql`vids.videoId`)), .innerJoin(videos, eq(videos.id, sql`vids.videoId::uuid`)),
) )
.onConflictDoNothing() .onConflictDoNothing()
.returning({ slug: entryVideoJoin.slug, entryPk: sql`vids.entryPk` }); .returning({
slug: entryVideoJoin.slug,
entryPk: entryVideoJoin.entry,
});
return retEntries.map((entry) => ({ return retEntries.map((entry) => ({
id: entry.id, id: entry.id,

View File

@ -70,3 +70,25 @@ export function conflictUpdateAllExcept<
export function sqlarr(array: unknown[]) { export function sqlarr(array: unknown[]) {
return `{${array.map((item) => `"${item}"`).join(",")}}`; return `{${array.map((item) => `"${item}"`).join(",")}}`;
} }
// TODO: upstream this
// TODO: type values (everything is a `text` for now)
export function values(items: Record<string, unknown>[]) {
const [firstProp, ...props] = Object.keys(items[0]);
const values = items
.map((x) => {
let ret = sql`(${x[firstProp]}`;
for (const val of props) {
ret = sql`${ret}, ${x[val]}`;
}
return sql`${ret})`;
})
.reduce((acc, x) => sql`${acc}, ${x}`);
const valueNames = [firstProp, ...props].join(", ");
return {
as: (name: string) => {
return sql`(values ${values}) as ${sql.raw(name)}(${sql.raw(valueNames)})`;
},
};
}