Skip to content

Commit ee3fd56

Browse files
fix: PostgreSQL insert_row fails for tables with text primary keys (#22)
The insert_row function always used RETURNING COALESCE(CAST(id AS BIGINT), 0) even when no auto_id_column was specified, defaulting to the id column. For tables with text primary keys (like NetBird's accounts, users, groups), CAST to BIGINT fails with a generic db error. Fix: Only use RETURNING clause when auto_id_column is explicitly set. When no auto_id is needed, use a simple INSERT without RETURNING.
1 parent 7fcbd8a commit ee3fd56

1 file changed

Lines changed: 28 additions & 14 deletions

File tree

src/seed/db.rs

Lines changed: 28 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -319,20 +319,34 @@ impl Database for PostgresDb {
319319
.map(|c| format!("\"{}\"", sanitize_identifier(c)))
320320
.collect();
321321
let value_list: Vec<String> = values.iter().map(|v| escape_sql_value(v)).collect();
322-
let returning_col = sanitize_identifier(auto_id_column.unwrap_or("id"));
323-
let sql = format!(
324-
"INSERT INTO \"{}\" ({}) VALUES ({}) RETURNING COALESCE(CAST(\"{}\" AS BIGINT), 0)",
325-
sanitize_identifier(table),
326-
col_list.join(", "),
327-
value_list.join(", "),
328-
returning_col
329-
);
330-
let row = self
331-
.client
332-
.query_one(&sql, &[])
333-
.map_err(|e| format!("inserting row into '{}': {}", table, e))?;
334-
let id: i64 = row.get(0);
335-
Ok(Some(id))
322+
323+
if let Some(auto_col) = auto_id_column {
324+
let returning_col = sanitize_identifier(auto_col);
325+
let sql = format!(
326+
"INSERT INTO \"{}\" ({}) VALUES ({}) RETURNING COALESCE(CAST(\"{}\" AS BIGINT), 0)",
327+
sanitize_identifier(table),
328+
col_list.join(", "),
329+
value_list.join(", "),
330+
returning_col
331+
);
332+
let row = self
333+
.client
334+
.query_one(&sql, &[])
335+
.map_err(|e| format!("inserting row into '{}': {}", table, e))?;
336+
let id: i64 = row.get(0);
337+
Ok(Some(id))
338+
} else {
339+
let sql = format!(
340+
"INSERT INTO \"{}\" ({}) VALUES ({})",
341+
sanitize_identifier(table),
342+
col_list.join(", "),
343+
value_list.join(", "),
344+
);
345+
self.client
346+
.execute(&sql, &[])
347+
.map_err(|e| format!("inserting row into '{}': {}", table, e))?;
348+
Ok(None)
349+
}
336350
}
337351

338352
fn row_exists(

0 commit comments

Comments
 (0)