Skip to content

Commit 2be62a8

Browse files
committed
Merge branch 'v0/global/db0811' of https://github.com/thinc-org/ipix into v0/global/db0811
2 parents ee87f2a + f98dd95 commit 2be62a8

1 file changed

Lines changed: 27 additions & 1 deletion

File tree

apps/api/src/modules/item/route.ts

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -220,10 +220,36 @@ export const itemRouter = new Elysia({ prefix: "/v1" })
220220
// Normalize MIME type to lowercase
221221
const normalizedMime = body.contentType.trim().toLowerCase();
222222

223+
// Compute the first available name to avoid unique constraint errors
224+
// Picks: name, name (1), name (2), ... within the same parent/space for non-trashed items
225+
const availableNameRes = await db.execute(sql`
226+
WITH existing AS (
227+
SELECT name
228+
FROM ${storageSchema.item}
229+
WHERE space_id = ${params.spaceId}
230+
AND (parent_id IS NOT DISTINCT FROM ${body.parentId})
231+
AND purge_at IS NULL
232+
),
233+
candidate AS (
234+
SELECT ${body.name} AS name
235+
UNION ALL
236+
SELECT ${body.name} || ' (' || gs.i::text || ')' AS name
237+
FROM generate_series(1, 10000) AS gs(i)
238+
)
239+
SELECT c.name
240+
FROM candidate c
241+
LEFT JOIN existing e ON e.name = c.name
242+
WHERE e.name IS NULL
243+
ORDER BY length(c.name), c.name
244+
LIMIT 1;
245+
`);
246+
247+
const availableName = (availableNameRes as any)?.rows?.[0]?.name ?? body.name;
248+
223249
const inserted = await db
224250
.insert(storageSchema.item)
225251
.values({
226-
name: body.name,
252+
name: availableName,
227253
spaceId: params.spaceId,
228254
parentId: body.parentId,
229255
createdBy: user!.id,

0 commit comments

Comments
 (0)