From a9ddc58f211db690fe555bb1f22a53633f57c487 Mon Sep 17 00:00:00 2001 From: Patryk Nowacki <41294605+NowackiPatryk@users.noreply.github.com> Date: Fri, 8 Mar 2024 16:50:18 +0100 Subject: [PATCH] Fix unexpected sqlite insert behaviour (attempt 2) (#12128) - fixes #11429 - fixes #12011 Refers to: https://github.com/nushell/nushell/pull/12039 In general looks a bit faster now. --- .../src/database/commands/into_sqlite.rs | 58 ++++++++++--------- 1 file changed, 32 insertions(+), 26 deletions(-) diff --git a/crates/nu-command/src/database/commands/into_sqlite.rs b/crates/nu-command/src/database/commands/into_sqlite.rs index 924508ef60..49da38ec88 100644 --- a/crates/nu-command/src/database/commands/into_sqlite.rs +++ b/crates/nu-command/src/database/commands/into_sqlite.rs @@ -209,21 +209,6 @@ fn insert_in_transaction( let table_name = table.name().clone(); let tx = table.try_init(first_val)?; - let insert_statement = format!( - "INSERT INTO [{}] VALUES ({})", - table_name, - ["?"].repeat(first_val.values().len()).join(", ") - ); - - let mut insert_statement = - tx.prepare(&insert_statement) - .map_err(|e| ShellError::GenericError { - error: "Failed to prepare SQLite statement".into(), - msg: e.to_string(), - span: None, - help: None, - inner: Vec::new(), - })?; // insert all the records stream.try_for_each(|stream_value| { @@ -233,18 +218,39 @@ fn insert_in_transaction( } } - insert_value(stream_value, &mut insert_statement) - })?; + let val = stream_value.as_record()?; - insert_statement - .finalize() - .map_err(|e| ShellError::GenericError { - error: "Failed to finalize SQLite prepared statement".into(), - msg: e.to_string(), - span: None, - help: None, - inner: Vec::new(), - })?; + let insert_statement = format!( + "INSERT INTO [{}] ({}) VALUES ({})", + table_name, + val.cols.join(", "), + ["?"].repeat(val.values().len()).join(", ") + ); + + let mut insert_statement = + tx.prepare(&insert_statement) + .map_err(|e| ShellError::GenericError { + error: "Failed to prepare SQLite statement".into(), + msg: e.to_string(), + span: None, + help: None, + inner: Vec::new(), + })?; + + let result = insert_value(stream_value, &mut insert_statement); + + insert_statement + .finalize() + .map_err(|e| ShellError::GenericError { + error: "Failed to finalize SQLite prepared statement".into(), + msg: e.to_string(), + span: None, + help: None, + inner: Vec::new(), + })?; + + result + })?; tx.commit().map_err(|e| ShellError::GenericError { error: "Failed to commit SQLite transaction".into(),