Skip to content

Commit d70ca58

Browse files
authored
Add test for foreign key constraint validation in Appender (#565)
refs #211
2 parents 5073edf + 680b7ab commit d70ca58

File tree

1 file changed

+35
-5
lines changed
  • crates/duckdb/src/appender

1 file changed

+35
-5
lines changed

crates/duckdb/src/appender/mod.rs

Lines changed: 35 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -176,7 +176,7 @@ impl fmt::Debug for Appender<'_> {
176176

177177
#[cfg(test)]
178178
mod test {
179-
use crate::{Connection, Result};
179+
use crate::{params, Connection, Error, Result};
180180

181181
#[test]
182182
fn test_append_one_row() -> Result<()> {
@@ -264,7 +264,6 @@ mod test {
264264
#[test]
265265
#[cfg(feature = "chrono")]
266266
fn test_append_datetime() -> Result<()> {
267-
use crate::params;
268267
use chrono::{NaiveDate, NaiveDateTime};
269268

270269
let db = Connection::open_in_memory()?;
@@ -285,8 +284,7 @@ mod test {
285284
}
286285

287286
#[test]
288-
fn test_appender_error() -> Result<(), crate::Error> {
289-
use crate::params;
287+
fn test_appender_error() -> Result<()> {
290288
let conn = Connection::open_in_memory()?;
291289
conn.execute(
292290
r"CREATE TABLE foo (
@@ -298,12 +296,44 @@ mod test {
298296
)?;
299297
let mut appender = conn.appender("foo")?;
300298
match appender.append_row(params!["foo"]) {
301-
Err(crate::Error::DuckDBFailure(.., Some(msg))) => {
299+
Err(Error::DuckDBFailure(.., Some(msg))) => {
302300
assert_eq!(msg, "Call to EndRow before all columns have been appended to!")
303301
}
304302
Err(err) => panic!("unexpected error: {err:?}"),
305303
Ok(_) => panic!("expected an error but got Ok"),
306304
}
307305
Ok(())
308306
}
307+
308+
#[test]
309+
fn test_appender_foreign_key_constraint() -> Result<()> {
310+
let conn = Connection::open_in_memory()?;
311+
conn.execute_batch(
312+
r"
313+
CREATE TABLE parent (id INTEGER PRIMARY KEY);
314+
CREATE TABLE child (
315+
id INTEGER,
316+
parent_id INTEGER,
317+
FOREIGN KEY (parent_id) REFERENCES parent(id)
318+
);",
319+
)?;
320+
conn.execute("INSERT INTO parent VALUES (1)", [])?;
321+
322+
let mut appender = conn.appender("child")?;
323+
appender.append_row(params![1, 999])?; // Invalid parent_id
324+
325+
// Foreign key constraint should be checked during flush
326+
match appender.flush() {
327+
Err(Error::DuckDBFailure(_, Some(msg))) => {
328+
assert_eq!(
329+
msg,
330+
"Violates foreign key constraint because key \"id: 999\" does not exist in the referenced table"
331+
);
332+
}
333+
Err(e) => panic!("Expected foreign key constraint error, got: {e:?}"),
334+
Ok(_) => panic!("Expected foreign key constraint error, but flush succeeded"),
335+
}
336+
337+
Ok(())
338+
}
309339
}

0 commit comments

Comments
 (0)