Skip to content

Commit 931ba44

Browse files
committed
Add primary key detection for deletes
1 parent 46eefca commit 931ba44

1 file changed

Lines changed: 24 additions & 1 deletion

File tree

sqliteadmin.go

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -247,6 +247,7 @@ func (h *Handler) deleteRows(w http.ResponseWriter, params map[string]interface{
247247
writeError(w, fmt.Errorf("Bad Request"), http.StatusBadRequest)
248248
return
249249
}
250+
250251
rowsAffected, err := batchDelete(h.db, table, ids)
251252
if err != nil {
252253
// TODO: use better logging
@@ -408,6 +409,27 @@ func batchDelete(db *sql.DB, tableName string, ids []any) (int64, error) {
408409
return 0, nil
409410
}
410411

412+
// Get the primary key of the table
413+
tableInfo, err := getTableInfo(db, tableName)
414+
if err != nil {
415+
return 0, fmt.Errorf("error getting primary key for delete: %v", err)
416+
}
417+
columns, ok := tableInfo["columns"].([]map[string]interface{})
418+
if !ok {
419+
return 0, fmt.Errorf("error getting primary key for delete")
420+
}
421+
var primaryKey string
422+
for _, column := range columns {
423+
if column["pk"].(int) == 1 {
424+
primaryKey = column["name"].(string)
425+
break
426+
}
427+
}
428+
429+
if primaryKey == "" {
430+
return 0, fmt.Errorf("table %s does not have a primary key", tableName)
431+
}
432+
411433
// Create the placeholders for the query (?,?,?)
412434
placeholders := make([]string, len(ids))
413435
for i := range ids {
@@ -416,8 +438,9 @@ func batchDelete(db *sql.DB, tableName string, ids []any) (int64, error) {
416438

417439
// Build the query
418440
query := fmt.Sprintf(
419-
"DELETE FROM %s WHERE id IN (%s)",
441+
"DELETE FROM %s WHERE %s IN (%s)",
420442
tableName,
443+
primaryKey,
421444
strings.Join(placeholders, ","),
422445
)
423446

0 commit comments

Comments
 (0)