Skip to content

fix(linux): load exported CSV and SQL INSERT files back with the same rows - #3714

Merged
datlechin merged 3 commits into
mainfrom
test/3665-linux-export-import-roundtrip
Oct 21, 2026
Merged

datlechin merged 3 commits into
mainfrom
test/3665-linux-export-import-roundtrip

Conversation

@datlechin

Copy link
Copy Markdown
Member

Summary

  • round_trip_suite! in tablepro-test-support, run by every driver (MySQL and MariaDB both, SQLite in the unit suite):
    • value corpus out as CSV, imported into an empty copy, under four writer/reader pairings (every delimiter, quoting always or where needed, LF, CRLF and CR, NULL as NULL). Row count and every row's text compared.
    • corpus out as SQL INSERT, run statement by statement in an editor session against an empty copy. Every value's text and kind compared.
    • a table whose CSV lands within 1 MiB under the 64 MiB limit, imported back and compared row by row. Off on ClickHouse (below).
  • MAX_CSV_FILE_BYTES moves from the app to tablepro_core::import so the test reads the same limit.
  • Fixed, all found by the new cases:
    • SQLite: a DATE, TIME or DATETIME value with an offset or Z, or in another form SQLite reads, was refused by the import and by cell edits.
    • PostgreSQL: dates and timestamps before year 1 (4713-01-01 BC), from year 10000, or past chrono's last year were refused by the import and by cell edits. One past chrono binds as text cast to the column type.
    • SQL Server: a decimal(38,38) value failed to save or import (tiberius sends precision 39); it now goes as text. Decimal parameters are cast to decimal(38, s), so a multi-row import no longer narrows a full-precision value beside a shorter one.
    • ClickHouse: SQL INSERT export wrote Map and Tuple values as strings the server refuses, and a Variant changed type. They are now JSONExtract('<json>', '<type>').
  • Corpus additions: SQLite DATE, TIME and DATETIME forms, PostgreSQL 10000-01-01.
  • Docs: linux/docs/testing.md (Export round trip), the PostgreSQL, SQL Server and ClickHouse driver pages, ROADMAP.md.
  • No changelog fragment: the Linux app has not shipped.

Not in this PR

  • ClickHouse near the import limit: parameters ride in the request URL (64 KiB client cap), so a statement carries 8 KiB of values. 64 MiB is about 8,000 statements at ~67 ms each (async insert wait), about 9 minutes. 128 KiB batches failed with uri too long and Too many form fields. Sending parameters in the body is its own driver change.
  • Export defaults: NULL in a text column comes back as '', and formula-like text gets an apostrophe. Both by design; a lossless round trip needs Convert NULL to empty off and the NULL marker.
  • Export's Decimal Comma has no import counterpart; a decimal column refuses 1,5 with a clear error.
  • A SQLite DATETIME holding a number (Unix time, Julian day) exports as the number, and the import refuses it.
  • ClickHouse binds a Tuple from a sorting key as its JSON text in a save's probe, which the server would not parse. Not reproduced.

Test plan

  • round_trip_suite! on PostgreSQL, MySQL, MariaDB, SQL Server, ClickHouse (--run-ignored only) and SQLite. Before the fixes the CSV case failed on SQLite, PostgreSQL and SQL Server, and the SQL case on ClickHouse; all pass now.
  • SQL Server: csv_import::a_decimal_at_full_precision_keeps_every_digit_beside_shorter_ones, filter::a_decimal_filter_keeps_the_digits_it_was_given.
  • Unit tests for eras, far years and SQLite forms in parse_literal_text, PostgreSQL far-date binding, SQL Server decimal encoding and cast, ClickHouse JSON literals.
  • Value corpus, CSV import, write batch and filter suites; meson test under xvfb; rustfmt and both clippy runs.

Fixes #3665

@J2TeamNNL J2TeamNNL left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Automated review: 9 findings.

