(
data: RowData,
schema: TableSchema,
existingRows: { id: string; data: RowData; position?: number }[],
excludeRowId?: string
)
| 374 | |
| 375 | /** Validates unique constraints against existing rows (in-memory version for batch validation within a batch). */ |
| 376 | export function validateUniqueConstraints( |
| 377 | data: RowData, |
| 378 | schema: TableSchema, |
| 379 | existingRows: { id: string; data: RowData; position?: number }[], |
| 380 | excludeRowId?: string |
| 381 | ): ValidationResult { |
| 382 | const errors: string[] = [] |
| 383 | const uniqueColumns = getUniqueColumns(schema) |
| 384 | |
| 385 | for (const column of uniqueColumns) { |
| 386 | const key = getColumnId(column) |
| 387 | const value = data[key] |
| 388 | if (value === null || value === undefined) continue |
| 389 | |
| 390 | const duplicate = existingRows.find((row) => { |
| 391 | if (excludeRowId && row.id === excludeRowId) return false |
| 392 | |
| 393 | const existingValue = row.data[key] |
| 394 | if (typeof value === 'string' && typeof existingValue === 'string') { |
| 395 | return value.toLowerCase() === existingValue.toLowerCase() |
| 396 | } |
| 397 | return value === existingValue |
| 398 | }) |
| 399 | |
| 400 | if (duplicate) { |
| 401 | const rowLabel = |
| 402 | typeof duplicate.position === 'number' ? `row ${duplicate.position + 1}` : duplicate.id |
| 403 | errors.push( |
| 404 | `Column "${column.name}" must be unique. Value "${value}" already exists in ${rowLabel}` |
| 405 | ) |
| 406 | } |
| 407 | } |
| 408 | |
| 409 | return { valid: errors.length === 0, errors } |
| 410 | } |
| 411 | |
| 412 | /** |
| 413 | * Checks unique constraints using targeted database queries. |
no test coverage detected