(params: {
tableId: string
workspaceId: string
data: RowData
rowId: string
position?: number
afterRowId?: string
beforeRowId?: string
createdBy?: string
now: Date
})
| 337 | * `increment_user_table_row_count` trigger. |
| 338 | */ |
| 339 | export async function insertOrderedRow(params: { |
| 340 | tableId: string |
| 341 | workspaceId: string |
| 342 | data: RowData |
| 343 | rowId: string |
| 344 | position?: number |
| 345 | afterRowId?: string |
| 346 | beforeRowId?: string |
| 347 | createdBy?: string |
| 348 | now: Date |
| 349 | }): Promise<{ |
| 350 | id: string |
| 351 | data: RowData |
| 352 | position: number |
| 353 | orderKey: string | null |
| 354 | createdAt: Date |
| 355 | updatedAt: Date |
| 356 | }> { |
| 357 | const { tableId, workspaceId, data, rowId, position, afterRowId, beforeRowId, createdBy, now } = |
| 358 | params |
| 359 | const [row] = await db.transaction(async (trx) => { |
| 360 | await setTableTxTimeouts(trx) |
| 361 | await acquireRowOrderLock(trx, tableId) |
| 362 | |
| 363 | const fractionalOrdering = await isFeatureEnabled('tables-fractional-ordering') |
| 364 | |
| 365 | // Resolve the order key (and a legacy slot position for the flag-off shift |
| 366 | // path) from neighbor ids when given, else from the requested position. |
| 367 | let orderKey: string |
| 368 | let slotPosition = position |
| 369 | if (afterRowId || beforeRowId) { |
| 370 | const resolved = await resolveInsertByNeighbor(trx, tableId, afterRowId, beforeRowId) |
| 371 | orderKey = resolved.orderKey |
| 372 | slotPosition = resolved.position |
| 373 | } else { |
| 374 | orderKey = await resolveInsertOrderKey(trx, tableId, position) |
| 375 | } |
| 376 | |
| 377 | let targetPosition: number |
| 378 | if (fractionalOrdering) { |
| 379 | // order_key is authoritative — keep a best-effort, no-shift position. |
| 380 | targetPosition = await nextRowPosition(trx, tableId) |
| 381 | } else if (slotPosition !== undefined) { |
| 382 | const [existing] = await trx |
| 383 | .select({ id: userTableRows.id }) |
| 384 | .from(userTableRows) |
| 385 | .where(and(eq(userTableRows.tableId, tableId), eq(userTableRows.position, slotPosition))) |
| 386 | .limit(1) |
| 387 | if (existing) await shiftRowsUpFrom(trx, tableId, slotPosition) |
| 388 | targetPosition = slotPosition |
| 389 | } else { |
| 390 | targetPosition = await nextRowPosition(trx, tableId) |
| 391 | } |
| 392 | |
| 393 | return trx |
| 394 | .insert(userTableRows) |
| 395 | .values({ |
| 396 | id: rowId, |
no test coverage detected