/// calendar repeats every 400 years, so the text is checked by `parse`
/// with its year moved into chrono's range, fraction and all. `None`
/// for text that is not such a value.
fn far_temporal(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

far_temporal returns Value::Other for any date or timestamp year above chrono's maximum, for every engine. It was written for PostgreSQL's 5874897 AD limit.

On a MySQL, MSSQL, ClickHouse or SQLite DATE column, an edit or INSERT of '300000-01-01' used to fail locally with InvalidDate. It is now accepted as Value::Other(text) and sent to the server, which rejects it at save time or may coerce the text. Only the Postgres dialect has a matching server_text binding in this PR, so the early validation is lost elsewhere.

(ParamType::Decimal, BindTarget::Column(column)) => match (&column.column_type.kind, &value) {
(ColumnKind::Decimal { scale: Some(scale), .. }, Value::Decimal(decimal)) => {
let room = MAX_NUMERIC_DIGITS.saturating_sub(decimal.integer_digits().unwrap_or(0));
let scale = decimal.scale().unwrap_or(0).max(*scale).min(room);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The decimal cast narrows the scale to room (38 minus the value's integer digits), so a value with many integer digits and a fraction is silently rounded.

A decimal(38,2) column filtered with 37 integer digits plus .55 gets room = 1, the cast becomes decimal(38,1) and the fraction becomes .6 or .5. An equality filter or UPDATE ... WHERE then misses rows, and an INSERT rounds before the column's own conversion. The old typed numeric parameter kept the full scale.

// part is 0, so a value at scale 38 goes out as precision 39,
// which the server refuses. Its text converts exactly.
match u32::from(numeric.precision()) > MAX_NUMERIC_DIGITS {
true => text_data(value_to_text(value).unwrap_or_default()),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When precision is above 38, value_to_text(value).unwrap_or_default() falls back to an empty string if the text is None. SQL Server casts '' to decimal 0 rather than failing, so a wrong value would be written or filtered on silently. Return a DriverError instead of defaulting.

// tiberius counts a digit before the point when the integer
// part is 0, so a value at scale 38 goes out as precision 39,
// which the server refuses. Its text converts exactly.
match u32::from(numeric.precision()) > MAX_NUMERIC_DIGITS {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This text fallback for precision 39+ only works because dialect.rs wraps the placeholder in a CAST, but encode applies it to every ParamType::Decimal bind.

For BindTarget::Pattern, EngineRowId, or any path hitting the dialect's _ => marker arm, a high-precision Decimal now goes out as nvarchar and is compared by implicit conversion. The encode and dialect layers are coupled by an unstated contract.

// A Map, Tuple, Variant or JSON value is the JSON the server
// wrote, which a string of it does not cast back from.
Value::Other(other) if matches!(ClickHouseType::parse(&other.type_name).plan, CellPlan::Raw { .. }) => {
format!("JSONExtract({}, {})", quoted(&other.text), quoted(&other.type_name))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Raw-plan values (Map, Tuple, Variant, JSON) all use JSONExtract(text, 'Type'). Nothing verifies it round-trips Variant, JSON, Dynamic, or Tuples with named elements; support varies by server version. A SQL INSERT export of such a column could fail at import time. The unit test only covers Map and Tuple.

}
Ok(value) => Ok(value),
Err(_) if column.dynamic_storage && keeps_text_on_failure(&column.kind) => Ok(Value::Text(input.to_owned())),
Err(EditParseError::InvalidDate | EditParseError::InvalidTime | EditParseError::InvalidTimestamp)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The dynamic-storage fallback only matches InvalidDate, InvalidTime and InvalidTimestamp. A zone-less timestamp typed into an Offset-zone dynamic column returns OffsetRequired and the edit is refused, while the same text in a naive column is kept as text. Inconsistent and untested.

};
let year_digits = dated.bytes().take_while(u8::is_ascii_digit).count();
let (year, rest) = dated.split_at(year_digits);
if !before_christ {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

chrono_year prefixes + for any year with more than 4 digits, including leading zeros. '00001-01-01' becomes +00001-01-01, which chrono accepts as year 1, so a cell that used to be rejected is now silently accepted as 0001-01-01. far_temporal's 2000 + year % 400 also never checks the digits are canonical, so '0000300000-01-01' passes as a far date.

/// Under the export defaults these rows of 200-character labels make a
/// file just under `MAX_CSV_FILE_BYTES`. 200 characters is the widest
/// label every engine's scratch table takes.
const NEAR_LIMIT_ROWS: u64 = 315_000;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The near-limit case relies on a fixed 315,000 rows of 200-character labels landing within 1 MiB under 64 MiB on every engine. Id widths or utf8mb4 vs SQLite encoding can push it over MAX_CSV_FILE_BYTES or out of the window, failing the size expect before testing anything. It also holds a 64 MiB file plus 315,000 BTreeMap rows against a 240s cap that slow CI can miss.

"`{}` as {:?}, {:?}, {:?}",
column.declaration, writer.delimiter, writer.quote, writer.line_break
);
let copy = corpus_table(&engine, connection.as_ref(), &format!("csv_{index}_copy"), column, &[]).await?;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The CSV case builds a new copy table per pairing (4 per corpus column) and never drops them; continue on an import failure leaves a half-filled copy. With dozens of corpus columns this creates hundreds of scratch tables and can exceed ROUND_TRIP_CASE_LIMIT on slow-DDL engines (SQL Server, ClickHouse) without reporting a real round-trip difference.

@J2TeamNNL

Copy link
Copy Markdown
Contributor

Follow-up to the review above. Two findings fixed in J2TeamNNL@6b2312d, seven skipped.

Fixed:

  • MSSQL encode.rs: a precision above 38 with no text form now returns a driver error instead of binding an empty string.
  • parse_literal_text.rs: a year with leading zeros (00001-01-01, 0005874897-12-31) is no longer accepted as a far date, in both chrono_year and far_temporal. Tests added.

Skipped:

  • far dates for every engine: the PR chose this on purpose, so it needs the author's call.
  • MSSQL decimal scale rounding: a value with 37 integer digits does not fit a decimal(38,2) column anyway.
  • encode/dialect coupling: the comment documents it and no bind path reaches it today.
  • ClickHouse JSONExtract for Variant, JSON, Dynamic: cannot verify without a server.
  • OffsetRequired in a dynamic column: refusing a zone-less value for an offset column is right.
  • near-limit CSV margin: the size expect already guards it.
  • scratch tables per pairing: not verified as a real leak.

Not run: no Rust toolchain on this machine, so fmt, clippy and tests were not run.

Cherry-pick: git fetch https://github.com/J2TeamNNL/TablePro review-fix/3714 && git cherry-pick 6b2312df3bbf1d39b449e974520c0007b64253fe

@datlechin
datlechin merged commit f5dbe35 into main Oct 21, 2026
57 of 59 checks passed
@datlechin
datlechin deleted the test/3665-linux-export-import-roundtrip branch October 22, 2026 07:05
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Test that a Linux CSV and SQL export imports back with the same rows

2 participants