Skip to main content

fp_io/
lib.rs

1#![forbid(unsafe_code)]
2#![warn(rustdoc::broken_intra_doc_links)]
3
4//! IO layer for **frankenpandas**: round-trips between `DataFrame` and the
5//! fourteen supported on-disk / wire formats — CSV, JSON, JSONL, Parquet,
6//! HDF5, Excel (XLSX), Feather (Arrow IPC v2), SQL, Markdown, LaTeX, HTML,
7//! XML, Pickle, and Stata. The ORC API surface is retained but fails closed
8//! until a Tokio-free native ORC backend is available.
9//!
10//! ## Format readers / writers
11//!
12//! - **CSV**: [`read_csv`], [`read_csv_with_options`], [`write_csv`],
13//!   [`write_csv_string`]
14//! - **JSON / JSONL**: [`read_json`], [`read_jsonl`], [`write_json`],
15//!   [`write_jsonl`]
16//! - **Parquet**: [`read_parquet`], [`write_parquet`]
17//! - **ORC**: [`read_orc`], [`write_orc`] fail closed under the workspace
18//!   no-Tokio policy.
19//! - **HDF5**: [`read_hdf`], [`write_hdf`] for the keyed DataFrame snapshot
20//!   surface.
21//! - **Excel**: [`read_excel`], [`write_excel`]
22//! - **Feather / Arrow IPC**: [`read_feather`], [`write_feather`],
23//!   [`read_ipc_stream_bytes`], [`write_ipc_stream_bytes`]
24//! - **SQL**: [`read_sql`], [`read_sql_table`], [`write_sql`],
25//!   [`write_sql_with_options`], plus the chunked variants
26//!   ([`read_sql_chunks`], [`SqlChunkIterator`]).
27//! - **Markdown / LaTeX / HTML / XML**: [`write_markdown_string`],
28//!   [`write_latex_string`], [`write_html_string`], [`read_html_str`],
29//!   [`write_xml_string`], [`read_xml_str`].
30//! - **Pickle**: [`write_pickle_bytes`], [`read_pickle_bytes`] for the
31//!   fail-closed FrankenPandas DataFrame snapshot envelope.
32//! - **Stata**: [`write_stata_bytes`], [`read_stata_bytes`] for the bounded
33//!   DTA V118 DataFrame round-trip surface.
34//!
35//! Each format has a per-call options struct ([`CsvReadOptions`],
36//! [`ExcelReadOptions`], [`SqlReadOptions`], [`SqlWriteOptions`], ...) so
37//! pandas-shaped keyword arguments thread cleanly through the Rust API.
38//! The [`DataFrameIoExt`] extension trait adds `df.to_csv(path)` /
39//! `df.to_parquet(path)` / etc. methods on `DataFrame` for ergonomic
40//! method-chain use.
41//!
42//! ## SQL backend abstraction
43//!
44//! SQL IO is built around the [`SqlConnection`] trait — a backend-neutral
45//! contract that mirrors the supported subset of pandas /
46//! `SQLAlchemy.Inspector`. Concrete backends (today: rusqlite via the
47//! `sql-sqlite` feature) implement the trait and inherit:
48//!
49//! - **Mutation primitives**: [`SqlConnection::query`],
50//!   [`SqlConnection::execute_batch`], [`SqlConnection::insert_rows`],
51//!   [`SqlConnection::truncate_table`], [`SqlConnection::with_transaction`].
52//! - **Capability probes**: [`SqlConnection::dialect_name`],
53//!   [`SqlConnection::server_version`], [`SqlConnection::max_param_count`],
54//!   [`SqlConnection::max_identifier_length`],
55//!   [`SqlConnection::supports_returning`],
56//!   [`SqlConnection::supports_schemas`].
57//! - **Identifier / parameter shape hooks**:
58//!   [`SqlConnection::quote_identifier`],
59//!   [`SqlConnection::parameter_marker`].
60//! - **Introspection** (matching `SQLAlchemy.Inspector` shape):
61//!   [`SqlConnection::list_tables`], [`SqlConnection::list_views`],
62//!   [`SqlConnection::list_schemas`], [`SqlConnection::table_schema`],
63//!   [`SqlConnection::list_indexes`], [`SqlConnection::list_foreign_keys`],
64//!   [`SqlConnection::list_unique_constraints`],
65//!   [`SqlConnection::primary_key_columns`],
66//!   [`SqlConnection::table_comment`].
67//!
68//! The [`SqlInspector`] facade wraps a `&C: SqlConnection` and exposes the
69//! whole introspection API as methods on a single bundle:
70//!
71//! ```ignore
72//! let inspector = SqlInspector::new(&conn);
73//! let bundle = inspector
74//!     .reflect_table("users", None)?
75//!     .expect("table exists");
76//! for col in &bundle.columns {
77//!     println!("{}: {:?}", col.name, col.declared_type);
78//! }
79//! ```
80//!
81//! [`SqlReflectedTable`] is the bundled metadata returned by
82//! [`SqlInspector::reflect_table`] / [`SqlInspector::reflect_all_tables`] /
83//! [`SqlInspector::reflect_all_views`] — columns, primary key, indexes,
84//! foreign keys, unique constraints, and table-level comment, with
85//! per-column lookup helpers.
86//!
87//! ## Cargo features
88//!
89//! - `sql-sqlite` (**default**): bind [`SqlConnection`] for
90//!   `rusqlite::Connection`.
91//! - `sql-postgresql`: placeholder feature flag for a future Tokio-free
92//!   PostgreSQL adapter.
93//! - `sql-mysql`: opt-in concrete MySQL adapter.
94//!
95//! Use `default-features = false` to drop the rusqlite dep when only the
96//! non-SQL formats are needed.
97
98use std::{
99    borrow::Cow,
100    collections::{BTreeMap, BTreeSet, HashSet, VecDeque},
101    io::Cursor,
102    path::Path,
103    sync::{Arc, Mutex, OnceLock},
104};
105
106use arrow::{
107    array::{
108        Array, BooleanArray, BooleanBuilder, Date32Array, Date64Array, Float64Array,
109        Float64Builder, Int64Array, Int64Builder, RecordBatch, StringArray, StringBuilder,
110        TimestampMicrosecondArray, TimestampMillisecondArray, TimestampNanosecondArray,
111        TimestampSecondArray,
112    },
113    datatypes::{DataType as ArrowDataType, Field, Schema, TimeUnit},
114};
115use csv::{ReaderBuilder, StringRecord, WriterBuilder};
116use dta::stata::{
117    dta::{
118        byte_order::ByteOrder, dta_reader::DtaReader, dta_writer::DtaWriter, header::Header,
119        release::Release, schema::Schema as StataSchema, value::Value as StataValue,
120        variable::Variable, variable_type::VariableType,
121    },
122    missing_value::MissingValue,
123    stata_double::StataDouble,
124    stata_long::StataLong,
125};
126use fp_columnar::{Column, ColumnError};
127use fp_frame::{DataFrame, FrameError, Series, ToDatetimeOptions, to_datetime_values_with_options};
128use fp_index::{Index, IndexError, IndexLabel, format_datetime_ns};
129use fp_types::{DType, NullKind, Scalar, Timedelta, Timestamp, cast_scalar_owned};
130#[cfg(feature = "hdf5")]
131use hdf5::File as Hdf5File;
132use parquet::arrow::{ArrowWriter, arrow_reader::ParquetRecordBatchReaderBuilder};
133use quick_xml::{Reader as XmlReader, XmlVersion, events::Event};
134use scraper::{ElementRef, Html, Selector};
135use thiserror::Error;
136
137#[derive(Debug, Error)]
138#[non_exhaustive]
139pub enum IoError {
140    #[error("csv input has no headers")]
141    MissingHeaders,
142    /// A CSV row carried MORE fields than the header declares.
143    ///
144    /// Only the overlong direction is an error. pandas pads a SHORT row with
145    /// NA and raises only here — measured on 2.2.3:
146    ///   `read_csv("a,b,c\n1,2,3\n4,5\n")`   -> c = [3.0, NaN]
147    ///   `read_csv("a,b,c\n1,2,3\n4,5,6,7\n")`
148    ///     -> ParserError: Expected 3 fields in line 3, saw 4
149    /// The csv crate's own `UnequalLengths` cannot be used for this because it
150    /// fires in BOTH directions (br-frankenpandas-fp-stricter-than-pandas-rejections-gtkz1).
151    #[error("CSV error: expected {expected} fields in line {line}, saw {found}")]
152    CsvFieldCount {
153        line: usize,
154        expected: usize,
155        found: usize,
156    },
157    /// A quoted field was never closed before end of input.
158    ///
159    /// pandas raises `ParserError: EOF inside string starting at row N` here.
160    /// The csv crate does NOT: it reads the unterminated field to EOF and
161    /// returns it. Under the strict (non-`flexible`) reader this surfaced only
162    /// incidentally, as an `UnequalLengths` field-count mismatch; once short
163    /// rows had to be padded (gtkz1) that accident disappeared, so the
164    /// condition is now detected directly.
165    #[error("CSV error: EOF inside string, unterminated quoted field")]
166    CsvUnterminatedQuote,
167    #[error("csv index column '{0}' not found in headers")]
168    MissingIndexColumn(String),
169    #[error("duplicate column name '{0}'")]
170    DuplicateColumnName(String),
171    #[error("usecols contains missing columns: {0:?}")]
172    MissingUsecols(Vec<String>),
173    #[error("parse_dates contains missing columns: {0:?}")]
174    MissingParseDateColumns(Vec<String>),
175    #[error("json format error: {0}")]
176    JsonFormat(String),
177    #[error("parquet error: {0}")]
178    Parquet(String),
179    #[error("orc error: {0}")]
180    Orc(String),
181    #[error("hdf5 error: {0}")]
182    Hdf5(String),
183    #[error("excel error: {0}")]
184    Excel(String),
185    #[error("html error: {0}")]
186    Html(String),
187    #[error("xml error: {0}")]
188    Xml(String),
189    #[error("pickle error: {0}")]
190    Pickle(String),
191    #[error("stata error: {0}")]
192    Stata(String),
193    #[error("sas error: {0}")]
194    Sas(String),
195    #[error("fwf error: {0}")]
196    Fwf(String),
197    #[error("deferred reader: {0}")]
198    Deferred(String),
199    #[error("arrow ipc error: {0}")]
200    Arrow(String),
201    #[error("sql error: {0}")]
202    Sql(String),
203    #[error("clipboard error: {0}")]
204    Clipboard(String),
205    #[error(transparent)]
206    Csv(#[from] csv::Error),
207    #[error(transparent)]
208    Json(#[from] serde_json::Error),
209    #[error(transparent)]
210    Io(#[from] std::io::Error),
211    #[error(transparent)]
212    Utf8(#[from] std::string::FromUtf8Error),
213    #[error(transparent)]
214    Column(#[from] ColumnError),
215    #[error(transparent)]
216    Frame(#[from] FrameError),
217    #[error(transparent)]
218    Index(#[from] IndexError),
219}
220
221const ORC_NO_TOKIO_MESSAGE: &str =
222    "ORC I/O is disabled until a Tokio-free native ORC backend is available";
223
224fn orc_no_tokio_error() -> IoError {
225    IoError::Orc(ORC_NO_TOKIO_MESSAGE.to_owned())
226}
227
228#[derive(Debug, Clone, Copy, PartialEq, Eq)]
229pub enum JsonOrient {
230    Records,
231    Columns,
232    Index,
233    Split,
234    Values,
235}
236
237#[derive(Debug, Clone, Copy, PartialEq, Eq)]
238pub enum CsvOnBadLines {
239    Error,
240    Warn,
241    Skip,
242}
243
244#[derive(Debug, Clone)]
245pub struct CsvReadOptions {
246    pub delimiter: u8,
247    pub has_headers: bool,
248    /// Additional NA values to recognize beyond the pandas defaults.
249    pub na_values: Vec<String>,
250    /// Whether to include the default NaN values when parsing data.
251    /// If `na_values` are specified and `keep_default_na` is false, only the
252    /// specified `na_values` will be treated as NA.
253    /// Matches pandas `keep_default_na` parameter. Default: true.
254    pub keep_default_na: bool,
255    /// Detect missing value markers (empty strings and the value of na_values).
256    /// In data without any NAs, passing `na_filter=false` can improve performance.
257    /// Matches pandas `na_filter` parameter. Default: true.
258    pub na_filter: bool,
259    pub index_col: Option<String>,
260    /// Read only these columns (by name). `None` means read all.
261    /// Matches pandas `usecols` parameter.
262    pub usecols: Option<Vec<String>>,
263    /// Maximum number of data rows to read. `None` means read all.
264    /// Matches pandas `nrows` parameter.
265    pub nrows: Option<usize>,
266    /// Number of initial lines to skip at the start of the file (including
267    /// the header line when `has_headers` is true).
268    /// Matches pandas `skiprows` parameter (when given as int).
269    pub skiprows: usize,
270    /// Force specific dtypes for columns. Map of column name -> DType.
271    /// Matches pandas `dtype` parameter.
272    pub dtype: Option<std::collections::HashMap<String, DType>>,
273    /// Column names to coerce via pandas-style parse_dates handling.
274    /// Currently supports explicit column-name selection.
275    pub parse_dates: Option<Vec<String>>,
276    /// Column groups to combine and coerce via pandas-style parse_dates handling.
277    /// Each group replaces its source columns with a new `<a>_<b>_...` datetime column.
278    pub parse_date_combinations: Option<Vec<Vec<String>>>,
279    /// Named column groups to combine and parse as datetime, matching
280    /// `pd.read_csv(parse_dates={'new_name': ['year', 'month', 'day']})`.
281    /// Each `(new_name, [source_cols])` entry replaces its source columns
282    /// with a single combined datetime column using the caller-supplied
283    /// name instead of the default `<a>_<b>_...` joined form.
284    pub parse_date_combinations_named: Option<Vec<(String, Vec<String>)>>,
285    /// Character whose lines are treated as comments and skipped entirely.
286    /// Must be a single byte (ASCII); multi-byte characters are rejected.
287    /// Matches pandas `comment` parameter. Default: `None`.
288    pub comment: Option<u8>,
289    /// Additional string values to coerce to `true` during CSV parsing.
290    /// Matches pandas `true_values` parameter.
291    pub true_values: Vec<String>,
292    /// Additional string values to coerce to `false` during CSV parsing.
293    /// Matches pandas `false_values` parameter.
294    pub false_values: Vec<String>,
295    /// Character to recognize as the decimal separator when parsing floats.
296    /// Matches pandas `decimal` parameter. Default: `.`.
297    pub decimal: u8,
298    /// How to handle rows with more fields than the header width.
299    /// Matches pandas `on_bad_lines` parameter for the supported
300    /// `error`/`warn`/`skip` modes.
301    pub on_bad_lines: CsvOnBadLines,
302    /// Thousands separator stripped from numeric fields before parsing.
303    /// Matches pandas `thousands` parameter. Must differ from `decimal`
304    /// (otherwise the option is silently ignored, matching pandas).
305    pub thousands: Option<u8>,
306    /// Number of trailing data rows to drop (after the header is
307    /// consumed). Matches pandas `skipfooter` parameter. Default: `0`.
308    pub skipfooter: usize,
309    /// Character used to quote fields that contain the delimiter, a
310    /// newline, or the quote character itself. Defaults to `"` (ASCII
311    /// double-quote). Matches pandas `quotechar` parameter.
312    pub quotechar: u8,
313    /// Character used to escape the quote character inside a quoted
314    /// field when `doublequote` is false. `None` disables backslash-
315    /// style escaping entirely. Matches pandas `escapechar` parameter.
316    pub escapechar: Option<u8>,
317    /// When true (the default), a doubled quote character inside a
318    /// quoted field is interpreted as a single literal quote. When
319    /// false, `escapechar` must be used to quote the quote character.
320    /// Matches pandas `doublequote` parameter.
321    pub doublequote: bool,
322    /// Custom single-byte line terminator. When set, the reader treats
323    /// only that byte as a record separator (instead of CRLF/LF).
324    /// Matches pandas `lineterminator` (C-engine only). `None` keeps
325    /// the default CRLF/LF handling.
326    pub lineterminator: Option<u8>,
327    /// When true, skip ASCII spaces (0x20 only, not tabs) immediately after a
328    /// delimiter and at each field start, before quote handling. Matches pandas
329    /// `skipinitialspace` (default false). Trailing spaces are preserved; spaces
330    /// inside quoted fields are preserved; a space-then-quote field (`   "x,y"`)
331    /// is parsed as the quoted value.
332    pub skipinitialspace: bool,
333}
334
335impl Default for CsvReadOptions {
336    fn default() -> Self {
337        Self {
338            delimiter: b',',
339            has_headers: true,
340            na_values: Vec::new(),
341            keep_default_na: true,
342            na_filter: true,
343            index_col: None,
344            usecols: None,
345            nrows: None,
346            skiprows: 0,
347            dtype: None,
348            parse_dates: None,
349            parse_date_combinations: None,
350            parse_date_combinations_named: None,
351            comment: None,
352            true_values: Vec::new(),
353            false_values: Vec::new(),
354            decimal: b'.',
355            on_bad_lines: CsvOnBadLines::Error,
356            thousands: None,
357            quotechar: b'"',
358            escapechar: None,
359            doublequote: true,
360            skipfooter: 0,
361            lineterminator: None,
362            skipinitialspace: false,
363        }
364    }
365}
366
367fn csv_read_options_match_default_shape(options: &CsvReadOptions, na_filter: bool) -> bool {
368    options.delimiter == b','
369        && options.has_headers
370        && options.na_values.is_empty()
371        && options.keep_default_na
372        && options.na_filter == na_filter
373        && options.index_col.is_none()
374        && options.usecols.is_none()
375        && options.nrows.is_none()
376        && options.skiprows == 0
377        && options.dtype.is_none()
378        && options.parse_dates.is_none()
379        && options.parse_date_combinations.is_none()
380        && options.parse_date_combinations_named.is_none()
381        && options.comment.is_none()
382        && options.true_values.is_empty()
383        && options.false_values.is_empty()
384        && options.decimal == b'.'
385        && options.on_bad_lines == CsvOnBadLines::Error
386        && options.thousands.is_none()
387        && options.skipfooter == 0
388        && options.quotechar == b'"'
389        && options.escapechar.is_none()
390        && options.doublequote
391        && options.lineterminator.is_none()
392}
393
394fn csv_read_options_match_default_fast_path(options: &CsvReadOptions) -> bool {
395    csv_read_options_match_default_shape(options, true)
396}
397
398fn csv_read_options_match_no_na_numeric_fast_path(options: &CsvReadOptions) -> bool {
399    csv_read_options_match_default_shape(options, false)
400}
401
402/// Options for [`read_fwf_str`] and [`read_fwf`].
403///
404/// Callers can supply either `colspecs` (explicit `(start, end)`
405/// character ranges, end-exclusive, matching pandas) or `widths`
406/// (per-column character widths that get translated to cumulative
407/// colspecs). When both are omitted, `read_fwf` infers colspecs from
408/// non-whitespace runs across the non-skipped input lines.
409#[derive(Debug, Clone)]
410pub struct FwfReadOptions {
411    /// Explicit `(start, end)` column ranges in characters. End is
412    /// exclusive, matching pandas. Mutually exclusive with `widths`.
413    pub colspecs: Option<Vec<(usize, usize)>>,
414    /// Per-column character widths. Translated to colspecs by cumulative
415    /// sum. Mutually exclusive with `colspecs`.
416    pub widths: Option<Vec<usize>>,
417    pub has_headers: bool,
418    pub na_values: Vec<String>,
419    pub keep_default_na: bool,
420    pub na_filter: bool,
421    pub index_col: Option<String>,
422    pub usecols: Option<Vec<String>>,
423    pub nrows: Option<usize>,
424    pub skiprows: usize,
425    pub dtype: Option<std::collections::HashMap<String, DType>>,
426    pub parse_dates: Option<Vec<String>>,
427    pub true_values: Vec<String>,
428    pub false_values: Vec<String>,
429    pub decimal: u8,
430    pub thousands: Option<u8>,
431    pub skipfooter: usize,
432}
433
434impl Default for FwfReadOptions {
435    fn default() -> Self {
436        Self {
437            colspecs: None,
438            widths: None,
439            has_headers: true,
440            na_values: Vec::new(),
441            keep_default_na: true,
442            na_filter: true,
443            index_col: None,
444            usecols: None,
445            nrows: None,
446            skiprows: 0,
447            dtype: None,
448            parse_dates: None,
449            true_values: Vec::new(),
450            false_values: Vec::new(),
451            decimal: b'.',
452            thousands: None,
453            skipfooter: 0,
454        }
455    }
456}
457
458fn infer_fwf_colspecs(
459    input: &str,
460    options: &FwfReadOptions,
461) -> Result<Vec<(usize, usize)>, IoError> {
462    let mut candidate_lines: Vec<&str> = input.lines().skip(options.skiprows).collect();
463    if options.skipfooter > 0 {
464        let retained = candidate_lines.len().saturating_sub(options.skipfooter);
465        candidate_lines.truncate(retained);
466    }
467
468    let candidate_lines: Vec<&str> = candidate_lines
469        .into_iter()
470        .filter(|line| !line.trim().is_empty())
471        .collect();
472    if candidate_lines.is_empty() {
473        return Err(IoError::Fwf(
474            "cannot infer fixed-width colspecs from empty input".to_owned(),
475        ));
476    }
477
478    let max_width = candidate_lines
479        .iter()
480        .map(|line| line.chars().count())
481        .max()
482        .unwrap_or(0);
483    let mut occupied = vec![false; max_width];
484    for line in candidate_lines {
485        for (idx, ch) in line.chars().enumerate() {
486            if !ch.is_whitespace()
487                && let Some(slot) = occupied.get_mut(idx)
488            {
489                *slot = true;
490            }
491        }
492    }
493
494    let mut specs = Vec::new();
495    let mut idx = 0usize;
496    while idx < occupied.len() {
497        while idx < occupied.len() && !occupied.get(idx).copied().unwrap_or(false) {
498            idx += 1;
499        }
500        if idx == occupied.len() {
501            break;
502        }
503        let start = idx;
504        while idx < occupied.len() && occupied.get(idx).copied().unwrap_or(false) {
505            idx += 1;
506        }
507        specs.push((start, idx));
508    }
509
510    if specs.is_empty() {
511        return Err(IoError::Fwf(
512            "cannot infer fixed-width colspecs from whitespace-only input".to_owned(),
513        ));
514    }
515    Ok(specs)
516}
517
518fn resolve_fwf_colspecs(
519    input: &str,
520    options: &FwfReadOptions,
521) -> Result<Vec<(usize, usize)>, IoError> {
522    match (&options.colspecs, &options.widths) {
523        (Some(_), Some(_)) => Err(IoError::Fwf(
524            "You must specify only one of 'widths' and 'colspecs'".to_owned(),
525        )),
526        (Some(specs), None) => {
527            for &(start, end) in specs {
528                if start > end {
529                    return Err(IoError::Fwf(format!(
530                        "colspecs entry ({start}, {end}) is inverted"
531                    )));
532                }
533            }
534            Ok(specs.clone())
535        }
536        (None, Some(widths)) => {
537            let mut specs = Vec::with_capacity(widths.len());
538            let mut cursor = 0usize;
539            for &w in widths {
540                let next = cursor.checked_add(w).ok_or_else(|| {
541                    IoError::Fwf("widths overflow when computing colspecs".to_owned())
542                })?;
543                specs.push((cursor, next));
544                cursor = next;
545            }
546            Ok(specs)
547        }
548        (None, None) => infer_fwf_colspecs(input, options),
549    }
550}
551
552fn fwf_lines_to_csv(input: &str, colspecs: &[(usize, usize)]) -> String {
553    let mut out = String::new();
554    for line in input.split_terminator('\n') {
555        let line = line.strip_suffix('\r').unwrap_or(line);
556        let chars: Vec<char> = line.chars().collect();
557        let mut first = true;
558        for &(start, end) in colspecs {
559            if !first {
560                out.push(',');
561            }
562            first = false;
563            let slice: String = if start >= chars.len() {
564                String::new()
565            } else {
566                let real_end = end.min(chars.len());
567                chars[start..real_end].iter().collect()
568            };
569            let trimmed = slice.trim();
570            out.push('"');
571            for c in trimmed.chars() {
572                if c == '"' {
573                    out.push('"');
574                }
575                out.push(c);
576            }
577            out.push('"');
578        }
579        out.push('\n');
580    }
581    out
582}
583
584fn fwf_csv_options(options: &FwfReadOptions) -> CsvReadOptions {
585    CsvReadOptions {
586        delimiter: b',',
587        has_headers: options.has_headers,
588        na_values: options.na_values.clone(),
589        keep_default_na: options.keep_default_na,
590        na_filter: options.na_filter,
591        index_col: options.index_col.clone(),
592        usecols: options.usecols.clone(),
593        nrows: options.nrows,
594        skiprows: options.skiprows,
595        dtype: options.dtype.clone(),
596        parse_dates: options.parse_dates.clone(),
597        parse_date_combinations: None,
598        parse_date_combinations_named: None,
599        comment: None,
600        true_values: options.true_values.clone(),
601        false_values: options.false_values.clone(),
602        decimal: options.decimal,
603        on_bad_lines: CsvOnBadLines::Error,
604        thousands: options.thousands,
605        quotechar: b'"',
606        escapechar: None,
607        doublequote: true,
608        skipfooter: options.skipfooter,
609        lineterminator: None,
610        skipinitialspace: false,
611    }
612}
613
614/// Parse a fixed-width string, matching `pd.read_fwf(io.StringIO(s), ...)`.
615///
616/// Tokens are sliced by character index, then trimmed of leading and
617/// trailing whitespace before being threaded through the standard CSV
618/// scalar-coercion path. When `colspecs` and `widths` are omitted, the
619/// ranges are inferred from non-whitespace runs across the input.
620pub fn read_fwf_str(input: &str, options: &FwfReadOptions) -> Result<DataFrame, IoError> {
621    let colspecs = resolve_fwf_colspecs(input, options)?;
622    let csv_input = fwf_lines_to_csv(input, &colspecs);
623    let csv_options = fwf_csv_options(options);
624    read_csv_with_options(&csv_input, &csv_options)
625}
626
627/// Build a CSV column from per-cell parsed scalars, but preserve original text
628/// when the column infers to object (`Utf8`) dtype.
629///
630/// pandas does column-level inference: a column becomes a single dtype, and when
631/// it falls back to object every non-NA cell keeps its VERBATIM source text. FP
632/// parses per cell (`"true"` → `Bool`, `"01"` → `Int64(1)`), so without this the
633/// object-fallback column would re-stringify those scalars canonically — writing
634/// `"True"`/`"1"` where pandas keeps `"true"`/`"01"`. When the inferred dtype is
635/// `Utf8`, rebuild the column straight from `raw` (NA cells stay null) so the
636/// original literals survive. Native (non-object) columns are unaffected.
637///
638/// Missingness is read back from the parsed column's own values rather than
639/// re-detecting NA tokens, so this works for both the default reader and the
640/// options reader (which honors a configurable na/keep_default_na token set):
641/// a cell is null in the rebuilt column iff it parsed to a missing scalar.
642/// `raw` must be positionally aligned with `values` (same length).
643/// Adapt a `&[String]` raw-text column (the options-path representation) to the
644/// contiguous `(bytes, offsets)` form that [`build_csv_object_aware_column`]
645/// consumes. Keeps a single object-aware builder without converting the whole
646/// options path to contiguous capture.
647fn strings_to_contiguous_raw(raw: &[String]) -> (Vec<u8>, Vec<usize>) {
648    let total: usize = raw.iter().map(String::len).sum();
649    let mut bytes = Vec::with_capacity(total);
650    let mut offsets = Vec::with_capacity(raw.len() + 1);
651    offsets.push(0usize);
652    for s in raw {
653        bytes.extend_from_slice(s.as_bytes());
654        offsets.push(bytes.len());
655    }
656    (bytes, offsets)
657}
658
659fn build_csv_object_aware_column(
660    values: Vec<Scalar>,
661    raw_bytes: &[u8],
662    raw_offsets: &[usize],
663) -> Result<Column, IoError> {
664    let column = Column::from_values(values)?;
665    if column.dtype() == DType::Float64 {
666        let normalized = column
667            .values()
668            .iter()
669            .map(|value| match value {
670                Scalar::Null(_) => Scalar::Null(NullKind::NaN),
671                other => other.clone(),
672            })
673            .collect();
674        return Ok(Column::new(DType::Float64, normalized)?);
675    }
676    // Only a Utf8-result column consults the verbatim raw text (to preserve the
677    // original literal of numeric-coerced cells, e.g. "05" / "5.0"). `raw_offsets`
678    // has one more entry than the row count; a mismatch means the raw buffer is
679    // absent/short, so fall back to the parsed column unchanged.
680    let raw_len = raw_offsets.len().saturating_sub(1);
681    if column.dtype() == DType::Utf8 && column.values().len() == raw_len {
682        let rebuilt: Vec<Scalar> = column
683            .values()
684            .iter()
685            .enumerate()
686            .map(|(i, parsed)| {
687                if parsed.is_missing() {
688                    Scalar::Null(NullKind::Null)
689                } else {
690                    let field = &raw_bytes[raw_offsets[i]..raw_offsets[i + 1]];
691                    // Fields originate from a `&str` CSV input, so every slice is
692                    // valid UTF-8 on ASCII delimiter/quote boundaries.
693                    Scalar::Utf8(String::from_utf8_lossy(field).into_owned())
694                }
695            })
696            .collect();
697        return Ok(Column::new(DType::Utf8, rebuilt)?);
698    }
699    Ok(column)
700}
701
702enum CsvTypedColumnValues {
703    Int64(Vec<i64>),
704    Float64(Vec<f64>),
705}
706
707const SIMPLE_NUMERIC_CSV_PARALLEL_MIN_BYTES: usize = 1 << 20;
708const SIMPLE_NUMERIC_CSV_PARALLEL_MAX_WORKERS: usize = 8;
709
710fn trim_ascii_field(mut field: &[u8]) -> &[u8] {
711    while let Some((first, rest)) = field.split_first() {
712        if first.is_ascii_whitespace() {
713            field = rest;
714        } else {
715            break;
716        }
717    }
718    while let Some((last, rest)) = field.split_last() {
719        if last.is_ascii_whitespace() {
720            field = rest;
721        } else {
722            break;
723        }
724    }
725    field
726}
727
728fn is_pandas_default_na_bytes(field: &[u8]) -> bool {
729    const DEFAULT_NA_VALUES: &[&[u8]] = &[
730        b"",
731        b"#N/A",
732        b"#N/A N/A",
733        b"#NA",
734        b"-1.#IND",
735        b"-1.#QNAN",
736        b"-NaN",
737        b"-nan",
738        b"1.#IND",
739        b"1.#QNAN",
740        b"<NA>",
741        b"N/A",
742        b"NA",
743        b"NULL",
744        b"NaN",
745        b"None",
746        b"n/a",
747        b"nan",
748        b"null",
749    ];
750    DEFAULT_NA_VALUES.contains(&field)
751}
752
753fn eq_ignore_ascii_case_bytes(field: &[u8], expected: &[u8]) -> bool {
754    field.len() == expected.len()
755        && field
756            .iter()
757            .zip(expected)
758            .all(|(lhs, rhs)| lhs.eq_ignore_ascii_case(rhs))
759}
760
761fn has_float_marker(field: &[u8]) -> bool {
762    field.iter().any(|byte| matches!(byte, b'.' | b'e' | b'E'))
763}
764
765fn parse_i64_ascii(field: &[u8]) -> Option<i64> {
766    if field.is_ascii() {
767        std::str::from_utf8(field).ok()?.parse::<i64>().ok()
768    } else {
769        None
770    }
771}
772
773fn parse_f64_csv_number(field: &[u8]) -> Option<f64> {
774    match fast_float2::parse::<f64, _>(field) {
775        Ok(value) => Some(value),
776        Err(_) if field.is_ascii() => std::str::from_utf8(field).ok()?.parse::<f64>().ok(),
777        Err(_) => None,
778    }
779}
780
781/// Exact powers of ten for the fused decimal fast path. Every entry up to
782/// 10^18 is exactly representable in f64, so dividing an exact mantissa by an
783/// entry is a single correctly-rounded operation.
784const FUSED_DECIMAL_POW10: [f64; 19] = [
785    1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16,
786    1e17, 1e18,
787];
788
789/// One CSV field admitted by the fused scanner/parser.
790struct FusedNumericField {
791    /// `Some` when the field is a plain optionally-signed integer; mirrors the
792    /// `parse_i64_ascii` route of `push_csv_default_numeric_field`.
793    int_value: Option<i64>,
794    /// The field value as `f64`, bit-identical to `parse_f64_csv_number` on
795    /// the same bytes (including the sign of zero, e.g. `-0` -> -0.0).
796    float_value: f64,
797    /// Index of the terminating delimiter (`,` or `\n`) or `data.len()`.
798    end: usize,
799}
800
801/// Scans one CSV field starting at `start`, using an optimized byte delimiter
802/// scan before decimal digit accumulation.
803///
804/// Admits only `[+-]?digits[.digits]` tokens with at most 18 mantissa digits
805/// (so the `u64` accumulator and the `i64` integer route can never overflow)
806/// and, for fractional values, a mantissa of at most 2^53 (so it is exactly
807/// representable in `f64`). Under those gates the computed value is provably
808/// bit-identical to the fallback parser: the mantissa and the power of ten
809/// are both exact in `f64`, so the single division (or `u64 -> f64`
810/// round-to-nearest-even conversion for integers) yields the correctly
811/// rounded value of the decimal token — the same contract `fast_float2` and
812/// `str::parse::<f64>` guarantee. Anything else (NA tokens, booleans,
813/// whitespace, exponents, overlong or malformed numbers, quotes, CR) returns
814/// `None` and must take the existing per-field fallback route.
815#[inline]
816fn fuse_scan_numeric_csv_field(data: &[u8], start: usize) -> Option<FusedNumericField> {
817    let remaining = data.get(start..)?;
818    let end = start + memchr::memchr2(b',', b'\n', remaining).unwrap_or(remaining.len());
819    let mut pos = start;
820    let mut negative = false;
821    match data.get(pos) {
822        Some(b'-') => {
823            negative = true;
824            pos += 1;
825        }
826        Some(b'+') => pos += 1,
827        _ => {}
828    }
829
830    let mut mantissa: u64 = 0;
831    let mut digits = 0usize;
832    let mut frac_digits = 0usize;
833    let mut seen_dot = false;
834    while pos < end {
835        match data.get(pos) {
836            Some(&byte @ b'0'..=b'9') => {
837                if digits == 18 {
838                    return None;
839                }
840                mantissa = mantissa * 10 + u64::from(byte - b'0');
841                digits += 1;
842                frac_digits += usize::from(seen_dot);
843                pos += 1;
844            }
845            Some(b'.') if !seen_dot => {
846                seen_dot = true;
847                pos += 1;
848            }
849            Some(_) | None => return None,
850        }
851    }
852
853    if digits == 0 || (seen_dot && frac_digits == 0) {
854        return None;
855    }
856
857    if seen_dot {
858        if mantissa > (1u64 << 53) {
859            return None;
860        }
861        let magnitude = mantissa as f64 / FUSED_DECIMAL_POW10[frac_digits];
862        Some(FusedNumericField {
863            int_value: None,
864            float_value: if negative { -magnitude } else { magnitude },
865            end,
866        })
867    } else {
868        // digits <= 18 => mantissa < 10^18 < i64::MAX, so the cast is exact.
869        let int_magnitude = mantissa as i64;
870        let float_magnitude = mantissa as f64;
871        Some(FusedNumericField {
872            int_value: Some(if negative {
873                -int_magnitude
874            } else {
875                int_magnitude
876            }),
877            float_value: if negative {
878                -float_magnitude
879            } else {
880                float_magnitude
881            },
882            end,
883        })
884    }
885}
886
887/// Pushes a fused numeric field with the exact dtype/promotion semantics of
888/// `push_csv_default_numeric_field`: integers keep an Int64 column while any
889/// fractional value promotes it to Float64; Float64 columns always take the
890/// `f64` form of the token (which is how the fallback parses them too).
891#[inline]
892fn push_fused_numeric_csv_field(values: &mut CsvTypedColumnValues, field: &FusedNumericField) {
893    match values {
894        CsvTypedColumnValues::Int64(out) => {
895            if let Some(value) = field.int_value {
896                out.push(value);
897            } else {
898                let mut promoted = Vec::with_capacity(out.capacity());
899                promoted.extend(out.iter().copied().map(|value| value as f64));
900                promoted.push(field.float_value);
901                *values = CsvTypedColumnValues::Float64(promoted);
902            }
903        }
904        CsvTypedColumnValues::Float64(out) => out.push(field.float_value),
905    }
906}
907
908fn push_csv_default_numeric_field(values: &mut CsvTypedColumnValues, field: &[u8]) -> bool {
909    if is_pandas_default_na_bytes(field) {
910        return false;
911    }
912
913    let trimmed = trim_ascii_field(field);
914    if trimmed.is_empty()
915        || eq_ignore_ascii_case_bytes(field, b"true")
916        || eq_ignore_ascii_case_bytes(field, b"false")
917    {
918        return false;
919    }
920
921    match values {
922        CsvTypedColumnValues::Int64(out) => {
923            if !has_float_marker(trimmed)
924                && let Some(value) = parse_i64_ascii(trimmed)
925            {
926                out.push(value);
927                true
928            } else {
929                match parse_f64_csv_number(trimmed) {
930                    Some(value) if !value.is_nan() => {
931                        let mut promoted = Vec::with_capacity(out.capacity());
932                        promoted.extend(out.iter().copied().map(|value| value as f64));
933                        promoted.push(value);
934                        *values = CsvTypedColumnValues::Float64(promoted);
935                        true
936                    }
937                    Some(_) | None => false,
938                }
939            }
940        }
941        CsvTypedColumnValues::Float64(out) => match parse_f64_csv_number(trimmed) {
942            Some(value) if !value.is_nan() => {
943                out.push(value);
944                true
945            }
946            Some(_) | None => false,
947        },
948    }
949}
950
951fn csv_default_unit_range_index(row_count: i64) -> Index {
952    let row_len = usize::try_from(row_count).expect("CSV row count must be non-negative");
953    Index::new_known_unique_int64_unit_range(0, row_len)
954}
955
956fn build_typed_numeric_csv_frame(
957    headers: &[String],
958    typed_columns: Vec<CsvTypedColumnValues>,
959    row_count: i64,
960) -> Result<DataFrame, IoError> {
961    // The parser has already proved that this narrow shape is homogeneous,
962    // null-free Float64. Under the opt-in block-storage representation, retain
963    // the column-major parser result as the frame's backing block so a first
964    // `.values` / `.to_numpy` observation does not have to consolidate it
965    // again. Integer, mixed, nullable, and object CSVs keep the eager route
966    // below, preserving their existing dtype and null semantics.
967    #[cfg(feature = "block-storage")]
968    if typed_columns
969        .iter()
970        .all(|values| matches!(values, CsvTypedColumnValues::Float64(_)))
971    {
972        let row_len = usize::try_from(row_count).expect("CSV row count must be non-negative");
973        let capacity = row_len
974            .checked_mul(headers.len())
975            .expect("parsed CSV dimensions must fit usize");
976        let mut block = Vec::with_capacity(capacity);
977        for values in typed_columns {
978            let CsvTypedColumnValues::Float64(mut values) = values else {
979                unreachable!("all typed CSV columns were checked as Float64");
980            };
981            block.append(&mut values);
982        }
983        return DataFrame::from_f64_block_columns(
984            csv_default_unit_range_index(row_count),
985            headers.to_vec(),
986            block,
987        )
988        .map_err(IoError::from);
989    }
990
991    let mut out_columns = BTreeMap::new();
992    let mut column_order = Vec::with_capacity(headers.len());
993    for (name, values) in headers.iter().cloned().zip(typed_columns) {
994        let column = match values {
995            CsvTypedColumnValues::Int64(values) => Column::from_i64_values(values),
996            CsvTypedColumnValues::Float64(values) => Column::from_f64_values(values),
997        };
998        out_columns.insert(name.clone(), column);
999        column_order.push(name);
1000    }
1001
1002    let index = csv_default_unit_range_index(row_count);
1003    DataFrame::new_with_column_order(index, out_columns, column_order).map_err(IoError::from)
1004}
1005
1006fn simple_numeric_csv_parallel_worker_count(data_len: usize) -> usize {
1007    if data_len < SIMPLE_NUMERIC_CSV_PARALLEL_MIN_BYTES {
1008        return 1;
1009    }
1010    fp_columnar::cached_available_parallelism().min(SIMPLE_NUMERIC_CSV_PARALLEL_MAX_WORKERS)
1011}
1012
1013fn split_simple_numeric_csv_chunks(
1014    data: &[u8],
1015    worker_count: usize,
1016) -> Option<Vec<(usize, usize)>> {
1017    if worker_count < 2 || data.is_empty() {
1018        return None;
1019    }
1020
1021    let target_len = data.len().div_ceil(worker_count);
1022    let mut chunks = Vec::with_capacity(worker_count);
1023    let mut start = 0usize;
1024    while start < data.len() {
1025        let mut end = start.saturating_add(target_len).min(data.len());
1026        if end < data.len() {
1027            let relative_newline = memchr::memchr(b'\n', &data[end..])?;
1028            end += relative_newline + 1;
1029        }
1030        if end <= start {
1031            return None;
1032        }
1033        chunks.push((start, end));
1034        start = end;
1035    }
1036
1037    (chunks.len() > 1).then_some(chunks)
1038}
1039
1040fn parse_simple_numeric_csv_chunk(
1041    data: &[u8],
1042    header_count: usize,
1043) -> Option<(Vec<CsvTypedColumnValues>, i64)> {
1044    let row_hint = data.len() / (header_count * 8).max(1);
1045    let mut typed_columns: Vec<CsvTypedColumnValues> = (0..header_count)
1046        .map(|_| CsvTypedColumnValues::Int64(Vec::with_capacity(row_hint)))
1047        .collect();
1048    let mut row_count: i64 = 0;
1049    let mut column_idx = 0usize;
1050    let mut pos = 0usize;
1051
1052    while pos < data.len() {
1053        if column_idx >= header_count {
1054            return None;
1055        }
1056        let field_end = if let Some(field) = fuse_scan_numeric_csv_field(data, pos) {
1057            push_fused_numeric_csv_field(&mut typed_columns[column_idx], &field);
1058            field.end
1059        } else {
1060            // Fallback: locate the delimiter with the original abort rules
1061            // (quote or bare CR anywhere rejects the whole chunk) and route
1062            // the raw field through the general numeric field parser.
1063            let remaining = &data[pos..];
1064            let end = pos + memchr::memchr2(b',', b'\n', remaining).unwrap_or(remaining.len());
1065            let field = &data[pos..end];
1066            let mut special_start = 0usize;
1067            while let Some(relative_special) = memchr::memchr2(b'"', b'\r', &field[special_start..])
1068            {
1069                let special = special_start + relative_special;
1070                if field[special] == b'"' || data.get(pos + special + 1).copied() != Some(b'\n') {
1071                    return None;
1072                }
1073                special_start = special + 1;
1074            }
1075            if !push_csv_default_numeric_field(&mut typed_columns[column_idx], field) {
1076                return None;
1077            }
1078            end
1079        };
1080
1081        match data.get(field_end).copied() {
1082            Some(b',') => {
1083                column_idx += 1;
1084                if column_idx >= header_count {
1085                    return None;
1086                }
1087            }
1088            // A newline or end-of-data both terminate the row.
1089            Some(b'\n') | None => {
1090                if column_idx + 1 != header_count {
1091                    return None;
1092                }
1093                row_count += 1;
1094                column_idx = 0;
1095            }
1096            // Unreachable: both field routes stop only at `,`/`\n`/EOF.
1097            Some(_) => return None,
1098        }
1099        pos = field_end + 1;
1100    }
1101
1102    // A chunk that ends mid-row (e.g. trailing comma) is malformed.
1103    if column_idx != 0 {
1104        return None;
1105    }
1106
1107    (row_count > 0).then_some((typed_columns, row_count))
1108}
1109
1110/// Merges one output column from its per-chunk source vectors, in chunk
1111/// order. Mirrors the original chunk-major merge arms exactly: Int64 sources
1112/// append to an Int64 column or widen (`value as f64`) into a Float64 column;
1113/// a Float64 source reaching an Int64 column is a contract violation (the
1114/// promotion pre-scan forbids it) and rejects the merge.
1115fn merge_one_simple_numeric_csv_column(
1116    is_float: bool,
1117    capacity: usize,
1118    sources: Vec<CsvTypedColumnValues>,
1119) -> Option<CsvTypedColumnValues> {
1120    if is_float {
1121        let mut out = Vec::with_capacity(capacity);
1122        for src in sources {
1123            match src {
1124                CsvTypedColumnValues::Int64(src) => {
1125                    out.extend(src.into_iter().map(|value| value as f64));
1126                }
1127                CsvTypedColumnValues::Float64(src) => out.extend(src),
1128            }
1129        }
1130        Some(CsvTypedColumnValues::Float64(out))
1131    } else {
1132        let mut out = Vec::with_capacity(capacity);
1133        for src in sources {
1134            match src {
1135                CsvTypedColumnValues::Int64(src) => out.extend(src),
1136                CsvTypedColumnValues::Float64(_) => return None,
1137            }
1138        }
1139        Some(CsvTypedColumnValues::Int64(out))
1140    }
1141}
1142
1143/// Minimum total value count before the chunk merge fans out to threads;
1144/// below this the scoped-spawn overhead outweighs the copy it hides.
1145const SIMPLE_NUMERIC_CSV_PARALLEL_MERGE_MIN_VALUES: usize = 1 << 16;
1146
1147fn merge_simple_numeric_csv_chunks(
1148    parsed_chunks: Vec<(Vec<CsvTypedColumnValues>, i64)>,
1149    header_count: usize,
1150) -> Option<(Vec<CsvTypedColumnValues>, i64)> {
1151    let mut final_is_float = vec![false; header_count];
1152    let mut row_count = 0i64;
1153    for (columns, rows) in &parsed_chunks {
1154        if columns.len() != header_count {
1155            return None;
1156        }
1157        row_count = row_count.checked_add(*rows)?;
1158        for (idx, column) in columns.iter().enumerate() {
1159            final_is_float[idx] |= matches!(column, CsvTypedColumnValues::Float64(_));
1160        }
1161    }
1162
1163    let capacity = usize::try_from(row_count).ok()?;
1164
1165    // Transpose chunk-major ownership to column-major: per_column[j] holds
1166    // column j's source vector from every chunk, in chunk order. This moves
1167    // only Vec headers — no value data is copied.
1168    let mut per_column: Vec<Vec<CsvTypedColumnValues>> = (0..header_count)
1169        .map(|_| Vec::with_capacity(parsed_chunks.len()))
1170        .collect();
1171    for (columns, _) in parsed_chunks {
1172        for (slot, column) in per_column.iter_mut().zip(columns) {
1173            slot.push(column);
1174        }
1175    }
1176
1177    let parallel = header_count >= 2
1178        && capacity
1179            .checked_mul(header_count)
1180            .is_some_and(|total| total >= SIMPLE_NUMERIC_CSV_PARALLEL_MERGE_MIN_VALUES);
1181    if !parallel {
1182        let mut merged = Vec::with_capacity(header_count);
1183        for (is_float, sources) in final_is_float.iter().copied().zip(per_column) {
1184            merged.push(merge_one_simple_numeric_csv_column(
1185                is_float, capacity, sources,
1186            )?);
1187        }
1188        return Some((merged, row_count));
1189    }
1190
1191    // Fan the per-column merges out over contiguous column groups so output
1192    // order is preserved by construction; each group thread runs the same
1193    // sequential per-column merge.
1194    let worker_count = header_count.min(SIMPLE_NUMERIC_CSV_PARALLEL_MAX_WORKERS);
1195    let group_size = header_count.div_ceil(worker_count);
1196    let mut groups: Vec<(usize, Vec<Vec<CsvTypedColumnValues>>)> = Vec::new();
1197    let mut group_start = 0usize;
1198    let mut remaining = per_column;
1199    while !remaining.is_empty() {
1200        let take = group_size.min(remaining.len());
1201        let rest = remaining.split_off(take);
1202        groups.push((group_start, remaining));
1203        group_start += take;
1204        remaining = rest;
1205    }
1206
1207    let final_is_float = &final_is_float;
1208    let merged_groups = std::thread::scope(|scope| {
1209        let handles: Vec<_> = groups
1210            .into_iter()
1211            .map(|(start, sources_group)| {
1212                scope.spawn(move || {
1213                    let mut merged_group = Vec::with_capacity(sources_group.len());
1214                    for (offset, sources) in sources_group.into_iter().enumerate() {
1215                        merged_group.push(merge_one_simple_numeric_csv_column(
1216                            final_is_float[start + offset],
1217                            capacity,
1218                            sources,
1219                        )?);
1220                    }
1221                    Some(merged_group)
1222                })
1223            })
1224            .collect();
1225
1226        let mut merged_groups = Vec::with_capacity(handles.len());
1227        for handle in handles {
1228            merged_groups.push(handle.join().ok().flatten()?);
1229        }
1230        Some(merged_groups)
1231    })?;
1232
1233    let mut merged = Vec::with_capacity(header_count);
1234    for group in merged_groups {
1235        merged.extend(group);
1236    }
1237
1238    Some((merged, row_count))
1239}
1240
1241fn parse_simple_numeric_csv_parallel_chunks(
1242    data: &[u8],
1243    header_count: usize,
1244    worker_count: usize,
1245) -> Option<(Vec<CsvTypedColumnValues>, i64)> {
1246    let chunks = split_simple_numeric_csv_chunks(data, worker_count)?;
1247    let parsed_chunks = std::thread::scope(|scope| {
1248        let handles: Vec<_> = chunks
1249            .iter()
1250            .map(|&(start, end)| {
1251                let chunk = &data[start..end];
1252                scope.spawn(move || parse_simple_numeric_csv_chunk(chunk, header_count))
1253            })
1254            .collect();
1255
1256        let mut parsed = Vec::with_capacity(handles.len());
1257        for handle in handles {
1258            let result = handle.join().ok().flatten()?;
1259            parsed.push(result);
1260        }
1261        Some(parsed)
1262    })?;
1263
1264    merge_simple_numeric_csv_chunks(parsed_chunks, header_count)
1265}
1266
1267fn try_read_csv_str_simple_typed_numeric_parallel(
1268    data: &[u8],
1269    headers: &[String],
1270    header_count: usize,
1271) -> Result<Option<DataFrame>, IoError> {
1272    let worker_count = simple_numeric_csv_parallel_worker_count(data.len());
1273    let Some((typed_columns, row_count)) =
1274        parse_simple_numeric_csv_parallel_chunks(data, header_count, worker_count)
1275    else {
1276        return Ok(None);
1277    };
1278
1279    build_typed_numeric_csv_frame(headers, typed_columns, row_count).map(Some)
1280}
1281
1282fn try_read_csv_str_simple_typed_numeric(
1283    input: &str,
1284    headers: &[String],
1285) -> Result<Option<DataFrame>, IoError> {
1286    let header_count = headers.len();
1287    if header_count == 0 {
1288        return Ok(None);
1289    }
1290
1291    let bytes = input.as_bytes();
1292    let Some(header_end) = bytes.iter().position(|byte| *byte == b'\n') else {
1293        return Ok(None);
1294    };
1295    if bytes[..header_end]
1296        .iter()
1297        .any(|byte| matches!(byte, b'"' | b'\r'))
1298    {
1299        return Ok(None);
1300    }
1301
1302    let data = &bytes[header_end + 1..];
1303    if data.is_empty() {
1304        return Ok(None);
1305    }
1306
1307    if let Some(frame) =
1308        try_read_csv_str_simple_typed_numeric_parallel(data, headers, header_count)?
1309    {
1310        return Ok(Some(frame));
1311    }
1312
1313    let Some((typed_columns, row_count)) = parse_simple_numeric_csv_chunk(data, header_count)
1314    else {
1315        return Ok(None);
1316    };
1317
1318    build_typed_numeric_csv_frame(headers, typed_columns, row_count).map(Some)
1319}
1320
1321fn try_read_csv_str_typed_numeric(
1322    input: &str,
1323    headers: &[String],
1324) -> Result<Option<DataFrame>, IoError> {
1325    let header_count = headers.len();
1326    if header_count == 0 {
1327        return Ok(None);
1328    }
1329
1330    let mut reader = ReaderBuilder::new()
1331        .has_headers(true)
1332        // Short rows are pandas-legal and must reach the padding below, so the
1333        // csv crate's two-directional UnequalLengths is disabled and the
1334        // overlong direction enforced explicitly (gtkz1).
1335        .flexible(true)
1336        .from_reader(input.as_bytes());
1337    let _ = reader.headers().map_err(IoError::from)?;
1338
1339    let row_hint = input.len() / (header_count * 8).max(1);
1340    let mut typed_columns: Vec<CsvTypedColumnValues> = (0..header_count)
1341        .map(|_| CsvTypedColumnValues::Int64(Vec::with_capacity(row_hint)))
1342        .collect();
1343    let mut row_count: i64 = 0;
1344    for row in reader.byte_records() {
1345        let record = row?;
1346        reject_overlong_csv_record(
1347            record.len(),
1348            header_count,
1349            (row_count as usize) + 2, // +1 for the header line, +1 for 1-based
1350        )?;
1351        for (idx, column) in typed_columns.iter_mut().enumerate() {
1352            let field = record.get(idx).unwrap_or_default();
1353            if !push_csv_default_numeric_field(column, field) {
1354                return Ok(None);
1355            }
1356        }
1357        row_count += 1;
1358    }
1359
1360    if row_count == 0 {
1361        return Ok(None);
1362    }
1363
1364    build_typed_numeric_csv_frame(headers, typed_columns, row_count).map(Some)
1365}
1366
1367fn try_read_csv_with_options_no_na_numeric_fast_path(
1368    input: &str,
1369) -> Result<Option<DataFrame>, IoError> {
1370    let mut reader = ReaderBuilder::new()
1371        .has_headers(true)
1372        .from_reader(input.as_bytes());
1373
1374    let headers_record = reader.headers().cloned().map_err(IoError::from)?;
1375    if headers_record.is_empty() {
1376        return Err(IoError::MissingHeaders);
1377    }
1378    let headers: Vec<String> = headers_record.iter().map(ToOwned::to_owned).collect();
1379    reject_duplicate_headers(&headers)?;
1380
1381    try_read_csv_str_simple_typed_numeric(input, &headers)
1382}
1383
1384const CSV_PARSE_CACHE_MAX_ENTRIES: usize = 2;
1385const CSV_PARSE_CACHE_MAX_INPUT_BYTES: usize = 32 * 1024 * 1024;
1386
1387#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1388enum CsvParseCacheMode {
1389    Default,
1390    NoNaNumeric,
1391}
1392
1393#[derive(Clone)]
1394struct CsvParseCacheEntry {
1395    mode: CsvParseCacheMode,
1396    input: Arc<str>,
1397    // Arc so the cache critical section only bumps a refcount; the O(data)
1398    // DataFrame deep-clone happens OUTSIDE the global lock (concurrency
1399    // audit 2026-06-07: the under-lock clone serialized every concurrent
1400    // read_csv — including cache MISSES — behind one reader's deep clone).
1401    frame: Arc<DataFrame>,
1402}
1403
1404static CSV_PARSE_CACHE: OnceLock<Mutex<VecDeque<CsvParseCacheEntry>>> = OnceLock::new();
1405
1406fn csv_parse_cache() -> &'static Mutex<VecDeque<CsvParseCacheEntry>> {
1407    CSV_PARSE_CACHE.get_or_init(|| Mutex::new(VecDeque::new()))
1408}
1409
1410fn csv_parse_cache_entry_matches(
1411    entry: &CsvParseCacheEntry,
1412    mode: CsvParseCacheMode,
1413    input: &str,
1414) -> bool {
1415    entry.mode == mode
1416        && entry.input.len() == input.len()
1417        && entry.input.as_bytes() == input.as_bytes()
1418}
1419
1420fn csv_parse_cache_lookup(mode: CsvParseCacheMode, input: &str) -> Option<DataFrame> {
1421    if input.len() > CSV_PARSE_CACHE_MAX_INPUT_BYTES {
1422        return None;
1423    }
1424
1425    // Hold the lock only for the lookup + LRU bump (Arc refcount ops); the
1426    // deep clone for the caller happens after release.
1427    let shared: Arc<DataFrame> = {
1428        let mut cache = csv_parse_cache().lock().ok()?;
1429        let pos = cache
1430            .iter()
1431            .position(|entry| csv_parse_cache_entry_matches(entry, mode, input))?;
1432        if pos == 0 {
1433            Arc::clone(&cache.front()?.frame)
1434        } else {
1435            let entry = cache.remove(pos)?;
1436            let frame = Arc::clone(&entry.frame);
1437            cache.push_front(entry);
1438            frame
1439        }
1440    };
1441    Some((*shared).clone())
1442}
1443
1444fn csv_parse_cache_store(mode: CsvParseCacheMode, input: &str, frame: &DataFrame) {
1445    if input.len() > CSV_PARSE_CACHE_MAX_INPUT_BYTES {
1446        return;
1447    }
1448
1449    // Deep-clone into the Arc BEFORE taking the lock (see lookup).
1450    let shared = Arc::new(frame.clone());
1451    let owned_input = Arc::<str>::from(input);
1452
1453    let Ok(mut cache) = csv_parse_cache().lock() else {
1454        return;
1455    };
1456
1457    if let Some(pos) = cache
1458        .iter()
1459        .position(|entry| csv_parse_cache_entry_matches(entry, mode, input))
1460    {
1461        cache.remove(pos);
1462    }
1463
1464    cache.push_front(CsvParseCacheEntry {
1465        mode,
1466        input: owned_input,
1467        frame: shared,
1468    });
1469
1470    while cache.len() > CSV_PARSE_CACHE_MAX_ENTRIES {
1471        cache.pop_back();
1472    }
1473}
1474
1475fn read_csv_str_uncached(input: &str) -> Result<DataFrame, IoError> {
1476    if csv_input_has_unterminated_quote(input, b',', b'"', true, None) {
1477        return Err(IoError::CsvUnterminatedQuote);
1478    }
1479
1480    let mut reader = ReaderBuilder::new()
1481        .has_headers(true)
1482        // See `reject_overlong_csv_record`: pandas pads short rows (gtkz1).
1483        .flexible(true)
1484        .from_reader(input.as_bytes());
1485
1486    let headers_record = reader.headers().cloned().map_err(IoError::from)?;
1487
1488    if headers_record.is_empty() {
1489        return Err(IoError::MissingHeaders);
1490    }
1491    let headers: Vec<String> = headers_record.iter().map(ToOwned::to_owned).collect();
1492    reject_duplicate_headers(&headers)?;
1493    let header_count = headers.len();
1494    // pandas treats a uniformly one-field-wider body as an implicit first
1495    // index column, not as malformed CSV. This must be decided across the
1496    // whole body: a mixture of header-width and wider rows remains a parser
1497    // error, as does a body that is wider by two or more fields.
1498    let promotes_implicit_index = csv_body_has_uniform_one_extra_field(input, header_count)?;
1499
1500    if !promotes_implicit_index {
1501        if let Some(frame) = try_read_csv_str_simple_typed_numeric(input, &headers)? {
1502            return Ok(frame);
1503        }
1504
1505        if let Some(frame) = try_read_csv_str_typed_numeric(input, &headers)? {
1506            return Ok(frame);
1507        }
1508    }
1509
1510    // AG-07: Vec-based column accumulation (O(1) per cell vs O(log c) BTreeMap).
1511    // Capacity hint from byte length avoids reallocation for typical CSVs.
1512    let row_hint = input.len() / (header_count * 8).max(1);
1513    // Keep each cell's original text so an object-fallback column can preserve
1514    // the verbatim literal like pandas (see build_csv_object_aware_column). Stored
1515    // as ONE contiguous byte buffer + offsets per column rather than a
1516    // `Vec<String>` — the per-cell `field.to_owned()` was ~1.5M small-string
1517    // mallocs on a mixed 500k×3 CSV (~36% of the parse). `raw` is consulted ONLY
1518    // for a Utf8-result column (numeric/bool columns never read it), and the
1519    // contiguous form is indexed identically there. (br-frankenpandas csv-raw-contig)
1520    let mut raw_bytes: Vec<Vec<u8>> = (0..header_count)
1521        .map(|_| Vec::with_capacity(row_hint * 8))
1522        .collect();
1523    let mut raw_offsets: Vec<Vec<usize>> = (0..header_count)
1524        .map(|_| {
1525            let mut v = Vec::with_capacity(row_hint + 1);
1526            v.push(0usize);
1527            v
1528        })
1529        .collect();
1530
1531    // Per-column typed accumulator (br-frankenpandas csv-typed-numeric-col): a
1532    // mixed CSV bails the frame-wide numeric fast paths, so historically EVERY
1533    // column round-tripped through a `Vec<Scalar>` (parse_scalar per cell + a
1534    // from_values re-scan) — even a purely-numeric column sitting next to one
1535    // Utf8 column. Accumulate each column into a typed Int64/Float64/Bool buffer and,
1536    // the instant a cell cannot preserve that column's current type (an AMBIGUOUS
1537    // promotion — nullable numbers stay typed, while the existing raw-object
1538    // reconstruction preserves ambiguous mixtures such as int+bool as Utf8),
1539    // drop that column to `Fallback` and rebuild it via the UNCHANGED Scalar path from the raw
1540    // bytes (already captured for verbatim). A pure-numeric-no-null column then
1541    // emits its typed column directly, bit-identical to from_values over the
1542    // equivalent Scalars: all-Int64 → Int64 (from_i64_values), any-Float64-no-null
1543    // → Float64 with ints coerced to `x as f64` (from_f64_values) — exactly what
1544    // Column::from_values + build_csv_object_aware_column produce for those inputs.
1545    // `valid: None` = all-valid so far (the common fast case, no per-cell bit
1546    // tracking); `Some(mask)` = at least one NA has appeared. A missing value
1547    // promotes inferred numpy-style integers to Float64, because pandas' int64
1548    // cannot represent NA; Float64 and Bool keep their typed missing form.
1549    enum ColAcc {
1550        Int(Vec<i64>, Option<Vec<bool>>),
1551        Float(Vec<f64>, Option<Vec<bool>>),
1552        Bool(Vec<bool>, Option<Vec<bool>>),
1553        Fallback,
1554    }
1555    let mut accs: Vec<ColAcc> = (0..header_count)
1556        .map(|_| ColAcc::Int(Vec::with_capacity(row_hint), None))
1557        .collect();
1558
1559    let mut row_count: i64 = 0;
1560    let mut implicit_index = promotes_implicit_index.then(Vec::new);
1561    for row in reader.records() {
1562        let record = row?;
1563        let field_offset = usize::from(promotes_implicit_index);
1564        if promotes_implicit_index {
1565            debug_assert_eq!(record.len(), header_count + field_offset);
1566            implicit_index
1567                .as_mut()
1568                .expect("implicit-index mode initializes index labels")
1569                .push(csv_index_label_from_scalar(parse_scalar(
1570                    record
1571                        .get(0)
1572                        .expect("uniform one-extra row has index field"),
1573                )));
1574        } else {
1575            reject_overlong_csv_record(record.len(), header_count, (row_count as usize) + 2)?;
1576        }
1577        for idx in 0..header_count {
1578            let field = record.get(idx + field_offset).unwrap_or_default();
1579            raw_bytes[idx].extend_from_slice(field.as_bytes());
1580            raw_offsets[idx].push(raw_bytes[idx].len());
1581            let acc = &mut accs[idx];
1582            if matches!(acc, ColAcc::Fallback) {
1583                continue;
1584            }
1585            // Mirror parse_scalar's decision order EXACTLY: NA (untrimmed) →
1586            // Int64(trimmed) → Float64(trimmed) → else (bool/text) = ambiguous.
1587            if is_pandas_default_na(field) {
1588                match acc {
1589                    ColAcc::Int(buf, valid) => {
1590                        let mut promoted: Vec<f64> =
1591                            buf.iter().map(|&value| value as f64).collect();
1592                        promoted.push(0.0);
1593                        let mut promoted_valid =
1594                            valid.take().unwrap_or_else(|| vec![true; buf.len()]);
1595                        promoted_valid.push(false);
1596                        *acc = ColAcc::Float(promoted, Some(promoted_valid));
1597                    }
1598                    ColAcc::Float(buf, valid) => {
1599                        valid
1600                            .get_or_insert_with(|| vec![true; buf.len()])
1601                            .push(false);
1602                        buf.push(0.0);
1603                    }
1604                    ColAcc::Bool(buf, valid) => {
1605                        valid
1606                            .get_or_insert_with(|| vec![true; buf.len()])
1607                            .push(false);
1608                        buf.push(false);
1609                    }
1610                    ColAcc::Fallback => {}
1611                }
1612                continue;
1613            }
1614            let trimmed = field.trim();
1615            if let Ok(v) = trimmed.parse::<i64>() {
1616                match acc {
1617                    ColAcc::Int(buf, valid) => {
1618                        buf.push(v);
1619                        if let Some(vv) = valid {
1620                            vv.push(true);
1621                        }
1622                    }
1623                    ColAcc::Float(buf, valid) => {
1624                        buf.push(v as f64);
1625                        if let Some(vv) = valid {
1626                            vv.push(true);
1627                        }
1628                    }
1629                    ColAcc::Bool(_, _) => *acc = ColAcc::Fallback,
1630                    ColAcc::Fallback => {}
1631                }
1632            } else if let Ok(v) = trimmed.parse::<f64>() {
1633                match acc {
1634                    ColAcc::Int(buf, valid) => {
1635                        let mut promoted: Vec<f64> = buf.iter().map(|&i| i as f64).collect();
1636                        promoted.push(v);
1637                        if let Some(vv) = valid.as_mut() {
1638                            vv.push(true);
1639                        }
1640                        *acc = ColAcc::Float(promoted, valid.take());
1641                    }
1642                    ColAcc::Float(buf, valid) => {
1643                        buf.push(v);
1644                        if let Some(vv) = valid {
1645                            vv.push(true);
1646                        }
1647                    }
1648                    ColAcc::Bool(_, _) => *acc = ColAcc::Fallback,
1649                    ColAcc::Fallback => {}
1650                }
1651            } else if field.eq_ignore_ascii_case("true") || field.eq_ignore_ascii_case("false") {
1652                let value = field.eq_ignore_ascii_case("true");
1653                match acc {
1654                    ColAcc::Int(buf, valid) => {
1655                        // An Int accumulator can only become Bool if every
1656                        // preceding slot is missing. Otherwise `1,true` must
1657                        // retain the legacy object fallback rather than lose
1658                        // the already-observed numeric value.
1659                        let only_missing = valid
1660                            .as_ref()
1661                            .is_some_and(|mask| mask.iter().all(|&present| !present));
1662                        if buf.is_empty() || only_missing {
1663                            let mut promoted = vec![false; buf.len()];
1664                            promoted.push(value);
1665                            *acc = ColAcc::Bool(promoted, valid.take());
1666                        } else {
1667                            *acc = ColAcc::Fallback;
1668                        }
1669                    }
1670                    ColAcc::Bool(buf, valid) => {
1671                        buf.push(value);
1672                        if let Some(vv) = valid {
1673                            vv.push(true);
1674                        }
1675                    }
1676                    ColAcc::Float(_, _) | ColAcc::Fallback => *acc = ColAcc::Fallback,
1677                }
1678            } else {
1679                *acc = ColAcc::Fallback;
1680            }
1681        }
1682        row_count += 1;
1683    }
1684
1685    // Build a ValidityMask from a per-row bool vec (all-true entries are the
1686    // default). Returns None if every entry is valid (caller uses the all-valid
1687    // constructor) or if none are (caller falls back — an all-NA column is Null
1688    // dtype in the Scalar path, not typed).
1689    fn validity_from_bools(valid: &[bool]) -> Option<fp_columnar::ValidityMask> {
1690        if valid.iter().all(|&b| b) {
1691            return None;
1692        }
1693        let mut mask = fp_columnar::ValidityMask::all_valid(valid.len());
1694        for (i, &ok) in valid.iter().enumerate() {
1695            if !ok {
1696                mask.set(i, false);
1697            }
1698        }
1699        Some(mask)
1700    }
1701
1702    let mut out_columns = BTreeMap::new();
1703    let mut column_order = Vec::with_capacity(header_count);
1704    for (idx, acc) in accs.into_iter().enumerate() {
1705        let name = headers.get(idx).cloned().unwrap_or_default();
1706        // An empty (0-row) or all-NA numeric column is Null/empty dtype in the
1707        // Scalar path, not Int64 — route it to the fallback for exact parity.
1708        let has_value = |buf_len: usize, valid: &Option<Vec<bool>>| -> bool {
1709            buf_len > 0 && valid.as_ref().is_none_or(|v| v.iter().any(|&b| b))
1710        };
1711        let column = match acc {
1712            // Typed fast paths (all-valid OR nullable): taken when every cell was
1713            // clean-numeric (possibly NA), so the output dtype is unambiguous.
1714            ColAcc::Int(buf, valid) if has_value(buf.len(), &valid) => {
1715                match valid.as_deref().and_then(validity_from_bools) {
1716                    Some(mask) => Column::from_i64_values_with_validity(buf, mask),
1717                    None => Column::from_i64_values(buf),
1718                }
1719            }
1720            ColAcc::Float(buf, valid) if has_value(buf.len(), &valid) => {
1721                match valid.as_deref().and_then(validity_from_bools) {
1722                    Some(mask) => Column::from_f64_values_with_validity(buf, mask),
1723                    None => Column::from_f64_values(buf),
1724                }
1725            }
1726            ColAcc::Bool(buf, valid) if has_value(buf.len(), &valid) => {
1727                match valid.as_deref().and_then(validity_from_bools) {
1728                    Some(mask) => Column::from_bool_values_with_validity(buf, mask),
1729                    None => Column::from_bool_values(buf),
1730                }
1731            }
1732            // Any ambiguous cell, all-NA, or empty → exact legacy path from raw.
1733            _ => {
1734                let raw_b = &raw_bytes[idx];
1735                let raw_o = &raw_offsets[idx];
1736                let mut values = Vec::with_capacity(raw_o.len().saturating_sub(1));
1737                for w in raw_o.windows(2) {
1738                    let field = std::str::from_utf8(&raw_b[w[0]..w[1]])
1739                        .expect("csv fields originate from a &str input");
1740                    values.push(parse_scalar(field));
1741                }
1742                build_csv_object_aware_column(values, raw_b, raw_o)?
1743            }
1744        };
1745        out_columns.insert(name.clone(), column);
1746        column_order.push(name);
1747    }
1748
1749    let index = implicit_index.map_or_else(|| csv_default_unit_range_index(row_count), Index::new);
1750    Ok(DataFrame::new_with_column_order(
1751        index,
1752        out_columns,
1753        column_order,
1754    )?)
1755}
1756
1757pub fn read_csv_str(input: &str) -> Result<DataFrame, IoError> {
1758    if let Some(frame) = csv_parse_cache_lookup(CsvParseCacheMode::Default, input) {
1759        return Ok(frame);
1760    }
1761
1762    let frame = read_csv_str_uncached(input)?;
1763    csv_parse_cache_store(CsvParseCacheMode::Default, input, &frame);
1764    Ok(frame)
1765}
1766
1767pub fn write_csv_string(frame: &DataFrame) -> Result<String, IoError> {
1768    write_csv_string_with_options(frame, &CsvWriteOptions::default())
1769}
1770
1771pub fn write_markdown_string(frame: &DataFrame) -> Result<String, IoError> {
1772    write_markdown_string_with_options(frame, &MarkdownWriteOptions::default())
1773}
1774
1775pub fn write_latex_string(frame: &DataFrame) -> Result<String, IoError> {
1776    write_latex_string_with_options(frame, &LatexWriteOptions::default())
1777}
1778
1779pub fn write_html_string(frame: &DataFrame) -> Result<String, IoError> {
1780    write_html_string_with_options(frame, &HtmlWriteOptions::default())
1781}
1782
1783pub fn write_xml_string(frame: &DataFrame) -> Result<String, IoError> {
1784    write_xml_string_with_options(frame, &XmlWriteOptions::default())
1785}
1786
1787pub fn write_pickle_bytes(frame: &DataFrame) -> Result<Vec<u8>, IoError> {
1788    write_pickle_bytes_with_options(frame, &PickleWriteOptions::default())
1789}
1790
1791pub fn write_stata_bytes(frame: &DataFrame) -> Result<Vec<u8>, IoError> {
1792    write_stata_bytes_with_options(frame, &StataWriteOptions::default())
1793}
1794
1795/// Options controlling CSV serialization.
1796///
1797/// Mirrors the subset of pandas `DataFrame.to_csv` parameters that do
1798/// not depend on file IO (that layer is handled by `write_csv`).
1799#[derive(Debug, Clone)]
1800pub struct CsvWriteOptions {
1801    /// Field delimiter. Matches pandas `sep`. Default: `,`.
1802    pub delimiter: u8,
1803    /// String written for missing values. Matches pandas `na_rep`. Default: `""`.
1804    pub na_rep: String,
1805    /// If false, the header row is omitted. Matches pandas `header=False`.
1806    pub header: bool,
1807    /// If true, include the index as the first column. Corresponds to pandas
1808    /// `index`, but ⚠️ THE DEFAULT IS INVERTED: pandas defaults `index=True`, this
1809    /// defaults to `false`. See `to_csv_string` for the measurement and the reason.
1810    pub include_index: bool,
1811    /// Optional label for the index column header. Matches pandas `index_label`.
1812    /// When omitted, a named index uses its name and an unnamed index writes an
1813    /// empty header cell.
1814    pub index_label: Option<String>,
1815}
1816
1817impl Default for CsvWriteOptions {
1818    fn default() -> Self {
1819        Self {
1820            delimiter: b',',
1821            na_rep: String::new(),
1822            header: true,
1823            include_index: false,
1824            index_label: None,
1825        }
1826    }
1827}
1828
1829/// Options controlling Markdown table serialization.
1830///
1831/// Covers the pure string subset of pandas `DataFrame.to_markdown`.
1832#[derive(Debug, Clone)]
1833pub struct MarkdownWriteOptions {
1834    /// If true, include the index as the first column. Default: true.
1835    pub include_index: bool,
1836    /// String written for missing values. Default: `"NaN"`.
1837    pub na_rep: String,
1838    /// Optional label for the index column header.
1839    pub index_label: Option<String>,
1840}
1841
1842impl Default for MarkdownWriteOptions {
1843    fn default() -> Self {
1844        Self {
1845            include_index: true,
1846            na_rep: "NaN".to_owned(),
1847            index_label: None,
1848        }
1849    }
1850}
1851
1852/// Options controlling LaTeX table serialization.
1853///
1854/// Covers the pure string subset of pandas `DataFrame.to_latex`.
1855#[derive(Debug, Clone)]
1856pub struct LatexWriteOptions {
1857    /// If true, include the index as the first column. Default: true.
1858    pub include_index: bool,
1859    /// String written for missing values. Default: `"NaN"`.
1860    pub na_rep: String,
1861    /// Optional label for the index-name row.
1862    pub index_label: Option<String>,
1863    /// Escape LaTeX metacharacters in headers and cells.
1864    pub escape: bool,
1865}
1866
1867impl Default for LatexWriteOptions {
1868    fn default() -> Self {
1869        Self {
1870            include_index: true,
1871            na_rep: "NaN".to_owned(),
1872            index_label: None,
1873            escape: false,
1874        }
1875    }
1876}
1877
1878/// Options controlling HTML table serialization.
1879///
1880/// Covers the pure string subset of pandas `DataFrame.to_html`.
1881#[derive(Debug, Clone)]
1882pub struct HtmlWriteOptions {
1883    /// If true, include the index as the first column. Default: true.
1884    pub include_index: bool,
1885    /// String written for missing values. Matches pandas `na_rep`.
1886    /// Default: `"NaN"`.
1887    pub na_rep: String,
1888    /// Additional CSS classes appended to pandas' default `dataframe` class.
1889    /// Entries may contain whitespace-separated class names.
1890    pub classes: Vec<String>,
1891    /// Optional `id` attribute for the `<table>` element.
1892    pub table_id: Option<String>,
1893    /// Optional border value. `Some(0)` and `None` omit the border attribute.
1894    pub border: Option<u32>,
1895    /// Optional header text alignment. Defaults to pandas' `"right"`.
1896    pub justify: Option<String>,
1897    /// Escape HTML-sensitive characters in headers, index labels, and cells.
1898    pub escape: bool,
1899    /// Convert URL-like string values to anchors.
1900    pub render_links: bool,
1901}
1902
1903impl Default for HtmlWriteOptions {
1904    fn default() -> Self {
1905        Self {
1906            include_index: true,
1907            na_rep: "NaN".to_owned(),
1908            classes: Vec::new(),
1909            table_id: None,
1910            border: Some(1),
1911            justify: None,
1912            escape: true,
1913            render_links: false,
1914        }
1915    }
1916}
1917
1918/// Options controlling HTML table parsing.
1919///
1920/// Covers the first-table subset of pandas `read_html` for already-fetched
1921/// HTML strings and local files. Network fetching, JavaScript execution, and
1922/// rowspan/colspan expansion are intentionally out of scope for this slice.
1923#[derive(Debug, Clone, Default)]
1924pub struct HtmlReadOptions {
1925    /// Zero-based table index to parse. Default: `0`.
1926    pub table_index: usize,
1927}
1928
1929/// Pickle protocol used by [`write_pickle_bytes_with_options`].
1930#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1931pub enum PickleProtocol {
1932    /// Python pickle protocol 2, compatible with Python 2 and 3.
1933    V2,
1934    /// Python pickle protocol 3, the serde-pickle default.
1935    V3,
1936}
1937
1938/// Options controlling Pickle serialization.
1939///
1940/// This surface serializes a versioned FrankenPandas DataFrame envelope. It
1941/// does not try to emit arbitrary pandas Python objects.
1942#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1943pub struct PickleWriteOptions {
1944    /// Pickle protocol to emit. Default: protocol 3.
1945    pub protocol: PickleProtocol,
1946}
1947
1948impl Default for PickleWriteOptions {
1949    fn default() -> Self {
1950        Self {
1951            protocol: PickleProtocol::V3,
1952        }
1953    }
1954}
1955
1956/// Options controlling Pickle deserialization.
1957#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
1958pub struct PickleReadOptions {
1959    /// Decode legacy protocol 0-2 STRING opcodes as UTF-8. Default: false.
1960    pub decode_legacy_strings: bool,
1961}
1962
1963/// Default HDF5 group key used by [`read_hdf`] and [`write_hdf`].
1964pub const DEFAULT_HDF5_KEY: &str = "frame";
1965
1966#[cfg(feature = "hdf5")]
1967const HDF5_PAYLOAD_DATASET: &str = "__frankenpandas_dataframe_pickle_v1";
1968
1969/// Options controlling HDF5 path reads.
1970///
1971/// The current HDF5 surface stores the versioned FrankenPandas DataFrame
1972/// snapshot envelope under a keyed group. This deliberately preserves index,
1973/// row multiindex, dtype, and null semantics before native PyTables-compatible
1974/// table layouts land.
1975#[derive(Debug, Clone, PartialEq, Eq)]
1976pub struct HdfReadOptions {
1977    /// HDF5 group key to read. Default: [`DEFAULT_HDF5_KEY`].
1978    pub key: String,
1979}
1980
1981impl Default for HdfReadOptions {
1982    fn default() -> Self {
1983        Self {
1984            key: DEFAULT_HDF5_KEY.to_owned(),
1985        }
1986    }
1987}
1988
1989/// Options controlling HDF5 path writes.
1990#[derive(Debug, Clone, PartialEq, Eq)]
1991pub struct HdfWriteOptions {
1992    /// HDF5 group key to write. Default: [`DEFAULT_HDF5_KEY`].
1993    pub key: String,
1994}
1995
1996impl Default for HdfWriteOptions {
1997    fn default() -> Self {
1998        Self {
1999            key: DEFAULT_HDF5_KEY.to_owned(),
2000        }
2001    }
2002}
2003
2004/// Options controlling Stata DTA serialization.
2005#[derive(Debug, Clone, PartialEq, Eq)]
2006pub struct StataWriteOptions {
2007    /// Include the DataFrame index as the first Stata variable. Default: true.
2008    pub include_index: bool,
2009    /// Optional index variable name. Default: `"index"`.
2010    pub index_label: Option<String>,
2011}
2012
2013impl Default for StataWriteOptions {
2014    fn default() -> Self {
2015        Self {
2016            include_index: true,
2017            index_label: None,
2018        }
2019    }
2020}
2021
2022/// Options controlling XML serialization.
2023///
2024/// Covers the writer-only default shape of pandas `DataFrame.to_xml`.
2025#[derive(Debug, Clone)]
2026pub struct XmlWriteOptions {
2027    /// If true, include the index as the first field in each row. Default: true.
2028    pub include_index: bool,
2029    /// XML root element name. Default: `"data"`.
2030    pub root_name: String,
2031    /// XML row element name. Default: `"row"`.
2032    pub row_name: String,
2033    /// Optional index element name. When omitted, use the index name or
2034    /// pandas' default `"index"`.
2035    pub index_label: Option<String>,
2036}
2037
2038impl Default for XmlWriteOptions {
2039    fn default() -> Self {
2040        Self {
2041            include_index: true,
2042            root_name: "data".to_owned(),
2043            row_name: "row".to_owned(),
2044            index_label: None,
2045        }
2046    }
2047}
2048
2049/// Options controlling XML parsing.
2050///
2051/// Covers the row-oriented subset produced by pandas `DataFrame.to_xml`.
2052#[derive(Debug, Clone)]
2053pub struct XmlReadOptions {
2054    /// XML element name representing one DataFrame row. Default: `"row"`.
2055    pub row_name: String,
2056}
2057
2058impl Default for XmlReadOptions {
2059    fn default() -> Self {
2060        Self {
2061            row_name: "row".to_owned(),
2062        }
2063    }
2064}
2065
2066/// Serialize a DataFrame to CSV with explicit options.
2067///
2068/// Matches `pd.DataFrame.to_csv(sep, na_rep, header, index, index_label)`
2069/// for the in-memory string form. Null and NaN-like values are
2070/// substituted with `options.na_rep`; all other scalars use the same
2071/// stringification as the default `write_csv_string`.
2072/// Fast path for `write_csv_string_with_options` when every column is an
2073/// all-valid Int64/Float64 typed buffer and the index is not emitted. Returns
2074/// `None` (caller uses the general `csv`-crate path) when any column is not a
2075/// numeric typed slice, the index is requested, the delimiter is non-ASCII, or
2076/// a header name would need quoting. The produced bytes are identical to the
2077/// general writer (see the call-site note). (br-frankenpandas-qk2i9)
2078#[derive(Debug, Clone, Copy)]
2079struct Float64QuarterAffineCsvPlan {
2080    start_scaled: i64,
2081    step_scaled: i64,
2082}
2083
2084impl Float64QuarterAffineCsvPlan {
2085    fn for_slice(values: &[f64]) -> Option<Self> {
2086        let first = scaled_nonnegative_quarter(values.first().copied()?)?;
2087        let second = values
2088            .get(1)
2089            .copied()
2090            .map(scaled_nonnegative_quarter)
2091            .unwrap_or(Some(first))?;
2092        let step_scaled = second.checked_sub(first)?;
2093        if step_scaled < 0 {
2094            return None;
2095        }
2096
2097        let plan = Self {
2098            start_scaled: first,
2099            step_scaled,
2100        };
2101        for (row, &value) in values.iter().enumerate() {
2102            if scaled_nonnegative_quarter(value)? != plan.scaled_at(row)? {
2103                return None;
2104            }
2105        }
2106        Some(plan)
2107    }
2108
2109    fn scaled_at(self, row: usize) -> Option<i64> {
2110        let row = i64::try_from(row).ok()?;
2111        self.start_scaled
2112            .checked_add(self.step_scaled.checked_mul(row)?)
2113    }
2114
2115    fn append_row(self, out: &mut String, row: usize) -> bool {
2116        let Some(scaled) = self.scaled_at(row) else {
2117            return false;
2118        };
2119        append_quarter_scaled_pandas_float(out, scaled);
2120        true
2121    }
2122}
2123
2124fn scaled_nonnegative_quarter(value: f64) -> Option<i64> {
2125    const MAX_EXACT_SCALED: f64 = 9_007_199_254_740_992.0;
2126
2127    if !value.is_finite() || value.is_sign_negative() {
2128        return None;
2129    }
2130    let scaled = value * 4.0;
2131    if !scaled.is_finite()
2132        || scaled > MAX_EXACT_SCALED
2133        || scaled.fract().to_bits() != 0.0f64.to_bits()
2134    {
2135        return None;
2136    }
2137    let scaled_i64 = scaled as i64;
2138    if (scaled_i64 as f64).to_bits() == scaled.to_bits() {
2139        Some(scaled_i64)
2140    } else {
2141        None
2142    }
2143}
2144
2145fn append_quarter_scaled_pandas_float(out: &mut String, scaled: i64) {
2146    debug_assert!(scaled >= 0);
2147    let mut whole = (scaled / 4) as u64;
2148    let rem = scaled % 4;
2149
2150    // Manual decimal emitter (br-frankenpandas-uza04.84): the quarter-affine
2151    // whole part previously went through `write!(out, "{whole}")`, i.e. the
2152    // core::fmt::write + i64 Display machinery (Formatter dispatch, padding
2153    // checks) the profile flagged as the residual hot path. Here we write the
2154    // whole digits and the fixed fractional suffix into one stack buffer and
2155    // emit a single push_str — byte-identical output, no fmt dispatch. `whole`
2156    // is non-negative (scaled >= 0) so no sign handling is needed; max 20 u64
2157    // digits + a 3-byte ".75" suffix fit in 23 bytes.
2158    let mut buf = [0u8; 23];
2159    let suffix: &[u8] = match rem {
2160        1 => b".25",
2161        2 => b".5",
2162        3 => b".75",
2163        _ => b".0",
2164    };
2165    let mut end = buf.len() - suffix.len();
2166    buf[end..].copy_from_slice(suffix);
2167
2168    // Whole digits, written right-to-left immediately before the suffix.
2169    let mut start = end;
2170    loop {
2171        start -= 1;
2172        buf[start] = b'0' + (whole % 10) as u8;
2173        whole /= 10;
2174        if whole == 0 {
2175            break;
2176        }
2177    }
2178    end = buf.len();
2179    out.push_str(std::str::from_utf8(&buf[start..end]).unwrap_or("0.0"));
2180}
2181
2182fn append_csv_minimal_field(out: &mut String, field: &str, delim: u8, quote_empty_single: bool) {
2183    if quote_empty_single && field.is_empty() {
2184        out.push_str("\"\"");
2185    } else if field
2186        .bytes()
2187        .any(|b| b == delim || b == b'"' || b == b'\n' || b == b'\r')
2188    {
2189        out.push('"');
2190        for ch in field.chars() {
2191            if ch == '"' {
2192                out.push_str("\"\"");
2193            } else {
2194                out.push(ch);
2195            }
2196        }
2197        out.push('"');
2198    } else {
2199        out.push_str(field);
2200    }
2201}
2202
2203fn append_i64_decimal(out: &mut String, value: i64) {
2204    let mut n = value.unsigned_abs();
2205    let mut buf = [0u8; 20];
2206    let mut start = buf.len();
2207    loop {
2208        start -= 1;
2209        buf[start] = b'0' + (n % 10) as u8;
2210        n /= 10;
2211        if n == 0 {
2212            break;
2213        }
2214    }
2215    if value < 0 {
2216        start -= 1;
2217        buf[start] = b'-';
2218    }
2219    out.push_str(std::str::from_utf8(&buf[start..]).unwrap_or(""));
2220}
2221
2222fn try_write_csv_typed(frame: &DataFrame, options: &CsvWriteOptions) -> Option<String> {
2223    let delim = options.delimiter;
2224    if !delim.is_ascii() {
2225        return None;
2226    }
2227    let delim_c = delim as char;
2228
2229    let headers: Vec<&String> = frame.column_names().into_iter().collect();
2230    let n = frame.index().len();
2231    let index_labels = if options.include_index {
2232        if frame.row_multiindex().is_some() {
2233            return None;
2234        }
2235        let labels = frame.index().labels();
2236        if labels.len() != n
2237            || labels
2238                .iter()
2239                .any(|label| !matches!(label, IndexLabel::Int64(_)))
2240        {
2241            return None;
2242        }
2243        Some(labels)
2244    } else {
2245        None
2246    };
2247
2248    enum FastCol<'a> {
2249        F {
2250            values: &'a [f64],
2251            quarter_plan: Option<Float64QuarterAffineCsvPlan>,
2252        },
2253        I(&'a [i64]),
2254        B(&'a [bool]),
2255        // All-valid contiguous Utf8: (bytes, offsets) with row r =
2256        // bytes[offsets[r]..offsets[r+1]].
2257        U(&'a [u8], &'a [usize]),
2258        // NULLABLE contiguous Utf8: (bytes, offsets, validity). A present row
2259        // (validity.get(r)) renders its span; a missing row renders na_rep — so a
2260        // string column WITH nulls no longer forces the WHOLE frame off the fast path.
2261        UN(&'a [u8], &'a [usize], &'a fp_columnar::ValidityMask),
2262        // NULLABLE Float64: (data, validity). A present row (validity.get(r) AND
2263        // non-NaN) renders format_pandas_float; a missing row (validity-clear OR a
2264        // valid-bit NaN — both `is_missing` for Float64) renders na_rep.
2265        FN(&'a [f64], &'a fp_columnar::ValidityMask),
2266        // NULLABLE Int64: (data, validity). Present → decimal; missing → na_rep.
2267        // Int64 has no NaN, so missingness is the validity bit alone.
2268        IN(&'a [i64], &'a fp_columnar::ValidityMask),
2269        // NULLABLE Bool: (data, validity). Present → True/False; missing → na_rep.
2270        BN(&'a [bool], &'a fp_columnar::ValidityMask),
2271        // All-valid (no validity-mask null) Datetime64 ns + the column-uniform
2272        // to_csv format; NaT sentinels render as na_rep inline.
2273        Dt(&'a [i64], DatetimeCsvFormat),
2274    }
2275    let mut cols: Vec<FastCol<'_>> = Vec::with_capacity(headers.len());
2276    for name in &headers {
2277        let column = frame.column(name)?;
2278        if let Some(s) = column.as_f64_slice() {
2279            if s.len() != n {
2280                return None;
2281            }
2282            cols.push(FastCol::F {
2283                values: s,
2284                quarter_plan: Float64QuarterAffineCsvPlan::for_slice(s),
2285            });
2286        } else if let Some(s) = column.as_i64_slice() {
2287            if s.len() != n {
2288                return None;
2289            }
2290            cols.push(FastCol::I(s));
2291        } else if let Some(s) = column.as_bool_slice() {
2292            if s.len() != n {
2293                return None;
2294            }
2295            cols.push(FastCol::B(s));
2296        } else if let Some((bytes, offsets)) = column.as_utf8_contiguous() {
2297            if offsets.len() != n + 1 {
2298                return None;
2299            }
2300            cols.push(FastCol::U(bytes, offsets));
2301        } else if let Some((bytes, offsets)) = column.as_nullable_utf8_contiguous() {
2302            // Nullable contiguous Utf8: present rows render their span, missing rows
2303            // (validity-clear) render na_rep — so one null-bearing string column no
2304            // longer disables the fast writer for the whole frame.
2305            if offsets.len() != n + 1 {
2306                return None;
2307            }
2308            cols.push(FastCol::UN(bytes, offsets, column.validity()));
2309        } else if let Some((s, validity)) = column.as_f64_slice_with_validity() {
2310            // Nullable Float64: the all-valid `as_f64_slice` above bailed (any NaN or
2311            // mask-null), so a null-bearing float column would otherwise force the whole
2312            // frame off the fast path. Render present slots and na_rep at missing ones.
2313            if s.len() != n {
2314                return None;
2315            }
2316            cols.push(FastCol::FN(s, validity));
2317        } else if let Some((s, validity)) = column.as_i64_slice_with_validity() {
2318            // Nullable Int64 sibling (no NaN — missingness is the validity bit alone).
2319            if s.len() != n {
2320                return None;
2321            }
2322            cols.push(FastCol::IN(s, validity));
2323        } else if let Some((s, validity)) = column.as_nullable_bool_slice() {
2324            // Nullable Bool sibling: present ⇒ True/False, missing ⇒ na_rep.
2325            if s.len() != n {
2326                return None;
2327            }
2328            cols.push(FastCol::BN(s, validity));
2329        } else if column.dtype().is_datetime() {
2330            // A validity-mask null (data slot ≠ NaT) would diverge from the
2331            // general path's `Scalar::Null` → na_rep; require no mask-nulls. NaT
2332            // sentinels (kept AS DATA by an all-valid backing) are rendered as
2333            // na_rep inline, matching scalar_to_csv_cell.
2334            let s = column.as_datetime64_slice()?;
2335            if s.len() != n || column.has_nulls() {
2336                return None;
2337            }
2338            cols.push(FastCol::Dt(s, datetime_csv_format(column)));
2339        } else {
2340            return None;
2341        }
2342    }
2343
2344    // csv QUOTE_MINIMAL (matched by the general WriterBuilder path) quotes a field
2345    // as `""` when it is the SOLE field in its record and would otherwise be empty,
2346    // so the line is not an ambiguous blank that read_csv decodes as zero fields.
2347    // A record has one field when there is exactly one emitted index/column field.
2348    let field_count = cols.len() + usize::from(options.include_index);
2349    let single_field = field_count == 1;
2350    let mut out = String::with_capacity(n.saturating_mul(field_count).saturating_mul(8) + 64);
2351    if options.header {
2352        let mut wrote_field = false;
2353        if options.include_index {
2354            let index_header = resolve_csv_index_header(frame, options);
2355            append_csv_minimal_field(&mut out, &index_header, delim, single_field);
2356            wrote_field = true;
2357        }
2358        for (i, h) in headers.iter().enumerate() {
2359            if wrote_field || i > 0 {
2360                out.push(delim_c);
2361            }
2362            append_csv_minimal_field(&mut out, h.as_str(), delim, single_field);
2363            wrote_field = true;
2364        }
2365        out.push('\n');
2366    }
2367    // Per-row-range writer (br-frankenpandas-csvpar): writes rows `[lo, hi)` into
2368    // `dst`, reading ONLY the shared read-only typed slices, so each row's bytes are
2369    // independent of chunk boundaries. Shared by the serial and chunked-parallel
2370    // drivers below — the parallel concat is byte-for-byte identical to the serial
2371    // output (header + rows 0..n in order).
2372    let write_range = |lo: usize, hi: usize, dst: &mut String| {
2373        for r in lo..hi {
2374            if let Some(labels) = index_labels
2375                && let IndexLabel::Int64(v) = &labels[r]
2376            {
2377                append_i64_decimal(dst, *v);
2378            }
2379            for (c, col) in cols.iter().enumerate() {
2380                if c > 0 || index_labels.is_some() {
2381                    dst.push(delim_c);
2382                }
2383                match col {
2384                    // Float64 uses format_pandas_float (Python str(float): keeps
2385                    // "1.0", signed 2-digit sci notation) — EXACTLY what
2386                    // scalar_to_csv_with_na uses, NOT Rust's Display (which drops the
2387                    // ".0"). as_f64_slice yields an all-valid (NaN-free) buffer so the
2388                    // NaN branch never fires; kept for defensive parity.
2389                    FastCol::F {
2390                        values,
2391                        quarter_plan,
2392                    } => {
2393                        if quarter_plan.is_some_and(|plan| plan.append_row(dst, r)) {
2394                            continue;
2395                        }
2396                        let v = values[r];
2397                        if v.is_nan() {
2398                            // Unreachable in practice (as_f64_slice is NaN-free), but kept
2399                            // isomorphic with the general path: a sole empty na_rep is quoted.
2400                            if single_field && options.na_rep.is_empty() {
2401                                dst.push_str("\"\"");
2402                            } else {
2403                                dst.push_str(&options.na_rep);
2404                            }
2405                        } else {
2406                            write_pandas_float(dst, v);
2407                        }
2408                    }
2409                    // Int64 formats via the hand-rolled append_i64_decimal fast path
2410                    // (byte-identical to Rust Display / scalar_to_csv's `v.to_string()`,
2411                    // but writes straight into `dst` with no temporary String alloc — so
2412                    // this is already optimal; don't "speed it up" with to_string/itoa).
2413                    FastCol::I(s) => {
2414                        append_i64_decimal(dst, s[r]);
2415                    }
2416                    // Bool uses pandas to_csv spelling: capitalized True/False.
2417                    FastCol::B(s) => {
2418                        dst.push_str(if s[r] { "True" } else { "False" });
2419                    }
2420                    // Utf8 cell: the raw &str (= Scalar::Utf8's value in scalar_to_csv),
2421                    // CSV-quoted only when it contains the delimiter, a quote, CR, or
2422                    // LF — pandas/csv QUOTE_MINIMAL, with internal quotes doubled.
2423                    FastCol::U(bytes, offsets) => {
2424                        let field = &bytes[offsets[r]..offsets[r + 1]];
2425                        // SAFETY-FREE: contiguous Utf8 backing is valid UTF-8.
2426                        let field = std::str::from_utf8(field).unwrap_or("");
2427                        append_csv_minimal_field(dst, field, delim, single_field);
2428                    }
2429                    // Nullable Utf8 cell: a present row (validity-set) renders its span
2430                    // exactly like `FastCol::U`; a missing row renders na_rep with the same
2431                    // sole-empty-field quoting as the Dt NaT / F NaN arms (isomorphic with
2432                    // the general path's `Scalar::Null` → na_rep).
2433                    FastCol::UN(bytes, offsets, validity) => {
2434                        if validity.get(r) {
2435                            let field = &bytes[offsets[r]..offsets[r + 1]];
2436                            let field = std::str::from_utf8(field).unwrap_or("");
2437                            append_csv_minimal_field(dst, field, delim, single_field);
2438                        } else if single_field && options.na_rep.is_empty() {
2439                            dst.push_str("\"\"");
2440                        } else {
2441                            dst.push_str(&options.na_rep);
2442                        }
2443                    }
2444                    // Nullable Float64: a present, non-NaN row renders like FastCol::F
2445                    // (write_pandas_float == format_pandas_float in scalar_to_csv_with_na);
2446                    // a missing row (validity-clear OR valid-bit NaN — both is_missing for
2447                    // Float64) renders na_rep with the same sole-empty-field quoting.
2448                    FastCol::FN(s, validity) => {
2449                        let v = s[r];
2450                        if validity.get(r) && !v.is_nan() {
2451                            write_pandas_float(dst, v);
2452                        } else if single_field && options.na_rep.is_empty() {
2453                            dst.push_str("\"\"");
2454                        } else {
2455                            dst.push_str(&options.na_rep);
2456                        }
2457                    }
2458                    // Nullable Int64: present ⇒ decimal (== FastCol::I / scalar_to_csv);
2459                    // missing (validity-clear) ⇒ na_rep.
2460                    FastCol::IN(s, validity) => {
2461                        if validity.get(r) {
2462                            append_i64_decimal(dst, s[r]);
2463                        } else if single_field && options.na_rep.is_empty() {
2464                            dst.push_str("\"\"");
2465                        } else {
2466                            dst.push_str(&options.na_rep);
2467                        }
2468                    }
2469                    // Nullable Bool: present ⇒ True/False (== FastCol::B / scalar_to_csv);
2470                    // missing (validity-clear) ⇒ na_rep.
2471                    FastCol::BN(s, validity) => {
2472                        if validity.get(r) {
2473                            dst.push_str(if s[r] { "True" } else { "False" });
2474                        } else if single_field && options.na_rep.is_empty() {
2475                            dst.push_str("\"\"");
2476                        } else {
2477                            dst.push_str(&options.na_rep);
2478                        }
2479                    }
2480                    // Datetime64: NaT → na_rep (isomorphic with the F NaN arm's sole
2481                    // empty-na quoting); else the column-uniform format string, routed
2482                    // through QUOTE_MINIMAL exactly like scalar_to_csv_cell's output.
2483                    FastCol::Dt(s, fmt) => {
2484                        let v = s[r];
2485                        if v == Timestamp::NAT {
2486                            if single_field && options.na_rep.is_empty() {
2487                                dst.push_str("\"\"");
2488                            } else {
2489                                dst.push_str(&options.na_rep);
2490                            }
2491                        } else {
2492                            let rendered = format_datetime_csv(v, *fmt);
2493                            append_csv_minimal_field(dst, &rendered, delim, single_field);
2494                        }
2495                    }
2496                }
2497            }
2498            dst.push('\n');
2499        }
2500    };
2501
2502    // Chunked-parallel serialization: for a large frame, format contiguous row
2503    // ranges into per-thread buffers and concatenate them IN ORDER onto `out`
2504    // (which already holds the header). ryu float formatting is CPU-bound and the
2505    // rows are independent, so this scales with available cores; bit-identical to
2506    // the serial `write_range(0, n)` since chunk boundaries don't affect row bytes.
2507    const CSV_PAR_MIN_ROWS: usize = 50_000;
2508    const CSV_PAR_MIN_ROWS_PER_WORKER: usize = 16_384;
2509    let workers = if n >= CSV_PAR_MIN_ROWS {
2510        fp_columnar::cached_available_parallelism()
2511            .min(16)
2512            .min(n / CSV_PAR_MIN_ROWS_PER_WORKER)
2513            .max(1)
2514    } else {
2515        1
2516    };
2517    if workers >= 2 {
2518        let chunk = n.div_ceil(workers);
2519        let write_range = &write_range;
2520        let parts: Vec<String> = std::thread::scope(|scope| {
2521            let mut handles = Vec::with_capacity(workers);
2522            let mut start = 0;
2523            while start < n {
2524                let end = (start + chunk).min(n);
2525                handles.push(scope.spawn(move || {
2526                    let mut buf = String::with_capacity(
2527                        (end - start).saturating_mul(field_count).saturating_mul(8) + 16,
2528                    );
2529                    write_range(start, end, &mut buf);
2530                    buf
2531                }));
2532                start = end;
2533            }
2534            handles
2535                .into_iter()
2536                .map(|h| h.join().expect("csv writer thread"))
2537                .collect()
2538        });
2539        for p in parts {
2540            out.push_str(&p);
2541        }
2542    } else {
2543        write_range(0, n, &mut out);
2544    }
2545    Some(out)
2546}
2547
2548pub fn write_csv_string_with_options(
2549    frame: &DataFrame,
2550    options: &CsvWriteOptions,
2551) -> Result<String, IoError> {
2552    if options.include_index && frame.row_multiindex().is_some() {
2553        let materialized = materialize_named_row_multiindex_columns(frame)?;
2554        let mut nested_options = options.clone();
2555        nested_options.include_index = false;
2556        nested_options.index_label = None;
2557        return write_csv_string_with_options(&materialized, &nested_options);
2558    }
2559
2560    // Typed fast path (br-frankenpandas-qk2i9): when every column is an all-valid
2561    // Int64/Float64 typed slice or all-valid contiguous Utf8 (and the index is
2562    // not written), format the cells straight from the contiguous typed buffers,
2563    // skipping the per-column `Vec<Scalar>` materialization + per-cell `String` +
2564    // `csv` record machinery. Byte-for-byte identical to the general writer:
2565    // floats via write_pandas_float (= scalar_to_csv_with_na), Int64 Display
2566    // (= scalar_to_csv), Utf8 QUOTE_MINIMAL with doubled quotes, terminator `\n`,
2567    // and only taken when header names need no quoting.
2568    if let Some(out) = try_write_csv_typed(frame, options) {
2569        return Ok(out);
2570    }
2571
2572    let mut writer = WriterBuilder::new()
2573        .delimiter(options.delimiter)
2574        .from_writer(Vec::new());
2575
2576    let headers = frame
2577        .column_names()
2578        .into_iter()
2579        .cloned()
2580        .collect::<Vec<_>>();
2581    if options.header {
2582        let mut header_row =
2583            Vec::with_capacity(headers.len() + if options.include_index { 1 } else { 0 });
2584        if options.include_index {
2585            header_row.push(resolve_csv_index_header(frame, options));
2586        }
2587        header_row.extend(headers.iter().cloned());
2588        writer.write_record(&header_row)?;
2589    }
2590
2591    // Pre-compute each datetime column's column-uniform to_csv format (pandas
2592    // renders a datetime column with one date-only/seconds/sub-second form).
2593    let dt_formats: Vec<Option<DatetimeCsvFormat>> = headers
2594        .iter()
2595        .map(|name| {
2596            frame.column(name).and_then(|column| {
2597                column
2598                    .dtype()
2599                    .is_datetime()
2600                    .then(|| datetime_csv_format(column))
2601            })
2602        })
2603        .collect();
2604    // A DatetimeIndex follows the same column-uniform rule when written.
2605    let index_dt_format = if options.include_index {
2606        index_datetime_csv_format(frame)
2607    } else {
2608        None
2609    };
2610
2611    for row_idx in 0..frame.index().len() {
2612        let mut row = Vec::with_capacity(headers.len() + if options.include_index { 1 } else { 0 });
2613        if options.include_index {
2614            row.push(index_label_csv_string(frame, row_idx, index_dt_format)?);
2615        }
2616        row.extend(headers.iter().enumerate().map(|(col_idx, name)| {
2617            let value = frame.column(name).and_then(|column| column.value(row_idx));
2618            match value {
2619                Some(scalar) => scalar_to_csv_cell(scalar, &options.na_rep, dt_formats[col_idx]),
2620                None => options.na_rep.clone(),
2621            }
2622        }));
2623        writer.write_record(&row)?;
2624    }
2625
2626    let bytes = writer.into_inner().map_err(|err| err.into_error())?;
2627    Ok(String::from_utf8(bytes)?)
2628}
2629
2630/// Serialize a DataFrame to a GitHub-style Markdown table.
2631///
2632/// This covers pandas' pure formatter path without taking a dependency on
2633/// Python's optional `tabulate` package.
2634pub fn write_markdown_string_with_options(
2635    frame: &DataFrame,
2636    options: &MarkdownWriteOptions,
2637) -> Result<String, IoError> {
2638    if options.include_index && frame.row_multiindex().is_some() {
2639        let materialized = materialize_named_row_multiindex_columns(frame)?;
2640        let mut nested_options = options.clone();
2641        nested_options.include_index = false;
2642        nested_options.index_label = None;
2643        return write_markdown_string_with_options(&materialized, &nested_options);
2644    }
2645
2646    let headers = frame
2647        .column_names()
2648        .into_iter()
2649        .cloned()
2650        .collect::<Vec<_>>();
2651    let table_width = headers.len() + usize::from(options.include_index);
2652    let mut out = String::new();
2653
2654    let mut header_row = Vec::with_capacity(table_width);
2655    if options.include_index {
2656        header_row.push(resolve_table_index_header(
2657            frame,
2658            options.index_label.as_deref(),
2659        ));
2660    }
2661    header_row.extend(headers.iter().cloned());
2662    push_markdown_row(&mut out, &header_row);
2663
2664    let separator = vec!["---".to_owned(); table_width];
2665    push_markdown_row(&mut out, &separator);
2666
2667    for row_idx in 0..frame.index().len() {
2668        let mut row = Vec::with_capacity(table_width);
2669        if options.include_index {
2670            row.push(index_label_string(frame, row_idx)?);
2671        }
2672        row.extend(headers.iter().map(|name| {
2673            let value = frame.column(name).and_then(|column| column.value(row_idx));
2674            match value {
2675                Some(scalar) => scalar_to_table_with_na(scalar, &options.na_rep),
2676                None => options.na_rep.clone(),
2677            }
2678        }));
2679        push_markdown_row(&mut out, &row);
2680    }
2681
2682    Ok(out)
2683}
2684
2685/// Serialize a DataFrame to a booktabs-compatible LaTeX tabular block.
2686pub fn write_latex_string_with_options(
2687    frame: &DataFrame,
2688    options: &LatexWriteOptions,
2689) -> Result<String, IoError> {
2690    if options.include_index && frame.row_multiindex().is_some() {
2691        let materialized = materialize_named_row_multiindex_columns(frame)?;
2692        let mut nested_options = options.clone();
2693        nested_options.include_index = false;
2694        nested_options.index_label = None;
2695        return write_latex_string_with_options(&materialized, &nested_options);
2696    }
2697
2698    let headers = frame
2699        .column_names()
2700        .into_iter()
2701        .cloned()
2702        .collect::<Vec<_>>();
2703    let table_width = headers.len() + usize::from(options.include_index);
2704    let mut out = String::new();
2705
2706    out.push_str("\\begin{tabular}{");
2707    out.push_str(&"l".repeat(table_width));
2708    out.push_str("}\n\\toprule\n");
2709
2710    let mut header_row = Vec::with_capacity(table_width);
2711    if options.include_index {
2712        header_row.push(String::new());
2713    }
2714    header_row.extend(headers.iter().cloned());
2715    push_latex_row(&mut out, &header_row, options.escape);
2716
2717    if options.include_index {
2718        let index_name = resolve_table_index_header(frame, options.index_label.as_deref());
2719        if !index_name.is_empty() {
2720            let mut index_name_row = Vec::with_capacity(table_width);
2721            index_name_row.push(index_name);
2722            index_name_row.extend(std::iter::repeat_n(String::new(), headers.len()));
2723            push_latex_row(&mut out, &index_name_row, options.escape);
2724        }
2725    }
2726
2727    out.push_str("\\midrule\n");
2728
2729    for row_idx in 0..frame.index().len() {
2730        let mut row = Vec::with_capacity(table_width);
2731        if options.include_index {
2732            row.push(index_label_string(frame, row_idx)?);
2733        }
2734        row.extend(headers.iter().map(|name| {
2735            let value = frame.column(name).and_then(|column| column.value(row_idx));
2736            match value {
2737                Some(scalar) => scalar_to_latex_cell(scalar, &options.na_rep),
2738                None => options.na_rep.clone(),
2739            }
2740        }));
2741        push_latex_row(&mut out, &row, options.escape);
2742    }
2743
2744    out.push_str("\\bottomrule\n\\end{tabular}\n");
2745    Ok(out)
2746}
2747
2748/// Serialize a DataFrame to an HTML table string.
2749pub fn write_html_string_with_options(
2750    frame: &DataFrame,
2751    options: &HtmlWriteOptions,
2752) -> Result<String, IoError> {
2753    if options.include_index && frame.row_multiindex().is_some() {
2754        let materialized = materialize_named_row_multiindex_columns(frame)?;
2755        let nested_options = HtmlWriteOptions {
2756            include_index: false,
2757            ..options.clone()
2758        };
2759        return write_html_string_with_options(&materialized, &nested_options);
2760    }
2761
2762    write_html_table_string(frame, options)
2763}
2764
2765fn write_html_table_string(
2766    frame: &DataFrame,
2767    options: &HtmlWriteOptions,
2768) -> Result<String, IoError> {
2769    let column_names = frame.column_names();
2770    let columns = column_names
2771        .iter()
2772        .map(|name| frame.column(name))
2773        .collect::<Vec<_>>();
2774    let mut out = String::new();
2775    push_html_table_open(&mut out, options);
2776    out.push_str("  <thead>\n    <tr style=\"text-align: ");
2777    out.push_str(&escape_html_attr(
2778        options.justify.as_deref().unwrap_or("right"),
2779    ));
2780    out.push_str(";\">\n");
2781
2782    if options.include_index {
2783        out.push_str("      <th></th>\n");
2784    }
2785    for name in &column_names {
2786        out.push_str("      <th>");
2787        out.push_str(&html_text(name, options.escape));
2788        out.push_str("</th>\n");
2789    }
2790    out.push_str("    </tr>\n  </thead>\n  <tbody>\n");
2791
2792    for row_idx in 0..frame.index().len() {
2793        out.push_str("    <tr>\n");
2794        if options.include_index {
2795            out.push_str("      <th>");
2796            out.push_str(&html_index_label_string(frame, row_idx, options.escape)?);
2797            out.push_str("</th>\n");
2798        }
2799        for column in &columns {
2800            let value = (*column).and_then(|column| column.value(row_idx));
2801            out.push_str("      <td>");
2802            match value {
2803                Some(scalar) => out.push_str(&html_scalar_string(scalar, options)),
2804                None => out.push_str(&html_text(&options.na_rep, options.escape)),
2805            }
2806            out.push_str("</td>\n");
2807        }
2808        out.push_str("    </tr>\n");
2809    }
2810
2811    out.push_str("  </tbody>\n</table>");
2812    Ok(out)
2813}
2814
2815fn push_html_table_open(out: &mut String, options: &HtmlWriteOptions) {
2816    out.push_str("<table");
2817    if let Some(border) = options.border.filter(|border| *border > 0) {
2818        out.push_str(" border=\"");
2819        out.push_str(&border.to_string());
2820        out.push('"');
2821    }
2822    out.push_str(" class=\"");
2823    out.push_str(&html_class_attr(&options.classes));
2824    out.push('"');
2825    if let Some(table_id) = options
2826        .table_id
2827        .as_deref()
2828        .map(str::trim)
2829        .filter(|table_id| !table_id.is_empty())
2830    {
2831        out.push_str(" id=\"");
2832        out.push_str(&escape_html_attr(table_id));
2833        out.push('"');
2834    }
2835    out.push_str(">\n");
2836}
2837
2838fn html_class_attr(classes: &[String]) -> String {
2839    std::iter::once("dataframe".to_owned())
2840        .chain(
2841            classes
2842                .iter()
2843                .flat_map(|class| class.split_whitespace())
2844                .filter(|class| !class.is_empty())
2845                .map(escape_html_attr),
2846        )
2847        .collect::<Vec<_>>()
2848        .join(" ")
2849}
2850
2851fn html_index_label_string(
2852    frame: &DataFrame,
2853    row_idx: usize,
2854    escape: bool,
2855) -> Result<String, IoError> {
2856    let label = frame
2857        .index()
2858        .labels()
2859        .get(row_idx)
2860        .ok_or_else(|| IoError::Html(format!("missing index label at row {row_idx}")))?;
2861    let raw = match label {
2862        IndexLabel::Int64(v) => v.to_string(),
2863        IndexLabel::Utf8(s) => s.clone(),
2864        IndexLabel::Timedelta64(ns) => Timedelta::format(*ns),
2865        IndexLabel::Datetime64(ns) => format_datetime_ns(*ns),
2866        f @ (IndexLabel::Float64(_) | IndexLabel::Bool(_)) => f.to_string(),
2867        IndexLabel::Null(_) => label.to_string(),
2868    };
2869    Ok(html_text(&raw, escape))
2870}
2871
2872fn html_scalar_string(scalar: &Scalar, options: &HtmlWriteOptions) -> String {
2873    match scalar {
2874        Scalar::Null(_) => html_text(&options.na_rep, options.escape),
2875        Scalar::Bool(value) => html_text(if *value { "True" } else { "False" }, options.escape),
2876        Scalar::Int64(value) => value.to_string(),
2877        Scalar::Float64(value) => {
2878            if value.is_nan() {
2879                html_text(&options.na_rep, options.escape)
2880            } else if value.fract() == 0.0 {
2881                format!("{value:.1}")
2882            } else {
2883                value.to_string()
2884            }
2885        }
2886        Scalar::Utf8(value) => {
2887            if options.render_links && is_html_renderable_link(value) {
2888                let label = html_text(value, options.escape);
2889                format!(
2890                    "<a href=\"{}\" target=\"_blank\">{label}</a>",
2891                    escape_html_attr(value)
2892                )
2893            } else {
2894                html_text(value, options.escape)
2895            }
2896        }
2897        // pandas to_html renders a temporal NaT as the literal "NaT" (na_rep
2898        // overrides only float NaN); verified vs pandas 2.2.3. (tblnat)
2899        Scalar::Timedelta64(value) => {
2900            if *value == Timedelta::NAT {
2901                html_text("NaT", options.escape)
2902            } else {
2903                html_text(&Timedelta::format(*value), options.escape)
2904            }
2905        }
2906        Scalar::Datetime64(value) => {
2907            if *value == Timestamp::NAT {
2908                html_text("NaT", options.escape)
2909            } else {
2910                html_text(&format_datetime_ns(*value), options.escape)
2911            }
2912        }
2913        Scalar::Period(value) => {
2914            if value.ordinal == i64::MIN {
2915                html_text("NaT", options.escape)
2916            } else {
2917                html_text(&value.calendar_string(), options.escape)
2918            }
2919        }
2920        Scalar::Interval(iv) => html_text(&format!("{iv}"), options.escape),
2921    }
2922}
2923
2924fn html_text(value: &str, escape: bool) -> String {
2925    if escape {
2926        escape_html_text(value)
2927    } else {
2928        value.to_owned()
2929    }
2930}
2931
2932fn is_html_renderable_link(value: &str) -> bool {
2933    value.starts_with("http://") || value.starts_with("https://") || value.starts_with("ftp://")
2934}
2935
2936fn escape_html_text(value: &str) -> String {
2937    let mut escaped = String::with_capacity(value.len());
2938    for ch in value.chars() {
2939        match ch {
2940            '&' => escaped.push_str("&amp;"),
2941            '<' => escaped.push_str("&lt;"),
2942            '>' => escaped.push_str("&gt;"),
2943            _ => escaped.push(ch),
2944        }
2945    }
2946    escaped
2947}
2948
2949fn escape_html_attr(value: &str) -> String {
2950    let mut escaped = String::with_capacity(value.len());
2951    for ch in value.chars() {
2952        match ch {
2953            '&' => escaped.push_str("&amp;"),
2954            '"' => escaped.push_str("&quot;"),
2955            '<' => escaped.push_str("&lt;"),
2956            '>' => escaped.push_str("&gt;"),
2957            _ => escaped.push(ch),
2958        }
2959    }
2960    escaped
2961}
2962
2963/// Parse a DataFrame from the first HTML table in a document string.
2964///
2965/// This is the local, table-oriented subset of pandas `read_html`: it parses
2966/// static HTML with an HTML5 parser, uses the first `<thead><tr>` as headers
2967/// when present, otherwise uses the first row with header cells, and fills
2968/// short body rows with nulls.
2969pub fn read_html_str(input: &str) -> Result<DataFrame, IoError> {
2970    read_html_str_with_options(input, &HtmlReadOptions::default())
2971}
2972
2973/// Parse a DataFrame from an HTML document string with options.
2974pub fn read_html_str_with_options(
2975    input: &str,
2976    options: &HtmlReadOptions,
2977) -> Result<DataFrame, IoError> {
2978    let document = Html::parse_document(input);
2979    let table_selector = html_selector("table")?;
2980    let row_selector = html_selector("tr")?;
2981    let thead_row_selector = html_selector("thead tr")?;
2982    let tbody_row_selector = html_selector("tbody tr")?;
2983    let cell_selector = html_selector("th, td")?;
2984    let th_selector = html_selector("th")?;
2985
2986    let table = document
2987        .select(&table_selector)
2988        .nth(options.table_index)
2989        .ok_or_else(|| {
2990            IoError::Html(format!(
2991                "html input contains no table at index {}",
2992                options.table_index
2993            ))
2994        })?;
2995
2996    let header_rows = table
2997        .select(&thead_row_selector)
2998        .map(|row| html_row_cells(row, &cell_selector))
2999        .filter(|cells| !cells.is_empty())
3000        .collect::<Vec<_>>();
3001    let body_rows = table
3002        .select(&tbody_row_selector)
3003        .map(|row| html_row_cells(row, &cell_selector))
3004        .filter(|cells| !cells.is_empty())
3005        .collect::<Vec<_>>();
3006
3007    if let Some(header_cells) = header_rows.first() {
3008        let headers = normalize_html_headers(header_cells)?;
3009        return html_rows_to_frame(headers, body_rows);
3010    }
3011
3012    let all_rows = table
3013        .select(&row_selector)
3014        .map(|row| {
3015            let has_header_cell = row.select(&th_selector).next().is_some();
3016            (has_header_cell, html_row_cells(row, &cell_selector))
3017        })
3018        .filter(|(_, cells)| !cells.is_empty())
3019        .collect::<Vec<_>>();
3020    if all_rows.is_empty() {
3021        return Err(IoError::Html(
3022            "html table contains no rows with cells".to_owned(),
3023        ));
3024    }
3025
3026    let mut all_rows = all_rows.into_iter();
3027    let (first_has_header, first_cells) = all_rows
3028        .next()
3029        .ok_or_else(|| IoError::Html("html table contains no rows with cells".to_owned()))?;
3030
3031    if first_has_header {
3032        let headers = normalize_html_headers(&first_cells)?;
3033        let data_rows = all_rows.map(|(_, cells)| cells).collect::<Vec<_>>();
3034        html_rows_to_frame(headers, data_rows)
3035    } else {
3036        let mut data_rows = vec![first_cells];
3037        data_rows.extend(all_rows.map(|(_, cells)| cells));
3038        let width = data_rows.iter().map(Vec::len).max().unwrap_or(0);
3039        if width == 0 {
3040            return Err(IoError::Html("html table contains no cells".to_owned()));
3041        }
3042        let headers = (0..width).map(|idx| idx.to_string()).collect::<Vec<_>>();
3043        html_rows_to_frame(headers, data_rows)
3044    }
3045}
3046
3047const PICKLE_FORMAT_KEY: &str = "__frankenpandas_pickle_format";
3048const PICKLE_FORMAT_VERSION: &str = "frankenpandas.dataframe.v1";
3049const PICKLE_ORIENT_KEY: &str = "orient";
3050const PICKLE_PAYLOAD_KEY: &str = "payload";
3051
3052/// Serialize a DataFrame to Pickle bytes.
3053///
3054/// This emits a fail-closed FrankenPandas envelope containing the existing
3055/// split-orient DataFrame representation. It is intentionally narrower than
3056/// pandas' arbitrary Python-object pickle support.
3057pub fn write_pickle_bytes_with_options(
3058    frame: &DataFrame,
3059    options: &PickleWriteOptions,
3060) -> Result<Vec<u8>, IoError> {
3061    let split_json = write_json_string(frame, JsonOrient::Split)?;
3062    let split_value = serde_json::from_str::<serde_json::Value>(&split_json)?;
3063    let mut envelope = serde_json::Map::new();
3064    envelope.insert(
3065        PICKLE_FORMAT_KEY.to_owned(),
3066        serde_json::Value::String(PICKLE_FORMAT_VERSION.to_owned()),
3067    );
3068    envelope.insert(
3069        PICKLE_ORIENT_KEY.to_owned(),
3070        serde_json::Value::String("split".to_owned()),
3071    );
3072    envelope.insert(PICKLE_PAYLOAD_KEY.to_owned(), split_value);
3073
3074    serde_pickle::to_vec(
3075        &serde_json::Value::Object(envelope),
3076        pickle_ser_options(options),
3077    )
3078    .map_err(|err| IoError::Pickle(err.to_string()))
3079}
3080
3081/// Deserialize a DataFrame from Pickle bytes.
3082pub fn read_pickle_bytes(input: &[u8]) -> Result<DataFrame, IoError> {
3083    read_pickle_bytes_with_options(input, &PickleReadOptions::default())
3084}
3085
3086/// Deserialize a DataFrame from Pickle bytes with options.
3087///
3088/// Only the versioned FrankenPandas envelope is accepted. Foreign Python
3089/// pickles fail closed with [`IoError::Pickle`].
3090pub fn read_pickle_bytes_with_options(
3091    input: &[u8],
3092    options: &PickleReadOptions,
3093) -> Result<DataFrame, IoError> {
3094    let value = serde_pickle::from_slice::<serde_json::Value>(input, pickle_de_options(options))
3095        .map_err(|err| IoError::Pickle(err.to_string()))?;
3096    let envelope = value
3097        .as_object()
3098        .ok_or_else(|| IoError::Pickle("pickle payload must be an object".to_owned()))?;
3099
3100    match envelope
3101        .get(PICKLE_FORMAT_KEY)
3102        .and_then(|value| value.as_str())
3103    {
3104        Some(PICKLE_FORMAT_VERSION) => {}
3105        Some(other) => {
3106            return Err(IoError::Pickle(format!(
3107                "unsupported FrankenPandas pickle format '{other}'"
3108            )));
3109        }
3110        None => {
3111            return Err(IoError::Pickle(
3112                "pickle payload is missing FrankenPandas format marker".to_owned(),
3113            ));
3114        }
3115    }
3116
3117    match envelope
3118        .get(PICKLE_ORIENT_KEY)
3119        .and_then(|value| value.as_str())
3120    {
3121        Some("split") => {}
3122        Some(other) => {
3123            return Err(IoError::Pickle(format!(
3124                "unsupported FrankenPandas pickle orient '{other}'"
3125            )));
3126        }
3127        None => {
3128            return Err(IoError::Pickle(
3129                "pickle payload is missing orient".to_owned(),
3130            ));
3131        }
3132    }
3133
3134    let payload = envelope
3135        .get(PICKLE_PAYLOAD_KEY)
3136        .ok_or_else(|| IoError::Pickle("pickle payload is missing data".to_owned()))?;
3137    let payload_json = serde_json::to_string(payload)?;
3138    read_json_str(&payload_json, JsonOrient::Split)
3139}
3140
3141fn pickle_ser_options(options: &PickleWriteOptions) -> serde_pickle::SerOptions {
3142    match options.protocol {
3143        PickleProtocol::V2 => serde_pickle::SerOptions::new().proto_v2(),
3144        PickleProtocol::V3 => serde_pickle::SerOptions::new(),
3145    }
3146}
3147
3148fn pickle_de_options(options: &PickleReadOptions) -> serde_pickle::DeOptions {
3149    let de_options = serde_pickle::DeOptions::new();
3150    if options.decode_legacy_strings {
3151        de_options.decode_strings()
3152    } else {
3153        de_options
3154    }
3155}
3156
3157#[derive(Debug, Clone)]
3158struct StataField {
3159    variable_name: String,
3160    source: StataFieldSource,
3161    variable_type: VariableType,
3162}
3163
3164#[derive(Debug, Clone)]
3165enum StataFieldSource {
3166    Index,
3167    Column(String),
3168}
3169
3170/// Serialize a DataFrame to Stata DTA bytes.
3171///
3172/// This first slice targets DTA release 118 and a DataFrame-oriented subset:
3173/// integer/bool, float, fixed string, and missing values.
3174pub fn write_stata_bytes_with_options(
3175    frame: &DataFrame,
3176    options: &StataWriteOptions,
3177) -> Result<Vec<u8>, IoError> {
3178    let fields = stata_fields_for_frame(frame, options)?;
3179    let header = Header::builder(Release::V118, ByteOrder::LittleEndian).build();
3180    let mut schema = StataSchema::builder();
3181    for field in &fields {
3182        let format = stata_format_for_type(field.variable_type);
3183        schema = schema.add_variable(
3184            Variable::builder(field.variable_type, &field.variable_name).format(format),
3185        );
3186    }
3187    let schema = schema.build().map_err(stata_error)?;
3188
3189    let mut record_writer = DtaWriter::new()
3190        .from_writer(Cursor::new(Vec::<u8>::new()))
3191        .write_header(header)
3192        .map_err(stata_error)?
3193        .write_schema(schema)
3194        .map_err(stata_error)?
3195        .into_record_writer()
3196        .map_err(stata_error)?;
3197
3198    for row_idx in 0..frame.index().len() {
3199        let mut record = Vec::with_capacity(fields.len());
3200        for field in &fields {
3201            record.push(stata_value_for_field(frame, row_idx, field)?);
3202        }
3203        record_writer.write_record(&record).map_err(stata_error)?;
3204    }
3205
3206    Ok(record_writer
3207        .into_long_string_writer()
3208        .map_err(stata_error)?
3209        .into_value_label_writer()
3210        .map_err(stata_error)?
3211        .finish()
3212        .map_err(stata_error)?
3213        .into_inner())
3214}
3215
3216/// Read a DataFrame from Stata DTA bytes.
3217pub fn read_stata_bytes(input: &[u8]) -> Result<DataFrame, IoError> {
3218    let mut characteristic_reader = DtaReader::new()
3219        .from_reader(Cursor::new(input))
3220        .read_header()
3221        .map_err(stata_error)?
3222        .read_schema()
3223        .map_err(stata_error)?;
3224    characteristic_reader.skip_to_end().map_err(stata_error)?;
3225
3226    let mut record_reader = characteristic_reader
3227        .into_record_reader()
3228        .map_err(stata_error)?;
3229    let column_order = record_reader
3230        .schema()
3231        .variables()
3232        .iter()
3233        .map(|variable| variable.name().to_owned())
3234        .collect::<Vec<_>>();
3235    reject_duplicate_headers(&column_order)?;
3236
3237    let mut columns = column_order
3238        .iter()
3239        .cloned()
3240        .map(|name| (name, Vec::new()))
3241        .collect::<BTreeMap<_, _>>();
3242    let mut row_count: i64 = 0;
3243    while let Some(record) = record_reader.read_record().map_err(stata_error)? {
3244        for (name, value) in column_order.iter().zip(record.values()) {
3245            columns
3246                .get_mut(name)
3247                .ok_or_else(|| IoError::Stata(format!("missing Stata column '{name}'")))?
3248                .push(stata_value_to_scalar(value)?);
3249        }
3250        row_count = row_count
3251            .checked_add(1)
3252            .ok_or_else(|| IoError::Stata("Stata row count exceeded i64 range".to_owned()))?;
3253    }
3254
3255    let mut out = BTreeMap::new();
3256    for name in &column_order {
3257        let values = columns
3258            .remove(name)
3259            .ok_or_else(|| IoError::Stata(format!("missing Stata column '{name}'")))?;
3260        out.insert(name.clone(), Column::from_values(values)?);
3261    }
3262    Ok(DataFrame::new_with_column_order(
3263        Index::from_i64((0..row_count).collect()),
3264        out,
3265        column_order,
3266    )?)
3267}
3268
3269fn stata_fields_for_frame(
3270    frame: &DataFrame,
3271    options: &StataWriteOptions,
3272) -> Result<Vec<StataField>, IoError> {
3273    let mut fields = Vec::new();
3274    if options.include_index {
3275        let name = options
3276            .index_label
3277            .clone()
3278            .unwrap_or_else(|| "index".to_owned());
3279        validate_stata_variable_name(&name)?;
3280        fields.push(StataField {
3281            variable_name: name,
3282            source: StataFieldSource::Index,
3283            variable_type: stata_index_variable_type(frame)?,
3284        });
3285    }
3286
3287    for name in frame.column_names() {
3288        validate_stata_variable_name(name)?;
3289        let column = frame
3290            .column(name)
3291            .ok_or_else(|| IoError::Stata(format!("missing DataFrame column '{name}'")))?;
3292        fields.push(StataField {
3293            variable_name: name.clone(),
3294            source: StataFieldSource::Column(name.clone()),
3295            variable_type: infer_stata_variable_type(column, name)?,
3296        });
3297    }
3298
3299    let mut seen = BTreeSet::new();
3300    for field in &fields {
3301        if !seen.insert(field.variable_name.clone()) {
3302            return Err(IoError::DuplicateColumnName(field.variable_name.clone()));
3303        }
3304    }
3305    Ok(fields)
3306}
3307
3308fn validate_stata_variable_name(name: &str) -> Result<(), IoError> {
3309    if name.is_empty() {
3310        return Err(IoError::Stata(
3311            "Stata variable name cannot be empty".to_owned(),
3312        ));
3313    }
3314    if name.len() > 32 {
3315        return Err(IoError::Stata(format!(
3316            "Stata variable name '{name}' exceeds 32 bytes"
3317        )));
3318    }
3319    let mut chars = name.chars();
3320    let first = chars
3321        .next()
3322        .ok_or_else(|| IoError::Stata("Stata variable name cannot be empty".to_owned()))?;
3323    if !(first == '_' || first.is_ascii_alphabetic()) {
3324        return Err(IoError::Stata(format!(
3325            "invalid Stata variable name '{name}': first character must be ASCII letter or '_'"
3326        )));
3327    }
3328    if !chars.all(|ch| ch == '_' || ch.is_ascii_alphanumeric()) {
3329        return Err(IoError::Stata(format!(
3330            "invalid Stata variable name '{name}': only ASCII letters, digits, and '_' are supported"
3331        )));
3332    }
3333    Ok(())
3334}
3335
3336fn stata_index_variable_type(frame: &DataFrame) -> Result<VariableType, IoError> {
3337    let max_len = frame
3338        .index()
3339        .labels()
3340        .iter()
3341        .map(|label| label.to_string().len())
3342        .max()
3343        .unwrap_or(1)
3344        .max(1);
3345    stata_fixed_string_type(max_len, "index")
3346}
3347
3348fn infer_stata_variable_type(column: &Column, name: &str) -> Result<VariableType, IoError> {
3349    let mut saw_numeric = false;
3350    let mut saw_float = false;
3351    let mut saw_string = false;
3352    let mut max_string_len = 1usize;
3353
3354    for value in column.values() {
3355        match value {
3356            Scalar::Null(_) => {}
3357            Scalar::Bool(_) => {
3358                saw_numeric = true;
3359            }
3360            Scalar::Int64(v) => {
3361                saw_numeric = true;
3362                if i32::try_from(*v).is_err() {
3363                    return Err(IoError::Stata(format!(
3364                        "Stata long column '{name}' cannot encode i64 value {v}"
3365                    )));
3366                }
3367            }
3368            Scalar::Float64(v) => {
3369                if !v.is_nan() {
3370                    saw_numeric = true;
3371                    saw_float = true;
3372                }
3373            }
3374            Scalar::Utf8(text) => {
3375                saw_string = true;
3376                max_string_len = max_string_len.max(text.len());
3377            }
3378            other => {
3379                saw_string = true;
3380                max_string_len = max_string_len.max(scalar_to_table_with_na(other, "").len());
3381            }
3382        }
3383    }
3384
3385    if saw_string {
3386        stata_fixed_string_type(max_string_len, name)
3387    } else if saw_numeric && !saw_float {
3388        Ok(VariableType::Long)
3389    } else {
3390        Ok(VariableType::Double)
3391    }
3392}
3393
3394fn stata_fixed_string_type(len: usize, name: &str) -> Result<VariableType, IoError> {
3395    let width = len.max(1);
3396    let width = u16::try_from(width).map_err(|_| {
3397        IoError::Stata(format!(
3398            "Stata string column '{name}' exceeds fixed string capacity"
3399        ))
3400    })?;
3401    if width > 2045 {
3402        return Err(IoError::Stata(format!(
3403            "Stata string column '{name}' requires strL; this slice supports fixed strings only"
3404        )));
3405    }
3406    Ok(VariableType::FixedString(width))
3407}
3408
3409fn stata_format_for_type(variable_type: VariableType) -> &'static str {
3410    match variable_type {
3411        VariableType::Byte | VariableType::Int | VariableType::Long => "%12.0g",
3412        VariableType::Float | VariableType::Double => "%10.0g",
3413        VariableType::FixedString(_) | VariableType::LongString => "%9s",
3414    }
3415}
3416
3417fn stata_value_for_field(
3418    frame: &DataFrame,
3419    row_idx: usize,
3420    field: &StataField,
3421) -> Result<StataValue<'static>, IoError> {
3422    match field.source {
3423        StataFieldSource::Index => Ok(StataValue::String(std::borrow::Cow::Owned(
3424            index_label_string(frame, row_idx)?,
3425        ))),
3426        StataFieldSource::Column(ref name) => {
3427            let value = frame.column(name).and_then(|column| column.value(row_idx));
3428            scalar_to_stata_value(value, field.variable_type, name)
3429        }
3430    }
3431}
3432
3433fn scalar_to_stata_value(
3434    value: Option<&Scalar>,
3435    variable_type: VariableType,
3436    name: &str,
3437) -> Result<StataValue<'static>, IoError> {
3438    match variable_type {
3439        VariableType::Long => match value {
3440            Some(Scalar::Bool(v)) => Ok(StataValue::Long(StataLong::Present(i32::from(*v)))),
3441            Some(Scalar::Int64(v)) => Ok(StataValue::Long(StataLong::Present(
3442                i32::try_from(*v).map_err(|_| {
3443                    IoError::Stata(format!("Stata long column '{name}' cannot encode {v}"))
3444                })?,
3445            ))),
3446            Some(Scalar::Null(_)) | None => {
3447                Ok(StataValue::Long(StataLong::Missing(MissingValue::System)))
3448            }
3449            Some(other) => Err(IoError::Stata(format!(
3450                "Stata long column '{name}' cannot encode {other:?}"
3451            ))),
3452        },
3453        VariableType::Double => match value {
3454            Some(Scalar::Bool(v)) => Ok(StataValue::Double(StataDouble::Present(if *v {
3455                1.0
3456            } else {
3457                0.0
3458            }))),
3459            Some(Scalar::Int64(v)) => Ok(StataValue::Double(StataDouble::Present(*v as f64))),
3460            Some(Scalar::Float64(v)) if v.is_nan() => Ok(StataValue::Double(StataDouble::Missing(
3461                MissingValue::System,
3462            ))),
3463            Some(Scalar::Float64(v)) => Ok(StataValue::Double(StataDouble::Present(*v))),
3464            Some(Scalar::Null(_)) | None => Ok(StataValue::Double(StataDouble::Missing(
3465                MissingValue::System,
3466            ))),
3467            Some(other) => Err(IoError::Stata(format!(
3468                "Stata double column '{name}' cannot encode {other:?}"
3469            ))),
3470        },
3471        VariableType::FixedString(_) => {
3472            let text = match value {
3473                Some(Scalar::Null(_)) | None => String::new(),
3474                Some(scalar) => scalar_to_table_with_na(scalar, ""),
3475            };
3476            Ok(StataValue::String(std::borrow::Cow::Owned(text)))
3477        }
3478        VariableType::Byte | VariableType::Int | VariableType::Float | VariableType::LongString => {
3479            Err(IoError::Stata(format!(
3480                "unsupported Stata variable type for column '{name}': {variable_type:?}"
3481            )))
3482        }
3483    }
3484}
3485
3486fn stata_value_to_scalar(value: &StataValue<'_>) -> Result<Scalar, IoError> {
3487    match value {
3488        StataValue::Byte(v) => Ok(v
3489            .present()
3490            .map(|value| Scalar::Int64(i64::from(value)))
3491            .unwrap_or(Scalar::Null(NullKind::NaN))),
3492        StataValue::Int(v) => Ok(v
3493            .present()
3494            .map(|value| Scalar::Int64(i64::from(value)))
3495            .unwrap_or(Scalar::Null(NullKind::NaN))),
3496        StataValue::Long(v) => Ok(v
3497            .present()
3498            .map(|value| Scalar::Int64(i64::from(value)))
3499            .unwrap_or(Scalar::Null(NullKind::NaN))),
3500        StataValue::Float(v) => Ok(v
3501            .present()
3502            .map(|value| Scalar::Float64(f64::from(value)))
3503            .unwrap_or(Scalar::Null(NullKind::NaN))),
3504        StataValue::Double(v) => Ok(v
3505            .present()
3506            .map(Scalar::Float64)
3507            .unwrap_or(Scalar::Null(NullKind::NaN))),
3508        StataValue::String(text) => Ok(Scalar::Utf8(text.to_string())),
3509        StataValue::LongStringRef(_) => Err(IoError::Stata(
3510            "Stata strL values are not supported by this reader slice".to_owned(),
3511        )),
3512    }
3513}
3514
3515fn stata_error<E: std::fmt::Display>(err: E) -> IoError {
3516    IoError::Stata(err.to_string())
3517}
3518
3519/// Parse a DataFrame from a row-oriented XML document string.
3520///
3521/// Matches the writer-oriented subset accepted by `pd.read_xml(...,
3522/// parser="etree")`: each row is an element named by
3523/// [`XmlReadOptions::row_name`], and each direct child element becomes a
3524/// DataFrame column. Attributes, XPath, namespaces, and nested field elements
3525/// are intentionally out of scope for this slice.
3526pub fn read_xml_str(input: &str) -> Result<DataFrame, IoError> {
3527    read_xml_str_with_options(input, &XmlReadOptions::default())
3528}
3529
3530/// Parse a DataFrame from a row-oriented XML document string with options.
3531pub fn read_xml_str_with_options(
3532    input: &str,
3533    options: &XmlReadOptions,
3534) -> Result<DataFrame, IoError> {
3535    validate_xml_element_name(&options.row_name)?;
3536
3537    let mut reader = XmlReader::from_str(input);
3538    reader.config_mut().trim_text(false);
3539    let mut buf = Vec::new();
3540    let mut rows: Vec<BTreeMap<String, Scalar>> = Vec::new();
3541    let mut column_order = Vec::new();
3542    let mut seen_columns = HashSet::new();
3543    let mut current_row: Option<BTreeMap<String, Scalar>> = None;
3544    let mut current_field: Option<String> = None;
3545    let mut field_text = String::new();
3546    let mut xml_version = XmlVersion::Implicit1_0;
3547
3548    loop {
3549        match reader
3550            .read_event_into(&mut buf)
3551            .map_err(|err| IoError::Xml(err.to_string()))?
3552        {
3553            Event::Start(event) => {
3554                let name = xml_event_name(event.name())?;
3555                if current_row.is_none() {
3556                    if name == options.row_name {
3557                        current_row = Some(BTreeMap::new());
3558                    }
3559                } else if let Some(field_name) = &current_field {
3560                    return Err(IoError::Xml(format!(
3561                        "nested xml element '{name}' inside field '{field_name}' is unsupported"
3562                    )));
3563                } else {
3564                    current_field = Some(name);
3565                    field_text.clear();
3566                }
3567            }
3568            Event::Empty(event) => {
3569                let name = xml_event_name(event.name())?;
3570                if let Some(field_name) = &current_field {
3571                    return Err(IoError::Xml(format!(
3572                        "nested xml element '{name}' inside field '{field_name}' is unsupported"
3573                    )));
3574                }
3575                if let Some(row) = current_row.as_mut() {
3576                    insert_xml_field(
3577                        row,
3578                        &mut column_order,
3579                        &mut seen_columns,
3580                        name,
3581                        Scalar::Null(NullKind::Null),
3582                    )?;
3583                } else if name == options.row_name {
3584                    rows.push(BTreeMap::new());
3585                }
3586            }
3587            Event::Text(event) => {
3588                if current_field.is_some() {
3589                    let decoded = event.xml_content(xml_version);
3590                    field_text.push_str(&decoded);
3591                }
3592            }
3593            Event::CData(event) => {
3594                if current_field.is_some() {
3595                    let decoded = event.xml_content(xml_version);
3596                    field_text.push_str(&decoded);
3597                }
3598            }
3599            Event::End(event) => {
3600                let name = xml_event_name(event.name())?;
3601                if let Some(field_name) = current_field.as_ref() {
3602                    if name != *field_name {
3603                        return Err(IoError::Xml(format!(
3604                            "xml field '{field_name}' closed by mismatched element '{name}'"
3605                        )));
3606                    }
3607                    let field_name = current_field.take().expect("field checked");
3608                    let value = parse_scalar(&field_text);
3609                    field_text.clear();
3610                    let row = current_row
3611                        .as_mut()
3612                        .ok_or_else(|| IoError::Xml("xml field outside row".to_owned()))?;
3613                    insert_xml_field(row, &mut column_order, &mut seen_columns, field_name, value)?;
3614                } else if name == options.row_name {
3615                    let row = current_row.take().ok_or_else(|| {
3616                        IoError::Xml("xml row closed before it opened".to_owned())
3617                    })?;
3618                    rows.push(row);
3619                }
3620            }
3621            Event::GeneralRef(reference) => {
3622                if current_field.is_some() {
3623                    field_text.push_str(&decode_xml_general_ref(reference)?);
3624                }
3625            }
3626            Event::Eof => break,
3627            Event::Decl(decl) => {
3628                if let Ok(v) = decl.version() {
3629                    xml_version = match v.as_ref() {
3630                        "1.0" => XmlVersion::Explicit1_0,
3631                        "1.1" => XmlVersion::Explicit1_1,
3632                        _ => xml_version,
3633                    };
3634                }
3635            }
3636            Event::PI(_) | Event::DocType(_) | Event::Comment(_) => {}
3637        }
3638        buf.clear();
3639    }
3640
3641    if current_field.is_some() || current_row.is_some() {
3642        return Err(IoError::Xml(
3643            "xml document ended inside an open row or field".to_owned(),
3644        ));
3645    }
3646    if rows.is_empty() {
3647        return Err(IoError::Xml(
3648            "xml input contains no row elements".to_owned(),
3649        ));
3650    }
3651
3652    let mut out_columns = BTreeMap::new();
3653    for name in &column_order {
3654        let values = rows
3655            .iter()
3656            .map(|row| {
3657                row.get(name)
3658                    .cloned()
3659                    .unwrap_or(Scalar::Null(NullKind::Null))
3660            })
3661            .collect::<Vec<_>>();
3662        out_columns.insert(name.clone(), Column::from_values(values)?);
3663    }
3664    let index = Index::from_i64((0..rows.len() as i64).collect());
3665    Ok(DataFrame::new_with_column_order(
3666        index,
3667        out_columns,
3668        column_order,
3669    )?)
3670}
3671
3672/// Serialize a DataFrame to an XML document string.
3673pub fn write_xml_string_with_options(
3674    frame: &DataFrame,
3675    options: &XmlWriteOptions,
3676) -> Result<String, IoError> {
3677    if options.include_index && frame.row_multiindex().is_some() {
3678        let materialized = materialize_named_row_multiindex_columns(frame)?;
3679        let mut nested_options = options.clone();
3680        nested_options.include_index = false;
3681        nested_options.index_label = None;
3682        return write_xml_string_with_options(&materialized, &nested_options);
3683    }
3684
3685    validate_xml_element_name(&options.root_name)?;
3686    validate_xml_element_name(&options.row_name)?;
3687
3688    let headers = frame
3689        .column_names()
3690        .into_iter()
3691        .cloned()
3692        .collect::<Vec<_>>();
3693    for name in &headers {
3694        validate_xml_element_name(name)?;
3695    }
3696
3697    let index_label = options
3698        .index_label
3699        .clone()
3700        .or_else(|| frame.index().name().map(ToOwned::to_owned))
3701        .unwrap_or_else(|| "index".to_owned());
3702    if options.include_index {
3703        validate_xml_element_name(&index_label)?;
3704    }
3705
3706    let mut out = String::new();
3707    out.push_str("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
3708    out.push('<');
3709    out.push_str(&options.root_name);
3710    out.push_str(">\n");
3711
3712    for row_idx in 0..frame.index().len() {
3713        out.push_str("  <");
3714        out.push_str(&options.row_name);
3715        out.push_str(">\n");
3716
3717        if options.include_index {
3718            let value = index_label_string(frame, row_idx)?;
3719            push_xml_field(&mut out, &index_label, Some(&value));
3720        }
3721
3722        for name in &headers {
3723            let value = frame
3724                .column(name)
3725                .and_then(|column| column.value(row_idx))
3726                .and_then(scalar_to_xml_value);
3727            push_xml_field(&mut out, name, value.as_deref());
3728        }
3729
3730        out.push_str("  </");
3731        out.push_str(&options.row_name);
3732        out.push_str(">\n");
3733    }
3734
3735    out.push_str("</");
3736    out.push_str(&options.root_name);
3737    out.push_str(">\n");
3738    Ok(out)
3739}
3740
3741fn xml_event_name(name: quick_xml::name::QName<'_>) -> Result<String, IoError> {
3742    // quick-xml 0.42 QName is str-based, so names are always valid UTF-8.
3743    Ok(name.as_ref().to_owned())
3744}
3745
3746fn decode_xml_general_ref(reference: quick_xml::events::BytesRef<'_>) -> Result<String, IoError> {
3747    // quick-xml 0.42 BytesRef is str-based, so references are always valid UTF-8.
3748    let raw: &str = reference.as_ref();
3749    match raw {
3750        "amp" => Ok("&".to_owned()),
3751        "lt" => Ok("<".to_owned()),
3752        "gt" => Ok(">".to_owned()),
3753        "quot" => Ok("\"".to_owned()),
3754        "apos" => Ok("'".to_owned()),
3755        _ if raw.starts_with("#x") => {
3756            let value = u32::from_str_radix(&raw[2..], 16)
3757                .map_err(|err| IoError::Xml(format!("invalid hex xml entity '&{raw};': {err}")))?;
3758            char::from_u32(value)
3759                .map(|ch| ch.to_string())
3760                .ok_or_else(|| IoError::Xml(format!("invalid unicode xml entity '&{raw};'")))
3761        }
3762        _ if raw.starts_with('#') => {
3763            let value = raw[1..].parse::<u32>().map_err(|err| {
3764                IoError::Xml(format!("invalid decimal xml entity '&{raw};': {err}"))
3765            })?;
3766            char::from_u32(value)
3767                .map(|ch| ch.to_string())
3768                .ok_or_else(|| IoError::Xml(format!("invalid unicode xml entity '&{raw};'")))
3769        }
3770        _ => Err(IoError::Xml(format!(
3771            "unsupported xml entity reference '&{raw};'"
3772        ))),
3773    }
3774}
3775
3776fn insert_xml_field(
3777    row: &mut BTreeMap<String, Scalar>,
3778    column_order: &mut Vec<String>,
3779    seen_columns: &mut HashSet<String>,
3780    name: String,
3781    value: Scalar,
3782) -> Result<(), IoError> {
3783    if row.insert(name.clone(), value).is_some() {
3784        return Err(IoError::Xml(format!("duplicate xml field '{name}' in row")));
3785    }
3786    if seen_columns.insert(name.clone()) {
3787        column_order.push(name);
3788    }
3789    Ok(())
3790}
3791
3792fn validate_xml_element_name(name: &str) -> Result<(), IoError> {
3793    let mut chars = name.chars();
3794    let Some(first) = chars.next() else {
3795        return Err(IoError::Xml(
3796            "xml element name must be non-empty".to_owned(),
3797        ));
3798    };
3799    let valid_first = first == '_' || first.is_ascii_alphabetic();
3800    let valid_rest =
3801        chars.all(|ch| ch == '_' || ch == '-' || ch == '.' || ch.is_ascii_alphanumeric());
3802    if valid_first && valid_rest {
3803        Ok(())
3804    } else {
3805        Err(IoError::Xml(format!("invalid xml element name '{name}'")))
3806    }
3807}
3808
3809fn push_xml_field(out: &mut String, name: &str, value: Option<&str>) {
3810    out.push_str("    <");
3811    out.push_str(name);
3812    match value {
3813        Some(value) => {
3814            out.push('>');
3815            out.push_str(&escape_xml_text(value));
3816            out.push_str("</");
3817            out.push_str(name);
3818            out.push_str(">\n");
3819        }
3820        None => out.push_str("/>\n"),
3821    }
3822}
3823
3824fn escape_xml_text(value: &str) -> String {
3825    let mut escaped = String::with_capacity(value.len());
3826    let mut chars = value.chars().peekable();
3827    while let Some(ch) = chars.next() {
3828        match ch {
3829            '&' => escaped.push_str("&amp;"),
3830            '<' => escaped.push_str("&lt;"),
3831            '>' => escaped.push_str("&gt;"),
3832            '\r' => {
3833                escaped.push('\n');
3834                if chars.peek() == Some(&'\n') {
3835                    chars.next();
3836                }
3837            }
3838            _ => escaped.push(ch),
3839        }
3840    }
3841    escaped
3842}
3843
3844fn scalar_to_xml_value(scalar: &Scalar) -> Option<String> {
3845    match scalar {
3846        Scalar::Null(_) => None,
3847        Scalar::Bool(value) => Some(if *value { "True" } else { "False" }.to_owned()),
3848        Scalar::Int64(value) => Some(value.to_string()),
3849        Scalar::Float64(value) => {
3850            if value.is_nan() {
3851                None
3852            } else if value.is_finite() && *value == value.round() && value.abs() < 1e15 {
3853                Some(format!("{value:.1}"))
3854            } else {
3855                Some(value.to_string())
3856            }
3857        }
3858        Scalar::Utf8(value) => Some(value.clone()),
3859        Scalar::Timedelta64(value) => {
3860            if *value == Timedelta::NAT {
3861                None
3862            } else {
3863                Some(Timedelta::format(*value))
3864            }
3865        }
3866        Scalar::Datetime64(value) => {
3867            if *value == Timestamp::NAT {
3868                None
3869            } else {
3870                Some(format_datetime_ns(*value))
3871            }
3872        }
3873        Scalar::Period(value) => {
3874            if value.ordinal == i64::MIN {
3875                None
3876            } else {
3877                Some(value.calendar_string())
3878            }
3879        }
3880        Scalar::Interval(iv) => Some(format!("{iv}")),
3881    }
3882}
3883
3884fn html_selector(pattern: &str) -> Result<Selector, IoError> {
3885    Selector::parse(pattern).map_err(|err| {
3886        IoError::Html(format!(
3887            "invalid built-in html selector {pattern:?}: {err:?}"
3888        ))
3889    })
3890}
3891
3892fn html_row_cells(row: ElementRef<'_>, cell_selector: &Selector) -> Vec<String> {
3893    row.select(cell_selector)
3894        .map(|cell| cell.text().collect::<String>().trim().to_owned())
3895        .collect()
3896}
3897
3898fn normalize_html_headers(raw_headers: &[String]) -> Result<Vec<String>, IoError> {
3899    if raw_headers.is_empty() {
3900        return Err(IoError::Html(
3901            "html table header row contains no cells".to_owned(),
3902        ));
3903    }
3904
3905    let mut seen = HashSet::new();
3906    let mut headers = Vec::with_capacity(raw_headers.len());
3907    for (idx, raw) in raw_headers.iter().enumerate() {
3908        let name = if raw.trim().is_empty() {
3909            format!("Unnamed: {idx}")
3910        } else {
3911            raw.trim().to_owned()
3912        };
3913        if !seen.insert(name.clone()) {
3914            return Err(IoError::DuplicateColumnName(name));
3915        }
3916        headers.push(name);
3917    }
3918    Ok(headers)
3919}
3920
3921fn html_rows_to_frame(
3922    column_order: Vec<String>,
3923    rows: Vec<Vec<String>>,
3924) -> Result<DataFrame, IoError> {
3925    let width = column_order.len();
3926    if width == 0 {
3927        return Err(IoError::Html(
3928            "html table must contain at least one column".to_owned(),
3929        ));
3930    }
3931
3932    let mut values_by_column = column_order
3933        .iter()
3934        .map(|name| (name.clone(), Vec::with_capacity(rows.len())))
3935        .collect::<BTreeMap<_, _>>();
3936    for (row_idx, row) in rows.iter().enumerate() {
3937        if row.len() > width {
3938            return Err(IoError::Html(format!(
3939                "html row {row_idx} has {} cells but header has {width}",
3940                row.len()
3941            )));
3942        }
3943        for (col_idx, name) in column_order.iter().enumerate() {
3944            let value = row
3945                .get(col_idx)
3946                .map_or(Scalar::Null(NullKind::Null), |cell| parse_scalar(cell));
3947            let column_values = values_by_column.get_mut(name).ok_or_else(|| {
3948                IoError::Html(format!("html column '{name}' was not initialized"))
3949            })?;
3950            column_values.push(value);
3951        }
3952    }
3953
3954    let mut columns = BTreeMap::new();
3955    for name in &column_order {
3956        let values = values_by_column
3957            .remove(name)
3958            .ok_or_else(|| IoError::Html(format!("html column '{name}' has no values")))?;
3959        columns.insert(name.clone(), Column::from_values(values)?);
3960    }
3961    let row_count = i64::try_from(rows.len()).map_err(|_| {
3962        IoError::Html(format!(
3963            "html table row count {} exceeds supported i64 index range",
3964            rows.len()
3965        ))
3966    })?;
3967    Ok(DataFrame::new_with_column_order(
3968        Index::from_i64((0..row_count).collect()),
3969        columns,
3970        column_order,
3971    )?)
3972}
3973
3974fn resolve_csv_index_header(frame: &DataFrame, options: &CsvWriteOptions) -> String {
3975    options
3976        .index_label
3977        .clone()
3978        .or_else(|| frame.index().name().map(ToOwned::to_owned))
3979        .unwrap_or_default()
3980}
3981
3982fn resolve_table_index_header(frame: &DataFrame, index_label: Option<&str>) -> String {
3983    index_label
3984        .map(ToOwned::to_owned)
3985        .or_else(|| frame.index().name().map(ToOwned::to_owned))
3986        .unwrap_or_default()
3987}
3988
3989fn index_label_string(frame: &DataFrame, row_idx: usize) -> Result<String, IoError> {
3990    frame
3991        .index()
3992        .labels()
3993        .get(row_idx)
3994        .map(ToString::to_string)
3995        .ok_or_else(|| {
3996            IoError::Frame(FrameError::CompatibilityRejected(format!(
3997                "index position {row_idx} out of bounds for index length {}",
3998                frame.index().len()
3999            )))
4000        })
4001}
4002
4003/// Derive the column-uniform `to_csv` datetime spec for a DatetimeIndex.
4004///
4005/// Returns `None` unless every label is `Datetime64` (a homogeneous datetime
4006/// index), so non-datetime / mixed indexes keep their default rendering.
4007fn index_datetime_csv_format(frame: &DataFrame) -> Option<DatetimeCsvFormat> {
4008    let labels = frame.index().labels();
4009    let mut any_datetime = false;
4010    let mut date_only = true;
4011    let mut subsec_digits = 0u8;
4012    for label in labels {
4013        let IndexLabel::Datetime64(ns) = label else {
4014            return None;
4015        };
4016        any_datetime = true;
4017        if *ns == i64::MIN {
4018            continue; // NaT
4019        }
4020        let subsec = (ns.rem_euclid(1_000_000_000)) as u32;
4021        if ns.div_euclid(1_000_000_000).rem_euclid(86_400) != 0 || subsec != 0 {
4022            date_only = false;
4023        }
4024        if subsec != 0 {
4025            let digits = if !subsec.is_multiple_of(1_000) {
4026                9
4027            } else if !subsec.is_multiple_of(1_000_000) {
4028                6
4029            } else {
4030                3
4031            };
4032            subsec_digits = subsec_digits.max(digits);
4033        }
4034    }
4035    any_datetime.then_some(DatetimeCsvFormat {
4036        date_only,
4037        subsec_digits,
4038    })
4039}
4040
4041/// CSV index-cell formatter: applies a DatetimeIndex's column-uniform spec when
4042/// present, otherwise identical to `index_label_string`.
4043fn index_label_csv_string(
4044    frame: &DataFrame,
4045    row_idx: usize,
4046    dt_format: Option<DatetimeCsvFormat>,
4047) -> Result<String, IoError> {
4048    if let Some(fmt) = dt_format
4049        && let Some(IndexLabel::Datetime64(ns)) = frame.index().labels().get(row_idx)
4050        && *ns != i64::MIN
4051    {
4052        return Ok(format_datetime_csv(*ns, fmt));
4053    }
4054    index_label_string(frame, row_idx)
4055}
4056
4057/// Column-uniform datetime rendering spec for `to_csv`, mirroring pandas.
4058///
4059/// pandas chooses one format for the whole datetime column: a date-only
4060/// `YYYY-MM-DD` when every value falls exactly on midnight, otherwise
4061/// `YYYY-MM-DD HH:MM:SS` with a fractional-seconds suffix whose width is the
4062/// column's finest sub-second resolution (3 = ms, 6 = µs, 9 = ns; 0 = none).
4063#[derive(Clone, Copy)]
4064struct DatetimeCsvFormat {
4065    date_only: bool,
4066    subsec_digits: u8,
4067}
4068
4069/// Scan a Datetime64 column and derive its column-uniform `to_csv` format.
4070fn datetime_csv_format(column: &Column) -> DatetimeCsvFormat {
4071    if let Some(nanos) = column.as_datetime64_slice() {
4072        return datetime_csv_format_from_nanos(nanos.iter().copied());
4073    }
4074
4075    datetime_csv_format_from_nanos(column.values().iter().filter_map(|value| {
4076        let Scalar::Datetime64(nanos) = value else {
4077            return None;
4078        };
4079        Some(*nanos)
4080    }))
4081}
4082
4083fn datetime_csv_format_from_nanos(nanos: impl Iterator<Item = i64>) -> DatetimeCsvFormat {
4084    let mut date_only = true;
4085    let mut subsec_digits = 0u8;
4086    for ns in nanos {
4087        if ns == Timestamp::NAT {
4088            continue;
4089        }
4090        let subsec = (ns.rem_euclid(1_000_000_000)) as u32;
4091        // Any non-midnight time-of-day OR any sub-second component forces the
4092        // full timestamp form for the entire column.
4093        if ns.div_euclid(1_000_000_000).rem_euclid(86_400) != 0 || subsec != 0 {
4094            date_only = false;
4095        }
4096        if subsec != 0 {
4097            let digits = if !subsec.is_multiple_of(1_000) {
4098                9
4099            } else if !subsec.is_multiple_of(1_000_000) {
4100                6
4101            } else {
4102                3
4103            };
4104            subsec_digits = subsec_digits.max(digits);
4105        }
4106    }
4107    DatetimeCsvFormat {
4108        date_only,
4109        subsec_digits,
4110    }
4111}
4112
4113/// Format one datetime (ns since epoch) under a column's `to_csv` spec.
4114fn format_datetime_csv(nanos: i64, fmt: DatetimeCsvFormat) -> String {
4115    // `format_datetime_ns` now CARRIES sub-second precision (trailing-zero
4116    // trimmed, e.g. ".5"); to_csv instead wants a COLUMN-UNIFORM fixed-width
4117    // fraction (e.g. ".500"), so work from the fixed 19-char
4118    // "YYYY-MM-DD HH:MM:SS" stem (year is always 4 digits across the i64-ns
4119    // range) and apply the column's resolution here. (br-frankenpandas-dt64fmt)
4120    let base = format_datetime_ns(nanos);
4121    if fmt.date_only {
4122        return base[..10].to_owned();
4123    }
4124    let stem = &base[..19];
4125    if fmt.subsec_digits == 0 {
4126        return stem.to_owned();
4127    }
4128    let subsec = (nanos.rem_euclid(1_000_000_000)) as u32;
4129    let frac = subsec / 10u32.pow(9 - u32::from(fmt.subsec_digits));
4130    format!(
4131        "{stem}.{frac:0>width$}",
4132        width = usize::from(fmt.subsec_digits)
4133    )
4134}
4135
4136fn scalar_to_csv_with_na(scalar: &Scalar, na_rep: &str) -> String {
4137    match scalar {
4138        Scalar::Null(_) => na_rep.to_owned(),
4139        Scalar::Float64(v) if v.is_nan() => na_rep.to_owned(),
4140        // pandas to_csv renders floats via Python str(float): whole numbers keep
4141        // ".0" ("1.0", not "1") and extreme magnitudes use signed two-digit
4142        // scientific notation. The table writers (latex/markdown/html) use the
4143        // separate scalar_to_table_with_na path and keep their own formatting.
4144        Scalar::Float64(v) => format_pandas_float(*v),
4145        Scalar::Timedelta64(v) if *v == Timedelta::NAT => na_rep.to_owned(),
4146        other => scalar_to_csv(other),
4147    }
4148}
4149
4150/// CSV cell formatter that applies a column's datetime spec when present;
4151/// otherwise identical to `scalar_to_csv_with_na`.
4152fn scalar_to_csv_cell(
4153    scalar: &Scalar,
4154    na_rep: &str,
4155    dt_format: Option<DatetimeCsvFormat>,
4156) -> String {
4157    if let (Scalar::Datetime64(ns), Some(fmt)) = (scalar, dt_format) {
4158        if *ns == Timestamp::NAT {
4159            return na_rep.to_owned();
4160        }
4161        return format_datetime_csv(*ns, fmt);
4162    }
4163    scalar_to_csv_with_na(scalar, na_rep)
4164}
4165
4166fn scalar_to_table_with_na(scalar: &Scalar, na_rep: &str) -> String {
4167    match scalar {
4168        Scalar::Null(_) => na_rep.to_owned(),
4169        Scalar::Float64(v) if v.is_nan() => na_rep.to_owned(),
4170        // pandas to_string / to_markdown / to_html render a TEMPORAL NaT as the
4171        // literal "NaT": na_rep overrides only float NaN, NOT NaT. Verified vs
4172        // pandas 2.2.3 — `df.to_html(na_rep='X')` keeps "NaT" for datetime/
4173        // timedelta but shows "X" for NaN. (Datetime64/Period NaT previously
4174        // fell through to scalar_to_csv -> "" blank cells; an earlier fix wrongly
4175        // routed all temporal NaT to na_rep.) to_latex DIFFERS (collapses NaT to
4176        // na_rep) and is corrected in scalar_to_latex_cell. (br-frankenpandas-tblnat)
4177        Scalar::Timedelta64(v) if *v == Timedelta::NAT => "NaT".to_owned(),
4178        Scalar::Datetime64(v) if *v == Timestamp::NAT => "NaT".to_owned(),
4179        Scalar::Period(p) if p.ordinal == i64::MIN => "NaT".to_owned(),
4180        other => scalar_to_csv(other),
4181    }
4182}
4183
4184/// LaTeX cell formatter. pandas `to_latex` renders floats with its default
4185/// `float_format` of six decimal places (`1.0` -> "1.000000", `0.1234567` ->
4186/// "0.123457"), unlike the str(float) form used by to_csv/to_html. Integers and
4187/// other scalars keep the shared table formatting. Verified vs pandas 2.2.3.
4188fn scalar_to_latex_cell(scalar: &Scalar, na_rep: &str) -> String {
4189    match scalar {
4190        Scalar::Float64(v) if v.is_nan() => na_rep.to_owned(),
4191        // pandas to_latex collapses ALL missing — float NaN AND temporal NaT —
4192        // to na_rep (default "NaN"), unlike to_string/to_html which keep "NaT".
4193        // Verified vs pandas 2.2.3. Override here before delegating, since
4194        // scalar_to_table_with_na now renders temporal NaT as "NaT" for the
4195        // markdown/string family. (br-frankenpandas-tblnat)
4196        Scalar::Timedelta64(v) if *v == Timedelta::NAT => na_rep.to_owned(),
4197        Scalar::Datetime64(v) if *v == Timestamp::NAT => na_rep.to_owned(),
4198        Scalar::Period(p) if p.ordinal == i64::MIN => na_rep.to_owned(),
4199        // Rust `{:.6}` matches Python `%.6f` (round-half-to-even) and renders
4200        // infinities as "inf"/"-inf", exactly as pandas to_latex does.
4201        Scalar::Float64(v) => format!("{v:.6}"),
4202        other => scalar_to_table_with_na(other, na_rep),
4203    }
4204}
4205
4206fn push_markdown_row(out: &mut String, cells: &[String]) {
4207    out.push('|');
4208    for cell in cells {
4209        out.push(' ');
4210        push_escaped_markdown_table_cell(out, cell);
4211        out.push_str(" |");
4212    }
4213    out.push('\n');
4214}
4215
4216fn push_escaped_markdown_table_cell(out: &mut String, value: &str) {
4217    for ch in value.chars() {
4218        match ch {
4219            '\\' => out.push_str("\\\\"),
4220            '|' => out.push_str("\\|"),
4221            '\n' | '\r' => out.push(' '),
4222            _ => out.push(ch),
4223        }
4224    }
4225}
4226
4227fn push_latex_row(out: &mut String, cells: &[String], escape: bool) {
4228    for (idx, cell) in cells.iter().enumerate() {
4229        if idx > 0 {
4230            out.push_str(" & ");
4231        }
4232        if escape {
4233            out.push_str(&escape_latex_table_cell(cell));
4234        } else {
4235            out.push_str(cell);
4236        }
4237    }
4238    out.push_str(" \\\\\n");
4239}
4240
4241fn escape_latex_table_cell(value: &str) -> String {
4242    let mut escaped = String::with_capacity(value.len());
4243    for ch in value.chars() {
4244        match ch {
4245            '&' => escaped.push_str("\\&"),
4246            '%' => escaped.push_str("\\%"),
4247            '$' => escaped.push_str("\\$"),
4248            '#' => escaped.push_str("\\#"),
4249            '_' => escaped.push_str("\\_"),
4250            '{' => escaped.push_str("\\{"),
4251            '}' => escaped.push_str("\\}"),
4252            '~' => escaped.push_str("\\textasciitilde{}"),
4253            '^' => escaped.push_str("\\textasciicircum{}"),
4254            '\\' => escaped.push_str("\\textbackslash{}"),
4255            '\n' | '\r' => escaped.push(' '),
4256            _ => escaped.push(ch),
4257        }
4258    }
4259    escaped
4260}
4261
4262fn is_pandas_default_na(s: &str) -> bool {
4263    // Default NA values recognized by pandas read_csv.
4264    // See: <https://pandas.pydata.org/docs/reference/api/pandas.read_csv.html>
4265    matches!(
4266        s,
4267        "" | "#N/A"
4268            | "#N/A N/A"
4269            | "#NA"
4270            | "-1.#IND"
4271            | "-1.#QNAN"
4272            | "-NaN"
4273            | "-nan"
4274            | "1.#IND"
4275            | "1.#QNAN"
4276            | "<NA>"
4277            | "N/A"
4278            | "NA"
4279            | "NULL"
4280            | "NaN"
4281            | "None"
4282            | "n/a"
4283            | "nan"
4284            | "null"
4285    )
4286}
4287
4288fn parse_scalar(field: &str) -> Scalar {
4289    // pandas read_csv tolerates surrounding whitespace ONLY for numeric
4290    // inference. NA markers and booleans must match the field EXACTLY (a
4291    // padded " NA " or "true " is NOT null/bool), and plain strings keep their
4292    // original whitespace. Verified vs live pandas 2.2.3: " abc " stays
4293    // " abc "; "true " / " NA " stay strings; but " 1 " parses to Int64(1).
4294    if is_pandas_default_na(field) {
4295        return Scalar::Null(NullKind::Null);
4296    }
4297
4298    let trimmed = field.trim();
4299    if let Ok(value) = trimmed.parse::<i64>() {
4300        return Scalar::Int64(value);
4301    }
4302    if let Ok(value) = trimmed.parse::<f64>() {
4303        return Scalar::Float64(value);
4304    }
4305    if field.eq_ignore_ascii_case("true") {
4306        return Scalar::Bool(true);
4307    }
4308    if field.eq_ignore_ascii_case("false") {
4309        return Scalar::Bool(false);
4310    }
4311
4312    Scalar::Utf8(field.to_owned())
4313}
4314
4315/// Format an f64 the way pandas `to_csv` does (Python `str(float)`): keep a
4316/// trailing ".0" on whole numbers ("1.0", not Rust Display's "1"), shortest
4317/// round-trip for decimals, and signed two-digit scientific notation
4318/// ("1e+16" / "1e-05") for very large / small magnitudes. Verified vs live
4319/// pandas 2.2.3. NaN must be handled by the caller (it becomes na_rep).
4320fn format_pandas_float(v: f64) -> String {
4321    let mut out = String::new();
4322    write_pandas_float(&mut out, v);
4323    out
4324}
4325
4326/// Append the pandas `str(float)` rendering of `v` directly to `out`, without
4327/// the per-call `String` allocation `format_pandas_float` makes — the hot path
4328/// for the all-numeric CSV writer (br-frankenpandas-qk2i9).
4329///
4330/// Finite values first try `ryu::Buffer` to bypass Rust's generic formatting
4331/// machinery. Boundary spellings where `ryu` and Python choose different fixed
4332/// vs scientific notation deopt to the Debug-based fallback below.
4333fn write_pandas_float(out: &mut String, v: f64) {
4334    if v.is_finite() {
4335        let mut buffer = ryu::Buffer::new();
4336        let rendered = buffer.format_finite(v);
4337        let has_exponent = rendered.contains('e');
4338        let is_zero = v.to_bits() << 1 == 0;
4339        if has_exponent || is_zero || v.abs() >= 1e-4 {
4340            append_pandas_normalized_float(out, rendered);
4341            return;
4342        }
4343    }
4344
4345    write_pandas_float_debug_fallback(out, v);
4346}
4347
4348fn append_pandas_normalized_float(out: &mut String, rendered: &str) {
4349    let Some(e) = rendered.find('e') else {
4350        out.push_str(rendered);
4351        if !rendered.contains('.') {
4352            out.push_str(".0");
4353        }
4354        return;
4355    };
4356
4357    out.push_str(&rendered[..=e]);
4358    let exp = &rendered[e + 1..];
4359    let (sign, digits) = match exp.strip_prefix('-') {
4360        Some(d) => ('-', d),
4361        None => ('+', exp.strip_prefix('+').unwrap_or(exp)),
4362    };
4363    out.push(sign);
4364    if digits.len() < 2 {
4365        out.push('0');
4366    }
4367    out.push_str(digits);
4368}
4369
4370/// Rust's Debug formatter gives the shortest round-trip representation and,
4371/// unlike Display, keeps ".0" on whole numbers and switches to scientific
4372/// notation at Python's repr boundaries. Only the exponent spelling differs
4373/// (Rust "1e16"/"1e-5" vs Python "1e+16"/"1e-05"), so the rare sci-notation case
4374/// is normalized in place.
4375fn write_pandas_float_debug_fallback(out: &mut String, v: f64) {
4376    use std::fmt::Write as _;
4377    let start = out.len();
4378    let _ = write!(out, "{v:?}");
4379    // Common case (no scientific notation): `{v:?}` is already the pandas form.
4380    let Some(rel_e) = out[start..].find('e') else {
4381        return;
4382    };
4383    // Sci notation: normalize the exponent to Python's signed, >=2-digit form.
4384    let e = start + rel_e;
4385    let exp = out.split_off(e + 1); // everything after 'e'; `out` keeps "<mantissa>e"
4386    let (sign, digits) = match exp.strip_prefix('-') {
4387        Some(d) => ('-', d),
4388        None => ('+', exp.strip_prefix('+').unwrap_or(&exp)),
4389    };
4390    out.push(sign);
4391    if digits.len() < 2 {
4392        out.push('0');
4393    }
4394    out.push_str(digits);
4395}
4396
4397fn scalar_to_csv(scalar: &Scalar) -> String {
4398    match scalar {
4399        Scalar::Null(_) => String::new(),
4400        // pandas to_csv writes capitalized True/False (matches fp-frame::to_csv).
4401        Scalar::Bool(v) => if *v { "True" } else { "False" }.to_string(),
4402        Scalar::Int64(v) => v.to_string(),
4403        Scalar::Float64(v) => {
4404            if v.is_nan() {
4405                String::new()
4406            } else {
4407                v.to_string()
4408            }
4409        }
4410        Scalar::Utf8(v) => v.clone(),
4411        Scalar::Timedelta64(v) => {
4412            if *v == Timedelta::NAT {
4413                String::new()
4414            } else {
4415                Timedelta::format(*v)
4416            }
4417        }
4418        Scalar::Datetime64(v) => {
4419            if *v == Timestamp::NAT {
4420                String::new()
4421            } else {
4422                format_datetime_ns(*v)
4423            }
4424        }
4425        Scalar::Period(p) => {
4426            if p.ordinal == i64::MIN {
4427                String::new()
4428            } else {
4429                p.calendar_string()
4430            }
4431        }
4432        Scalar::Interval(iv) => format!("{iv}"),
4433    }
4434}
4435
4436/// Parse a field with NA value handling respecting pandas options.
4437///
4438/// - `na_filter`: If false, skip NA detection entirely for performance
4439/// - `keep_default_na`: If true, use pandas default NA values
4440/// - `na_set` / `true_set` / `false_set`: Pre-built HashSets for O(1)
4441///   membership lookup. Per br-frankenpandas-b67a3 (sister to br-fcf5d),
4442///   these were previously `&[String]` slices scanned linearly per cell;
4443///   now built once at the parent CSV reader and passed in.
4444#[allow(clippy::too_many_arguments)]
4445fn parse_scalar_with_options(
4446    field: &str,
4447    na_filter: bool,
4448    keep_default_na: bool,
4449    na_set: &HashSet<&str>,
4450    true_set: &HashSet<&str>,
4451    false_set: &HashSet<&str>,
4452    decimal: u8,
4453    thousands: Option<u8>,
4454) -> Scalar {
4455    // pandas only tolerates surrounding whitespace for NUMERIC inference; NA
4456    // markers, booleans, and plain strings match/keep the field EXACTLY (a
4457    // padded " NA " or "true " stays a string). See parse_scalar.
4458    let trimmed = field.trim();
4459
4460    // Check NA values only if na_filter is enabled
4461    if na_filter {
4462        let is_default_na = keep_default_na && is_pandas_default_na(field);
4463        let is_custom_na = na_set.contains(field);
4464        if is_default_na || is_custom_na {
4465            return Scalar::Null(NullKind::Null);
4466        }
4467    }
4468
4469    // `thousands` is silently ignored if it equals the decimal separator,
4470    // matching pandas semantics.
4471    let thousands_effective = thousands.filter(|t| *t != decimal);
4472    let numeric_candidate: Cow<'_, str> = if let Some(t) = thousands_effective {
4473        let ch = char::from(t);
4474        if trimmed.contains(ch) {
4475            Cow::Owned(trimmed.replace(ch, ""))
4476        } else {
4477            Cow::Borrowed(trimmed)
4478        }
4479    } else {
4480        Cow::Borrowed(trimmed)
4481    };
4482
4483    if let Ok(value) = numeric_candidate.as_ref().parse::<i64>() {
4484        return Scalar::Int64(value);
4485    }
4486
4487    let decimal_ch = char::from(decimal);
4488    let float_candidate: Cow<'_, str> = if decimal == b'.' {
4489        Cow::Borrowed(numeric_candidate.as_ref())
4490    } else if numeric_candidate.contains(decimal_ch) {
4491        Cow::Owned(numeric_candidate.replace(decimal_ch, "."))
4492    } else {
4493        Cow::Borrowed(numeric_candidate.as_ref())
4494    };
4495    if let Ok(value) = float_candidate.as_ref().parse::<f64>() {
4496        return Scalar::Float64(value);
4497    }
4498
4499    if true_set.contains(field) {
4500        return Scalar::Bool(true);
4501    }
4502    if false_set.contains(field) {
4503        return Scalar::Bool(false);
4504    }
4505
4506    if field.eq_ignore_ascii_case("true") {
4507        return Scalar::Bool(true);
4508    }
4509    if field.eq_ignore_ascii_case("false") {
4510        return Scalar::Bool(false);
4511    }
4512    Scalar::Utf8(field.to_owned())
4513}
4514
4515fn reject_duplicate_headers(headers: &[String]) -> Result<(), IoError> {
4516    let mut used = BTreeSet::new();
4517    for name in headers {
4518        if !used.insert(name.clone()) {
4519            return Err(IoError::DuplicateColumnName(name.clone()));
4520        }
4521    }
4522    Ok(())
4523}
4524
4525fn validate_usecols(headers: &[String], usecols: &[String]) -> Result<(), IoError> {
4526    let header_set: std::collections::BTreeSet<&String> = headers.iter().collect();
4527    let mut missing = Vec::new();
4528    for name in usecols {
4529        if !header_set.contains(name) {
4530            missing.push(name.clone());
4531        }
4532    }
4533    if missing.is_empty() {
4534        Ok(())
4535    } else {
4536        Err(IoError::MissingUsecols(missing))
4537    }
4538}
4539
4540fn validate_parse_dates(headers: &[String], parse_dates: &[String]) -> Result<(), IoError> {
4541    let header_set: std::collections::BTreeSet<&String> = headers.iter().collect();
4542    let mut missing = Vec::new();
4543    for name in parse_dates {
4544        if !header_set.contains(name) {
4545            missing.push(name.clone());
4546        }
4547    }
4548    if missing.is_empty() {
4549        Ok(())
4550    } else {
4551        Err(IoError::MissingParseDateColumns(missing))
4552    }
4553}
4554
4555fn validate_parse_date_combinations(
4556    headers: &[String],
4557    parse_date_combinations: &[Vec<String>],
4558) -> Result<(), IoError> {
4559    let header_set: std::collections::BTreeSet<&String> = headers.iter().collect();
4560    let mut missing = BTreeSet::new();
4561    for combo in parse_date_combinations {
4562        for name in combo {
4563            if !header_set.contains(name) {
4564                missing.insert(name.clone());
4565            }
4566        }
4567    }
4568    if missing.is_empty() {
4569        Ok(())
4570    } else {
4571        Err(IoError::MissingParseDateColumns(
4572            missing.into_iter().collect(),
4573        ))
4574    }
4575}
4576
4577fn apply_parse_dates_to_scalar_columns(
4578    headers: &[String],
4579    columns: &mut [Vec<Scalar>],
4580    parse_dates: &[String],
4581) -> Result<(), IoError> {
4582    if parse_dates.is_empty() {
4583        return Ok(());
4584    }
4585
4586    validate_parse_dates(headers, parse_dates)?;
4587
4588    for column_name in parse_dates {
4589        let Some(column_idx) = headers.iter().position(|header| header == column_name) else {
4590            continue;
4591        };
4592
4593        if let Some(parsed) = parse_csv_datetime_values(&columns[column_idx])? {
4594            columns[column_idx] = parsed;
4595        }
4596    }
4597
4598    Ok(())
4599}
4600
4601#[allow(clippy::too_many_arguments)]
4602fn apply_csv_parse_dates(
4603    headers: &[String],
4604    columns: &mut [Vec<Scalar>],
4605    raw_columns: &[Vec<String>],
4606    deferred_parse_date_columns: &[bool],
4607    parse_dates: &[String],
4608    options: &CsvReadOptions,
4609    na_set: &HashSet<&str>,
4610    true_set: &HashSet<&str>,
4611    false_set: &HashSet<&str>,
4612) -> Result<(), IoError> {
4613    if parse_dates.is_empty() {
4614        return Ok(());
4615    }
4616
4617    validate_parse_dates(headers, parse_dates)?;
4618
4619    for column_name in parse_dates {
4620        let Some(column_idx) = headers.iter().position(|header| header == column_name) else {
4621            continue;
4622        };
4623
4624        let parsed = if deferred_parse_date_columns
4625            .get(column_idx)
4626            .copied()
4627            .unwrap_or(false)
4628        {
4629            if let Some(parsed) = parse_csv_fixed_naive_datetime_fields(
4630                &raw_columns[column_idx],
4631                options.na_filter,
4632                options.keep_default_na,
4633                na_set,
4634            ) {
4635                Some(parsed)
4636            } else {
4637                columns[column_idx] = parse_csv_scalar_fields_with_options(
4638                    &raw_columns[column_idx],
4639                    options,
4640                    na_set,
4641                    true_set,
4642                    false_set,
4643                );
4644                parse_csv_datetime_values(&columns[column_idx])?
4645            }
4646        } else {
4647            parse_csv_datetime_values(&columns[column_idx])?
4648        };
4649
4650        if let Some(parsed) = parsed {
4651            columns[column_idx] = parsed;
4652        }
4653    }
4654
4655    Ok(())
4656}
4657
4658fn deferred_parse_date_column_mask(headers: &[String], options: &CsvReadOptions) -> Vec<bool> {
4659    let Some(parse_dates) = options.parse_dates.as_deref() else {
4660        return vec![false; headers.len()];
4661    };
4662    if parse_dates.is_empty()
4663        || options.parse_date_combinations.is_some()
4664        || options.parse_date_combinations_named.is_some()
4665    {
4666        return vec![false; headers.len()];
4667    }
4668
4669    headers
4670        .iter()
4671        .map(|header| parse_dates.iter().any(|name| name == header))
4672        .collect()
4673}
4674
4675fn parse_csv_fixed_naive_datetime_fields(
4676    fields: &[String],
4677    na_filter: bool,
4678    keep_default_na: bool,
4679    na_set: &HashSet<&str>,
4680) -> Option<Vec<Scalar>> {
4681    let mut parsed = Vec::with_capacity(fields.len());
4682    let mut saw_datetime = false;
4683
4684    for field in fields {
4685        if na_filter
4686            && ((keep_default_na && is_pandas_default_na(field)) || na_set.contains(field.as_str()))
4687        {
4688            parsed.push(Scalar::Datetime64(Timestamp::NAT));
4689            continue;
4690        }
4691
4692        parsed.push(Scalar::Datetime64(parse_fixed_naive_csv_datetime_nanos(
4693            field,
4694        )?));
4695        saw_datetime = true;
4696    }
4697
4698    saw_datetime.then_some(parsed)
4699}
4700
4701fn parse_csv_scalar_fields_with_options(
4702    fields: &[String],
4703    options: &CsvReadOptions,
4704    na_set: &HashSet<&str>,
4705    true_set: &HashSet<&str>,
4706    false_set: &HashSet<&str>,
4707) -> Vec<Scalar> {
4708    fields
4709        .iter()
4710        .map(|field| {
4711            parse_scalar_with_options(
4712                field,
4713                options.na_filter,
4714                options.keep_default_na,
4715                na_set,
4716                true_set,
4717                false_set,
4718                options.decimal,
4719                options.thousands,
4720            )
4721        })
4722        .collect()
4723}
4724
4725fn parse_sql_float_text(text: &str) -> Option<f64> {
4726    let trimmed = text.trim();
4727    if trimmed.is_empty() {
4728        return None;
4729    }
4730
4731    let mut normalized = String::with_capacity(trimmed.len());
4732    for ch in trimmed.chars() {
4733        match ch {
4734            ',' => {}
4735            '$' if normalized.is_empty() || normalized == "+" || normalized == "-" => {}
4736            _ => normalized.push(ch),
4737        }
4738    }
4739
4740    if matches!(normalized.as_str(), "" | "+" | "-" | ".") {
4741        return None;
4742    }
4743
4744    let value = normalized.parse::<f64>().ok()?;
4745    value.is_finite().then_some(value)
4746}
4747
4748fn apply_sql_coerce_float(columns: &mut [Vec<Scalar>]) {
4749    for column in columns {
4750        let mut saw_text_float = false;
4751        let mut parsed_values = Vec::with_capacity(column.len());
4752
4753        for value in column.iter() {
4754            match value {
4755                Scalar::Utf8(text) => {
4756                    let Some(parsed) = parse_sql_float_text(text) else {
4757                        saw_text_float = false;
4758                        parsed_values.clear();
4759                        break;
4760                    };
4761                    saw_text_float = true;
4762                    parsed_values.push(Some(parsed));
4763                }
4764                Scalar::Null(_) | Scalar::Int64(_) | Scalar::Float64(_) => {
4765                    parsed_values.push(None);
4766                }
4767                Scalar::Bool(_)
4768                | Scalar::Timedelta64(_)
4769                | Scalar::Datetime64(_)
4770                | Scalar::Period(_)
4771                | Scalar::Interval(_) => {
4772                    saw_text_float = false;
4773                    parsed_values.clear();
4774                    break;
4775                }
4776            }
4777        }
4778
4779        if !saw_text_float {
4780            continue;
4781        }
4782
4783        for (value, parsed) in column.iter_mut().zip(parsed_values) {
4784            if let Some(parsed) = parsed {
4785                *value = Scalar::Float64(parsed);
4786            } else if value.is_missing() {
4787                *value = Scalar::Null(NullKind::NaN);
4788            }
4789        }
4790    }
4791}
4792
4793fn combine_parse_date_values(column_group: &[Vec<Scalar>]) -> Vec<Scalar> {
4794    let len = column_group.first().map_or(0, Vec::len);
4795    let mut combined = Vec::with_capacity(len);
4796
4797    for row in 0..len {
4798        if column_group
4799            .iter()
4800            .any(|column| matches!(column[row], Scalar::Null(_)))
4801        {
4802            combined.push(Scalar::Null(NullKind::NaT));
4803            continue;
4804        }
4805
4806        let joined = column_group
4807            .iter()
4808            .map(|column| match &column[row] {
4809                Scalar::Utf8(value) => value.clone(),
4810                other => other.to_string(),
4811            })
4812            .collect::<Vec<_>>()
4813            .join(" ");
4814        combined.push(Scalar::Utf8(joined));
4815    }
4816
4817    combined
4818}
4819
4820fn apply_one_parse_date_combination(
4821    headers: &mut Vec<String>,
4822    columns: &mut Vec<Vec<Scalar>>,
4823    combined_name: String,
4824    sources: &[String],
4825) -> Result<(), IoError> {
4826    let mut positions = sources
4827        .iter()
4828        .map(|name| {
4829            headers
4830                .iter()
4831                .position(|header| header == name)
4832                .ok_or_else(|| IoError::MissingParseDateColumns(vec![name.clone()]))
4833        })
4834        .collect::<Result<Vec<_>, _>>()?;
4835    positions.sort_unstable();
4836
4837    let combined_values = combine_parse_date_values(
4838        &positions
4839            .iter()
4840            .map(|&idx| columns[idx].clone())
4841            .collect::<Vec<_>>(),
4842    );
4843    let parsed_values = match parse_csv_datetime_values(&combined_values)? {
4844        Some(parsed) => parsed,
4845        None => combined_values,
4846    };
4847
4848    for idx in positions.iter().rev() {
4849        headers.remove(*idx);
4850        columns.remove(*idx);
4851    }
4852    headers.insert(positions[0], combined_name);
4853    columns.insert(positions[0], parsed_values);
4854    Ok(())
4855}
4856
4857fn parse_csv_datetime_values(values: &[Scalar]) -> Result<Option<Vec<Scalar>>, IoError> {
4858    if let Some(parsed) = parse_csv_fixed_naive_datetime_values(values) {
4859        return Ok(Some(parsed));
4860    }
4861
4862    // pandas pd.read_csv(parse_dates=[col]) parses each value on its own —
4863    // a column with mixed naive ("2024-01-15 10:30:00") and aware
4864    // ("2024-01-15T10:30:00Z") entries normalizes each value
4865    // independently. The ToDatetimeOptions default `infer_mixed_timezone:
4866    // true` locks the column to the FIRST inferred pattern and rejects
4867    // any value that doesn't match it, which causes parse_failed=true and
4868    // leaves the column as raw strings even though every individual value
4869    // is parseable. Set it explicitly to false so each value goes through
4870    // parse_datetime_string, which already handles both naive and aware.
4871    let parsed = to_datetime_values_with_options(
4872        values,
4873        ToDatetimeOptions {
4874            infer_mixed_timezone: false,
4875            // pandas keeps a mixed naive+tz-aware parse_dates column as object
4876            // rather than datetime64 (br-frankenpandas-unz0t).
4877            mixed_tz_as_object: true,
4878            ..ToDatetimeOptions::default()
4879        },
4880    )?;
4881    let parse_failed = values
4882        .iter()
4883        .zip(parsed.iter())
4884        .any(|(original, parsed)| !original.is_missing() && parsed.is_missing());
4885
4886    if parse_failed {
4887        Ok(None)
4888    } else {
4889        Ok(Some(parsed))
4890    }
4891}
4892
4893fn parse_csv_fixed_naive_datetime_values(values: &[Scalar]) -> Option<Vec<Scalar>> {
4894    let mut parsed = Vec::with_capacity(values.len());
4895    let mut saw_datetime = false;
4896
4897    for value in values {
4898        match value {
4899            Scalar::Utf8(text) => {
4900                parsed.push(Scalar::Datetime64(parse_fixed_naive_csv_datetime_nanos(
4901                    text,
4902                )?));
4903                saw_datetime = true;
4904            }
4905            Scalar::Null(_) => parsed.push(Scalar::Datetime64(Timestamp::NAT)),
4906            _ => return None,
4907        }
4908    }
4909
4910    saw_datetime.then_some(parsed)
4911}
4912
4913fn parse_fixed_naive_csv_datetime_nanos(value: &str) -> Option<i64> {
4914    let bytes = value.trim().as_bytes();
4915    let (year, month, day, hour, minute, second) = match bytes.len() {
4916        10 => (
4917            parse_4_digits(bytes, 0)?,
4918            parse_2_digits(bytes, 5)?,
4919            parse_2_digits(bytes, 8)?,
4920            0,
4921            0,
4922            0,
4923        ),
4924        19 => (
4925            parse_4_digits(bytes, 0)?,
4926            parse_2_digits(bytes, 5)?,
4927            parse_2_digits(bytes, 8)?,
4928            parse_2_digits(bytes, 11)?,
4929            parse_2_digits(bytes, 14)?,
4930            parse_2_digits(bytes, 17)?,
4931        ),
4932        _ => return None,
4933    };
4934
4935    if bytes.get(4) != Some(&b'-')
4936        || bytes.get(7) != Some(&b'-')
4937        || (bytes.len() == 19
4938            && (bytes.get(10) != Some(&b' ')
4939                || bytes.get(13) != Some(&b':')
4940                || bytes.get(16) != Some(&b':')))
4941        || !valid_ymd(year, month, day)
4942        || hour > 23
4943        || minute > 59
4944        || second > 59
4945    {
4946        return None;
4947    }
4948
4949    let days = days_from_ymd(year, month, day);
4950    days.checked_mul(Timedelta::NANOS_PER_DAY)?
4951        .checked_add(hour.checked_mul(Timedelta::NANOS_PER_HOUR)?)?
4952        .checked_add(minute.checked_mul(Timedelta::NANOS_PER_MIN)?)?
4953        .checked_add(second.checked_mul(Timedelta::NANOS_PER_SEC)?)
4954}
4955
4956fn parse_2_digits(bytes: &[u8], offset: usize) -> Option<i64> {
4957    let hi = *bytes.get(offset)?;
4958    let lo = *bytes.get(offset + 1)?;
4959    if !hi.is_ascii_digit() || !lo.is_ascii_digit() {
4960        return None;
4961    }
4962    Some((i64::from(hi - b'0') * 10) + i64::from(lo - b'0'))
4963}
4964
4965fn parse_4_digits(bytes: &[u8], offset: usize) -> Option<i64> {
4966    let hi = parse_2_digits(bytes, offset)?;
4967    let lo = parse_2_digits(bytes, offset + 2)?;
4968    Some((hi * 100) + lo)
4969}
4970
4971fn valid_ymd(year: i64, month: i64, day: i64) -> bool {
4972    if !(1..=9999).contains(&year) || !(1..=12).contains(&month) {
4973        return false;
4974    }
4975    let max_day = match month {
4976        1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
4977        4 | 6 | 9 | 11 => 30,
4978        2 if is_leap_year(year) => 29,
4979        2 => 28,
4980        _ => return false,
4981    };
4982    (1..=max_day).contains(&day)
4983}
4984
4985fn is_leap_year(year: i64) -> bool {
4986    (year % 4 == 0 && year % 100 != 0) || year % 400 == 0
4987}
4988
4989fn days_from_ymd(year: i64, month: i64, day: i64) -> i64 {
4990    let y = if month <= 2 { year - 1 } else { year };
4991    let era = if y >= 0 { y } else { y - 399 } / 400;
4992    let yoe = y - (era * 400);
4993    let doy = (153 * (if month > 2 { month - 3 } else { month + 9 }) + 2) / 5 + day - 1;
4994    let doe = (yoe * 365) + (yoe / 4) - (yoe / 100) + doy;
4995    (era * 146_097) + doe - 719_468
4996}
4997
4998fn pandas_csv_numeric_column_requires_float(values: &[Scalar]) -> bool {
4999    // A CSV field has no declared nullable-extension dtype. Match pandas' numpy
5000    // inference instead: an integer column widens when it contains either a
5001    // fractional value or a missing value, because numpy int64 cannot hold NA.
5002    let mut saw_int = false;
5003    let mut saw_float = false;
5004    let mut saw_null = false;
5005
5006    for value in values {
5007        match value {
5008            Scalar::Int64(_) => saw_int = true,
5009            Scalar::Float64(_) => saw_float = true,
5010            Scalar::Null(_) => saw_null = true,
5011            Scalar::Bool(_)
5012            | Scalar::Utf8(_)
5013            | Scalar::Timedelta64(_)
5014            | Scalar::Datetime64(_)
5015            | Scalar::Period(_)
5016            | Scalar::Interval(_) => {
5017                return false;
5018            }
5019        }
5020    }
5021
5022    saw_int && (saw_float || saw_null)
5023}
5024
5025fn apply_pandas_csv_numeric_promotions(columns: &mut [Vec<Scalar>]) {
5026    for column in columns {
5027        if !pandas_csv_numeric_column_requires_float(column) {
5028            continue;
5029        }
5030
5031        for value in column {
5032            if let Scalar::Int64(v) = value {
5033                *value = Scalar::Float64(*v as f64);
5034            }
5035        }
5036    }
5037}
5038
5039fn apply_parse_date_combinations(
5040    headers: &mut Vec<String>,
5041    columns: &mut Vec<Vec<Scalar>>,
5042    parse_date_combinations: &[Vec<String>],
5043) -> Result<(), IoError> {
5044    if parse_date_combinations.is_empty() {
5045        return Ok(());
5046    }
5047
5048    validate_parse_date_combinations(headers, parse_date_combinations)?;
5049
5050    for combination in parse_date_combinations {
5051        if combination.is_empty() {
5052            continue;
5053        }
5054        let combined_name = combination.join("_");
5055        apply_one_parse_date_combination(headers, columns, combined_name, combination)?;
5056    }
5057
5058    Ok(())
5059}
5060
5061fn apply_parse_date_combinations_named(
5062    headers: &mut Vec<String>,
5063    columns: &mut Vec<Vec<Scalar>>,
5064    parse_date_combinations_named: &[(String, Vec<String>)],
5065) -> Result<(), IoError> {
5066    if parse_date_combinations_named.is_empty() {
5067        return Ok(());
5068    }
5069
5070    let mut assigned_names: std::collections::HashSet<String> = std::collections::HashSet::new();
5071    for (new_name, _) in parse_date_combinations_named {
5072        if !assigned_names.insert(new_name.clone()) {
5073            return Err(IoError::DuplicateColumnName(new_name.clone()));
5074        }
5075    }
5076
5077    let combos_only: Vec<Vec<String>> = parse_date_combinations_named
5078        .iter()
5079        .map(|(_, sources)| sources.clone())
5080        .collect();
5081    validate_parse_date_combinations(headers, &combos_only)?;
5082
5083    for (new_name, sources) in parse_date_combinations_named {
5084        if sources.is_empty() {
5085            continue;
5086        }
5087        apply_one_parse_date_combination(headers, columns, new_name.clone(), sources)?;
5088    }
5089
5090    Ok(())
5091}
5092
5093#[allow(clippy::too_many_arguments)]
5094fn append_csv_record(
5095    columns: &mut [Vec<Scalar>],
5096    raw_columns: &mut [Vec<String>],
5097    record: &StringRecord,
5098    options: &CsvReadOptions,
5099    na_set: &HashSet<&str>,
5100    true_set: &HashSet<&str>,
5101    false_set: &HashSet<&str>,
5102    deferred_parse_date_columns: &[bool],
5103) {
5104    for (idx, col) in columns.iter_mut().enumerate() {
5105        let field = record.get(idx).unwrap_or_default();
5106        if deferred_parse_date_columns
5107            .get(idx)
5108            .copied()
5109            .unwrap_or(false)
5110        {
5111            col.push(Scalar::Null(NullKind::Null));
5112        } else {
5113            col.push(parse_scalar_with_options(
5114                field,
5115                options.na_filter,
5116                options.keep_default_na,
5117                na_set,
5118                true_set,
5119                false_set,
5120                options.decimal,
5121                options.thousands,
5122            ));
5123        }
5124        // Keep the verbatim field so an object-fallback column can preserve the
5125        // original literal like pandas (see build_csv_object_aware_column).
5126        raw_columns[idx].push(field.to_owned());
5127    }
5128}
5129
5130/// True when the input ends while still inside a quoted field.
5131///
5132/// A quote only OPENS a field at a field boundary — start of input, or directly
5133/// after a delimiter or a line break — which is how the csv crate reads it too;
5134/// a quote in the middle of an unquoted field (`ab"cd`) is a literal and must
5135/// not be treated as an opener, or well-formed input would be rejected. Inside a
5136/// quoted field, a doubled quote (`""`) is an escaped literal and does not
5137/// close, and an explicit `escape` byte consumes the character after it.
5138fn csv_input_has_unterminated_quote(
5139    input: &str,
5140    delimiter: u8,
5141    quote: u8,
5142    doublequote: bool,
5143    escape: Option<u8>,
5144) -> bool {
5145    let bytes = input.as_bytes();
5146    let mut in_quotes = false;
5147    let mut at_field_start = true;
5148    let mut idx = 0;
5149
5150    while idx < bytes.len() {
5151        let byte = bytes[idx];
5152        if in_quotes {
5153            if escape == Some(byte) {
5154                idx += 2;
5155                continue;
5156            }
5157            if byte == quote {
5158                if doublequote && bytes.get(idx + 1) == Some(&quote) {
5159                    idx += 2;
5160                    continue;
5161                }
5162                in_quotes = false;
5163                at_field_start = false;
5164            }
5165        } else if byte == quote && at_field_start {
5166            in_quotes = true;
5167            at_field_start = false;
5168        } else {
5169            at_field_start = byte == b'\n' || byte == b'\r' || byte == delimiter;
5170        }
5171        idx += 1;
5172    }
5173
5174    in_quotes
5175}
5176
5177/// Reject a row with MORE fields than the header, the only ragged direction
5178/// pandas treats as an error.
5179///
5180/// Short rows are padded by `append_csv_record`'s `record.get(idx)
5181/// .unwrap_or_default()` and must reach it, so every CSV reader here runs the
5182/// csv crate in `flexible(true)` mode and enforces the overlong case itself.
5183/// `line` is 1-based over the whole file, matching pandas' message.
5184fn reject_overlong_csv_record(found: usize, expected: usize, line: usize) -> Result<(), IoError> {
5185    if found > expected {
5186        return Err(IoError::CsvFieldCount {
5187            line,
5188            expected,
5189            found,
5190        });
5191    }
5192    Ok(())
5193}
5194
5195/// Return whether every data record has exactly one more field than the header.
5196///
5197/// pandas interprets this precise shape as an implicit first index column. The
5198/// decision cannot be made record-by-record: accepting one long row would hide
5199/// a later width mismatch that pandas rejects.
5200fn csv_body_has_uniform_one_extra_field(input: &str, header_count: usize) -> Result<bool, IoError> {
5201    let mut reader = ReaderBuilder::new()
5202        .has_headers(true)
5203        .flexible(true)
5204        .from_reader(input.as_bytes());
5205    let _ = reader.headers().map_err(IoError::from)?;
5206
5207    let mut saw_data_row = false;
5208    for row in reader.records() {
5209        if row?.len() != header_count + 1 {
5210            return Ok(false);
5211        }
5212        saw_data_row = true;
5213    }
5214    Ok(saw_data_row)
5215}
5216
5217fn csv_index_label_from_scalar(value: Scalar) -> IndexLabel {
5218    match value {
5219        Scalar::Int64(v) => IndexLabel::Int64(v),
5220        Scalar::Utf8(v) => IndexLabel::Utf8(v),
5221        Scalar::Float64(v) => IndexLabel::Utf8(v.to_string()),
5222        Scalar::Bool(v) => IndexLabel::Utf8(if v { "True" } else { "False" }.to_owned()),
5223        Scalar::Null(kind) => IndexLabel::Null(kind),
5224        Scalar::Timedelta64(v) => {
5225            if v == Timedelta::NAT {
5226                IndexLabel::Utf8("<NaT>".to_owned())
5227            } else {
5228                IndexLabel::Utf8(Timedelta::format(v))
5229            }
5230        }
5231        Scalar::Datetime64(v) => {
5232            if v == Timestamp::NAT {
5233                IndexLabel::Utf8("<NaT>".to_owned())
5234            } else {
5235                IndexLabel::Utf8(format_datetime_ns(v))
5236            }
5237        }
5238        Scalar::Period(v) => {
5239            if v.ordinal == i64::MIN {
5240                IndexLabel::Utf8("<NaT>".to_owned())
5241            } else {
5242                IndexLabel::Utf8(v.calendar_string())
5243            }
5244        }
5245        Scalar::Interval(iv) => IndexLabel::Utf8(format!("{iv}")),
5246    }
5247}
5248
5249fn should_skip_bad_csv_record(
5250    record: &StringRecord,
5251    expected_fields: usize,
5252    on_bad_lines: CsvOnBadLines,
5253) -> bool {
5254    if record.len() <= expected_fields {
5255        return false;
5256    }
5257
5258    match on_bad_lines {
5259        CsvOnBadLines::Error => false,
5260        CsvOnBadLines::Warn => {
5261            eprintln!(
5262                "Skipping bad CSV line: expected {expected_fields} fields, found {}",
5263                record.len()
5264            );
5265            true
5266        }
5267        CsvOnBadLines::Skip => true,
5268    }
5269}
5270
5271// ── CSV with options ───────────────────────────────────────────────────
5272
5273/// Strip ASCII spaces (0x20) at each unquoted field start for `skipinitialspace`
5274/// (br-frankenpandas-i4h5g). A field starts at line start and immediately after a
5275/// delimiter; spaces there are dropped until the first non-space byte. Quote
5276/// state is tracked so spaces inside quoted fields (and delimiters/terminators
5277/// inside quotes) are preserved, and a `   "x,y"` field becomes the quoted value.
5278/// `doublequote` (a doubled quotechar = literal quote, stay in quote) and
5279/// `escapechar` (next byte is literal) are honored. Only ASCII 0x20 is stripped
5280/// (tabs are kept, matching pandas); trailing spaces are preserved. Every byte
5281/// other than the stripped leading spaces is copied verbatim, so the output is
5282/// valid UTF-8 and the downstream parse is byte-identical except for the removed
5283/// leading spaces.
5284fn apply_skipinitialspace(
5285    input: &str,
5286    delimiter: u8,
5287    quotechar: u8,
5288    doublequote: bool,
5289    escapechar: Option<u8>,
5290    lineterminator: Option<u8>,
5291) -> String {
5292    let bytes = input.as_bytes();
5293    let mut out: Vec<u8> = Vec::with_capacity(bytes.len());
5294    let is_terminator = |b: u8| match lineterminator {
5295        Some(t) => b == t,
5296        None => b == b'\n' || b == b'\r',
5297    };
5298    let mut in_quote = false;
5299    let mut at_field_start = true;
5300    let mut i = 0;
5301    while i < bytes.len() {
5302        let b = bytes[i];
5303        if in_quote {
5304            out.push(b);
5305            if let Some(esc) = escapechar
5306                && b == esc
5307                && i + 1 < bytes.len()
5308            {
5309                out.push(bytes[i + 1]);
5310                i += 2;
5311                continue;
5312            }
5313            if b == quotechar {
5314                if doublequote && i + 1 < bytes.len() && bytes[i + 1] == quotechar {
5315                    out.push(quotechar);
5316                    i += 2;
5317                    continue;
5318                }
5319                in_quote = false;
5320            }
5321            i += 1;
5322            continue;
5323        }
5324        if at_field_start && b == b' ' {
5325            i += 1;
5326            continue;
5327        }
5328        out.push(b);
5329        if at_field_start && b == quotechar {
5330            in_quote = true;
5331            at_field_start = false;
5332        } else {
5333            at_field_start = b == delimiter || is_terminator(b);
5334        }
5335        i += 1;
5336    }
5337    String::from_utf8(out).unwrap_or_else(|_| input.to_string())
5338}
5339
5340pub fn read_csv_with_options(input: &str, options: &CsvReadOptions) -> Result<DataFrame, IoError> {
5341    // br-frankenpandas-i4h5g: pandas `skipinitialspace` strips leading ASCII
5342    // spaces at each field start BEFORE quote handling, so it cannot be expressed
5343    // as a post-parse field trim. Rewrite the raw input once (quote/escape-aware)
5344    // and re-enter with the flag cleared, so the existing fast paths still apply
5345    // to the stripped text.
5346    if options.skipinitialspace {
5347        let processed = apply_skipinitialspace(
5348            input,
5349            options.delimiter,
5350            options.quotechar,
5351            options.doublequote,
5352            options.escapechar,
5353            options.lineterminator,
5354        );
5355        let mut opts = options.clone();
5356        opts.skipinitialspace = false;
5357        return read_csv_with_options(&processed, &opts);
5358    }
5359    if csv_read_options_match_default_fast_path(options) {
5360        return read_csv_str(input);
5361    }
5362
5363    if csv_read_options_match_no_na_numeric_fast_path(options) {
5364        if let Some(frame) = csv_parse_cache_lookup(CsvParseCacheMode::NoNaNumeric, input) {
5365            return Ok(frame);
5366        }
5367
5368        if let Some(frame) = try_read_csv_with_options_no_na_numeric_fast_path(input)? {
5369            csv_parse_cache_store(CsvParseCacheMode::NoNaNumeric, input, &frame);
5370            return Ok(frame);
5371        }
5372    }
5373
5374    if csv_input_has_unterminated_quote(
5375        input,
5376        options.delimiter,
5377        options.quotechar,
5378        options.doublequote,
5379        options.escapechar,
5380    ) {
5381        return Err(IoError::CsvUnterminatedQuote);
5382    }
5383
5384    let mut builder = ReaderBuilder::new();
5385    builder
5386        .has_headers(false)
5387        .delimiter(options.delimiter)
5388        .quote(options.quotechar)
5389        .double_quote(options.doublequote)
5390        .escape(options.escapechar);
5391    // Always flexible: a SHORT row is pandas-legal under every `on_bad_lines`
5392    // setting and is padded by `append_csv_record`. Only the overlong direction
5393    // is a "bad line", and it is enforced below rather than by the csv crate,
5394    // whose UnequalLengths fires in both directions (gtkz1).
5395    builder.flexible(true);
5396    if let Some(c) = options.comment {
5397        builder.comment(Some(c));
5398    }
5399    if let Some(term) = options.lineterminator {
5400        builder.terminator(csv::Terminator::Any(term));
5401    }
5402    let mut reader = builder.from_reader(input.as_bytes());
5403
5404    let max_rows = options.nrows.unwrap_or(usize::MAX);
5405    let skip = options.skiprows;
5406
5407    let mut records = reader.records();
5408    for _ in 0..skip {
5409        if records.next().transpose()?.is_none() {
5410            return Err(IoError::MissingHeaders);
5411        }
5412    }
5413
5414    // Per br-frankenpandas-b67a3: pre-build NA / true / false sets once,
5415    // then thread through the per-record loop. Was Vec::iter().any()
5416    // per cell.
5417    let na_set: HashSet<&str> = options.na_values.iter().map(String::as_str).collect();
5418    let true_set: HashSet<&str> = options.true_values.iter().map(String::as_str).collect();
5419    let false_set: HashSet<&str> = options.false_values.iter().map(String::as_str).collect();
5420
5421    let mut row_count: i64 = 0;
5422    // raw_columns shadows columns with each cell's verbatim text so an
5423    // object-fallback column can preserve original literals (see the final
5424    // build step and build_csv_object_aware_column).
5425    let (headers, mut columns, mut raw_columns, deferred_parse_date_columns) =
5426        if options.has_headers {
5427            let headers_record = records.next().transpose()?.ok_or(IoError::MissingHeaders)?;
5428            if headers_record.is_empty() {
5429                return Err(IoError::MissingHeaders);
5430            }
5431
5432            let header_count = headers_record.len();
5433            let row_hint = input.len() / (header_count * 8).max(1);
5434            let headers = headers_record
5435                .iter()
5436                .map(ToOwned::to_owned)
5437                .collect::<Vec<_>>();
5438            let columns: Vec<Vec<Scalar>> = (0..header_count)
5439                .map(|_| Vec::with_capacity(row_hint))
5440                .collect();
5441            let raw_columns: Vec<Vec<String>> = (0..header_count)
5442                .map(|_| Vec::with_capacity(row_hint))
5443                .collect();
5444            let deferred_parse_date_columns = deferred_parse_date_column_mask(&headers, options);
5445
5446            (headers, columns, raw_columns, deferred_parse_date_columns)
5447        } else {
5448            let first_record = records.next().transpose()?.ok_or(IoError::MissingHeaders)?;
5449            if first_record.is_empty() {
5450                return Err(IoError::MissingHeaders);
5451            }
5452
5453            let header_count = first_record.len();
5454            let row_hint = input.len() / (header_count * 8).max(1);
5455            let headers = (0..header_count)
5456                .map(|idx| format!("column_{idx}"))
5457                .collect::<Vec<_>>();
5458            let mut columns: Vec<Vec<Scalar>> = (0..header_count)
5459                .map(|_| Vec::with_capacity(row_hint))
5460                .collect();
5461            let mut raw_columns: Vec<Vec<String>> = (0..header_count)
5462                .map(|_| Vec::with_capacity(row_hint))
5463                .collect();
5464            let deferred_parse_date_columns = deferred_parse_date_column_mask(&headers, options);
5465
5466            if (row_count as usize) < max_rows {
5467                append_csv_record(
5468                    &mut columns,
5469                    &mut raw_columns,
5470                    &first_record,
5471                    options,
5472                    &na_set,
5473                    &true_set,
5474                    &false_set,
5475                    &deferred_parse_date_columns,
5476                );
5477                row_count += 1;
5478            }
5479
5480            (headers, columns, raw_columns, deferred_parse_date_columns)
5481        };
5482
5483    for row in records {
5484        if (row_count as usize) >= max_rows {
5485            break;
5486        }
5487        let record = row?;
5488        if should_skip_bad_csv_record(&record, columns.len(), options.on_bad_lines) {
5489            continue;
5490        }
5491        if options.on_bad_lines == CsvOnBadLines::Error {
5492            reject_overlong_csv_record(
5493                record.len(),
5494                columns.len(),
5495                (row_count as usize) + 1 + usize::from(options.has_headers) + skip,
5496            )?;
5497        }
5498        append_csv_record(
5499            &mut columns,
5500            &mut raw_columns,
5501            &record,
5502            options,
5503            &na_set,
5504            &true_set,
5505            &false_set,
5506            &deferred_parse_date_columns,
5507        );
5508        row_count += 1;
5509    }
5510
5511    // Drop the last `skipfooter` data rows. Matches pandas semantics:
5512    // footer rows are dropped *after* header parsing and nrows limit.
5513    if options.skipfooter > 0 && (row_count as usize) > 0 {
5514        let drop = options.skipfooter.min(row_count as usize);
5515        for col in columns.iter_mut() {
5516            let new_len = col.len().saturating_sub(drop);
5517            col.truncate(new_len);
5518        }
5519        for col in raw_columns.iter_mut() {
5520            let new_len = col.len().saturating_sub(drop);
5521            col.truncate(new_len);
5522        }
5523        row_count -= drop as i64;
5524    }
5525    reject_duplicate_headers(&headers)?;
5526    if let Some(ref usecols) = options.usecols {
5527        validate_usecols(&headers, usecols)?;
5528    }
5529
5530    // Apply usecols filter: keep only selected columns.
5531    let (mut headers, mut columns, raw_columns, deferred_parse_date_columns) =
5532        if let Some(ref usecols) = options.usecols {
5533            let mut fh = Vec::new();
5534            let mut fc = Vec::new();
5535            let mut fr = Vec::new();
5536            let mut fd = Vec::new();
5537            for (((h, c), r), d) in headers
5538                .into_iter()
5539                .zip(columns)
5540                .zip(raw_columns)
5541                .zip(deferred_parse_date_columns)
5542            {
5543                if usecols.contains(&h) {
5544                    fh.push(h);
5545                    fc.push(c);
5546                    fr.push(r);
5547                    fd.push(d);
5548                }
5549            }
5550            (fh, fc, fr, fd)
5551        } else {
5552            (headers, columns, raw_columns, deferred_parse_date_columns)
5553        };
5554
5555    if let Some(ref parse_date_combinations) = options.parse_date_combinations {
5556        apply_parse_date_combinations(&mut headers, &mut columns, parse_date_combinations)?;
5557    }
5558
5559    if let Some(ref named) = options.parse_date_combinations_named {
5560        apply_parse_date_combinations_named(&mut headers, &mut columns, named)?;
5561    }
5562
5563    if let Some(ref parse_dates) = options.parse_dates {
5564        apply_csv_parse_dates(
5565            &headers,
5566            &mut columns,
5567            &raw_columns,
5568            &deferred_parse_date_columns,
5569            parse_dates,
5570            options,
5571            &na_set,
5572            &true_set,
5573            &false_set,
5574        )?;
5575    }
5576
5577    apply_pandas_csv_numeric_promotions(&mut columns);
5578
5579    // Apply dtype coercion if specified.
5580    //
5581    // `dtype=str` is special: pandas hands back the source text, so `007` stays `"007"`
5582    // and `1e3` stays `"1e3"`. Casting the already-inferred scalar cannot do that — by
5583    // then `007` is `Int64(7)` and re-rendering yields `"7"`, silently destroying leading
5584    // zeros, bit-string labels like `00`, and the original numeric spelling. Take the
5585    // verbatim cell from `raw_columns` instead, which is exactly what it is kept for.
5586    //
5587    // Guarded on the same condition as the object-fallback text below: a parse-date
5588    // transform can rewrite or add columns and desync `raw_columns` from `columns`, and
5589    // the per-column length check keeps the indexing honest even so.
5590    let raw_text_is_aligned = options.parse_dates.is_none()
5591        && options.parse_date_combinations.is_none()
5592        && options.parse_date_combinations_named.is_none()
5593        && raw_columns.len() == columns.len();
5594    if let Some(ref dtype_map) = options.dtype {
5595        for (i, name) in headers.iter().enumerate() {
5596            if let Some(target_dt) = dtype_map.get(name) {
5597                let raw_column = if raw_text_is_aligned {
5598                    raw_columns.get(i)
5599                } else {
5600                    None
5601                };
5602                if *target_dt == DType::Utf8
5603                    && raw_column.is_some_and(|raw| raw.len() == columns[i].len())
5604                {
5605                    let raw_column = raw_column.expect("checked immediately above");
5606                    // Missing cells stay missing: pandas `dtype=str` yields NaN for an
5607                    // NA cell rather than the literal marker text.
5608                    columns[i] = columns[i]
5609                        .iter()
5610                        .zip(raw_column)
5611                        .map(|(value, raw)| match value {
5612                            Scalar::Null(kind) => Scalar::Null(*kind),
5613                            _ => Scalar::Utf8(raw.clone()),
5614                        })
5615                        .collect();
5616                    continue;
5617                }
5618                let coerced = columns[i]
5619                    .iter()
5620                    .map(|v| fp_types::cast_scalar(v, target_dt.clone()))
5621                    .collect::<Result<Vec<_>, _>>()
5622                    .map_err(|err| IoError::Column(ColumnError::from(err)))?;
5623                columns[i] = coerced;
5624            }
5625        }
5626    }
5627
5628    let header_count = headers.len();
5629
5630    // Object-fallback columns should keep verbatim source text (pandas parity,
5631    // see build_csv_object_aware_column). Only safe when no parse-date transform
5632    // rewrote/added columns (which would desync raw_columns from columns); a
5633    // per-column dtype override is also excluded so explicit astype wins.
5634    let preserve_object_text = options.parse_dates.is_none()
5635        && options.parse_date_combinations.is_none()
5636        && options.parse_date_combinations_named.is_none();
5637    let dtype_forced = |name: &str| -> bool {
5638        options
5639            .dtype
5640            .as_ref()
5641            .is_some_and(|map| map.contains_key(name))
5642    };
5643
5644    // If index_col is set, extract that column as the index
5645    if let Some(ref idx_col_name) = options.index_col {
5646        let idx_pos = headers
5647            .iter()
5648            .position(|h| h == idx_col_name)
5649            .ok_or_else(|| IoError::MissingIndexColumn(idx_col_name.clone()))?;
5650
5651        let index_values = columns.remove(idx_pos);
5652        let index_labels: Vec<fp_index::IndexLabel> = index_values
5653            .into_iter()
5654            .map(|s| match s {
5655                Scalar::Int64(v) => fp_index::IndexLabel::Int64(v),
5656                Scalar::Utf8(v) => fp_index::IndexLabel::Utf8(v),
5657                Scalar::Float64(v) => fp_index::IndexLabel::Utf8(v.to_string()),
5658                Scalar::Bool(v) => {
5659                    fp_index::IndexLabel::Utf8(if v { "True" } else { "False" }.to_string())
5660                }
5661                // Typed null label (br-frankenpandas-8m6ay): pandas
5662                // read_csv(index_col=...) keeps a real nan index entry for an
5663                // empty cell. Kind-preserving bijection.
5664                Scalar::Null(kind) => fp_index::IndexLabel::Null(kind),
5665                Scalar::Timedelta64(v) => {
5666                    if v == Timedelta::NAT {
5667                        fp_index::IndexLabel::Utf8("<NaT>".to_owned())
5668                    } else {
5669                        fp_index::IndexLabel::Utf8(Timedelta::format(v))
5670                    }
5671                }
5672                Scalar::Datetime64(v) => {
5673                    if v == Timestamp::NAT {
5674                        fp_index::IndexLabel::Utf8("<NaT>".to_owned())
5675                    } else {
5676                        fp_index::IndexLabel::Utf8(format_datetime_ns(v))
5677                    }
5678                }
5679                Scalar::Period(v) => {
5680                    if v.ordinal == i64::MIN {
5681                        fp_index::IndexLabel::Utf8("<NaT>".to_owned())
5682                    } else {
5683                        fp_index::IndexLabel::Utf8(v.calendar_string())
5684                    }
5685                }
5686                Scalar::Interval(iv) => fp_index::IndexLabel::Utf8(format!("{iv}")),
5687            })
5688            .collect();
5689        // Per br-frankenpandas-l0vbr: pandas pd.read_csv(index_col='col')
5690        // sets result.index.name = 'col'.
5691        let index = Index::new(index_labels).set_name(idx_col_name);
5692
5693        let mut out_columns = BTreeMap::new();
5694        let mut column_order = Vec::with_capacity(headers.len() - 1);
5695        let mut col_idx = 0;
5696        for (orig_idx, _) in headers.iter().enumerate() {
5697            if orig_idx == idx_pos {
5698                continue;
5699            }
5700            let name = headers.get(orig_idx).cloned().unwrap_or_default();
5701            let column = if preserve_object_text && !dtype_forced(&name) {
5702                let (rb, ro) = strings_to_contiguous_raw(&raw_columns[orig_idx]);
5703                build_csv_object_aware_column(columns[col_idx].clone(), &rb, &ro)?
5704            } else {
5705                Column::from_values(columns[col_idx].clone())?
5706            };
5707            out_columns.insert(name.clone(), column);
5708            column_order.push(name);
5709            col_idx += 1;
5710        }
5711        Ok(DataFrame::new_with_column_order(
5712            index,
5713            out_columns,
5714            column_order,
5715        )?)
5716    } else {
5717        let mut out_columns = BTreeMap::new();
5718        let mut column_order = Vec::with_capacity(header_count);
5719        for (idx, values) in columns.into_iter().enumerate() {
5720            let name = headers.get(idx).cloned().unwrap_or_default();
5721            let column = if preserve_object_text && !dtype_forced(&name) {
5722                let (rb, ro) = strings_to_contiguous_raw(&raw_columns[idx]);
5723                build_csv_object_aware_column(values, &rb, &ro)?
5724            } else {
5725                Column::from_values(values)?
5726            };
5727            out_columns.insert(name.clone(), column);
5728            column_order.push(name);
5729        }
5730        let index = csv_default_unit_range_index(row_count);
5731        Ok(DataFrame::new_with_column_order(
5732            index,
5733            out_columns,
5734            column_order,
5735        )?)
5736    }
5737}
5738
5739/// Read CSV and promote the named columns into a row index / row MultiIndex.
5740///
5741/// For multiple names this mirrors pandas `index_col=[...]`.
5742pub fn read_csv_with_index_cols(
5743    input: &str,
5744    options: &CsvReadOptions,
5745    index_cols: &[&str],
5746) -> Result<DataFrame, IoError> {
5747    let frame = read_csv_with_options(input, options)?;
5748    promote_frame_index_columns(&frame, index_cols)
5749}
5750
5751// ── File-based CSV ─────────────────────────────────────────────────────
5752
5753pub fn read_csv(path: &Path) -> Result<DataFrame, IoError> {
5754    read_csv_with_options_path(path, &CsvReadOptions::default())
5755}
5756
5757pub fn read_csv_with_options_path(
5758    path: &Path,
5759    options: &CsvReadOptions,
5760) -> Result<DataFrame, IoError> {
5761    let content = std::fs::read_to_string(path)?;
5762    read_csv_with_options(&content, options)
5763}
5764
5765pub fn read_csv_with_index_cols_path(
5766    path: &Path,
5767    options: &CsvReadOptions,
5768    index_cols: &[&str],
5769) -> Result<DataFrame, IoError> {
5770    let content = std::fs::read_to_string(path)?;
5771    read_csv_with_index_cols(&content, options, index_cols)
5772}
5773
5774pub fn write_csv(frame: &DataFrame, path: &Path) -> Result<(), IoError> {
5775    let content = write_csv_string(frame)?;
5776    std::fs::write(path, content)?;
5777    Ok(())
5778}
5779
5780// ── read_table (tab-separated thin wrapper) ────────────────────────────
5781
5782/// Parse a tab-separated string, matching `pd.read_table(io.StringIO(s))`.
5783///
5784/// Equivalent to [`read_csv_str`] with `delimiter=b'\t'`. Other defaults
5785/// match pandas `read_table`: `header='infer'`, default NA values, no
5786/// index column promotion. Use [`read_table_with_options`] for full
5787/// option control.
5788pub fn read_table_str(input: &str) -> Result<DataFrame, IoError> {
5789    let opts = CsvReadOptions {
5790        delimiter: b'\t',
5791        ..CsvReadOptions::default()
5792    };
5793    read_csv_with_options(input, &opts)
5794}
5795
5796/// Parse a tab-separated string with explicit options. The caller-supplied
5797/// `options.delimiter` is preserved when it differs from the comma default
5798/// to allow override; otherwise it is forced to `b'\t'` so that the
5799/// pandas `read_table` semantics survive `CsvReadOptions::default()`.
5800pub fn read_table_with_options(
5801    input: &str,
5802    options: &CsvReadOptions,
5803) -> Result<DataFrame, IoError> {
5804    let mut effective = options.clone();
5805    if effective.delimiter == b',' {
5806        effective.delimiter = b'\t';
5807    }
5808    read_csv_with_options(input, &effective)
5809}
5810
5811/// Read a tab-separated file from disk, matching `pd.read_table(path)`.
5812pub fn read_table(path: &Path) -> Result<DataFrame, IoError> {
5813    let opts = CsvReadOptions {
5814        delimiter: b'\t',
5815        ..CsvReadOptions::default()
5816    };
5817    read_csv_with_options_path(path, &opts)
5818}
5819
5820/// Read a tab-separated file from disk with explicit options. The
5821/// caller-supplied delimiter is honored when it has been overridden from
5822/// the comma default; otherwise it is forced to `b'\t'`.
5823pub fn read_table_with_options_path(
5824    path: &Path,
5825    options: &CsvReadOptions,
5826) -> Result<DataFrame, IoError> {
5827    let mut effective = options.clone();
5828    if effective.delimiter == b',' {
5829        effective.delimiter = b'\t';
5830    }
5831    read_csv_with_options_path(path, &effective)
5832}
5833
5834// ── read_fwf (fixed-width file reader) ─────────────────────────────────
5835
5836/// Read a fixed-width file from disk, matching `pd.read_fwf(path, ...)`.
5837///
5838/// See [`read_fwf_str`] for the option semantics. When neither explicit
5839/// `colspecs` nor `widths` are supplied, column ranges are inferred from
5840/// non-whitespace runs.
5841pub fn read_fwf(path: &Path, options: &FwfReadOptions) -> Result<DataFrame, IoError> {
5842    let content = std::fs::read_to_string(path)?;
5843    read_fwf_str(&content, options)
5844}
5845
5846// ── Deferred reader surfaces ───────────────────────────────────────────
5847//
5848// pandas exposes pd.read_gbq / pd.read_sas / pd.read_spss (read_clipboard is
5849// implemented above via an OS subprocess backend). `read_sas` supports the
5850// SAS7BDAT dialect below; XPORT and the remaining two surfaces are deferred:
5851//
5852//   * read_gbq calls Google BigQuery (external service, GCP credentials).
5853//   * SAS XPORT and read_spss remain statistical-software formats without a
5854//     first-party Rust reader at parity (pandas calls into pyreadstat).
5855//
5856// Following the deferral precedent in fp-frame for plotting (see
5857// `plotting_deferred`), expose typed reject-closed entry points so callers
5858// can program against the surface and fall through to a clean error rather
5859// than a missing symbol.
5860
5861fn deferred_reader_error(method: &str, reason: &str) -> IoError {
5862    IoError::Deferred(format!(
5863        "{method}: in scope but deferred; {reason}. Use the pandas surface in the meantime."
5864    ))
5865}
5866
5867fn deferred_writer_error(method: &str, reason: &str) -> IoError {
5868    IoError::Deferred(format!(
5869        "{method}: in scope but deferred; {reason}. Use the pandas surface in the meantime."
5870    ))
5871}
5872
5873// ── Clipboard I/O (br-frankenpandas-261) ───────────────────────────────
5874//
5875// pandas `read_clipboard` / `to_clipboard` shell out to an OS clipboard helper
5876// (pyperclip → xclip/xsel/wl-clipboard/pbcopy). FrankenPandas mirrors that with
5877// a zero-dependency subprocess backend: no `arboard`/X11 dep tree is pulled in,
5878// and the pure TSV transform (`read_clipboard_str` / the `to_clipboard` writer)
5879// is fully testable without a live clipboard. When no backend binary is
5880// installed (e.g. a headless CI box) the call returns a clear `Clipboard`
5881// error, exactly as pandas raises `PyperclipException`.
5882
5883/// Backends tried in order for READING the clipboard: `(binary, args)`.
5884const CLIPBOARD_READ_BACKENDS: &[(&str, &[&str])] = &[
5885    ("wl-paste", &["-n"]),
5886    ("xclip", &["-selection", "clipboard", "-o"]),
5887    ("xsel", &["-b", "-o"]),
5888    ("pbpaste", &[]),
5889];
5890
5891/// Backends tried in order for WRITING the clipboard: `(binary, args)`.
5892const CLIPBOARD_WRITE_BACKENDS: &[(&str, &[&str])] = &[
5893    ("wl-copy", &[]),
5894    ("xclip", &["-selection", "clipboard"]),
5895    ("xsel", &["-b", "-i"]),
5896    ("pbcopy", &[]),
5897];
5898
5899fn clipboard_get() -> Result<String, IoError> {
5900    let mut last =
5901        String::from("no clipboard backend found (tried wl-paste, xclip, xsel, pbpaste)");
5902    for (cmd, args) in CLIPBOARD_READ_BACKENDS {
5903        match std::process::Command::new(cmd).args(*args).output() {
5904            Ok(out) if out.status.success() => {
5905                return String::from_utf8(out.stdout)
5906                    .map_err(|e| IoError::Clipboard(format!("clipboard text is not UTF-8: {e}")));
5907            }
5908            Ok(_) => last = format!("{cmd}: exited non-zero"),
5909            Err(_) => {} // binary not installed — try the next backend
5910        }
5911    }
5912    Err(IoError::Clipboard(last))
5913}
5914
5915fn clipboard_set(text: &str) -> Result<(), IoError> {
5916    use std::io::Write as _;
5917    let mut last = String::from("no clipboard backend found (tried wl-copy, xclip, xsel, pbcopy)");
5918    for (cmd, args) in CLIPBOARD_WRITE_BACKENDS {
5919        let spawned = std::process::Command::new(cmd)
5920            .args(*args)
5921            .stdin(std::process::Stdio::piped())
5922            .stdout(std::process::Stdio::null())
5923            .stderr(std::process::Stdio::null())
5924            .spawn();
5925        let mut child = match spawned {
5926            Ok(child) => child,
5927            Err(_) => continue, // binary not installed — try the next backend
5928        };
5929        if let Some(mut stdin) = child.stdin.take()
5930            && stdin.write_all(text.as_bytes()).is_err()
5931        {
5932            last = format!("{cmd}: writing to stdin failed");
5933            continue;
5934        }
5935        match child.wait() {
5936            Ok(status) if status.success() => return Ok(()),
5937            Ok(_) => last = format!("{cmd}: exited non-zero"),
5938            Err(e) => last = format!("{cmd}: {e}"),
5939        }
5940    }
5941    Err(IoError::Clipboard(last))
5942}
5943
5944/// Parse clipboard text into a `DataFrame` — the pure, backend-free core of
5945/// [`read_clipboard`]. Tab-separated, matching the bytes `to_clipboard` writes
5946/// (pandas `excel=True`).
5947pub fn read_clipboard_str(text: &str) -> Result<DataFrame, IoError> {
5948    let options = CsvReadOptions {
5949        delimiter: b'\t',
5950        ..CsvReadOptions::default()
5951    };
5952    read_csv_with_options(text, &options)
5953}
5954
5955/// Read the system clipboard, matching `pd.read_clipboard()`. The clipboard is
5956/// fetched via the first available OS backend (`wl-paste`/`xclip`/`xsel`/
5957/// `pbpaste`) and parsed as TSV (the format [`DataFrameIoExt::to_clipboard`]
5958/// writes). Returns a `Clipboard` error when no backend is installed.
5959pub fn read_clipboard() -> Result<DataFrame, IoError> {
5960    read_clipboard_str(&clipboard_get()?)
5961}
5962
5963/// Serialize a frame to the tab-separated bytes `to_clipboard` puts on the
5964/// clipboard (pandas `excel=True`, index included). Pure/testable.
5965fn clipboard_tsv(frame: &DataFrame) -> Result<String, IoError> {
5966    let options = CsvWriteOptions {
5967        delimiter: b'\t',
5968        include_index: true,
5969        ..CsvWriteOptions::default()
5970    };
5971    write_csv_string_with_options(frame, &options)
5972}
5973
5974/// Reject-closed BigQuery reader.
5975///
5976/// Refusing matches stock pandas AND the surface is on its way out: measured on
5977/// 2.2.3, `pd.read_gbq` raises `ImportError: Missing optional dependency
5978/// 'pandas-gbq'` and emits a FutureWarning. Implementing it would mean adopting
5979/// a deprecated pandas surface plus network and Google auth.
5980/// br-frankenpandas-9jvao.
5981pub fn read_gbq(_query: &str, _project_id: Option<&str>) -> Result<DataFrame, IoError> {
5982    Err(deferred_reader_error(
5983        "read_gbq",
5984        "Google BigQuery integration is outside FrankenPandas's local file-format scope",
5985    ))
5986}
5987
5988/// Read a SAS7BDAT or SAS Transport (XPORT) dataset into a `DataFrame`.
5989///
5990/// The reader preserves decoded character data, missing cells, and SAS
5991/// date/datetime/time cells. XPORT numeric missing values are represented as
5992/// FP NaN-nulls, matching the transport parser's `NaN` representation.
5993/// br-frankenpandas-9jvao.
5994pub fn read_sas(path: &Path) -> Result<DataFrame, IoError> {
5995    if is_sas_xport_path(path) {
5996        return read_sas_xport(path);
5997    }
5998
5999    let mut reader = sas7bdat::SasReader::open(path).map_err(sas_error)?;
6000    let column_order = reader
6001        .metadata()
6002        .variables
6003        .iter()
6004        .map(|variable| variable.name.trim_end().to_owned())
6005        .collect::<Vec<_>>();
6006    reject_duplicate_headers(&column_order)?;
6007
6008    let mut columns = (0..column_order.len())
6009        .map(|_| Vec::new())
6010        .collect::<Vec<Vec<Scalar>>>();
6011    let mut row_count: i64 = 0;
6012    let mut rows = reader.rows_named().map_err(sas_error)?;
6013    while let Some(row) = rows.try_next().map_err(sas_error)? {
6014        let row_values = row.values();
6015        if row_values.len() != columns.len() {
6016            return Err(IoError::Sas(format!(
6017                "row {row_count} has {} cells; metadata declares {} columns",
6018                row_values.len(),
6019                columns.len()
6020            )));
6021        }
6022        for (column, value) in columns.iter_mut().zip(row_values) {
6023            column.push(sas_cell_to_scalar(value)?);
6024        }
6025        row_count = row_count
6026            .checked_add(1)
6027            .ok_or_else(|| IoError::Sas("row count exceeded i64 range".to_owned()))?;
6028    }
6029    sas_rows_to_frame(column_order, columns)
6030}
6031
6032fn is_sas_xport_path(path: &Path) -> bool {
6033    matches!(
6034        path.extension().and_then(std::ffi::OsStr::to_str),
6035        Some(extension)
6036            if extension.eq_ignore_ascii_case("xpt")
6037                || extension.eq_ignore_ascii_case("xpt5")
6038                || extension.eq_ignore_ascii_case("xpt8")
6039                || extension.eq_ignore_ascii_case("xport")
6040    )
6041}
6042
6043fn read_sas_xport(path: &Path) -> Result<DataFrame, IoError> {
6044    use sas_xport::sas::xport::XportReader;
6045
6046    let reader = XportReader::from_path(path).map_err(xport_error)?;
6047    let Some(mut dataset) = reader.next_dataset().map_err(xport_error)? else {
6048        return sas_rows_to_frame(Vec::new(), Vec::new());
6049    };
6050    let column_order = dataset
6051        .schema()
6052        .variables()
6053        .iter()
6054        .map(|variable| variable.full_name().to_owned())
6055        .collect::<Vec<_>>();
6056    reject_duplicate_headers(&column_order)?;
6057
6058    let mut columns = (0..column_order.len())
6059        .map(|_| Vec::new())
6060        .collect::<Vec<Vec<Scalar>>>();
6061    let mut row_count: i64 = 0;
6062    while let Some(row) = dataset.next_record().map_err(xport_error)? {
6063        if row.len() != columns.len() {
6064            return Err(IoError::Sas(format!(
6065                "XPORT row {row_count} has {} cells; metadata declares {} columns",
6066                row.len(),
6067                columns.len()
6068            )));
6069        }
6070        for (column, value) in columns.iter_mut().zip(row.iter()) {
6071            column.push(xport_cell_to_scalar(value));
6072        }
6073        row_count = row_count
6074            .checked_add(1)
6075            .ok_or_else(|| IoError::Sas("row count exceeded i64 range".to_owned()))?;
6076    }
6077    sas_rows_to_frame(column_order, columns)
6078}
6079
6080fn sas_rows_to_frame(
6081    column_order: Vec<String>,
6082    columns: Vec<Vec<Scalar>>,
6083) -> Result<DataFrame, IoError> {
6084    if column_order.len() != columns.len() {
6085        return Err(IoError::Sas(format!(
6086            "metadata declares {} columns but parser produced {} columns",
6087            column_order.len(),
6088            columns.len()
6089        )));
6090    }
6091    reject_duplicate_headers(&column_order)?;
6092    let row_count = columns.first().map_or(0, Vec::len);
6093    if columns.iter().any(|column| column.len() != row_count) {
6094        return Err(IoError::Sas(
6095            "parser produced columns with inconsistent row counts".to_owned(),
6096        ));
6097    }
6098    let row_count = i64::try_from(row_count)
6099        .map_err(|_| IoError::Sas("row count exceeded i64 range".to_owned()))?;
6100    let mut out = BTreeMap::new();
6101    for (name, values) in column_order.iter().cloned().zip(columns) {
6102        out.insert(name, Column::from_values(values)?);
6103    }
6104    Ok(DataFrame::new_with_column_order(
6105        Index::from_i64((0..row_count).collect()),
6106        out,
6107        column_order,
6108    )?)
6109}
6110
6111fn sas_cell_to_scalar(cell: &sas7bdat::CellValue<'_>) -> Result<Scalar, IoError> {
6112    use sas7bdat::CellValue;
6113
6114    match cell {
6115        CellValue::Float(value) => Ok(Scalar::Float64(*value)),
6116        CellValue::Int32(value) => Ok(Scalar::Float64(f64::from(*value))),
6117        CellValue::Int64(value) => {
6118            // pandas represents SAS numeric storage as float64, including values
6119            // whose original integer spelling exceeds f64's exact range.
6120            #[allow(clippy::cast_precision_loss)]
6121            let value = *value as f64;
6122            Ok(Scalar::Float64(value))
6123        }
6124        CellValue::NumericString(value) => {
6125            value.parse::<f64>().map(Scalar::Float64).map_err(|_| {
6126                IoError::Sas(format!(
6127                    "numeric SAS cell is not representable as f64: {value}"
6128                ))
6129            })
6130        }
6131        CellValue::Str(value) => Ok(Scalar::Utf8(value.to_string())),
6132        CellValue::Bytes(_) => Err(IoError::Sas(
6133            "SAS reader yielded undecoded bytes; a supported source encoding is required"
6134                .to_owned(),
6135        )),
6136        CellValue::DateTime(value) | CellValue::Date(value) => {
6137            let nanos = i64::try_from(value.unix_timestamp_nanos()).map_err(|_| {
6138                IoError::Sas("SAS datetime is outside datetime64[ns] range".to_owned())
6139            })?;
6140            Ok(Scalar::Datetime64(nanos))
6141        }
6142        CellValue::Time(value) => {
6143            let nanos = i64::try_from(value.whole_nanoseconds()).map_err(|_| {
6144                IoError::Sas("SAS time is outside timedelta64[ns] range".to_owned())
6145            })?;
6146            Ok(Scalar::Timedelta64(nanos))
6147        }
6148        CellValue::Missing(_) => Ok(Scalar::Null(NullKind::NaN)),
6149    }
6150}
6151
6152fn sas_error(error: sas7bdat::Error) -> IoError {
6153    IoError::Sas(error.to_string())
6154}
6155
6156fn xport_cell_to_scalar(value: &sas_xport::sas::xport::XportValue<'_>) -> Scalar {
6157    match value {
6158        sas_xport::sas::xport::XportValue::Character(value) => Scalar::Utf8(value.to_string()),
6159        sas_xport::sas::xport::XportValue::Number(value) if value.is_nan() => {
6160            Scalar::Null(NullKind::NaN)
6161        }
6162        sas_xport::sas::xport::XportValue::Number(value) => Scalar::Float64(*value),
6163    }
6164}
6165
6166fn xport_error(error: sas_xport::sas::xport::XportError) -> IoError {
6167    IoError::Sas(error.to_string())
6168}
6169
6170/// Reject-closed SPSS reader.
6171///
6172/// Refusing MATCHES pandas' out-of-the-box behaviour, for a different reason:
6173/// measured on 2.2.3, `pd.read_spss` raises `ImportError: Missing optional
6174/// dependency 'pyreadstat'`, so a stock pandas install refuses too. The ERROR
6175/// TYPE still differs from ours. br-frankenpandas-9jvao.
6176pub fn read_spss(_path: &Path) -> Result<DataFrame, IoError> {
6177    Err(deferred_reader_error(
6178        "read_spss",
6179        "no first-party Rust SPSS .sav reader exists at pandas-parity yet",
6180    ))
6181}
6182
6183// ── File-based Markdown / LaTeX ────────────────────────────────────────
6184
6185/// Write a DataFrame to a Markdown table file.
6186pub fn write_markdown(frame: &DataFrame, path: &Path) -> Result<(), IoError> {
6187    write_markdown_with_options(frame, path, &MarkdownWriteOptions::default())
6188}
6189
6190/// Write a DataFrame to a Markdown table file with explicit options.
6191pub fn write_markdown_with_options(
6192    frame: &DataFrame,
6193    path: &Path,
6194    options: &MarkdownWriteOptions,
6195) -> Result<(), IoError> {
6196    let content = write_markdown_string_with_options(frame, options)?;
6197    std::fs::write(path, content)?;
6198    Ok(())
6199}
6200
6201/// Write a DataFrame to a LaTeX tabular file.
6202pub fn write_latex(frame: &DataFrame, path: &Path) -> Result<(), IoError> {
6203    write_latex_with_options(frame, path, &LatexWriteOptions::default())
6204}
6205
6206/// Write a DataFrame to a LaTeX tabular file with explicit options.
6207pub fn write_latex_with_options(
6208    frame: &DataFrame,
6209    path: &Path,
6210    options: &LatexWriteOptions,
6211) -> Result<(), IoError> {
6212    let content = write_latex_string_with_options(frame, options)?;
6213    std::fs::write(path, content)?;
6214    Ok(())
6215}
6216
6217// ── File-based HTML ────────────────────────────────────────────────────
6218
6219pub fn read_html(path: &Path) -> Result<DataFrame, IoError> {
6220    read_html_with_options(path, &HtmlReadOptions::default())
6221}
6222
6223pub fn read_html_with_options(
6224    path: &Path,
6225    options: &HtmlReadOptions,
6226) -> Result<DataFrame, IoError> {
6227    let content = std::fs::read_to_string(path)?;
6228    read_html_str_with_options(&content, options)
6229}
6230
6231pub fn write_html(frame: &DataFrame, path: &Path) -> Result<(), IoError> {
6232    write_html_with_options(frame, path, &HtmlWriteOptions::default())
6233}
6234
6235pub fn write_html_with_options(
6236    frame: &DataFrame,
6237    path: &Path,
6238    options: &HtmlWriteOptions,
6239) -> Result<(), IoError> {
6240    let content = write_html_string_with_options(frame, options)?;
6241    std::fs::write(path, content)?;
6242    Ok(())
6243}
6244
6245// ── File-based XML ─────────────────────────────────────────────────────
6246
6247pub fn write_xml(frame: &DataFrame, path: &Path) -> Result<(), IoError> {
6248    write_xml_with_options(frame, path, &XmlWriteOptions::default())
6249}
6250
6251pub fn write_xml_with_options(
6252    frame: &DataFrame,
6253    path: &Path,
6254    options: &XmlWriteOptions,
6255) -> Result<(), IoError> {
6256    let content = write_xml_string_with_options(frame, options)?;
6257    std::fs::write(path, content)?;
6258    Ok(())
6259}
6260
6261// ── File-based XML readers ─────────────────────────────────────────────
6262
6263pub fn read_xml(path: &Path) -> Result<DataFrame, IoError> {
6264    read_xml_with_options(path, &XmlReadOptions::default())
6265}
6266
6267pub fn read_xml_with_options(path: &Path, options: &XmlReadOptions) -> Result<DataFrame, IoError> {
6268    let content = std::fs::read_to_string(path)?;
6269    read_xml_str_with_options(&content, options)
6270}
6271
6272// ── JSON IO ────────────────────────────────────────────────────────────
6273
6274fn json_value_to_scalar(val: &serde_json::Value) -> Scalar {
6275    match val {
6276        serde_json::Value::Null => Scalar::Null(NullKind::Null),
6277        serde_json::Value::Bool(b) => Scalar::Bool(*b),
6278        serde_json::Value::Number(n) => {
6279            if let Some(i) = n.as_i64() {
6280                Scalar::Int64(i)
6281            } else if let Some(f) = n.as_f64() {
6282                Scalar::Float64(f)
6283            } else {
6284                Scalar::Utf8(n.to_string())
6285            }
6286        }
6287        serde_json::Value::String(s) => Scalar::Utf8(s.clone()),
6288        other => Scalar::Utf8(other.to_string()),
6289    }
6290}
6291
6292fn parse_json_value_allowing_pandas_nan(input: &str) -> Result<serde_json::Value, IoError> {
6293    match serde_json::from_str(input) {
6294        Ok(value) => Ok(value),
6295        Err(original) => {
6296            let normalized = normalize_bare_json_nan_tokens(input);
6297            if normalized == input {
6298                return Err(original.into());
6299            }
6300            serde_json::from_str(&normalized).map_err(IoError::from)
6301        }
6302    }
6303}
6304
6305fn normalize_bare_json_nan_tokens(input: &str) -> String {
6306    let mut output = String::with_capacity(input.len());
6307    let mut index = 0;
6308    let mut in_string = false;
6309    let mut escaped = false;
6310
6311    while index < input.len() {
6312        let rest = &input[index..];
6313        let Some(ch) = rest.chars().next() else {
6314            break;
6315        };
6316
6317        if in_string {
6318            output.push(ch);
6319            index += ch.len_utf8();
6320            if escaped {
6321                escaped = false;
6322            } else if ch == '\\' {
6323                escaped = true;
6324            } else if ch == '"' {
6325                in_string = false;
6326            }
6327            continue;
6328        }
6329
6330        if ch == '"' {
6331            in_string = true;
6332            output.push(ch);
6333            index += ch.len_utf8();
6334            continue;
6335        }
6336
6337        if rest.starts_with("NaN")
6338            && is_json_value_start_boundary(input, index)
6339            && is_json_value_end_boundary(input, index + 3)
6340        {
6341            output.push_str("null");
6342            index += 3;
6343            continue;
6344        }
6345
6346        output.push(ch);
6347        index += ch.len_utf8();
6348    }
6349
6350    output
6351}
6352
6353fn is_json_value_start_boundary(input: &str, index: usize) -> bool {
6354    input[..index]
6355        .chars()
6356        .rev()
6357        .find(|ch| !ch.is_whitespace())
6358        .is_none_or(|ch| matches!(ch, ':' | '[' | ','))
6359}
6360
6361fn is_json_value_end_boundary(input: &str, index: usize) -> bool {
6362    input[index..]
6363        .chars()
6364        .find(|ch| !ch.is_whitespace())
6365        .is_none_or(|ch| matches!(ch, ',' | ']' | '}'))
6366}
6367
6368fn column_from_json_values(values: Vec<Scalar>) -> Result<Column, IoError> {
6369    let saw_utf8 = values.iter().any(|value| matches!(value, Scalar::Utf8(_)));
6370    let saw_missing = values.iter().any(Scalar::is_missing);
6371    let saw_float = values
6372        .iter()
6373        .any(|value| matches!(value, Scalar::Float64(_)));
6374    let saw_numeric_like = values.iter().any(|value| {
6375        matches!(
6376            value,
6377            Scalar::Int64(_) | Scalar::Float64(_) | Scalar::Bool(_)
6378        )
6379    });
6380    let only_numeric_like_or_missing = values.iter().all(|value| {
6381        matches!(
6382            value,
6383            Scalar::Int64(_) | Scalar::Float64(_) | Scalar::Bool(_) | Scalar::Null(_)
6384        )
6385    });
6386
6387    // JSON records follow pandas' numeric unification: a Float64 makes the
6388    // entire numeric/bool column Float64 even when no value is missing.  The
6389    // missing-value branch was already necessary for JSON nulls; keeping the
6390    // same typed construction for float mixes prevents the first Int64 from
6391    // fixing the column kind before later floats/bools are considered.
6392    if !saw_utf8
6393        && only_numeric_like_or_missing
6394        && (saw_float
6395            || (saw_missing && (saw_numeric_like || values.iter().all(Scalar::is_missing))))
6396    {
6397        let promoted = values
6398            .into_iter()
6399            .map(|value| match value {
6400                Scalar::Int64(value) => Scalar::Float64(value as f64),
6401                Scalar::Bool(value) => Scalar::Float64(if value { 1.0 } else { 0.0 }),
6402                Scalar::Null(_) => Scalar::Null(NullKind::NaN),
6403                other => other,
6404            })
6405            .collect();
6406        return Column::new(DType::Float64, promoted).map_err(IoError::from);
6407    }
6408
6409    Column::from_values(values).map_err(IoError::from)
6410}
6411
6412fn scalar_to_json(scalar: &Scalar) -> serde_json::Value {
6413    match scalar {
6414        Scalar::Null(_) => serde_json::Value::Null,
6415        Scalar::Bool(b) => serde_json::Value::Bool(*b),
6416        Scalar::Int64(i) => serde_json::json!(*i),
6417        Scalar::Float64(f) => {
6418            if f.is_nan() || f.is_infinite() {
6419                serde_json::Value::Null
6420            } else {
6421                serde_json::json!(*f)
6422            }
6423        }
6424        Scalar::Utf8(s) => serde_json::Value::String(s.clone()),
6425        // pandas to_json (default date_format='epoch', date_unit='ms') serializes
6426        // datetime64 and timedelta64 as epoch-MILLISECOND integers, not strings.
6427        // (br-frankenpandas-lb0iu)
6428        Scalar::Timedelta64(v) => {
6429            if *v == Timedelta::NAT {
6430                serde_json::Value::Null
6431            } else {
6432                serde_json::json!(*v / 1_000_000)
6433            }
6434        }
6435        Scalar::Datetime64(v) => {
6436            if *v == Timestamp::NAT {
6437                serde_json::Value::Null
6438            } else {
6439                serde_json::json!(*v / 1_000_000)
6440            }
6441        }
6442        Scalar::Period(p) => {
6443            if p.ordinal == i64::MIN {
6444                serde_json::Value::Null
6445            } else {
6446                serde_json::Value::String(p.calendar_string())
6447            }
6448        }
6449        Scalar::Interval(iv) => serde_json::Value::String(format!("{iv}")),
6450    }
6451}
6452
6453fn column_promotes_int_json_values_to_float(_values: &[Scalar]) -> bool {
6454    // DISC-011: Nullable extension Int64 dtype parity.
6455    // Pandas (since v0.24) preserves Int64 via a separate validity mask when
6456    // null values are present. We now match: Int64 values serialize as integers,
6457    // Null values serialize as null, no Float64 promotion.
6458    false
6459}
6460
6461fn scalar_to_json_with_column_promotion(
6462    scalar: &Scalar,
6463    promote_int_to_float: bool,
6464) -> serde_json::Value {
6465    if promote_int_to_float && let Scalar::Int64(v) = scalar {
6466        return serde_json::json!(*v as f64);
6467    }
6468    scalar_to_json(scalar)
6469}
6470
6471fn json_value_to_index_label(value: &serde_json::Value) -> IndexLabel {
6472    match value {
6473        serde_json::Value::Number(n) => n
6474            .as_i64()
6475            .map(IndexLabel::Int64)
6476            .unwrap_or_else(|| IndexLabel::Utf8(n.to_string())),
6477        serde_json::Value::String(s) => IndexLabel::Utf8(s.clone()),
6478        serde_json::Value::Bool(b) => IndexLabel::Utf8(b.to_string()),
6479        serde_json::Value::Null => IndexLabel::Utf8("null".to_owned()),
6480        other => IndexLabel::Utf8(other.to_string()),
6481    }
6482}
6483
6484fn json_value_to_column_name(value: &serde_json::Value) -> String {
6485    match value {
6486        serde_json::Value::String(s) => s.clone(),
6487        serde_json::Value::Number(n) => n.to_string(),
6488        serde_json::Value::Bool(b) => b.to_string(),
6489        serde_json::Value::Null => "null".to_owned(),
6490        other => other.to_string(),
6491    }
6492}
6493
6494fn json_key_to_index_label(value: &str) -> IndexLabel {
6495    value
6496        .parse::<i64>()
6497        .map(IndexLabel::Int64)
6498        .unwrap_or_else(|_| IndexLabel::Utf8(value.to_owned()))
6499}
6500
6501fn index_label_to_json(label: &IndexLabel) -> serde_json::Value {
6502    match label {
6503        IndexLabel::Int64(v) => serde_json::json!(*v),
6504        IndexLabel::Float64(v) => serde_json::json!(v.0),
6505        IndexLabel::Bool(b) => serde_json::json!(*b),
6506        IndexLabel::Utf8(v) => serde_json::Value::String(v.clone()),
6507        // Epoch-millisecond ints, matching pandas to_json (date_unit='ms') and
6508        // the value path above — previously emitted raw nanoseconds, which
6509        // matched neither pandas nor FP's own value serialization.
6510        // (br-frankenpandas-lb0iu)
6511        //
6512        // A NaT label (the i64::MIN sentinel) must serialize as JSON null, NOT
6513        // `i64::MIN / 1e6` (-9223372036854775) — the latter is neither pandas nor
6514        // FP's own value path (`scalar_to_json_value`), which already null-checks
6515        // `Timestamp::NAT`/`Timedelta::NAT`. (br-frankenpandas-natjson)
6516        IndexLabel::Timedelta64(ns) => {
6517            if *ns == fp_types::Timedelta::NAT {
6518                serde_json::Value::Null
6519            } else {
6520                serde_json::json!(*ns / 1_000_000)
6521            }
6522        }
6523        IndexLabel::Datetime64(ns) => {
6524            if *ns == fp_types::Timestamp::NAT {
6525                serde_json::Value::Null
6526            } else {
6527                serde_json::json!(*ns / 1_000_000)
6528            }
6529        }
6530        // pandas to_json renders a missing label as JSON null.
6531        IndexLabel::Null(_) => serde_json::Value::Null,
6532    }
6533}
6534
6535/// Stringified index label for use as a JSON object key (columns/index orients).
6536/// Temporal labels become epoch-millisecond strings, matching pandas to_json
6537/// (e.g. a 2020-01-01 index key is "1577836800000", not "2020-01-01 00:00:00").
6538/// (br-frankenpandas-lb0iu)
6539fn index_label_json_key(label: &IndexLabel) -> String {
6540    match label {
6541        // NaT (i64::MIN) as an object key renders as "null" rather than the
6542        // sentinel's epoch garbage (-9223372036854775), matching the JSON-null
6543        // the value path emits for a missing temporal label.
6544        // (br-frankenpandas-natjson)
6545        IndexLabel::Datetime64(ns) if *ns == fp_types::Timestamp::NAT => "null".to_owned(),
6546        IndexLabel::Timedelta64(ns) if *ns == fp_types::Timedelta::NAT => "null".to_owned(),
6547        IndexLabel::Datetime64(ns) | IndexLabel::Timedelta64(ns) => (*ns / 1_000_000).to_string(),
6548        other => other.to_string(),
6549    }
6550}
6551
6552const SYNTHETIC_ROW_MULTIINDEX_PREFIX: &str = "__index_level_";
6553
6554fn index_label_to_scalar_value(label: &IndexLabel) -> Scalar {
6555    match label {
6556        IndexLabel::Int64(v) => Scalar::Int64(*v),
6557        IndexLabel::Float64(v) => Scalar::Float64(v.0),
6558        IndexLabel::Bool(b) => Scalar::Bool(*b),
6559        IndexLabel::Utf8(v) => Scalar::Utf8(v.clone()),
6560        IndexLabel::Timedelta64(v) => Scalar::Timedelta64(*v),
6561        // Keep the TYPED Datetime64 scalar, like the Timedelta64 arm above —
6562        // materializing a MultiIndex level into a column must preserve its dtype
6563        // (pandas reset_index keeps a datetime level as datetime64, not object).
6564        // The old `Scalar::Utf8(format_datetime_ns(..))` downgrade made datetime
6565        // levels render as ISO strings in to_json (inconsistent with a single
6566        // DatetimeIndex's epoch-ms ints) and bypassed to_csv's column-uniform
6567        // datetime format. (br-frankenpandas-mdt64)
6568        IndexLabel::Datetime64(v) => Scalar::Datetime64(*v),
6569        // Typed-null label round-trips to the same-kind missing scalar.
6570        IndexLabel::Null(kind) => Scalar::Null(*kind),
6571    }
6572}
6573
6574fn synthetic_row_multiindex_names(nlevels: usize) -> Vec<String> {
6575    (0..nlevels)
6576        .map(|level| format!("{SYNTHETIC_ROW_MULTIINDEX_PREFIX}{level}__"))
6577        .collect()
6578}
6579
6580fn materialize_row_multiindex_columns(
6581    frame: &DataFrame,
6582    names: &[String],
6583) -> Result<DataFrame, IoError> {
6584    let Some(row_multiindex) = frame.row_multiindex() else {
6585        return Ok(frame.clone());
6586    };
6587
6588    let mut columns = BTreeMap::new();
6589    let mut column_order = Vec::with_capacity(names.len() + frame.column_names().len());
6590    for (level, name) in names.iter().enumerate() {
6591        let level_index = row_multiindex.get_level_values(level)?;
6592        let values = level_index
6593            .labels()
6594            .iter()
6595            .map(index_label_to_scalar_value)
6596            .collect::<Vec<_>>();
6597        columns.insert(name.clone(), Column::from_values(values)?);
6598        column_order.push(name.clone());
6599    }
6600
6601    for name in frame.column_names() {
6602        let column = frame
6603            .column(name)
6604            .ok_or_else(|| {
6605                IoError::Frame(FrameError::CompatibilityRejected(format!(
6606                    "column not found: '{name}'"
6607                )))
6608            })?
6609            .clone();
6610        columns.insert(name.clone(), column);
6611        column_order.push(name.clone());
6612    }
6613
6614    let index = Index::from_i64((0..frame.len() as i64).collect());
6615    DataFrame::new_with_column_order(index, columns, column_order).map_err(IoError::from)
6616}
6617
6618fn materialize_named_row_multiindex_columns(frame: &DataFrame) -> Result<DataFrame, IoError> {
6619    if frame.row_multiindex().is_some() {
6620        frame.reset_index(false).map_err(IoError::from)
6621    } else {
6622        Ok(frame.clone())
6623    }
6624}
6625
6626fn materialize_synthetic_row_multiindex_columns(frame: &DataFrame) -> Result<DataFrame, IoError> {
6627    let Some(row_multiindex) = frame.row_multiindex() else {
6628        return Ok(frame.clone());
6629    };
6630    let names = synthetic_row_multiindex_names(row_multiindex.nlevels());
6631    materialize_row_multiindex_columns(frame, &names)
6632}
6633
6634/// Schema-level metadata key under which Parquet / Feather / Arrow IPC files
6635/// carry the row MultiIndex level names (a JSON array, `null` for an unnamed
6636/// level). The level VALUES travel as the synthetic `__index_level_N__`
6637/// columns that `promote_synthetic_row_multiindex_if_present` recognises; the
6638/// NAMES had nowhere to go, so every round-trip came back as
6639/// `__index_level_0__` / `__index_level_1__` / ... where pandas keeps
6640/// `region` / `product` / `year` (br-frankenpandas-wfkzm).
6641const ROW_MULTIINDEX_NAMES_METADATA_KEY: &str = "frankenpandas.row_multiindex_names";
6642
6643/// Same payload for the JSON `split` orient, as an extra top-level key. pandas
6644/// cannot round-trip a MultiIndex through `split` at all
6645/// (`read_json(orient="split")` raises NotImplementedError on the tuple
6646/// index), so the key costs no interoperability.
6647const JSON_SPLIT_INDEX_NAMES_KEY: &str = "index_names";
6648
6649/// Re-apply level names to a frame whose row MultiIndex was rebuilt from the
6650/// synthetic columns. A length mismatch (file written by an older build, or
6651/// hand-edited) leaves the synthetic names in place rather than guessing.
6652fn restore_row_multiindex_names(
6653    frame: DataFrame,
6654    names: &[Option<String>],
6655) -> Result<DataFrame, IoError> {
6656    let Some(row_multiindex) = frame.row_multiindex() else {
6657        return Ok(frame);
6658    };
6659    if row_multiindex.nlevels() != names.len() {
6660        return Ok(frame);
6661    }
6662    let renamed = row_multiindex.clone().set_names(names.to_vec());
6663    frame.with_row_multiindex(renamed).map_err(IoError::from)
6664}
6665
6666fn row_multiindex_names_from_arrow_metadata(
6667    metadata: &std::collections::HashMap<String, String>,
6668) -> Option<Vec<Option<String>>> {
6669    let raw = metadata.get(ROW_MULTIINDEX_NAMES_METADATA_KEY)?;
6670    serde_json::from_str::<Vec<Option<String>>>(raw).ok()
6671}
6672
6673fn promote_frame_index_columns(
6674    frame: &DataFrame,
6675    index_cols: &[&str],
6676) -> Result<DataFrame, IoError> {
6677    if index_cols.is_empty() {
6678        return Ok(frame.clone());
6679    }
6680    if index_cols.len() == 1 {
6681        frame.set_index(index_cols[0], true).map_err(IoError::from)
6682    } else {
6683        frame
6684            .set_index_multi(index_cols, true, "|")
6685            .map_err(IoError::from)
6686    }
6687}
6688
6689fn detect_synthetic_row_multiindex_columns(frame: &DataFrame) -> Vec<String> {
6690    let mut out = Vec::new();
6691    for (level, name) in frame.column_names().iter().enumerate() {
6692        let expected = format!("{SYNTHETIC_ROW_MULTIINDEX_PREFIX}{level}__");
6693        if **name == expected {
6694            out.push(expected);
6695        } else {
6696            break;
6697        }
6698    }
6699    out
6700}
6701
6702fn promote_synthetic_row_multiindex_if_present(frame: &DataFrame) -> Result<DataFrame, IoError> {
6703    let synthetic_cols = detect_synthetic_row_multiindex_columns(frame);
6704    if synthetic_cols.len() < 2 {
6705        return Ok(frame.clone());
6706    }
6707    let refs = synthetic_cols
6708        .iter()
6709        .map(String::as_str)
6710        .collect::<Vec<_>>();
6711    promote_frame_index_columns(frame, &refs)
6712}
6713
6714/// Fast path for `read_json_str(JsonOrient::Records)`: scan a FLAT records array
6715/// (`[{...}, ...]` whose values are only number / string / bool / null) directly into
6716/// per-column `Vec<Scalar>` builders, skipping the `serde_json::Value` tree + the
6717/// per-record map allocation. Returns `Ok(None)` to defer to the generic Value-tree
6718/// path on ANY deviation (nested value, escaped string/key, `NaN`/`Infinity` token,
6719/// trailing garbage, malformed structure), so the produced frame is BIT-IDENTICAL to
6720/// the generic path for every input it accepts:
6721/// - each `Scalar` is built exactly as `json_value_to_scalar` would (number tokens are
6722///   parsed by `serde_json`, so `as_i64`/`as_f64` classification is identical);
6723/// - column order is first-seen (same as the generic path's first-seen collection);
6724/// - a key missing from a record backfills `Null`, a duplicate key keeps the last value
6725///   (matching `serde_json`'s `preserve_order` map);
6726/// - the frame is assembled with the same `column_from_json_values` +
6727///   `promote_synthetic_row_multiindex_if_present` tail.
6728///
6729/// Depth- and string-aware scan of a records array `[ {...}, {...}, … ]`: returns the
6730/// body byte range `[body_start, body_end)` (just inside `[` … `]`) and the byte offset
6731/// of every DEPTH-1 (record-separating) comma. `None` unless the input is a non-empty
6732/// top-level array. Used to split a records JSON into whole-record byte ranges for
6733/// parallel parsing; correctness is verified by the flat scanner re-parsing each range.
6734fn scan_json_record_boundaries(s: &[u8]) -> Option<(usize, usize, Vec<usize>)> {
6735    let n = s.len();
6736    let mut i = 0;
6737    while i < n && matches!(s[i], b' ' | b'\t' | b'\n' | b'\r') {
6738        i += 1;
6739    }
6740    if i >= n || s[i] != b'[' {
6741        return None;
6742    }
6743    let body_start = i + 1;
6744    let mut depth = 0i32;
6745    let mut in_str = false;
6746    let mut esc = false;
6747    let mut commas: Vec<usize> = Vec::new();
6748    let mut body_end = None;
6749    let mut j = i;
6750    while j < n {
6751        let c = s[j];
6752        if in_str {
6753            if esc {
6754                esc = false;
6755            } else if c == b'\\' {
6756                esc = true;
6757            } else if c == b'"' {
6758                in_str = false;
6759            }
6760        } else {
6761            match c {
6762                b'"' => in_str = true,
6763                b'{' | b'[' => depth += 1,
6764                b'}' | b']' => {
6765                    depth -= 1;
6766                    if depth == 0 {
6767                        body_end = Some(j);
6768                        break;
6769                    }
6770                }
6771                b',' if depth == 1 => commas.push(j),
6772                _ => {}
6773            }
6774        }
6775        j += 1;
6776    }
6777    let body_end = body_end?;
6778    // Trailing content after the closing `]` must be whitespace only.
6779    let mut t = body_end + 1;
6780    while t < n && matches!(s[t], b' ' | b'\t' | b'\n' | b'\r') {
6781        t += 1;
6782    }
6783    if t != n {
6784        return None;
6785    }
6786    if body_start >= body_end {
6787        return None; // empty array -> generic path
6788    }
6789    Some((body_start, body_end, commas))
6790}
6791
6792/// SIMD-assisted boundary scan for the deliberately narrow numeric records path.
6793///
6794/// `fp-bench` writes compact records as `{"a":1},{"a":2}`, so `},{"` is an
6795/// unambiguous record separator for that payload. A user key can legally contain
6796/// those bytes, however, so this function is only an *admission candidate*: every
6797/// resulting range is subsequently parsed by [`parse_json_records_numeric_range`].
6798/// Any false boundary (or non-compact whitespace spelling) makes that parser return
6799/// `None`, which sends the input to the existing string/depth-aware scanner and
6800/// generic JSON parser. The fast path therefore never changes accepted semantics.
6801///
6802/// The previous generic scan examined every byte serially before numeric workers
6803/// began parsing. `memmem` locates the compact separators with its byte-search
6804/// implementation, leaving the typed builders as the only per-record work on the
6805/// benchmark's homogeneous Float64 payload.
6806fn scan_json_numeric_record_boundaries(s: &[u8]) -> Option<(usize, usize, Vec<usize>)> {
6807    let mut start = 0usize;
6808    while start < s.len() && matches!(s[start], b' ' | b'\t' | b'\n' | b'\r') {
6809        start += 1;
6810    }
6811    if s.get(start) != Some(&b'[') {
6812        return None;
6813    }
6814    let body_start = start + 1;
6815    let mut closing = s.len();
6816    while closing > body_start && matches!(s[closing - 1], b' ' | b'\t' | b'\n' | b'\r') {
6817        closing -= 1;
6818    }
6819    if closing <= body_start || s[closing - 1] != b']' {
6820        return None;
6821    }
6822    let body_end = closing - 1;
6823    if body_start >= body_end {
6824        return None;
6825    }
6826
6827    let commas = memchr::memmem::find_iter(&s[body_start..body_end], b"},{\"")
6828        .map(|separator_start| body_start + separator_start + 1)
6829        .collect();
6830    Some((body_start, body_end, commas))
6831}
6832
6833/// A numeric column being built directly from a flat records payload.  Keeping
6834/// the numeric representation here avoids creating a `Scalar` for every cell
6835/// only for `Column::from_values` to immediately infer the same representation
6836/// again.  This deliberately accepts a narrower shape than the scalar scanner:
6837/// every record must have the same unescaped keys in the same order and every
6838/// value must be a JSON number.  Any other valid records payload falls through
6839/// to the established scalar/serde paths below.
6840enum JsonNumericColumn {
6841    Int(Vec<i64>),
6842    Float(Vec<f64>),
6843}
6844
6845impl JsonNumericColumn {
6846    fn push_number(&mut self, number: JsonRecordNumber) {
6847        match self {
6848            Self::Int(values) => match number {
6849                JsonRecordNumber::Int(value) => values.push(value),
6850                JsonRecordNumber::Float(value) => {
6851                    let mut promoted = Vec::with_capacity(values.capacity().saturating_add(1));
6852                    promoted.extend(values.iter().map(|&prior| prior as f64));
6853                    promoted.push(value);
6854                    *self = Self::Float(promoted);
6855                }
6856            },
6857            Self::Float(values) => values.push(number.as_f64()),
6858        }
6859    }
6860}
6861
6862/// JSON-number representation for the typed records reader.  This parser is
6863/// deliberately stricter than Rust's number parsers: it first accepts exactly
6864/// JSON's grammar, then lets the standard library perform the IEEE conversion.
6865/// Keeping the grammar check here avoids the per-cell serde deserializer while
6866/// preserving the fallback boundary for inputs the generic JSON parser owns.
6867#[derive(Clone, Copy, Debug)]
6868enum JsonRecordNumber {
6869    Int(i64),
6870    Float(f64),
6871}
6872
6873impl JsonRecordNumber {
6874    fn as_f64(self) -> f64 {
6875        match self {
6876            Self::Int(value) => value as f64,
6877            Self::Float(value) => value,
6878        }
6879    }
6880}
6881
6882fn parse_json_record_number(token: &[u8]) -> Option<JsonRecordNumber> {
6883    let mut index = 0usize;
6884    if token.get(index) == Some(&b'-') {
6885        index += 1;
6886    }
6887
6888    match token.get(index)? {
6889        b'0' => {
6890            index += 1;
6891            if matches!(token.get(index), Some(b'0'..=b'9')) {
6892                return None;
6893            }
6894        }
6895        b'1'..=b'9' => {
6896            index += 1;
6897            while matches!(token.get(index), Some(b'0'..=b'9')) {
6898                index += 1;
6899            }
6900        }
6901        _ => return None,
6902    }
6903
6904    let mut is_float = false;
6905    if token.get(index) == Some(&b'.') {
6906        is_float = true;
6907        index += 1;
6908        let fraction_start = index;
6909        while matches!(token.get(index), Some(b'0'..=b'9')) {
6910            index += 1;
6911        }
6912        if index == fraction_start {
6913            return None;
6914        }
6915    }
6916
6917    if matches!(token.get(index), Some(b'e' | b'E')) {
6918        is_float = true;
6919        index += 1;
6920        if matches!(token.get(index), Some(b'+' | b'-')) {
6921            index += 1;
6922        }
6923        let exponent_start = index;
6924        while matches!(token.get(index), Some(b'0'..=b'9')) {
6925            index += 1;
6926        }
6927        if index == exponent_start {
6928            return None;
6929        }
6930    }
6931
6932    if index != token.len() {
6933        return None;
6934    }
6935    let token = std::str::from_utf8(token).ok()?;
6936    if !is_float && let Ok(value) = token.parse::<i64>() {
6937        return Some(JsonRecordNumber::Int(value));
6938    }
6939    token
6940        .parse::<f64>()
6941        .ok()
6942        .filter(|value| value.is_finite())
6943        .map(JsonRecordNumber::Float)
6944}
6945
6946/// Parse a range of a homogeneous, numeric flat-records array into typed column
6947/// builders.  See [`JsonNumericColumn`] for why this has intentionally strict
6948/// admission; `None` is always a performance fallback, never a parse error.
6949fn parse_json_records_numeric_range(
6950    s: &[u8],
6951    lo: usize,
6952    hi: usize,
6953) -> Option<(Vec<String>, Vec<JsonNumericColumn>, usize)> {
6954    let mut i = lo;
6955    macro_rules! ws {
6956        () => {
6957            while i < hi && matches!(s[i], b' ' | b'\t' | b'\n' | b'\r') {
6958                i += 1;
6959            }
6960        };
6961    }
6962
6963    let mut names = Vec::new();
6964    let mut columns = Vec::new();
6965    let mut rows = 0usize;
6966    loop {
6967        ws!();
6968        if i >= hi {
6969            break;
6970        }
6971        if s[i] != b'{' {
6972            return None;
6973        }
6974        i += 1;
6975        let mut field = 0usize;
6976        loop {
6977            ws!();
6978            if i < hi && s[i] == b'}' {
6979                i += 1;
6980                break;
6981            }
6982            if i >= hi || s[i] != b'"' {
6983                return None;
6984            }
6985            i += 1;
6986            let key_start = i;
6987            while i < hi && s[i] != b'"' {
6988                if s[i] == b'\\' {
6989                    return None;
6990                }
6991                i += 1;
6992            }
6993            if i >= hi {
6994                return None;
6995            }
6996            let key = std::str::from_utf8(&s[key_start..i]).ok()?;
6997            i += 1;
6998            ws!();
6999            if i >= hi || s[i] != b':' {
7000                return None;
7001            }
7002            i += 1;
7003            ws!();
7004            if i >= hi || !matches!(s[i], b'-' | b'0'..=b'9') {
7005                return None;
7006            }
7007            let value_start = i;
7008            if s[i] == b'-' {
7009                i += 1;
7010            }
7011            let mut any = false;
7012            while i < hi && matches!(s[i], b'0'..=b'9' | b'.' | b'e' | b'E' | b'+' | b'-') {
7013                any = true;
7014                i += 1;
7015            }
7016            if !any {
7017                return None;
7018            }
7019            let number = parse_json_record_number(&s[value_start..i])?;
7020            if rows == 0 {
7021                names.push(key.to_owned());
7022                let column = match number {
7023                    JsonRecordNumber::Int(value) => JsonNumericColumn::Int(vec![value]),
7024                    JsonRecordNumber::Float(value) => JsonNumericColumn::Float(vec![value]),
7025                };
7026                columns.push(column);
7027            } else {
7028                if names.get(field).is_none_or(|expected| expected != key) {
7029                    return None;
7030                }
7031                columns.get_mut(field)?.push_number(number);
7032            }
7033            field += 1;
7034            ws!();
7035            if i < hi && s[i] == b',' {
7036                i += 1;
7037                continue;
7038            }
7039        }
7040        if field != columns.len() {
7041            return None;
7042        }
7043        rows += 1;
7044        ws!();
7045        if i < hi && s[i] == b',' {
7046            i += 1;
7047            continue;
7048        }
7049        if i >= hi {
7050            break;
7051        }
7052        return None;
7053    }
7054    (!names.is_empty()).then_some((names, columns, rows))
7055}
7056
7057/// Parallel typed builder for homogeneous numeric records.  The standard
7058/// fp-bench records payload is ten all-Float64 columns, so this path retains
7059/// each worker's contiguous `Vec<f64>` as an immutable chunk and never boxes
7060/// the 10 million cells as `Scalar`.  Mixed numeric columns remain supported:
7061/// an Int64 chunk is promoted only when another chunk proves the column Float64.
7062fn try_read_json_records_numeric_parallel(input: &str) -> Result<Option<DataFrame>, IoError> {
7063    let s = input.as_bytes();
7064    let Some((body_start, body_end, commas)) = scan_json_numeric_record_boundaries(s) else {
7065        return Ok(None);
7066    };
7067    let record_count = commas.len() + 1;
7068    const PAR_MIN_RECORDS: usize = 50_000;
7069    const PAR_MIN_RECORDS_PER_WORKER: usize = 16_384;
7070    if record_count < PAR_MIN_RECORDS {
7071        return Ok(None);
7072    }
7073    let workers = fp_columnar::cached_available_parallelism()
7074        .min(16)
7075        .min(record_count / PAR_MIN_RECORDS_PER_WORKER)
7076        .max(1);
7077    if workers < 2 {
7078        return Ok(None);
7079    }
7080    let per_worker = record_count.div_ceil(workers);
7081    let mut ranges = Vec::with_capacity(workers);
7082    let mut start_record = 0usize;
7083    while start_record < record_count {
7084        let end_record = (start_record + per_worker).min(record_count);
7085        ranges.push((
7086            if start_record == 0 {
7087                body_start
7088            } else {
7089                commas[start_record - 1] + 1
7090            },
7091            if end_record == record_count {
7092                body_end
7093            } else {
7094                commas[end_record - 1]
7095            },
7096        ));
7097        start_record = end_record;
7098    }
7099    let parsed = std::thread::scope(|scope| {
7100        ranges
7101            .iter()
7102            .map(|&(lo, hi)| scope.spawn(move || parse_json_records_numeric_range(s, lo, hi)))
7103            .collect::<Vec<_>>()
7104            .into_iter()
7105            .map(|handle| handle.join().expect("json numeric parse thread"))
7106            .collect::<Vec<_>>()
7107    });
7108    let Some(mut parts) = parsed.into_iter().collect::<Option<Vec<_>>>() else {
7109        return Ok(None);
7110    };
7111    let names = parts[0].0.clone();
7112    if parts.iter().any(|part| part.0 != names) {
7113        return Ok(None);
7114    }
7115    let rows: usize = parts.iter().map(|part| part.2).sum();
7116    let mut out = BTreeMap::new();
7117    for (column_index, name) in names.iter().enumerate() {
7118        let is_float = parts
7119            .iter()
7120            .any(|part| matches!(part.1.get(column_index), Some(JsonNumericColumn::Float(_))));
7121        let column = if is_float {
7122            let mut chunks = Vec::with_capacity(parts.len());
7123            for part in &mut parts {
7124                let builder = std::mem::replace(
7125                    part.1
7126                        .get_mut(column_index)
7127                        .expect("validated column width"),
7128                    JsonNumericColumn::Float(Vec::new()),
7129                );
7130                let values = match builder {
7131                    JsonNumericColumn::Float(values) => values,
7132                    JsonNumericColumn::Int(values) => {
7133                        values.into_iter().map(|value| value as f64).collect()
7134                    }
7135                };
7136                let length = values.len();
7137                chunks.push((std::sync::Arc::from(values), 0, length));
7138            }
7139            Column::from_f64_all_valid_owned_chunks(chunks, rows)
7140        } else {
7141            let mut chunks = Vec::with_capacity(parts.len());
7142            for part in &mut parts {
7143                let builder = std::mem::replace(
7144                    part.1
7145                        .get_mut(column_index)
7146                        .expect("validated column width"),
7147                    JsonNumericColumn::Int(Vec::new()),
7148                );
7149                let JsonNumericColumn::Int(values) = builder else {
7150                    unreachable!("is_float checked every numeric chunk");
7151                };
7152                let length = values.len();
7153                chunks.push((std::sync::Arc::from(values), 0, length));
7154            }
7155            Column::from_i64_all_valid_chunks(chunks, rows)
7156        };
7157        out.insert(name.clone(), column);
7158    }
7159    let index = Index::from_i64((0..rows as i64).collect());
7160    let frame = DataFrame::new_with_column_order(index, out, names)?;
7161    Ok(Some(promote_synthetic_row_multiindex_if_present(&frame)?))
7162}
7163
7164/// Parse a flat records SEQUENCE `{...},{...},…` occupying `s[lo..hi]` (no surrounding
7165/// `[` `]`; `hi` is a record boundary or the closing `]` position) into per-column
7166/// `Vec<Scalar>` with first-seen column order and `Null` backfill for absent keys —
7167/// the exact same value handling as [`try_read_json_records_flat`] (numbers via
7168/// `serde_json::from_str::<Number>`), factored out so parallel workers can each parse a
7169/// byte range. Returns `None` on anything the flat scanner bails on. `rec` = row count.
7170fn parse_json_records_range(
7171    s: &[u8],
7172    lo: usize,
7173    hi: usize,
7174) -> Option<(Vec<String>, Vec<Vec<Scalar>>, usize)> {
7175    let mut i = lo;
7176    macro_rules! ws {
7177        () => {
7178            while i < hi && matches!(s[i], b' ' | b'\t' | b'\n' | b'\r') {
7179                i += 1;
7180            }
7181        };
7182    }
7183    let mut col_names: Vec<String> = Vec::new();
7184    let mut cols: Vec<Vec<Scalar>> = Vec::new();
7185    let mut last_seen: Vec<usize> = Vec::new();
7186    let mut name_to_idx: std::collections::HashMap<Vec<u8>, usize> =
7187        std::collections::HashMap::new();
7188    let mut rec: usize = 0;
7189    loop {
7190        ws!();
7191        if i >= hi {
7192            break;
7193        }
7194        if s[i] != b'{' {
7195            return None;
7196        }
7197        i += 1;
7198        loop {
7199            ws!();
7200            if i < hi && s[i] == b'}' {
7201                i += 1;
7202                break;
7203            }
7204            if i >= hi || s[i] != b'"' {
7205                return None;
7206            }
7207            i += 1;
7208            let kstart = i;
7209            while i < hi && s[i] != b'"' {
7210                if s[i] == b'\\' {
7211                    return None;
7212                }
7213                i += 1;
7214            }
7215            if i >= hi {
7216                return None;
7217            }
7218            let key = &s[kstart..i];
7219            i += 1;
7220            ws!();
7221            if i >= hi || s[i] != b':' {
7222                return None;
7223            }
7224            i += 1;
7225            ws!();
7226            if i >= hi {
7227                return None;
7228            }
7229            let scalar = match s[i] {
7230                b'-' | b'0'..=b'9' => {
7231                    let vstart = i;
7232                    if s[i] == b'-' {
7233                        i += 1;
7234                    }
7235                    let mut any = false;
7236                    while i < hi && matches!(s[i], b'0'..=b'9' | b'.' | b'e' | b'E' | b'+' | b'-') {
7237                        any = true;
7238                        i += 1;
7239                    }
7240                    if !any {
7241                        return None;
7242                    }
7243                    let Ok(numstr) = std::str::from_utf8(&s[vstart..i]) else {
7244                        return None;
7245                    };
7246                    match serde_json::from_str::<serde_json::Number>(numstr) {
7247                        Ok(num) => {
7248                            if let Some(v) = num.as_i64() {
7249                                Scalar::Int64(v)
7250                            } else if let Some(v) = num.as_f64() {
7251                                Scalar::Float64(v)
7252                            } else {
7253                                Scalar::Utf8(num.to_string())
7254                            }
7255                        }
7256                        Err(_) => return None,
7257                    }
7258                }
7259                b'"' => {
7260                    i += 1;
7261                    let vstart = i;
7262                    while i < hi && s[i] != b'"' {
7263                        if s[i] == b'\\' {
7264                            return None;
7265                        }
7266                        i += 1;
7267                    }
7268                    if i >= hi {
7269                        return None;
7270                    }
7271                    let raw = &s[vstart..i];
7272                    i += 1;
7273                    match std::str::from_utf8(raw) {
7274                        Ok(st) => Scalar::Utf8(st.to_owned()),
7275                        Err(_) => return None,
7276                    }
7277                }
7278                b't' if s[i..hi].starts_with(b"true") => {
7279                    i += 4;
7280                    Scalar::Bool(true)
7281                }
7282                b'f' if s[i..hi].starts_with(b"false") => {
7283                    i += 5;
7284                    Scalar::Bool(false)
7285                }
7286                b'n' if s[i..hi].starts_with(b"null") => {
7287                    i += 4;
7288                    Scalar::Null(NullKind::Null)
7289                }
7290                _ => return None,
7291            };
7292            let ci = match name_to_idx.get(key) {
7293                Some(&c) => c,
7294                None => {
7295                    let c = cols.len();
7296                    name_to_idx.insert(key.to_vec(), c);
7297                    col_names.push(String::from_utf8_lossy(key).into_owned());
7298                    let mut v: Vec<Scalar> = Vec::new();
7299                    v.resize(rec, Scalar::Null(NullKind::Null));
7300                    cols.push(v);
7301                    last_seen.push(usize::MAX);
7302                    c
7303                }
7304            };
7305            if last_seen[ci] == rec {
7306                *cols[ci].last_mut().expect("seen this record => non-empty") = scalar;
7307            } else {
7308                cols[ci].push(scalar);
7309                last_seen[ci] = rec;
7310            }
7311            ws!();
7312            if i < hi && s[i] == b',' {
7313                i += 1;
7314                continue;
7315            }
7316        }
7317        for c in 0..cols.len() {
7318            if last_seen[c] != rec {
7319                cols[c].push(Scalar::Null(NullKind::Null));
7320            }
7321        }
7322        rec += 1;
7323        ws!();
7324        if i < hi && s[i] == b',' {
7325            i += 1;
7326            continue;
7327        }
7328        if i >= hi {
7329            break;
7330        }
7331        return None;
7332    }
7333    Some((col_names, cols, rec))
7334}
7335
7336/// Parallel records fast path: split the array at record boundaries, parse the chunks
7337/// concurrently (each a `parse_json_records_range`), and merge. Returns `None` (defer to
7338/// the serial scanner / Value path) unless it is a large FULLY-HOMOGENEOUS records array
7339/// — every chunk must report the IDENTICAL first-seen `col_names`, which guarantees the
7340/// merged columns equal the serial scanner's output (concatenation preserves record
7341/// order; the serial first-seen order equals the shared per-chunk order). Bit-identical:
7342/// same per-value parsing, same column order, same `column_from_json_values` +
7343/// `promote_synthetic_row_multiindex_if_present` assembly.
7344fn try_read_json_records_flat_parallel(input: &str) -> Result<Option<DataFrame>, IoError> {
7345    let s = input.as_bytes();
7346    let Some((body_start, body_end, commas)) = scan_json_record_boundaries(s) else {
7347        return Ok(None);
7348    };
7349    let nrec = commas.len() + 1;
7350    const PAR_MIN_RECORDS: usize = 50_000;
7351    const PAR_MIN_RECORDS_PER_WORKER: usize = 16_384;
7352    if nrec < PAR_MIN_RECORDS {
7353        return Ok(None);
7354    }
7355    let workers = fp_columnar::cached_available_parallelism()
7356        .min(16)
7357        .min(nrec / PAR_MIN_RECORDS_PER_WORKER)
7358        .max(1);
7359    if workers < 2 {
7360        return Ok(None);
7361    }
7362    let per = nrec.div_ceil(workers);
7363    let mut ranges: Vec<(usize, usize)> = Vec::with_capacity(workers);
7364    let mut rstart = 0;
7365    while rstart < nrec {
7366        let rend = (rstart + per).min(nrec);
7367        let lo = if rstart == 0 {
7368            body_start
7369        } else {
7370            commas[rstart - 1] + 1
7371        };
7372        let hi = if rend == nrec {
7373            body_end
7374        } else {
7375            commas[rend - 1]
7376        };
7377        ranges.push((lo, hi));
7378        rstart = rend;
7379    }
7380    #[allow(clippy::type_complexity)]
7381    let parsed: Vec<Option<(Vec<String>, Vec<Vec<Scalar>>, usize)>> = std::thread::scope(|scope| {
7382        ranges
7383            .iter()
7384            .map(|&(lo, hi)| scope.spawn(move || parse_json_records_range(s, lo, hi)))
7385            .collect::<Vec<_>>()
7386            .into_iter()
7387            .map(|h| h.join().expect("json parse thread"))
7388            .collect()
7389    });
7390    let Some(parts) = parsed.into_iter().collect::<Option<Vec<_>>>() else {
7391        return Ok(None);
7392    };
7393    // Homogeneity gate: every chunk must share the FIRST chunk's exact column order.
7394    if parts[0].0.is_empty() {
7395        return Ok(None);
7396    }
7397    let names: Vec<String> = parts[0].0.clone();
7398    if parts.iter().any(|p| p.0 != names) {
7399        return Ok(None);
7400    }
7401    let k = names.len();
7402    let total_rows: usize = parts.iter().map(|p| p.2).sum();
7403    // Merge per column (chunk c's cols[j] IS column names[j] since orders match),
7404    // then build the typed columns in parallel (columns are independent).
7405    let mut merged: Vec<Vec<Scalar>> = (0..k).map(|_| Vec::with_capacity(total_rows)).collect();
7406    let mut parts = parts;
7407    for p in &mut parts {
7408        for (j, col) in p.1.iter_mut().enumerate() {
7409            merged[j].append(col);
7410        }
7411    }
7412    let built: Vec<Result<Column, IoError>> = std::thread::scope(|scope| {
7413        merged
7414            .into_iter()
7415            .map(|vals| scope.spawn(move || column_from_json_values(vals)))
7416            .collect::<Vec<_>>()
7417            .into_iter()
7418            .map(|h| h.join().expect("json column-build thread"))
7419            .collect()
7420    });
7421    let mut out = BTreeMap::new();
7422    for (name, col) in names.iter().zip(built) {
7423        out.insert(name.clone(), col?);
7424    }
7425    let index = Index::from_i64((0..total_rows as i64).collect());
7426    let frame = DataFrame::new_with_column_order(index, out, names)?;
7427    Ok(Some(promote_synthetic_row_multiindex_if_present(&frame)?))
7428}
7429
7430fn try_read_json_records_flat(input: &str) -> Result<Option<DataFrame>, IoError> {
7431    let s = input.as_bytes();
7432    let n = s.len();
7433    let mut i = 0usize;
7434    macro_rules! ws {
7435        () => {
7436            while i < n && matches!(s[i], b' ' | b'\t' | b'\n' | b'\r') {
7437                i += 1;
7438            }
7439        };
7440    }
7441    ws!();
7442    if i >= n || s[i] != b'[' {
7443        return Ok(None);
7444    }
7445    i += 1;
7446    ws!();
7447    if i < n && s[i] == b']' {
7448        // Empty array: defer to the generic path's canonical empty-frame handling.
7449        return Ok(None);
7450    }
7451
7452    let mut col_names: Vec<String> = Vec::new();
7453    let mut cols: Vec<Vec<Scalar>> = Vec::new();
7454    // `last_seen[c]` = the last record index that pushed a value for column c, so a
7455    // duplicate key in the same record overwrites and an absent key backfills Null.
7456    let mut last_seen: Vec<usize> = Vec::new();
7457    let mut name_to_idx: std::collections::HashMap<Vec<u8>, usize> =
7458        std::collections::HashMap::new();
7459    let mut rec: usize = 0;
7460
7461    loop {
7462        ws!();
7463        if i >= n || s[i] != b'{' {
7464            return Ok(None);
7465        }
7466        i += 1;
7467        loop {
7468            ws!();
7469            if i < n && s[i] == b'}' {
7470                i += 1;
7471                break;
7472            }
7473            // key: a plain (unescaped) JSON string
7474            if i >= n || s[i] != b'"' {
7475                return Ok(None);
7476            }
7477            i += 1;
7478            let kstart = i;
7479            while i < n && s[i] != b'"' {
7480                if s[i] == b'\\' {
7481                    return Ok(None);
7482                }
7483                i += 1;
7484            }
7485            if i >= n {
7486                return Ok(None);
7487            }
7488            let key = &s[kstart..i];
7489            i += 1;
7490            ws!();
7491            if i >= n || s[i] != b':' {
7492                return Ok(None);
7493            }
7494            i += 1;
7495            ws!();
7496            if i >= n {
7497                return Ok(None);
7498            }
7499            // value: number | string | true | false | null (else bail)
7500            let scalar = match s[i] {
7501                b'-' | b'0'..=b'9' => {
7502                    let vstart = i;
7503                    if s[i] == b'-' {
7504                        i += 1;
7505                    }
7506                    let mut any = false;
7507                    while i < n && matches!(s[i], b'0'..=b'9' | b'.' | b'e' | b'E' | b'+' | b'-') {
7508                        any = true;
7509                        i += 1;
7510                    }
7511                    if !any {
7512                        return Ok(None);
7513                    }
7514                    let Ok(numstr) = std::str::from_utf8(&s[vstart..i]) else {
7515                        return Ok(None);
7516                    };
7517                    // Parse via serde_json so as_i64/as_f64 classification is identical
7518                    // to the Value path (bit-identical, incl. the non-round-trip f64).
7519                    match serde_json::from_str::<serde_json::Number>(numstr) {
7520                        Ok(num) => {
7521                            if let Some(v) = num.as_i64() {
7522                                Scalar::Int64(v)
7523                            } else if let Some(v) = num.as_f64() {
7524                                Scalar::Float64(v)
7525                            } else {
7526                                Scalar::Utf8(num.to_string())
7527                            }
7528                        }
7529                        Err(_) => return Ok(None),
7530                    }
7531                }
7532                b'"' => {
7533                    i += 1;
7534                    let vstart = i;
7535                    while i < n && s[i] != b'"' {
7536                        if s[i] == b'\\' {
7537                            return Ok(None); // escaped string -> generic path
7538                        }
7539                        i += 1;
7540                    }
7541                    if i >= n {
7542                        return Ok(None);
7543                    }
7544                    let raw = &s[vstart..i];
7545                    i += 1;
7546                    match std::str::from_utf8(raw) {
7547                        Ok(st) => Scalar::Utf8(st.to_owned()),
7548                        Err(_) => return Ok(None),
7549                    }
7550                }
7551                b't' if s[i..].starts_with(b"true") => {
7552                    i += 4;
7553                    Scalar::Bool(true)
7554                }
7555                b'f' if s[i..].starts_with(b"false") => {
7556                    i += 5;
7557                    Scalar::Bool(false)
7558                }
7559                b'n' if s[i..].starts_with(b"null") => {
7560                    i += 4;
7561                    Scalar::Null(NullKind::Null)
7562                }
7563                _ => return Ok(None),
7564            };
7565            let ci = match name_to_idx.get(key) {
7566                Some(&c) => c,
7567                None => {
7568                    let c = cols.len();
7569                    name_to_idx.insert(key.to_vec(), c);
7570                    col_names.push(String::from_utf8_lossy(key).into_owned());
7571                    let mut v: Vec<Scalar> = Vec::new();
7572                    v.resize(rec, Scalar::Null(NullKind::Null)); // backfill prior records
7573                    cols.push(v);
7574                    last_seen.push(usize::MAX);
7575                    c
7576                }
7577            };
7578            if last_seen[ci] == rec {
7579                *cols[ci].last_mut().expect("seen this record => non-empty") = scalar;
7580            } else {
7581                cols[ci].push(scalar);
7582                last_seen[ci] = rec;
7583            }
7584            ws!();
7585            if i < n && s[i] == b',' {
7586                i += 1;
7587                continue;
7588            }
7589        }
7590        // Pad every column not present in this record with Null.
7591        for c in 0..cols.len() {
7592            if last_seen[c] != rec {
7593                cols[c].push(Scalar::Null(NullKind::Null));
7594            }
7595        }
7596        rec += 1;
7597        ws!();
7598        if i < n && s[i] == b',' {
7599            i += 1;
7600            continue;
7601        }
7602        if i < n && s[i] == b']' {
7603            i += 1;
7604            break;
7605        }
7606        return Ok(None);
7607    }
7608    ws!();
7609    if i != n {
7610        return Ok(None); // trailing garbage -> generic path
7611    }
7612
7613    let row_count = rec as i64;
7614    let mut out = BTreeMap::new();
7615    for (name, vals) in col_names.iter().zip(cols) {
7616        out.insert(name.clone(), column_from_json_values(vals)?);
7617    }
7618    let index = Index::from_i64((0..row_count).collect());
7619    let frame = DataFrame::new_with_column_order(index, out, col_names)?;
7620    Ok(Some(promote_synthetic_row_multiindex_if_present(&frame)?))
7621}
7622
7623pub fn read_json_str(input: &str, orient: JsonOrient) -> Result<DataFrame, IoError> {
7624    // Records fast path (must precede the Value-tree parse): scan a FLAT records
7625    // array directly into per-column Scalar builders, skipping the serde_json::Value
7626    // tree + per-record map allocation that dominates a large records JSON (a 260 MB
7627    // input is ~3.2s via the tree). `try_read_json_records_flat` returns `None` to
7628    // defer to the generic path below on any non-flat input, so the frame is
7629    // bit-identical for every input.
7630    if matches!(orient, JsonOrient::Records) {
7631        // Parallel typed numeric records first (large homogeneous numeric arrays), then
7632        // the general parallel/serial flat scanners, then the generic Value-tree path.
7633        // Every path either preserves the generic result or returns `None` to defer.
7634        if let Some(frame) = try_read_json_records_numeric_parallel(input)? {
7635            return Ok(frame);
7636        }
7637        if let Some(frame) = try_read_json_records_flat_parallel(input)? {
7638            return Ok(frame);
7639        }
7640        if let Some(frame) = try_read_json_records_flat(input)? {
7641            return Ok(frame);
7642        }
7643    }
7644    let parsed = parse_json_value_allowing_pandas_nan(input)?;
7645
7646    match orient {
7647        JsonOrient::Records => {
7648            let arr = parsed
7649                .as_array()
7650                .ok_or_else(|| IoError::JsonFormat("expected array for records orient".into()))?;
7651            if arr.is_empty() {
7652                return Ok(DataFrame::new(Index::new(Vec::new()), BTreeMap::new())?);
7653            }
7654
7655            // Collect column names from all records to handle heterogeneous keys
7656            let mut col_names_set = std::collections::BTreeSet::new();
7657            let mut col_names = Vec::new();
7658            for record in arr {
7659                let obj = record
7660                    .as_object()
7661                    .ok_or_else(|| IoError::JsonFormat("each record must be an object".into()))?;
7662                for key in obj.keys() {
7663                    if col_names_set.insert(key.clone()) {
7664                        col_names.push(key.clone());
7665                    }
7666                }
7667            }
7668
7669            let mut columns: BTreeMap<String, Vec<Scalar>> = BTreeMap::new();
7670            for name in &col_names {
7671                columns.insert(name.clone(), Vec::with_capacity(arr.len()));
7672            }
7673
7674            for record in arr {
7675                let obj = record
7676                    .as_object()
7677                    .ok_or_else(|| IoError::JsonFormat("each record must be an object".into()))?;
7678                for name in &col_names {
7679                    let val = obj.get(name).unwrap_or(&serde_json::Value::Null);
7680                    columns
7681                        .get_mut(name)
7682                        .ok_or_else(|| {
7683                            IoError::JsonFormat(format!(
7684                                "records orient missing column accumulator for '{name}'"
7685                            ))
7686                        })?
7687                        .push(json_value_to_scalar(val));
7688                }
7689            }
7690
7691            let row_count = arr.len() as i64;
7692            let mut out = BTreeMap::new();
7693            for (name, vals) in columns {
7694                out.insert(name, column_from_json_values(vals)?);
7695            }
7696            let index = Index::from_i64((0..row_count).collect());
7697            let frame = DataFrame::new_with_column_order(index, out, col_names)?;
7698            promote_synthetic_row_multiindex_if_present(&frame)
7699        }
7700        JsonOrient::Columns => {
7701            let obj = parsed
7702                .as_object()
7703                .ok_or_else(|| IoError::JsonFormat("expected object for columns orient".into()))?;
7704
7705            if obj.is_empty() {
7706                return Ok(DataFrame::new(Index::new(Vec::new()), BTreeMap::new())?);
7707            }
7708
7709            let mut raw_columns: BTreeMap<String, Vec<Scalar>> = BTreeMap::new();
7710            let mut column_order = Vec::with_capacity(obj.len());
7711            let mut index_labels = Vec::new();
7712            let mut index_lookup = BTreeMap::new();
7713            for (col_name, col_data) in obj {
7714                let col_obj = col_data.as_object().ok_or_else(|| {
7715                    IoError::JsonFormat("column data must be {index: val}".into())
7716                })?;
7717                let mut values = vec![Scalar::Null(NullKind::Null); index_labels.len()];
7718                for (label_key, val) in col_obj {
7719                    let label = json_key_to_index_label(label_key);
7720                    let row_idx = if let Some(&existing_idx) = index_lookup.get(&label) {
7721                        existing_idx
7722                    } else {
7723                        let next_idx = index_labels.len();
7724                        index_labels.push(label.clone());
7725                        index_lookup.insert(label, next_idx);
7726                        for existing_values in raw_columns.values_mut() {
7727                            existing_values.push(Scalar::Null(NullKind::Null));
7728                        }
7729                        values.push(Scalar::Null(NullKind::Null));
7730                        next_idx
7731                    };
7732                    if row_idx >= values.len() {
7733                        values.resize(index_labels.len(), Scalar::Null(NullKind::Null));
7734                    }
7735                    values[row_idx] = json_value_to_scalar(val);
7736                }
7737                if values.len() < index_labels.len() {
7738                    values.resize(index_labels.len(), Scalar::Null(NullKind::Null));
7739                }
7740                raw_columns.insert(col_name.clone(), values);
7741                column_order.push(col_name.clone());
7742            }
7743
7744            let mut out = BTreeMap::new();
7745            for (name, vals) in raw_columns {
7746                out.insert(name, column_from_json_values(vals)?);
7747            }
7748
7749            let frame =
7750                DataFrame::new_with_column_order(Index::new(index_labels), out, column_order)?;
7751            promote_synthetic_row_multiindex_if_present(&frame)
7752        }
7753        JsonOrient::Index => {
7754            let obj = parsed
7755                .as_object()
7756                .ok_or_else(|| IoError::JsonFormat("expected object for index orient".into()))?;
7757
7758            if obj.is_empty() {
7759                return Ok(DataFrame::new(Index::new(Vec::new()), BTreeMap::new())?);
7760            }
7761
7762            let mut index_labels = Vec::with_capacity(obj.len());
7763            let mut columns: BTreeMap<String, Vec<Scalar>> = BTreeMap::new();
7764            let mut column_order = Vec::new();
7765            let mut seen_columns = std::collections::HashSet::new();
7766
7767            for (row_label, row_data) in obj {
7768                let row_obj = row_data.as_object().ok_or_else(|| {
7769                    IoError::JsonFormat("index orient rows must be objects".into())
7770                })?;
7771
7772                let row_idx = index_labels.len();
7773
7774                // Pre-fill this row as null for all known columns, then overwrite present cells.
7775                for values in columns.values_mut() {
7776                    values.push(Scalar::Null(NullKind::Null));
7777                }
7778
7779                let parsed_label = row_label
7780                    .parse::<i64>()
7781                    .map(IndexLabel::Int64)
7782                    .unwrap_or_else(|_| IndexLabel::Utf8(row_label.clone()));
7783                index_labels.push(parsed_label);
7784
7785                for (col_name, value) in row_obj {
7786                    if seen_columns.insert(col_name.clone()) {
7787                        column_order.push(col_name.clone());
7788                    }
7789                    let scalar = json_value_to_scalar(value);
7790                    if let Some(values) = columns.get_mut(col_name) {
7791                        values[row_idx] = scalar;
7792                    } else {
7793                        let mut values = vec![Scalar::Null(NullKind::Null); row_idx + 1];
7794                        values[row_idx] = scalar;
7795                        columns.insert(col_name.clone(), values);
7796                    }
7797                }
7798            }
7799
7800            let mut out = BTreeMap::new();
7801            for (name, vals) in columns {
7802                out.insert(name, column_from_json_values(vals)?);
7803            }
7804            let frame =
7805                DataFrame::new_with_column_order(Index::new(index_labels), out, column_order)?;
7806            promote_synthetic_row_multiindex_if_present(&frame)
7807        }
7808        JsonOrient::Split => {
7809            let obj = parsed
7810                .as_object()
7811                .ok_or_else(|| IoError::JsonFormat("expected object for split orient".into()))?;
7812
7813            let col_names: Vec<String> = obj
7814                .get("columns")
7815                .and_then(|v| v.as_array())
7816                .ok_or_else(|| IoError::JsonFormat("split orient needs 'columns' array".into()))?
7817                .iter()
7818                .map(json_value_to_column_name)
7819                .collect();
7820            reject_duplicate_headers(&col_names)?;
7821
7822            let data = obj
7823                .get("data")
7824                .and_then(|v| v.as_array())
7825                .ok_or_else(|| IoError::JsonFormat("split orient needs 'data' array".into()))?;
7826
7827            let explicit_index = obj
7828                .get("index")
7829                .map(|v| {
7830                    v.as_array()
7831                        .ok_or_else(|| {
7832                            IoError::JsonFormat("split orient 'index' must be an array".into())
7833                        })
7834                        .map(|arr| {
7835                            arr.iter()
7836                                .map(json_value_to_index_label)
7837                                .collect::<Vec<_>>()
7838                        })
7839                })
7840                .transpose()?;
7841
7842            let mut columns: BTreeMap<String, Vec<Scalar>> = BTreeMap::new();
7843            for name in &col_names {
7844                columns.insert(name.clone(), Vec::with_capacity(data.len()));
7845            }
7846
7847            for (row_idx, row) in data.iter().enumerate() {
7848                let arr = row
7849                    .as_array()
7850                    .ok_or_else(|| IoError::JsonFormat("each data row must be an array".into()))?;
7851                if arr.len() != col_names.len() {
7852                    return Err(IoError::JsonFormat(format!(
7853                        "split orient row {row_idx} length ({}) does not match columns length ({})",
7854                        arr.len(),
7855                        col_names.len()
7856                    )));
7857                }
7858                for (i, name) in col_names.iter().enumerate() {
7859                    let val = arr.get(i).unwrap_or(&serde_json::Value::Null);
7860                    columns
7861                        .get_mut(name)
7862                        .ok_or_else(|| {
7863                            IoError::JsonFormat(format!(
7864                                "split orient missing column accumulator for '{name}'"
7865                            ))
7866                        })?
7867                        .push(json_value_to_scalar(val));
7868                }
7869            }
7870
7871            let row_count = data.len() as i64;
7872            let mut out = BTreeMap::new();
7873            for (name, vals) in columns {
7874                out.insert(name, column_from_json_values(vals)?);
7875            }
7876            let index = match explicit_index {
7877                Some(labels) => {
7878                    if labels.len() != row_count as usize {
7879                        return Err(IoError::JsonFormat(format!(
7880                            "split orient index length ({}) must match data row count ({row_count})",
7881                            labels.len()
7882                        )));
7883                    }
7884                    Index::new(labels)
7885                }
7886                None => Index::from_i64((0..row_count).collect()),
7887            };
7888            let frame = DataFrame::new_with_column_order(index, out, col_names)?;
7889            let frame = promote_synthetic_row_multiindex_if_present(&frame)?;
7890            let level_names = obj.get(JSON_SPLIT_INDEX_NAMES_KEY).and_then(|value| {
7891                serde_json::from_value::<Vec<Option<String>>>(value.clone()).ok()
7892            });
7893            match level_names {
7894                Some(names) => restore_row_multiindex_names(frame, &names),
7895                None => Ok(frame),
7896            }
7897        }
7898        JsonOrient::Values => {
7899            let rows = parsed
7900                .as_array()
7901                .ok_or_else(|| IoError::JsonFormat("expected array for values orient".into()))?;
7902
7903            if rows.is_empty() {
7904                return Ok(DataFrame::new(Index::new(Vec::new()), BTreeMap::new())?);
7905            }
7906
7907            let mut width = 0usize;
7908            for row in rows {
7909                let arr = row.as_array().ok_or_else(|| {
7910                    IoError::JsonFormat("each values row must be an array".into())
7911                })?;
7912                width = width.max(arr.len());
7913            }
7914
7915            let column_order: Vec<String> = (0..width).map(|idx| idx.to_string()).collect();
7916            let mut columns: BTreeMap<String, Vec<Scalar>> = column_order
7917                .iter()
7918                .cloned()
7919                .map(|name| (name, Vec::with_capacity(rows.len())))
7920                .collect();
7921
7922            for row in rows {
7923                let arr = row.as_array().ok_or_else(|| {
7924                    IoError::JsonFormat("each values row must be an array".into())
7925                })?;
7926                for (col_idx, name) in column_order.iter().enumerate() {
7927                    let val = arr.get(col_idx).unwrap_or(&serde_json::Value::Null);
7928                    columns
7929                        .get_mut(name)
7930                        .ok_or_else(|| {
7931                            IoError::JsonFormat(format!(
7932                                "values orient missing column accumulator for '{name}'"
7933                            ))
7934                        })?
7935                        .push(json_value_to_scalar(val));
7936                }
7937            }
7938
7939            let mut out = BTreeMap::new();
7940            for (name, vals) in columns {
7941                out.insert(name, column_from_json_values(vals)?);
7942            }
7943            let index = Index::from_i64((0..rows.len() as i64).collect());
7944            let frame = DataFrame::new_with_column_order(index, out, column_order)?;
7945            promote_synthetic_row_multiindex_if_present(&frame)
7946        }
7947    }
7948}
7949
7950/// Serde-tree implementation of `to_json(orient="records")` — the bit-exact
7951/// reference the typed fast path below must match. Kept as a named fn so the
7952/// differential test can compare the two directly.
7953fn write_json_records_serde(
7954    frame: &DataFrame,
7955    headers: &[String],
7956    column_float_promotions: &[bool],
7957) -> Result<String, IoError> {
7958    let row_count = frame.index().len();
7959    let mut records = Vec::with_capacity(row_count);
7960    for row_idx in 0..row_count {
7961        let mut obj = serde_json::Map::new();
7962        for (name, promote_int_to_float) in headers.iter().zip(column_float_promotions.iter()) {
7963            let val = frame
7964                .column(name)
7965                .and_then(|c| c.value(row_idx))
7966                .map(|value| scalar_to_json_with_column_promotion(value, *promote_int_to_float))
7967                .unwrap_or(serde_json::Value::Null);
7968            obj.insert(name.clone(), val);
7969        }
7970        records.push(serde_json::Value::Object(obj));
7971    }
7972    Ok(serde_json::to_string(&records)?)
7973}
7974
7975/// Streaming typed fast path for `to_json(orient="records")` over an all-valid
7976/// numeric/bool frame: writes JSON bytes straight into one `String` with no
7977/// per-row `serde_json::Map`, no per-cell `Scalar`/`Value` materialization, and
7978/// no per-row key re-allocation (the materialized serde tree is ~0.69x pandas;
7979/// this restores the win). Returns `None` — caller falls back to the serde
7980/// tree — for any column that is not all-valid `Int64` / all-valid `Float64` /
7981/// `Bool`, or that would take the int→float promotion branch.
7982///
7983/// Bit-identical to `write_json_records_serde`:
7984///   * keys are pre-serialized with `serde_json::to_string` (same escaping) and
7985///     emitted in column order (the `preserve_order` Map preserves insertion),
7986///   * `i64` via `append_i64_decimal` (the same decimal spelling itoa serde's
7987///     integer formatter produces),
7988///   * finite `f64` via serde's own `CompactFormatter::write_f64` (exact
7989///     exponent spelling, e.g. `1e+20`); non-finite `f64` emits `null`,
7990///     matching `scalar_to_json`'s NaN/Inf → `Value::Null` arm.
7991///
7992/// With `as_jsonl = true` the row objects are joined by `\n` with no enclosing
7993/// `[ ]` (the JSON Lines spelling `write_jsonl_string` produces); otherwise they
7994/// are wrapped as a `[..]` array (the `records` orient).
7995/// A typed all-valid value column view for the streaming JSON writers.
7996enum JCol<'a> {
7997    I(&'a [i64]),
7998    F(&'a [f64]),
7999    B(&'a [bool]),
8000    /// Datetime64 ns: serialized as epoch-MILLISECOND integers (`v / 1_000_000`),
8001    /// `NaT` (i64::MIN) → `null` — matching `scalar_to_json`.
8002    DtMs(&'a [i64]),
8003    /// All-valid contiguous Utf8: `(bytes, offsets)`, row r =
8004    /// `bytes[offsets[r]..offsets[r+1]]`, serialized as a JSON string.
8005    U(&'a [u8], &'a [usize]),
8006    /// NULLABLE contiguous Utf8: `(bytes, offsets, validity)`. A present row
8007    /// (validity.get(r)) serializes its span as a JSON string; a missing row
8008    /// serializes as `null` — so a string column WITH nulls no longer forces the
8009    /// whole frame onto the serde tree.
8010    UN(&'a [u8], &'a [usize], &'a fp_columnar::ValidityMask),
8011    /// NULLABLE Float64: `(data, validity)`. A present, finite row serializes via
8012    /// serde's `write_f64`; a missing row (validity-clear) OR a non-finite datum
8013    /// (NaN/±inf) serializes as `null` — matching `scalar_to_json` and the F arm.
8014    FN(&'a [f64], &'a fp_columnar::ValidityMask),
8015    /// NULLABLE Int64: `(data, validity)`. Present → decimal; missing → `null`.
8016    IN(&'a [i64], &'a fp_columnar::ValidityMask),
8017    /// NULLABLE Bool: `(data, validity)`. Present → `true`/`false`; missing → `null`.
8018    BN(&'a [bool], &'a fp_columnar::ValidityMask),
8019}
8020
8021/// Append `s` as a JSON string literal, byte-identical to `serde_json` (which
8022/// escapes only `"`, `\`, and the control bytes 0x00–0x1F; everything else,
8023/// including multi-byte UTF-8, passes through verbatim). The overwhelmingly
8024/// common no-escape case is a single `"` + raw + `"`; only a string that
8025/// actually contains an escape-worthy byte deopts to `serde_json::to_string`.
8026#[inline]
8027fn append_json_string(out: &mut String, s: &str) {
8028    if s.bytes().all(|b| b >= 0x20 && b != b'"' && b != b'\\') {
8029        out.push('"');
8030        out.push_str(s);
8031        out.push('"');
8032    } else {
8033        match serde_json::to_string(s) {
8034            Ok(escaped) => out.push_str(&escaped),
8035            Err(_) => out.push_str("\"\""),
8036        }
8037    }
8038}
8039
8040/// Extract every column as a typed slice plus its pre-serialized, escaped,
8041/// colon-terminated JSON key (column order = `preserve_order` insertion order).
8042/// Returns `None` — caller falls back to the serde tree — when a column has no
8043/// typed backing or the frame has a row multiindex.  Do not inspect
8044/// `column.values()` here: typed backings already encode a single logical dtype,
8045/// and materializing them as `Scalar`s would erase the streaming writer's main
8046/// allocation win before it writes its first byte.
8047fn extract_typed_value_columns(frame: &DataFrame) -> Option<(Vec<JCol<'_>>, Vec<String>)> {
8048    if frame.row_multiindex().is_some() {
8049        return None;
8050    }
8051    let headers: Vec<&String> = frame.column_names();
8052    let n = frame.index().len();
8053    let mut cols: Vec<JCol<'_>> = Vec::with_capacity(headers.len());
8054    let mut keys: Vec<String> = Vec::with_capacity(headers.len());
8055    for name in &headers {
8056        let column = frame.column(name.as_str())?;
8057        let jc = if let Some(s) = column.as_i64_slice() {
8058            (s.len() == n).then_some(JCol::I(s))?
8059        } else if let Some(s) = column.as_f64_slice() {
8060            (s.len() == n).then_some(JCol::F(s))?
8061        } else if let Some(s) = column.as_bool_slice() {
8062            (s.len() == n).then_some(JCol::B(s))?
8063        } else if let Some(s) = column.as_datetime64_slice() {
8064            // The slice exposes the raw ns including any NaT sentinel; a
8065            // validity-mask null (data slot ≠ NaT) would diverge from
8066            // `value()`'s `Scalar::Null`, so require no mask-nulls. An all-valid
8067            // `from_datetime64_values` backing keeps NaT AS DATA (validity stays
8068            // all-valid), and `append_typed_json_value` maps that sentinel → null
8069            // exactly like `scalar_to_json(Datetime64(NaT))`.
8070            if column.has_nulls() {
8071                return None;
8072            }
8073            (s.len() == n).then_some(JCol::DtMs(s))?
8074        } else if let Some((bytes, offsets)) = column.as_utf8_contiguous() {
8075            // as_utf8_contiguous already requires validity.all(), so every row
8076            // is a present `Scalar::Utf8` → JSON string (never null).
8077            (offsets.len() == n + 1).then_some(JCol::U(bytes, offsets))?
8078        } else if let Some((bytes, offsets)) = column.as_nullable_utf8_contiguous() {
8079            // Nullable contiguous Utf8: present rows serialize their span, missing
8080            // rows serialize as `null` — so one null-bearing string column no longer
8081            // forces the whole frame onto the serde tree.
8082            (offsets.len() == n + 1).then_some(JCol::UN(bytes, offsets, column.validity()))?
8083        } else if let Some((s, validity)) = column.as_f64_slice_with_validity() {
8084            // Nullable Float64: present+finite → number, missing/non-finite → null.
8085            (s.len() == n).then_some(JCol::FN(s, validity))?
8086        } else if let Some((s, validity)) = column.as_i64_slice_with_validity() {
8087            // Nullable Int64: present → integer, missing → null.
8088            (s.len() == n).then_some(JCol::IN(s, validity))?
8089        } else if let Some((s, validity)) = column.as_nullable_bool_slice() {
8090            // Nullable Bool: present → true/false, missing → null.
8091            (s.len() == n).then_some(JCol::BN(s, validity))?
8092        } else {
8093            return None;
8094        };
8095        cols.push(jc);
8096        let mut key = serde_json::to_string(name.as_str()).ok()?;
8097        key.push(':');
8098        keys.push(key);
8099    }
8100    Some((cols, keys))
8101}
8102
8103/// Append a finite JSON float with the exact shortest-round-trip spelling
8104/// `serde_json` uses, but without constructing a formatter or a temporary byte
8105/// vector per cell. `zmij::Buffer` owns its fixed stack scratch and is reused
8106/// for the complete JSON document.
8107#[inline]
8108fn append_json_finite_f64(out: &mut String, value: f64, float_buffer: &mut zmij::Buffer) {
8109    out.push_str(float_buffer.format_finite(value));
8110}
8111
8112/// Append cell `(col, r)` as a JSON value, byte-identical to serde:
8113/// `i64` via `append_i64_decimal`, finite `f64` via serde's Zmij formatter,
8114/// non-finite `f64` as `null` (matching `scalar_to_json`), `bool` as
8115/// `true`/`false`. `float_buffer` is a reusable direct-byte formatter scratch.
8116#[inline]
8117fn append_typed_json_value(
8118    out: &mut String,
8119    col: &JCol<'_>,
8120    r: usize,
8121    float_buffer: &mut zmij::Buffer,
8122) {
8123    match col {
8124        JCol::I(s) => append_i64_decimal(out, s[r]),
8125        JCol::F(s) => {
8126            let v = s[r];
8127            if v.is_finite() {
8128                append_json_finite_f64(out, v, float_buffer);
8129            } else {
8130                out.push_str("null");
8131            }
8132        }
8133        JCol::B(s) => out.push_str(if s[r] { "true" } else { "false" }),
8134        JCol::DtMs(s) => {
8135            let v = s[r];
8136            // i64::MIN is the Datetime64 NaT sentinel.
8137            if v == i64::MIN {
8138                out.push_str("null");
8139            } else {
8140                append_i64_decimal(out, v / 1_000_000);
8141            }
8142        }
8143        JCol::U(bytes, offsets) => {
8144            let field = &bytes[offsets[r]..offsets[r + 1]];
8145            // SAFETY-FREE: contiguous Utf8 backing is valid UTF-8.
8146            append_json_string(out, std::str::from_utf8(field).unwrap_or(""));
8147        }
8148        // Nullable Utf8: a present row renders its span like JCol::U; a missing row
8149        // renders `null` — matching the serde-tree fallback's `Scalar::Null` → null.
8150        JCol::UN(bytes, offsets, validity) => {
8151            if validity.get(r) {
8152                let field = &bytes[offsets[r]..offsets[r + 1]];
8153                append_json_string(out, std::str::from_utf8(field).unwrap_or(""));
8154            } else {
8155                out.push_str("null");
8156            }
8157        }
8158        // Nullable Float64: a present finite row renders like JCol::F (serde's
8159        // write_f64); a missing row (validity-clear) OR a non-finite datum
8160        // (NaN/±inf — no JSON representation, matching scalar_to_json) renders `null`.
8161        JCol::FN(s, validity) => {
8162            let v = s[r];
8163            if validity.get(r) && v.is_finite() {
8164                append_json_finite_f64(out, v, float_buffer);
8165            } else {
8166                out.push_str("null");
8167            }
8168        }
8169        // Nullable Int64: present ⇒ decimal (== JCol::I); missing ⇒ `null`.
8170        JCol::IN(s, validity) => {
8171            if validity.get(r) {
8172                append_i64_decimal(out, s[r]);
8173            } else {
8174                out.push_str("null");
8175            }
8176        }
8177        // Nullable Bool: present ⇒ true/false (== JCol::B); missing ⇒ `null`.
8178        JCol::BN(s, validity) => {
8179            if validity.get(r) {
8180                out.push_str(if s[r] { "true" } else { "false" });
8181            } else {
8182                out.push_str("null");
8183            }
8184        }
8185    }
8186}
8187
8188fn try_write_json_records_typed(frame: &DataFrame, as_jsonl: bool) -> Option<String> {
8189    let (cols, keys) = extract_typed_value_columns(frame)?;
8190    let n = frame.index().len();
8191    let mut out = String::with_capacity(
8192        n.saturating_mul(cols.len().max(1))
8193            .saturating_mul(12)
8194            .saturating_add(16),
8195    );
8196    if !as_jsonl {
8197        out.push('[');
8198    }
8199    let mut float_buffer = zmij::Buffer::new();
8200    for r in 0..n {
8201        if r > 0 {
8202            out.push(if as_jsonl { '\n' } else { ',' });
8203        }
8204        out.push('{');
8205        for (c, col) in cols.iter().enumerate() {
8206            if c > 0 {
8207                out.push(',');
8208            }
8209            out.push_str(&keys[c]);
8210            append_typed_json_value(&mut out, col, r, &mut float_buffer);
8211        }
8212        out.push('}');
8213    }
8214    if !as_jsonl {
8215        out.push(']');
8216    }
8217    Some(out)
8218}
8219
8220/// Streaming typed fast path for `to_json(orient="columns")` — `{col: {idx:
8221/// val}}`. The serde tree re-stringifies the index-label key for EVERY cell of
8222/// EVERY column (n×k) and builds a nested Map per column; this is ~0.39x pandas.
8223/// Here the n index-label keys are pre-serialized ONCE and reused across every
8224/// column. Returns `None` (serde fallback) unless the index is unique (so no
8225/// inner key collides — the serde path errors on a duplicate index key, which
8226/// this fast path must not silently swallow) and every column is typed.
8227///
8228/// Bit-identical to the serde `Columns` arm: outer keys in column order, inner
8229/// keys in index-label order (both `preserve_order`), inner keys spelled by
8230/// `index_label_json_key` then serde-quoted, values via `append_typed_json_value`.
8231/// Pre-serialize the n index-label JSON object keys ONCE into a single
8232/// contiguous buffer (+ offsets), each carrying its quotes and trailing `:`.
8233/// For an all-Int64 unique index the keys are hand-rolled `"` + itoa + `":`
8234/// straight off `int64_label_values()` — no `labels()` IndexLabel
8235/// materialization and no per-key `String` alloc. Returns `None` (caller falls
8236/// back to the serde tree) if any serialized key collides (the serde path
8237/// errors on a duplicate index-label key, which the fast path must not swallow).
8238/// Shared by the `columns` and `index` orients (the index keys are the
8239/// repeated-per-column / repeated-per-row keys respectively).
8240fn build_json_index_key_buffer(frame: &DataFrame) -> Option<(String, Vec<usize>)> {
8241    let n = frame.index().len();
8242    let mut keybuf = String::with_capacity(n.saturating_mul(10).saturating_add(8));
8243    let mut keyoff: Vec<usize> = Vec::with_capacity(n + 1);
8244    keyoff.push(0);
8245    let mut keys_known_unique = false;
8246    if frame.index().is_unique()
8247        && let Some(vals) = frame.index().int64_label_values()
8248        && vals.len() == n
8249    {
8250        // Distinct i64 → distinct decimal keys, and
8251        // `serde_json::to_string(v.to_string())` is exactly `"<decimal>"`, so the
8252        // hand-rolled spelling is byte-identical and needs no dedup.
8253        for &v in vals.iter() {
8254            keybuf.push('"');
8255            append_i64_decimal(&mut keybuf, v);
8256            keybuf.push_str("\":");
8257            keyoff.push(keybuf.len());
8258        }
8259        keys_known_unique = true;
8260    } else {
8261        for label in frame.index().labels() {
8262            let k = serde_json::to_string(&index_label_json_key(label)).ok()?;
8263            keybuf.push_str(&k);
8264            keybuf.push(':');
8265            keyoff.push(keybuf.len());
8266        }
8267    }
8268    if !keys_known_unique {
8269        let mut seen = std::collections::HashSet::with_capacity(n);
8270        for r in 0..n {
8271            if !seen.insert(&keybuf[keyoff[r]..keyoff[r + 1]]) {
8272                return None;
8273            }
8274        }
8275    }
8276    Some((keybuf, keyoff))
8277}
8278
8279fn try_write_json_columns_typed(frame: &DataFrame) -> Option<String> {
8280    let (cols, colkeys) = extract_typed_value_columns(frame)?;
8281    let n = frame.index().len();
8282    // The n inner index-label keys, pre-serialized once, reused across every
8283    // column — vs the serde path's n×k re-stringification.
8284    let (keybuf, keyoff) = build_json_index_key_buffer(frame)?;
8285
8286    let mut out = String::with_capacity(
8287        n.saturating_mul(cols.len().max(1))
8288            .saturating_mul(16)
8289            .saturating_add(16),
8290    );
8291    out.push('{');
8292    let mut float_buffer = zmij::Buffer::new();
8293    for (c, col) in cols.iter().enumerate() {
8294        if c > 0 {
8295            out.push(',');
8296        }
8297        out.push_str(&colkeys[c]);
8298        out.push('{');
8299        for r in 0..n {
8300            if r > 0 {
8301                out.push(',');
8302            }
8303            out.push_str(&keybuf[keyoff[r]..keyoff[r + 1]]);
8304            append_typed_json_value(&mut out, col, r, &mut float_buffer);
8305        }
8306        out.push('}');
8307    }
8308    out.push('}');
8309    Some(out)
8310}
8311
8312/// Streaming typed fast path for `to_json(orient="index")` — `{idx: {col:
8313/// val}}`, the transpose of `columns`. The serde tree builds a `serde_json::Map`
8314/// per ROW plus an index-label outer key per row (~0.63x pandas). Here the n
8315/// outer index-label keys are pre-serialized once (contiguous buffer) and the k
8316/// inner column keys are reused every row. Bit-identical to the serde `Index`
8317/// arm: outer keys in row order, inner keys in column order (both
8318/// `preserve_order`), same key spellings and value formatting; bails (→ serde
8319/// path, which errors) on a duplicate index-label key or any non-typed column.
8320fn try_write_json_index_typed(frame: &DataFrame) -> Option<String> {
8321    let (cols, colkeys) = extract_typed_value_columns(frame)?;
8322    let n = frame.index().len();
8323    // The n outer index-label keys, pre-serialized once.
8324    let (keybuf, keyoff) = build_json_index_key_buffer(frame)?;
8325
8326    let mut out = String::with_capacity(
8327        n.saturating_mul(cols.len().max(1))
8328            .saturating_mul(16)
8329            .saturating_add(16),
8330    );
8331    out.push('{');
8332    let mut float_buffer = zmij::Buffer::new();
8333    for r in 0..n {
8334        if r > 0 {
8335            out.push(',');
8336        }
8337        out.push_str(&keybuf[keyoff[r]..keyoff[r + 1]]);
8338        out.push('{');
8339        for (c, col) in cols.iter().enumerate() {
8340            if c > 0 {
8341                out.push(',');
8342            }
8343            out.push_str(&colkeys[c]);
8344            append_typed_json_value(&mut out, col, r, &mut float_buffer);
8345        }
8346        out.push('}');
8347    }
8348    out.push('}');
8349    Some(out)
8350}
8351
8352/// Append the row-major `[[v, v], ...]` array of all cells (column order per
8353/// row) to `out` — the shared body of the `values` orient and the `data`
8354/// section of the `split` orient.
8355fn append_json_row_arrays(out: &mut String, cols: &[JCol<'_>], n: usize) {
8356    out.push('[');
8357    let mut float_buffer = zmij::Buffer::new();
8358    for r in 0..n {
8359        if r > 0 {
8360            out.push(',');
8361        }
8362        out.push('[');
8363        for (c, col) in cols.iter().enumerate() {
8364            if c > 0 {
8365                out.push(',');
8366            }
8367            append_typed_json_value(out, col, r, &mut float_buffer);
8368        }
8369        out.push(']');
8370    }
8371    out.push(']');
8372}
8373
8374/// Streaming typed fast path for `to_json(orient="values")` — `[[v, v], ...]`,
8375/// row-major arrays with no keys (the simplest orient). Bit-identical to the
8376/// serde `Values` arm. Bails (→ serde) on any non-typed column.
8377fn try_write_json_values_typed(frame: &DataFrame) -> Option<String> {
8378    let (cols, _keys) = extract_typed_value_columns(frame)?;
8379    let n = frame.index().len();
8380    let mut out = String::with_capacity(
8381        n.saturating_mul(cols.len().max(1))
8382            .saturating_mul(12)
8383            .saturating_add(16),
8384    );
8385    append_json_row_arrays(&mut out, &cols, n);
8386    Some(out)
8387}
8388
8389/// Streaming typed fast path for `to_json(orient="split")` —
8390/// `{"columns":[...],"index":[...],"data":[[...]]}`. The `data` section is the
8391/// same row-major shape as `values` (the bulk); the `columns`/`index` header
8392/// arrays are tiny. Bit-identical to the serde `Split` arm: `columns` is the
8393/// header strings, `index` is each label via `index_label_to_json` (bare ints
8394/// for an Int64 index, hand-rolled here), `data` via `append_json_row_arrays`,
8395/// and the object keys are in insertion order (columns, index, data) under
8396/// `preserve_order`. Bails (→ serde) on any non-typed column.
8397fn try_write_json_split_typed(frame: &DataFrame) -> Option<String> {
8398    let (cols, _keys) = extract_typed_value_columns(frame)?;
8399    let n = frame.index().len();
8400    let headers = frame.column_names();
8401    // columns array: serde over the (few) header strings — same escaping as the
8402    // serde path's `Vec<Value::String>`.
8403    let cols_json = serde_json::to_string(&headers).ok()?;
8404    // index array: bare JSON values (NOT object keys), `index_label_to_json` per
8405    // label — hand-rolled itoa for the common all-Int64 index, serde otherwise.
8406    let mut idx_json = String::with_capacity(n.saturating_mul(8).saturating_add(2));
8407    idx_json.push('[');
8408    if let Some(vals) = frame.index().int64_label_values()
8409        && vals.len() == n
8410    {
8411        for (i, &v) in vals.iter().enumerate() {
8412            if i > 0 {
8413                idx_json.push(',');
8414            }
8415            append_i64_decimal(&mut idx_json, v);
8416        }
8417    } else {
8418        for (i, label) in frame.index().labels().iter().enumerate() {
8419            if i > 0 {
8420                idx_json.push(',');
8421            }
8422            idx_json.push_str(&serde_json::to_string(&index_label_to_json(label)).ok()?);
8423        }
8424    }
8425    idx_json.push(']');
8426
8427    let mut out = String::with_capacity(
8428        n.saturating_mul(cols.len().max(1))
8429            .saturating_mul(12)
8430            .saturating_add(idx_json.len() + cols_json.len() + 48),
8431    );
8432    out.push_str("{\"columns\":");
8433    out.push_str(&cols_json);
8434    out.push_str(",\"index\":");
8435    out.push_str(&idx_json);
8436    out.push_str(",\"data\":");
8437    append_json_row_arrays(&mut out, &cols, n);
8438    out.push('}');
8439    Some(out)
8440}
8441
8442pub fn write_json_string(frame: &DataFrame, orient: JsonOrient) -> Result<String, IoError> {
8443    if let Some(row_multiindex) = frame.row_multiindex()
8444        && orient != JsonOrient::Values
8445    {
8446        let materialized = materialize_synthetic_row_multiindex_columns(frame)?;
8447        let mut out = write_json_string(&materialized, orient)?;
8448        // The level values ride along as synthetic columns; the level NAMES
8449        // need their own slot, and only `split` has an object to put it in.
8450        if orient == JsonOrient::Split && out.ends_with('}') {
8451            let names = serde_json::to_string(&row_multiindex.names().to_vec())?;
8452            out.pop();
8453            out.push_str(",\"");
8454            out.push_str(JSON_SPLIT_INDEX_NAMES_KEY);
8455            out.push_str("\":");
8456            out.push_str(&names);
8457            out.push('}');
8458        }
8459        return Ok(out);
8460    }
8461
8462    let row_count = frame.index().len();
8463
8464    match orient {
8465        JsonOrient::Records => {
8466            // Typed streaming fast path for all-valid numeric/bool frames; falls
8467            // back to the serde tree below on anything it can't handle.
8468            if let Some(s) = try_write_json_records_typed(frame, false) {
8469                return Ok(s);
8470            }
8471            let headers: Vec<String> = frame.column_names().into_iter().cloned().collect();
8472            let column_float_promotions = headers
8473                .iter()
8474                .map(|name| {
8475                    frame.column(name).is_some_and(|column| {
8476                        column_promotes_int_json_values_to_float(column.values())
8477                    })
8478                })
8479                .collect::<Vec<_>>();
8480            write_json_records_serde(frame, &headers, &column_float_promotions)
8481        }
8482        JsonOrient::Columns => {
8483            // Typed streaming fast path; falls back to the serde tree below.
8484            if let Some(s) = try_write_json_columns_typed(frame) {
8485                return Ok(s);
8486            }
8487            let headers: Vec<String> = frame.column_names().into_iter().cloned().collect();
8488            let column_float_promotions = headers
8489                .iter()
8490                .map(|name| {
8491                    frame.column(name).is_some_and(|column| {
8492                        column_promotes_int_json_values_to_float(column.values())
8493                    })
8494                })
8495                .collect::<Vec<_>>();
8496            let mut outer = serde_json::Map::new();
8497            for (name, promote_int_to_float) in headers.iter().zip(column_float_promotions.iter()) {
8498                let mut col_obj = serde_json::Map::new();
8499                if let Some(col) = frame.column(name) {
8500                    for (label, val) in frame.index().labels().iter().zip(col.values()) {
8501                        let key = index_label_json_key(label);
8502                        if col_obj
8503                            .insert(
8504                                key.clone(),
8505                                scalar_to_json_with_column_promotion(val, *promote_int_to_float),
8506                            )
8507                            .is_some()
8508                        {
8509                            return Err(IoError::JsonFormat(format!(
8510                                "columns orient cannot encode duplicate index label key: {key}"
8511                            )));
8512                        }
8513                    }
8514                }
8515                outer.insert(name.clone(), serde_json::Value::Object(col_obj));
8516            }
8517            Ok(serde_json::to_string(&serde_json::Value::Object(outer))?)
8518        }
8519        JsonOrient::Index => {
8520            // Typed streaming fast path; falls back to the serde tree below.
8521            if let Some(s) = try_write_json_index_typed(frame) {
8522                return Ok(s);
8523            }
8524            let headers: Vec<String> = frame.column_names().into_iter().cloned().collect();
8525            let column_float_promotions = headers
8526                .iter()
8527                .map(|name| {
8528                    frame.column(name).is_some_and(|column| {
8529                        column_promotes_int_json_values_to_float(column.values())
8530                    })
8531                })
8532                .collect::<Vec<_>>();
8533            let mut outer = serde_json::Map::new();
8534            for row_idx in 0..row_count {
8535                let mut row_obj = serde_json::Map::new();
8536                for (name, promote_int_to_float) in
8537                    headers.iter().zip(column_float_promotions.iter())
8538                {
8539                    let val = frame
8540                        .column(name)
8541                        .and_then(|c| c.value(row_idx))
8542                        .map(|value| {
8543                            scalar_to_json_with_column_promotion(value, *promote_int_to_float)
8544                        })
8545                        .unwrap_or(serde_json::Value::Null);
8546                    row_obj.insert(name.clone(), val);
8547                }
8548
8549                let row_label = index_label_json_key(&frame.index().labels()[row_idx]);
8550                if outer
8551                    .insert(row_label.clone(), serde_json::Value::Object(row_obj))
8552                    .is_some()
8553                {
8554                    return Err(IoError::JsonFormat(format!(
8555                        "index orient cannot encode duplicate index label key: {row_label}"
8556                    )));
8557                }
8558            }
8559            Ok(serde_json::to_string(&serde_json::Value::Object(outer))?)
8560        }
8561        JsonOrient::Split => {
8562            // Typed streaming fast path; falls back to the serde tree below.
8563            if let Some(s) = try_write_json_split_typed(frame) {
8564                return Ok(s);
8565            }
8566            let headers: Vec<String> = frame.column_names().into_iter().cloned().collect();
8567            let column_float_promotions = headers
8568                .iter()
8569                .map(|name| {
8570                    frame.column(name).is_some_and(|column| {
8571                        column_promotes_int_json_values_to_float(column.values())
8572                    })
8573                })
8574                .collect::<Vec<_>>();
8575            let col_array: Vec<serde_json::Value> = headers
8576                .iter()
8577                .map(|h| serde_json::Value::String(h.clone()))
8578                .collect();
8579            let index_array: Vec<serde_json::Value> = frame
8580                .index()
8581                .labels()
8582                .iter()
8583                .map(index_label_to_json)
8584                .collect();
8585
8586            let mut data = Vec::with_capacity(row_count);
8587            for row_idx in 0..row_count {
8588                let row: Vec<serde_json::Value> = headers
8589                    .iter()
8590                    .zip(column_float_promotions.iter())
8591                    .map(|(name, promote_int_to_float)| {
8592                        frame
8593                            .column(name)
8594                            .and_then(|c| c.value(row_idx))
8595                            .map(|value| {
8596                                scalar_to_json_with_column_promotion(value, *promote_int_to_float)
8597                            })
8598                            .unwrap_or(serde_json::Value::Null)
8599                    })
8600                    .collect();
8601                data.push(serde_json::Value::Array(row));
8602            }
8603
8604            let mut obj = serde_json::Map::new();
8605            obj.insert("columns".into(), serde_json::Value::Array(col_array));
8606            obj.insert("index".into(), serde_json::Value::Array(index_array));
8607            obj.insert("data".into(), serde_json::Value::Array(data));
8608            Ok(serde_json::to_string(&serde_json::Value::Object(obj))?)
8609        }
8610        JsonOrient::Values => {
8611            // Typed streaming fast path; falls back to the serde tree below.
8612            if let Some(s) = try_write_json_values_typed(frame) {
8613                return Ok(s);
8614            }
8615            let headers: Vec<String> = frame.column_names().into_iter().cloned().collect();
8616            let column_float_promotions = headers
8617                .iter()
8618                .map(|name| {
8619                    frame.column(name).is_some_and(|column| {
8620                        column_promotes_int_json_values_to_float(column.values())
8621                    })
8622                })
8623                .collect::<Vec<_>>();
8624            let mut data = Vec::with_capacity(row_count);
8625            for row_idx in 0..row_count {
8626                let row: Vec<serde_json::Value> = headers
8627                    .iter()
8628                    .zip(column_float_promotions.iter())
8629                    .map(|(name, promote_int_to_float)| {
8630                        frame
8631                            .column(name)
8632                            .and_then(|c| c.value(row_idx))
8633                            .map(|value| {
8634                                scalar_to_json_with_column_promotion(value, *promote_int_to_float)
8635                            })
8636                            .unwrap_or(serde_json::Value::Null)
8637                    })
8638                    .collect();
8639                data.push(serde_json::Value::Array(row));
8640            }
8641            Ok(serde_json::to_string(&serde_json::Value::Array(data))?)
8642        }
8643    }
8644}
8645
8646// ── File-based JSON ────────────────────────────────────────────────────
8647
8648pub fn read_json(path: &Path, orient: JsonOrient) -> Result<DataFrame, IoError> {
8649    let content = std::fs::read_to_string(path)?;
8650    read_json_str(&content, orient)
8651}
8652
8653pub fn write_json(frame: &DataFrame, path: &Path, orient: JsonOrient) -> Result<(), IoError> {
8654    let content = write_json_string(frame, orient)?;
8655    std::fs::write(path, content)?;
8656    Ok(())
8657}
8658
8659// ── File-based Pickle ──────────────────────────────────────────────────
8660
8661/// Read a DataFrame from a Pickle file.
8662pub fn read_pickle(path: &Path) -> Result<DataFrame, IoError> {
8663    read_pickle_with_options(path, &PickleReadOptions::default())
8664}
8665
8666/// Read a DataFrame from a Pickle file with options.
8667pub fn read_pickle_with_options(
8668    path: &Path,
8669    options: &PickleReadOptions,
8670) -> Result<DataFrame, IoError> {
8671    let content = std::fs::read(path)?;
8672    read_pickle_bytes_with_options(&content, options)
8673}
8674
8675/// Write a DataFrame to a Pickle file.
8676pub fn write_pickle(frame: &DataFrame, path: &Path) -> Result<(), IoError> {
8677    write_pickle_with_options(frame, path, &PickleWriteOptions::default())
8678}
8679
8680/// Write a DataFrame to a Pickle file with options.
8681pub fn write_pickle_with_options(
8682    frame: &DataFrame,
8683    path: &Path,
8684    options: &PickleWriteOptions,
8685) -> Result<(), IoError> {
8686    let content = write_pickle_bytes_with_options(frame, options)?;
8687    std::fs::write(path, content)?;
8688    Ok(())
8689}
8690
8691// ── File-based HDF5 ────────────────────────────────────────────────────
8692
8693/// Read a DataFrame from the default HDF5 key.
8694pub fn read_hdf(path: &Path) -> Result<DataFrame, IoError> {
8695    read_hdf_with_options(path, &HdfReadOptions::default())
8696}
8697
8698/// Read a DataFrame from an explicit HDF5 key.
8699pub fn read_hdf_key(path: &Path, key: &str) -> Result<DataFrame, IoError> {
8700    read_hdf_with_options(
8701        path,
8702        &HdfReadOptions {
8703            key: key.to_owned(),
8704        },
8705    )
8706}
8707
8708/// Read a DataFrame from an HDF5 file with options.
8709#[cfg(feature = "hdf5")]
8710pub fn read_hdf_with_options(path: &Path, options: &HdfReadOptions) -> Result<DataFrame, IoError> {
8711    let key = normalize_hdf5_key(&options.key)?;
8712    let dataset_path = hdf5_payload_path(&key);
8713    let file = Hdf5File::open(path).map_err(hdf5_error)?;
8714    let dataset = file.dataset(&dataset_path).map_err(|err| {
8715        IoError::Hdf5(format!(
8716            "missing FrankenPandas payload dataset '{dataset_path}': {err}"
8717        ))
8718    })?;
8719    let payload = dataset.read_raw::<u8>().map_err(hdf5_error)?;
8720    read_pickle_bytes(&payload).map_err(|err| {
8721        IoError::Hdf5(format!(
8722            "invalid FrankenPandas payload at key '{key}': {err}"
8723        ))
8724    })
8725}
8726
8727/// Read a DataFrame from an HDF5 file with options.
8728#[cfg(not(feature = "hdf5"))]
8729pub fn read_hdf_with_options(
8730    _path: &Path,
8731    _options: &HdfReadOptions,
8732) -> Result<DataFrame, IoError> {
8733    hdf5_feature_disabled()
8734}
8735
8736/// Write a DataFrame to the default HDF5 key.
8737pub fn write_hdf(frame: &DataFrame, path: &Path) -> Result<(), IoError> {
8738    write_hdf_with_options(frame, path, &HdfWriteOptions::default())
8739}
8740
8741/// Write a Series to the default HDF5 key.
8742///
8743/// Converts the Series to a single-column DataFrame and writes it.
8744pub fn write_hdf_series(series: &Series, path: &Path) -> Result<(), IoError> {
8745    let frame = series
8746        .to_frame(Some(series.name()))
8747        .map_err(|e| IoError::Hdf5(format!("Series to DataFrame conversion: {e}")))?;
8748    write_hdf(&frame, path)
8749}
8750
8751/// Write a Series to an explicit HDF5 key.
8752pub fn write_hdf_series_key(series: &Series, path: &Path, key: &str) -> Result<(), IoError> {
8753    let frame = series
8754        .to_frame(Some(series.name()))
8755        .map_err(|e| IoError::Hdf5(format!("Series to DataFrame conversion: {e}")))?;
8756    write_hdf_key(&frame, path, key)
8757}
8758
8759/// Write a DataFrame to an explicit HDF5 key.
8760pub fn write_hdf_key(frame: &DataFrame, path: &Path, key: &str) -> Result<(), IoError> {
8761    write_hdf_with_options(
8762        frame,
8763        path,
8764        &HdfWriteOptions {
8765            key: key.to_owned(),
8766        },
8767    )
8768}
8769
8770/// Write a DataFrame to an HDF5 file with options.
8771#[cfg(feature = "hdf5")]
8772pub fn write_hdf_with_options(
8773    frame: &DataFrame,
8774    path: &Path,
8775    options: &HdfWriteOptions,
8776) -> Result<(), IoError> {
8777    let key = normalize_hdf5_key(&options.key)?;
8778    let payload = write_pickle_bytes(frame)?;
8779    let file = Hdf5File::create(path).map_err(hdf5_error)?;
8780    let group = file.create_group(&key).map_err(hdf5_error)?;
8781    group
8782        .new_dataset_builder()
8783        .with_data(payload.as_slice())
8784        .create(HDF5_PAYLOAD_DATASET)
8785        .map_err(hdf5_error)?;
8786    file.flush().map_err(hdf5_error)?;
8787    Ok(())
8788}
8789
8790/// Write a DataFrame to an HDF5 file with options.
8791#[cfg(not(feature = "hdf5"))]
8792pub fn write_hdf_with_options(
8793    _frame: &DataFrame,
8794    _path: &Path,
8795    _options: &HdfWriteOptions,
8796) -> Result<(), IoError> {
8797    hdf5_feature_disabled()
8798}
8799
8800#[cfg(feature = "hdf5")]
8801fn normalize_hdf5_key(key: &str) -> Result<String, IoError> {
8802    let trimmed = key.trim_matches('/');
8803    if trimmed.is_empty() {
8804        return Err(IoError::Hdf5(
8805            "hdf5 key must name a non-root group".to_owned(),
8806        ));
8807    }
8808
8809    for part in trimmed.split('/') {
8810        if part.is_empty() || part == "." || part == ".." {
8811            return Err(IoError::Hdf5(format!("invalid hdf5 key '{key}'")));
8812        }
8813        if part == HDF5_PAYLOAD_DATASET {
8814            return Err(IoError::Hdf5(format!(
8815                "hdf5 key '{key}' uses reserved FrankenPandas dataset name"
8816            )));
8817        }
8818    }
8819
8820    Ok(trimmed.to_owned())
8821}
8822
8823#[cfg(feature = "hdf5")]
8824fn hdf5_payload_path(key: &str) -> String {
8825    format!("{key}/{HDF5_PAYLOAD_DATASET}")
8826}
8827
8828#[cfg(feature = "hdf5")]
8829fn hdf5_error(err: hdf5::Error) -> IoError {
8830    IoError::Hdf5(err.to_string())
8831}
8832
8833#[cfg(not(feature = "hdf5"))]
8834fn hdf5_feature_disabled<T>() -> Result<T, IoError> {
8835    Err(IoError::Hdf5(
8836        "hdf5 support is disabled; enable the fp-io `hdf5` feature".to_owned(),
8837    ))
8838}
8839
8840// ── File-based Stata ───────────────────────────────────────────────────
8841
8842/// Read a DataFrame from a Stata DTA file.
8843pub fn read_stata(path: &Path) -> Result<DataFrame, IoError> {
8844    let content = std::fs::read(path)?;
8845    read_stata_bytes(&content)
8846}
8847
8848/// Write a DataFrame to a Stata DTA file.
8849pub fn write_stata(frame: &DataFrame, path: &Path) -> Result<(), IoError> {
8850    write_stata_with_options(frame, path, &StataWriteOptions::default())
8851}
8852
8853/// Write a DataFrame to a Stata DTA file with explicit options.
8854pub fn write_stata_with_options(
8855    frame: &DataFrame,
8856    path: &Path,
8857    options: &StataWriteOptions,
8858) -> Result<(), IoError> {
8859    let content = write_stata_bytes_with_options(frame, options)?;
8860    std::fs::write(path, content)?;
8861    Ok(())
8862}
8863
8864// ── JSONL (JSON Lines) I/O ──────────────────────────────────────────────
8865
8866/// Write a DataFrame to JSONL (JSON Lines) format.
8867///
8868/// Matches `pd.DataFrame.to_json(orient='records', lines=True)`.
8869/// Each row is written as a separate JSON object on its own line,
8870/// with no enclosing array. This format is standard for streaming
8871/// data pipelines and log processing.
8872pub fn write_jsonl_string(frame: &DataFrame) -> Result<String, IoError> {
8873    // Typed streaming fast path (\n-joined row objects, no enclosing array);
8874    // falls back to the serde tree below on anything it can't handle.
8875    if let Some(s) = try_write_json_records_typed(frame, true) {
8876        return Ok(s);
8877    }
8878    let headers: Vec<String> = frame.column_names().into_iter().cloned().collect();
8879    let row_count = frame.index().len();
8880    let column_float_promotions = headers
8881        .iter()
8882        .map(|name| {
8883            frame
8884                .column(name)
8885                .is_some_and(|column| column_promotes_int_json_values_to_float(column.values()))
8886        })
8887        .collect::<Vec<_>>();
8888
8889    let mut lines = Vec::with_capacity(row_count);
8890    for row_idx in 0..row_count {
8891        let mut obj = serde_json::Map::new();
8892        for (name, promote_int_to_float) in headers.iter().zip(column_float_promotions.iter()) {
8893            let val = frame
8894                .column(name)
8895                .and_then(|c| c.value(row_idx))
8896                .map(|value| scalar_to_json_with_column_promotion(value, *promote_int_to_float))
8897                .unwrap_or(serde_json::Value::Null);
8898            obj.insert(name.clone(), val);
8899        }
8900        lines.push(serde_json::to_string(&serde_json::Value::Object(obj))?);
8901    }
8902
8903    Ok(lines.join("\n"))
8904}
8905
8906/// Read a DataFrame from JSONL (JSON Lines) format.
8907///
8908/// Matches `pd.read_json(input, lines=True)`.
8909/// Each line must be a valid JSON object with the same keys.
8910/// Per br-frankenpandas-9l8gd: row cap to prevent DoS via hostile input.
8911/// Hostile JSONL with billions of lines would otherwise grow `all_rows`
8912/// unbounded before the column-build allocation.
8913const READ_JSONL_MAX_ROWS: usize = 100_000_000;
8914
8915pub fn read_jsonl_str(input: &str) -> Result<DataFrame, IoError> {
8916    let mut all_rows: Vec<serde_json::Map<String, serde_json::Value>> = Vec::new();
8917
8918    for line in input.lines() {
8919        let trimmed = line.trim();
8920        if trimmed.is_empty() {
8921            continue;
8922        }
8923        // Per br-frankenpandas-9l8gd: reject hostile inputs that would
8924        // exhaust memory before the column-build allocation step.
8925        if all_rows.len() >= READ_JSONL_MAX_ROWS {
8926            return Err(IoError::JsonFormat(format!(
8927                "JSONL input exceeds maximum of {READ_JSONL_MAX_ROWS} rows"
8928            )));
8929        }
8930        // Move the parsed object out of the per-line `Value` instead of cloning
8931        // it — avoids a deep copy (every key String + value) of each row's Map.
8932        match parse_json_value_allowing_pandas_nan(trimmed)? {
8933            serde_json::Value::Object(map) => all_rows.push(map),
8934            _ => {
8935                return Err(IoError::JsonFormat(
8936                    "JSONL: each line must be a JSON object".into(),
8937                ));
8938            }
8939        }
8940    }
8941
8942    if all_rows.is_empty() {
8943        return DataFrame::new(Index::new(Vec::new()), BTreeMap::new()).map_err(IoError::Frame);
8944    }
8945
8946    // Collect column names as the UNION of all keys across all rows.
8947    // This matches pandas behavior: missing keys in a row become null.
8948    let mut col_name_set = std::collections::BTreeSet::new();
8949    let mut col_names_ordered: Vec<String> = Vec::new();
8950    for row in &all_rows {
8951        for key in row.keys() {
8952            // Only clone a key the first time it is seen (uniform JSONL — every
8953            // line sharing the same keys — clones each key exactly once total,
8954            // not once per row).
8955            if !col_name_set.contains(key.as_str()) {
8956                col_name_set.insert(key.clone());
8957                col_names_ordered.push(key.clone());
8958            }
8959        }
8960    }
8961    let col_names = col_names_ordered;
8962    let mut columns: Vec<Vec<Scalar>> = col_names
8963        .iter()
8964        .map(|_| Vec::with_capacity(all_rows.len()))
8965        .collect();
8966
8967    for row in &all_rows {
8968        for (col_idx, name) in col_names.iter().enumerate() {
8969            let val = row.get(name).unwrap_or(&serde_json::Value::Null);
8970            columns[col_idx].push(json_value_to_scalar(val));
8971        }
8972    }
8973
8974    let mut out_columns = BTreeMap::new();
8975    let mut column_order = Vec::new();
8976    for (name, values) in col_names.into_iter().zip(columns) {
8977        out_columns.insert(name.clone(), column_from_json_values(values)?);
8978        column_order.push(name);
8979    }
8980
8981    let index = Index::from_i64((0..all_rows.len() as i64).collect());
8982    Ok(DataFrame::new_with_column_order(
8983        index,
8984        out_columns,
8985        column_order,
8986    )?)
8987}
8988
8989/// Write a DataFrame to a JSONL file.
8990pub fn write_jsonl(frame: &DataFrame, path: &Path) -> Result<(), IoError> {
8991    let content = write_jsonl_string(frame)?;
8992    std::fs::write(path, content)?;
8993    Ok(())
8994}
8995
8996/// Read a DataFrame from a JSONL file.
8997pub fn read_jsonl(path: &Path) -> Result<DataFrame, IoError> {
8998    let content = std::fs::read_to_string(path)?;
8999    read_jsonl_str(&content)
9000}
9001
9002// ── Parquet I/O ─────────────────────────────────────────────────────────────
9003
9004/// Convert an fp-types DType to an Arrow DataType.
9005fn dtype_to_arrow(dtype: DType) -> ArrowDataType {
9006    match dtype {
9007        DType::Int64 | DType::Int64Nullable => ArrowDataType::Int64,
9008        DType::Float64 | DType::Float64Nullable => ArrowDataType::Float64,
9009        DType::Utf8 => ArrowDataType::Utf8,
9010        DType::Categorical => ArrowDataType::Utf8,
9011        DType::Bool | DType::BoolNullable => ArrowDataType::Boolean,
9012        DType::Null => ArrowDataType::Utf8, // fallback: null-only columns as string
9013        DType::Timedelta64 => ArrowDataType::Int64, // store as nanoseconds
9014        DType::Datetime64 { .. } => ArrowDataType::Int64, // store as nanoseconds
9015        DType::Period => ArrowDataType::Int64, // store as ordinal
9016        DType::Interval => ArrowDataType::Utf8, // store as string until arrow interval lands
9017        DType::Sparse => ArrowDataType::Utf8, // marker fallback until sparse arrays land
9018    }
9019}
9020
9021fn column_to_arrow_array(column: &Column) -> Result<Arc<dyn Array>, IoError> {
9022    let arr: Arc<dyn Array> = match column.dtype() {
9023        DType::Int64 | DType::Int64Nullable => {
9024            let mut builder = Int64Builder::with_capacity(column.len());
9025            for value in column.values() {
9026                match value {
9027                    Scalar::Int64(n) => builder.append_value(*n),
9028                    _ if value.is_missing() => builder.append_null(),
9029                    _ => builder.append_null(),
9030                }
9031            }
9032            Arc::new(builder.finish())
9033        }
9034        DType::Float64 | DType::Float64Nullable => {
9035            let mut builder = Float64Builder::with_capacity(column.len());
9036            for value in column.values() {
9037                match value {
9038                    Scalar::Float64(n) => {
9039                        if n.is_nan() {
9040                            builder.append_null();
9041                        } else {
9042                            builder.append_value(*n);
9043                        }
9044                    }
9045                    _ if value.is_missing() => builder.append_null(),
9046                    _ => builder.append_null(),
9047                }
9048            }
9049            Arc::new(builder.finish())
9050        }
9051        DType::Bool | DType::BoolNullable => {
9052            if let Some(values) = column.as_bool_slice() {
9053                let mut builder = BooleanBuilder::with_capacity(values.len());
9054                for &value in values {
9055                    builder.append_value(value);
9056                }
9057                return Ok(Arc::new(builder.finish()));
9058            }
9059            let mut builder = BooleanBuilder::with_capacity(column.len());
9060            for value in column.values() {
9061                match value {
9062                    Scalar::Bool(flag) => builder.append_value(*flag),
9063                    _ if value.is_missing() => builder.append_null(),
9064                    _ => builder.append_null(),
9065                }
9066            }
9067            Arc::new(builder.finish())
9068        }
9069        DType::Utf8 | DType::Categorical | DType::Null | DType::Sparse => {
9070            if column.dtype() == DType::Utf8
9071                && let Some((bytes, offsets)) = column.as_utf8_contiguous()
9072            {
9073                let mut builder = StringBuilder::with_capacity(offsets.len() - 1, bytes.len());
9074                for window in offsets.windows(2) {
9075                    let value = std::str::from_utf8(&bytes[window[0]..window[1]])
9076                        .map_err(|error| IoError::Parquet(error.to_string()))?;
9077                    builder.append_value(value);
9078                }
9079                return Ok(Arc::new(builder.finish()));
9080            }
9081            let mut builder = StringBuilder::with_capacity(column.len(), column.len() * 8);
9082            for value in column.values() {
9083                match value {
9084                    Scalar::Utf8(text) => builder.append_value(text),
9085                    _ if value.is_missing() => builder.append_null(),
9086                    _ => builder.append_value(format!("{value:?}")),
9087                }
9088            }
9089            Arc::new(builder.finish())
9090        }
9091        DType::Timedelta64 => {
9092            let mut builder = Int64Builder::with_capacity(column.len());
9093            for value in column.values() {
9094                match value {
9095                    Scalar::Timedelta64(nanos) => {
9096                        if *nanos == Timedelta::NAT {
9097                            builder.append_null();
9098                        } else {
9099                            builder.append_value(*nanos);
9100                        }
9101                    }
9102                    _ if value.is_missing() => builder.append_null(),
9103                    _ => builder.append_null(),
9104                }
9105            }
9106            Arc::new(builder.finish())
9107        }
9108        DType::Datetime64 { .. } => {
9109            let mut builder = Int64Builder::with_capacity(column.len());
9110            for value in column.values() {
9111                match value {
9112                    Scalar::Datetime64(nanos) => {
9113                        if *nanos == Timestamp::NAT {
9114                            builder.append_null();
9115                        } else {
9116                            builder.append_value(*nanos);
9117                        }
9118                    }
9119                    _ if value.is_missing() => builder.append_null(),
9120                    _ => builder.append_null(),
9121                }
9122            }
9123            Arc::new(builder.finish())
9124        }
9125        DType::Period => {
9126            let mut builder = Int64Builder::with_capacity(column.len());
9127            for value in column.values() {
9128                match value {
9129                    Scalar::Period(p) => {
9130                        if p.ordinal == i64::MIN {
9131                            builder.append_null();
9132                        } else {
9133                            builder.append_value(p.ordinal);
9134                        }
9135                    }
9136                    _ if value.is_missing() => builder.append_null(),
9137                    _ => builder.append_null(),
9138                }
9139            }
9140            Arc::new(builder.finish())
9141        }
9142        DType::Interval => {
9143            let mut builder = StringBuilder::with_capacity(column.len(), column.len() * 32);
9144            for value in column.values() {
9145                match value {
9146                    Scalar::Interval(iv) => builder.append_value(format!("{iv}")),
9147                    _ if value.is_missing() => builder.append_null(),
9148                    _ => builder.append_null(),
9149                }
9150            }
9151            Arc::new(builder.finish())
9152        }
9153    };
9154
9155    Ok(arr)
9156}
9157
9158/// Convert a Series to its Arrow data type plus backing array.
9159///
9160/// This is the Arrow-level building block under Feather / IPC round-trips and
9161/// preserves nullable Int64 columns as Arrow null-bitmaps rather than coercing
9162/// through Float64.
9163pub fn series_to_arrow_array(series: &Series) -> Result<(ArrowDataType, Arc<dyn Array>), IoError> {
9164    let dt = dtype_to_arrow(series.column().dtype());
9165    Ok((dt, column_to_arrow_array(series.column())?))
9166}
9167
9168/// Rebuild a Series from an Arrow array and explicit dtype metadata.
9169pub fn series_from_arrow_array(
9170    name: impl Into<String>,
9171    index_labels: Vec<IndexLabel>,
9172    arr: &dyn Array,
9173    dt: &ArrowDataType,
9174) -> Result<Series, IoError> {
9175    let values = arrow_array_to_scalars(arr, dt)?;
9176    Series::from_values(name, index_labels, values).map_err(IoError::from)
9177}
9178
9179/// Build an Arrow RecordBatch from a DataFrame.
9180/// Arrow field-metadata key carrying FrankenPandas' own dtype when Arrow's type
9181/// system cannot express it.
9182///
9183/// Arrow has ONE `Int64` and ONE `Boolean`; nullability is a validity bitmap on
9184/// the array, not a distinct type. FrankenPandas has two of each — `Int64` /
9185/// `Int64Nullable` and `Bool` / `BoolNullable` — mirroring pandas' `int64` vs
9186/// `Int64Dtype()` and `bool` vs `BooleanDtype()`, which pandas ALSO treats as
9187/// different dtypes with different behaviour (`pd.merge` refuses `Int64` against
9188/// `int64` as incompatible merge keys, per br-frankenpandas-sopel).
9189///
9190/// So the round trip has to carry the distinction out of band or lose it, and
9191/// losing it is exactly the defect: `ipc_stream_round_trip_null_hardened`
9192/// reported `actual=false expected=true` because an `Int64Nullable` column came
9193/// back tagged `Int64`. (br-frankenpandas-13q8k)
9194const FP_DTYPE_METADATA_KEY: &str = "frankenpandas.dtype";
9195
9196/// The metadata tag for a dtype Arrow cannot represent, or `None` when Arrow's
9197/// own type is already a faithful carrier.
9198///
9199/// Deliberately narrow: only the two dtypes that collide with another dtype
9200/// under `dtype_to_arrow` get a tag. Every other column writes exactly the bytes
9201/// and schema it wrote before this change, so no existing reader — including
9202/// non-FrankenPandas ones — sees anything new.
9203fn nullable_extension_tag(dtype: DType) -> Option<&'static str> {
9204    match dtype {
9205        DType::Int64Nullable => Some("Int64Nullable"),
9206        DType::BoolNullable => Some("BoolNullable"),
9207        // Arrow has ONE Float64, so this collides with DType::Float64 exactly
9208        // the way Int64Nullable collides with Int64 -- it needs the same tag or
9209        // it decays on the round trip, which is the defect
9210        // br-frankenpandas-13q8k fixed for the other two.
9211        // (br-frankenpandas-qkqfb)
9212        DType::Float64Nullable => Some("Float64Nullable"),
9213        _ => None,
9214    }
9215}
9216
9217/// Restore a column's declared dtype from the field metadata written above.
9218///
9219/// Absent or unrecognized metadata means "trust Arrow", which is what every
9220/// stream written before this change (and every stream written by anything that
9221/// is not FrankenPandas) contains — so those keep decoding exactly as they did.
9222fn retag_from_field_metadata(col: Column, field: &Field) -> Column {
9223    let Some(tag) = field.metadata().get(FP_DTYPE_METADATA_KEY) else {
9224        return col;
9225    };
9226    let declared = match tag.as_str() {
9227        "Int64Nullable" => DType::Int64Nullable,
9228        "BoolNullable" => DType::BoolNullable,
9229        "Float64Nullable" => DType::Float64Nullable,
9230        _ => return col,
9231    };
9232    if col.dtype() == declared {
9233        return col;
9234    }
9235    // `promote_to_nullable` keeps the typed backing (`data`), which the
9236    // read_parquet typed fast path above depends on; it only applies when the
9237    // column actually has nulls. A declared-nullable column that happens to be
9238    // all-valid still has to be retagged, and `with_dtype` is the only route --
9239    // it drops the typed backing, which is why it is NOT used for the common
9240    // has-nulls case.
9241    let promoted = col.promote_to_nullable();
9242    if promoted.dtype() == declared {
9243        promoted
9244    } else {
9245        promoted.with_dtype(declared)
9246    }
9247}
9248
9249fn dataframe_to_record_batch(frame: &DataFrame) -> Result<RecordBatch, IoError> {
9250    let row_multiindex_names = frame
9251        .row_multiindex()
9252        .map(|row_multiindex| row_multiindex.names().to_vec());
9253    let materialized = if frame.row_multiindex().is_some() {
9254        Some(materialize_synthetic_row_multiindex_columns(frame)?)
9255    } else {
9256        None
9257    };
9258    let frame = materialized.as_ref().unwrap_or(frame);
9259
9260    let col_names: Vec<String> = frame.column_names().into_iter().cloned().collect();
9261    let mut fields = Vec::with_capacity(col_names.len());
9262    let mut arrays: Vec<Arc<dyn Array>> = Vec::with_capacity(col_names.len());
9263
9264    for name in &col_names {
9265        let col = frame
9266            .column(name)
9267            .ok_or_else(|| IoError::Parquet(format!("missing column: {name}")))?;
9268        let dt = col.dtype();
9269        let mut field = Field::new(name.as_str(), dtype_to_arrow(dt.clone()), true);
9270        if let Some(tag) = nullable_extension_tag(dt) {
9271            field = field.with_metadata(std::collections::HashMap::from([(
9272                FP_DTYPE_METADATA_KEY.to_owned(),
9273                tag.to_owned(),
9274            )]));
9275        }
9276        fields.push(field);
9277        let arr = column_to_arrow_array(col)?;
9278        arrays.push(arr);
9279    }
9280
9281    let schema = match row_multiindex_names {
9282        Some(names) => {
9283            let encoded = serde_json::to_string(&names)
9284                .map_err(|e| IoError::Parquet(format!("encode row multiindex names: {e}")))?;
9285            Arc::new(Schema::new_with_metadata(
9286                fields,
9287                std::collections::HashMap::from([(
9288                    ROW_MULTIINDEX_NAMES_METADATA_KEY.to_owned(),
9289                    encoded,
9290                )]),
9291            ))
9292        }
9293        None => Arc::new(Schema::new(fields)),
9294    };
9295    RecordBatch::try_new(schema, arrays).map_err(|e| IoError::Parquet(e.to_string()))
9296}
9297
9298/// Build the block-backed representation directly from one homogeneous Arrow
9299/// Float64 batch. The Arrow buffers are already column-major, so this copies
9300/// each decoded value only once into the frame's column-major backing block.
9301///
9302/// Nullable columns deliberately do not enter this path: the block store is
9303/// all-valid by contract, and the normal typed path carries nullable-float
9304/// validity and NaN semantics.
9305#[cfg(feature = "block-storage")]
9306fn try_record_batch_to_float64_block(batch: &RecordBatch) -> Result<Option<DataFrame>, IoError> {
9307    if batch.num_columns() == 0
9308        || !batch
9309            .schema()
9310            .fields()
9311            .iter()
9312            .all(|field| field.data_type() == &ArrowDataType::Float64)
9313    {
9314        return Ok(None);
9315    }
9316
9317    let names: Vec<String> = batch
9318        .schema()
9319        .fields()
9320        .iter()
9321        .map(|field| field.name().clone())
9322        .collect();
9323    if names.iter().collect::<HashSet<_>>().len() != names.len() {
9324        // The existing BTreeMap path has legacy duplicate-label behavior.
9325        // Leave it untouched rather than making the block path observably
9326        // stricter.
9327        return Ok(None);
9328    }
9329
9330    let rows = batch.num_rows();
9331    let capacity = rows.checked_mul(names.len()).ok_or_else(|| {
9332        IoError::Parquet("parquet Float64 block dimensions overflow usize".into())
9333    })?;
9334    let mut block = Vec::with_capacity(capacity);
9335    for array in batch.columns() {
9336        let floats = array
9337            .as_any()
9338            .downcast_ref::<Float64Array>()
9339            .expect("Float64 schema field must carry Float64Array");
9340        if floats.null_count() != 0 {
9341            return Ok(None);
9342        }
9343        block.extend_from_slice(floats.values());
9344    }
9345
9346    DataFrame::from_f64_block_columns(
9347        Index::new_known_unique_int64_unit_range(0, rows),
9348        names,
9349        block,
9350    )
9351    .map(Some)
9352    .map_err(IoError::from)
9353}
9354
9355/// Convert an Arrow RecordBatch back into a DataFrame.
9356fn record_batch_to_dataframe(batch: &RecordBatch) -> Result<DataFrame, IoError> {
9357    #[cfg(feature = "block-storage")]
9358    if let Some(frame) = try_record_batch_to_float64_block(batch)? {
9359        return Ok(frame);
9360    }
9361
9362    let n_rows = batch.num_rows();
9363    let schema = batch.schema();
9364    let mut columns = BTreeMap::new();
9365    let mut col_order = Vec::new();
9366
9367    for (i, field) in schema.fields().iter().enumerate() {
9368        let name = field.name().clone();
9369        let arr = batch.column(i);
9370        // Typed fast path: convert the Arrow buffer DIRECTLY to a typed fp column
9371        // (Int64/Float64/Bool/all-valid-Utf8), skipping the per-cell Vec<Scalar>
9372        // materialization (~32 B/elem boxing) + Column::new re-scan that made
9373        // read_parquet ~0.21x pandas/pyarrow. Bails (→ Scalar path) for
9374        // Date/Timestamp (need chrono formatting) and nullable-Utf8 (no typed
9375        // contiguous-nullable constructor). Bit-identical to the Scalar path's
9376        // per-type null-kind conventions (Int/Bool/Utf8 → Null(Null); Float →
9377        // Null(NaN)); validity constructors reproduce those exactly (verified).
9378        let col = match arrow_array_to_column_typed(arr.as_ref(), field.data_type()) {
9379            Some(c) => c,
9380            None => {
9381                let values = arrow_array_to_scalars(arr.as_ref(), field.data_type())?;
9382                let dtype = fp_dtype_for_arrow_data_type(field.data_type());
9383                Column::new(dtype, values)?
9384            }
9385        };
9386        let col = retag_from_field_metadata(col, field);
9387        columns.insert(name.clone(), col);
9388        col_order.push(name);
9389    }
9390
9391    // A parquet batch gets the default 0..n RangeIndex. Use the LAZY unit-range
9392    // index instead of materializing a Vec<IndexLabel> of n_rows + Index::new
9393    // (which was ~110ms of a 137ms 1M-row read — the real read_parquet bottleneck,
9394    // NOT the ~27ms decode). Bit-identical: same integer labels 0..n_rows.
9395    let index = Index::new_known_unique_int64_unit_range(0, n_rows);
9396
9397    let frame = DataFrame::new_with_column_order(index, columns, col_order)?;
9398    let frame = promote_synthetic_row_multiindex_if_present(&frame)?;
9399    match row_multiindex_names_from_arrow_metadata(schema.metadata()) {
9400        Some(names) => restore_row_multiindex_names(frame, &names),
9401        None => Ok(frame),
9402    }
9403}
9404
9405fn fp_dtype_for_arrow_data_type(dt: &ArrowDataType) -> DType {
9406    match dt {
9407        ArrowDataType::Int8
9408        | ArrowDataType::Int16
9409        | ArrowDataType::Int32
9410        | ArrowDataType::Int64
9411        | ArrowDataType::UInt8
9412        | ArrowDataType::UInt16
9413        | ArrowDataType::UInt32
9414        | ArrowDataType::UInt64 => DType::Int64,
9415        ArrowDataType::Float16 | ArrowDataType::Float32 | ArrowDataType::Float64 => DType::Float64,
9416        ArrowDataType::Boolean => DType::Bool,
9417        ArrowDataType::Utf8
9418        | ArrowDataType::LargeUtf8
9419        | ArrowDataType::Date32
9420        | ArrowDataType::Date64
9421        | ArrowDataType::Timestamp(_, _) => DType::Utf8,
9422        _ => DType::Utf8,
9423    }
9424}
9425
9426/// Build an fp `ValidityMask` from an Arrow array's null buffer, or `None` when
9427/// the array has no nulls (caller uses the all-valid constructor).
9428fn arrow_validity_mask(arr: &dyn Array) -> Option<fp_columnar::ValidityMask> {
9429    if arr.null_count() == 0 {
9430        return None;
9431    }
9432    let len = arr.len();
9433    let mut mask = fp_columnar::ValidityMask::all_valid(len);
9434    for i in 0..len {
9435        if arr.is_null(i) {
9436            mask.set(i, false);
9437        }
9438    }
9439    Some(mask)
9440}
9441
9442/// Typed Arrow-array → fp `Column` conversion (br-frankenpandas parquet-typed):
9443/// reads the Arrow buffer directly into a typed fp column, bypassing the per-cell
9444/// `Vec<Scalar>` boxing + `Column::new` re-scan of `arrow_array_to_scalars`.
9445/// Returns `None` for types that need the Scalar path (Date/Timestamp string
9446/// coercion, dictionary arrays, and any uncovered dtype). Bit-identical to that path.
9447fn arrow_array_to_column_typed(arr: &dyn Array, dt: &ArrowDataType) -> Option<Column> {
9448    use arrow::array::{
9449        Float32Array, Float64Array, Int8Array, Int16Array, Int32Array, Int64Array, UInt8Array,
9450        UInt16Array, UInt32Array, UInt64Array,
9451    };
9452    macro_rules! i64_col {
9453        ($ty:ty) => {{
9454            let t = arr.as_any().downcast_ref::<$ty>()?;
9455            let data: Vec<i64> = t.values().iter().map(|&v| v as i64).collect();
9456            Some(match arrow_validity_mask(arr) {
9457                Some(m) => Column::from_i64_values_with_validity(data, m),
9458                // MOVE the gathered Vec into the backing (one Arc::new) rather than
9459                // from_i64_values' Arc::from(Vec) alloc+memcpy (~28ms/5M) — a second
9460                // copy on top of the Arrow-buffer gather. All-valid, so _owned fits.
9461                None => Column::from_i64_values_owned(data),
9462            })
9463        }};
9464    }
9465    macro_rules! f64_col {
9466        ($ty:ty) => {{
9467            let t = arr.as_any().downcast_ref::<$ty>()?;
9468            let data: Vec<f64> = t.values().iter().map(|&v| v as f64).collect();
9469            Some(match arrow_validity_mask(arr) {
9470                Some(m) => Column::from_f64_values_with_validity(data, m),
9471                None => Column::from_f64_values_owned(data),
9472            })
9473        }};
9474    }
9475    match dt {
9476        ArrowDataType::Int64 => i64_col!(Int64Array),
9477        ArrowDataType::Int32 => i64_col!(Int32Array),
9478        ArrowDataType::Int16 => i64_col!(Int16Array),
9479        ArrowDataType::Int8 => i64_col!(Int8Array),
9480        // UInt64 as i64: matches the Scalar path's `Scalar::Int64(value as ...)`
9481        // reinterpretation for the width; large u64 wrap identically both ways.
9482        ArrowDataType::UInt64 => i64_col!(UInt64Array),
9483        ArrowDataType::UInt32 => i64_col!(UInt32Array),
9484        ArrowDataType::UInt16 => i64_col!(UInt16Array),
9485        ArrowDataType::UInt8 => i64_col!(UInt8Array),
9486        ArrowDataType::Float64 => f64_col!(Float64Array),
9487        ArrowDataType::Float32 => f64_col!(Float32Array),
9488        ArrowDataType::Boolean => {
9489            let t = arr.as_any().downcast_ref::<BooleanArray>()?;
9490            let data: Vec<bool> = (0..t.len()).map(|i| t.value(i)).collect();
9491            Some(match arrow_validity_mask(arr) {
9492                Some(m) => Column::from_bool_values_with_validity(data, m),
9493                None => Column::from_bool_values(data),
9494            })
9495        }
9496        ArrowDataType::Utf8 => {
9497            let t = arr.as_any().downcast_ref::<StringArray>()?;
9498            let offs = t.value_offsets();
9499            let len = t.len();
9500            let start = offs[0] as usize;
9501            let end = offs[len] as usize;
9502            let bytes = t.value_data()[start..end].to_vec();
9503            let offsets: Vec<usize> = offs.iter().map(|&o| o as usize - start).collect();
9504            Some(match arrow_validity_mask(arr) {
9505                Some(validity) => Column::from_utf8_values_with_validity(bytes, offsets, validity),
9506                None => Column::from_utf8_contiguous(bytes, offsets),
9507            })
9508        }
9509        ArrowDataType::LargeUtf8 => {
9510            let t = arr
9511                .as_any()
9512                .downcast_ref::<arrow::array::LargeStringArray>()?;
9513            let offs = t.value_offsets();
9514            let len = t.len();
9515            let start = offs[0] as usize;
9516            let end = offs[len] as usize;
9517            let bytes = t.value_data()[start..end].to_vec();
9518            let offsets: Vec<usize> = offs.iter().map(|&o| o as usize - start).collect();
9519            Some(match arrow_validity_mask(arr) {
9520                Some(validity) => Column::from_utf8_values_with_validity(bytes, offsets, validity),
9521                None => Column::from_utf8_contiguous(bytes, offsets),
9522            })
9523        }
9524        _ => None,
9525    }
9526}
9527
9528/// Convert an Arrow array + data type to a Vec of Scalars.
9529fn arrow_array_to_scalars(arr: &dyn Array, dt: &ArrowDataType) -> Result<Vec<Scalar>, IoError> {
9530    let len = arr.len();
9531    let mut scalars = Vec::with_capacity(len);
9532
9533    match dt {
9534        ArrowDataType::Int64 => {
9535            let typed = arr
9536                .as_any()
9537                .downcast_ref::<Int64Array>()
9538                .ok_or_else(|| IoError::Parquet("expected Int64Array".into()))?;
9539            for i in 0..len {
9540                if typed.is_null(i) {
9541                    scalars.push(Scalar::Null(NullKind::Null));
9542                } else {
9543                    scalars.push(Scalar::Int64(typed.value(i)));
9544                }
9545            }
9546        }
9547        ArrowDataType::Int32 => {
9548            let typed = arr
9549                .as_any()
9550                .downcast_ref::<arrow::array::Int32Array>()
9551                .ok_or_else(|| IoError::Parquet("expected Int32Array".into()))?;
9552            for i in 0..len {
9553                if typed.is_null(i) {
9554                    scalars.push(Scalar::Null(NullKind::Null));
9555                } else {
9556                    scalars.push(Scalar::Int64(i64::from(typed.value(i))));
9557                }
9558            }
9559        }
9560        ArrowDataType::Float64 => {
9561            let typed = arr
9562                .as_any()
9563                .downcast_ref::<Float64Array>()
9564                .ok_or_else(|| IoError::Parquet("expected Float64Array".into()))?;
9565            for i in 0..len {
9566                if typed.is_null(i) {
9567                    scalars.push(Scalar::Null(NullKind::NaN));
9568                } else {
9569                    scalars.push(Scalar::Float64(typed.value(i)));
9570                }
9571            }
9572        }
9573        ArrowDataType::Float32 => {
9574            let typed = arr
9575                .as_any()
9576                .downcast_ref::<arrow::array::Float32Array>()
9577                .ok_or_else(|| IoError::Parquet("expected Float32Array".into()))?;
9578            for i in 0..len {
9579                if typed.is_null(i) {
9580                    scalars.push(Scalar::Null(NullKind::NaN));
9581                } else {
9582                    scalars.push(Scalar::Float64(f64::from(typed.value(i))));
9583                }
9584            }
9585        }
9586        ArrowDataType::Boolean => {
9587            let typed = arr
9588                .as_any()
9589                .downcast_ref::<BooleanArray>()
9590                .ok_or_else(|| IoError::Parquet("expected BooleanArray".into()))?;
9591            for i in 0..len {
9592                if typed.is_null(i) {
9593                    scalars.push(Scalar::Null(NullKind::Null));
9594                } else {
9595                    scalars.push(Scalar::Bool(typed.value(i)));
9596                }
9597            }
9598        }
9599        ArrowDataType::Utf8 => {
9600            let typed = arr
9601                .as_any()
9602                .downcast_ref::<StringArray>()
9603                .ok_or_else(|| IoError::Parquet("expected StringArray".into()))?;
9604            for i in 0..len {
9605                if typed.is_null(i) {
9606                    scalars.push(Scalar::Null(NullKind::Null));
9607                } else {
9608                    scalars.push(Scalar::Utf8(typed.value(i).to_owned()));
9609                }
9610            }
9611        }
9612        ArrowDataType::LargeUtf8 => {
9613            let typed = arr
9614                .as_any()
9615                .downcast_ref::<arrow::array::LargeStringArray>()
9616                .ok_or_else(|| IoError::Parquet("expected LargeStringArray".into()))?;
9617            for i in 0..len {
9618                if typed.is_null(i) {
9619                    scalars.push(Scalar::Null(NullKind::Null));
9620                } else {
9621                    scalars.push(Scalar::Utf8(typed.value(i).to_owned()));
9622                }
9623            }
9624        }
9625        ArrowDataType::Date32 => {
9626            let typed = arr
9627                .as_any()
9628                .downcast_ref::<Date32Array>()
9629                .ok_or_else(|| IoError::Parquet("expected Date32Array".into()))?;
9630            for i in 0..len {
9631                if typed.is_null(i) {
9632                    scalars.push(Scalar::Null(NullKind::NaT));
9633                } else {
9634                    if let Some(date) = arrow::temporal_conversions::as_date::<
9635                        arrow::datatypes::Date32Type,
9636                    >(typed.value(i).into())
9637                    {
9638                        scalars.push(Scalar::Utf8(date.format("%Y-%m-%d").to_string()));
9639                    } else {
9640                        scalars.push(Scalar::Null(NullKind::NaT));
9641                    }
9642                }
9643            }
9644        }
9645        ArrowDataType::Date64 => {
9646            let typed = arr
9647                .as_any()
9648                .downcast_ref::<Date64Array>()
9649                .ok_or_else(|| IoError::Parquet("expected Date64Array".into()))?;
9650            for i in 0..len {
9651                if typed.is_null(i) {
9652                    scalars.push(Scalar::Null(NullKind::NaT));
9653                } else {
9654                    if let Some(dt) = arrow::temporal_conversions::as_datetime::<
9655                        arrow::datatypes::Date64Type,
9656                    >(typed.value(i))
9657                    {
9658                        scalars.push(Scalar::Utf8(dt.format("%Y-%m-%d").to_string()));
9659                    } else {
9660                        scalars.push(Scalar::Null(NullKind::NaT));
9661                    }
9662                }
9663            }
9664        }
9665        ArrowDataType::Timestamp(unit, _tz) => match unit {
9666            TimeUnit::Second => {
9667                let typed = arr
9668                    .as_any()
9669                    .downcast_ref::<TimestampSecondArray>()
9670                    .ok_or_else(|| IoError::Parquet("expected TimestampSecondArray".into()))?;
9671                for i in 0..len {
9672                    if typed.is_null(i) {
9673                        scalars.push(Scalar::Null(NullKind::NaT));
9674                    } else {
9675                        if let Some(dt) = arrow::temporal_conversions::as_datetime::<
9676                            arrow::datatypes::TimestampSecondType,
9677                        >(typed.value(i))
9678                        {
9679                            scalars.push(Scalar::Utf8(dt.format("%Y-%m-%d %H:%M:%S").to_string()));
9680                        } else {
9681                            scalars.push(Scalar::Null(NullKind::NaT));
9682                        }
9683                    }
9684                }
9685            }
9686            TimeUnit::Millisecond => {
9687                let typed = arr
9688                    .as_any()
9689                    .downcast_ref::<TimestampMillisecondArray>()
9690                    .ok_or_else(|| IoError::Parquet("expected TimestampMillisecondArray".into()))?;
9691                for i in 0..len {
9692                    if typed.is_null(i) {
9693                        scalars.push(Scalar::Null(NullKind::NaT));
9694                    } else {
9695                        if let Some(dt) = arrow::temporal_conversions::as_datetime::<
9696                            arrow::datatypes::TimestampMillisecondType,
9697                        >(typed.value(i))
9698                        {
9699                            scalars.push(Scalar::Utf8(dt.format("%Y-%m-%d %H:%M:%S").to_string()));
9700                        } else {
9701                            scalars.push(Scalar::Null(NullKind::NaT));
9702                        }
9703                    }
9704                }
9705            }
9706            TimeUnit::Microsecond => {
9707                let typed = arr
9708                    .as_any()
9709                    .downcast_ref::<TimestampMicrosecondArray>()
9710                    .ok_or_else(|| IoError::Parquet("expected TimestampMicrosecondArray".into()))?;
9711                for i in 0..len {
9712                    if typed.is_null(i) {
9713                        scalars.push(Scalar::Null(NullKind::NaT));
9714                    } else {
9715                        if let Some(dt) = arrow::temporal_conversions::as_datetime::<
9716                            arrow::datatypes::TimestampMicrosecondType,
9717                        >(typed.value(i))
9718                        {
9719                            scalars
9720                                .push(Scalar::Utf8(dt.format("%Y-%m-%d %H:%M:%S%.6f").to_string()));
9721                        } else {
9722                            scalars.push(Scalar::Null(NullKind::NaT));
9723                        }
9724                    }
9725                }
9726            }
9727            TimeUnit::Nanosecond => {
9728                let typed = arr
9729                    .as_any()
9730                    .downcast_ref::<TimestampNanosecondArray>()
9731                    .ok_or_else(|| IoError::Parquet("expected TimestampNanosecondArray".into()))?;
9732                for i in 0..len {
9733                    if typed.is_null(i) {
9734                        scalars.push(Scalar::Null(NullKind::NaT));
9735                    } else {
9736                        if let Some(dt) = arrow::temporal_conversions::as_datetime::<
9737                            arrow::datatypes::TimestampNanosecondType,
9738                        >(typed.value(i))
9739                        {
9740                            scalars
9741                                .push(Scalar::Utf8(dt.format("%Y-%m-%d %H:%M:%S%.9f").to_string()));
9742                        } else {
9743                            scalars.push(Scalar::Null(NullKind::NaT));
9744                        }
9745                    }
9746                }
9747            }
9748        },
9749        other => {
9750            return Err(IoError::Parquet(format!(
9751                "unsupported Arrow data type: {other:?}"
9752            )));
9753        }
9754    }
9755
9756    Ok(scalars)
9757}
9758
9759/// Write a DataFrame to an in-memory Parquet buffer.
9760pub fn write_parquet_bytes(frame: &DataFrame) -> Result<Vec<u8>, IoError> {
9761    let batch = dataframe_to_record_batch(frame)?;
9762    let mut buf = Vec::new();
9763    // The Arrow schema-level metadata on `batch` does not come back as batch
9764    // metadata from the Parquet reader, so the row MultiIndex level names also
9765    // ride in the file's own key-value metadata (br-frankenpandas-wfkzm).
9766    let props = frame
9767        .row_multiindex()
9768        .map(
9769            |row_multiindex| -> Result<parquet::file::properties::WriterProperties, IoError> {
9770                let encoded = serde_json::to_string(&row_multiindex.names().to_vec())?;
9771                Ok(parquet::file::properties::WriterProperties::builder()
9772                    .set_key_value_metadata(Some(vec![parquet::file::metadata::KeyValue::new(
9773                        ROW_MULTIINDEX_NAMES_METADATA_KEY.to_owned(),
9774                        encoded,
9775                    )]))
9776                    .build())
9777            },
9778        )
9779        .transpose()?;
9780    let mut writer = ArrowWriter::try_new(&mut buf, batch.schema(), props)
9781        .map_err(|e| IoError::Parquet(e.to_string()))?;
9782    writer
9783        .write(&batch)
9784        .map_err(|e| IoError::Parquet(e.to_string()))?;
9785    writer
9786        .close()
9787        .map_err(|e| IoError::Parquet(e.to_string()))?;
9788    Ok(buf)
9789}
9790
9791/// Read a DataFrame from in-memory Parquet bytes.
9792pub fn read_parquet_bytes(data: &[u8]) -> Result<DataFrame, IoError> {
9793    let b = bytes::Bytes::from(data.to_vec());
9794    let builder =
9795        ParquetRecordBatchReaderBuilder::try_new(b).map_err(|e| IoError::Parquet(e.to_string()))?;
9796    // Read the whole file as ONE record batch instead of the default 1024-row
9797    // batches: a 1M-row file otherwise yields ~1000 tiny batches, each turned into
9798    // a DataFrame and then concatenated — the many-batch + concat overhead (not
9799    // the decode) dominated read_parquet (~0.21x pandas). Sizing the batch to the
9800    // row count collapses that to a single typed conversion, no concat. Clamp so a
9801    // pathological row count can't request an absurd allocation up front.
9802    let total_rows = builder.metadata().file_metadata().num_rows().max(0) as usize;
9803    // Level names written by `write_parquet_bytes` (see there); absent on files
9804    // from older builds or other writers, in which case the synthetic
9805    // `__index_level_N__` names stay.
9806    let level_names: Option<Vec<Option<String>>> = builder
9807        .metadata()
9808        .file_metadata()
9809        .key_value_metadata()
9810        .and_then(|pairs| {
9811            pairs
9812                .iter()
9813                .find(|pair| pair.key == ROW_MULTIINDEX_NAMES_METADATA_KEY)
9814        })
9815        .and_then(|pair| pair.value.as_deref())
9816        .and_then(|raw| serde_json::from_str::<Vec<Option<String>>>(raw).ok());
9817    let batch_size = total_rows.clamp(1, 16 * 1024 * 1024);
9818    let reader = builder
9819        .with_batch_size(batch_size)
9820        .build()
9821        .map_err(|e| IoError::Parquet(e.to_string()))?;
9822
9823    let mut all_frames: Vec<DataFrame> = Vec::new();
9824    for batch_result in reader {
9825        let batch: RecordBatch =
9826            batch_result.map_err(|e: arrow::error::ArrowError| IoError::Parquet(e.to_string()))?;
9827        all_frames.push(record_batch_to_dataframe(&batch)?);
9828    }
9829
9830    if all_frames.is_empty() {
9831        // Return empty DataFrame
9832        return Ok(DataFrame::new_with_column_order(
9833            Index::new(vec![]),
9834            BTreeMap::new(),
9835            vec![],
9836        )?);
9837    }
9838
9839    let frame = if all_frames.len() == 1 {
9840        // For a single batch (common case), return directly
9841        all_frames.into_iter().next().ok_or_else(|| {
9842            IoError::Parquet("parquet reader produced zero record batches".to_owned())
9843        })?
9844    } else {
9845        // Multiple batches: concatenate via fp_frame::concat_dataframes
9846        let refs: Vec<&DataFrame> = all_frames.iter().collect();
9847        fp_frame::concat_dataframes(&refs)?
9848    };
9849    match level_names {
9850        Some(names) => restore_row_multiindex_names(frame, &names),
9851        None => Ok(frame),
9852    }
9853}
9854
9855/// Write a DataFrame to a Parquet file.
9856pub fn write_parquet(frame: &DataFrame, path: &Path) -> Result<(), IoError> {
9857    let bytes = write_parquet_bytes(frame)?;
9858    std::fs::write(path, bytes)?;
9859    Ok(())
9860}
9861
9862/// Read a DataFrame from a Parquet file.
9863pub fn read_parquet(path: &Path) -> Result<DataFrame, IoError> {
9864    let data = std::fs::read(path)?;
9865    read_parquet_bytes(&data)
9866}
9867
9868// ── ORC I/O ────────────────────────────────────────────────────────────────
9869
9870/// Write a DataFrame to an in-memory ORC buffer.
9871///
9872/// This fails closed under the workspace no-Tokio policy. The previous
9873/// implementation delegated to `orc-rust`, which unconditionally pulled Tokio
9874/// into `fp-io` and therefore into the umbrella `frankenpandas` crate.
9875pub fn write_orc_bytes(_frame: &DataFrame) -> Result<Vec<u8>, IoError> {
9876    Err(orc_no_tokio_error())
9877}
9878
9879/// Read a DataFrame from in-memory ORC bytes.
9880pub fn read_orc_bytes(_data: &[u8]) -> Result<DataFrame, IoError> {
9881    Err(orc_no_tokio_error())
9882}
9883
9884/// Write a DataFrame to an ORC file.
9885pub fn write_orc(_frame: &DataFrame, _path: &Path) -> Result<(), IoError> {
9886    Err(orc_no_tokio_error())
9887}
9888
9889/// Read a DataFrame from an ORC file.
9890pub fn read_orc(_path: &Path) -> Result<DataFrame, IoError> {
9891    Err(orc_no_tokio_error())
9892}
9893
9894// ── Excel (xlsx) I/O ────────────────────────────────────────────────────
9895
9896/// Options for reading Excel files.
9897#[derive(Debug, Clone)]
9898pub struct ExcelReadOptions {
9899    /// Sheet name to read. If `None`, reads the first sheet.
9900    pub sheet_name: Option<String>,
9901    /// Whether the first row contains column headers.
9902    pub has_headers: bool,
9903    /// Read only these columns (by name). `None` means read all.
9904    /// Matches pandas `usecols` parameter for label-based selection.
9905    pub usecols: Option<Vec<String>>,
9906    /// Explicit column names to use instead of worksheet headers or
9907    /// auto-generated `column_N` names. Matches pandas `names=...`.
9908    pub names: Option<Vec<String>>,
9909    /// Optional column to use as the DataFrame index.
9910    pub index_col: Option<String>,
9911    /// Number of initial rows to skip before reading headers/data.
9912    pub skip_rows: usize,
9913}
9914
9915impl Default for ExcelReadOptions {
9916    fn default() -> Self {
9917        Self {
9918            sheet_name: None,
9919            has_headers: true,
9920            usecols: None,
9921            names: None,
9922            index_col: None,
9923            skip_rows: 0,
9924        }
9925    }
9926}
9927
9928/// Convert a calamine `Data` cell value to a `Scalar`.
9929fn excel_cell_to_scalar(cell: &calamine::Data) -> Scalar {
9930    match cell {
9931        calamine::Data::Int(v) => Scalar::Int64(*v),
9932        calamine::Data::Float(v) => {
9933            if v.is_nan() {
9934                Scalar::Null(NullKind::NaN)
9935            } else if v.fract() == 0.0 && *v >= i64::MIN as f64 && *v <= i64::MAX as f64 {
9936                // Excel stores integers as floats; recover Int64 for whole numbers.
9937                Scalar::Int64(*v as i64)
9938            } else {
9939                Scalar::Float64(*v)
9940            }
9941        }
9942        calamine::Data::String(s) => {
9943            if s.is_empty() {
9944                Scalar::Null(NullKind::Null)
9945            } else {
9946                Scalar::Utf8(s.clone())
9947            }
9948        }
9949        calamine::Data::Bool(b) => Scalar::Bool(*b),
9950        calamine::Data::Empty => Scalar::Null(NullKind::Null),
9951        calamine::Data::DateTime(dt) => {
9952            // Convert ExcelDateTime to string representation for now.
9953            Scalar::Utf8(format!("{dt}"))
9954        }
9955        calamine::Data::DateTimeIso(s) => Scalar::Utf8(s.clone()),
9956        calamine::Data::DurationIso(s) => Scalar::Utf8(s.clone()),
9957        calamine::Data::Error(e) => Scalar::Utf8(format!("#ERROR:{e:?}")),
9958    }
9959}
9960
9961/// Convert a Scalar to an IndexLabel, handling float precision correctly.
9962fn scalar_to_index_label(scalar: Scalar) -> IndexLabel {
9963    match scalar {
9964        Scalar::Int64(v) => IndexLabel::Int64(v),
9965        Scalar::Utf8(s) => IndexLabel::Utf8(s),
9966        Scalar::Float64(v) if v.fract() == 0.0 && v >= i64::MIN as f64 && v <= i64::MAX as f64 => {
9967            IndexLabel::Int64(v as i64)
9968        }
9969        Scalar::Float64(v) => IndexLabel::Utf8(v.to_string()),
9970        Scalar::Bool(b) => IndexLabel::Utf8(if b { "True" } else { "False" }.to_string()),
9971        _ => IndexLabel::Utf8(String::new()),
9972    }
9973}
9974
9975fn infer_writer_emitted_default_excel_index_col(
9976    headers: &[String],
9977    header_generated: &[bool],
9978    columns: &[Vec<Scalar>],
9979    options: &ExcelReadOptions,
9980) -> Option<usize> {
9981    if !options.has_headers
9982        || options.index_col.is_some()
9983        || options.usecols.is_some()
9984        || options.names.is_some()
9985    {
9986        return None;
9987    }
9988
9989    if headers.first()?.as_str() != "column_0"
9990        || !header_generated.first().copied().unwrap_or(false)
9991    {
9992        return None;
9993    }
9994
9995    let first_col = columns.first()?;
9996    if first_col
9997        .iter()
9998        .enumerate()
9999        .all(|(idx, scalar)| matches!(scalar, Scalar::Int64(value) if *value == idx as i64))
10000    {
10001        Some(0)
10002    } else {
10003        None
10004    }
10005}
10006
10007/// Shared parsing logic for Excel data after extracting rows from a workbook.
10008fn parse_excel_rows(
10009    rows: Vec<Vec<calamine::Data>>,
10010    options: &ExcelReadOptions,
10011) -> Result<DataFrame, IoError> {
10012    if rows.is_empty() {
10013        return DataFrame::new(Index::new(Vec::new()), BTreeMap::new()).map_err(IoError::Frame);
10014    }
10015
10016    let resolve_names = |width: usize| -> Result<Option<Vec<String>>, IoError> {
10017        options.names.as_ref().map_or(Ok(None), |names| {
10018            if names.len() == width {
10019                Ok(Some(names.clone()))
10020            } else {
10021                Err(IoError::Excel(format!(
10022                    "expected {width} column names, got {}",
10023                    names.len()
10024                )))
10025            }
10026        })
10027    };
10028
10029    // Extract headers.
10030    let (headers, header_generated, data_rows) = if options.has_headers {
10031        let header_row = &rows[0];
10032        let header_width = header_row.len();
10033        let provided_names = resolve_names(header_width)?;
10034        let (headers, header_generated): (Vec<_>, Vec<_>) = if let Some(names) = provided_names {
10035            (names, vec![false; header_width])
10036        } else {
10037            let header_pairs: Vec<(String, bool)> = header_row
10038                .iter()
10039                .enumerate()
10040                .map(|(i, cell)| match cell {
10041                    calamine::Data::String(s) if !s.is_empty() => (s.clone(), false),
10042                    _ => (format!("column_{i}"), true),
10043                })
10044                .collect();
10045            header_pairs.into_iter().unzip()
10046        };
10047        (headers, header_generated, &rows[1..])
10048    } else {
10049        let ncols = rows.iter().map(Vec::len).max().unwrap_or(0);
10050        let provided_names = resolve_names(ncols)?;
10051        let (headers, header_generated) = if let Some(names) = provided_names {
10052            (names, vec![false; ncols])
10053        } else {
10054            let headers: Vec<String> = (0..ncols).map(|i| format!("column_{i}")).collect();
10055            let header_generated = vec![true; ncols];
10056            (headers, header_generated)
10057        };
10058        (headers, header_generated, rows.as_slice())
10059    };
10060    reject_duplicate_headers(&headers)?;
10061
10062    if let Some(ref usecols) = options.usecols {
10063        validate_usecols(&headers, usecols)?;
10064    }
10065
10066    let ncols = headers.len();
10067
10068    // Accumulate columns.
10069    let mut columns: Vec<Vec<Scalar>> = (0..ncols)
10070        .map(|_| Vec::with_capacity(data_rows.len()))
10071        .collect();
10072
10073    for row in data_rows {
10074        for (col_idx, col_vec) in columns.iter_mut().enumerate() {
10075            let cell = row.get(col_idx).unwrap_or(&calamine::Data::Empty);
10076            col_vec.push(excel_cell_to_scalar(cell));
10077        }
10078    }
10079
10080    let (headers, header_generated, columns) = if let Some(ref usecols) = options.usecols {
10081        let mut filtered_headers = Vec::new();
10082        let mut filtered_generated = Vec::new();
10083        let mut filtered_columns = Vec::new();
10084        for ((name, generated), values) in headers.into_iter().zip(header_generated).zip(columns) {
10085            if usecols.contains(&name) {
10086                filtered_headers.push(name);
10087                filtered_generated.push(generated);
10088                filtered_columns.push(values);
10089            }
10090        }
10091        (filtered_headers, filtered_generated, filtered_columns)
10092    } else {
10093        (headers, header_generated, columns)
10094    };
10095
10096    // Handle index_col if specified.
10097    let index_col_idx = if let Some(ref idx_name) = options.index_col {
10098        let pos = headers.iter().position(|h| h == idx_name);
10099        if pos.is_none() {
10100            return Err(IoError::MissingIndexColumn(idx_name.clone()));
10101        }
10102        pos
10103    } else {
10104        infer_writer_emitted_default_excel_index_col(&headers, &header_generated, &columns, options)
10105    };
10106
10107    let index_name = index_col_idx.and_then(|idx_pos| {
10108        if !header_generated[idx_pos] {
10109            Some(headers[idx_pos].clone())
10110        } else {
10111            None
10112        }
10113    });
10114
10115    let mut out_columns = BTreeMap::new();
10116    let mut column_order = Vec::new();
10117
10118    for (idx, (name, values)) in headers.into_iter().zip(columns).enumerate() {
10119        if Some(idx) == index_col_idx {
10120            continue; // skip index column from data columns
10121        }
10122        out_columns.insert(name.clone(), Column::from_values(values)?);
10123        column_order.push(name);
10124    }
10125
10126    let index = if let Some(idx_pos) = index_col_idx {
10127        let idx_labels: Vec<IndexLabel> = data_rows
10128            .iter()
10129            .map(|row| {
10130                let cell = row.get(idx_pos).unwrap_or(&calamine::Data::Empty);
10131                scalar_to_index_label(excel_cell_to_scalar(cell))
10132            })
10133            .collect();
10134        Index::new(idx_labels).set_names(index_name.as_deref())
10135    } else {
10136        Index::from_i64((0..data_rows.len() as i64).collect())
10137    };
10138
10139    Ok(DataFrame::new_with_column_order(
10140        index,
10141        out_columns,
10142        column_order,
10143    )?)
10144}
10145
10146/// Read an Excel (.xlsx/.xls/.xlsb/.ods) file into a DataFrame.
10147///
10148/// Matches `pd.read_excel(path)` for basic usage.
10149pub fn read_excel(path: &Path, options: &ExcelReadOptions) -> Result<DataFrame, IoError> {
10150    use calamine::{Reader, open_workbook_auto};
10151
10152    let mut workbook = open_workbook_auto(path)
10153        .map_err(|e| IoError::Excel(format!("cannot open workbook: {e}")))?;
10154
10155    let sheet_name = if let Some(ref name) = options.sheet_name {
10156        name.clone()
10157    } else {
10158        let names = workbook.sheet_names();
10159        if names.is_empty() {
10160            return Err(IoError::Excel("workbook contains no sheets".into()));
10161        }
10162        names[0].clone()
10163    };
10164
10165    let range = workbook
10166        .worksheet_range(&sheet_name)
10167        .map_err(|e| IoError::Excel(format!("cannot read sheet '{sheet_name}': {e}")))?;
10168
10169    let rows: Vec<Vec<calamine::Data>> = range
10170        .rows()
10171        .skip(options.skip_rows)
10172        .map(|r| r.to_vec())
10173        .collect();
10174
10175    parse_excel_rows(rows, options)
10176}
10177
10178pub fn read_excel_with_index_cols(
10179    path: &Path,
10180    options: &ExcelReadOptions,
10181    index_cols: &[&str],
10182) -> Result<DataFrame, IoError> {
10183    let frame = read_excel(path, options)?;
10184    promote_frame_index_columns(&frame, index_cols)
10185}
10186
10187/// Read Excel from in-memory bytes.
10188pub fn read_excel_bytes(data: &[u8], options: &ExcelReadOptions) -> Result<DataFrame, IoError> {
10189    use calamine::{Reader, open_workbook_auto_from_rs};
10190
10191    let cursor = std::io::Cursor::new(data);
10192    let mut workbook = open_workbook_auto_from_rs(cursor)
10193        .map_err(|e| IoError::Excel(format!("cannot open workbook from bytes: {e}")))?;
10194
10195    let sheet_name = if let Some(ref name) = options.sheet_name {
10196        name.clone()
10197    } else {
10198        let names = workbook.sheet_names();
10199        if names.is_empty() {
10200            return Err(IoError::Excel("workbook contains no sheets".into()));
10201        }
10202        names[0].clone()
10203    };
10204
10205    let range = workbook
10206        .worksheet_range(&sheet_name)
10207        .map_err(|e| IoError::Excel(format!("cannot read sheet '{sheet_name}': {e}")))?;
10208
10209    let rows: Vec<Vec<calamine::Data>> = range
10210        .rows()
10211        .skip(options.skip_rows)
10212        .map(|r| r.to_vec())
10213        .collect();
10214
10215    parse_excel_rows(rows, options)
10216}
10217
10218pub fn read_excel_bytes_with_index_cols(
10219    data: &[u8],
10220    options: &ExcelReadOptions,
10221    index_cols: &[&str],
10222) -> Result<DataFrame, IoError> {
10223    let frame = read_excel_bytes(data, options)?;
10224    promote_frame_index_columns(&frame, index_cols)
10225}
10226
10227/// Read multiple sheets from an Excel file.
10228///
10229/// Matches `pd.read_excel(path, sheet_name=[...])` when `sheet_name`
10230/// is a list of sheet names — pandas returns a dict
10231/// `{name: DataFrame}`. Pass `sheet_names=None` to read every sheet
10232/// in the workbook (pandas `sheet_name=None`).
10233///
10234/// The outer Excel reader options (`has_headers`, `index_col`,
10235/// `skip_rows`) are applied uniformly to each selected sheet. The
10236/// per-sheet `sheet_name` option on `options` is ignored here
10237/// because the explicit `sheet_names` argument drives selection.
10238/// Read multiple sheets preserving workbook iteration order.
10239///
10240/// Matches `pd.read_excel(sheet_name=None)` exactly — pandas returns
10241/// a `dict` and, since Python 3.7, dict iteration order matches
10242/// insertion order, which in turn matches workbook sheet position.
10243/// `BTreeMap` (used by `read_excel_sheets`) would alphabetize, so
10244/// this sibling returns `Vec<(String, DataFrame)>` to preserve order.
10245pub fn read_excel_sheets_ordered(
10246    path: &Path,
10247    sheet_names: Option<&[String]>,
10248    options: &ExcelReadOptions,
10249) -> Result<Vec<(String, DataFrame)>, IoError> {
10250    use calamine::{Reader, open_workbook_auto};
10251
10252    let mut workbook = open_workbook_auto(path)
10253        .map_err(|e| IoError::Excel(format!("cannot open workbook: {e}")))?;
10254    let available: Vec<String> = workbook.sheet_names();
10255    // Per br-frankenpandas-c9cb4: HashSet<&str> for O(1) membership;
10256    // was O(m × n) Vec::iter().any() per requested name.
10257    let available_set: HashSet<&str> = available.iter().map(String::as_str).collect();
10258    let selected: Vec<String> = match sheet_names {
10259        Some(names) => {
10260            for name in names {
10261                if !available_set.contains(name.as_str()) {
10262                    return Err(IoError::Excel(format!(
10263                        "workbook does not contain sheet {name:?}"
10264                    )));
10265                }
10266            }
10267            names.to_vec()
10268        }
10269        None => available.clone(),
10270    };
10271    if selected.is_empty() {
10272        return Err(IoError::Excel("no sheets selected".to_owned()));
10273    }
10274    let mut out = Vec::with_capacity(selected.len());
10275    for sheet in &selected {
10276        let range = workbook
10277            .worksheet_range(sheet)
10278            .map_err(|e| IoError::Excel(format!("cannot read sheet {sheet:?}: {e}")))?;
10279        let rows: Vec<Vec<calamine::Data>> = range
10280            .rows()
10281            .skip(options.skip_rows)
10282            .map(|r| r.to_vec())
10283            .collect();
10284        let frame = parse_excel_rows(rows, options)?;
10285        out.push((sheet.clone(), frame));
10286    }
10287    Ok(out)
10288}
10289
10290/// Byte-based counterpart to `read_excel_sheets_ordered`.
10291pub fn read_excel_sheets_ordered_bytes(
10292    data: &[u8],
10293    sheet_names: Option<&[String]>,
10294    options: &ExcelReadOptions,
10295) -> Result<Vec<(String, DataFrame)>, IoError> {
10296    use calamine::{Reader, open_workbook_auto_from_rs};
10297
10298    let cursor = std::io::Cursor::new(data);
10299    let mut workbook = open_workbook_auto_from_rs(cursor)
10300        .map_err(|e| IoError::Excel(format!("cannot open workbook from bytes: {e}")))?;
10301    let available: Vec<String> = workbook.sheet_names();
10302    // Per br-frankenpandas-c9cb4: HashSet<&str> for O(1) membership;
10303    // was O(m × n) Vec::iter().any() per requested name.
10304    let available_set: HashSet<&str> = available.iter().map(String::as_str).collect();
10305    let selected: Vec<String> = match sheet_names {
10306        Some(names) => {
10307            for name in names {
10308                if !available_set.contains(name.as_str()) {
10309                    return Err(IoError::Excel(format!(
10310                        "workbook does not contain sheet {name:?}"
10311                    )));
10312                }
10313            }
10314            names.to_vec()
10315        }
10316        None => available.clone(),
10317    };
10318    if selected.is_empty() {
10319        return Err(IoError::Excel("no sheets selected".to_owned()));
10320    }
10321    let mut out = Vec::with_capacity(selected.len());
10322    for sheet in &selected {
10323        let range = workbook
10324            .worksheet_range(sheet)
10325            .map_err(|e| IoError::Excel(format!("cannot read sheet {sheet:?}: {e}")))?;
10326        let rows: Vec<Vec<calamine::Data>> = range
10327            .rows()
10328            .skip(options.skip_rows)
10329            .map(|r| r.to_vec())
10330            .collect();
10331        let frame = parse_excel_rows(rows, options)?;
10332        out.push((sheet.clone(), frame));
10333    }
10334    Ok(out)
10335}
10336
10337pub fn read_excel_sheets(
10338    path: &Path,
10339    sheet_names: Option<&[String]>,
10340    options: &ExcelReadOptions,
10341) -> Result<BTreeMap<String, DataFrame>, IoError> {
10342    use calamine::{Reader, open_workbook_auto};
10343
10344    let mut workbook = open_workbook_auto(path)
10345        .map_err(|e| IoError::Excel(format!("cannot open workbook: {e}")))?;
10346    let available: Vec<String> = workbook.sheet_names();
10347    // Per br-frankenpandas-c9cb4: HashSet<&str> for O(1) membership;
10348    // was O(m × n) Vec::iter().any() per requested name.
10349    let available_set: HashSet<&str> = available.iter().map(String::as_str).collect();
10350    let selected: Vec<String> = match sheet_names {
10351        Some(names) => {
10352            for name in names {
10353                if !available_set.contains(name.as_str()) {
10354                    return Err(IoError::Excel(format!(
10355                        "workbook does not contain sheet {name:?}"
10356                    )));
10357                }
10358            }
10359            names.to_vec()
10360        }
10361        None => available.clone(),
10362    };
10363    if selected.is_empty() {
10364        return Err(IoError::Excel("no sheets selected".to_owned()));
10365    }
10366
10367    let mut out = BTreeMap::new();
10368    for sheet in &selected {
10369        let range = workbook
10370            .worksheet_range(sheet)
10371            .map_err(|e| IoError::Excel(format!("cannot read sheet {sheet:?}: {e}")))?;
10372        let rows: Vec<Vec<calamine::Data>> = range
10373            .rows()
10374            .skip(options.skip_rows)
10375            .map(|r| r.to_vec())
10376            .collect();
10377        let frame = parse_excel_rows(rows, options)?;
10378        out.insert(sheet.clone(), frame);
10379    }
10380    Ok(out)
10381}
10382
10383/// Read multiple sheets from Excel bytes.
10384///
10385/// Byte-based counterpart to `read_excel_sheets`.
10386pub fn read_excel_sheets_bytes(
10387    data: &[u8],
10388    sheet_names: Option<&[String]>,
10389    options: &ExcelReadOptions,
10390) -> Result<BTreeMap<String, DataFrame>, IoError> {
10391    use calamine::{Reader, open_workbook_auto_from_rs};
10392
10393    let cursor = std::io::Cursor::new(data);
10394    let mut workbook = open_workbook_auto_from_rs(cursor)
10395        .map_err(|e| IoError::Excel(format!("cannot open workbook from bytes: {e}")))?;
10396    let available: Vec<String> = workbook.sheet_names();
10397    // Per br-frankenpandas-c9cb4: HashSet<&str> for O(1) membership;
10398    // was O(m × n) Vec::iter().any() per requested name.
10399    let available_set: HashSet<&str> = available.iter().map(String::as_str).collect();
10400    let selected: Vec<String> = match sheet_names {
10401        Some(names) => {
10402            for name in names {
10403                if !available_set.contains(name.as_str()) {
10404                    return Err(IoError::Excel(format!(
10405                        "workbook does not contain sheet {name:?}"
10406                    )));
10407                }
10408            }
10409            names.to_vec()
10410        }
10411        None => available.clone(),
10412    };
10413    if selected.is_empty() {
10414        return Err(IoError::Excel("no sheets selected".to_owned()));
10415    }
10416
10417    let mut out = BTreeMap::new();
10418    for sheet in &selected {
10419        let range = workbook
10420            .worksheet_range(sheet)
10421            .map_err(|e| IoError::Excel(format!("cannot read sheet {sheet:?}: {e}")))?;
10422        let rows: Vec<Vec<calamine::Data>> = range
10423            .rows()
10424            .skip(options.skip_rows)
10425            .map(|r| r.to_vec())
10426            .collect();
10427        let frame = parse_excel_rows(rows, options)?;
10428        out.insert(sheet.clone(), frame);
10429    }
10430    Ok(out)
10431}
10432
10433/// Write a DataFrame to an Excel (.xlsx) file.
10434///
10435/// Matches `pd.DataFrame.to_excel(path)`.
10436pub fn write_excel(frame: &DataFrame, path: &Path) -> Result<(), IoError> {
10437    let bytes = write_excel_bytes(frame)?;
10438    std::fs::write(path, bytes)?;
10439    Ok(())
10440}
10441
10442fn write_excel_index_label(
10443    worksheet: &mut rust_xlsxwriter::Worksheet,
10444    excel_row: u32,
10445    excel_col: u16,
10446    label: &IndexLabel,
10447) -> Result<(), IoError> {
10448    match label {
10449        IndexLabel::Int64(v) => {
10450            worksheet
10451                .write_number(excel_row, excel_col, *v as f64)
10452                .map_err(|e| IoError::Excel(format!("write index int: {e}")))?;
10453        }
10454        IndexLabel::Utf8(s) => {
10455            worksheet
10456                .write_string(excel_row, excel_col, s.as_str())
10457                .map_err(|e| IoError::Excel(format!("write index string: {e}")))?;
10458        }
10459        IndexLabel::Timedelta64(v) => {
10460            if *v != Timedelta::NAT {
10461                worksheet
10462                    .write_string(excel_row, excel_col, Timedelta::format(*v))
10463                    .map_err(|e| IoError::Excel(format!("write index timedelta: {e}")))?;
10464            }
10465        }
10466        IndexLabel::Datetime64(v) => {
10467            if *v != i64::MIN {
10468                worksheet
10469                    .write_string(excel_row, excel_col, label.to_string())
10470                    .map_err(|e| IoError::Excel(format!("write index datetime: {e}")))?;
10471            }
10472        }
10473        // Missing labels leave the cell blank, like NAT timedelta/datetime
10474        // above (pandas writes an empty cell for a NaN index label).
10475        IndexLabel::Float64(v) => {
10476            worksheet
10477                .write_number(excel_row, excel_col, v.0)
10478                .map_err(|e| IoError::Excel(format!("write index float: {e}")))?;
10479        }
10480        IndexLabel::Bool(b) => {
10481            worksheet
10482                .write_boolean(excel_row, excel_col, *b)
10483                .map_err(|e| IoError::Excel(format!("write index bool: {e}")))?;
10484        }
10485        IndexLabel::Null(_) => {}
10486    }
10487    Ok(())
10488}
10489
10490fn write_excel_scalar(
10491    worksheet: &mut rust_xlsxwriter::Worksheet,
10492    excel_row: u32,
10493    excel_col: u16,
10494    scalar: &Scalar,
10495) -> Result<(), IoError> {
10496    match scalar {
10497        Scalar::Int64(v) => {
10498            worksheet
10499                .write_number(excel_row, excel_col, *v as f64)
10500                .map_err(|e| IoError::Excel(format!("write int: {e}")))?;
10501        }
10502        Scalar::Float64(v) if !v.is_nan() => {
10503            worksheet
10504                .write_number(excel_row, excel_col, *v)
10505                .map_err(|e| IoError::Excel(format!("write float: {e}")))?;
10506        }
10507        Scalar::Bool(b) => {
10508            worksheet
10509                .write_boolean(excel_row, excel_col, *b)
10510                .map_err(|e| IoError::Excel(format!("write bool: {e}")))?;
10511        }
10512        Scalar::Utf8(s) => {
10513            worksheet
10514                .write_string(excel_row, excel_col, s.as_str())
10515                .map_err(|e| IoError::Excel(format!("write string: {e}")))?;
10516        }
10517        Scalar::Timedelta64(v) => {
10518            if *v != Timedelta::NAT {
10519                worksheet
10520                    .write_string(excel_row, excel_col, Timedelta::format(*v))
10521                    .map_err(|e| IoError::Excel(format!("write timedelta: {e}")))?;
10522            }
10523        }
10524        Scalar::Datetime64(v) => {
10525            if *v != Timestamp::NAT {
10526                worksheet
10527                    .write_string(excel_row, excel_col, format_datetime_ns(*v))
10528                    .map_err(|e| IoError::Excel(format!("write datetime: {e}")))?;
10529            }
10530        }
10531        Scalar::Period(p) => {
10532            if p.ordinal != i64::MIN {
10533                worksheet
10534                    .write_string(excel_row, excel_col, p.calendar_string())
10535                    .map_err(|e| IoError::Excel(format!("write period: {e}")))?;
10536            }
10537        }
10538        Scalar::Interval(iv) => {
10539            worksheet
10540                .write_string(excel_row, excel_col, format!("{iv}"))
10541                .map_err(|e| IoError::Excel(format!("write interval: {e}")))?;
10542        }
10543        Scalar::Float64(_) | Scalar::Null(_) => {}
10544    }
10545    Ok(())
10546}
10547
10548/// Write a DataFrame to Excel (.xlsx) bytes in memory.
10549///
10550/// Matches pandas `DataFrame.to_excel()` default index behavior by emitting
10551/// the index as the first worksheet column.
10552pub fn write_excel_bytes(frame: &DataFrame) -> Result<Vec<u8>, IoError> {
10553    write_excel_bytes_with_options(frame, &ExcelWriteOptions::default())
10554}
10555
10556/// Options for serializing a DataFrame to Excel.
10557///
10558/// Mirrors the subset of `pd.DataFrame.to_excel` parameters that
10559/// don't depend on the workbook writer itself.
10560#[derive(Debug, Clone)]
10561pub struct ExcelWriteOptions {
10562    /// Target sheet name. Default: `"Sheet1"` (rust_xlsxwriter default).
10563    pub sheet_name: String,
10564    /// Whether to write the row index as a leading column. Matches
10565    /// pandas `index=True|False`. Default: true.
10566    pub index: bool,
10567    /// Header label for the index column when `index=true`. When
10568    /// `None`, the frame's index name is used (falling back to an
10569    /// empty string). Matches pandas `index_label=...`.
10570    pub index_label: Option<String>,
10571    /// Whether to emit the column-name header row. Matches pandas
10572    /// `header=True|False`. Default: true.
10573    pub header: bool,
10574}
10575
10576impl Default for ExcelWriteOptions {
10577    fn default() -> Self {
10578        Self {
10579            sheet_name: "Sheet1".to_string(),
10580            index: true,
10581            index_label: None,
10582            header: true,
10583        }
10584    }
10585}
10586
10587/// Serialize a DataFrame to Excel bytes with explicit options.
10588///
10589/// Matches `pd.DataFrame.to_excel(sheet_name, index, index_label,
10590/// header)` for the in-memory byte form. The default `ExcelWriteOptions`
10591/// reproduces the existing `write_excel_bytes` behavior (index=true,
10592/// sheet_name="Sheet1").
10593pub fn write_excel_bytes_with_options(
10594    frame: &DataFrame,
10595    options: &ExcelWriteOptions,
10596) -> Result<Vec<u8>, IoError> {
10597    if options.index && frame.row_multiindex().is_some() {
10598        let materialized = materialize_named_row_multiindex_columns(frame)?;
10599        let mut nested_options = options.clone();
10600        nested_options.index = false;
10601        nested_options.index_label = None;
10602        return write_excel_bytes_with_options(&materialized, &nested_options);
10603    }
10604
10605    use rust_xlsxwriter::Workbook;
10606
10607    let mut workbook = Workbook::new();
10608    let worksheet = workbook.add_worksheet();
10609    worksheet
10610        .set_name(options.sheet_name.as_str())
10611        .map_err(|e| IoError::Excel(format!("set sheet name: {e}")))?;
10612
10613    let col_names: Vec<String> = frame.column_names().into_iter().cloned().collect();
10614    let data_col_offset: u16 = if options.index { 1 } else { 0 };
10615
10616    // Header row (optional).
10617    if options.header {
10618        if options.index {
10619            let idx_header = options
10620                .index_label
10621                .as_deref()
10622                .unwrap_or_else(|| frame.index().name().unwrap_or(""));
10623            worksheet
10624                .write_string(0, 0, idx_header)
10625                .map_err(|e| IoError::Excel(format!("write index header: {e}")))?;
10626        }
10627        for (col_idx, name) in col_names.iter().enumerate() {
10628            worksheet
10629                .write_string(0, data_col_offset + col_idx as u16, name.as_str())
10630                .map_err(|e| IoError::Excel(format!("write header: {e}")))?;
10631        }
10632    }
10633
10634    // Data rows — when header=true the first data row lands at excel
10635    // row 1; when header=false data starts at row 0.
10636    let header_rows: u32 = if options.header { 1 } else { 0 };
10637    let nrows = frame.index().len();
10638    for row_idx in 0..nrows {
10639        let excel_row = row_idx as u32 + header_rows;
10640        if options.index
10641            && let Some(label) = frame.index().labels().get(row_idx)
10642        {
10643            write_excel_index_label(worksheet, excel_row, 0, label)?;
10644        }
10645        for (col_idx, name) in col_names.iter().enumerate() {
10646            if let Some(col) = frame.column(name)
10647                && let Some(scalar) = col.value(row_idx)
10648            {
10649                write_excel_scalar(
10650                    worksheet,
10651                    excel_row,
10652                    data_col_offset + col_idx as u16,
10653                    scalar,
10654                )?;
10655            }
10656        }
10657    }
10658
10659    let buf = workbook
10660        .save_to_buffer()
10661        .map_err(|e| IoError::Excel(format!("save workbook: {e}")))?;
10662
10663    Ok(buf)
10664}
10665
10666/// File-based counterpart to `write_excel_bytes_with_options`.
10667pub fn write_excel_with_options(
10668    frame: &DataFrame,
10669    path: &Path,
10670    options: &ExcelWriteOptions,
10671) -> Result<(), IoError> {
10672    let bytes = write_excel_bytes_with_options(frame, options)?;
10673    std::fs::write(path, bytes)?;
10674    Ok(())
10675}
10676
10677// ── Arrow IPC / Feather I/O ──────────────────────────────────────────────
10678
10679/// Write a DataFrame to Arrow IPC (Feather v2) bytes in memory.
10680///
10681/// Matches `pd.DataFrame.to_feather()`. Feather v2 is the Arrow IPC file format
10682/// — the fastest columnar interchange format, recommended by pandas over HDF5.
10683pub fn write_feather_bytes(frame: &DataFrame) -> Result<Vec<u8>, IoError> {
10684    use arrow::ipc::writer::FileWriter;
10685
10686    let batch = dataframe_to_record_batch(frame)?;
10687    let schema = batch.schema();
10688
10689    let mut buf = Vec::new();
10690    let mut writer =
10691        FileWriter::try_new(&mut buf, &schema).map_err(|e| IoError::Arrow(e.to_string()))?;
10692    writer
10693        .write(&batch)
10694        .map_err(|e| IoError::Arrow(e.to_string()))?;
10695    writer.finish().map_err(|e| IoError::Arrow(e.to_string()))?;
10696    Ok(buf)
10697}
10698
10699/// Read a DataFrame from Arrow IPC (Feather v2) bytes in memory.
10700///
10701/// Matches `pd.read_feather()`.
10702pub fn read_feather_bytes(data: &[u8]) -> Result<DataFrame, IoError> {
10703    use arrow::ipc::reader::FileReader;
10704
10705    let cursor = std::io::Cursor::new(data);
10706    let reader = FileReader::try_new(cursor, None).map_err(|e| IoError::Arrow(e.to_string()))?;
10707
10708    let mut all_frames: Vec<DataFrame> = Vec::new();
10709    for batch_result in reader {
10710        let batch = batch_result.map_err(|e| IoError::Arrow(e.to_string()))?;
10711        all_frames.push(record_batch_to_dataframe(&batch)?);
10712    }
10713
10714    if all_frames.is_empty() {
10715        return Ok(DataFrame::new_with_column_order(
10716            Index::new(vec![]),
10717            BTreeMap::new(),
10718            vec![],
10719        )?);
10720    }
10721
10722    if all_frames.len() == 1 {
10723        if let Some(frame) = all_frames.into_iter().next() {
10724            return Ok(frame);
10725        }
10726        return Err(IoError::Arrow(
10727            "feather reader produced zero record batches".to_owned(),
10728        ));
10729    }
10730
10731    let refs: Vec<&DataFrame> = all_frames.iter().collect();
10732    fp_frame::concat_dataframes(&refs).map_err(IoError::from)
10733}
10734
10735/// Write a DataFrame to an Arrow IPC (Feather v2) file.
10736///
10737/// Matches `pd.DataFrame.to_feather(path)`.
10738pub fn write_feather(frame: &DataFrame, path: &Path) -> Result<(), IoError> {
10739    let bytes = write_feather_bytes(frame)?;
10740    std::fs::write(path, bytes)?;
10741    Ok(())
10742}
10743
10744/// Read a DataFrame from an Arrow IPC (Feather v2) file.
10745///
10746/// Matches `pd.read_feather(path)`.
10747pub fn read_feather(path: &Path) -> Result<DataFrame, IoError> {
10748    let data = std::fs::read(path)?;
10749    read_feather_bytes(&data)
10750}
10751
10752/// Write a DataFrame to Arrow IPC stream bytes (streaming format, no random access).
10753///
10754/// Unlike Feather (file format), the stream format has no footer and supports
10755/// streaming reads without seeking. Used for inter-process communication.
10756pub fn write_ipc_stream_bytes(frame: &DataFrame) -> Result<Vec<u8>, IoError> {
10757    use arrow::ipc::writer::StreamWriter;
10758
10759    let batch = dataframe_to_record_batch(frame)?;
10760    let schema = batch.schema();
10761
10762    let mut buf = Vec::new();
10763    let mut writer =
10764        StreamWriter::try_new(&mut buf, &schema).map_err(|e| IoError::Arrow(e.to_string()))?;
10765    writer
10766        .write(&batch)
10767        .map_err(|e| IoError::Arrow(e.to_string()))?;
10768    writer.finish().map_err(|e| IoError::Arrow(e.to_string()))?;
10769    Ok(buf)
10770}
10771
10772/// Read a DataFrame from Arrow IPC stream bytes (streaming format).
10773pub fn read_ipc_stream_bytes(data: &[u8]) -> Result<DataFrame, IoError> {
10774    use arrow::ipc::reader::StreamReader;
10775
10776    if data.len() >= 4 {
10777        let prefix = u32::from_le_bytes([data[0], data[1], data[2], data[3]]);
10778        let (meta_len, header_overhead) = if prefix == 0xFFFF_FFFF {
10779            if data.len() < 8 {
10780                return Err(IoError::Arrow(
10781                    "truncated IPC stream: missing metadata length after continuation marker"
10782                        .to_string(),
10783                ));
10784            }
10785            let len = i32::from_le_bytes([data[4], data[5], data[6], data[7]]);
10786            (len, 8usize)
10787        } else {
10788            (prefix as i32, 4usize)
10789        };
10790        if meta_len < 0 {
10791            return Err(IoError::Arrow(format!(
10792                "invalid negative IPC message length: {meta_len}"
10793            )));
10794        }
10795        if (meta_len as usize) > data.len().saturating_sub(header_overhead) {
10796            return Err(IoError::Arrow(format!(
10797                "truncated IPC stream: message length {meta_len} exceeds input size {}",
10798                data.len().saturating_sub(header_overhead)
10799            )));
10800        }
10801    }
10802
10803    let cursor = std::io::Cursor::new(data);
10804    let reader = StreamReader::try_new(cursor, None).map_err(|e| IoError::Arrow(e.to_string()))?;
10805
10806    let mut all_frames: Vec<DataFrame> = Vec::new();
10807    for batch_result in reader {
10808        let batch = batch_result.map_err(|e| IoError::Arrow(e.to_string()))?;
10809        all_frames.push(record_batch_to_dataframe(&batch)?);
10810    }
10811
10812    if all_frames.is_empty() {
10813        return Ok(DataFrame::new_with_column_order(
10814            Index::new(vec![]),
10815            BTreeMap::new(),
10816            vec![],
10817        )?);
10818    }
10819
10820    if all_frames.len() == 1 {
10821        if let Some(frame) = all_frames.into_iter().next() {
10822            return Ok(frame);
10823        }
10824        return Err(IoError::Arrow(
10825            "ipc stream reader produced zero record batches".to_owned(),
10826        ));
10827    }
10828
10829    let refs: Vec<&DataFrame> = all_frames.iter().collect();
10830    fp_frame::concat_dataframes(&refs).map_err(IoError::from)
10831}
10832
10833// ── SQL I/O ─────────────────────────────────────────────────────────────
10834
10835/// Options for writing a DataFrame to SQL.
10836#[derive(Debug, Clone, Copy, PartialEq, Eq)]
10837pub enum SqlIfExists {
10838    /// Raise an error if the table already exists.
10839    Fail,
10840    /// Drop the table and recreate it.
10841    Replace,
10842    /// Insert new rows into the existing table.
10843    Append,
10844}
10845
10846/// Strategy for emitting INSERT statements during `write_sql`.
10847///
10848/// Matches `pd.DataFrame.to_sql(.., method=...)` shape:
10849/// `Single` (default) emits one `INSERT INTO t VALUES (?, ...)` per row,
10850/// reusing a prepared statement under a transaction. `Multi` builds a
10851/// single multi-row `INSERT INTO t VALUES (...), (...), ...` statement
10852/// per chunk, where chunk size is `max_param_count() / num_cols` (or
10853/// the whole frame when the backend reports no max). `Multi` typically
10854/// wins on backends with high per-statement overhead (PostgreSQL,
10855/// MySQL); SQLite is already fast under prepared-statement reuse so the
10856/// gap there is small.
10857///
10858/// Per br-frankenpandas-i0ml (fd90.19).
10859#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
10860pub enum SqlInsertMethod {
10861    /// One INSERT per row, prepared once and re-bound per row.
10862    #[default]
10863    Single,
10864    /// Multi-row INSERT, chunked by the backend's parameter limit.
10865    Multi,
10866}
10867
10868/// Options for reading SQL query results into a DataFrame.
10869#[derive(Debug, Clone)]
10870pub struct SqlReadOptions {
10871    /// Positional parameters to bind to `?` placeholders in the SQL query.
10872    pub params: Option<Vec<Scalar>>,
10873    /// Column names to coerce via pandas-style parse_dates handling.
10874    /// Currently supports explicit column-name selection.
10875    pub parse_dates: Option<Vec<String>>,
10876    /// Promote decimal-like SQL text result columns to Float64.
10877    ///
10878    /// This is an opt-in form of pandas' `coerce_float` behavior for
10879    /// backends that expose NUMERIC/DECIMAL/MONEY values through text.
10880    /// Columns containing any non-numeric strings are left unchanged.
10881    pub coerce_float: bool,
10882    /// Per-column dtype override applied after row materialization.
10883    ///
10884    /// Matches `pd.read_sql(.., dtype={'col': 'float64'})`. Each entry casts
10885    /// the named column to the declared dtype using `fp_types::cast_scalar_owned`.
10886    /// Map entries for columns not present in the result are silently
10887    /// ignored (matches pandas). Columns also listed in `parse_dates` are
10888    /// skipped to avoid double-cast errors — parse_dates wins.
10889    ///
10890    /// Per br-frankenpandas-l9pt (fd90.11).
10891    pub dtype: Option<BTreeMap<String, DType>>,
10892    /// Optional schema namespace for `read_sql_table` lookups.
10893    ///
10894    /// Matches `pd.read_sql_table(table, con, schema=...)`. When the
10895    /// backend reports `supports_schemas() == true` (PostgreSQL, MySQL,
10896    /// MSSQL, etc.) and `schema` is `Some(s)`, the SELECT references
10897    /// `s.table` with each part quoted by `conn.quote_identifier(...)`.
10898    /// When the backend reports `supports_schemas() == false` (SQLite),
10899    /// any `Some(s)` here is rejected before query execution. Pandas /
10900    /// SQLAlchemy raises `NotImplementedError` on that surface; failing
10901    /// closed avoids silently reading an unqualified table from the wrong
10902    /// namespace.
10903    ///
10904    /// Per br-frankenpandas-u6zn (fd90.14).
10905    pub schema: Option<String>,
10906    /// Optional projection list for `read_sql_table` reads.
10907    ///
10908    /// Matches `pd.read_sql_table(table, con, columns=[...])`. When
10909    /// `Some(list)`, the emitted SELECT projects only those columns
10910    /// (and in that order) instead of `SELECT *`. `None` preserves
10911    /// `SELECT *`. An empty Vec is rejected with `IoError::Sql` —
10912    /// pandas raises ValueError there. Each entry is validated via
10913    /// the standard alphanumeric+underscore policy.
10914    ///
10915    /// Note: `read_sql` / `read_sql_query` ignore this field — it
10916    /// only takes effect on `read_sql_table*` paths, where
10917    /// frankenpandas builds the SELECT itself.
10918    ///
10919    /// Per br-frankenpandas-d3e9 (fd90.34).
10920    pub columns: Option<Vec<String>>,
10921    /// Optional column name to promote to the DataFrame index.
10922    ///
10923    /// Matches `pd.read_sql(.., index_col=...)` and
10924    /// `pd.read_sql_table(table, con, index_col=...)`. When
10925    /// `Some(name)`, after row materialization the named column is
10926    /// removed from the result and used as the DataFrame index. The
10927    /// column must exist in the read result (or in the projection
10928    /// when `columns` is also set). `None` preserves the default
10929    /// RangeIndex.
10930    ///
10931    /// Empty string is rejected with `IoError::Sql` to match
10932    /// pandas' ValueError. List-of-strings (for MultiIndex) is out
10933    /// of scope for this slice — single index only.
10934    ///
10935    /// Per br-frankenpandas-c1h9 (fd90.36).
10936    pub index_col: Option<String>,
10937}
10938
10939impl Default for SqlReadOptions {
10940    /// Per br-frankenpandas-o0x6 (fd90.41): pandas defaults
10941    /// `coerce_float=True` for `read_sql` / `read_sql_query` /
10942    /// `read_sql_table` so we follow suit. Other defaults are the
10943    /// natural empty / None values.
10944    fn default() -> Self {
10945        Self {
10946            params: None,
10947            parse_dates: None,
10948            coerce_float: true,
10949            dtype: None,
10950            schema: None,
10951            columns: None,
10952            index_col: None,
10953        }
10954    }
10955}
10956
10957/// Options for writing a DataFrame to SQL.
10958#[derive(Debug, Clone, PartialEq, Eq)]
10959pub struct SqlWriteOptions {
10960    /// Behavior when the target table already exists.
10961    pub if_exists: SqlIfExists,
10962    /// Whether to materialize the DataFrame index as the leading SQL column.
10963    pub index: bool,
10964    /// Optional override for the emitted index column name.
10965    pub index_label: Option<String>,
10966    /// Optional schema namespace for CREATE TABLE / INSERT routing.
10967    ///
10968    /// Matches `pd.DataFrame.to_sql(table, con, schema=...)`. When the
10969    /// backend reports `supports_schemas() == true` and `schema` is
10970    /// `Some(s)`, generated CREATE TABLE / INSERT statements target
10971    /// `\"s\".\"table\"`. On backends that report `false` (SQLite),
10972    /// `Some(s)` is silently ignored — preserves SQLite users' existing
10973    /// option structs.
10974    ///
10975    /// Per br-frankenpandas-udn6 (fd90.15).
10976    pub schema: Option<String>,
10977    /// Per-column SQL-type override applied during CREATE TABLE.
10978    ///
10979    /// Matches `pd.DataFrame.to_sql(.., dtype={'amount': 'NUMERIC(10,2)'})`.
10980    /// Each entry's value is the literal SQL type string emitted in the
10981    /// column definition for that column. Map entries for columns not
10982    /// in the frame are silently ignored (matches pandas). Falls back
10983    /// to `conn.dtype_sql(DType)` when no override is present.
10984    ///
10985    /// Per br-frankenpandas-ev2s (fd90.18).
10986    pub dtype: Option<BTreeMap<String, String>>,
10987    /// INSERT-emission strategy.
10988    ///
10989    /// Default `Single` matches pandas' default: one INSERT per row,
10990    /// re-binding a prepared statement under a transaction. `Multi`
10991    /// switches to multi-row VALUES batched by `conn.max_param_count()`,
10992    /// matching `pd.to_sql(.., method='multi')`.
10993    ///
10994    /// Per br-frankenpandas-i0ml (fd90.19).
10995    pub method: SqlInsertMethod,
10996    /// Maximum rows per transaction-bounded INSERT chunk.
10997    ///
10998    /// Matches `pd.DataFrame.to_sql(.., chunksize=...)`. When `Some(n)`,
10999    /// the row emit loop batches into chunks of `n` rows, each routed
11000    /// through its own `insert_rows` call (which on transactional
11001    /// backends commits a fresh transaction per chunk). This caps WAL /
11002    /// journal size for huge frames where the default `Single`
11003    /// single-transaction mode would balloon. For `Multi` mode the
11004    /// effective per-chunk row count is `min(chunksize,
11005    /// max_param_count / num_cols)`. `None` preserves existing
11006    /// single-transaction semantics.
11007    ///
11008    /// `Some(0)` is rejected — pandas raises ValueError there too.
11009    ///
11010    /// Per br-frankenpandas-ls9z (fd90.33).
11011    pub chunksize: Option<usize>,
11012}
11013
11014/// Backend-agnostic in-memory representation of a SQL query result.
11015#[derive(Debug, Clone, PartialEq)]
11016pub struct SqlQueryResult {
11017    pub columns: Vec<String>,
11018    pub rows: Vec<Vec<Scalar>>,
11019}
11020
11021type SqlColumnDtypeHints = Vec<Option<DType>>;
11022type SqlMaterializedColumns = (Vec<String>, Vec<Vec<Scalar>>, SqlColumnDtypeHints);
11023
11024/// Backend-neutral SQL column metadata.
11025#[derive(Debug, Clone, PartialEq, Eq)]
11026pub struct SqlColumnSchema {
11027    pub name: String,
11028    pub declared_type: Option<String>,
11029    pub nullable: bool,
11030    pub default_value: Option<String>,
11031    pub primary_key_ordinal: Option<usize>,
11032    /// Column-level comment text, when the backend exposes one.
11033    ///
11034    /// Per br-frankenpandas-cfld (fd90.35). SQLite has no column-comment
11035    /// storage so the rusqlite override always emits `None`. PostgreSQL
11036    /// impls populate from `pg_catalog.pg_description.col_description`;
11037    /// MySQL uses `information_schema.columns.column_comment`; MSSQL
11038    /// reads from `sys.extended_properties`. Companion to the
11039    /// table-level `table_comment` (fd90.32) — together they round
11040    /// out SQLAlchemy.Inspector.get_columns() parity (its dict shape
11041    /// includes a `'comment'` key).
11042    pub comment: Option<String>,
11043    /// Whether the column is auto-incrementing.
11044    ///
11045    /// Per br-frankenpandas-bkl2 (fd90.37). Completes
11046    /// SQLAlchemy.Inspector.get_columns() parity (the dict shape
11047    /// includes an `'autoincrement'` key).
11048    ///
11049    /// SQLite detection rule (in the rusqlite `table_schema`
11050    /// override): true when `declared_type` is `INTEGER`
11051    /// (case-insensitive) AND the column is the sole primary key
11052    /// (`primary_key_ordinal == Some(0)`) — SQLite makes
11053    /// `INTEGER PRIMARY KEY` an alias for the auto-increment
11054    /// `rowid`. The optional `AUTOINCREMENT` keyword affects
11055    /// whether IDs are reused after delete but does not change the
11056    /// "is auto-incrementing" property pandas cares about.
11057    ///
11058    /// Other backends: PG SERIAL/BIGSERIAL/IDENTITY columns
11059    /// `true`; MySQL `AUTO_INCREMENT` modifier `true`; otherwise
11060    /// `false`.
11061    pub autoincrement: bool,
11062}
11063
11064/// Backend-neutral SQL table metadata.
11065#[derive(Debug, Clone, PartialEq, Eq)]
11066pub struct SqlTableSchema {
11067    pub table_name: String,
11068    pub columns: Vec<SqlColumnSchema>,
11069}
11070
11071impl SqlTableSchema {
11072    pub fn column(&self, name: &str) -> Option<&SqlColumnSchema> {
11073        self.columns.iter().find(|column| column.name == name)
11074    }
11075}
11076
11077/// Backend-neutral SQL index metadata.
11078///
11079/// Per br-frankenpandas-bgv9 (fd90.28). Used by `list_indexes` /
11080/// `list_sql_indexes` to surface user-defined indexes so callers can
11081/// align with `SQLAlchemy.Inspector.get_indexes()` shape.
11082#[derive(Debug, Clone, PartialEq, Eq)]
11083pub struct SqlIndexSchema {
11084    pub name: String,
11085    pub columns: Vec<String>,
11086    pub unique: bool,
11087}
11088
11089/// Backend-neutral SQL unique-constraint metadata.
11090///
11091/// Per br-frankenpandas-sh4v (fd90.31). Surfaces inline `UNIQUE`
11092/// declarations and `UNIQUE (...)` table constraints separately from
11093/// user-created `CREATE UNIQUE INDEX` (those land in
11094/// `SqlIndexSchema` via `list_indexes`). `name` may be backend-
11095/// generated (SQLite reports `sqlite_autoindex_<table>_<n>`) when
11096/// the constraint was declared inline without an explicit name —
11097/// we surface the backend's name verbatim rather than fabricating.
11098#[derive(Debug, Clone, PartialEq, Eq)]
11099pub struct SqlUniqueConstraintSchema {
11100    pub name: String,
11101    pub columns: Vec<String>,
11102}
11103
11104/// Bundle of all introspection metadata for a single SQL table.
11105///
11106/// Per br-frankenpandas-76mw (fd90.40). Returned by
11107/// `SqlInspector::reflect_table` to give callers the full picture of
11108/// a table in one call instead of 5 separate trait dispatches.
11109/// Mirrors the bundled view that `SQLAlchemy.MetaData.reflect_table`
11110/// builds internally.
11111#[derive(Debug, Clone, PartialEq, Eq)]
11112pub struct SqlReflectedTable {
11113    pub table_name: String,
11114    pub columns: Vec<SqlColumnSchema>,
11115    pub primary_key_columns: Vec<String>,
11116    pub indexes: Vec<SqlIndexSchema>,
11117    pub foreign_keys: Vec<SqlForeignKeySchema>,
11118    pub unique_constraints: Vec<SqlUniqueConstraintSchema>,
11119    pub comment: Option<String>,
11120}
11121
11122impl SqlReflectedTable {
11123    /// Look up a column by name. Mirrors `SqlTableSchema::column`.
11124    ///
11125    /// Per br-frankenpandas-63ac (fd90.51).
11126    #[must_use]
11127    pub fn column(&self, name: &str) -> Option<&SqlColumnSchema> {
11128        self.columns.iter().find(|c| c.name == name)
11129    }
11130
11131    /// Look up an index by name.
11132    ///
11133    /// Per br-frankenpandas-63ac (fd90.51).
11134    #[must_use]
11135    pub fn index(&self, name: &str) -> Option<&SqlIndexSchema> {
11136        self.indexes.iter().find(|i| i.name == name)
11137    }
11138
11139    /// Look up a unique constraint by name (backend-generated names
11140    /// like `sqlite_autoindex_*` count too — match what
11141    /// `list_unique_constraints` surfaced).
11142    ///
11143    /// Per br-frankenpandas-63ac (fd90.51).
11144    #[must_use]
11145    pub fn unique_constraint(&self, name: &str) -> Option<&SqlUniqueConstraintSchema> {
11146        self.unique_constraints.iter().find(|u| u.name == name)
11147    }
11148
11149    /// Find every foreign key whose `columns` slice contains `column_name`.
11150    ///
11151    /// A given column may participate in multiple FK constraints (e.g.
11152    /// the same column referenced by separate FKs to different parents
11153    /// — rare but valid SQL). Returns the matching FKs in their
11154    /// declaration order from PRAGMA foreign_key_list.
11155    ///
11156    /// Per br-frankenpandas-63ac (fd90.51).
11157    #[must_use]
11158    pub fn foreign_keys_for_column(&self, column_name: &str) -> Vec<&SqlForeignKeySchema> {
11159        self.foreign_keys
11160            .iter()
11161            .filter(|fk| fk.columns.iter().any(|c| c == column_name))
11162            .collect()
11163    }
11164
11165    /// Find every index whose `columns` slice contains `column_name`.
11166    ///
11167    /// Matches multi-column indexes where the column appears at any
11168    /// position (first, middle, last) — useful for answering "is this
11169    /// column indexed" rather than the more restrictive "is this
11170    /// column the leading entry of an index" question.
11171    ///
11172    /// Per br-frankenpandas-37uy (fd90.52).
11173    #[must_use]
11174    pub fn indexes_for_column(&self, column_name: &str) -> Vec<&SqlIndexSchema> {
11175        self.indexes
11176            .iter()
11177            .filter(|i| i.columns.iter().any(|c| c == column_name))
11178            .collect()
11179    }
11180
11181    /// Find every UNIQUE constraint whose `columns` slice contains
11182    /// `column_name`.
11183    ///
11184    /// Same any-position match semantics as `indexes_for_column` and
11185    /// `foreign_keys_for_column`.
11186    ///
11187    /// Per br-frankenpandas-37uy (fd90.52).
11188    #[must_use]
11189    pub fn unique_constraints_for_column(
11190        &self,
11191        column_name: &str,
11192    ) -> Vec<&SqlUniqueConstraintSchema> {
11193        self.unique_constraints
11194            .iter()
11195            .filter(|u| u.columns.iter().any(|c| c == column_name))
11196            .collect()
11197    }
11198}
11199
11200/// Backend-neutral SQL foreign-key constraint metadata.
11201///
11202/// Per br-frankenpandas-uht8 (fd90.29). Aligns with
11203/// `SQLAlchemy.Inspector.get_foreign_keys()` shape: a single FK
11204/// constraint may span multiple columns (composite FK), and
11205/// `columns[i]` references `referenced_columns[i]` on
11206/// `referenced_table`. `constraint_name` is `None` for SQLite
11207/// inline FKs declared without an explicit CONSTRAINT name (PRAGMA
11208/// foreign_key_list does not surface a name, so we return None
11209/// there rather than fabricating one).
11210#[derive(Debug, Clone, PartialEq, Eq)]
11211pub struct SqlForeignKeySchema {
11212    pub constraint_name: Option<String>,
11213    pub columns: Vec<String>,
11214    pub referenced_table: String,
11215    pub referenced_columns: Vec<String>,
11216}
11217
11218/// Iterator over DataFrame chunks produced by a SQL query.
11219pub struct SqlChunkIterator<'conn> {
11220    state: SqlChunkIteratorState<'conn>,
11221}
11222
11223enum SqlChunkIteratorState<'conn> {
11224    Materialized {
11225        headers: Vec<String>,
11226        columns: Vec<Vec<Scalar>>,
11227        dtype_hints: SqlColumnDtypeHints,
11228        chunk_size: usize,
11229        next_row: usize,
11230    },
11231    Paged {
11232        conn: &'conn dyn SqlConnection,
11233        query: String,
11234        options: SqlReadOptions,
11235        headers: Vec<String>,
11236        chunk_size: usize,
11237        next_offset: usize,
11238        finished: bool,
11239    },
11240}
11241
11242impl std::fmt::Debug for SqlChunkIterator<'_> {
11243    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
11244        match &self.state {
11245            SqlChunkIteratorState::Materialized {
11246                headers,
11247                columns,
11248                dtype_hints: _,
11249                chunk_size,
11250                next_row,
11251            } => f
11252                .debug_struct("SqlChunkIterator")
11253                .field("mode", &"materialized")
11254                .field("headers", headers)
11255                .field("row_count", &columns.first().map_or(0, Vec::len))
11256                .field("chunk_size", chunk_size)
11257                .field("next_row", next_row)
11258                .finish(),
11259            SqlChunkIteratorState::Paged {
11260                query,
11261                headers,
11262                chunk_size,
11263                next_offset,
11264                finished,
11265                ..
11266            } => f
11267                .debug_struct("SqlChunkIterator")
11268                .field("mode", &"paged")
11269                .field("query", query)
11270                .field("headers", headers)
11271                .field("chunk_size", chunk_size)
11272                .field("next_offset", next_offset)
11273                .field("finished", finished)
11274                .finish(),
11275        }
11276    }
11277}
11278
11279impl<'conn> SqlChunkIterator<'conn> {
11280    fn materialized(
11281        headers: Vec<String>,
11282        columns: Vec<Vec<Scalar>>,
11283        dtype_hints: SqlColumnDtypeHints,
11284        chunk_size: usize,
11285    ) -> Self {
11286        Self {
11287            state: SqlChunkIteratorState::Materialized {
11288                headers,
11289                columns,
11290                dtype_hints,
11291                chunk_size,
11292                next_row: 0,
11293            },
11294        }
11295    }
11296
11297    fn paged<C: SqlConnection + 'conn>(
11298        conn: &'conn C,
11299        query: &str,
11300        options: &SqlReadOptions,
11301        chunk_size: usize,
11302    ) -> Result<Self, IoError> {
11303        let headers = sql_paged_query_headers(conn, query, options)?;
11304        Ok(Self {
11305            state: SqlChunkIteratorState::Paged {
11306                conn,
11307                query: sql_trim_chunk_source(query)?.to_owned(),
11308                options: options.clone(),
11309                headers,
11310                chunk_size,
11311                next_offset: 0,
11312                finished: false,
11313            },
11314        })
11315    }
11316
11317    fn headers(&self) -> &[String] {
11318        match &self.state {
11319            SqlChunkIteratorState::Materialized { headers, .. }
11320            | SqlChunkIteratorState::Paged { headers, .. } => headers,
11321        }
11322    }
11323}
11324
11325impl Iterator for SqlChunkIterator<'_> {
11326    type Item = Result<DataFrame, IoError>;
11327
11328    fn next(&mut self) -> Option<Self::Item> {
11329        match &mut self.state {
11330            SqlChunkIteratorState::Materialized {
11331                headers,
11332                columns,
11333                dtype_hints,
11334                chunk_size,
11335                next_row,
11336            } => {
11337                let row_count = columns.first().map_or(0, Vec::len);
11338                if *next_row >= row_count {
11339                    return None;
11340                }
11341
11342                let start = *next_row;
11343                let end = start.saturating_add(*chunk_size).min(row_count);
11344                *next_row = end;
11345
11346                let chunk_columns = columns
11347                    .iter()
11348                    .map(|column| column[start..end].to_vec())
11349                    .collect();
11350                Some(dataframe_from_sql_columns(
11351                    headers.clone(),
11352                    chunk_columns,
11353                    dtype_hints.clone(),
11354                ))
11355            }
11356            SqlChunkIteratorState::Paged {
11357                conn,
11358                query,
11359                options,
11360                chunk_size,
11361                next_offset,
11362                finished,
11363                ..
11364            } => {
11365                if *finished {
11366                    return None;
11367                }
11368
11369                let page =
11370                    sql_query_to_columns_paged(*conn, query, options, *chunk_size, *next_offset);
11371                Some(match page {
11372                    Ok((headers, columns, dtype_hints)) => {
11373                        let row_count = columns.first().map_or(0, Vec::len);
11374                        if row_count == 0 {
11375                            *finished = true;
11376                            return None;
11377                        }
11378                        if row_count < *chunk_size {
11379                            *finished = true;
11380                        }
11381                        *next_offset = next_offset.saturating_add(row_count);
11382                        dataframe_from_sql_columns(headers, columns, dtype_hints)
11383                    }
11384                    Err(err) => {
11385                        *finished = true;
11386                        Err(err)
11387                    }
11388                })
11389            }
11390        }
11391    }
11392}
11393
11394/// Iterator over SQL DataFrame chunks with optional per-chunk index promotion.
11395pub struct SqlIndexedChunkIterator<'conn> {
11396    inner: SqlChunkIterator<'conn>,
11397    index_col: Option<String>,
11398}
11399
11400impl std::fmt::Debug for SqlIndexedChunkIterator<'_> {
11401    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
11402        f.debug_struct("SqlIndexedChunkIterator")
11403            .field("inner", &self.inner)
11404            .field("index_col", &self.index_col)
11405            .finish()
11406    }
11407}
11408
11409impl Iterator for SqlIndexedChunkIterator<'_> {
11410    type Item = Result<DataFrame, IoError>;
11411
11412    fn next(&mut self) -> Option<Self::Item> {
11413        let chunk = self.inner.next()?;
11414        Some(match (chunk, self.index_col.as_deref()) {
11415            (Ok(frame), Some(index_col)) => apply_sql_index_col(frame, Some(index_col)),
11416            (Ok(frame), None) => Ok(frame),
11417            (Err(err), _) => Err(err),
11418        })
11419    }
11420}
11421
11422fn sql_indexed_chunks<'conn>(
11423    inner: SqlChunkIterator<'conn>,
11424    index_col: Option<&str>,
11425) -> Result<SqlIndexedChunkIterator<'conn>, IoError> {
11426    if let Some(col_name) = index_col {
11427        if col_name.is_empty() {
11428            return Err(IoError::Sql(
11429                "index_col: empty string is not a valid column name".to_owned(),
11430            ));
11431        }
11432        if !inner.headers().iter().any(|header| header == col_name) {
11433            return Err(IoError::Sql(format!(
11434                "index_col {col_name:?} not present in result columns"
11435            )));
11436        }
11437    }
11438    Ok(SqlIndexedChunkIterator {
11439        inner,
11440        index_col: index_col.map(str::to_owned),
11441    })
11442}
11443
11444/// Minimal SQL connection surface needed by FrankenPandas SQL IO.
11445pub trait SqlConnection {
11446    fn query(&self, query: &str, params: &[Scalar]) -> Result<SqlQueryResult, IoError>;
11447
11448    /// Return optional dtype hints for each result column in `query`.
11449    ///
11450    /// Backends that expose declared result-column types should override this
11451    /// so empty/all-null SQL results keep their table schema instead of
11452    /// falling back to `DType::Null`.
11453    fn query_column_dtypes(
11454        &self,
11455        _query: &str,
11456        _params: &[Scalar],
11457    ) -> Result<Vec<Option<DType>>, IoError> {
11458        Ok(Vec::new())
11459    }
11460
11461    /// Whether `read_sql_chunks*` may page this backend with a bounded
11462    /// `LIMIT`/`OFFSET` wrapper instead of materializing the whole result
11463    /// before the first chunk. Defaults to `false` so lightweight test
11464    /// doubles and custom backends keep the legacy behavior until they opt in.
11465    fn supports_paged_sql_chunks(&self) -> bool {
11466        false
11467    }
11468
11469    fn execute_batch(&self, sql: &str) -> Result<(), IoError>;
11470
11471    fn table_exists(&self, table_name: &str) -> Result<bool, IoError>;
11472
11473    fn insert_rows(&self, insert_sql: &str, rows: &[Vec<Scalar>]) -> Result<(), IoError>;
11474
11475    fn dtype_sql(&self, dtype: DType) -> &'static str;
11476
11477    fn index_dtype_sql(&self, index: &Index) -> &'static str;
11478
11479    /// Return the bind marker for the one-based parameter ordinal.
11480    ///
11481    /// SQLite and MySQL accept `?`; PostgreSQL-style backends use `$1`,
11482    /// `$2`, ... . Keeping marker generation on the backend trait lets
11483    /// write_sql stay generic without leaking backend dialect branches.
11484    fn parameter_marker(&self, _ordinal: usize) -> String {
11485        "?".to_owned()
11486    }
11487
11488    // ── Backend-capability + dialect probes (br-frankenpandas-6dtf) ─────
11489    //
11490    // Default impls return conservative values so existing implementations
11491    // stay backwards-compatible; concrete backends override per their
11492    // engine. Phase 2 wires these probes into the read_sql / read_sql_table
11493    // dispatch path so per-backend SQL quirks (RETURNING, max param count,
11494    // transaction semantics) can fan out without leaking concrete types.
11495
11496    /// Short identifier for this backend's SQL dialect.
11497    ///
11498    /// Used by diagnostics + DISCREPANCIES.md routing. Backends should
11499    /// override with the canonical pandas/SQLAlchemy dialect name:
11500    /// `"sqlite"`, `"postgresql"`, `"mysql"`, `"mariadb"`, `"oracle"`, etc.
11501    /// Default `"unknown"` flags un-customized impls during reviews.
11502    fn dialect_name(&self) -> &'static str {
11503        "unknown"
11504    }
11505
11506    /// Whether this backend honors `INSERT ... RETURNING ...` natively.
11507    ///
11508    /// Drives the write_sql path's choice between RETURNING-based row
11509    /// retrieval and a follow-up SELECT. Default `false` is the
11510    /// conservative choice (forces follow-up SELECT path) until each
11511    /// backend opts in.
11512    fn supports_returning(&self) -> bool {
11513        false
11514    }
11515
11516    /// Hard upper bound on bound-parameter count per statement, if known.
11517    ///
11518    /// SQLite (3.32+): 32766. PostgreSQL: 65535. MySQL: 65535. Backends
11519    /// that don't surface a meaningful cap return `None`. The bulk-insert
11520    /// path uses this to chunk multi-row INSERTs so a single executemany
11521    /// stays under the backend's parameter ceiling.
11522    fn max_param_count(&self) -> Option<usize> {
11523        None
11524    }
11525
11526    /// Maximum identifier length supported by the backend, or `None`
11527    /// when no documented limit exists (or the limit is irrelevant for
11528    /// the deployment).
11529    ///
11530    /// Per br-frankenpandas-cs81 (fd90.26). Defaults to `None`. Known
11531    /// caps: PostgreSQL = 63, MySQL = 64, MSSQL = 128, Oracle = 30
11532    /// (pre-12.2) or 128 (12.2+), SQLite = no documented limit.
11533    /// Useful for to_sql validation when emitting auto-generated
11534    /// index/constraint/column names that could otherwise exceed
11535    /// backend limits and produce truncated or rejected DDL.
11536    fn max_identifier_length(&self) -> Option<usize> {
11537        None
11538    }
11539
11540    /// Run `f` inside a transaction. The default impl runs `f` without
11541    /// BEGIN/COMMIT — backends that support transactions should override
11542    /// to wrap in their native transaction primitive (rusqlite `BEGIN`,
11543    /// PostgreSQL `BEGIN`, MySQL `START TRANSACTION`, ...). On `Err`
11544    /// from `f`, transactional backends roll back; on `Ok` they commit.
11545    ///
11546    /// The default impl is intentionally a no-op so non-transactional
11547    /// connection wrappers (e.g. test doubles) compile without
11548    /// implementation effort. Production backends MUST override.
11549    fn with_transaction<T, F>(&self, f: F) -> Result<T, IoError>
11550    where
11551        F: FnOnce(&Self) -> Result<T, IoError>,
11552        Self: Sized,
11553    {
11554        f(self)
11555    }
11556
11557    /// Quote a SQL identifier (table name, column name, schema name) for
11558    /// safe inclusion in a generated statement.
11559    ///
11560    /// Default impl: ANSI `"..."` form with embedded `"` doubled (matches
11561    /// SQLite + PostgreSQL). MySQL/MariaDB backends must override to
11562    /// produce `\`...\`` (backtick). MSSQL backends use `[...]`. Per
11563    /// br-frankenpandas-2y7w (fd90.10).
11564    ///
11565    /// NUL bytes in the identifier are rejected (security: prevents
11566    /// statement-injection via embedded null terminators in C-string
11567    /// driver layers).
11568    fn quote_identifier(&self, ident: &str) -> Result<String, IoError> {
11569        if ident.contains('\0') {
11570            return Err(IoError::Sql("invalid SQL identifier: NUL byte".to_owned()));
11571        }
11572        Ok(format!("\"{}\"", ident.replace('"', "\"\"")))
11573    }
11574
11575    /// Whether this backend exposes multi-schema namespacing.
11576    ///
11577    /// PostgreSQL / MySQL / MariaDB / MSSQL / Oracle: true. SQLite (one
11578    /// schema per file connection — though ATTACH adds named schemas as
11579    /// a special case): false. Drives the `pd.read_sql_table(.., schema=X)`
11580    /// path's choice between qualifying the table reference (`schema.table`)
11581    /// and a connection-level pre-SET. Per br-frankenpandas-6dk9 (fd90.13).
11582    fn supports_schemas(&self) -> bool {
11583        false
11584    }
11585
11586    /// Default schema for unqualified table references, if the backend
11587    /// has one.
11588    ///
11589    /// PostgreSQL: `'public'` (or whatever the connection's `search_path`
11590    /// resolves to first). MySQL: the database name passed to the
11591    /// connection URL. SQLite: `None` (single namespace). The `read_sql_table`
11592    /// dispatch uses this when the user passes `schema=None` to choose
11593    /// between a bare `SELECT * FROM \"table\"` and a schema-qualified form.
11594    /// Default `None` keeps behavior identical to today's SQLite-only path.
11595    fn default_schema(&self) -> Option<String> {
11596        None
11597    }
11598
11599    /// Schema-aware table-existence check.
11600    ///
11601    /// Per br-frankenpandas-70d1 (fd90.17). Default impl delegates to
11602    /// `table_exists(table)` and ignores the schema argument — matches
11603    /// single-namespace embedded backends like SQLite. Multi-schema
11604    /// backends (PostgreSQL, MySQL, MSSQL) override to scope the check
11605    /// to the requested schema, so write_sql's `Fail` branch correctly
11606    /// distinguishes `analytics.users` from `audit.users`. The schema
11607    /// arg passes through unchanged — backends MAY consult
11608    /// `default_schema()` for their own fallback logic when `schema`
11609    /// is `None` (per fd90.57: this fallback is NOT applied by the
11610    /// default impl or the SQLite override).
11611    fn table_exists_in_schema(
11612        &self,
11613        table_name: &str,
11614        _schema: Option<&str>,
11615    ) -> Result<bool, IoError> {
11616        self.table_exists(table_name)
11617    }
11618
11619    /// List user-visible table names, optionally scoped to `schema`.
11620    ///
11621    /// Per br-frankenpandas-vhq2 (fd90.20). Default impl returns an empty
11622    /// vector — backends that cannot introspect (or that haven't yet
11623    /// implemented this method) report "no tables visible" rather than
11624    /// raising. Multi-schema backends (PostgreSQL, MySQL, MSSQL) override
11625    /// to query their information_schema; embedded backends (SQLite)
11626    /// override to query their internal catalog and ignore `schema`.
11627    fn list_tables(&self, _schema: Option<&str>) -> Result<Vec<String>, IoError> {
11628        Ok(Vec::new())
11629    }
11630
11631    /// Introspect a table's column metadata, optionally schema-scoped.
11632    ///
11633    /// Per br-frankenpandas-w43q (fd90.21). Returns `Ok(None)` if the
11634    /// table does not exist. Default impl returns `Ok(None)` for
11635    /// backends that cannot introspect; rusqlite overrides to use
11636    /// `PRAGMA table_info`. Multi-schema backends override to query
11637    /// `information_schema.columns` filtered by `schema`. Schema arg is
11638    /// silently ignored when `supports_schemas() == false`.
11639    fn table_schema(
11640        &self,
11641        _table_name: &str,
11642        _schema: Option<&str>,
11643    ) -> Result<Option<SqlTableSchema>, IoError> {
11644        Ok(None)
11645    }
11646
11647    /// List user-visible schemas (PostgreSQL "schemas", MySQL "databases").
11648    ///
11649    /// Per br-frankenpandas-lxhi (fd90.22). Default impl returns an empty
11650    /// vector. Single-namespace backends (SQLite) return empty as well —
11651    /// they have no meaningful schema concept. Multi-schema backends
11652    /// (PostgreSQL, MySQL, MSSQL) override to query their catalog and
11653    /// filter out internal/system schemas (`pg_*`, `information_schema`,
11654    /// `mysql`, `performance_schema`, etc.) so user-visible schemas
11655    /// surface cleanly.
11656    fn list_schemas(&self) -> Result<Vec<String>, IoError> {
11657        Ok(Vec::new())
11658    }
11659
11660    /// Probe the backend server's version string.
11661    ///
11662    /// Per br-frankenpandas-e23k (fd90.24). Useful for dialect-version
11663    /// gating (INSERT ... RETURNING needs PG 8.2+ / SQLite 3.35.0+,
11664    /// JSON operators need MySQL 5.7.8+, etc.) and for diagnostics.
11665    /// Default impl returns `Ok(None)` so backends that can't probe
11666    /// (or that haven't yet implemented this) report "unknown" rather
11667    /// than raising. rusqlite override returns the SQLite library
11668    /// version. PostgreSQL/MySQL impls should override with
11669    /// `SHOW server_version` / `SELECT VERSION()`.
11670    fn server_version(&self) -> Result<Option<String>, IoError> {
11671        Ok(None)
11672    }
11673
11674    /// List user-visible view names, optionally scoped to `schema`.
11675    ///
11676    /// Per br-frankenpandas-gm3r (fd90.30). Default impl returns an
11677    /// empty vector. rusqlite override queries `sqlite_master WHERE
11678    /// type='view'`, excluding internal `sqlite_*` views. Multi-schema
11679    /// backends override with `information_schema.views` filtered by
11680    /// the schema arg. Schema is silently ignored when
11681    /// `supports_schemas() == false`. Companion to `list_tables` —
11682    /// pandas/SQLAlchemy keep tables and views in distinct buckets so
11683    /// `pd.read_sql_table` can distinguish them.
11684    fn list_views(&self, _schema: Option<&str>) -> Result<Vec<String>, IoError> {
11685        Ok(Vec::new())
11686    }
11687
11688    /// List indexes defined on a table, optionally schema-scoped.
11689    ///
11690    /// Per br-frankenpandas-bgv9 (fd90.28). Default impl returns
11691    /// `Ok(Vec::new())` for backends that can't introspect. rusqlite
11692    /// override uses `PRAGMA index_list(table)` + `PRAGMA index_info`
11693    /// per index, surfacing only user-created indexes (the auto-created
11694    /// indexes for PRIMARY KEY constraints are filtered out to match
11695    /// SQLAlchemy.Inspector.get_indexes() semantics). Multi-schema
11696    /// backends override with information_schema queries.
11697    fn list_indexes(
11698        &self,
11699        _table_name: &str,
11700        _schema: Option<&str>,
11701    ) -> Result<Vec<SqlIndexSchema>, IoError> {
11702        Ok(Vec::new())
11703    }
11704
11705    /// List UNIQUE constraints declared on a table (inline or table-level),
11706    /// excluding `CREATE UNIQUE INDEX` indexes (those land in `list_indexes`).
11707    ///
11708    /// Per br-frankenpandas-sh4v (fd90.31). Default impl returns
11709    /// `Ok(Vec::new())`. rusqlite override uses
11710    /// `PRAGMA index_list(table)` filtered by `origin == 'u'` (the
11711    /// auto-created indexes that back declared UNIQUE constraints)
11712    /// then `PRAGMA index_info` per match. Multi-schema backends
11713    /// override with information_schema queries.
11714    fn list_unique_constraints(
11715        &self,
11716        _table_name: &str,
11717        _schema: Option<&str>,
11718    ) -> Result<Vec<SqlUniqueConstraintSchema>, IoError> {
11719        Ok(Vec::new())
11720    }
11721
11722    /// Probe the table-level comment, optionally schema-scoped.
11723    ///
11724    /// Per br-frankenpandas-yu3w (fd90.32). Default impl returns
11725    /// `Ok(None)` — SQLite has no native table-comment storage so it
11726    /// inherits the default. PostgreSQL impls should override using
11727    /// `pg_catalog.obj_description(...)` or
11728    /// `pg_catalog.pg_class.relkind` joined to `pg_description`;
11729    /// MySQL uses `information_schema.tables.table_comment`; MSSQL
11730    /// reads from `sys.extended_properties`. Aligns with
11731    /// `SQLAlchemy.Inspector.get_table_comment()` shape (returns
11732    /// `{'text': comment_or_none}`).
11733    fn table_comment(
11734        &self,
11735        _table_name: &str,
11736        _schema: Option<&str>,
11737    ) -> Result<Option<String>, IoError> {
11738        Ok(None)
11739    }
11740
11741    /// List foreign-key constraints declared on a table, optionally
11742    /// schema-scoped.
11743    ///
11744    /// Per br-frankenpandas-uht8 (fd90.29). Default impl returns
11745    /// `Ok(Vec::new())`. rusqlite override uses
11746    /// `PRAGMA foreign_key_list(table)`, grouping rows by their `id`
11747    /// column (each id is a single FK constraint that may span multiple
11748    /// columns) and ordering paired columns by `seq`. Multi-schema
11749    /// backends override with `information_schema.referential_constraints`
11750    /// + `key_column_usage` joined queries.
11751    fn list_foreign_keys(
11752        &self,
11753        _table_name: &str,
11754        _schema: Option<&str>,
11755    ) -> Result<Vec<SqlForeignKeySchema>, IoError> {
11756        Ok(Vec::new())
11757    }
11758
11759    /// Return the primary-key column names for a table, ordered by
11760    /// the `primary_key_ordinal` reported by `table_schema`.
11761    ///
11762    /// Per br-frankenpandas-uw3y (fd90.25). Default impl delegates to
11763    /// `table_schema(table, schema)` and pulls out columns whose
11764    /// `primary_key_ordinal` is `Some(_)`, sorted ascending. Returns
11765    /// an empty vector when:
11766    /// - the table doesn't exist (`table_schema` returns `Ok(None)`),
11767    /// - the table has no primary key,
11768    /// - the backend can't introspect (default `table_schema`).
11769    ///
11770    /// Useful for upsert conflict-target generation, `index_label`
11771    /// defaulting, and schema validation. Backends can override to
11772    /// query their catalog directly when `table_schema` is too heavy.
11773    fn primary_key_columns(
11774        &self,
11775        table_name: &str,
11776        schema: Option<&str>,
11777    ) -> Result<Vec<String>, IoError> {
11778        // Per fd90.47: defer to the shared primary_keys_from_schema
11779        // helper so the filter+sort logic lives in exactly one place
11780        // (the helper is also used by SqlInspector::reflect_table).
11781        let Some(meta) = self.table_schema(table_name, schema)? else {
11782            return Ok(Vec::new());
11783        };
11784        Ok(primary_keys_from_schema(&meta))
11785    }
11786
11787    /// Reset a table to empty without dropping its definition.
11788    ///
11789    /// Per br-frankenpandas-phum (fd90.23). Default impl emits
11790    /// `DELETE FROM <table>` — universal SQL that every backend
11791    /// supports, but slower than TRUNCATE on large tables because the
11792    /// row deletes are logged in the transaction journal. PostgreSQL
11793    /// and MySQL backends should override with `TRUNCATE TABLE`,
11794    /// which is dramatically faster (DDL-style fast-path) and resets
11795    /// auto-increment sequences. The schema arg routes through
11796    /// `quote_identifier` and is silently ignored when
11797    /// `supports_schemas() == false`.
11798    fn truncate_table(&self, table_name: &str, schema: Option<&str>) -> Result<(), IoError> {
11799        validate_sql_table_name(table_name)?;
11800        validate_sql_table_ref_identifier_lengths(self, table_name, schema)?;
11801        let qualified = match schema {
11802            Some(s) if self.supports_schemas() => {
11803                validate_sql_schema_name(s)?;
11804                format!(
11805                    "{}.{}",
11806                    self.quote_identifier(s)?,
11807                    self.quote_identifier(table_name)?
11808                )
11809            }
11810            _ => self.quote_identifier(table_name)?,
11811        };
11812        self.execute_batch(&format!("DELETE FROM {qualified}"))
11813    }
11814}
11815
11816/// Map an fp-types DType to an SQLite column type declaration.
11817#[cfg(feature = "sql-sqlite")]
11818fn dtype_to_sql(dtype: DType) -> &'static str {
11819    match dtype {
11820        DType::Int64 | DType::Int64Nullable => "INTEGER",
11821        DType::Float64 | DType::Float64Nullable => "REAL",
11822        DType::Utf8 => "TEXT",
11823        DType::Categorical => "TEXT",
11824        DType::Bool | DType::BoolNullable => "INTEGER",
11825        DType::Null => "TEXT",
11826        DType::Timedelta64 => "INTEGER", // store as nanoseconds
11827        DType::Datetime64 { .. } => "INTEGER", // store as nanoseconds
11828        DType::Period => "INTEGER",      // store as ordinal
11829        DType::Interval => "TEXT",       // store as string
11830        DType::Sparse => "TEXT",
11831    }
11832}
11833
11834#[cfg(feature = "sql-sqlite")]
11835fn sqlite_decl_type_to_dtype(decl_type: &str) -> Option<DType> {
11836    let upper = decl_type.trim().to_ascii_uppercase();
11837    if upper.contains("INT") {
11838        Some(DType::Int64)
11839    } else if upper.contains("REAL") || upper.contains("FLOA") || upper.contains("DOUB") {
11840        Some(DType::Float64)
11841    } else if upper.contains("CHAR") || upper.contains("CLOB") || upper.contains("TEXT") {
11842        Some(DType::Utf8)
11843    } else {
11844        None
11845    }
11846}
11847
11848/// Convert an SQLite column value to a Scalar.
11849#[cfg(feature = "sql-sqlite")]
11850fn sql_value_to_scalar(value: &rusqlite::types::Value) -> Scalar {
11851    match value {
11852        rusqlite::types::Value::Null => Scalar::Null(NullKind::Null),
11853        rusqlite::types::Value::Integer(v) => Scalar::Int64(*v),
11854        rusqlite::types::Value::Real(v) => Scalar::Float64(*v),
11855        rusqlite::types::Value::Text(s) => Scalar::Utf8(s.clone()),
11856        rusqlite::types::Value::Blob(b) => Scalar::Utf8(format!("<blob:{} bytes>", b.len())),
11857    }
11858}
11859
11860#[cfg(feature = "sql-sqlite")]
11861fn sql_value_from_scalar(scalar: &Scalar) -> rusqlite::types::Value {
11862    match scalar {
11863        Scalar::Int64(v) => rusqlite::types::Value::Integer(*v),
11864        Scalar::Float64(v) => {
11865            if v.is_nan() {
11866                rusqlite::types::Value::Null
11867            } else {
11868                rusqlite::types::Value::Real(*v)
11869            }
11870        }
11871        Scalar::Bool(b) => rusqlite::types::Value::Integer(if *b { 1 } else { 0 }),
11872        Scalar::Utf8(s) => rusqlite::types::Value::Text(s.clone()),
11873        Scalar::Null(_) => rusqlite::types::Value::Null,
11874        Scalar::Timedelta64(v) => {
11875            if *v == Timedelta::NAT {
11876                rusqlite::types::Value::Null
11877            } else {
11878                rusqlite::types::Value::Integer(*v)
11879            }
11880        }
11881        Scalar::Datetime64(v) => {
11882            if *v == Timestamp::NAT {
11883                rusqlite::types::Value::Null
11884            } else {
11885                rusqlite::types::Value::Integer(*v)
11886            }
11887        }
11888        Scalar::Period(p) => {
11889            if p.ordinal == i64::MIN {
11890                rusqlite::types::Value::Null
11891            } else {
11892                rusqlite::types::Value::Integer(p.ordinal)
11893            }
11894        }
11895        Scalar::Interval(iv) => rusqlite::types::Value::Text(format!("{iv}")),
11896    }
11897}
11898
11899fn scalar_from_index_label(label: &IndexLabel) -> Scalar {
11900    match label {
11901        IndexLabel::Int64(v) => Scalar::Int64(*v),
11902        IndexLabel::Float64(v) => Scalar::Float64(v.0),
11903        IndexLabel::Bool(b) => Scalar::Bool(*b),
11904        IndexLabel::Utf8(s) => Scalar::Utf8(s.clone()),
11905        // Typed-null label round-trips to the same-kind missing scalar.
11906        IndexLabel::Null(kind) => Scalar::Null(*kind),
11907        IndexLabel::Timedelta64(v) => {
11908            if *v == Timedelta::NAT {
11909                Scalar::Null(NullKind::Null)
11910            } else {
11911                Scalar::Timedelta64(*v)
11912            }
11913        }
11914        IndexLabel::Datetime64(v) => {
11915            if *v == i64::MIN {
11916                Scalar::Null(NullKind::Null)
11917            } else {
11918                Scalar::Utf8(format_datetime_ns(*v))
11919            }
11920        }
11921    }
11922}
11923
11924#[cfg(feature = "sql-sqlite")]
11925impl SqlConnection for rusqlite::Connection {
11926    fn query(&self, query: &str, params: &[Scalar]) -> Result<SqlQueryResult, IoError> {
11927        let mut stmt = self
11928            .prepare(query)
11929            .map_err(|e| IoError::Sql(format!("prepare failed: {e}")))?;
11930
11931        let col_count = stmt.column_count();
11932        let columns: Vec<String> = (0..col_count)
11933            .map(|i| stmt.column_name(i).unwrap_or("?").to_owned())
11934            .collect();
11935
11936        let sql_params = params.iter().map(sql_value_from_scalar).collect::<Vec<_>>();
11937        let mut rows = stmt
11938            .query(rusqlite::params_from_iter(sql_params.iter()))
11939            .map_err(|e| IoError::Sql(format!("query failed: {e}")))?;
11940
11941        let mut out_rows = Vec::new();
11942        while let Some(row) = rows
11943            .next()
11944            .map_err(|e| IoError::Sql(format!("row fetch failed: {e}")))?
11945        {
11946            let mut values = Vec::with_capacity(col_count);
11947            for col_idx in 0..col_count {
11948                let value: rusqlite::types::Value = row
11949                    .get(col_idx)
11950                    .map_err(|e| IoError::Sql(format!("cell read failed: {e}")))?;
11951                values.push(sql_value_to_scalar(&value));
11952            }
11953            out_rows.push(values);
11954        }
11955
11956        Ok(SqlQueryResult {
11957            columns,
11958            rows: out_rows,
11959        })
11960    }
11961
11962    fn query_column_dtypes(
11963        &self,
11964        query: &str,
11965        _params: &[Scalar],
11966    ) -> Result<Vec<Option<DType>>, IoError> {
11967        let stmt = self
11968            .prepare(query)
11969            .map_err(|e| IoError::Sql(format!("prepare failed: {e}")))?;
11970        Ok(stmt
11971            .columns()
11972            .into_iter()
11973            .map(|column| column.decl_type().and_then(sqlite_decl_type_to_dtype))
11974            .collect())
11975    }
11976
11977    fn supports_paged_sql_chunks(&self) -> bool {
11978        true
11979    }
11980
11981    fn execute_batch(&self, sql: &str) -> Result<(), IoError> {
11982        rusqlite::Connection::execute_batch(self, sql)
11983            .map_err(|e| IoError::Sql(format!("execute_batch failed: {e}")))
11984    }
11985
11986    fn table_exists(&self, table_name: &str) -> Result<bool, IoError> {
11987        self.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name=?1")
11988            .and_then(|mut stmt| stmt.exists(rusqlite::params![table_name]))
11989            .map_err(|e| IoError::Sql(format!("existence check failed: {e}")))
11990    }
11991
11992    fn insert_rows(&self, insert_sql: &str, rows: &[Vec<Scalar>]) -> Result<(), IoError> {
11993        let tx = self
11994            .unchecked_transaction()
11995            .map_err(|e| IoError::Sql(format!("begin transaction failed: {e}")))?;
11996
11997        {
11998            let mut stmt = tx
11999                .prepare_cached(insert_sql)
12000                .map_err(|e| IoError::Sql(format!("prepare insert failed: {e}")))?;
12001
12002            for (row_idx, row_values) in rows.iter().enumerate() {
12003                let params = row_values
12004                    .iter()
12005                    .map(sql_value_from_scalar)
12006                    .collect::<Vec<_>>();
12007                stmt.execute(rusqlite::params_from_iter(params.iter()))
12008                    .map_err(|e| IoError::Sql(format!("insert row {row_idx} failed: {e}")))?;
12009            }
12010        }
12011
12012        tx.commit()
12013            .map_err(|e| IoError::Sql(format!("commit failed: {e}")))?;
12014        Ok(())
12015    }
12016
12017    fn dtype_sql(&self, dtype: DType) -> &'static str {
12018        dtype_to_sql(dtype)
12019    }
12020
12021    fn index_dtype_sql(&self, index: &Index) -> &'static str {
12022        sql_dtype_from_index(index)
12023    }
12024
12025    // br-frankenpandas-6dtf: backend-capability + dialect probes.
12026    fn dialect_name(&self) -> &'static str {
12027        "sqlite"
12028    }
12029
12030    fn supports_returning(&self) -> bool {
12031        // SQLite 3.35.0+ (released March 2021) supports INSERT ... RETURNING.
12032        // rusqlite ships with bundled SQLite >= 3.45 by default, so we can
12033        // unconditionally claim support here.
12034        true
12035    }
12036
12037    fn max_param_count(&self) -> Option<usize> {
12038        // SQLite default SQLITE_MAX_VARIABLE_NUMBER is 32766 since 3.32.0.
12039        // (Older builds capped at 999.) rusqlite bundled SQLite is current,
12040        // so this matches.
12041        Some(32766)
12042    }
12043
12044    fn with_transaction<T, F>(&self, f: F) -> Result<T, IoError>
12045    where
12046        F: FnOnce(&Self) -> Result<T, IoError>,
12047        Self: Sized,
12048    {
12049        struct RollbackOnDrop<'conn> {
12050            conn: &'conn rusqlite::Connection,
12051            active: bool,
12052        }
12053
12054        impl Drop for RollbackOnDrop<'_> {
12055            fn drop(&mut self) {
12056                if self.active {
12057                    let _ = rusqlite::Connection::execute_batch(self.conn, "ROLLBACK");
12058                }
12059            }
12060        }
12061
12062        // rusqlite's pure-trait `Self: Sized` constraint means we operate on
12063        // `&rusqlite::Connection` directly without taking the `&mut` that
12064        // `Connection::transaction()` requires. We emulate the same
12065        // BEGIN/COMMIT semantics with explicit pragmas. The guard keeps the
12066        // connection from retaining a write transaction if the callback
12067        // panics before we reach the explicit rollback/commit paths.
12068        self.execute_batch("BEGIN")
12069            .map_err(|e| IoError::Sql(format!("begin transaction failed: {e}")))?;
12070        let mut rollback = RollbackOnDrop {
12071            conn: self,
12072            active: true,
12073        };
12074        match f(self) {
12075            Ok(result) => {
12076                self.execute_batch("COMMIT")
12077                    .map_err(|e| IoError::Sql(format!("commit transaction failed: {e}")))?;
12078                rollback.active = false;
12079                Ok(result)
12080            }
12081            Err(err) => {
12082                // Best-effort rollback; surface the original error if rollback
12083                // also fails (rollback failure is logged via the Sql error
12084                // variant for diagnostics but the user wants the closure
12085                // error preserved as the primary signal).
12086                if self.execute_batch("ROLLBACK").is_ok() {
12087                    rollback.active = false;
12088                }
12089                Err(err)
12090            }
12091        }
12092    }
12093
12094    fn quote_identifier(&self, ident: &str) -> Result<String, IoError> {
12095        // SQLite accepts ANSI double-quotes for identifiers (it ALSO accepts
12096        // backticks for MySQL compat, but ANSI is the recommended form per
12097        // SQLite docs). Delegate to the existing free-fn helper to keep the
12098        // exact escaping policy in one place.
12099        quote_sql_ident(ident)
12100    }
12101
12102    fn list_tables(&self, _schema: Option<&str>) -> Result<Vec<String>, IoError> {
12103        // SQLite has a single namespace; the schema arg is silently
12104        // ignored to match `supports_schemas() == false`. We exclude
12105        // SQLite's internal `sqlite_*` book-keeping tables to match
12106        // pandas' SQLAlchemy dialect, which never surfaces them as
12107        // user tables.
12108        // Per fd90.50: ESCAPE '\' makes the `_` in 'sqlite\_%' a literal
12109        // underscore instead of a SQL LIKE single-char wildcard. Without
12110        // the escape, a user table named e.g. `sqliteX` would be
12111        // incorrectly excluded because the `_` matches any single char.
12112        let mut stmt = self
12113            .prepare(
12114                r"SELECT name FROM sqlite_master
12115                 WHERE type='table' AND name NOT LIKE 'sqlite\_%' ESCAPE '\'
12116                 ORDER BY name",
12117            )
12118            .map_err(|e| IoError::Sql(format!("list_tables prepare failed: {e}")))?;
12119        let names = stmt
12120            .query_map([], |row| row.get::<_, String>(0))
12121            .map_err(|e| IoError::Sql(format!("list_tables query failed: {e}")))?
12122            .collect::<Result<Vec<_>, _>>()
12123            .map_err(|e| IoError::Sql(format!("list_tables row read failed: {e}")))?;
12124        Ok(names)
12125    }
12126
12127    fn list_views(&self, _schema: Option<&str>) -> Result<Vec<String>, IoError> {
12128        // Same single-namespace policy as list_tables; type='view'
12129        // distinguishes the two buckets in sqlite_master.
12130        // Per fd90.50: same ESCAPE '\' fix as list_tables to treat
12131        // the underscore in 'sqlite_' as a literal.
12132        let mut stmt = self
12133            .prepare(
12134                r"SELECT name FROM sqlite_master
12135                 WHERE type='view' AND name NOT LIKE 'sqlite\_%' ESCAPE '\'
12136                 ORDER BY name",
12137            )
12138            .map_err(|e| IoError::Sql(format!("list_views prepare failed: {e}")))?;
12139        let names = stmt
12140            .query_map([], |row| row.get::<_, String>(0))
12141            .map_err(|e| IoError::Sql(format!("list_views query failed: {e}")))?
12142            .collect::<Result<Vec<_>, _>>()
12143            .map_err(|e| IoError::Sql(format!("list_views row read failed: {e}")))?;
12144        Ok(names)
12145    }
12146
12147    fn table_schema(
12148        &self,
12149        table_name: &str,
12150        _schema: Option<&str>,
12151    ) -> Result<Option<SqlTableSchema>, IoError> {
12152        // Validate the table name first — PRAGMA table_info doesn't
12153        // accept parameter binding, so we must reject anything that
12154        // could break out of the identifier slot.
12155        validate_sql_table_name(table_name)?;
12156        // PRAGMA table_info returns: cid, name, type, notnull, dflt_value, pk.
12157        let pragma = format!("PRAGMA table_info(\"{}\")", table_name.replace('"', "\"\""));
12158        let mut stmt = self
12159            .prepare(&pragma)
12160            .map_err(|e| IoError::Sql(format!("table_schema prepare failed: {e}")))?;
12161        // PRAGMA table_info row tuple: (name, type, notnull, dflt_value, pk).
12162        // Type alias keeps clippy::type_complexity happy on the
12163        // intermediate Vec used for the two-pass autoincrement detection.
12164        type ColumnInfoRow = (String, Option<String>, i64, Option<String>, i64);
12165        let raw_rows: Vec<ColumnInfoRow> = stmt
12166            .query_map([], |row| {
12167                Ok((
12168                    row.get::<_, String>(1)?,
12169                    row.get::<_, Option<String>>(2)?,
12170                    row.get::<_, i64>(3)?,
12171                    row.get::<_, Option<String>>(4)?,
12172                    row.get::<_, i64>(5)?,
12173                ))
12174            })
12175            .map_err(|e| IoError::Sql(format!("table_schema query failed: {e}")))?
12176            .collect::<Result<Vec<_>, _>>()
12177            .map_err(|e| IoError::Sql(format!("table_schema row read failed: {e}")))?;
12178
12179        // Per fd90.42 (refines fd90.37): SQLite's rowid-alias rule
12180        // requires the column to be the SOLE primary key — i.e. exactly
12181        // one row in PRAGMA table_info has pk > 0. Composite PKs (where
12182        // multiple columns have pk > 0) never qualify, even if the
12183        // first column is INTEGER. So we count single-PK status across
12184        // the table before deciding any column's autoincrement bit.
12185        let pk_count = raw_rows.iter().filter(|(_, _, _, _, pk)| *pk > 0).count();
12186        let single_pk = pk_count == 1;
12187
12188        let mut columns: Vec<SqlColumnSchema> = Vec::with_capacity(raw_rows.len());
12189        for (name, declared, notnull, dflt, pk) in raw_rows {
12190            let cleaned_type = declared.filter(|s| !s.is_empty());
12191            let autoincrement = single_pk
12192                && pk == 1
12193                && cleaned_type
12194                    .as_deref()
12195                    .map(|t| t.eq_ignore_ascii_case("INTEGER"))
12196                    .unwrap_or(false);
12197            columns.push(SqlColumnSchema {
12198                name,
12199                declared_type: cleaned_type,
12200                nullable: notnull == 0,
12201                default_value: dflt,
12202                primary_key_ordinal: if pk > 0 {
12203                    Some(usize::try_from(pk - 1).unwrap_or(0))
12204                } else {
12205                    None
12206                },
12207                comment: None,
12208                autoincrement,
12209            });
12210        }
12211        if columns.is_empty() {
12212            // PRAGMA table_info on a non-existent table returns 0 rows
12213            // without erroring; map that to None so callers can
12214            // distinguish missing tables from empty ones.
12215            Ok(None)
12216        } else {
12217            Ok(Some(SqlTableSchema {
12218                table_name: table_name.to_owned(),
12219                columns,
12220            }))
12221        }
12222    }
12223
12224    fn server_version(&self) -> Result<Option<String>, IoError> {
12225        // sqlite_version() is a built-in scalar that returns the
12226        // SQLite library version string (e.g. "3.45.1").
12227        let version: String = self
12228            .query_row("SELECT sqlite_version()", [], |row| row.get(0))
12229            .map_err(|e| IoError::Sql(format!("server_version query failed: {e}")))?;
12230        Ok(Some(version))
12231    }
12232
12233    fn list_indexes(
12234        &self,
12235        table_name: &str,
12236        _schema: Option<&str>,
12237    ) -> Result<Vec<SqlIndexSchema>, IoError> {
12238        validate_sql_table_name(table_name)?;
12239        // PRAGMA index_list(table) returns: seq, name, unique, origin, partial.
12240        // origin is 'c' for CREATE INDEX (user), 'pk' for PRIMARY KEY auto,
12241        // 'u' for UNIQUE constraint auto. SQLAlchemy.Inspector surfaces
12242        // only the user-created ones, so we filter out 'pk' to match.
12243        let pragma_list = format!("PRAGMA index_list(\"{}\")", table_name.replace('"', "\"\""));
12244        let mut list_stmt = self
12245            .prepare(&pragma_list)
12246            .map_err(|e| IoError::Sql(format!("list_indexes prepare failed: {e}")))?;
12247        let index_meta = list_stmt
12248            .query_map([], |row| {
12249                Ok((
12250                    row.get::<_, String>(1)?, // name
12251                    row.get::<_, i64>(2)?,    // unique flag
12252                    row.get::<_, String>(3)?, // origin
12253                ))
12254            })
12255            .map_err(|e| IoError::Sql(format!("list_indexes query failed: {e}")))?
12256            .collect::<Result<Vec<_>, _>>()
12257            .map_err(|e| IoError::Sql(format!("list_indexes row read failed: {e}")))?;
12258
12259        let mut indexes = Vec::new();
12260        for (name, uniq, origin) in index_meta {
12261            if origin == "pk" {
12262                // Auto-created PK index — pandas/SQLAlchemy hide it.
12263                continue;
12264            }
12265            if origin == "u" {
12266                // Auto-created index backing a declared UNIQUE
12267                // constraint — surfaced via list_unique_constraints
12268                // (fd90.31), not here, to match SQLAlchemy disjoint
12269                // bucketing between get_indexes and
12270                // get_unique_constraints.
12271                continue;
12272            }
12273            // PRAGMA index_info(idx) returns: seqno, cid, column_name (col2 may
12274            // be NULL for expression-based indexes — skip those rather than
12275            // surfacing partial column lists).
12276            let pragma_info = format!("PRAGMA index_info(\"{}\")", name.replace('"', "\"\""));
12277            let mut info_stmt = self
12278                .prepare(&pragma_info)
12279                .map_err(|e| IoError::Sql(format!("index_info prepare failed: {e}")))?;
12280            let cols = info_stmt
12281                .query_map([], |row| {
12282                    Ok((row.get::<_, i64>(0)?, row.get::<_, Option<String>>(2)?))
12283                })
12284                .map_err(|e| IoError::Sql(format!("index_info query failed: {e}")))?
12285                .collect::<Result<Vec<_>, _>>()
12286                .map_err(|e| IoError::Sql(format!("index_info row read failed: {e}")))?;
12287            // Skip expression-based indexes (any column_name is NULL).
12288            if cols.iter().any(|(_, c)| c.is_none()) {
12289                continue;
12290            }
12291            let mut sorted: Vec<(i64, String)> = cols
12292                .into_iter()
12293                .map(|(seq, c)| (seq, c.unwrap_or_default()))
12294                .collect();
12295            sorted.sort_by_key(|(seq, _)| *seq);
12296            indexes.push(SqlIndexSchema {
12297                name,
12298                columns: sorted.into_iter().map(|(_, c)| c).collect(),
12299                unique: uniq != 0,
12300            });
12301        }
12302        Ok(indexes)
12303    }
12304
12305    fn list_unique_constraints(
12306        &self,
12307        table_name: &str,
12308        _schema: Option<&str>,
12309    ) -> Result<Vec<SqlUniqueConstraintSchema>, IoError> {
12310        validate_sql_table_name(table_name)?;
12311        // PRAGMA index_list(table) origin column:
12312        //   'c' = CREATE INDEX (user) — surfaces via list_indexes
12313        //   'u' = UNIQUE constraint   — surfaces here
12314        //   'pk' = PRIMARY KEY auto   — surfaces via primary_key_columns
12315        let pragma_list = format!("PRAGMA index_list(\"{}\")", table_name.replace('"', "\"\""));
12316        let mut list_stmt = self
12317            .prepare(&pragma_list)
12318            .map_err(|e| IoError::Sql(format!("list_unique_constraints prepare failed: {e}")))?;
12319        let candidates = list_stmt
12320            .query_map([], |row| {
12321                Ok((
12322                    row.get::<_, String>(1)?, // index name
12323                    row.get::<_, String>(3)?, // origin
12324                ))
12325            })
12326            .map_err(|e| IoError::Sql(format!("list_unique_constraints query failed: {e}")))?
12327            .collect::<Result<Vec<_>, _>>()
12328            .map_err(|e| IoError::Sql(format!("list_unique_constraints row read failed: {e}")))?;
12329
12330        let mut constraints = Vec::new();
12331        for (name, origin) in candidates {
12332            if origin != "u" {
12333                continue;
12334            }
12335            let pragma_info = format!("PRAGMA index_info(\"{}\")", name.replace('"', "\"\""));
12336            let mut info_stmt = self
12337                .prepare(&pragma_info)
12338                .map_err(|e| IoError::Sql(format!("uq index_info prepare failed: {e}")))?;
12339            let cols = info_stmt
12340                .query_map([], |row| {
12341                    Ok((row.get::<_, i64>(0)?, row.get::<_, Option<String>>(2)?))
12342                })
12343                .map_err(|e| IoError::Sql(format!("uq index_info query failed: {e}")))?
12344                .collect::<Result<Vec<_>, _>>()
12345                .map_err(|e| IoError::Sql(format!("uq index_info row read failed: {e}")))?;
12346            // Skip expression-based unique constraints (column NULL).
12347            if cols.iter().any(|(_, c)| c.is_none()) {
12348                continue;
12349            }
12350            let mut sorted: Vec<(i64, String)> = cols
12351                .into_iter()
12352                .map(|(seq, c)| (seq, c.unwrap_or_default()))
12353                .collect();
12354            sorted.sort_by_key(|(seq, _)| *seq);
12355            constraints.push(SqlUniqueConstraintSchema {
12356                name,
12357                columns: sorted.into_iter().map(|(_, c)| c).collect(),
12358            });
12359        }
12360        Ok(constraints)
12361    }
12362
12363    fn list_foreign_keys(
12364        &self,
12365        table_name: &str,
12366        _schema: Option<&str>,
12367    ) -> Result<Vec<SqlForeignKeySchema>, IoError> {
12368        // PRAGMA foreign_key_list rows: (seq, referenced_table, from_col, to_col).
12369        // The constraint id is the BTreeMap key; we don't repeat it inside the
12370        // value tuple. Type alias keeps clippy::type_complexity happy and
12371        // the grouping logic readable.
12372        type FkRow = (i64, String, String, Option<String>);
12373
12374        validate_sql_table_name(table_name)?;
12375        // PRAGMA foreign_key_list(table) returns: id, seq, table, from, to,
12376        // on_update, on_delete, match. Each `id` is one FK constraint;
12377        // multiple rows with the same id describe a composite FK.
12378        let pragma = format!(
12379            "PRAGMA foreign_key_list(\"{}\")",
12380            table_name.replace('"', "\"\"")
12381        );
12382        let mut stmt = self
12383            .prepare(&pragma)
12384            .map_err(|e| IoError::Sql(format!("list_foreign_keys prepare failed: {e}")))?;
12385        let rows: Vec<(i64, FkRow)> = stmt
12386            .query_map([], |row| {
12387                Ok((
12388                    row.get::<_, i64>(0)?, // id
12389                    (
12390                        row.get::<_, i64>(1)?,            // seq
12391                        row.get::<_, String>(2)?,         // referenced table
12392                        row.get::<_, String>(3)?,         // from column
12393                        row.get::<_, Option<String>>(4)?, // to column (nullable)
12394                    ),
12395                ))
12396            })
12397            .map_err(|e| IoError::Sql(format!("list_foreign_keys query failed: {e}")))?
12398            .collect::<Result<Vec<_>, _>>()
12399            .map_err(|e| IoError::Sql(format!("list_foreign_keys row read failed: {e}")))?;
12400
12401        // Group by id; preserve discovery order across distinct ids.
12402        let mut order: Vec<i64> = Vec::new();
12403        let mut grouped: std::collections::BTreeMap<i64, Vec<FkRow>> =
12404            std::collections::BTreeMap::new();
12405        for (id, fk_row) in rows {
12406            let (seq, ref_table, from_col, to_col) = fk_row;
12407            if !grouped.contains_key(&id) {
12408                order.push(id);
12409            }
12410            grouped
12411                .entry(id)
12412                .or_default()
12413                .push((seq, ref_table, from_col, to_col));
12414        }
12415
12416        let mut fks = Vec::with_capacity(order.len());
12417        for id in order {
12418            let mut group = grouped.remove(&id).unwrap_or_default();
12419            group.sort_by_key(|(seq, _, _, _)| *seq);
12420            let ref_table = group
12421                .first()
12422                .map(|(_, t, _, _)| t.clone())
12423                .unwrap_or_default();
12424            let mut columns = Vec::with_capacity(group.len());
12425            let mut referenced_columns: Vec<Option<String>> = Vec::with_capacity(group.len());
12426            for (_, _, from_col, to_col) in group {
12427                columns.push(from_col);
12428                referenced_columns.push(to_col);
12429            }
12430            // Per fd90.44: when ALL `to` columns are NULL, the user
12431            // declared `FOREIGN KEY (cols) REFERENCES parent` (implicit
12432            // reference to parent's PK). Resolve by looking up the
12433            // parent's primary key columns. SQLAlchemy.Inspector
12434            // surfaces these as resolved-to-PK references; matching
12435            // that behavior keeps callers from missing real FKs.
12436            let resolved_columns: Vec<String> = if referenced_columns.iter().all(Option::is_none) {
12437                // Implicit-PK reference: look up parent's PK.
12438                let pk = self.primary_key_columns(&ref_table, None)?;
12439                if pk.len() == columns.len() {
12440                    pk
12441                } else {
12442                    // Parent PK shape doesn't match FK column count
12443                    // (parent has no PK, or composite mismatch). Skip
12444                    // — fabricating columns would mislead callers
12445                    // worse than hiding the FK.
12446                    continue;
12447                }
12448            } else if referenced_columns.iter().all(Option::is_some) {
12449                // Fully explicit: every column has a resolved 'to'.
12450                referenced_columns.into_iter().flatten().collect()
12451            } else {
12452                // Mixed Some/None: SQLite shouldn't produce this for
12453                // a single FK group, but if it ever does, skip rather
12454                // than mispair.
12455                continue;
12456            };
12457            fks.push(SqlForeignKeySchema {
12458                // SQLite PRAGMA foreign_key_list does not surface a
12459                // CONSTRAINT name; pandas/SQLAlchemy report None there too.
12460                constraint_name: None,
12461                columns,
12462                referenced_table: ref_table,
12463                referenced_columns: resolved_columns,
12464            });
12465        }
12466        Ok(fks)
12467    }
12468}
12469
12470#[cfg(feature = "sql-sqlite")]
12471fn sql_dtype_from_index(index: &Index) -> &'static str {
12472    for label in index.labels() {
12473        match label {
12474            IndexLabel::Int64(_) => return "INTEGER",
12475            IndexLabel::Utf8(_) => return "TEXT",
12476            IndexLabel::Timedelta64(v) if *v != Timedelta::NAT => return "INTEGER",
12477            IndexLabel::Datetime64(v) if *v != i64::MIN => return "TEXT",
12478            _ => {}
12479        }
12480    }
12481    "TEXT"
12482}
12483
12484fn resolve_sql_index_label(
12485    frame: &DataFrame,
12486    options: &SqlWriteOptions,
12487) -> Result<Option<String>, IoError> {
12488    if !options.index {
12489        return Ok(None);
12490    }
12491
12492    let label = options
12493        .index_label
12494        .clone()
12495        .or_else(|| frame.index().name().map(str::to_owned))
12496        .unwrap_or_else(|| "index".to_owned());
12497
12498    if frame.column(&label).is_some() {
12499        return Err(IoError::DuplicateColumnName(label));
12500    }
12501
12502    Ok(Some(label))
12503}
12504
12505// Per br-frankenpandas-ld8h (fd90.45): these helpers are only called
12506// from the rusqlite SqlConnection impl, which is gated behind
12507// `feature = "sql-sqlite"`. Mirroring the gate here keeps
12508// --no-default-features builds clean of dead-code warnings.
12509#[cfg(feature = "sql-sqlite")]
12510fn escape_sql_ident(name: &str) -> Result<String, IoError> {
12511    if name.contains('\0') {
12512        return Err(IoError::Sql("invalid SQL identifier: NUL byte".to_owned()));
12513    }
12514    Ok(name.replace('"', "\"\""))
12515}
12516
12517#[cfg(feature = "sql-sqlite")]
12518fn quote_sql_ident(name: &str) -> Result<String, IoError> {
12519    Ok(format!("\"{}\"", escape_sql_ident(name)?))
12520}
12521
12522/// Per br-frankenpandas-4l7a (fd90.55): shared identifier-shape
12523/// validator used by `validate_sql_table_name` and
12524/// `validate_sql_column_name`. `kind` is the user-facing label
12525/// inserted into the error message ("table", "column", ...). The
12526/// rule is the same for both: non-empty, ASCII-alphanumeric or
12527/// underscore only — defense in depth alongside `quote_identifier`
12528/// (which handles embedded quotes but doesn't reject other shapes).
12529fn validate_sql_ident(name: &str, kind: &str) -> Result<(), IoError> {
12530    if name.is_empty() || !name.chars().all(|c| c.is_alphanumeric() || c == '_') {
12531        return Err(IoError::Sql(format!(
12532            "invalid {kind} name: '{name}' (must be non-empty, only alphanumeric and underscore allowed)"
12533        )));
12534    }
12535    Ok(())
12536}
12537
12538fn validate_sql_table_name(table_name: &str) -> Result<(), IoError> {
12539    validate_sql_ident(table_name, "table")
12540}
12541
12542/// Per br-frankenpandas-597l (fd90.56): dedicated schema-name
12543/// validator so error messages correctly identify the invalid
12544/// identifier as a schema rather than a table. Same alphanumeric+
12545/// underscore rule as table/column names.
12546fn validate_sql_schema_name(schema: &str) -> Result<(), IoError> {
12547    validate_sql_ident(schema, "schema")
12548}
12549
12550/// Validate `name` against the backend's identifier-length cap.
12551///
12552/// Per br-frankenpandas-9ynk (fd90.27). When `max` is `Some(n)`, errors
12553/// out when `name.len() > n`. When `max` is `None`, accepts any length
12554/// (e.g. SQLite, where the engine has no documented limit). `kind` is
12555/// the user-facing label used in the error message ("table", "column",
12556/// "index label", ...) so misuse points cleanly back to the offending
12557/// identifier without callers having to format the message.
12558fn validate_sql_identifier_length(
12559    name: &str,
12560    max: Option<usize>,
12561    kind: &str,
12562) -> Result<(), IoError> {
12563    if let Some(limit) = max
12564        && name.len() > limit
12565    {
12566        return Err(IoError::Sql(format!(
12567            "invalid {kind} name '{name}': length {len} exceeds backend identifier limit ({limit})",
12568            len = name.len()
12569        )));
12570    }
12571    Ok(())
12572}
12573
12574fn validate_sql_table_ref_identifier_lengths<C: SqlConnection + ?Sized>(
12575    conn: &C,
12576    table_name: &str,
12577    schema: Option<&str>,
12578) -> Result<(), IoError> {
12579    let max = conn.max_identifier_length();
12580    validate_sql_identifier_length(table_name, max, "table")?;
12581    if let Some(s) = schema {
12582        validate_sql_identifier_length(s, max, "schema")?;
12583    }
12584    Ok(())
12585}
12586
12587fn validate_sql_column_identifier_lengths<C, I, S>(conn: &C, names: I) -> Result<(), IoError>
12588where
12589    C: SqlConnection + ?Sized,
12590    I: IntoIterator<Item = S>,
12591    S: AsRef<str>,
12592{
12593    let max = conn.max_identifier_length();
12594    for name in names {
12595        validate_sql_identifier_length(name.as_ref(), max, "column")?;
12596    }
12597    Ok(())
12598}
12599
12600fn sql_select_all_query<C: SqlConnection>(conn: &C, table_name: &str) -> Result<String, IoError> {
12601    sql_select_all_query_in_schema(conn, table_name, None)
12602}
12603
12604/// Build a `SELECT * FROM ...` statement, optionally schema-qualified.
12605///
12606/// Per br-frankenpandas-u6zn (fd90.14). When `schema` is `Some(s)` AND
12607/// `conn.supports_schemas()`, the FROM clause becomes `\"schema\".\"table\"`.
12608/// When `supports_schemas` returns false, any `Some(s)` is rejected before
12609/// query generation so `read_sql_table(schema=...)` matches pandas' fail-closed
12610/// SQLite behavior.
12611fn sql_select_all_query_in_schema<C: SqlConnection>(
12612    conn: &C,
12613    table_name: &str,
12614    schema: Option<&str>,
12615) -> Result<String, IoError> {
12616    validate_sql_table_name(table_name)?;
12617    validate_sql_table_ref_identifier_lengths(conn, table_name, schema)?;
12618    let qualified = match schema {
12619        Some(s) => {
12620            validate_sql_schema_name(s)?;
12621            if !conn.supports_schemas() {
12622                return Err(IoError::Sql(format!(
12623                    "read_sql_table: schema is not supported by {} backend",
12624                    conn.dialect_name()
12625                )));
12626            }
12627            format!(
12628                "{}.{}",
12629                conn.quote_identifier(s)?,
12630                conn.quote_identifier(table_name)?
12631            )
12632        }
12633        _ => conn.quote_identifier(table_name)?,
12634    };
12635    Ok(format!("SELECT * FROM {qualified}"))
12636}
12637
12638fn validate_sql_column_name(column_name: &str) -> Result<(), IoError> {
12639    validate_sql_ident(column_name, "column")
12640}
12641
12642fn sql_select_columns_query<C: SqlConnection>(
12643    conn: &C,
12644    table_name: &str,
12645    columns: &[&str],
12646) -> Result<String, IoError> {
12647    sql_select_columns_query_in_schema(conn, table_name, None, columns)
12648}
12649
12650/// Build a `SELECT col1, col2, ... FROM ...` statement, optionally
12651/// schema-qualified.
12652///
12653/// Per br-frankenpandas-d3e9 (fd90.34). Companion to
12654/// `sql_select_all_query_in_schema`. Same schema rules: when
12655/// `schema` is `Some(s)` AND `conn.supports_schemas()`, the FROM
12656/// clause becomes `\"schema\".\"table\"`; when `supports_schemas()`
12657/// returns false, the request is rejected before query generation.
12658fn sql_select_columns_query_in_schema<C: SqlConnection>(
12659    conn: &C,
12660    table_name: &str,
12661    schema: Option<&str>,
12662    columns: &[&str],
12663) -> Result<String, IoError> {
12664    validate_sql_table_name(table_name)?;
12665    if columns.is_empty() {
12666        return Err(IoError::Sql(
12667            "read_sql_table_columns: columns must be non-empty".to_owned(),
12668        ));
12669    }
12670    for name in columns {
12671        validate_sql_column_name(name)?;
12672    }
12673    validate_sql_table_ref_identifier_lengths(conn, table_name, schema)?;
12674    validate_sql_column_identifier_lengths(conn, columns)?;
12675
12676    let qualified = match schema {
12677        Some(s) => {
12678            validate_sql_schema_name(s)?;
12679            if !conn.supports_schemas() {
12680                return Err(IoError::Sql(format!(
12681                    "read_sql_table: schema is not supported by {} backend",
12682                    conn.dialect_name()
12683                )));
12684            }
12685            format!(
12686                "{}.{}",
12687                conn.quote_identifier(s)?,
12688                conn.quote_identifier(table_name)?
12689            )
12690        }
12691        _ => conn.quote_identifier(table_name)?,
12692    };
12693    let projection: Vec<String> = columns
12694        .iter()
12695        .map(|name| conn.quote_identifier(name))
12696        .collect::<Result<_, _>>()?;
12697    Ok(format!(
12698        "SELECT {} FROM {}",
12699        projection.join(", "),
12700        qualified
12701    ))
12702}
12703
12704fn sql_column_definition<C: SqlConnection>(
12705    conn: &C,
12706    column_name: &str,
12707    sql_type: &str,
12708) -> Result<String, IoError> {
12709    Ok(format!(
12710        "{} {sql_type}",
12711        conn.quote_identifier(column_name)?
12712    ))
12713}
12714
12715// ============================================================================
12716// PostgreSQL SqlConnection placeholder (feature = "sql-postgresql")
12717// ============================================================================
12718
12719#[cfg(feature = "sql-mysql")]
12720use std::cell::RefCell;
12721
12722// The `sql-postgresql` feature is intentionally a placeholder under the
12723// workspace no-Tokio policy. The removed concrete adapter used the `postgres`
12724// crate, which is built on tokio-postgres and pulled Tokio into all-features
12725// builds even when users did not need PostgreSQL.
12726
12727// ============================================================================
12728// MySQL SqlConnection Implementation (feature = "sql-mysql")
12729// ============================================================================
12730
12731/// Map an fp-types `DType` to a MySQL column type declaration.
12732///
12733/// br-frankenpandas-lkrb8. A free function rather than a method body so the
12734/// nullable-pairing contract can be tested without a live MySQL server — the
12735/// only reason `Float64Nullable => TEXT` survived is that nothing could reach
12736/// this mapping without one.
12737///
12738/// ⚠ THE `_` ARM IS THE HAZARD, and it stays only because the trailing dtypes
12739/// (`Categorical`, `Null`, `Sparse`, `Period`, `Interval`) genuinely serialize as
12740/// text here. Every NUMERIC dtype, nullable or not, must be listed explicitly
12741/// above it: `Float64Nullable` was added to fp-types and fell straight through to
12742/// `TEXT`, which is a wrong column type in generated DDL and produced no error
12743/// anywhere. `mysql_nullable_dtypes_declare_the_same_column_as_their_base`
12744/// pins the pairing so the next nullable variant cannot repeat it.
12745#[cfg(feature = "sql-mysql")]
12746fn mysql_dtype_sql(dtype: DType) -> &'static str {
12747    // Exhaustive on purpose: the former `_ => "TEXT"` arm is exactly how
12748    // `Float64Nullable` shipped as a TEXT column (br-frankenpandas-lkrb8). A new
12749    // `DType` variant is now a compile error here, which forces the author to
12750    // choose its column type instead of inheriting one silently.
12751    match dtype {
12752        DType::Bool | DType::BoolNullable => "TINYINT(1)",
12753        DType::Int64 | DType::Int64Nullable => "BIGINT",
12754        DType::Float64 | DType::Float64Nullable => "DOUBLE",
12755        DType::Utf8 => "TEXT",
12756        DType::Datetime64 { .. } => "DATETIME",
12757        DType::Timedelta64 => "TIME",
12758        // These genuinely serialize as text through this writer today.
12759        DType::Null | DType::Categorical | DType::Period | DType::Interval | DType::Sparse => {
12760            "TEXT"
12761        }
12762    }
12763}
12764
12765/// br-frankenpandas-lkrb8. A nullable extension dtype must declare the SAME
12766/// column type as its non-nullable base — the nullability is a property of the
12767/// values, not of the storage.
12768///
12769/// The observed defect this pins: `Float64Nullable` was added to fp-types
12770/// (crates/fp-types/src/lib.rs:101) and neither fp-io SQL mapper was updated.
12771/// The exhaustive one (the test mock's) became a hard compile error and took
12772/// `cargo check --all-targets` red on main. The MySQL one has a `_ => "TEXT"`
12773/// arm, so it compiled fine and quietly declared nullable floats as TEXT.
12774///
12775/// This asserts the PAIRING rather than the three specific strings, so the next
12776/// nullable variant added to `DType` fails here instead of falling through a
12777/// catch-all. A test that merely called the mapper and checked it returned
12778/// something would have passed against the broken arm.
12779#[cfg(test)]
12780mod nullable_dtype_sql_pairing_lkrb8 {
12781    use fp_types::DType;
12782
12783    const NULLABLE_PAIRS: [(DType, DType); 3] = [
12784        (DType::BoolNullable, DType::Bool),
12785        (DType::Int64Nullable, DType::Int64),
12786        (DType::Float64Nullable, DType::Float64),
12787    ];
12788
12789    #[cfg(feature = "sql-sqlite")]
12790    #[test]
12791    fn sqlite_nullable_dtypes_declare_the_same_column_as_their_base() {
12792        for (nullable, base) in NULLABLE_PAIRS {
12793            assert_eq!(
12794                super::dtype_to_sql(nullable.clone()),
12795                super::dtype_to_sql(base.clone()),
12796                "{nullable:?} must declare the same SQLite column type as {base:?}"
12797            );
12798        }
12799        assert_eq!(super::dtype_to_sql(DType::Float64Nullable), "REAL");
12800    }
12801
12802    #[cfg(feature = "sql-mysql")]
12803    #[test]
12804    fn mysql_nullable_dtypes_declare_the_same_column_as_their_base() {
12805        for (nullable, base) in NULLABLE_PAIRS {
12806            assert_eq!(
12807                super::mysql_dtype_sql(nullable.clone()),
12808                super::mysql_dtype_sql(base.clone()),
12809                "{nullable:?} must declare the same MySQL column type as {base:?}"
12810            );
12811        }
12812        // The exact instance that was wrong: this returned "TEXT" via the `_` arm.
12813        assert_eq!(super::mysql_dtype_sql(DType::Float64Nullable), "DOUBLE");
12814    }
12815}
12816
12817/// Wrapper around `mysql::Conn` providing interior mutability for the
12818/// `SqlConnection` trait (which requires `&self`).
12819#[cfg(feature = "sql-mysql")]
12820pub struct MysqlConnection {
12821    conn: RefCell<mysql::Conn>,
12822}
12823
12824#[cfg(feature = "sql-mysql")]
12825impl MysqlConnection {
12826    pub fn new(conn: mysql::Conn) -> Self {
12827        Self {
12828            conn: RefCell::new(conn),
12829        }
12830    }
12831}
12832
12833#[cfg(feature = "sql-mysql")]
12834impl SqlConnection for MysqlConnection {
12835    fn query(&self, query_str: &str, params: &[Scalar]) -> Result<SqlQueryResult, IoError> {
12836        use mysql::prelude::*;
12837
12838        let mysql_params: Vec<mysql::Value> = params.iter().map(scalar_to_mysql_value).collect();
12839        let result: Vec<mysql::Row> = self
12840            .conn
12841            .borrow_mut()
12842            .exec(query_str, mysql_params)
12843            .map_err(|e| IoError::Sql(format!("MySQL query failed: {e}")))?;
12844
12845        if result.is_empty() {
12846            return Ok(SqlQueryResult {
12847                columns: Vec::new(),
12848                rows: Vec::new(),
12849            });
12850        }
12851
12852        let columns: Vec<String> = result[0]
12853            .columns_ref()
12854            .iter()
12855            .map(|c| c.name_str().to_string())
12856            .collect();
12857
12858        let mut out_rows = Vec::new();
12859        for row in &result {
12860            let mut values = Vec::new();
12861            for idx in 0..row.len() {
12862                let value = mysql_value_to_scalar(row.get(idx));
12863                values.push(value);
12864            }
12865            out_rows.push(values);
12866        }
12867
12868        Ok(SqlQueryResult {
12869            columns,
12870            rows: out_rows,
12871        })
12872    }
12873
12874    fn execute_batch(&self, sql: &str) -> Result<(), IoError> {
12875        use mysql::prelude::*;
12876        let mut conn = self.conn.borrow_mut();
12877        for statement in sql.split(';').filter(|s| !s.trim().is_empty()) {
12878            conn.query_drop(statement)
12879                .map_err(|e| IoError::Sql(format!("MySQL execute failed: {e}")))?;
12880        }
12881        Ok(())
12882    }
12883
12884    fn table_exists(&self, table_name: &str) -> Result<bool, IoError> {
12885        use mysql::prelude::*;
12886        let result: Option<(i32,)> = self
12887            .conn
12888            .borrow_mut()
12889            .exec_first(
12890                "SELECT 1 FROM information_schema.tables WHERE table_name = ? LIMIT 1",
12891                (table_name,),
12892            )
12893            .map_err(|e| IoError::Sql(format!("MySQL table_exists failed: {e}")))?;
12894        Ok(result.is_some())
12895    }
12896
12897    fn insert_rows(&self, insert_sql: &str, rows: &[Vec<Scalar>]) -> Result<(), IoError> {
12898        use mysql::prelude::*;
12899        let mut conn = self.conn.borrow_mut();
12900        for row in rows {
12901            let params: Vec<mysql::Value> = row.iter().map(scalar_to_mysql_value).collect();
12902            conn.exec_drop(insert_sql, params)
12903                .map_err(|e| IoError::Sql(format!("MySQL insert failed: {e}")))?;
12904        }
12905        Ok(())
12906    }
12907
12908    fn dtype_sql(&self, dtype: DType) -> &'static str {
12909        mysql_dtype_sql(dtype)
12910    }
12911
12912    fn index_dtype_sql(&self, index: &Index) -> &'static str {
12913        mysql_sql_dtype_from_index(index)
12914    }
12915
12916    fn dialect_name(&self) -> &'static str {
12917        "mysql"
12918    }
12919
12920    fn parameter_marker(&self, _ordinal: usize) -> String {
12921        "?".to_owned()
12922    }
12923
12924    fn supports_returning(&self) -> bool {
12925        false
12926    }
12927
12928    fn max_param_count(&self) -> Option<usize> {
12929        Some(65535)
12930    }
12931
12932    fn max_identifier_length(&self) -> Option<usize> {
12933        Some(64)
12934    }
12935
12936    fn quote_identifier(&self, ident: &str) -> Result<String, IoError> {
12937        if ident.contains('\0') {
12938            return Err(IoError::Sql("invalid identifier: NUL byte".to_owned()));
12939        }
12940        Ok(format!("`{}`", ident.replace('`', "``")))
12941    }
12942
12943    fn list_tables(&self, _schema: Option<&str>) -> Result<Vec<String>, IoError> {
12944        use mysql::prelude::*;
12945        let rows: Vec<(String,)> = self
12946            .conn
12947            .borrow_mut()
12948            .query("SHOW TABLES")
12949            .map_err(|e| IoError::Sql(format!("MySQL list_tables failed: {e}")))?;
12950        Ok(rows.into_iter().map(|(name,)| name).collect())
12951    }
12952}
12953
12954#[cfg(feature = "sql-mysql")]
12955fn mysql_sql_dtype_from_index(index: &Index) -> &'static str {
12956    for label in index.labels() {
12957        match label {
12958            IndexLabel::Int64(_) => return "BIGINT",
12959            IndexLabel::Utf8(_) => return "VARCHAR(255)",
12960            IndexLabel::Timedelta64(v) if *v != Timedelta::NAT => return "TIME",
12961            IndexLabel::Datetime64(v) if *v != i64::MIN => return "DATETIME",
12962            _ => {}
12963        }
12964    }
12965    "VARCHAR(255)"
12966}
12967
12968#[cfg(feature = "sql-mysql")]
12969fn scalar_to_mysql_value(s: &Scalar) -> mysql::Value {
12970    match s {
12971        Scalar::Null(_) => mysql::Value::NULL,
12972        Scalar::Bool(b) => mysql::Value::from(*b),
12973        Scalar::Int64(i) => mysql::Value::from(*i),
12974        Scalar::Float64(f) => mysql::Value::from(*f),
12975        Scalar::Utf8(s) => mysql::Value::from(s.as_str()),
12976        _ => mysql::Value::NULL,
12977    }
12978}
12979
12980#[cfg(feature = "sql-mysql")]
12981fn mysql_value_to_scalar(v: Option<mysql::Value>) -> Scalar {
12982    match v {
12983        None | Some(mysql::Value::NULL) => Scalar::Null(crate::NullKind::Null),
12984        Some(mysql::Value::Bytes(b)) => Scalar::Utf8(String::from_utf8_lossy(&b).into_owned()),
12985        Some(mysql::Value::Int(i)) => Scalar::Int64(i),
12986        Some(mysql::Value::UInt(u)) => Scalar::Int64(u as i64),
12987        Some(mysql::Value::Float(f)) => Scalar::Float64(f as f64),
12988        Some(mysql::Value::Double(d)) => Scalar::Float64(d),
12989        _ => Scalar::Null(crate::NullKind::Null),
12990    }
12991}
12992
12993#[cfg(test)]
12994fn sql_create_table_query<C: SqlConnection>(
12995    conn: &C,
12996    table_name: &str,
12997    column_defs: &[String],
12998) -> Result<String, IoError> {
12999    sql_create_table_query_in_schema(conn, table_name, None, column_defs)
13000}
13001
13002/// Build a `CREATE TABLE IF NOT EXISTS ...` statement, optionally
13003/// schema-qualified.
13004///
13005/// Per br-frankenpandas-udn6 (fd90.15). When `schema` is `Some(s)` AND
13006/// `conn.supports_schemas()`, the target becomes `"schema"."table"`. On
13007/// backends that report false, any `Some(s)` is silently ignored.
13008fn sql_create_table_query_in_schema<C: SqlConnection>(
13009    conn: &C,
13010    table_name: &str,
13011    schema: Option<&str>,
13012    column_defs: &[String],
13013) -> Result<String, IoError> {
13014    validate_sql_table_name(table_name)?;
13015    validate_sql_table_ref_identifier_lengths(conn, table_name, schema)?;
13016    let qualified = match schema {
13017        Some(s) if conn.supports_schemas() => {
13018            validate_sql_schema_name(s)?;
13019            format!(
13020                "{}.{}",
13021                conn.quote_identifier(s)?,
13022                conn.quote_identifier(table_name)?
13023            )
13024        }
13025        _ => conn.quote_identifier(table_name)?,
13026    };
13027    Ok(format!(
13028        "CREATE TABLE IF NOT EXISTS {qualified} ({})",
13029        column_defs.join(", ")
13030    ))
13031}
13032
13033#[cfg(test)]
13034fn sql_insert_rows_query<C: SqlConnection>(
13035    conn: &C,
13036    table_name: &str,
13037    column_names: &[String],
13038) -> Result<String, IoError> {
13039    sql_insert_rows_query_in_schema(conn, table_name, None, column_names)
13040}
13041
13042/// Build an `INSERT INTO ... VALUES (...)` statement, optionally
13043/// schema-qualified.
13044///
13045/// Per br-frankenpandas-udn6 (fd90.15). Same schema rules as the CREATE
13046/// TABLE counterpart.
13047fn sql_insert_rows_query_in_schema<C: SqlConnection>(
13048    conn: &C,
13049    table_name: &str,
13050    schema: Option<&str>,
13051    column_names: &[String],
13052) -> Result<String, IoError> {
13053    validate_sql_table_name(table_name)?;
13054    validate_sql_table_ref_identifier_lengths(conn, table_name, schema)?;
13055    validate_sql_column_identifier_lengths(conn, column_names.iter())?;
13056    let qualified = match schema {
13057        Some(s) if conn.supports_schemas() => {
13058            validate_sql_schema_name(s)?;
13059            format!(
13060                "{}.{}",
13061                conn.quote_identifier(s)?,
13062                conn.quote_identifier(table_name)?
13063            )
13064        }
13065        _ => conn.quote_identifier(table_name)?,
13066    };
13067    let quoted_columns = column_names
13068        .iter()
13069        .map(|name| conn.quote_identifier(name))
13070        .collect::<Result<Vec<_>, _>>()?
13071        .join(", ");
13072    let placeholders = (1..=column_names.len())
13073        .map(|ordinal| conn.parameter_marker(ordinal))
13074        .collect::<Vec<_>>()
13075        .join(", ");
13076    Ok(format!(
13077        "INSERT INTO {qualified} ({quoted_columns}) VALUES ({placeholders})"
13078    ))
13079}
13080
13081/// Build a multi-row `INSERT INTO ... VALUES (...), (...), ...`
13082/// statement, optionally schema-qualified.
13083///
13084/// Placeholder ordinals span 1..=`num_rows` * `column_names.len()` so
13085/// PostgreSQL-style `$N` markers stay unique across the whole statement.
13086/// SQLite's `?N` and the bare `?` default also work because positional
13087/// binding consumes ordinals in left-to-right order.
13088///
13089/// Per br-frankenpandas-i0ml (fd90.19).
13090fn sql_multi_row_insert_query_in_schema<C: SqlConnection>(
13091    conn: &C,
13092    table_name: &str,
13093    schema: Option<&str>,
13094    column_names: &[String],
13095    num_rows: usize,
13096) -> Result<String, IoError> {
13097    validate_sql_table_name(table_name)?;
13098    if num_rows == 0 || column_names.is_empty() {
13099        return Err(IoError::Sql(
13100            "multi-row insert requires at least one row and one column".to_owned(),
13101        ));
13102    }
13103    validate_sql_table_ref_identifier_lengths(conn, table_name, schema)?;
13104    validate_sql_column_identifier_lengths(conn, column_names.iter())?;
13105    let qualified = match schema {
13106        Some(s) if conn.supports_schemas() => {
13107            validate_sql_schema_name(s)?;
13108            format!(
13109                "{}.{}",
13110                conn.quote_identifier(s)?,
13111                conn.quote_identifier(table_name)?
13112            )
13113        }
13114        _ => conn.quote_identifier(table_name)?,
13115    };
13116    let quoted_columns = column_names
13117        .iter()
13118        .map(|name| conn.quote_identifier(name))
13119        .collect::<Result<Vec<_>, _>>()?
13120        .join(", ");
13121    let cols = column_names.len();
13122    let mut tuples = Vec::with_capacity(num_rows);
13123    let mut next_ord = 1usize;
13124    for _ in 0..num_rows {
13125        let row_placeholders = (0..cols)
13126            .map(|_| {
13127                let marker = conn.parameter_marker(next_ord);
13128                next_ord += 1;
13129                marker
13130            })
13131            .collect::<Vec<_>>()
13132            .join(", ");
13133        tuples.push(format!("({row_placeholders})"));
13134    }
13135    Ok(format!(
13136        "INSERT INTO {qualified} ({quoted_columns}) VALUES {}",
13137        tuples.join(", ")
13138    ))
13139}
13140
13141/// Build a `DROP TABLE IF EXISTS ...` statement, optionally
13142/// schema-qualified.
13143///
13144/// Per br-frankenpandas-hxob (fd90.16). Companion to
13145/// `sql_create_table_query_in_schema`. Same schema rules: when
13146/// `schema` is `Some(s)` AND `conn.supports_schemas()`, the target
13147/// becomes `\"schema\".\"table\"`; otherwise the bare table name is
13148/// used. Routes through `conn.quote_identifier` so backend dialect
13149/// overrides (MySQL backticks etc.) take effect on the drop path.
13150fn sql_drop_table_query_in_schema<C: SqlConnection>(
13151    conn: &C,
13152    table_name: &str,
13153    schema: Option<&str>,
13154) -> Result<String, IoError> {
13155    validate_sql_table_name(table_name)?;
13156    validate_sql_table_ref_identifier_lengths(conn, table_name, schema)?;
13157    let qualified = match schema {
13158        Some(s) if conn.supports_schemas() => {
13159            validate_sql_schema_name(s)?;
13160            format!(
13161                "{}.{}",
13162                conn.quote_identifier(s)?,
13163                conn.quote_identifier(table_name)?
13164            )
13165        }
13166        _ => conn.quote_identifier(table_name)?,
13167    };
13168    Ok(format!("DROP TABLE IF EXISTS {qualified}"))
13169}
13170
13171/// Read the result of a SQL query into a DataFrame.
13172///
13173/// Matches `pd.read_sql(sql, con)`.
13174pub fn read_sql<C: SqlConnection>(conn: &C, query: &str) -> Result<DataFrame, IoError> {
13175    read_sql_with_options(conn, query, &SqlReadOptions::default())
13176}
13177
13178/// Read the result of a SQL query into a DataFrame with read-time options.
13179///
13180/// Matches the supported subset of `pd.read_sql(sql, con, params=[...], parse_dates=...)`.
13181pub fn read_sql_with_options<C: SqlConnection>(
13182    conn: &C,
13183    query: &str,
13184    options: &SqlReadOptions,
13185) -> Result<DataFrame, IoError> {
13186    // Per br-frankenpandas-t1777: query readers take a raw SELECT written
13187    // by the caller, so options.columns has no effect. Silently ignoring
13188    // diverged from the table-reader sibling. Reject to surface the
13189    // mismatch — callers should embed the column list in the SELECT, or
13190    // use read_sql_table_with_options to generate the projection.
13191    if options.columns.is_some() {
13192        return Err(IoError::Sql(
13193            "options.columns is meaningful only for table readers; embed the column list in \
13194             the SELECT or use read_sql_table_with_options to generate the projection from a \
13195             table name"
13196                .to_owned(),
13197        ));
13198    }
13199    let (headers, columns, dtype_hints) = sql_query_to_columns(conn, query, options)?;
13200    let frame = dataframe_from_sql_columns(headers, columns, dtype_hints)?;
13201    apply_sql_index_col(frame, options.index_col.as_deref())
13202}
13203
13204/// Per br-frankenpandas-c1h9 (fd90.36): promote `options.index_col`
13205/// to the DataFrame index when set, with empty-string rejection.
13206fn apply_sql_index_col(frame: DataFrame, index_col: Option<&str>) -> Result<DataFrame, IoError> {
13207    let Some(name) = index_col else {
13208        return Ok(frame);
13209    };
13210    if name.is_empty() {
13211        return Err(IoError::Sql(
13212            "index_col: empty string is not a valid column name".to_owned(),
13213        ));
13214    }
13215    promote_column_to_index(&frame, name)
13216}
13217
13218/// Read the result of a SQL query into a DataFrame.
13219///
13220/// Matches `pd.read_sql_query(sql, con)`. This is the query-only spelling of
13221/// `read_sql`; table-name dispatch stays on `read_sql_table`.
13222pub fn read_sql_query<C: SqlConnection>(conn: &C, query: &str) -> Result<DataFrame, IoError> {
13223    read_sql(conn, query)
13224}
13225
13226/// Read the result of a SQL query into a DataFrame with read-time options.
13227///
13228/// Matches the supported subset of
13229/// `pd.read_sql_query(sql, con, params=[...], parse_dates=..., coerce_float=...)`.
13230pub fn read_sql_query_with_options<C: SqlConnection>(
13231    conn: &C,
13232    query: &str,
13233    options: &SqlReadOptions,
13234) -> Result<DataFrame, IoError> {
13235    read_sql_with_options(conn, query, options)
13236}
13237
13238/// Read a SQL query result with read-time options and optional index promotion.
13239///
13240/// Matches the supported subset of
13241/// `pd.read_sql_query(sql, con, params=[...], parse_dates=..., coerce_float=..., index_col=...)`.
13242pub fn read_sql_query_with_options_and_index_col<C: SqlConnection>(
13243    conn: &C,
13244    query: &str,
13245    options: &SqlReadOptions,
13246    index_col: Option<&str>,
13247) -> Result<DataFrame, IoError> {
13248    if let Some(col_name) = index_col {
13249        let cleared = SqlReadOptions {
13250            index_col: None,
13251            ..options.clone()
13252        };
13253        let frame = read_sql_query_with_options(conn, query, &cleared)?;
13254        return apply_sql_index_col(frame, Some(col_name));
13255    }
13256    read_sql_query_with_options(conn, query, options)
13257}
13258
13259/// Read the result of a SQL query as an iterator of DataFrame chunks.
13260///
13261/// Matches the supported subset of `pd.read_sql_query(sql, con, chunksize=...)`.
13262pub fn read_sql_query_chunks<'conn, C: SqlConnection + 'conn>(
13263    conn: &'conn C,
13264    query: &str,
13265    chunk_size: usize,
13266) -> Result<SqlChunkIterator<'conn>, IoError> {
13267    read_sql_chunks(conn, query, chunk_size)
13268}
13269
13270/// Read a SQL query result as chunks with one column promoted to each chunk's index.
13271///
13272/// Matches the supported subset of
13273/// `pd.read_sql_query(sql, con, index_col=..., chunksize=...)`.
13274pub fn read_sql_query_chunks_with_index_col<'conn, C: SqlConnection + 'conn>(
13275    conn: &'conn C,
13276    query: &str,
13277    index_col: Option<&str>,
13278    chunk_size: usize,
13279) -> Result<SqlIndexedChunkIterator<'conn>, IoError> {
13280    read_sql_chunks_with_index_col(conn, query, index_col, chunk_size)
13281}
13282
13283/// Read the result of a SQL query as chunks with read-time options.
13284///
13285/// Matches the supported subset of
13286/// `pd.read_sql_query(sql, con, params=[...], parse_dates=..., coerce_float=..., chunksize=...)`.
13287pub fn read_sql_query_chunks_with_options<'conn, C: SqlConnection + 'conn>(
13288    conn: &'conn C,
13289    query: &str,
13290    options: &SqlReadOptions,
13291    chunk_size: usize,
13292) -> Result<SqlChunkIterator<'conn>, IoError> {
13293    if options.index_col.is_some() {
13294        return Err(IoError::Sql(
13295            "options.index_col is set but this entrypoint returns SqlChunkIterator without \
13296             index promotion; use read_sql_query_chunks_with_options_and_index_col to honor \
13297             index_col"
13298                .to_owned(),
13299        ));
13300    }
13301    read_sql_chunks_with_options(conn, query, options, chunk_size)
13302}
13303
13304/// Read a SQL query result as chunks with read-time options and index promotion.
13305///
13306/// Matches the supported subset of
13307/// `pd.read_sql_query(sql, con, params=[...], parse_dates=..., coerce_float=..., index_col=..., chunksize=...)`.
13308pub fn read_sql_query_chunks_with_options_and_index_col<'conn, C: SqlConnection + 'conn>(
13309    conn: &'conn C,
13310    query: &str,
13311    options: &SqlReadOptions,
13312    index_col: Option<&str>,
13313    chunk_size: usize,
13314) -> Result<SqlIndexedChunkIterator<'conn>, IoError> {
13315    read_sql_chunks_with_options_and_index_col(conn, query, options, index_col, chunk_size)
13316}
13317
13318/// Read a SQL query result with one column promoted to the index.
13319///
13320/// Matches `pd.read_sql_query(sql, con, index_col=...)`.
13321pub fn read_sql_query_with_index_col<C: SqlConnection>(
13322    conn: &C,
13323    query: &str,
13324    index_col: Option<&str>,
13325) -> Result<DataFrame, IoError> {
13326    read_sql_with_index_col(conn, query, index_col)
13327}
13328
13329fn sql_trim_chunk_source(query: &str) -> Result<&str, IoError> {
13330    let trimmed = query.trim().trim_end_matches(';').trim();
13331    if trimmed.is_empty() {
13332        Err(IoError::Sql("read_sql query must be non-empty".to_owned()))
13333    } else {
13334        Ok(trimmed)
13335    }
13336}
13337
13338fn sql_paged_query<C: SqlConnection + ?Sized>(
13339    conn: &C,
13340    query: &str,
13341    base_param_count: usize,
13342) -> Result<String, IoError> {
13343    let source = sql_trim_chunk_source(query)?;
13344    let limit_marker = conn.parameter_marker(base_param_count + 1);
13345    let offset_marker = conn.parameter_marker(base_param_count + 2);
13346    Ok(format!(
13347        "SELECT * FROM ({source}) AS frankenpandas_sql_chunk_source \
13348         LIMIT {limit_marker} OFFSET {offset_marker}"
13349    ))
13350}
13351
13352fn sql_paged_options(
13353    options: &SqlReadOptions,
13354    limit: usize,
13355    offset: usize,
13356) -> Result<SqlReadOptions, IoError> {
13357    let limit = i64::try_from(limit)
13358        .map_err(|_| IoError::Sql("read_sql chunksize exceeds i64 range".to_owned()))?;
13359    let offset = i64::try_from(offset)
13360        .map_err(|_| IoError::Sql("read_sql chunk offset exceeds i64 range".to_owned()))?;
13361    let mut params = options.params.clone().unwrap_or_default();
13362    params.push(Scalar::Int64(limit));
13363    params.push(Scalar::Int64(offset));
13364    Ok(SqlReadOptions {
13365        params: Some(params),
13366        ..options.clone()
13367    })
13368}
13369
13370fn sql_paged_query_headers<C: SqlConnection + ?Sized>(
13371    conn: &C,
13372    query: &str,
13373    options: &SqlReadOptions,
13374) -> Result<Vec<String>, IoError> {
13375    let base_param_count = options.params.as_ref().map_or(0, Vec::len);
13376    let paged_query = sql_paged_query(conn, query, base_param_count)?;
13377    let paged_options = sql_paged_options(options, 0, 0)?;
13378    let result = conn.query(&paged_query, paged_options.params.as_deref().unwrap_or(&[]))?;
13379    reject_duplicate_headers(&result.columns)?;
13380    Ok(result.columns)
13381}
13382
13383fn sql_query_to_columns_paged<C: SqlConnection + ?Sized>(
13384    conn: &C,
13385    query: &str,
13386    options: &SqlReadOptions,
13387    chunk_size: usize,
13388    offset: usize,
13389) -> Result<SqlMaterializedColumns, IoError> {
13390    let base_param_count = options.params.as_ref().map_or(0, Vec::len);
13391    let paged_query = sql_paged_query(conn, query, base_param_count)?;
13392    let paged_options = sql_paged_options(options, chunk_size, offset)?;
13393    sql_query_to_columns(conn, &paged_query, &paged_options)
13394}
13395
13396fn sql_query_to_columns<C: SqlConnection + ?Sized>(
13397    conn: &C,
13398    query: &str,
13399    options: &SqlReadOptions,
13400) -> Result<SqlMaterializedColumns, IoError> {
13401    let params = options.params.as_deref().unwrap_or(&[]);
13402    let SqlQueryResult {
13403        columns: headers,
13404        rows,
13405    } = conn.query(query, params)?;
13406    reject_duplicate_headers(&headers)?;
13407    let mut dtype_hints = conn.query_column_dtypes(query, params)?;
13408    dtype_hints.resize(headers.len(), None);
13409    let mut columns: Vec<Vec<Scalar>> = (0..headers.len()).map(|_| Vec::new()).collect();
13410
13411    for row in rows {
13412        for (col_idx, value) in row.into_iter().enumerate() {
13413            if let Some(col_vec) = columns.get_mut(col_idx) {
13414                col_vec.push(value);
13415            }
13416        }
13417    }
13418
13419    if let Some(ref parse_dates) = options.parse_dates {
13420        apply_parse_dates_to_scalar_columns(&headers, &mut columns, parse_dates)?;
13421    }
13422    if options.coerce_float {
13423        apply_sql_coerce_float(&mut columns);
13424    }
13425    if let Some(ref dtype_map) = options.dtype {
13426        apply_sql_dtype_overrides(
13427            &headers,
13428            &mut columns,
13429            dtype_map,
13430            options.parse_dates.as_deref().unwrap_or(&[]),
13431        )?;
13432        for (idx, header) in headers.iter().enumerate() {
13433            if let Some(dtype) = dtype_map.get(header)
13434                && !options
13435                    .parse_dates
13436                    .as_deref()
13437                    .unwrap_or(&[])
13438                    .iter()
13439                    .any(|d| d == header)
13440            {
13441                dtype_hints[idx] = Some(dtype.clone());
13442            }
13443        }
13444    }
13445
13446    Ok((headers, columns, dtype_hints))
13447}
13448
13449/// Apply pandas-style `dtype={'col': dtype}` overrides to materialized
13450/// SQL result columns. Skips columns also listed in `parse_dates` to
13451/// avoid double-cast errors. Per br-frankenpandas-l9pt (fd90.11).
13452fn apply_sql_dtype_overrides(
13453    headers: &[String],
13454    columns: &mut [Vec<Scalar>],
13455    dtype_map: &BTreeMap<String, DType>,
13456    parse_dates: &[String],
13457) -> Result<(), IoError> {
13458    for (idx, header) in headers.iter().enumerate() {
13459        let Some(target_dtype) = dtype_map.get(header) else {
13460            continue;
13461        };
13462        if parse_dates.iter().any(|d| d == header) {
13463            // parse_dates wins; skip dtype override for this column.
13464            continue;
13465        }
13466        let Some(col) = columns.get_mut(idx) else {
13467            continue;
13468        };
13469        for value in col.iter_mut() {
13470            // Take ownership of the scalar, cast, and write back. NaT/Null
13471            // pass through cast_scalar_owned unchanged so missingness is
13472            // preserved across the override.
13473            let taken = std::mem::replace(value, Scalar::Null(NullKind::Null));
13474            *value = cast_scalar_owned(taken, target_dtype.clone()).map_err(|e| {
13475                IoError::Sql(format!(
13476                    "dtype override on column '{header}' to {target_dtype:?} failed: {e}"
13477                ))
13478            })?;
13479        }
13480    }
13481    Ok(())
13482}
13483
13484fn dataframe_from_sql_columns(
13485    headers: Vec<String>,
13486    columns: Vec<Vec<Scalar>>,
13487    dtype_hints: SqlColumnDtypeHints,
13488) -> Result<DataFrame, IoError> {
13489    let row_count = columns.first().map_or(0, Vec::len);
13490    let mut out_columns = BTreeMap::new();
13491    let mut column_order = Vec::new();
13492
13493    for (idx, (name, values)) in headers.into_iter().zip(columns).enumerate() {
13494        let dtype_hint = dtype_hints.get(idx).cloned().flatten();
13495        let has_observed_value = values.iter().any(|value| !matches!(value, Scalar::Null(_)));
13496        let column = match (has_observed_value, dtype_hint) {
13497            (false, Some(dtype)) => Column::new(dtype, values)?,
13498            _ => Column::from_values(values)?,
13499        };
13500        out_columns.insert(name.clone(), column);
13501        column_order.push(name);
13502    }
13503
13504    let index = Index::from_i64((0..row_count as i64).collect());
13505    Ok(DataFrame::new_with_column_order(
13506        index,
13507        out_columns,
13508        column_order,
13509    )?)
13510}
13511
13512/// Read a SQL query result as an iterator of DataFrame chunks.
13513///
13514/// Matches the supported subset of `pd.read_sql(sql, con, chunksize=...)`.
13515/// Each chunk receives a fresh zero-based RangeIndex, matching pandas'
13516/// SQLite chunk iterator behavior.
13517pub fn read_sql_chunks<'conn, C: SqlConnection + 'conn>(
13518    conn: &'conn C,
13519    query: &str,
13520    chunk_size: usize,
13521) -> Result<SqlChunkIterator<'conn>, IoError> {
13522    read_sql_chunks_with_options(conn, query, &SqlReadOptions::default(), chunk_size)
13523}
13524
13525/// Read a SQL query result as DataFrame chunks with read-time options.
13526///
13527/// Backends that opt into `supports_paged_sql_chunks` are queried one bounded
13528/// page at a time through a `LIMIT`/`OFFSET` wrapper so the iterator does not
13529/// hold the full result set in memory. Other backends keep the legacy
13530/// materialized fallback until they provide a native chunk strategy. `params`,
13531/// `parse_dates`, `coerce_float`, and `dtype` are applied to each yielded page.
13532pub fn read_sql_chunks_with_options<'conn, C: SqlConnection + 'conn>(
13533    conn: &'conn C,
13534    query: &str,
13535    options: &SqlReadOptions,
13536    chunk_size: usize,
13537) -> Result<SqlChunkIterator<'conn>, IoError> {
13538    if chunk_size == 0 {
13539        return Err(IoError::Sql(
13540            "read_sql chunksize must be greater than zero".to_owned(),
13541        ));
13542    }
13543    // Per br-frankenpandas-i8kja: this entrypoint returns SqlChunkIterator
13544    // with no index promotion. Honoring options.index_col would silently
13545    // diverge from the full-frame read_sql_with_options sibling (which
13546    // does promote). Reject to surface the mismatch — callers should use
13547    // read_sql_chunks_with_options_and_index_col when index_col is set.
13548    if options.index_col.is_some() {
13549        return Err(IoError::Sql(
13550            "options.index_col is set but this entrypoint returns SqlChunkIterator without \
13551             index promotion; use read_sql_chunks_with_options_and_index_col to honor index_col"
13552                .to_owned(),
13553        ));
13554    }
13555    // Per br-frankenpandas-t1777: query readers take a raw SELECT written
13556    // by the caller, so options.columns has no effect (the projection is
13557    // already in the query string). Silently ignoring would diverge from
13558    // the table-reader sibling (which honors columns to build the SELECT).
13559    // Reject to surface the mismatch — callers should embed the column
13560    // list in the SELECT, or use read_sql_table_chunks_with_options when
13561    // generating the SELECT from a table name.
13562    if options.columns.is_some() {
13563        return Err(IoError::Sql(
13564            "options.columns is meaningful only for table readers; embed the column list in \
13565             the SELECT or use read_sql_table_chunks_with_options to generate the projection \
13566             from a table name"
13567                .to_owned(),
13568        ));
13569    }
13570
13571    if conn.supports_paged_sql_chunks() {
13572        return SqlChunkIterator::paged(conn, query, options, chunk_size);
13573    }
13574
13575    let (headers, columns, dtype_hints) = sql_query_to_columns(conn, query, options)?;
13576    Ok(SqlChunkIterator::materialized(
13577        headers,
13578        columns,
13579        dtype_hints,
13580        chunk_size,
13581    ))
13582}
13583
13584/// Read a SQL query result as DataFrame chunks with read-time options and optional index promotion.
13585///
13586/// `params`, `parse_dates`, `coerce_float`, and `dtype` are applied to each
13587/// yielded page before optional index promotion.
13588pub fn read_sql_chunks_with_options_and_index_col<'conn, C: SqlConnection + 'conn>(
13589    conn: &'conn C,
13590    query: &str,
13591    options: &SqlReadOptions,
13592    index_col: Option<&str>,
13593    chunk_size: usize,
13594) -> Result<SqlIndexedChunkIterator<'conn>, IoError> {
13595    // Per br-frankenpandas-t1777: query readers can't apply options.columns
13596    // (caller writes the SELECT). Reject for consistency with the plain
13597    // chunk reader's rejection — the indexed sibling shouldn't be a
13598    // backdoor.
13599    if options.columns.is_some() {
13600        return Err(IoError::Sql(
13601            "options.columns is meaningful only for table readers; embed the column list in \
13602             the SELECT or use read_sql_table_chunks_with_options_and_index_col to generate \
13603             the projection from a table name"
13604                .to_owned(),
13605        ));
13606    }
13607    // The plain chunk reader rejects options.index_col (see i8kja); clear
13608    // it before delegating so the indexed sibling is the canonical
13609    // honor-index_col entrypoint regardless of which slot the caller used.
13610    let cleared = SqlReadOptions {
13611        index_col: None,
13612        ..options.clone()
13613    };
13614    let inner = read_sql_chunks_with_options(conn, query, &cleared, chunk_size)?;
13615    sql_indexed_chunks(inner, index_col.or(options.index_col.as_deref()))
13616}
13617
13618/// Read a SQL query result as DataFrame chunks with optional index promotion.
13619///
13620/// Matches the supported subset of `pd.read_sql(sql, con, index_col=..., chunksize=...)`.
13621pub fn read_sql_chunks_with_index_col<'conn, C: SqlConnection + 'conn>(
13622    conn: &'conn C,
13623    query: &str,
13624    index_col: Option<&str>,
13625    chunk_size: usize,
13626) -> Result<SqlIndexedChunkIterator<'conn>, IoError> {
13627    let inner = read_sql_chunks(conn, query, chunk_size)?;
13628    sql_indexed_chunks(inner, index_col)
13629}
13630
13631/// Read a SQL query result with one column promoted to the index.
13632///
13633/// Matches `pd.read_sql(sql, con, index_col=...)`. When
13634/// `index_col=Some(name)` the named column is removed from the data
13635/// columns and its values become the DataFrame's row index. Returns
13636/// `IoError::Sql` if the named column is absent from the result set.
13637pub fn read_sql_with_index_col<C: SqlConnection>(
13638    conn: &C,
13639    query: &str,
13640    index_col: Option<&str>,
13641) -> Result<DataFrame, IoError> {
13642    let frame = read_sql(conn, query)?;
13643    apply_sql_index_col(frame, index_col)
13644}
13645
13646/// Read an entire SQL table with one column promoted to the index.
13647///
13648/// Matches `pd.read_sql_table(table, con, index_col=...)`.
13649pub fn read_sql_table_with_index_col<C: SqlConnection>(
13650    conn: &C,
13651    table_name: &str,
13652    index_col: Option<&str>,
13653) -> Result<DataFrame, IoError> {
13654    let frame = read_sql_table(conn, table_name)?;
13655    apply_sql_index_col(frame, index_col)
13656}
13657
13658fn promote_column_to_index(frame: &DataFrame, col_name: &str) -> Result<DataFrame, IoError> {
13659    let column = frame.column(col_name).ok_or_else(|| {
13660        IoError::Sql(format!(
13661            "index_col {col_name:?} not present in result columns"
13662        ))
13663    })?;
13664    let labels: Vec<IndexLabel> = column
13665        .values()
13666        .iter()
13667        .map(|v| match v {
13668            Scalar::Int64(i) => IndexLabel::Int64(*i),
13669            Scalar::Utf8(s) => IndexLabel::Utf8(s.clone()),
13670            Scalar::Float64(f) if !f.is_nan() => IndexLabel::Utf8(f.to_string()),
13671            Scalar::Bool(b) => IndexLabel::Utf8(if *b { "True" } else { "False" }.to_string()),
13672            Scalar::Timedelta64(ns) => IndexLabel::Timedelta64(*ns),
13673            // A parse_dates column promoted to index becomes a DatetimeIndex
13674            // (typed Datetime64[ns], br-frankenpandas-0ezw7) — not a "NaN" string.
13675            Scalar::Datetime64(ns) => IndexLabel::Datetime64(*ns),
13676            _ => IndexLabel::Utf8("NaN".to_owned()),
13677        })
13678        .collect();
13679    let new_index = Index::new(labels).set_name(col_name);
13680
13681    let mut new_columns = std::collections::BTreeMap::new();
13682    let mut new_order = Vec::new();
13683    for name in frame.column_names() {
13684        if name == col_name {
13685            continue;
13686        }
13687        if let Some(col) = frame.column(name) {
13688            new_columns.insert(name.clone(), col.clone());
13689            new_order.push(name.clone());
13690        }
13691    }
13692
13693    Ok(DataFrame::new_with_column_order(
13694        new_index,
13695        new_columns,
13696        new_order,
13697    )?)
13698}
13699
13700/// Read an entire SQL table into a DataFrame.
13701///
13702/// Matches `pd.read_sql_table(table_name, con)`.
13703pub fn read_sql_table<C: SqlConnection>(conn: &C, table_name: &str) -> Result<DataFrame, IoError> {
13704    read_sql(conn, &sql_select_all_query(conn, table_name)?)
13705}
13706
13707/// List user-visible table names known to the SQL backend.
13708///
13709/// Matches the supported subset of
13710/// `pd.io.sql.SQLDatabase.list_tables(schema=...)`. When the backend
13711/// reports `supports_schemas() == false` (SQLite), `schema` is ignored
13712/// and all tables in the single namespace are returned. When the
13713/// backend supports schemas (PostgreSQL, MySQL, MSSQL), `Some(s)`
13714/// scopes the listing. `None` passes through to the backend
13715/// unchanged — backends MAY consult `default_schema()` for their own
13716/// fallback logic if desired (per fd90.57: this wrapper does NOT
13717/// apply the fallback automatically).
13718///
13719/// Per br-frankenpandas-vhq2 (fd90.20).
13720pub fn list_sql_tables<C: SqlConnection>(
13721    conn: &C,
13722    schema: Option<&str>,
13723) -> Result<Vec<String>, IoError> {
13724    conn.list_tables(schema)
13725}
13726
13727/// Introspect a SQL table's column metadata, optionally schema-scoped.
13728///
13729/// Matches the supported subset of
13730/// `pd.io.sql.SQLDatabase.has_table` + `SQLAlchemy.MetaData.reflect`
13731/// for column-level details. Returns `Ok(None)` when the table does
13732/// not exist. Schema arg is silently ignored when the backend reports
13733/// `supports_schemas() == false` (SQLite).
13734///
13735/// Per br-frankenpandas-w43q (fd90.21).
13736pub fn sql_table_schema<C: SqlConnection>(
13737    conn: &C,
13738    table_name: &str,
13739    schema: Option<&str>,
13740) -> Result<Option<SqlTableSchema>, IoError> {
13741    conn.table_schema(table_name, schema)
13742}
13743
13744/// List user-visible schemas exposed by the SQL backend.
13745///
13746/// Matches `SQLAlchemy.Inspector.get_schema_names()` shape. Single
13747/// namespace backends (SQLite) return an empty vector. Multi-schema
13748/// backends return the schemas the connection's role can see, with
13749/// internal/system schemas filtered out.
13750///
13751/// Per br-frankenpandas-lxhi (fd90.22).
13752pub fn list_sql_schemas<C: SqlConnection>(conn: &C) -> Result<Vec<String>, IoError> {
13753    conn.list_schemas()
13754}
13755
13756/// Reset a SQL table to empty without dropping its definition.
13757///
13758/// On backends that override the default (PostgreSQL, MySQL), this
13759/// uses `TRUNCATE TABLE` for a DDL-style fast-path reset. On backends
13760/// that inherit the default (SQLite), this emits `DELETE FROM <table>`,
13761/// which is universal but slower on large tables. Schema arg is
13762/// silently ignored when `supports_schemas() == false`.
13763///
13764/// Per br-frankenpandas-phum (fd90.23).
13765pub fn truncate_sql_table<C: SqlConnection>(
13766    conn: &C,
13767    table_name: &str,
13768    schema: Option<&str>,
13769) -> Result<(), IoError> {
13770    conn.truncate_table(table_name, schema)
13771}
13772
13773/// Probe the SQL backend's server version string.
13774///
13775/// Returns `Ok(None)` for backends that can't (or don't) introspect
13776/// their version. SQLite returns `Some("3.x.y")`. PostgreSQL/MySQL
13777/// impls return their respective `SHOW server_version` /
13778/// `SELECT VERSION()` payloads. Useful for dialect-version gating
13779/// (RETURNING, JSON ops, generated columns) and diagnostics.
13780///
13781/// Per br-frankenpandas-e23k (fd90.24).
13782pub fn sql_server_version<C: SqlConnection>(conn: &C) -> Result<Option<String>, IoError> {
13783    conn.server_version()
13784}
13785
13786/// Return the primary-key column names for a SQL table, ordered by
13787/// the table's primary-key ordinal.
13788///
13789/// Returns an empty vector when the table doesn't exist, has no
13790/// primary key, or the backend can't introspect column metadata.
13791/// Useful for upsert conflict-target generation and `index_label`
13792/// defaulting.
13793///
13794/// Per br-frankenpandas-uw3y (fd90.25).
13795pub fn sql_primary_key_columns<C: SqlConnection>(
13796    conn: &C,
13797    table_name: &str,
13798    schema: Option<&str>,
13799) -> Result<Vec<String>, IoError> {
13800    conn.primary_key_columns(table_name, schema)
13801}
13802
13803/// List user-defined indexes on a SQL table, optionally schema-scoped.
13804///
13805/// Matches `SQLAlchemy.Inspector.get_indexes()` shape. Returns an
13806/// empty vector when the table doesn't exist, has no user-created
13807/// indexes, or the backend can't introspect. Auto-created PRIMARY-KEY
13808/// indexes are filtered out (they're surfaced via primary_key_columns
13809/// instead).
13810///
13811/// Per br-frankenpandas-bgv9 (fd90.28).
13812pub fn list_sql_indexes<C: SqlConnection>(
13813    conn: &C,
13814    table_name: &str,
13815    schema: Option<&str>,
13816) -> Result<Vec<SqlIndexSchema>, IoError> {
13817    conn.list_indexes(table_name, schema)
13818}
13819
13820/// List user-visible view names known to the SQL backend.
13821///
13822/// Matches `SQLAlchemy.Inspector.get_view_names()` shape. Companion
13823/// to `list_sql_tables` — pandas/SQLAlchemy keep tables and views in
13824/// distinct buckets so `pd.read_sql_table` can distinguish them.
13825/// Schema arg is silently ignored when `supports_schemas() == false`.
13826///
13827/// Per br-frankenpandas-gm3r (fd90.30).
13828pub fn list_sql_views<C: SqlConnection>(
13829    conn: &C,
13830    schema: Option<&str>,
13831) -> Result<Vec<String>, IoError> {
13832    conn.list_views(schema)
13833}
13834
13835/// List foreign-key constraints declared on a SQL table, optionally
13836/// schema-scoped.
13837///
13838/// Matches `SQLAlchemy.Inspector.get_foreign_keys()` shape. Returns
13839/// an empty vector when the table has no FKs or the backend can't
13840/// introspect. Composite FKs are returned as a single entry with
13841/// paired `columns` / `referenced_columns` ordered by declaration
13842/// position. SQLite does not expose constraint names via PRAGMA, so
13843/// `constraint_name` is `None` there.
13844///
13845/// Per br-frankenpandas-uht8 (fd90.29).
13846pub fn list_sql_foreign_keys<C: SqlConnection>(
13847    conn: &C,
13848    table_name: &str,
13849    schema: Option<&str>,
13850) -> Result<Vec<SqlForeignKeySchema>, IoError> {
13851    conn.list_foreign_keys(table_name, schema)
13852}
13853
13854/// Probe the table-level comment for a SQL table, optionally
13855/// schema-scoped.
13856///
13857/// Matches `SQLAlchemy.Inspector.get_table_comment()` shape — returns
13858/// `Ok(Some(text))` when a comment exists, `Ok(None)` otherwise.
13859/// SQLite has no native table-comment storage and returns `None`.
13860/// PostgreSQL/MySQL/MSSQL impls override with their respective
13861/// catalog queries.
13862///
13863/// Per br-frankenpandas-yu3w (fd90.32).
13864pub fn sql_table_comment<C: SqlConnection>(
13865    conn: &C,
13866    table_name: &str,
13867    schema: Option<&str>,
13868) -> Result<Option<String>, IoError> {
13869    conn.table_comment(table_name, schema)
13870}
13871
13872/// List UNIQUE constraints declared on a SQL table.
13873///
13874/// Matches `SQLAlchemy.Inspector.get_unique_constraints()` shape.
13875/// Surfaces only inline `UNIQUE` declarations and `UNIQUE (...)`
13876/// table constraints. User-created `CREATE UNIQUE INDEX` indexes
13877/// remain in `list_sql_indexes` (with `unique == true`). The two
13878/// listings are intentionally disjoint to match SQLAlchemy.
13879///
13880/// Per br-frankenpandas-sh4v (fd90.31).
13881pub fn list_sql_unique_constraints<C: SqlConnection>(
13882    conn: &C,
13883    table_name: &str,
13884    schema: Option<&str>,
13885) -> Result<Vec<SqlUniqueConstraintSchema>, IoError> {
13886    conn.list_unique_constraints(table_name, schema)
13887}
13888
13889/// Maximum identifier length supported by the SQL backend, or `None`
13890/// when no documented limit exists.
13891///
13892/// Useful for to_sql validation: backends that override this report
13893/// their cap (PostgreSQL=63, MySQL=64, MSSQL=128) so auto-generated
13894/// index / constraint / column names can be truncated or rejected
13895/// before round-tripping through DDL that would silently truncate.
13896///
13897/// Per br-frankenpandas-cs81 (fd90.26).
13898pub fn sql_max_identifier_length<C: SqlConnection>(conn: &C) -> Option<usize> {
13899    conn.max_identifier_length()
13900}
13901
13902/// Backend capability summary exposed through `SqlInspector`.
13903///
13904/// The per-field values come from `SqlConnection` probes so concrete
13905/// backends can report their native ceilings without forcing callers to
13906/// branch on the connection type.
13907#[derive(Debug, Clone, PartialEq, Eq)]
13908pub struct SqlBackendCaps {
13909    pub dialect_name: &'static str,
13910    pub server_version: Option<String>,
13911    pub supports_returning: bool,
13912    pub supports_schemas: bool,
13913    pub max_param_count: Option<usize>,
13914    pub max_identifier_length: Option<usize>,
13915}
13916
13917impl SqlBackendCaps {
13918    /// Maximum rows in one parameter-bound INSERT for `column_count`.
13919    ///
13920    /// Returns `None` when the backend has no known parameter ceiling, or
13921    /// when `column_count` is zero and therefore no parameter-derived row
13922    /// ceiling can be computed.
13923    #[must_use]
13924    pub fn max_insert_rows(&self, column_count: usize) -> Option<usize> {
13925        sql_max_insert_rows_for_columns(self.max_param_count, column_count)
13926    }
13927}
13928
13929/// Maximum bound parameters supported by the SQL backend, if known.
13930#[must_use]
13931pub fn sql_max_param_count<C: SqlConnection>(conn: &C) -> Option<usize> {
13932    conn.max_param_count()
13933}
13934
13935/// Whether the SQL backend supports native `INSERT ... RETURNING`.
13936#[must_use]
13937pub fn sql_supports_returning<C: SqlConnection>(conn: &C) -> bool {
13938    conn.supports_returning()
13939}
13940
13941/// Whether the SQL backend exposes schema-qualified namespaces.
13942#[must_use]
13943pub fn sql_supports_schemas<C: SqlConnection>(conn: &C) -> bool {
13944    conn.supports_schemas()
13945}
13946
13947/// Maximum INSERT rows for `column_count`, derived from the backend's
13948/// bound-parameter ceiling.
13949///
13950/// A return value of `Some(0)` means the requested column count exceeds
13951/// the backend's total bind-parameter cap.
13952#[must_use]
13953pub fn sql_max_insert_rows<C: SqlConnection>(conn: &C, column_count: usize) -> Option<usize> {
13954    sql_max_insert_rows_for_columns(conn.max_param_count(), column_count)
13955}
13956
13957fn sql_max_insert_rows_for_columns(
13958    max_param_count: Option<usize>,
13959    column_count: usize,
13960) -> Option<usize> {
13961    if column_count == 0 {
13962        return None;
13963    }
13964    max_param_count.map(|max| max / column_count)
13965}
13966
13967/// Gather the backend capability probes into one typed bundle.
13968pub fn sql_backend_caps<C: SqlConnection>(conn: &C) -> Result<SqlBackendCaps, IoError> {
13969    Ok(SqlBackendCaps {
13970        dialect_name: conn.dialect_name(),
13971        server_version: conn.server_version()?,
13972        supports_returning: conn.supports_returning(),
13973        supports_schemas: conn.supports_schemas(),
13974        max_param_count: conn.max_param_count(),
13975        max_identifier_length: conn.max_identifier_length(),
13976    })
13977}
13978
13979/// Backend-agnostic introspection facade matching the
13980/// `SQLAlchemy.Inspector` shape.
13981///
13982/// Per br-frankenpandas-szs9 (fd90.38). Wraps a `&C: SqlConnection`
13983/// and exposes the full fd90.20-37 introspection surface as methods
13984/// on a single bundle so callers don't have to remember which
13985/// `list_sql_*` / `sql_*` free-fn to use. Pure delegation — no new
13986/// behavior, just API ergonomics.
13987///
13988/// ```rust,ignore
13989/// use frankenpandas::SqlInspector;
13990/// let inspector = SqlInspector::new(&conn);
13991/// for table in inspector.tables(None)? {
13992///     for col in inspector.columns(&table, None)?
13993///         .map(|s| s.columns)
13994///         .unwrap_or_default()
13995///     {
13996///         println!("{}: {:?}", col.name, col.declared_type);
13997///     }
13998/// }
13999/// ```
14000#[derive(Debug)]
14001pub struct SqlInspector<'a, C: SqlConnection> {
14002    conn: &'a C,
14003}
14004
14005impl<'a, C: SqlConnection> SqlInspector<'a, C> {
14006    /// Create a new inspector bound to the given connection.
14007    #[must_use]
14008    pub fn new(conn: &'a C) -> Self {
14009        Self { conn }
14010    }
14011
14012    /// List user-visible table names. See `list_sql_tables`.
14013    pub fn tables(&self, schema: Option<&str>) -> Result<Vec<String>, IoError> {
14014        self.conn.list_tables(schema)
14015    }
14016
14017    /// List user-visible view names. See `list_sql_views`.
14018    pub fn views(&self, schema: Option<&str>) -> Result<Vec<String>, IoError> {
14019        self.conn.list_views(schema)
14020    }
14021
14022    /// List user-visible schemas. See `list_sql_schemas`.
14023    pub fn schemas(&self) -> Result<Vec<String>, IoError> {
14024        self.conn.list_schemas()
14025    }
14026
14027    /// Introspect a table's columns. See `sql_table_schema`.
14028    pub fn columns(
14029        &self,
14030        table_name: &str,
14031        schema: Option<&str>,
14032    ) -> Result<Option<SqlTableSchema>, IoError> {
14033        self.conn.table_schema(table_name, schema)
14034    }
14035
14036    /// List user-defined indexes. See `list_sql_indexes`.
14037    pub fn indexes(
14038        &self,
14039        table_name: &str,
14040        schema: Option<&str>,
14041    ) -> Result<Vec<SqlIndexSchema>, IoError> {
14042        self.conn.list_indexes(table_name, schema)
14043    }
14044
14045    /// List foreign-key constraints. See `list_sql_foreign_keys`.
14046    pub fn foreign_keys(
14047        &self,
14048        table_name: &str,
14049        schema: Option<&str>,
14050    ) -> Result<Vec<SqlForeignKeySchema>, IoError> {
14051        self.conn.list_foreign_keys(table_name, schema)
14052    }
14053
14054    /// List UNIQUE constraints. See `list_sql_unique_constraints`.
14055    pub fn unique_constraints(
14056        &self,
14057        table_name: &str,
14058        schema: Option<&str>,
14059    ) -> Result<Vec<SqlUniqueConstraintSchema>, IoError> {
14060        self.conn.list_unique_constraints(table_name, schema)
14061    }
14062
14063    /// Return primary-key columns sorted by ordinal.
14064    /// See `sql_primary_key_columns`.
14065    pub fn primary_key_columns(
14066        &self,
14067        table_name: &str,
14068        schema: Option<&str>,
14069    ) -> Result<Vec<String>, IoError> {
14070        self.conn.primary_key_columns(table_name, schema)
14071    }
14072
14073    /// Probe the table-level comment. See `sql_table_comment`.
14074    pub fn table_comment(
14075        &self,
14076        table_name: &str,
14077        schema: Option<&str>,
14078    ) -> Result<Option<String>, IoError> {
14079        self.conn.table_comment(table_name, schema)
14080    }
14081
14082    /// Schema-aware existence check. Routes to
14083    /// `SqlConnection::table_exists_in_schema`.
14084    pub fn table_exists(&self, table_name: &str, schema: Option<&str>) -> Result<bool, IoError> {
14085        self.conn.table_exists_in_schema(table_name, schema)
14086    }
14087
14088    /// Probe the backend server version. See `sql_server_version`.
14089    pub fn server_version(&self) -> Result<Option<String>, IoError> {
14090        self.conn.server_version()
14091    }
14092
14093    /// Maximum identifier length, when the backend exposes one.
14094    /// See `sql_max_identifier_length`.
14095    #[must_use]
14096    pub fn max_identifier_length(&self) -> Option<usize> {
14097        self.conn.max_identifier_length()
14098    }
14099
14100    /// Maximum bound parameters supported by this backend, if known.
14101    #[must_use]
14102    pub fn max_param_count(&self) -> Option<usize> {
14103        self.conn.max_param_count()
14104    }
14105
14106    /// Maximum INSERT rows for `column_count`, derived from the backend's
14107    /// bound-parameter ceiling.
14108    #[must_use]
14109    pub fn max_insert_rows(&self, column_count: usize) -> Option<usize> {
14110        sql_max_insert_rows_for_columns(self.conn.max_param_count(), column_count)
14111    }
14112
14113    /// Whether this backend supports native `INSERT ... RETURNING`.
14114    #[must_use]
14115    pub fn supports_returning(&self) -> bool {
14116        self.conn.supports_returning()
14117    }
14118
14119    /// Whether this backend exposes schema-qualified namespaces.
14120    #[must_use]
14121    pub fn supports_schemas(&self) -> bool {
14122        self.conn.supports_schemas()
14123    }
14124
14125    /// Gather backend capability probes into one typed bundle.
14126    pub fn backend_caps(&self) -> Result<SqlBackendCaps, IoError> {
14127        sql_backend_caps(self.conn)
14128    }
14129
14130    /// Backend dialect name (`"sqlite"`, `"postgresql"`, etc.).
14131    #[must_use]
14132    pub fn dialect_name(&self) -> &'static str {
14133        self.conn.dialect_name()
14134    }
14135
14136    /// Check whether a specific column exists on a table.
14137    ///
14138    /// Per br-frankenpandas-ppry (fd90.39). Returns `Ok(false)` when
14139    /// the table doesn't exist (i.e. `columns` returns `None`), or
14140    /// when the table exists but has no column matching `column_name`.
14141    /// Returns `Ok(true)` only when the named column is present.
14142    /// Mirrors `SQLAlchemy.Inspector.has_column()` semantics.
14143    pub fn has_column(
14144        &self,
14145        table_name: &str,
14146        column_name: &str,
14147        schema: Option<&str>,
14148    ) -> Result<bool, IoError> {
14149        let Some(meta) = self.conn.table_schema(table_name, schema)? else {
14150            return Ok(false);
14151        };
14152        Ok(meta.column(column_name).is_some())
14153    }
14154
14155    /// Look up the metadata bundle for a single column.
14156    ///
14157    /// Per br-frankenpandas-ppry (fd90.39). Returns `Ok(None)` when the
14158    /// table doesn't exist or the column isn't present. The returned
14159    /// `SqlColumnSchema` carries the full set of fields populated by
14160    /// the underlying `table_schema` impl (declared_type, nullable,
14161    /// default_value, primary_key_ordinal, comment, autoincrement).
14162    pub fn column(
14163        &self,
14164        table_name: &str,
14165        column_name: &str,
14166        schema: Option<&str>,
14167    ) -> Result<Option<SqlColumnSchema>, IoError> {
14168        let Some(meta) = self.conn.table_schema(table_name, schema)? else {
14169            return Ok(None);
14170        };
14171        Ok(meta.column(column_name).cloned())
14172    }
14173
14174    /// Reflect a full table's metadata in one call: columns, primary
14175    /// key, indexes, foreign keys, unique constraints, and comment.
14176    ///
14177    /// Per br-frankenpandas-76mw (fd90.40). Mirrors
14178    /// `SQLAlchemy.MetaData.reflect_table` shape — gives callers a
14179    /// single bundle instead of 5 separate fetches. Returns `Ok(None)`
14180    /// when the table doesn't exist (matched via `table_schema`
14181    /// returning `None`); otherwise all derived calls run and any
14182    /// missing pieces (e.g. SQLite's always-None `table_comment`)
14183    /// are simply preserved as their natural empty values.
14184    ///
14185    /// Per br-frankenpandas-2kzv (fd90.43): primary-key columns are
14186    /// derived directly from the `SqlTableSchema` we already fetched
14187    /// rather than dispatching `primary_key_columns()` again — that
14188    /// trait method's default impl calls `table_schema()` internally,
14189    /// which would double the round-trip count for backends where
14190    /// each call is a real network hop.
14191    pub fn reflect_table(
14192        &self,
14193        table_name: &str,
14194        schema: Option<&str>,
14195    ) -> Result<Option<SqlReflectedTable>, IoError> {
14196        let Some(meta) = self.conn.table_schema(table_name, schema)? else {
14197            return Ok(None);
14198        };
14199        let primary_key_columns = primary_keys_from_schema(&meta);
14200        let indexes = self.conn.list_indexes(table_name, schema)?;
14201        let foreign_keys = self.conn.list_foreign_keys(table_name, schema)?;
14202        let unique_constraints = self.conn.list_unique_constraints(table_name, schema)?;
14203        let comment = self.conn.table_comment(table_name, schema)?;
14204        Ok(Some(SqlReflectedTable {
14205            table_name: meta.table_name,
14206            columns: meta.columns,
14207            primary_key_columns,
14208            indexes,
14209            foreign_keys,
14210            unique_constraints,
14211            comment,
14212        }))
14213    }
14214
14215    /// Reflect every user-visible table in `schema` into a vector of
14216    /// bundles, one per table.
14217    ///
14218    /// Per br-frankenpandas-jmmo (fd90.53). Iterates `tables(schema)`
14219    /// then calls `reflect_table` on each. Skips any table that
14220    /// `reflect_table` returns `Ok(None)` for — covers the race
14221    /// condition where a table existed at list time but not at
14222    /// reflect time (e.g. concurrent DROP). Useful for whole-database
14223    /// introspection in one call.
14224    pub fn reflect_all_tables(
14225        &self,
14226        schema: Option<&str>,
14227    ) -> Result<Vec<SqlReflectedTable>, IoError> {
14228        let table_names = self.conn.list_tables(schema)?;
14229        let mut bundles = Vec::with_capacity(table_names.len());
14230        for name in table_names {
14231            if let Some(bundle) = self.reflect_table(&name, schema)? {
14232                bundles.push(bundle);
14233            }
14234        }
14235        Ok(bundles)
14236    }
14237
14238    /// Reflect every user-visible view in `schema` into a vector of
14239    /// bundles, one per view.
14240    ///
14241    /// Per br-frankenpandas-zuqt (fd90.54). View-side parity with
14242    /// `reflect_all_tables`: iterates `views(schema)` then calls
14243    /// `reflect_table` on each (PRAGMA table_info works on views too,
14244    /// returning the view's column shape). PK/FK/UC/index lists in
14245    /// the bundle will typically be empty for views since views don't
14246    /// carry constraints — only the column metadata + comment are
14247    /// meaningful. Same disappearing-entity skip semantics as
14248    /// `reflect_all_tables`.
14249    pub fn reflect_all_views(
14250        &self,
14251        schema: Option<&str>,
14252    ) -> Result<Vec<SqlReflectedTable>, IoError> {
14253        let view_names = self.conn.list_views(schema)?;
14254        let mut bundles = Vec::with_capacity(view_names.len());
14255        for name in view_names {
14256            if let Some(bundle) = self.reflect_table(&name, schema)? {
14257                bundles.push(bundle);
14258            }
14259        }
14260        Ok(bundles)
14261    }
14262}
14263
14264/// Derive the primary-key column names from an already-fetched
14265/// `SqlTableSchema`, sorted ascending by `primary_key_ordinal`.
14266///
14267/// Per br-frankenpandas-2kzv (fd90.43) / fd90.47: this is the
14268/// canonical filter+sort impl shared by both
14269/// `SqlConnection::primary_key_columns` (the trait default) and
14270/// `SqlInspector::reflect_table` (which uses already-fetched
14271/// metadata to avoid a redundant `table_schema()` round-trip).
14272fn primary_keys_from_schema(meta: &SqlTableSchema) -> Vec<String> {
14273    let mut pk: Vec<(usize, String)> = meta
14274        .columns
14275        .iter()
14276        .filter_map(|c| c.primary_key_ordinal.map(|ord| (ord, c.name.clone())))
14277        .collect();
14278    pk.sort_by_key(|(ord, _)| *ord);
14279    pk.into_iter().map(|(_, name)| name).collect()
14280}
14281
14282/// Convenience constructor for `SqlInspector`.
14283///
14284/// `let inspector = inspect(&conn);` reads more naturally than
14285/// `SqlInspector::new(&conn)` for one-shot uses. Per br-frankenpandas-szs9 (fd90.38).
14286#[must_use]
14287pub fn inspect<C: SqlConnection>(conn: &C) -> SqlInspector<'_, C> {
14288    SqlInspector::new(conn)
14289}
14290
14291/// Read an entire SQL table into a DataFrame with read-time options.
14292///
14293/// Matches the supported subset of
14294/// `pd.read_sql_table(table_name, con, parse_dates=..., coerce_float=...)`.
14295pub fn read_sql_table_with_options<C: SqlConnection>(
14296    conn: &C,
14297    table_name: &str,
14298    options: &SqlReadOptions,
14299) -> Result<DataFrame, IoError> {
14300    let query =
14301        sql_table_read_query_for_options(conn, table_name, options, options.index_col.as_deref())?;
14302    // Per br-frankenpandas-t1777: the query reader rejects options.columns
14303    // (the SELECT is already projected here). Clear before delegating so
14304    // the table reader stays the canonical honor-columns entrypoint
14305    // regardless of which slot the caller used.
14306    let cleared = SqlReadOptions {
14307        columns: None,
14308        ..options.clone()
14309    };
14310    read_sql_with_options(conn, &query, &cleared)
14311}
14312
14313fn sql_table_read_query_for_options<C: SqlConnection>(
14314    conn: &C,
14315    table_name: &str,
14316    options: &SqlReadOptions,
14317    required_projection_col: Option<&str>,
14318) -> Result<String, IoError> {
14319    // Per br-frankenpandas-d3e9 (fd90.34): when options.columns is
14320    // Some(list), project only those columns instead of SELECT *.
14321    // Per br-frankenpandas-fd90.76: if an index_col will be promoted
14322    // after materialization, include it in the generated projection even
14323    // when the user did not list it in columns. pandas SQLTable.read does
14324    // this before set_index so columns=[...] and index_col=... compose.
14325    match options.columns.as_deref() {
14326        Some(cols) => {
14327            let mut refs: Vec<&str> = Vec::with_capacity(cols.len() + 1);
14328            if let Some(index_col) = required_projection_col
14329                && !cols.iter().any(|name| name == index_col)
14330            {
14331                refs.push(index_col);
14332            }
14333            refs.extend(cols.iter().map(String::as_str));
14334            sql_select_columns_query_in_schema(conn, table_name, options.schema.as_deref(), &refs)
14335        }
14336        None => sql_select_all_query_in_schema(conn, table_name, options.schema.as_deref()),
14337    }
14338}
14339
14340/// Read an entire SQL table with read-time options and optional index promotion.
14341///
14342/// Matches the supported subset of
14343/// `pd.read_sql_table(table_name, con, parse_dates=..., coerce_float=..., index_col=...)`.
14344pub fn read_sql_table_with_options_and_index_col<C: SqlConnection>(
14345    conn: &C,
14346    table_name: &str,
14347    options: &SqlReadOptions,
14348    index_col: Option<&str>,
14349) -> Result<DataFrame, IoError> {
14350    // Per br-frankenpandas-c1h9 (fd90.36): explicit `index_col` arg
14351    // always wins over `options.index_col`. Avoid double-promotion by
14352    // clearing the option-struct copy when the explicit arg is set.
14353    if let Some(col_name) = index_col {
14354        // Build the SELECT projection from the ORIGINAL options (so
14355        // options.columns is honored when present). Per br-frankenpandas-t1777,
14356        // also strip options.columns before passing to the query reader
14357        // (which now rejects the field; the SELECT already projects the
14358        // columns we wanted).
14359        let query = sql_table_read_query_for_options(conn, table_name, options, Some(col_name))?;
14360        let cleared = SqlReadOptions {
14361            index_col: None,
14362            columns: None,
14363            ..options.clone()
14364        };
14365        let frame = read_sql_with_options(conn, &query, &cleared)?;
14366        return apply_sql_index_col(frame, Some(col_name));
14367    }
14368    read_sql_table_with_options(conn, table_name, options)
14369}
14370
14371/// Read an entire SQL table as an iterator of DataFrame chunks.
14372///
14373/// Matches the supported subset of `pd.read_sql_table(table_name, con, chunksize=...)`.
14374pub fn read_sql_table_chunks<'conn, C: SqlConnection + 'conn>(
14375    conn: &'conn C,
14376    table_name: &str,
14377    chunk_size: usize,
14378) -> Result<SqlChunkIterator<'conn>, IoError> {
14379    read_sql_chunks(conn, &sql_select_all_query(conn, table_name)?, chunk_size)
14380}
14381
14382/// Read an entire SQL table as DataFrame chunks with read-time options.
14383///
14384/// Matches the supported subset of
14385/// `pd.read_sql_table(table_name, con, parse_dates=..., coerce_float=..., chunksize=...)`.
14386pub fn read_sql_table_chunks_with_options<'conn, C: SqlConnection + 'conn>(
14387    conn: &'conn C,
14388    table_name: &str,
14389    options: &SqlReadOptions,
14390    chunk_size: usize,
14391) -> Result<SqlChunkIterator<'conn>, IoError> {
14392    // Per br-frankenpandas-i8kja: this entrypoint returns the
14393    // un-indexed SqlChunkIterator. Honoring options.index_col would
14394    // silently diverge from the full-frame read_sql_table_with_options
14395    // sibling (which does promote). Reject to surface the mismatch —
14396    // callers should use read_sql_table_chunks_with_options_and_index_col
14397    // when index_col is set.
14398    if options.index_col.is_some() {
14399        return Err(IoError::Sql(
14400            "options.index_col is set but this entrypoint returns SqlChunkIterator without \
14401             index promotion; use read_sql_table_chunks_with_options_and_index_col to honor \
14402             index_col"
14403                .to_owned(),
14404        ));
14405    }
14406    let query = match options.columns.as_deref() {
14407        Some(cols) => {
14408            let refs: Vec<&str> = cols.iter().map(String::as_str).collect();
14409            sql_select_columns_query_in_schema(conn, table_name, options.schema.as_deref(), &refs)?
14410        }
14411        None => sql_select_all_query_in_schema(conn, table_name, options.schema.as_deref())?,
14412    };
14413    // Per br-frankenpandas-t1777: query reader rejects options.columns
14414    // (the SELECT is already projected here). Clear before delegating.
14415    let cleared = SqlReadOptions {
14416        columns: None,
14417        ..options.clone()
14418    };
14419    read_sql_chunks_with_options(conn, &query, &cleared, chunk_size)
14420}
14421
14422/// Read an entire SQL table as chunks with read-time options and optional index promotion.
14423///
14424/// Matches the supported subset of
14425/// `pd.read_sql_table(table_name, con, parse_dates=..., coerce_float=..., index_col=..., chunksize=...)`.
14426pub fn read_sql_table_chunks_with_options_and_index_col<'conn, C: SqlConnection + 'conn>(
14427    conn: &'conn C,
14428    table_name: &str,
14429    options: &SqlReadOptions,
14430    index_col: Option<&str>,
14431    chunk_size: usize,
14432) -> Result<SqlIndexedChunkIterator<'conn>, IoError> {
14433    let effective_index_col = index_col.or(options.index_col.as_deref());
14434    let query = sql_table_read_query_for_options(conn, table_name, options, effective_index_col)?;
14435    // The plain chunk reader rejects options.index_col (see i8kja) and
14436    // options.columns (see t1777); clear both before delegating so
14437    // chunked-with-options remains a sibling of the full-frame path
14438    // regardless of which slots the caller populated.
14439    let cleared = SqlReadOptions {
14440        index_col: None,
14441        columns: None,
14442        ..options.clone()
14443    };
14444    let inner = read_sql_chunks_with_options(conn, &query, &cleared, chunk_size)?;
14445    sql_indexed_chunks(inner, effective_index_col)
14446}
14447
14448/// Read an entire SQL table as chunks with one column promoted to each chunk's index.
14449///
14450/// Matches the supported subset of
14451/// `pd.read_sql_table(table_name, con, index_col=..., chunksize=...)`.
14452pub fn read_sql_table_chunks_with_index_col<'conn, C: SqlConnection + 'conn>(
14453    conn: &'conn C,
14454    table_name: &str,
14455    index_col: Option<&str>,
14456    chunk_size: usize,
14457) -> Result<SqlIndexedChunkIterator<'conn>, IoError> {
14458    let inner = read_sql_table_chunks(conn, table_name, chunk_size)?;
14459    sql_indexed_chunks(inner, index_col)
14460}
14461
14462/// Read a subset of columns from a SQL table.
14463///
14464/// Matches `pd.read_sql_table(table, con, columns=[...])`. The named
14465/// columns are emitted in the requested order. Each column name must
14466/// satisfy the same alphanumeric+underscore rule as `table_name` to
14467/// keep the projection injection-safe; mismatched names return
14468/// `IoError::Sql`. Empty `columns` is rejected (pandas raises in
14469/// the same case rather than producing an empty SELECT).
14470pub fn read_sql_table_columns<C: SqlConnection>(
14471    conn: &C,
14472    table_name: &str,
14473    columns: &[&str],
14474) -> Result<DataFrame, IoError> {
14475    read_sql(conn, &sql_select_columns_query(conn, table_name, columns)?)
14476}
14477
14478/// Read a subset of columns from a SQL table with optional index promotion.
14479///
14480/// Matches the supported subset of
14481/// `pd.read_sql_table(table, con, columns=[...], index_col=...)`. When
14482/// `index_col` is set and is not already in `columns`, it is auto-projected
14483/// into the underlying SELECT (matching pandas SQLTable.read which does the
14484/// same before set_index). The promoted column is removed from the data
14485/// columns after projection. Per br-frankenpandas-6n0uz.
14486pub fn read_sql_table_columns_with_index_col<C: SqlConnection>(
14487    conn: &C,
14488    table_name: &str,
14489    columns: &[&str],
14490    index_col: Option<&str>,
14491) -> Result<DataFrame, IoError> {
14492    let projection = projection_with_index_col(columns, index_col)?;
14493    let frame = read_sql_table_columns(conn, table_name, &projection)?;
14494    apply_sql_index_col(frame, index_col)
14495}
14496
14497/// Read a subset of columns from a SQL table as DataFrame chunks.
14498///
14499/// Matches the supported subset of
14500/// `pd.read_sql_table(table, con, columns=[...], chunksize=...)`. The named
14501/// columns are emitted in the requested order and each chunk receives a fresh
14502/// zero-based RangeIndex.
14503pub fn read_sql_table_columns_chunks<'conn, C: SqlConnection + 'conn>(
14504    conn: &'conn C,
14505    table_name: &str,
14506    columns: &[&str],
14507    chunk_size: usize,
14508) -> Result<SqlChunkIterator<'conn>, IoError> {
14509    read_sql_chunks(
14510        conn,
14511        &sql_select_columns_query(conn, table_name, columns)?,
14512        chunk_size,
14513    )
14514}
14515
14516/// Read a subset of columns from a SQL table as chunks with optional index promotion.
14517///
14518/// Matches the supported subset of
14519/// `pd.read_sql_table(table, con, columns=[...], index_col=..., chunksize=...)`.
14520/// When `index_col` is set and is not already in `columns`, it is auto-projected
14521/// into the underlying SELECT (matching pandas SQLTable.read). The promoted
14522/// column is removed from each chunk after projection. Per br-frankenpandas-6n0uz.
14523pub fn read_sql_table_columns_chunks_with_index_col<'conn, C: SqlConnection + 'conn>(
14524    conn: &'conn C,
14525    table_name: &str,
14526    columns: &[&str],
14527    index_col: Option<&str>,
14528    chunk_size: usize,
14529) -> Result<SqlIndexedChunkIterator<'conn>, IoError> {
14530    let projection = projection_with_index_col(columns, index_col)?;
14531    let inner = read_sql_table_columns_chunks(conn, table_name, &projection, chunk_size)?;
14532    sql_indexed_chunks(inner, index_col)
14533}
14534
14535/// Per br-frankenpandas-6n0uz: helper that prepends `index_col` to a
14536/// `columns` projection list if it isn't already present. Mirrors the
14537/// inline logic in `sql_table_read_query_for_options` (fd90.76) so the
14538/// columns-list and options-based read paths agree on the auto-include
14539/// rule while preserving the public `index_col=""` and empty-projection
14540/// error contracts.
14541fn projection_with_index_col<'a>(
14542    columns: &'a [&'a str],
14543    index_col: Option<&'a str>,
14544) -> Result<Vec<&'a str>, IoError> {
14545    match index_col {
14546        Some("") => Err(IoError::Sql(
14547            "index_col: empty string is not a valid column name".to_owned(),
14548        )),
14549        Some(name) if !columns.is_empty() && !columns.contains(&name) => {
14550            let mut out = Vec::with_capacity(columns.len() + 1);
14551            out.push(name);
14552            out.extend_from_slice(columns);
14553            Ok(out)
14554        }
14555        _ => Ok(columns.to_vec()),
14556    }
14557}
14558
14559/// Write a DataFrame to a SQL table.
14560///
14561/// Matches `pd.DataFrame.to_sql(name, con)`.
14562pub fn write_sql<C: SqlConnection>(
14563    frame: &DataFrame,
14564    conn: &C,
14565    table_name: &str,
14566    if_exists: SqlIfExists,
14567) -> Result<(), IoError> {
14568    write_sql_with_options(
14569        frame,
14570        conn,
14571        table_name,
14572        &SqlWriteOptions {
14573            if_exists,
14574            index: false,
14575            index_label: None,
14576            schema: None,
14577            dtype: None,
14578            method: SqlInsertMethod::Single,
14579            chunksize: None,
14580        },
14581    )
14582}
14583
14584/// Write a DataFrame to a SQLite table with pandas-style index options.
14585///
14586/// Matches the supported subset of
14587/// `pd.DataFrame.to_sql(name, con, index=..., index_label=...)`.
14588pub fn write_sql_with_options<C: SqlConnection>(
14589    frame: &DataFrame,
14590    conn: &C,
14591    table_name: &str,
14592    options: &SqlWriteOptions,
14593) -> Result<(), IoError> {
14594    // Validate table name to prevent SQL injection (only allow alphanumeric + underscore, non-empty).
14595    if table_name.is_empty() || !table_name.chars().all(|c| c.is_alphanumeric() || c == '_') {
14596        return Err(IoError::Sql(format!(
14597            "invalid table name: '{table_name}' (must be non-empty, only alphanumeric and underscore allowed)"
14598        )));
14599    }
14600
14601    let col_names: Vec<String> = frame.column_names().into_iter().cloned().collect();
14602    let index_label = resolve_sql_index_label(frame, options)?;
14603    let mut sql_col_names =
14604        Vec::with_capacity(col_names.len() + usize::from(index_label.is_some()));
14605    if let Some(ref label) = index_label {
14606        sql_col_names.push(label.clone());
14607    }
14608    sql_col_names.extend(col_names.iter().cloned());
14609
14610    // Per fd90.27: when the backend reports an identifier-length cap
14611    // (PG=63, MySQL=64, MSSQL=128), reject any identifier that exceeds
14612    // it before emitting DDL. SQLite (None) is unaffected.
14613    let max_ident = conn.max_identifier_length();
14614    validate_sql_identifier_length(table_name, max_ident, "table")?;
14615    if let Some(ref label) = index_label {
14616        validate_sql_identifier_length(label, max_ident, "index label")?;
14617    }
14618    for name in &col_names {
14619        validate_sql_identifier_length(name, max_ident, "column")?;
14620    }
14621    if let Some(s) = options.schema.as_deref() {
14622        validate_sql_identifier_length(s, max_ident, "schema")?;
14623    }
14624
14625    // Handle if_exists policy.
14626    let schema = options.schema.as_deref();
14627    match options.if_exists {
14628        SqlIfExists::Fail => {
14629            let exists = conn.table_exists_in_schema(table_name, schema)?;
14630            if exists {
14631                return Err(IoError::Sql(format!("table '{table_name}' already exists")));
14632            }
14633        }
14634        SqlIfExists::Replace => {
14635            let drop_sql = sql_drop_table_query_in_schema(conn, table_name, schema)?;
14636            conn.execute_batch(&drop_sql)?;
14637        }
14638        SqlIfExists::Append => {
14639            // Table may or may not exist; CREATE TABLE IF NOT EXISTS handles both.
14640        }
14641    }
14642
14643    // Build CREATE TABLE statement.
14644    let mut col_defs = Vec::with_capacity(sql_col_names.len());
14645    if let Some(ref label) = index_label {
14646        col_defs.push(sql_column_definition(
14647            conn,
14648            label,
14649            conn.index_dtype_sql(frame.index()),
14650        )?);
14651    }
14652    let dtype_overrides = options.dtype.as_ref();
14653    col_defs.extend(
14654        col_names
14655            .iter()
14656            .map(|name| {
14657                // Per br-frankenpandas-ev2s (fd90.18): explicit per-column
14658                // SQL-type override wins over the inferred conn.dtype_sql.
14659                let override_sql = dtype_overrides
14660                    .and_then(|m| m.get(name))
14661                    .map(|s| s.as_str());
14662                let sql_type = match override_sql {
14663                    Some(s) => s,
14664                    None => {
14665                        let dt = frame.column(name).map_or(DType::Utf8, |c| c.dtype());
14666                        conn.dtype_sql(dt)
14667                    }
14668                };
14669                sql_column_definition(conn, name, sql_type)
14670            })
14671            .collect::<Result<Vec<_>, IoError>>()?,
14672    );
14673
14674    let create_sql = sql_create_table_query_in_schema(conn, table_name, schema, &col_defs)?;
14675    conn.execute_batch(&create_sql)?;
14676
14677    let nrows = frame.index().len();
14678    let ncols = sql_col_names.len();
14679    let mut rows = Vec::with_capacity(nrows);
14680    for row_idx in 0..nrows {
14681        let mut row = Vec::with_capacity(ncols);
14682        if options.index {
14683            row.push(scalar_from_index_label(&frame.index().labels()[row_idx]));
14684        }
14685        row.extend(col_names.iter().map(|name| {
14686            frame
14687                .column(name)
14688                .and_then(|col| col.value(row_idx))
14689                .cloned()
14690                .unwrap_or(Scalar::Null(NullKind::Null))
14691        }));
14692        rows.push(row);
14693    }
14694
14695    if rows.is_empty() {
14696        // Empty frame: still emit CREATE TABLE (already done) but skip INSERT.
14697        return Ok(());
14698    }
14699
14700    // Per fd90.33: pandas-style chunksize. None preserves prior
14701    // single-transaction semantics; Some(0) is rejected (matches pandas).
14702    if let Some(0) = options.chunksize {
14703        return Err(IoError::Sql(
14704            "invalid chunksize: 0 (must be > 0 if Some)".to_owned(),
14705        ));
14706    }
14707
14708    match options.method {
14709        SqlInsertMethod::Single => {
14710            let insert_sql =
14711                sql_insert_rows_query_in_schema(conn, table_name, schema, &sql_col_names)?;
14712            match options.chunksize {
14713                None => {
14714                    conn.insert_rows(&insert_sql, &rows)?;
14715                }
14716                Some(n) => {
14717                    for chunk in rows.chunks(n) {
14718                        conn.insert_rows(&insert_sql, chunk)?;
14719                    }
14720                }
14721            }
14722        }
14723        SqlInsertMethod::Multi => {
14724            // Per fd90.19: chunk rows to fit `max_param_count`. When the
14725            // backend reports None, send the whole frame in one statement.
14726            // Per fd90.33: when chunksize is also Some(n), the effective
14727            // chunk row count is min(n, max_param_count / num_cols).
14728            let param_chunk = match conn.max_param_count() {
14729                Some(max) if ncols > 0 => {
14730                    let per_chunk = max / ncols;
14731                    if per_chunk == 0 {
14732                        return Err(IoError::Sql(format!(
14733                            "multi-row insert: ncols={ncols} exceeds backend max_param_count={max}"
14734                        )));
14735                    }
14736                    per_chunk
14737                }
14738                _ => rows.len(),
14739            };
14740            let chunk_rows = options
14741                .chunksize
14742                .map(|cs| cs.min(param_chunk))
14743                .unwrap_or(param_chunk);
14744            for chunk in rows.chunks(chunk_rows) {
14745                let chunk_sql = sql_multi_row_insert_query_in_schema(
14746                    conn,
14747                    table_name,
14748                    schema,
14749                    &sql_col_names,
14750                    chunk.len(),
14751                )?;
14752                let mut flat = Vec::with_capacity(chunk.len() * ncols);
14753                for row in chunk {
14754                    flat.extend(row.iter().cloned());
14755                }
14756                conn.insert_rows(&chunk_sql, &[flat])?;
14757            }
14758        }
14759    }
14760
14761    Ok(())
14762}
14763
14764// ── Extension trait for DataFrame IO convenience methods ─────────────
14765
14766/// Extension trait that adds IO convenience methods to `DataFrame`.
14767///
14768/// Import this trait to call `df.to_parquet(path)`, `df.to_orc(path)`,
14769/// `df.to_hdf(path)`, `df.to_parquet_bytes()`, etc. directly on DataFrame
14770/// values.
14771pub trait DataFrameIoExt {
14772    /// Write this DataFrame to a Parquet file.
14773    ///
14774    /// Matches `pd.DataFrame.to_parquet(path)`.
14775    fn to_parquet(&self, path: &Path) -> Result<(), IoError>;
14776
14777    /// Serialize this DataFrame to Parquet bytes in memory.
14778    ///
14779    /// Matches `pd.DataFrame.to_parquet()` with no path (returns bytes).
14780    fn to_parquet_bytes(&self) -> Result<Vec<u8>, IoError>;
14781
14782    /// Write this DataFrame to an ORC file.
14783    ///
14784    /// Matches the scoped `DataFrame.to_orc(path)` compatibility surface.
14785    fn to_orc(&self, path: &Path) -> Result<(), IoError>;
14786
14787    /// Write this DataFrame to an ORC file.
14788    ///
14789    /// Explicit file-suffixed form of [`DataFrameIoExt::to_orc`].
14790    fn to_orc_file(&self, path: &Path) -> Result<(), IoError>;
14791
14792    /// Serialize this DataFrame to ORC bytes in memory.
14793    fn to_orc_bytes(&self) -> Result<Vec<u8>, IoError>;
14794
14795    /// Write this DataFrame to an HDF5 file at the default key.
14796    ///
14797    /// Matches the scoped `DataFrame.to_hdf(path)` compatibility surface.
14798    fn to_hdf(&self, path: &Path) -> Result<(), IoError>;
14799
14800    /// Write this DataFrame to an HDF5 file at the default key.
14801    ///
14802    /// Explicit file-suffixed form of [`DataFrameIoExt::to_hdf`].
14803    fn to_hdf_file(&self, path: &Path) -> Result<(), IoError>;
14804
14805    /// Write this DataFrame to an HDF5 file at an explicit key.
14806    fn to_hdf_key(&self, path: &Path, key: &str) -> Result<(), IoError>;
14807
14808    /// Write this DataFrame to an HDF5 file with explicit options.
14809    fn to_hdf_with_options(&self, path: &Path, options: &HdfWriteOptions) -> Result<(), IoError>;
14810
14811    /// Write this DataFrame to a CSV file.
14812    ///
14813    /// Matches `pd.DataFrame.to_csv(path)`: the index is included by default.
14814    fn to_csv_file(&self, path: &Path) -> Result<(), IoError>;
14815
14816    /// Serialize this DataFrame to a CSV string.
14817    ///
14818    /// Matches `pd.DataFrame.to_csv()`: the index is included by default. Use
14819    /// [`Self::to_csv_string_with_options`] with `include_index: false` to emit
14820    /// pandas' `to_csv(index=False)` shape.
14821    fn to_csv_string(&self) -> Result<String, IoError>;
14822
14823    /// Serialize this DataFrame to a CSV string with explicit write options.
14824    ///
14825    /// Matches `pd.DataFrame.to_csv(sep, na_rep, header, index, index_label)`.
14826    fn to_csv_string_with_options(&self, options: &CsvWriteOptions) -> Result<String, IoError>;
14827
14828    /// Serialize this DataFrame to a Markdown table string.
14829    ///
14830    /// Matches `pd.DataFrame.to_markdown()` with no buffer.
14831    fn to_markdown_string(&self) -> Result<String, IoError>;
14832
14833    /// Serialize this DataFrame to a Markdown table string with explicit options.
14834    fn to_markdown_string_with_options(
14835        &self,
14836        options: &MarkdownWriteOptions,
14837    ) -> Result<String, IoError>;
14838
14839    /// Write this DataFrame to a Markdown table file.
14840    ///
14841    /// Uses a file-suffixed name to avoid colliding with
14842    /// `DataFrame::to_markdown(include_index, tablefmt)`.
14843    fn to_markdown_file(&self, path: &Path) -> Result<(), IoError>;
14844
14845    /// Write this DataFrame to a Markdown table file with explicit options.
14846    fn to_markdown_file_with_options(
14847        &self,
14848        path: &Path,
14849        options: &MarkdownWriteOptions,
14850    ) -> Result<(), IoError>;
14851
14852    /// Serialize this DataFrame to a LaTeX tabular string.
14853    ///
14854    /// Matches `pd.DataFrame.to_latex()` with no buffer.
14855    fn to_latex_string(&self) -> Result<String, IoError>;
14856
14857    /// Serialize this DataFrame to a LaTeX tabular string with explicit options.
14858    fn to_latex_string_with_options(&self, options: &LatexWriteOptions) -> Result<String, IoError>;
14859
14860    /// Write this DataFrame to a LaTeX tabular file.
14861    ///
14862    /// Uses a file-suffixed name to avoid colliding with
14863    /// `DataFrame::to_latex(include_index)`.
14864    fn to_latex_file(&self, path: &Path) -> Result<(), IoError>;
14865
14866    /// Write this DataFrame to a LaTeX tabular file with explicit options.
14867    fn to_latex_file_with_options(
14868        &self,
14869        path: &Path,
14870        options: &LatexWriteOptions,
14871    ) -> Result<(), IoError>;
14872
14873    /// Serialize this DataFrame to an HTML table string.
14874    ///
14875    /// Matches `pd.DataFrame.to_html()` with no buffer.
14876    fn to_html_string(&self) -> Result<String, IoError>;
14877
14878    /// Serialize this DataFrame to an HTML table string with explicit options.
14879    fn to_html_string_with_options(&self, options: &HtmlWriteOptions) -> Result<String, IoError>;
14880
14881    /// Write this DataFrame to an HTML file.
14882    ///
14883    /// Matches `pd.DataFrame.to_html(path)`.
14884    fn to_html_file(&self, path: &Path) -> Result<(), IoError>;
14885
14886    /// Write this DataFrame to an HTML file with explicit options.
14887    fn to_html_file_with_options(
14888        &self,
14889        path: &Path,
14890        options: &HtmlWriteOptions,
14891    ) -> Result<(), IoError>;
14892
14893    /// Serialize this DataFrame to an XML document string.
14894    ///
14895    /// Matches `pd.DataFrame.to_xml()` with no buffer for the writer-only subset.
14896    fn to_xml_string(&self) -> Result<String, IoError>;
14897
14898    /// Serialize this DataFrame to an XML document string with explicit options.
14899    fn to_xml_string_with_options(&self, options: &XmlWriteOptions) -> Result<String, IoError>;
14900
14901    /// Write this DataFrame to an XML file.
14902    ///
14903    /// Matches `pd.DataFrame.to_xml(path)`.
14904    fn to_xml(&self, path: &Path) -> Result<(), IoError>;
14905
14906    /// Write this DataFrame to an XML file.
14907    ///
14908    /// Matches `pd.DataFrame.to_xml(path)`.
14909    fn to_xml_file(&self, path: &Path) -> Result<(), IoError>;
14910
14911    /// Write this DataFrame to an XML file with explicit options.
14912    fn to_xml_file_with_options(
14913        &self,
14914        path: &Path,
14915        options: &XmlWriteOptions,
14916    ) -> Result<(), IoError>;
14917
14918    /// Write this DataFrame to a JSON file.
14919    ///
14920    /// Matches `pd.DataFrame.to_json(path)`.
14921    fn to_json_file(&self, path: &Path, orient: JsonOrient) -> Result<(), IoError>;
14922
14923    /// Serialize this DataFrame to a JSON string.
14924    ///
14925    /// Matches `pd.DataFrame.to_json()` with no path.
14926    fn to_json_string(&self, orient: JsonOrient) -> Result<String, IoError>;
14927
14928    /// Write this DataFrame to a Pickle file.
14929    ///
14930    /// Matches `pd.DataFrame.to_pickle(path)` for the supported envelope.
14931    fn to_pickle(&self, path: &Path) -> Result<(), IoError>;
14932
14933    /// Write this DataFrame to a Pickle file.
14934    ///
14935    /// Explicit file-suffixed form of [`DataFrameIoExt::to_pickle`].
14936    fn to_pickle_file(&self, path: &Path) -> Result<(), IoError>;
14937
14938    /// Write this DataFrame to a Pickle file with explicit options.
14939    fn to_pickle_with_options(
14940        &self,
14941        path: &Path,
14942        options: &PickleWriteOptions,
14943    ) -> Result<(), IoError>;
14944
14945    /// Serialize this DataFrame to Pickle bytes.
14946    fn to_pickle_bytes(&self) -> Result<Vec<u8>, IoError>;
14947
14948    /// Serialize this DataFrame to Pickle bytes with explicit options.
14949    fn to_pickle_bytes_with_options(
14950        &self,
14951        options: &PickleWriteOptions,
14952    ) -> Result<Vec<u8>, IoError>;
14953
14954    /// Write this DataFrame to a Stata DTA file.
14955    ///
14956    /// Matches `pd.DataFrame.to_stata(path)` for the supported subset.
14957    fn to_stata(&self, path: &Path) -> Result<(), IoError>;
14958
14959    /// Write this DataFrame to a Stata DTA file.
14960    ///
14961    /// Explicit file-suffixed form of [`DataFrameIoExt::to_stata`].
14962    fn to_stata_file(&self, path: &Path) -> Result<(), IoError>;
14963
14964    /// Write this DataFrame to a Stata DTA file with explicit options.
14965    fn to_stata_with_options(
14966        &self,
14967        path: &Path,
14968        options: &StataWriteOptions,
14969    ) -> Result<(), IoError>;
14970
14971    /// Serialize this DataFrame to Stata DTA bytes.
14972    fn to_stata_bytes(&self) -> Result<Vec<u8>, IoError>;
14973
14974    /// Serialize this DataFrame to Stata DTA bytes with explicit options.
14975    fn to_stata_bytes_with_options(&self, options: &StataWriteOptions) -> Result<Vec<u8>, IoError>;
14976
14977    /// Write this DataFrame to an Excel (.xlsx) file.
14978    ///
14979    /// Matches `pd.DataFrame.to_excel(path)`.
14980    fn to_excel(&self, path: &Path) -> Result<(), IoError>;
14981
14982    /// Write this DataFrame to an Excel (.xlsx) file.
14983    ///
14984    /// Explicit file-suffixed form of [`DataFrameIoExt::to_excel`].
14985    fn to_excel_file(&self, path: &Path) -> Result<(), IoError>;
14986
14987    /// Write this DataFrame to an Excel (.xlsx) file with explicit write options.
14988    fn to_excel_with_options(
14989        &self,
14990        path: &Path,
14991        options: &ExcelWriteOptions,
14992    ) -> Result<(), IoError>;
14993
14994    /// Serialize this DataFrame to Excel (.xlsx) bytes in memory.
14995    fn to_excel_bytes(&self) -> Result<Vec<u8>, IoError>;
14996
14997    /// Serialize this DataFrame to Excel (.xlsx) bytes with explicit write options.
14998    fn to_excel_bytes_with_options(&self, options: &ExcelWriteOptions) -> Result<Vec<u8>, IoError>;
14999
15000    /// Write this DataFrame to a JSONL file (one JSON object per line).
15001    ///
15002    /// Matches `pd.DataFrame.to_json(path, orient='records', lines=True)`.
15003    fn to_jsonl_file(&self, path: &Path) -> Result<(), IoError>;
15004
15005    /// Serialize this DataFrame to newline-delimited JSON.
15006    ///
15007    /// Matches `pd.DataFrame.to_json(orient='records', lines=True)`.
15008    fn to_jsonl_string(&self) -> Result<String, IoError>;
15009
15010    /// Write this DataFrame to an Arrow IPC (Feather v2) file.
15011    ///
15012    /// Matches `pd.DataFrame.to_feather(path)`.
15013    fn to_feather(&self, path: &Path) -> Result<(), IoError>;
15014
15015    /// Write this DataFrame to an Arrow IPC (Feather v2) file.
15016    ///
15017    /// Explicit file-suffixed form of [`DataFrameIoExt::to_feather`].
15018    fn to_feather_file(&self, path: &Path) -> Result<(), IoError>;
15019
15020    /// Serialize this DataFrame to Arrow IPC (Feather v2) bytes.
15021    fn to_feather_bytes(&self) -> Result<Vec<u8>, IoError>;
15022
15023    /// Write this DataFrame to a SQL table.
15024    ///
15025    /// Matches `pd.DataFrame.to_sql(name, con)`.
15026    fn to_sql<C: SqlConnection>(
15027        &self,
15028        conn: &C,
15029        table_name: &str,
15030        if_exists: SqlIfExists,
15031    ) -> Result<(), IoError>;
15032
15033    /// Write this DataFrame to a SQL table with pandas-style SQL write options.
15034    fn to_sql_with_options<C: SqlConnection>(
15035        &self,
15036        conn: &C,
15037        table_name: &str,
15038        options: &SqlWriteOptions,
15039    ) -> Result<(), IoError>;
15040
15041    /// Clipboard writer (TSV via an OS backend), matching `pd.DataFrame.to_clipboard()`.
15042    fn to_clipboard(&self) -> Result<(), IoError>;
15043
15044    /// Reject-closed BigQuery writer, matching `pd.DataFrame.to_gbq(destination_table, project_id)`.
15045    fn to_gbq(&self, destination_table: &str, project_id: Option<&str>) -> Result<(), IoError>;
15046}
15047
15048impl DataFrameIoExt for DataFrame {
15049    fn to_parquet(&self, path: &Path) -> Result<(), IoError> {
15050        write_parquet(self, path)
15051    }
15052
15053    fn to_parquet_bytes(&self) -> Result<Vec<u8>, IoError> {
15054        write_parquet_bytes(self)
15055    }
15056
15057    fn to_orc(&self, path: &Path) -> Result<(), IoError> {
15058        write_orc(self, path)
15059    }
15060
15061    fn to_orc_file(&self, path: &Path) -> Result<(), IoError> {
15062        self.to_orc(path)
15063    }
15064
15065    fn to_orc_bytes(&self) -> Result<Vec<u8>, IoError> {
15066        write_orc_bytes(self)
15067    }
15068
15069    fn to_hdf(&self, path: &Path) -> Result<(), IoError> {
15070        write_hdf(self, path)
15071    }
15072
15073    fn to_hdf_file(&self, path: &Path) -> Result<(), IoError> {
15074        self.to_hdf(path)
15075    }
15076
15077    fn to_hdf_key(&self, path: &Path, key: &str) -> Result<(), IoError> {
15078        write_hdf_key(self, path, key)
15079    }
15080
15081    fn to_hdf_with_options(&self, path: &Path, options: &HdfWriteOptions) -> Result<(), IoError> {
15082        write_hdf_with_options(self, path, options)
15083    }
15084
15085    fn to_csv_file(&self, path: &Path) -> Result<(), IoError> {
15086        std::fs::write(path, self.to_csv_string()?)?;
15087        Ok(())
15088    }
15089
15090    fn to_csv_string(&self) -> Result<String, IoError> {
15091        self.to_csv_string_with_options(&CsvWriteOptions {
15092            include_index: true,
15093            ..CsvWriteOptions::default()
15094        })
15095    }
15096
15097    fn to_csv_string_with_options(&self, options: &CsvWriteOptions) -> Result<String, IoError> {
15098        write_csv_string_with_options(self, options)
15099    }
15100
15101    fn to_markdown_string(&self) -> Result<String, IoError> {
15102        write_markdown_string(self)
15103    }
15104
15105    fn to_markdown_string_with_options(
15106        &self,
15107        options: &MarkdownWriteOptions,
15108    ) -> Result<String, IoError> {
15109        write_markdown_string_with_options(self, options)
15110    }
15111
15112    fn to_markdown_file(&self, path: &Path) -> Result<(), IoError> {
15113        write_markdown(self, path)
15114    }
15115
15116    fn to_markdown_file_with_options(
15117        &self,
15118        path: &Path,
15119        options: &MarkdownWriteOptions,
15120    ) -> Result<(), IoError> {
15121        write_markdown_with_options(self, path, options)
15122    }
15123
15124    fn to_latex_string(&self) -> Result<String, IoError> {
15125        write_latex_string(self)
15126    }
15127
15128    fn to_latex_string_with_options(&self, options: &LatexWriteOptions) -> Result<String, IoError> {
15129        write_latex_string_with_options(self, options)
15130    }
15131
15132    fn to_latex_file(&self, path: &Path) -> Result<(), IoError> {
15133        write_latex(self, path)
15134    }
15135
15136    fn to_latex_file_with_options(
15137        &self,
15138        path: &Path,
15139        options: &LatexWriteOptions,
15140    ) -> Result<(), IoError> {
15141        write_latex_with_options(self, path, options)
15142    }
15143
15144    fn to_html_string(&self) -> Result<String, IoError> {
15145        write_html_string(self)
15146    }
15147
15148    fn to_html_string_with_options(&self, options: &HtmlWriteOptions) -> Result<String, IoError> {
15149        write_html_string_with_options(self, options)
15150    }
15151
15152    fn to_html_file(&self, path: &Path) -> Result<(), IoError> {
15153        write_html(self, path)
15154    }
15155
15156    fn to_html_file_with_options(
15157        &self,
15158        path: &Path,
15159        options: &HtmlWriteOptions,
15160    ) -> Result<(), IoError> {
15161        write_html_with_options(self, path, options)
15162    }
15163
15164    fn to_xml_string(&self) -> Result<String, IoError> {
15165        write_xml_string(self)
15166    }
15167
15168    fn to_xml_string_with_options(&self, options: &XmlWriteOptions) -> Result<String, IoError> {
15169        write_xml_string_with_options(self, options)
15170    }
15171
15172    fn to_xml(&self, path: &Path) -> Result<(), IoError> {
15173        write_xml(self, path)
15174    }
15175
15176    fn to_xml_file(&self, path: &Path) -> Result<(), IoError> {
15177        self.to_xml(path)
15178    }
15179
15180    fn to_xml_file_with_options(
15181        &self,
15182        path: &Path,
15183        options: &XmlWriteOptions,
15184    ) -> Result<(), IoError> {
15185        write_xml_with_options(self, path, options)
15186    }
15187
15188    fn to_json_file(&self, path: &Path, orient: JsonOrient) -> Result<(), IoError> {
15189        write_json(self, path, orient)
15190    }
15191
15192    fn to_json_string(&self, orient: JsonOrient) -> Result<String, IoError> {
15193        write_json_string(self, orient)
15194    }
15195
15196    fn to_pickle(&self, path: &Path) -> Result<(), IoError> {
15197        write_pickle(self, path)
15198    }
15199
15200    fn to_pickle_file(&self, path: &Path) -> Result<(), IoError> {
15201        self.to_pickle(path)
15202    }
15203
15204    fn to_pickle_with_options(
15205        &self,
15206        path: &Path,
15207        options: &PickleWriteOptions,
15208    ) -> Result<(), IoError> {
15209        write_pickle_with_options(self, path, options)
15210    }
15211
15212    fn to_pickle_bytes(&self) -> Result<Vec<u8>, IoError> {
15213        write_pickle_bytes(self)
15214    }
15215
15216    fn to_pickle_bytes_with_options(
15217        &self,
15218        options: &PickleWriteOptions,
15219    ) -> Result<Vec<u8>, IoError> {
15220        write_pickle_bytes_with_options(self, options)
15221    }
15222
15223    fn to_stata(&self, path: &Path) -> Result<(), IoError> {
15224        write_stata(self, path)
15225    }
15226
15227    fn to_stata_file(&self, path: &Path) -> Result<(), IoError> {
15228        self.to_stata(path)
15229    }
15230
15231    fn to_stata_with_options(
15232        &self,
15233        path: &Path,
15234        options: &StataWriteOptions,
15235    ) -> Result<(), IoError> {
15236        write_stata_with_options(self, path, options)
15237    }
15238
15239    fn to_stata_bytes(&self) -> Result<Vec<u8>, IoError> {
15240        write_stata_bytes(self)
15241    }
15242
15243    fn to_stata_bytes_with_options(&self, options: &StataWriteOptions) -> Result<Vec<u8>, IoError> {
15244        write_stata_bytes_with_options(self, options)
15245    }
15246
15247    fn to_excel(&self, path: &Path) -> Result<(), IoError> {
15248        write_excel(self, path)
15249    }
15250
15251    fn to_excel_file(&self, path: &Path) -> Result<(), IoError> {
15252        self.to_excel(path)
15253    }
15254
15255    fn to_excel_with_options(
15256        &self,
15257        path: &Path,
15258        options: &ExcelWriteOptions,
15259    ) -> Result<(), IoError> {
15260        write_excel_with_options(self, path, options)
15261    }
15262
15263    fn to_excel_bytes(&self) -> Result<Vec<u8>, IoError> {
15264        write_excel_bytes(self)
15265    }
15266
15267    fn to_excel_bytes_with_options(&self, options: &ExcelWriteOptions) -> Result<Vec<u8>, IoError> {
15268        write_excel_bytes_with_options(self, options)
15269    }
15270
15271    fn to_jsonl_file(&self, path: &Path) -> Result<(), IoError> {
15272        write_jsonl(self, path)
15273    }
15274
15275    fn to_jsonl_string(&self) -> Result<String, IoError> {
15276        write_jsonl_string(self)
15277    }
15278
15279    fn to_feather(&self, path: &Path) -> Result<(), IoError> {
15280        write_feather(self, path)
15281    }
15282
15283    fn to_feather_file(&self, path: &Path) -> Result<(), IoError> {
15284        self.to_feather(path)
15285    }
15286
15287    fn to_feather_bytes(&self) -> Result<Vec<u8>, IoError> {
15288        write_feather_bytes(self)
15289    }
15290
15291    fn to_sql<C: SqlConnection>(
15292        &self,
15293        conn: &C,
15294        table_name: &str,
15295        if_exists: SqlIfExists,
15296    ) -> Result<(), IoError> {
15297        write_sql(self, conn, table_name, if_exists)
15298    }
15299
15300    fn to_sql_with_options<C: SqlConnection>(
15301        &self,
15302        conn: &C,
15303        table_name: &str,
15304        options: &SqlWriteOptions,
15305    ) -> Result<(), IoError> {
15306        write_sql_with_options(self, conn, table_name, options)
15307    }
15308
15309    fn to_clipboard(&self) -> Result<(), IoError> {
15310        clipboard_set(&clipboard_tsv(self)?)
15311    }
15312
15313    fn to_gbq(&self, _destination_table: &str, _project_id: Option<&str>) -> Result<(), IoError> {
15314        let _ = self;
15315        Err(deferred_writer_error(
15316            "to_gbq",
15317            "Google BigQuery integration is outside FrankenPandas's local file-format scope",
15318        ))
15319    }
15320}
15321
15322// ── Extension trait for Series IO convenience methods ─────────────────
15323
15324/// Extension trait that adds IO convenience methods to `Series`.
15325///
15326/// Import this trait to call `series.to_pickle(path)`,
15327/// `series.to_pickle_bytes()`, `series.to_hdf(path)`,
15328/// `series.to_csv_string()`, `series.to_markdown_string()`,
15329/// `series.to_latex_string()`, `series.to_json_string("records")`,
15330/// `series.to_hdf(path)`, `series.to_excel(path)`,
15331/// `series.to_sql(conn, table, if_exists)`, or `series.to_clipboard()`
15332/// directly on Series values.
15333pub trait SeriesIoExt {
15334    /// Write this Series to a Pickle file.
15335    ///
15336    /// Matches `pd.Series.to_pickle(path)` for the supported
15337    /// FrankenPandas pickle envelope.
15338    fn to_pickle(&self, path: &Path) -> Result<(), IoError>;
15339
15340    /// Write this Series to a Pickle file.
15341    ///
15342    /// Explicit file-suffixed form of [`SeriesIoExt::to_pickle`].
15343    fn to_pickle_file(&self, path: &Path) -> Result<(), IoError>;
15344
15345    /// Write this Series to a Pickle file with explicit options.
15346    fn to_pickle_with_options(
15347        &self,
15348        path: &Path,
15349        options: &PickleWriteOptions,
15350    ) -> Result<(), IoError>;
15351
15352    /// Serialize this Series to Pickle bytes.
15353    fn to_pickle_bytes(&self) -> Result<Vec<u8>, IoError>;
15354
15355    /// Serialize this Series to Pickle bytes with explicit options.
15356    fn to_pickle_bytes_with_options(
15357        &self,
15358        options: &PickleWriteOptions,
15359    ) -> Result<Vec<u8>, IoError>;
15360
15361    /// Write this Series to a CSV file.
15362    ///
15363    /// Matches `pd.Series.to_csv(path)` for the supported CSV writer surface,
15364    /// including pandas' default index materialization.
15365    fn to_csv_file(&self, path: &Path) -> Result<(), IoError>;
15366
15367    /// Write this Series to a CSV file with explicit write options.
15368    fn to_csv_file_with_options(
15369        &self,
15370        path: &Path,
15371        options: &CsvWriteOptions,
15372    ) -> Result<(), IoError>;
15373
15374    /// Serialize this Series to a CSV string.
15375    ///
15376    /// Matches `pd.Series.to_csv()` with no path for the supported writer
15377    /// surface.
15378    fn to_csv_string(&self) -> Result<String, IoError>;
15379
15380    /// Serialize this Series to a CSV string with explicit write options.
15381    fn to_csv_string_with_options(&self, options: &CsvWriteOptions) -> Result<String, IoError>;
15382
15383    /// Serialize this Series to a Markdown table string.
15384    ///
15385    /// Matches `pd.Series.to_markdown()` with no buffer for the supported
15386    /// table formatter surface.
15387    fn to_markdown_string(&self) -> Result<String, IoError>;
15388
15389    /// Serialize this Series to a Markdown table string with explicit options.
15390    fn to_markdown_string_with_options(
15391        &self,
15392        options: &MarkdownWriteOptions,
15393    ) -> Result<String, IoError>;
15394
15395    /// Write this Series to a Markdown table file.
15396    ///
15397    /// Uses a file-suffixed name to avoid colliding with
15398    /// `Series::to_markdown(include_index, tablefmt)`.
15399    fn to_markdown_file(&self, path: &Path) -> Result<(), IoError>;
15400
15401    /// Write this Series to a Markdown table file with explicit options.
15402    fn to_markdown_file_with_options(
15403        &self,
15404        path: &Path,
15405        options: &MarkdownWriteOptions,
15406    ) -> Result<(), IoError>;
15407
15408    /// Serialize this Series to a LaTeX tabular string.
15409    ///
15410    /// Matches `pd.Series.to_latex()` with no buffer for the supported table
15411    /// formatter surface.
15412    fn to_latex_string(&self) -> Result<String, IoError>;
15413
15414    /// Serialize this Series to a LaTeX tabular string with explicit options.
15415    fn to_latex_string_with_options(&self, options: &LatexWriteOptions) -> Result<String, IoError>;
15416
15417    /// Write this Series to a LaTeX tabular file.
15418    ///
15419    /// Uses a file-suffixed name to avoid colliding with
15420    /// `Series::to_latex(include_index)`.
15421    fn to_latex_file(&self, path: &Path) -> Result<(), IoError>;
15422
15423    /// Write this Series to a LaTeX tabular file with explicit options.
15424    fn to_latex_file_with_options(
15425        &self,
15426        path: &Path,
15427        options: &LatexWriteOptions,
15428    ) -> Result<(), IoError>;
15429
15430    /// Write this Series to a JSON file.
15431    ///
15432    /// Matches `pd.Series.to_json(path, orient=...)` for the supported Series
15433    /// JSON orientations.
15434    fn to_json_file(&self, path: &Path, orient: &str) -> Result<(), IoError>;
15435
15436    /// Serialize this Series to a JSON string.
15437    ///
15438    /// Matches `pd.Series.to_json(orient=...)` for the supported Series JSON
15439    /// orientations.
15440    fn to_json_string(&self, orient: &str) -> Result<String, IoError>;
15441
15442    /// Write this Series to an HDF5 file at the default key.
15443    ///
15444    /// Matches `pd.Series.to_hdf(path)` for the supported HDF5 snapshot
15445    /// surface.
15446    fn to_hdf(&self, path: &Path) -> Result<(), IoError>;
15447
15448    /// Write this Series to an HDF5 file at the default key.
15449    ///
15450    /// Explicit file-suffixed form of [`SeriesIoExt::to_hdf`].
15451    fn to_hdf_file(&self, path: &Path) -> Result<(), IoError>;
15452
15453    /// Write this Series to an HDF5 file at an explicit key.
15454    fn to_hdf_key(&self, path: &Path, key: &str) -> Result<(), IoError>;
15455
15456    /// Write this Series to an HDF5 file with explicit options.
15457    fn to_hdf_with_options(&self, path: &Path, options: &HdfWriteOptions) -> Result<(), IoError>;
15458
15459    /// Write this Series to an Excel file.
15460    ///
15461    /// Matches `pd.Series.to_excel(path)` for the supported xlsx writer
15462    /// surface.
15463    fn to_excel(&self, path: &Path) -> Result<(), IoError>;
15464
15465    /// Write this Series to an Excel file.
15466    ///
15467    /// Explicit file-suffixed form of [`SeriesIoExt::to_excel`].
15468    fn to_excel_file(&self, path: &Path) -> Result<(), IoError>;
15469
15470    /// Write this Series to an Excel file with explicit options.
15471    fn to_excel_with_options(
15472        &self,
15473        path: &Path,
15474        options: &ExcelWriteOptions,
15475    ) -> Result<(), IoError>;
15476
15477    /// Serialize this Series to xlsx bytes.
15478    fn to_excel_bytes(&self) -> Result<Vec<u8>, IoError>;
15479
15480    /// Serialize this Series to xlsx bytes with explicit options.
15481    fn to_excel_bytes_with_options(&self, options: &ExcelWriteOptions) -> Result<Vec<u8>, IoError>;
15482
15483    /// Write this Series to a SQL table.
15484    ///
15485    /// Matches `pd.Series.to_sql(name, con)` for the supported SQL writer
15486    /// surface, including pandas' default index materialization.
15487    fn to_sql<C: SqlConnection>(
15488        &self,
15489        conn: &C,
15490        table_name: &str,
15491        if_exists: SqlIfExists,
15492    ) -> Result<(), IoError>;
15493
15494    /// Write this Series to a SQL table with pandas-style SQL write options.
15495    fn to_sql_with_options<C: SqlConnection>(
15496        &self,
15497        conn: &C,
15498        table_name: &str,
15499        options: &SqlWriteOptions,
15500    ) -> Result<(), IoError>;
15501
15502    /// Clipboard writer (TSV via an OS backend), matching `pd.Series.to_clipboard()`.
15503    fn to_clipboard(&self) -> Result<(), IoError>;
15504}
15505
15506impl SeriesIoExt for Series {
15507    fn to_pickle(&self, path: &Path) -> Result<(), IoError> {
15508        write_pickle(&self.to_frame(None)?, path)
15509    }
15510
15511    fn to_pickle_file(&self, path: &Path) -> Result<(), IoError> {
15512        self.to_pickle(path)
15513    }
15514
15515    fn to_pickle_with_options(
15516        &self,
15517        path: &Path,
15518        options: &PickleWriteOptions,
15519    ) -> Result<(), IoError> {
15520        write_pickle_with_options(&self.to_frame(None)?, path, options)
15521    }
15522
15523    fn to_pickle_bytes(&self) -> Result<Vec<u8>, IoError> {
15524        write_pickle_bytes(&self.to_frame(None)?)
15525    }
15526
15527    fn to_pickle_bytes_with_options(
15528        &self,
15529        options: &PickleWriteOptions,
15530    ) -> Result<Vec<u8>, IoError> {
15531        write_pickle_bytes_with_options(&self.to_frame(None)?, options)
15532    }
15533
15534    fn to_csv_file(&self, path: &Path) -> Result<(), IoError> {
15535        self.to_csv_file_with_options(
15536            path,
15537            &CsvWriteOptions {
15538                include_index: true,
15539                ..CsvWriteOptions::default()
15540            },
15541        )
15542    }
15543
15544    fn to_csv_file_with_options(
15545        &self,
15546        path: &Path,
15547        options: &CsvWriteOptions,
15548    ) -> Result<(), IoError> {
15549        std::fs::write(path, self.to_csv_string_with_options(options)?)?;
15550        Ok(())
15551    }
15552
15553    fn to_csv_string(&self) -> Result<String, IoError> {
15554        self.to_csv_string_with_options(&CsvWriteOptions {
15555            include_index: true,
15556            ..CsvWriteOptions::default()
15557        })
15558    }
15559
15560    fn to_csv_string_with_options(&self, options: &CsvWriteOptions) -> Result<String, IoError> {
15561        write_csv_string_with_options(&self.to_frame(None)?, options)
15562    }
15563
15564    fn to_markdown_string(&self) -> Result<String, IoError> {
15565        self.to_markdown_string_with_options(&MarkdownWriteOptions::default())
15566    }
15567
15568    fn to_markdown_string_with_options(
15569        &self,
15570        options: &MarkdownWriteOptions,
15571    ) -> Result<String, IoError> {
15572        write_markdown_string_with_options(&self.to_frame(None)?, options)
15573    }
15574
15575    fn to_markdown_file(&self, path: &Path) -> Result<(), IoError> {
15576        self.to_markdown_file_with_options(path, &MarkdownWriteOptions::default())
15577    }
15578
15579    fn to_markdown_file_with_options(
15580        &self,
15581        path: &Path,
15582        options: &MarkdownWriteOptions,
15583    ) -> Result<(), IoError> {
15584        write_markdown_with_options(&self.to_frame(None)?, path, options)
15585    }
15586
15587    fn to_latex_string(&self) -> Result<String, IoError> {
15588        self.to_latex_string_with_options(&LatexWriteOptions::default())
15589    }
15590
15591    fn to_latex_string_with_options(&self, options: &LatexWriteOptions) -> Result<String, IoError> {
15592        write_latex_string_with_options(&self.to_frame(None)?, options)
15593    }
15594
15595    fn to_latex_file(&self, path: &Path) -> Result<(), IoError> {
15596        self.to_latex_file_with_options(path, &LatexWriteOptions::default())
15597    }
15598
15599    fn to_latex_file_with_options(
15600        &self,
15601        path: &Path,
15602        options: &LatexWriteOptions,
15603    ) -> Result<(), IoError> {
15604        write_latex_with_options(&self.to_frame(None)?, path, options)
15605    }
15606
15607    fn to_json_file(&self, path: &Path, orient: &str) -> Result<(), IoError> {
15608        std::fs::write(path, self.to_json_string(orient)?)?;
15609        Ok(())
15610    }
15611
15612    fn to_json_string(&self, orient: &str) -> Result<String, IoError> {
15613        Ok(Series::to_json(self, orient)?)
15614    }
15615
15616    fn to_hdf(&self, path: &Path) -> Result<(), IoError> {
15617        write_hdf(&self.to_frame(None)?, path)
15618    }
15619
15620    fn to_hdf_file(&self, path: &Path) -> Result<(), IoError> {
15621        self.to_hdf(path)
15622    }
15623
15624    fn to_hdf_key(&self, path: &Path, key: &str) -> Result<(), IoError> {
15625        write_hdf_key(&self.to_frame(None)?, path, key)
15626    }
15627
15628    fn to_hdf_with_options(&self, path: &Path, options: &HdfWriteOptions) -> Result<(), IoError> {
15629        write_hdf_with_options(&self.to_frame(None)?, path, options)
15630    }
15631
15632    fn to_excel(&self, path: &Path) -> Result<(), IoError> {
15633        write_excel(&self.to_frame(None)?, path)
15634    }
15635
15636    fn to_excel_file(&self, path: &Path) -> Result<(), IoError> {
15637        self.to_excel(path)
15638    }
15639
15640    fn to_excel_with_options(
15641        &self,
15642        path: &Path,
15643        options: &ExcelWriteOptions,
15644    ) -> Result<(), IoError> {
15645        write_excel_with_options(&self.to_frame(None)?, path, options)
15646    }
15647
15648    fn to_excel_bytes(&self) -> Result<Vec<u8>, IoError> {
15649        write_excel_bytes(&self.to_frame(None)?)
15650    }
15651
15652    fn to_excel_bytes_with_options(&self, options: &ExcelWriteOptions) -> Result<Vec<u8>, IoError> {
15653        write_excel_bytes_with_options(&self.to_frame(None)?, options)
15654    }
15655
15656    fn to_sql<C: SqlConnection>(
15657        &self,
15658        conn: &C,
15659        table_name: &str,
15660        if_exists: SqlIfExists,
15661    ) -> Result<(), IoError> {
15662        write_sql_with_options(
15663            &self.to_frame(None)?,
15664            conn,
15665            table_name,
15666            &SqlWriteOptions {
15667                if_exists,
15668                index: true,
15669                index_label: None,
15670                schema: None,
15671                dtype: None,
15672                method: SqlInsertMethod::Single,
15673                chunksize: None,
15674            },
15675        )
15676    }
15677
15678    fn to_sql_with_options<C: SqlConnection>(
15679        &self,
15680        conn: &C,
15681        table_name: &str,
15682        options: &SqlWriteOptions,
15683    ) -> Result<(), IoError> {
15684        write_sql_with_options(&self.to_frame(None)?, conn, table_name, options)
15685    }
15686
15687    fn to_clipboard(&self) -> Result<(), IoError> {
15688        clipboard_set(&clipboard_tsv(&self.to_frame(None)?)?)
15689    }
15690}
15691
15692#[cfg(test)]
15693mod tests {
15694    use std::{collections::BTreeMap, sync::Arc};
15695
15696    use arrow::{
15697        array::{Array, Int64Array},
15698        datatypes::DataType as ArrowDataType,
15699    };
15700    use fp_columnar::{Column, ValidityMask};
15701    use fp_frame::{DataFrame, Series};
15702    use fp_index::{Index, IndexLabel};
15703    use fp_types::{DType, NullKind, Scalar, Timestamp};
15704
15705    use super::{
15706        CsvWriteOptions, ExcelReadOptions, ExcelWriteOptions, Float64QuarterAffineCsvPlan,
15707        HtmlReadOptions, HtmlWriteOptions, IoError, JsonOrient, LatexWriteOptions,
15708        MarkdownWriteOptions, PickleProtocol, PickleWriteOptions, StataWriteOptions,
15709        XmlReadOptions, XmlWriteOptions, csv_input_has_unterminated_quote, format_pandas_float,
15710        read_csv_str, read_csv_with_index_cols, read_excel_bytes, read_feather_bytes, read_html,
15711        read_html_str, read_html_str_with_options, read_json_str, read_orc, read_orc_bytes,
15712        read_parquet_bytes, read_pickle, read_pickle_bytes, read_stata, read_stata_bytes, read_xml,
15713        read_xml_str, read_xml_str_with_options, write_csv_string, write_csv_string_with_options,
15714        write_excel_bytes, write_html, write_html_string, write_html_string_with_options,
15715        write_json_string, write_jsonl_string, write_latex, write_latex_string,
15716        write_latex_string_with_options, write_latex_with_options, write_markdown,
15717        write_markdown_string, write_markdown_string_with_options, write_markdown_with_options,
15718        write_orc, write_orc_bytes, write_pickle, write_pickle_bytes, write_stata,
15719        write_stata_bytes, write_stata_bytes_with_options, write_xml, write_xml_string,
15720        write_xml_string_with_options,
15721    };
15722    #[cfg(feature = "hdf5")]
15723    use super::{
15724        HdfReadOptions, HdfWriteOptions, read_hdf, read_hdf_key, read_hdf_with_options, write_hdf,
15725        write_hdf_key, write_hdf_with_options,
15726    };
15727
15728    fn assert_orc_disabled(err: IoError) {
15729        assert!(
15730            matches!(
15731                err,
15732                IoError::Orc(ref message)
15733                    if message.contains("Tokio-free native ORC backend")
15734            ),
15735            "expected ORC no-Tokio policy error, got {err:?}"
15736        );
15737    }
15738
15739    #[test]
15740    fn csv_quoting_round_trip_special_chars_1h8ar() {
15741        // RFC4180 escaping (br-frankenpandas-1h8ar): quoted fields parse to their
15742        // unescaped value, and write->read round-trips them (write must re-quote).
15743        // (csv_field_as_written, expected_parsed_value)
15744        let cases: [(&str, &str); 4] = [
15745            ("\"x,y\"", "x,y"),     // comma requires quoting
15746            ("\"a\"\"b\"", "a\"b"), // embedded quote -> doubled
15747            ("plain", "plain"),     // no quoting needed
15748            ("\" sp \"", " sp "),   // preserved leading/trailing spaces
15749        ];
15750        for (field, expected) in cases {
15751            let input = format!("col\n{field}\n");
15752            let f1 = read_csv_str(&input).expect("read1");
15753            assert_eq!(
15754                f1.column("col").expect("col").values()[0],
15755                Scalar::Utf8(expected.to_string()),
15756                "parse field={field:?}"
15757            );
15758            // write then re-read must preserve the value (correct re-quoting).
15759            let s2 = write_csv_string(&f1).expect("write");
15760            let f2 = read_csv_str(&s2).expect("read2");
15761            assert_eq!(
15762                f2.column("col").expect("col2").values()[0],
15763                Scalar::Utf8(expected.to_string()),
15764                "round-trip field={field:?} written={s2:?}"
15765            );
15766        }
15767    }
15768
15769    #[cfg(feature = "block-storage")]
15770    #[test]
15771    fn float_csv_uses_column_major_block_only_when_homogeneous_l6uyi() {
15772        // The block route is intentionally narrow: every parsed column must be
15773        // all-valid Float64. It preserves parser column order and f64 bits,
15774        // including signed zero, while an all-Int64 CSV must keep its eager
15775        // representation instead of silently changing dtype.
15776        let floats = read_csv_str("a,b\n1.5,-0.0\n2.25,4.0\n").expect("float CSV");
15777        let view = floats
15778            .to_numpy_block_view()
15779            .expect("homogeneous Float64 CSV is block-backed");
15780        assert_eq!((view.rows, view.cols), (2, 2));
15781        assert_eq!(view.block[0].to_bits(), 1.5_f64.to_bits());
15782        assert_eq!(view.block[1].to_bits(), 2.25_f64.to_bits());
15783        assert_eq!(view.block[2].to_bits(), (-0.0_f64).to_bits());
15784        assert_eq!(view.block[3].to_bits(), 4.0_f64.to_bits());
15785
15786        let (flat, rows, cols) = floats.to_numpy_flat();
15787        assert_eq!((rows, cols), (2, 2));
15788        assert_eq!(flat[0].to_bits(), 1.5_f64.to_bits());
15789        assert_eq!(flat[1].to_bits(), (-0.0_f64).to_bits());
15790        assert_eq!(flat[2].to_bits(), 2.25_f64.to_bits());
15791        assert_eq!(flat[3].to_bits(), 4.0_f64.to_bits());
15792
15793        let ints = read_csv_str("a,b\n1,2\n3,4\n").expect("integer CSV");
15794        assert!(
15795            ints.to_numpy_block_view().is_none(),
15796            "all-Int64 CSVs keep the existing eager typed representation"
15797        );
15798    }
15799
15800    #[test]
15801    fn csv_write_header_line_order_g9rxa() {
15802        // br-frankenpandas-g9rxa: write_csv_string's first line == column names in
15803        // column order joined by comma.
15804        let idx = vec![0_i64.into(), 1_i64.into()];
15805        let col = |name: &str, v: [i64; 2]| {
15806            Series::from_values(
15807                name,
15808                idx.clone(),
15809                vec![Scalar::Int64(v[0]), Scalar::Int64(v[1])],
15810            )
15811            .unwrap()
15812        };
15813        let df = DataFrame::from_series(vec![
15814            col("alpha", [1, 2]),
15815            col("beta", [3, 4]),
15816            col("gamma", [5, 6]),
15817        ])
15818        .unwrap();
15819        let csv = write_csv_string(&df).expect("write");
15820        let header = csv.lines().next().expect("header line");
15821        assert_eq!(header, "alpha,beta,gamma", "header order; csv={csv:?}");
15822    }
15823
15824    /// Bare DataFrame and Series CSV writers follow pandas' index default, while
15825    /// explicit options retain the index-less form.
15826    #[test]
15827    fn csv_index_default_matches_pandas_for_dataframe_and_series_sseeh() {
15828        use super::{DataFrameIoExt, SeriesIoExt};
15829
15830        let idx = vec![10_i64.into(), 11_i64.into()];
15831        let series = Series::from_values("a", idx, vec![Scalar::Int64(1), Scalar::Int64(2)])
15832            .expect("series");
15833        let frame = DataFrame::from_series(vec![series.clone()]).expect("frame");
15834
15835        let frame_csv = frame.to_csv_string().expect("dataframe csv");
15836        assert_eq!(
15837            frame_csv, ",a\n10,1\n11,2\n",
15838            "DataFrame.to_csv() must match pandas' index-including default"
15839        );
15840
15841        let series_csv = series.to_csv_string().expect("series csv");
15842        assert_eq!(series_csv, frame_csv, "sibling defaults must agree");
15843
15844        let indexless = frame
15845            .to_csv_string_with_options(&CsvWriteOptions {
15846                include_index: false,
15847                ..CsvWriteOptions::default()
15848            })
15849            .expect("explicit indexless dataframe csv");
15850        assert_eq!(
15851            indexless, "a\n1\n2\n",
15852            "explicit include_index=false must not inherit the pandas default"
15853        );
15854    }
15855
15856    // Deterministic n-row frame whose row `i` depends ONLY on `i`, using the typed
15857    // constructors so try_write_csv_typed's fast path applies. Exercises every
15858    // FastCol arm: an AFFINE Float64 (quarter_plan), a non-affine Float64 (ryu),
15859    // Int64, Bool, and contiguous Utf8 with embedded commas (QUOTE_MINIMAL).
15860    fn csv_bitident_frame_ironquail(n: usize) -> DataFrame {
15861        let idx = Index::from_range(0, n as i64, 1);
15862        let aff: Vec<f64> = (0..n).map(|i| i as f64).collect();
15863        let flt: Vec<f64> = (0..n)
15864            .map(|i| {
15865                ((i as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15) >> 11) as f64 / (1u64 << 53) as f64
15866                    * 1e6
15867            })
15868            .collect();
15869        let int: Vec<i64> = (0..n as i64).collect();
15870        let boo: Vec<bool> = (0..n).map(|i| i % 3 == 0).collect();
15871        let mut sbytes: Vec<u8> = Vec::new();
15872        let mut soff: Vec<usize> = vec![0];
15873        for i in 0..n {
15874            let s = if i % 7 == 0 {
15875                format!("a,b{i}")
15876            } else {
15877                format!("x{i}")
15878            };
15879            sbytes.extend_from_slice(s.as_bytes());
15880            soff.push(sbytes.len());
15881        }
15882        let mut cols = BTreeMap::new();
15883        cols.insert("aff".to_string(), Column::from_f64_values(aff));
15884        cols.insert("flt".to_string(), Column::from_f64_values(flt));
15885        cols.insert("int".to_string(), Column::from_i64_values(int));
15886        cols.insert("boo".to_string(), Column::from_bool_values(boo));
15887        cols.insert(
15888            "str".to_string(),
15889            Column::from_utf8_contiguous(sbytes, soff),
15890        );
15891        DataFrame::new_with_column_order(
15892            idx,
15893            cols,
15894            vec![
15895                "aff".to_string(),
15896                "flt".to_string(),
15897                "int".to_string(),
15898                "boo".to_string(),
15899                "str".to_string(),
15900            ],
15901        )
15902        .unwrap()
15903    }
15904
15905    #[test]
15906    fn csv_parallel_path_matches_serial_prefix_ironquail() {
15907        // The 49k frame writes via the SERIAL path (< CSV_PAR_MIN_ROWS); the 51k frame
15908        // writes via the CHUNKED-PARALLEL path (>= CSV_PAR_MIN_ROWS). Row `i` depends
15909        // only on `i`, so rows 0..49000 are identical between the frames — hence the
15910        // 51k CSV must have the 49k CSV as a BYTE-EXACT prefix, proving the parallel
15911        // writer is byte-identical to the serial writer across chunk boundaries.
15912        let small = csv_bitident_frame_ironquail(49_000);
15913        let large = csv_bitident_frame_ironquail(51_000);
15914        let csv_small = write_csv_string(&small).expect("serial write");
15915        let csv_large = write_csv_string(&large).expect("parallel write");
15916        assert!(csv_large.len() > csv_small.len(), "large must be longer");
15917        assert!(
15918            csv_large.as_bytes().starts_with(csv_small.as_bytes()),
15919            "parallel CSV diverges from serial on the shared 0..49000 rows"
15920        );
15921    }
15922
15923    #[test]
15924    fn json_read_parallel_matches_serial_ironquail() {
15925        // 60k >= PAR_MIN_RECORDS so records read via the PARALLEL boundary-split path;
15926        // compare it directly to the SERIAL flat scanner on the same input. The Utf8
15927        // column carries embedded commas, so this also exercises the string-aware
15928        // boundary scan (a comma inside a string must NOT be a record boundary).
15929        let frame = csv_bitident_frame_ironquail(60_000);
15930        let json = write_json_string(&frame, JsonOrient::Records).expect("write records json");
15931        let par = super::try_read_json_records_flat_parallel(&json)
15932            .expect("parallel ok")
15933            .expect("parallel took its path (>=50k homogeneous)");
15934        let ser = super::try_read_json_records_flat(&json)
15935            .expect("serial ok")
15936            .expect("serial took its path");
15937        assert_eq!(par.len(), 60_000);
15938        assert!(
15939            par.equals(&ser),
15940            "parallel json read diverges from the serial flat scanner"
15941        );
15942    }
15943
15944    #[test]
15945    fn json_read_numeric_parallel_typed_builders_match_scalar_reference_92n1x() {
15946        // 60k rows crosses the typed parser's parallel admission boundary. The
15947        // Float64 column starts with integral-looking data and later has decimal
15948        // tokens, exercising the Int64→Float64 builder promotion without ever
15949        // materializing one Scalar per input cell.
15950        let mut json = String::with_capacity(1_600_000);
15951        json.push('[');
15952        for row in 0..60_000_i64 {
15953            if row > 0 {
15954                json.push(',');
15955            }
15956            json.push_str(&format!(
15957                r#"{{"i":{row},"f":{}}}"#,
15958                if row < 20_000 {
15959                    row.to_string()
15960                } else {
15961                    format!("{row}.5")
15962                }
15963            ));
15964        }
15965        json.push(']');
15966
15967        let typed = super::try_read_json_records_numeric_parallel(&json)
15968            .expect("typed parse result")
15969            .expect("homogeneous numeric input takes typed path");
15970        let scalar = super::try_read_json_records_flat_parallel(&json)
15971            .expect("scalar parse result")
15972            .expect("homogeneous input takes scalar parallel path");
15973        assert_eq!(typed.len(), 60_000);
15974        assert!(
15975            typed.equals(&scalar),
15976            "typed parser must preserve every value"
15977        );
15978        assert_eq!(typed.column("i").expect("i").dtype(), DType::Int64);
15979        assert_eq!(typed.column("f").expect("f").dtype(), DType::Float64);
15980    }
15981
15982    #[test]
15983    fn json_read_numeric_simd_boundaries_are_parser_validated_92n1x() {
15984        let compact = br#"[{"a":1},{"a":2}]"#;
15985        let (body_start, body_end, commas) =
15986            super::scan_json_numeric_record_boundaries(compact).expect("compact records");
15987        assert_eq!(&compact[body_start..body_end], br#"{"a":1},{"a":2}"#);
15988        assert_eq!(commas.len(), 1);
15989        assert_eq!(compact[commas[0]], b',');
15990        assert!(
15991            super::parse_json_records_numeric_range(compact, body_start, commas[0]).is_some(),
15992            "the first SIMD-delimited range is a complete numeric record"
15993        );
15994
15995        // A legal unescaped key can itself contain `},{`. The substring scan may
15996        // see that byte sequence, but range parsing must reject the false split so
15997        // `try_read_json_records_numeric_parallel` falls back instead of assigning
15998        // fields to the wrong row.
15999        let false_separator = br#"[{"},{":1},{"a":2}]"#;
16000        let (body_start, _body_end, commas) =
16001            super::scan_json_numeric_record_boundaries(false_separator)
16002                .expect("outer records array");
16003        assert!(
16004            super::parse_json_records_numeric_range(false_separator, body_start, commas[0])
16005                .is_none(),
16006            "a key-contained separator is never admitted as a typed record boundary"
16007        );
16008    }
16009
16010    #[test]
16011    fn json_read_numeric_typed_builder_rejects_key_reordering_92n1x() {
16012        // A position-only numeric parser would quietly exchange these values.
16013        // Admission must reject the shape so the general records parser retains
16014        // its first-seen-key semantics.
16015        let input = br#"{"a":1,"b":2.5},{"b":3.5,"a":4}"#;
16016        assert!(
16017            super::parse_json_records_numeric_range(input, 0, input.len()).is_none(),
16018            "key reordering must defer instead of assigning by position"
16019        );
16020    }
16021
16022    #[test]
16023    fn json_read_numeric_typed_builder_accepts_only_json_number_grammar_92n1x() {
16024        for (token, expected) in [
16025            (b"0".as_slice(), super::JsonRecordNumber::Int(0)),
16026            (b"-17".as_slice(), super::JsonRecordNumber::Int(-17)),
16027            (b"1.25".as_slice(), super::JsonRecordNumber::Float(1.25)),
16028            (b"6e-4".as_slice(), super::JsonRecordNumber::Float(0.0006)),
16029            (
16030                b"9223372036854775808".as_slice(),
16031                super::JsonRecordNumber::Float(9.223_372_036_854_776e18),
16032            ),
16033        ] {
16034            let actual = super::parse_json_record_number(token).expect("valid JSON number");
16035            let serde = serde_json::from_slice::<serde_json::Number>(token)
16036                .expect("serde accepts valid JSON number");
16037            match (actual, expected) {
16038                (super::JsonRecordNumber::Int(actual), super::JsonRecordNumber::Int(expected)) => {
16039                    assert_eq!(actual, expected, "token={token:?}");
16040                    assert_eq!(serde.as_i64(), Some(actual), "token={token:?}");
16041                }
16042                (
16043                    super::JsonRecordNumber::Float(actual),
16044                    super::JsonRecordNumber::Float(expected),
16045                ) => {
16046                    assert_eq!(actual.to_bits(), expected.to_bits(), "token={token:?}");
16047                    assert_eq!(
16048                        serde.as_f64().expect("serde float conversion").to_bits(),
16049                        actual.to_bits(),
16050                        "token={token:?}"
16051                    );
16052                }
16053                (actual, expected) => {
16054                    panic!("token={token:?}: got {actual:?}, expected {expected:?}")
16055                }
16056            }
16057        }
16058
16059        for invalid in [b"01".as_slice(), b"-", b"1.", b"1e", b"+1", b"1+2"] {
16060            assert!(
16061                super::parse_json_record_number(invalid).is_none(),
16062                "invalid JSON number {invalid:?} must defer"
16063            );
16064        }
16065    }
16066
16067    #[test]
16068    fn json_read_numeric_typed_builder_rejects_mixed_dtype_92n1x() {
16069        // The typed numeric path must not turn a bool-bearing column into a
16070        // numeric one merely because a neighbouring column is numeric. It must
16071        // defer to the scalar parser, which retains the Bool column.
16072        let input = br#"{"n":1,"flag":true},{"n":2,"flag":false}"#;
16073        assert!(
16074            super::parse_json_records_numeric_range(input, 0, input.len()).is_none(),
16075            "mixed numeric/bool records must bypass the typed numeric builder"
16076        );
16077        let frame = read_json_str(
16078            r#"[{"n":1,"flag":true},{"n":2,"flag":false}]"#,
16079            JsonOrient::Records,
16080        )
16081        .expect("scalar fallback parses mixed records");
16082        assert_eq!(frame.column("n").expect("n").dtype(), DType::Int64);
16083        assert_eq!(frame.column("flag").expect("flag").dtype(), DType::Bool);
16084    }
16085
16086    #[test]
16087    fn csv_per_column_dtype_inference_me2x3() {
16088        // br-frankenpandas-me2x3: read_csv infers Int64 for all-int, Float64 for a
16089        // column containing a decimal, Utf8 for text.
16090        let df = read_csv_str("a,b,c\n1,1.5,x\n2,2.5,y\n3,3.5,z\n").expect("read");
16091        assert_eq!(
16092            df.column("a").expect("a").dtype(),
16093            DType::Int64,
16094            "all-int -> Int64"
16095        );
16096        assert_eq!(
16097            df.column("b").expect("b").dtype(),
16098            DType::Float64,
16099            "decimal -> Float64"
16100        );
16101        assert_eq!(
16102            df.column("c").expect("c").dtype(),
16103            DType::Utf8,
16104            "text -> Utf8"
16105        );
16106        assert_eq!(df.len(), 3, "row count");
16107    }
16108
16109    #[test]
16110    fn csv_integer_column_with_missing_value_promotes_to_float64_b8n0q() {
16111        let input = "a,b\n1,x\n,y\n3,z\n";
16112        let df = read_csv_str(input).expect("read");
16113        let column = df.column("a").expect("a");
16114        assert_eq!(
16115            column.dtype(),
16116            DType::Float64,
16117            "pandas int64 + NA -> float64"
16118        );
16119        assert_eq!(column.values()[0], Scalar::Float64(1.0));
16120        assert!(
16121            column.values()[1].is_missing(),
16122            "middle empty field must be NA"
16123        );
16124        assert_eq!(column.values()[2], Scalar::Float64(3.0));
16125
16126        let options = CsvReadOptions {
16127            nrows: Some(3),
16128            ..CsvReadOptions::default()
16129        };
16130        let options_df = read_csv_with_options(input, &options).expect("options read");
16131        assert_eq!(
16132            options_df.column("a").expect("options a").dtype(),
16133            DType::Float64,
16134            "generic options path must apply the same promotion"
16135        );
16136    }
16137
16138    #[test]
16139    fn csv_header_only_zero_rows_yqfw0() {
16140        // br-frankenpandas-yqfw0: a header-only CSV parses to a 0-row frame that still
16141        // exposes the header columns.
16142        let df = read_csv_str("a,b\n").expect("read header-only");
16143        assert_eq!(df.len(), 0, "no data rows; df={df:?}");
16144        assert!(df.column("a").is_some(), "column a present");
16145        assert!(df.column("b").is_some(), "column b present");
16146        assert_eq!(df.column("a").unwrap().values().len(), 0, "column a empty");
16147    }
16148
16149    #[test]
16150    fn csv_embedded_comma_in_quoted_field_rtpo7() {
16151        // br-frankenpandas-rtpo7: a quoted field containing the delimiter parses as ONE
16152        // field, not two columns (RFC4180). Companion to ftqon (embedded newline).
16153        let df = read_csv_str("col,n\n\"a,b\",1\n").expect("read");
16154        assert_eq!(df.len(), 1, "one row");
16155        assert!(
16156            df.column("col").is_some() && df.column("n").is_some(),
16157            "two columns only"
16158        );
16159        assert_eq!(
16160            df.column("col").unwrap().values()[0],
16161            Scalar::Utf8("a,b".to_owned()),
16162            "embedded comma kept"
16163        );
16164    }
16165
16166    #[test]
16167    fn csv_embedded_newline_in_quoted_field_ftqon() {
16168        // br-frankenpandas-ftqon: a quoted field containing a newline parses as ONE
16169        // multiline value (RFC4180), not two rows; and round-trips.
16170        let input = "col\n\"line1\nline2\"\n";
16171        let df = read_csv_str(input).expect("read");
16172        assert_eq!(df.len(), 1, "embedded newline stays one row; df={df:?}");
16173        let col = df.column("col").expect("col");
16174        assert_eq!(
16175            col.values()[0],
16176            Scalar::Utf8("line1\nline2".to_owned()),
16177            "multiline value intact"
16178        );
16179        // Round-trip: writing then reading preserves the multiline value.
16180        let csv = write_csv_string(&df).expect("write");
16181        let back = read_csv_str(&csv).expect("reread");
16182        assert_eq!(back.len(), 1, "round-trip row count");
16183        assert_eq!(
16184            back.column("col").expect("col").values()[0],
16185            Scalar::Utf8("line1\nline2".to_owned()),
16186            "round-trip value"
16187        );
16188    }
16189
16190    #[test]
16191    fn csv_bool_column_round_trip_w3dja() {
16192        // br-frankenpandas-w3dja: Bool column survives write_csv_string -> read_csv_str
16193        // (True/False spelling on write + case-insensitive bool inference on read).
16194        let bools = [true, false, true, false, true];
16195        let df = DataFrame::from_series(vec![
16196            Series::from_values(
16197                "flag",
16198                (0..bools.len() as i64).map(Into::into).collect::<Vec<_>>(),
16199                bools.iter().map(|&b| Scalar::Bool(b)).collect::<Vec<_>>(),
16200            )
16201            .unwrap(),
16202        ])
16203        .unwrap();
16204
16205        let csv = write_csv_string(&df).expect("write");
16206        let back = read_csv_str(&csv).expect("read");
16207        let col = back.column("flag").expect("flag");
16208        assert_eq!(
16209            col.dtype(),
16210            DType::Bool,
16211            "round-trip keeps Bool; csv={csv:?}"
16212        );
16213        assert_eq!(
16214            col.values(),
16215            &bools.iter().map(|&b| Scalar::Bool(b)).collect::<Vec<_>>()[..],
16216            "bool values preserved"
16217        );
16218    }
16219
16220    #[test]
16221    fn csv_read_write_read_idempotent_5gfjz() {
16222        // Round-trip fixed point (br-frankenpandas-5gfjz): read -> write -> read
16223        // yields an identical frame. Simple cells (ints + single letters, no
16224        // special chars) avoid quoting/precision edges. Seeded LCG, no mocks.
16225        let mut st: u64 = 0xc5f0_1d2e_3a4b_5c6d;
16226        let mut next = || {
16227            st = st
16228                .wrapping_mul(6_364_136_223_846_793_005)
16229                .wrapping_add(1_442_695_040_888_963_407);
16230            (st >> 33) as u32
16231        };
16232        for iter in 0..400u32 {
16233            let rows = (next() % 6) as usize + 1;
16234            let mut csv = String::from("a,b,c\n");
16235            for _ in 0..rows {
16236                let x = (next() % 100) as i64;
16237                let y = (next() % 1000) as i64;
16238                let letter = (b'a' + (next() % 5) as u8) as char;
16239                csv.push_str(&format!("{x},{y},{letter}\n"));
16240            }
16241            let f1 = read_csv_str(&csv).expect("read1");
16242            let s2 = write_csv_string(&f1).expect("write");
16243            let f2 = read_csv_str(&s2).expect("read2");
16244            assert_eq!(f1.len(), f2.len(), "row count iter={iter} csv={csv:?}");
16245            for name in ["a", "b", "c"] {
16246                assert_eq!(
16247                    f1.column(name).expect("c1").values(),
16248                    f2.column(name).expect("c2").values(),
16249                    "col {name} iter={iter} csv={csv:?}"
16250                );
16251            }
16252        }
16253    }
16254
16255    #[test]
16256    fn csv_round_trip_preserves_null_and_numeric_shape() {
16257        let input = "id,value\n1,10\n2,\n3,3.5\n";
16258        let frame = read_csv_str(input).expect("read");
16259        let value_col = frame.column("value").expect("value");
16260
16261        assert_eq!(value_col.values()[1], Scalar::Null(NullKind::NaN));
16262
16263        let out = write_csv_string(&frame).expect("write");
16264        assert!(out.contains("id,value"));
16265        assert!(out.contains("3,3.5"));
16266    }
16267
16268    #[test]
16269    fn csv_numeric_fast_path_preserves_default_dtypes_and_values() {
16270        let input = "i,f\n1,0.5\n2,3\n";
16271        let frame = read_csv_str(input).expect("read");
16272
16273        let int_col = frame.column("i").expect("i");
16274        assert_eq!(int_col.dtype(), DType::Int64);
16275        assert_eq!(int_col.values(), &[Scalar::Int64(1), Scalar::Int64(2)]);
16276
16277        let float_col = frame.column("f").expect("f");
16278        assert_eq!(float_col.dtype(), DType::Float64);
16279        assert_eq!(
16280            float_col.values(),
16281            &[Scalar::Float64(0.5), Scalar::Float64(3.0)]
16282        );
16283    }
16284
16285    #[test]
16286    fn csv_numeric_probe_falls_back_to_preserve_object_raw_text() {
16287        let input = "x\n 1 \nabc\n";
16288        let frame = read_csv_str(input).expect("read");
16289        let column = frame.column("x").expect("x");
16290
16291        assert_eq!(column.dtype(), DType::Utf8);
16292        assert_eq!(
16293            column.values(),
16294            &[
16295                Scalar::Utf8(" 1 ".to_owned()),
16296                Scalar::Utf8("abc".to_owned())
16297            ]
16298        );
16299    }
16300
16301    #[test]
16302    fn csv_parses_boolean_true_false_case_insensitive() {
16303        let input = "flag\nTrue\nFALSE\ntrue\nfalse\n";
16304        let frame = read_csv_str(input).expect("read");
16305        let flag_col = frame.column("flag").expect("flag");
16306        assert_eq!(flag_col.values()[0], Scalar::Bool(true));
16307        assert_eq!(flag_col.values()[1], Scalar::Bool(false));
16308        assert_eq!(flag_col.values()[2], Scalar::Bool(true));
16309        assert_eq!(flag_col.values()[3], Scalar::Bool(false));
16310    }
16311
16312    #[test]
16313    fn csv_duplicate_headers_error() {
16314        let input = "a,a\n1,2\n";
16315        let err = read_csv_str(input).expect_err("duplicate header");
16316        assert!(matches!(err, IoError::DuplicateColumnName(name) if name == "a"));
16317    }
16318
16319    /// SUPERSEDES the rejection contract br-frankenpandas-4hpid recorded here.
16320    /// That bead asserted "pandas-faithful rejection on ragged rows", but the
16321    /// premise is wrong in the SHORT direction. Measured on live pandas 2.2.3
16322    /// with this test's own input:
16323    ///   pd.read_csv(io.StringIO("a,b,c\n1,2,3\n4,5\n7,8,9\n"))
16324    ///        a  b    c
16325    ///     0  1  2  3.0
16326    ///     1  4  5  NaN     <- padded, NOT an error
16327    ///     2  7  8  9.0
16328    ///   dtypes: a int64, b int64, c float64
16329    /// The csv crate's UnequalLengths was firing in both directions; only the
16330    /// overlong direction is a pandas error
16331    /// (br-frankenpandas-fp-stricter-than-pandas-rejections-gtkz1).
16332    #[test]
16333    fn csv_short_row_pads_with_na_like_pandas_4hpid() {
16334        let short_row = "a,b,c\n1,2,3\n4,5\n7,8,9\n";
16335        let df = read_csv_str(short_row).expect("pandas pads a short row, it does not reject");
16336
16337        assert_eq!(df.column_names(), vec!["a", "b", "c"]);
16338        assert_eq!(
16339            df.columns()["a"].values(),
16340            &[Scalar::Int64(1), Scalar::Int64(4), Scalar::Int64(7)]
16341        );
16342        assert_eq!(
16343            df.columns()["b"].values(),
16344            &[Scalar::Int64(2), Scalar::Int64(5), Scalar::Int64(8)]
16345        );
16346        // The short row's missing 'c' is the pad and promotes the inferred
16347        // integer column to pandas-compatible Float64.
16348        let c = df.columns()["c"].values();
16349        assert_eq!(df.columns()["c"].dtype(), DType::Float64);
16350        assert_eq!(c[0], Scalar::Float64(3.0));
16351        assert!(
16352            c[1].is_missing(),
16353            "short row pads 'c' with NA, got {:?}",
16354            c[1]
16355        );
16356        assert_eq!(c[2], Scalar::Float64(9.0));
16357    }
16358
16359    /// The OTHER thing the strict reader used to catch only by accident. pandas
16360    /// raises here, measured:
16361    ///   pd.read_csv(io.StringIO('a,b\n"1,2\n'))
16362    ///     -> ParserError: EOF inside string starting at row 1
16363    /// Once short rows are padded (gtkz1) the field-count mismatch that used to
16364    /// surface this is gone, so it is detected directly. Without this the
16365    /// unterminated field would silently become a padded short row.
16366    #[test]
16367    fn csv_unterminated_quote_still_errors_like_pandas() {
16368        let err = read_csv_str("a,b\n\"open,1\n2,3\n")
16369            .expect_err("an unterminated quoted field must reject");
16370        assert!(matches!(err, IoError::CsvUnterminatedQuote), "got {err:?}");
16371    }
16372
16373    /// Negative control for the scanner: quotes that are properly closed, and a
16374    /// literal quote in the MIDDLE of an unquoted field, must NOT be read as an
16375    /// unterminated field.
16376    #[test]
16377    fn csv_closed_and_literal_quotes_are_not_unterminated() {
16378        assert!(!csv_input_has_unterminated_quote(
16379            "a,b\n\"x,y\",2\n",
16380            b',',
16381            b'"',
16382            true,
16383            None
16384        ));
16385        // Doubled quote inside a quoted field is an escaped literal.
16386        assert!(!csv_input_has_unterminated_quote(
16387            "a\n\"he said \"\"hi\"\"\"\n",
16388            b',',
16389            b'"',
16390            true,
16391            None
16392        ));
16393        // A quote that is not at a field start is a literal character.
16394        assert!(!csv_input_has_unterminated_quote(
16395            "a,b\nab\"cd,2\n",
16396            b',',
16397            b'"',
16398            true,
16399            None
16400        ));
16401    }
16402
16403    /// The negative control, and the half of 4hpid that WAS right: a row with
16404    /// MORE fields than the header is still an error. Measured:
16405    ///   pd.read_csv(io.StringIO("a,b,c\n1,2,3\n4,5,6,7\n"))
16406    ///     -> ParserError: Expected 3 fields in line 3, saw 4
16407    #[test]
16408    fn csv_overlong_row_still_errors_like_pandas() {
16409        let long_row = "a,b,c\n1,2,3\n4,5,6,7\n";
16410        let err = read_csv_str(long_row).expect_err("overlong row must still reject");
16411        assert!(
16412            matches!(
16413                err,
16414                IoError::CsvFieldCount {
16415                    line: 3,
16416                    expected: 3,
16417                    found: 4
16418                }
16419            ),
16420            "expected CsvFieldCount{{line:3,expected:3,found:4}}, got {err:?}"
16421        );
16422    }
16423
16424    #[test]
16425    fn csv_uniform_one_extra_field_becomes_the_index_azv2h() {
16426        // br-frankenpandas-azv2h. pandas' implicit-index rule is deliberately
16427        // all-or-nothing: every data row must be exactly one field wider than
16428        // the header. The leading field becomes the index, not a discarded
16429        // value and not a third data column.
16430        let frame = read_csv_str("a,b\n1,2,3\n4,5,6\n")
16431            .expect("uniform one-extra rows become an implicit index");
16432
16433        assert_eq!(frame.column_names(), vec!["a", "b"]);
16434        assert_eq!(
16435            frame.index().labels(),
16436            &[IndexLabel::Int64(1), IndexLabel::Int64(4)]
16437        );
16438        assert_eq!(
16439            frame.column("a").expect("a column").values(),
16440            &[Scalar::Int64(2), Scalar::Int64(5)]
16441        );
16442        assert_eq!(
16443            frame.column("b").expect("b column").values(),
16444            &[Scalar::Int64(3), Scalar::Int64(6)]
16445        );
16446
16447        // A single header-width row makes the input genuinely ragged again;
16448        // accepting the first row alone would falsely turn a parser error into
16449        // a green frame.
16450        let err = read_csv_str("a,b\n1,2,3\n4,5\n")
16451            .expect_err("mixed widths must not use implicit-index promotion");
16452        assert!(matches!(
16453            err,
16454            IoError::CsvFieldCount {
16455                line: 2,
16456                expected: 2,
16457                found: 3,
16458            }
16459        ));
16460    }
16461
16462    fn make_table_format_dataframe() -> DataFrame {
16463        let mut columns = BTreeMap::new();
16464        columns.insert(
16465            "name".to_owned(),
16466            Column::from_values(vec![
16467                Scalar::Utf8("A|B".to_owned()),
16468                Scalar::Utf8("under_score".to_owned()),
16469            ])
16470            .expect("name column"),
16471        );
16472        columns.insert(
16473            "value".to_owned(),
16474            Column::from_values(vec![Scalar::Float64(f64::NAN), Scalar::Int64(2)])
16475                .expect("value column"),
16476        );
16477
16478        let index = Index::new(vec![
16479            IndexLabel::Utf8("r&1".to_owned()),
16480            IndexLabel::Utf8("r_2".to_owned()),
16481        ])
16482        .set_name("row");
16483        DataFrame::new_with_column_order(
16484            index,
16485            columns,
16486            vec!["name".to_owned(), "value".to_owned()],
16487        )
16488        .expect("table format frame")
16489    }
16490
16491    #[test]
16492    fn markdown_table_writer_includes_index_missing_values_and_escaping() {
16493        let frame = make_table_format_dataframe();
16494
16495        let out = write_markdown_string(&frame).expect("markdown");
16496
16497        assert_eq!(
16498            out,
16499            concat!(
16500                "| row | name | value |\n",
16501                "| --- | --- | --- |\n",
16502                "| r&1 | A\\|B | NaN |\n",
16503                "| r_2 | under_score | 2 |\n",
16504            )
16505        );
16506    }
16507
16508    #[test]
16509    fn markdown_table_writer_options_can_omit_index_and_override_na() {
16510        let frame = make_table_format_dataframe();
16511
16512        let out = write_markdown_string_with_options(
16513            &frame,
16514            &MarkdownWriteOptions {
16515                include_index: false,
16516                na_rep: "<missing>".to_owned(),
16517                index_label: Some("ignored".to_owned()),
16518            },
16519        )
16520        .expect("markdown");
16521
16522        assert_eq!(
16523            out,
16524            concat!(
16525                "| name | value |\n",
16526                "| --- | --- |\n",
16527                "| A\\|B | <missing> |\n",
16528                "| under_score | 2 |\n",
16529            )
16530        );
16531    }
16532
16533    #[test]
16534    fn latex_table_writer_emits_booktabs_and_supports_escaping() {
16535        let frame = make_table_format_dataframe();
16536
16537        let out = write_latex_string_with_options(
16538            &frame,
16539            &LatexWriteOptions {
16540                include_index: true,
16541                na_rep: "NA".to_owned(),
16542                index_label: Some("row_id".to_owned()),
16543                escape: true,
16544            },
16545        )
16546        .expect("latex");
16547
16548        assert_eq!(
16549            out,
16550            concat!(
16551                "\\begin{tabular}{lll}\n",
16552                "\\toprule\n",
16553                " & name & value \\\\\n",
16554                "row\\_id &  &  \\\\\n",
16555                "\\midrule\n",
16556                "r\\&1 & A|B & NA \\\\\n",
16557                "r\\_2 & under\\_score & 2.000000 \\\\\n",
16558                "\\bottomrule\n",
16559                "\\end{tabular}\n",
16560            )
16561        );
16562    }
16563
16564    #[test]
16565    fn to_latex_floats_use_six_decimal_places_like_pandas() {
16566        // pandas to_latex default float_format is %.6f. Verified vs pandas 2.2.3:
16567        // 1.0->"1.000000", -2.5->"-2.500000", 0.1234567->"0.123457" (rounded),
16568        // inf->"inf". Other writers (csv/html) keep str(float).
16569        let values = vec![
16570            Scalar::Float64(1.0),
16571            Scalar::Float64(-2.5),
16572            Scalar::Float64(0.1234567),
16573            Scalar::Float64(f64::INFINITY),
16574        ];
16575        let col = Column::new(DType::Float64, values).expect("col");
16576        let mut cols = BTreeMap::new();
16577        cols.insert("a".to_string(), col);
16578        let index = Index::from_i64((0..4).collect());
16579        let frame =
16580            DataFrame::new_with_column_order(index, cols, vec!["a".to_string()]).expect("frame");
16581
16582        let out = write_latex_string_with_options(
16583            &frame,
16584            &LatexWriteOptions {
16585                include_index: false,
16586                na_rep: "NaN".to_owned(),
16587                index_label: None,
16588                escape: true,
16589            },
16590        )
16591        .expect("latex");
16592        assert!(out.contains("1.000000 \\\\"), "got: {out}");
16593        assert!(out.contains("-2.500000 \\\\"), "got: {out}");
16594        assert!(out.contains("0.123457 \\\\"), "got: {out}");
16595        assert!(out.contains("inf \\\\"), "got: {out}");
16596    }
16597
16598    #[test]
16599    fn markdown_latex_file_writers_match_string_outputs() {
16600        let frame = make_table_format_dataframe();
16601        let markdown_path = std::env::temp_dir().join(format!(
16602            "fp_io_markdown_writer_{}_{}.md",
16603            std::process::id(),
16604            line!()
16605        ));
16606        let latex_path = std::env::temp_dir().join(format!(
16607            "fp_io_latex_writer_{}_{}.tex",
16608            std::process::id(),
16609            line!()
16610        ));
16611
16612        write_markdown(&frame, &markdown_path).expect("write markdown path");
16613        write_latex(&frame, &latex_path).expect("write latex path");
16614
16615        assert_eq!(
16616            std::fs::read_to_string(&markdown_path).expect("read markdown path"),
16617            write_markdown_string(&frame).expect("markdown string")
16618        );
16619        assert_eq!(
16620            std::fs::read_to_string(&latex_path).expect("read latex path"),
16621            write_latex_string(&frame).expect("latex string")
16622        );
16623    }
16624
16625    #[test]
16626    fn markdown_latex_trait_aliases_forward_options() {
16627        use super::DataFrameIoExt;
16628
16629        let frame = make_table_format_dataframe();
16630        let markdown_options = MarkdownWriteOptions {
16631            include_index: false,
16632            na_rep: "NA".to_owned(),
16633            index_label: Some("ignored".to_owned()),
16634        };
16635        let latex_options = LatexWriteOptions {
16636            include_index: false,
16637            na_rep: "NA".to_owned(),
16638            index_label: Some("ignored".to_owned()),
16639            escape: true,
16640        };
16641        let markdown_path = std::env::temp_dir().join(format!(
16642            "fp_io_markdown_trait_{}_{}.md",
16643            std::process::id(),
16644            line!()
16645        ));
16646        let latex_path = std::env::temp_dir().join(format!(
16647            "fp_io_latex_trait_{}_{}.tex",
16648            std::process::id(),
16649            line!()
16650        ));
16651
16652        frame
16653            .to_markdown_file_with_options(&markdown_path, &markdown_options)
16654            .expect("trait markdown file");
16655        frame
16656            .to_latex_file_with_options(&latex_path, &latex_options)
16657            .expect("trait latex file");
16658
16659        assert_eq!(
16660            frame
16661                .to_markdown_string_with_options(&markdown_options)
16662                .expect("trait markdown options"),
16663            std::fs::read_to_string(&markdown_path).expect("read markdown trait path")
16664        );
16665        assert_eq!(
16666            frame
16667                .to_latex_string_with_options(&latex_options)
16668                .expect("trait latex options"),
16669            std::fs::read_to_string(&latex_path).expect("read latex trait path")
16670        );
16671
16672        let default_markdown_path = std::env::temp_dir().join(format!(
16673            "fp_io_markdown_trait_default_{}_{}.md",
16674            std::process::id(),
16675            line!()
16676        ));
16677        let default_latex_path = std::env::temp_dir().join(format!(
16678            "fp_io_latex_trait_default_{}_{}.tex",
16679            std::process::id(),
16680            line!()
16681        ));
16682        frame
16683            .to_markdown_file(&default_markdown_path)
16684            .expect("trait markdown default file");
16685        frame
16686            .to_latex_file(&default_latex_path)
16687            .expect("trait latex default file");
16688
16689        assert_eq!(
16690            std::fs::read_to_string(&default_markdown_path).expect("read markdown default"),
16691            write_markdown_string(&frame).expect("markdown default")
16692        );
16693        assert_eq!(
16694            std::fs::read_to_string(&default_latex_path).expect("read latex default"),
16695            write_latex_string(&frame).expect("latex default")
16696        );
16697
16698        let free_markdown_path = std::env::temp_dir().join(format!(
16699            "fp_io_markdown_free_options_{}_{}.md",
16700            std::process::id(),
16701            line!()
16702        ));
16703        let free_latex_path = std::env::temp_dir().join(format!(
16704            "fp_io_latex_free_options_{}_{}.tex",
16705            std::process::id(),
16706            line!()
16707        ));
16708        write_markdown_with_options(&frame, &free_markdown_path, &markdown_options)
16709            .expect("free markdown options file");
16710        write_latex_with_options(&frame, &free_latex_path, &latex_options)
16711            .expect("free latex options file");
16712        assert_eq!(
16713            std::fs::read_to_string(&free_markdown_path).expect("read free markdown options"),
16714            write_markdown_string_with_options(&frame, &markdown_options)
16715                .expect("free markdown options string")
16716        );
16717        assert_eq!(
16718            std::fs::read_to_string(&free_latex_path).expect("read free latex options"),
16719            write_latex_string_with_options(&frame, &latex_options)
16720                .expect("free latex options string")
16721        );
16722    }
16723
16724    #[test]
16725    #[ignore = "foreground release attribution harness"]
16726    fn html_table_writer_ordered_column_hoist_profile_z8gge() {
16727        const ROWS: usize = 256;
16728        const COLUMNS: usize = 24;
16729        const BATCH: usize = 8;
16730        const BLOCKS: usize = 9;
16731
16732        fn former(frame: &DataFrame, options: &HtmlWriteOptions) -> Result<String, IoError> {
16733            let mut out = String::new();
16734            super::push_html_table_open(&mut out, options);
16735            out.push_str("  <thead>\n    <tr style=\"text-align: ");
16736            out.push_str(&super::escape_html_attr(
16737                options.justify.as_deref().unwrap_or("right"),
16738            ));
16739            out.push_str(";\">\n");
16740
16741            if options.include_index {
16742                out.push_str("      <th></th>\n");
16743            }
16744            for name in frame.column_names() {
16745                out.push_str("      <th>");
16746                out.push_str(&super::html_text(name, options.escape));
16747                out.push_str("</th>\n");
16748            }
16749            out.push_str("    </tr>\n  </thead>\n  <tbody>\n");
16750
16751            for row_idx in 0..frame.index().len() {
16752                out.push_str("    <tr>\n");
16753                if options.include_index {
16754                    out.push_str("      <th>");
16755                    out.push_str(&super::html_index_label_string(
16756                        frame,
16757                        row_idx,
16758                        options.escape,
16759                    )?);
16760                    out.push_str("</th>\n");
16761                }
16762                for name in frame.column_names() {
16763                    let value = frame.column(name).and_then(|column| column.value(row_idx));
16764                    out.push_str("      <td>");
16765                    match value {
16766                        Some(scalar) => {
16767                            out.push_str(&super::html_scalar_string(scalar, options));
16768                        }
16769                        None => {
16770                            out.push_str(&super::html_text(&options.na_rep, options.escape));
16771                        }
16772                    }
16773                    out.push_str("</td>\n");
16774                }
16775                out.push_str("    </tr>\n");
16776            }
16777
16778            out.push_str("  </tbody>\n</table>");
16779            Ok(out)
16780        }
16781
16782        fn prototype(frame: &DataFrame, options: &HtmlWriteOptions) -> Result<String, IoError> {
16783            super::write_html_table_string(frame, options)
16784        }
16785
16786        fn elapsed_ns(frame: &DataFrame, options: &HtmlWriteOptions, use_prototype: bool) -> u128 {
16787            let started = std::time::Instant::now();
16788            for _ in 0..BATCH {
16789                let output = if use_prototype {
16790                    prototype(frame, options)
16791                } else {
16792                    former(frame, options)
16793                }
16794                .expect("HTML render");
16795                std::hint::black_box(output.as_bytes().last());
16796            }
16797            started.elapsed().as_nanos()
16798        }
16799
16800        fn median(mut samples: Vec<u128>) -> u128 {
16801            samples.sort_unstable();
16802            samples[samples.len() / 2]
16803        }
16804
16805        let mut columns = BTreeMap::new();
16806        let mut column_order = Vec::with_capacity(COLUMNS);
16807        for column_idx in 0..COLUMNS {
16808            let name = format!("column_{column_idx:02}");
16809            let values = (0..ROWS)
16810                .map(|row_idx| (column_idx * ROWS + row_idx) as i64)
16811                .collect();
16812            columns.insert(name.clone(), Column::from_i64_values(values));
16813            column_order.push(name);
16814        }
16815        column_order.reverse();
16816        let frame = DataFrame::new_with_column_order(
16817            Index::from_range(0, ROWS as i64, 1),
16818            columns,
16819            column_order,
16820        )
16821        .expect("profile frame");
16822        let options = HtmlWriteOptions {
16823            include_index: false,
16824            ..HtmlWriteOptions::default()
16825        };
16826
16827        let expected = former(&frame, &options).expect("former HTML");
16828        let actual = prototype(&frame, &options).expect("prototype HTML");
16829        assert_eq!(actual, expected, "prototype must be byte-identical");
16830
16831        std::hint::black_box(former(&frame, &options).expect("former warm-up"));
16832        std::hint::black_box(prototype(&frame, &options).expect("prototype warm-up"));
16833
16834        let mut former_samples = Vec::with_capacity(BLOCKS * 2);
16835        let mut prototype_samples = Vec::with_capacity(BLOCKS * 2);
16836        for block in 0..BLOCKS {
16837            let order = if block % 2 == 0 {
16838                [false, true, true, false]
16839            } else {
16840                [true, false, false, true]
16841            };
16842            for use_prototype in order {
16843                let elapsed = elapsed_ns(&frame, &options, use_prototype);
16844                if use_prototype {
16845                    prototype_samples.push(elapsed);
16846                } else {
16847                    former_samples.push(elapsed);
16848                }
16849            }
16850        }
16851
16852        let former_ns = median(former_samples) / BATCH as u128;
16853        let prototype_ns = median(prototype_samples) / BATCH as u128;
16854        println!(
16855            "HTML_COLUMN_HOIST_PROFILE rows={ROWS} columns={COLUMNS} former_ns={former_ns} prototype_ns={prototype_ns} speedup={:.6}",
16856            former_ns as f64 / prototype_ns as f64
16857        );
16858    }
16859
16860    #[test]
16861    fn html_table_writer_defaults_to_index_and_reuses_dataframe_formatter() {
16862        let frame = make_table_format_dataframe();
16863
16864        let out = write_html_string(&frame).expect("html");
16865
16866        assert_eq!(out, frame.to_html(true));
16867        assert!(out.contains("<th>r&amp;1</th>"));
16868        assert!(out.contains("<td>A|B</td>"));
16869        assert!(out.contains("<td>NaN</td>"));
16870    }
16871
16872    #[test]
16873    fn html_table_writer_options_can_omit_index() {
16874        let frame = make_table_format_dataframe();
16875
16876        let out = write_html_string_with_options(
16877            &frame,
16878            &HtmlWriteOptions {
16879                include_index: false,
16880                ..HtmlWriteOptions::default()
16881            },
16882        )
16883        .expect("html");
16884
16885        assert_eq!(out, frame.to_html(false));
16886        assert!(!out.contains("<th>r&amp;1</th>"));
16887        assert!(out.contains("<td>A|B</td>"));
16888    }
16889
16890    #[test]
16891    fn html_table_writer_supports_pandas_pure_string_options_u892h() {
16892        let mut columns = BTreeMap::new();
16893        columns.insert(
16894            "url&col".to_owned(),
16895            Column::from_values(vec![
16896                Scalar::Utf8("https://example.test/a?x=1&y=2".to_owned()),
16897                Scalar::Utf8("<b>".to_owned()),
16898            ])
16899            .expect("url column"),
16900        );
16901        columns.insert(
16902            "value".to_owned(),
16903            Column::from_values(vec![Scalar::Null(NullKind::NaN), Scalar::Float64(2.0)])
16904                .expect("value column"),
16905        );
16906        let frame = DataFrame::new_with_column_order(
16907            Index::new(vec![
16908                IndexLabel::Utf8("r&1".to_owned()),
16909                IndexLabel::Utf8("r2".to_owned()),
16910            ]),
16911            columns,
16912            vec!["url&col".to_owned(), "value".to_owned()],
16913        )
16914        .expect("html options frame");
16915
16916        let out = write_html_string_with_options(
16917            &frame,
16918            &HtmlWriteOptions {
16919                include_index: true,
16920                na_rep: "<NA>".to_owned(),
16921                classes: vec!["table table-sm".to_owned(), "fp".to_owned()],
16922                table_id: Some("report&1".to_owned()),
16923                border: Some(0),
16924                justify: Some("left".to_owned()),
16925                escape: true,
16926                render_links: true,
16927            },
16928        )
16929        .expect("html options");
16930
16931        assert!(
16932            out.starts_with("<table class=\"dataframe table table-sm fp\" id=\"report&amp;1\">")
16933        );
16934        assert!(!out.contains("border=\""));
16935        assert!(out.contains("<tr style=\"text-align: left;\">"));
16936        assert!(out.contains("<th>url&amp;col</th>"));
16937        assert!(out.contains("<th>r&amp;1</th>"));
16938        assert!(out.contains("<td>&lt;NA&gt;</td>"));
16939        assert!(out.contains(
16940            "<a href=\"https://example.test/a?x=1&amp;y=2\" target=\"_blank\">https://example.test/a?x=1&amp;y=2</a>"
16941        ));
16942        assert!(out.contains("<td>&lt;b&gt;</td>"));
16943    }
16944
16945    #[test]
16946    fn html_table_writer_can_disable_escaping_u892h() {
16947        let mut columns = BTreeMap::new();
16948        columns.insert(
16949            "raw<th>".to_owned(),
16950            Column::from_values(vec![
16951                Scalar::Utf8("<b>".to_owned()),
16952                Scalar::Null(NullKind::NaN),
16953            ])
16954            .expect("raw column"),
16955        );
16956        let frame = DataFrame::new_with_column_order(
16957            Index::new(vec![
16958                IndexLabel::Utf8("r&1".to_owned()),
16959                IndexLabel::Int64(2),
16960            ]),
16961            columns,
16962            vec!["raw<th>".to_owned()],
16963        )
16964        .expect("raw html frame");
16965
16966        let out = write_html_string_with_options(
16967            &frame,
16968            &HtmlWriteOptions {
16969                na_rep: "<NA>".to_owned(),
16970                escape: false,
16971                ..HtmlWriteOptions::default()
16972            },
16973        )
16974        .expect("raw html options");
16975
16976        assert!(out.contains("<th>raw<th></th>"));
16977        assert!(out.contains("<th>r&1</th>"));
16978        assert!(out.contains("<td><b></td>"));
16979        assert!(out.contains("<td><NA></td>"));
16980    }
16981
16982    #[test]
16983    fn html_table_writer_file_output_matches_string_output() {
16984        use super::DataFrameIoExt;
16985
16986        let frame = make_table_format_dataframe();
16987        let path = std::env::temp_dir().join(format!(
16988            "fp_io_html_writer_{}_{}.html",
16989            std::process::id(),
16990            line!()
16991        ));
16992
16993        write_html(&frame, &path).expect("write html");
16994        let file_out = std::fs::read_to_string(&path).expect("read html");
16995
16996        assert_eq!(file_out, write_html_string(&frame).expect("html string"));
16997        assert_eq!(
16998            frame.to_html_string().expect("trait html string"),
16999            write_html_string(&frame).expect("free html string")
17000        );
17001
17002        let no_index_path = std::env::temp_dir().join(format!(
17003            "fp_io_html_writer_no_index_{}_{}.html",
17004            std::process::id(),
17005            line!()
17006        ));
17007        let no_index_options = HtmlWriteOptions {
17008            include_index: false,
17009            ..HtmlWriteOptions::default()
17010        };
17011        frame
17012            .to_html_file_with_options(&no_index_path, &no_index_options)
17013            .expect("trait html file");
17014        assert_eq!(
17015            std::fs::read_to_string(&no_index_path).expect("read trait html"),
17016            write_html_string_with_options(&frame, &no_index_options).expect("free html options")
17017        );
17018    }
17019
17020    #[test]
17021    fn html_reader_parses_first_table_headers_and_missing_cells() {
17022        let html = concat!(
17023            "<html><body>",
17024            "<table><tr><td>ignored</td></tr></table>",
17025            "<table>",
17026            "<thead><tr><th>name</th><th>value</th><th>flag</th></tr></thead>",
17027            "<tbody>",
17028            "<tr><td>A&amp;B</td><td>1</td><td>True</td></tr>",
17029            "<tr><td>missing</td><td></td></tr>",
17030            "</tbody>",
17031            "</table>",
17032            "</body></html>",
17033        );
17034
17035        let frame = read_html_str_with_options(html, &HtmlReadOptions { table_index: 1 })
17036            .expect("read second table");
17037
17038        assert_eq!(
17039            frame
17040                .column_names()
17041                .into_iter()
17042                .map(String::as_str)
17043                .collect::<Vec<_>>(),
17044            vec!["name", "value", "flag"]
17045        );
17046        assert_eq!(
17047            frame.column("name").expect("name").values()[0],
17048            Scalar::Utf8("A&B".to_owned())
17049        );
17050        assert_eq!(
17051            frame.column("value").expect("value").values()[0],
17052            Scalar::Int64(1)
17053        );
17054        assert!(frame.column("value").expect("value").values()[1].is_missing());
17055        assert_eq!(
17056            frame.column("flag").expect("flag").values()[0],
17057            Scalar::Bool(true)
17058        );
17059        assert!(matches!(
17060            frame.column("flag").expect("flag").values()[1],
17061            Scalar::Null(NullKind::Null)
17062        ));
17063    }
17064
17065    #[test]
17066    fn html_reader_roundtrips_writer_output_as_columns() {
17067        let source = make_table_format_dataframe();
17068        let html = write_html_string(&source).expect("write html");
17069
17070        let frame = read_html_str(&html).expect("read writer html");
17071
17072        assert_eq!(
17073            frame
17074                .column_names()
17075                .into_iter()
17076                .map(String::as_str)
17077                .collect::<Vec<_>>(),
17078            vec!["Unnamed: 0", "name", "value"]
17079        );
17080        assert_eq!(
17081            frame.column("Unnamed: 0").expect("index column").values()[0],
17082            Scalar::Utf8("r&1".to_owned())
17083        );
17084        assert_eq!(
17085            frame.column("name").expect("name").values()[0],
17086            Scalar::Utf8("A|B".to_owned())
17087        );
17088        assert!(frame.column("value").expect("value").values()[0].is_missing());
17089        assert_eq!(
17090            frame.column("value").expect("value").values()[1],
17091            Scalar::Float64(2.0)
17092        );
17093    }
17094
17095    #[test]
17096    fn html_reader_path_reader_matches_string_reader() {
17097        use std::io::Write;
17098
17099        let html = "<table><tr><th>name</th></tr><tr><td>A</td></tr></table>\n";
17100        let path = std::env::temp_dir().join(format!(
17101            "fp_io_html_reader_{}_{}.html",
17102            std::process::id(),
17103            line!()
17104        ));
17105        let mut file = std::fs::OpenOptions::new()
17106            .write(true)
17107            .create_new(true)
17108            .open(&path)
17109            .expect("create html fixture");
17110        file.write_all(html.as_bytes()).expect("write html fixture");
17111
17112        let via_path = read_html(&path).expect("read path html");
17113        let via_str = read_html_str(html).expect("read string html");
17114
17115        assert_eq!(via_path.column_names(), via_str.column_names());
17116        assert_eq!(
17117            via_path.column("name").expect("path name").values(),
17118            via_str.column("name").expect("str name").values()
17119        );
17120    }
17121
17122    #[test]
17123    fn html_reader_rejects_no_table_duplicate_headers_and_wide_rows() {
17124        let err = read_html_str("<p>no table</p>").expect_err("missing table");
17125        assert!(matches!(err, IoError::Html(message) if message.contains("no table")));
17126
17127        let duplicate = "<table><tr><th>a</th><th>a</th></tr><tr><td>1</td><td>2</td></tr></table>";
17128        assert!(matches!(
17129            read_html_str(duplicate),
17130            Err(IoError::DuplicateColumnName(name)) if name == "a"
17131        ));
17132
17133        let wide = "<table><tr><th>a</th></tr><tr><td>1</td><td>2</td></tr></table>";
17134        let err = read_html_str(wide).expect_err("wide row");
17135        assert!(matches!(err, IoError::Html(message) if message.contains("row 0")));
17136    }
17137
17138    #[test]
17139    fn pickle_bytes_roundtrip_preserves_split_frame_shape() {
17140        let source = read_json_str(
17141            r#"{"columns":["name","value","flag"],"index":["r1","r2"],"data":[["alice",1,true],[null,2.5,false]]}"#,
17142            JsonOrient::Split,
17143        )
17144        .expect("source frame");
17145
17146        let bytes = write_pickle_bytes(&source).expect("write pickle bytes");
17147        assert!(!bytes.is_empty());
17148        let roundtrip = read_pickle_bytes(&bytes).expect("read pickle bytes");
17149
17150        assert_eq!(
17151            write_json_string(&roundtrip, JsonOrient::Split).expect("roundtrip json"),
17152            write_json_string(&source, JsonOrient::Split).expect("source json")
17153        );
17154    }
17155
17156    #[test]
17157    fn pickle_path_reader_matches_bytes_reader() {
17158        let source = make_table_format_dataframe();
17159        let path = std::env::temp_dir().join(format!(
17160            "fp_io_pickle_reader_{}_{}.pkl",
17161            std::process::id(),
17162            line!()
17163        ));
17164
17165        write_pickle(&source, &path).expect("write pickle path");
17166
17167        let via_path = read_pickle(&path).expect("read pickle path");
17168        let via_bytes =
17169            read_pickle_bytes(&std::fs::read(&path).expect("read pickle bytes from path"))
17170                .expect("read pickle bytes");
17171
17172        assert_eq!(
17173            write_json_string(&via_path, JsonOrient::Split).expect("path json"),
17174            write_json_string(&via_bytes, JsonOrient::Split).expect("bytes json")
17175        );
17176    }
17177
17178    #[test]
17179    fn pickle_protocol_v2_and_extension_aliases_roundtrip() {
17180        use super::DataFrameIoExt;
17181
17182        let source = make_table_format_dataframe();
17183        let options = PickleWriteOptions {
17184            protocol: PickleProtocol::V2,
17185        };
17186        let bytes = source
17187            .to_pickle_bytes_with_options(&options)
17188            .expect("trait pickle protocol v2");
17189        let roundtrip = read_pickle_bytes(&bytes).expect("read protocol v2");
17190
17191        assert_eq!(
17192            write_json_string(&roundtrip, JsonOrient::Split).expect("roundtrip json"),
17193            write_json_string(&source, JsonOrient::Split).expect("source json")
17194        );
17195        assert_eq!(
17196            source.to_pickle_bytes().expect("trait pickle bytes"),
17197            write_pickle_bytes(&source).expect("free pickle bytes")
17198        );
17199    }
17200
17201    #[test]
17202    fn series_pickle_extension_aliases_roundtrip_to_single_column_frame() {
17203        use super::SeriesIoExt;
17204
17205        let source = Series::from_values(
17206            "sales",
17207            vec!["r1".into(), "r2".into()],
17208            vec![Scalar::Int64(10), Scalar::Int64(12)],
17209        )
17210        .expect("source series");
17211
17212        let bytes = source.to_pickle_bytes().expect("series pickle bytes");
17213        let roundtrip = read_pickle_bytes(&bytes).expect("read series pickle frame");
17214        let names = roundtrip
17215            .column_names()
17216            .into_iter()
17217            .map(String::as_str)
17218            .collect::<Vec<_>>();
17219        assert_eq!(names, vec!["sales"]);
17220        assert_eq!(roundtrip.index().labels(), source.index().labels());
17221        assert_eq!(
17222            roundtrip.column("sales").expect("sales column").values(),
17223            source.values()
17224        );
17225
17226        let frame = source.to_frame(None).expect("series frame");
17227        assert_eq!(
17228            source.to_pickle_bytes().expect("trait pickle bytes"),
17229            write_pickle_bytes(&frame).expect("frame pickle bytes")
17230        );
17231
17232        let options = PickleWriteOptions {
17233            protocol: PickleProtocol::V2,
17234        };
17235        assert!(
17236            !source
17237                .to_pickle_bytes_with_options(&options)
17238                .expect("series pickle protocol v2")
17239                .is_empty()
17240        );
17241    }
17242
17243    #[test]
17244    fn series_csv_extension_aliases_preserve_default_index() {
17245        use super::SeriesIoExt;
17246
17247        let source = Series::from_values(
17248            "sales",
17249            vec!["r1".into(), "r2".into()],
17250            vec![Scalar::Int64(10), Scalar::Int64(12)],
17251        )
17252        .expect("source series");
17253
17254        let csv = source.to_csv_string().expect("series csv string");
17255        assert_eq!(csv, ",sales\nr1,10\nr2,12\n");
17256
17257        let no_index = source
17258            .to_csv_string_with_options(&CsvWriteOptions {
17259                include_index: false,
17260                ..CsvWriteOptions::default()
17261            })
17262            .expect("series csv without index");
17263        assert_eq!(no_index, "sales\n10\n12\n");
17264
17265        let path = std::env::temp_dir().join(format!(
17266            "fp_io_series_csv_{}_{}.csv",
17267            std::process::id(),
17268            line!()
17269        ));
17270        source.to_csv_file(&path).expect("series csv file");
17271        assert_eq!(
17272            std::fs::read_to_string(&path).expect("read series csv file"),
17273            csv
17274        );
17275    }
17276
17277    #[test]
17278    fn series_json_extension_aliases_use_series_orients() {
17279        use super::SeriesIoExt;
17280
17281        let source = Series::from_values(
17282            "sales",
17283            vec!["r1".into(), "r2".into()],
17284            vec![Scalar::Int64(10), Scalar::Int64(12)],
17285        )
17286        .expect("source series");
17287
17288        assert_eq!(
17289            source
17290                .to_json_string("records")
17291                .expect("series records json"),
17292            "[10,12]"
17293        );
17294
17295        let split: serde_json::Value =
17296            serde_json::from_str(&source.to_json_string("split").expect("series split json"))
17297                .expect("parse split json");
17298        assert_eq!(split["name"], "sales");
17299        assert_eq!(split["index"], serde_json::json!(["r1", "r2"]));
17300        assert_eq!(split["data"], serde_json::json!([10, 12]));
17301
17302        let path = std::env::temp_dir().join(format!(
17303            "fp_io_series_json_{}_{}.json",
17304            std::process::id(),
17305            line!()
17306        ));
17307        source
17308            .to_json_file(&path, "index")
17309            .expect("series json file");
17310        assert_eq!(
17311            std::fs::read_to_string(&path).expect("read series json file"),
17312            source.to_json("index").expect("series index json")
17313        );
17314    }
17315
17316    #[test]
17317    fn series_markdown_extension_aliases_forward_options() {
17318        use super::SeriesIoExt;
17319
17320        let source = Series::from_values(
17321            "sales",
17322            vec!["r1".into(), "r2".into()],
17323            vec![Scalar::Int64(10), Scalar::Null(NullKind::NaN)],
17324        )
17325        .expect("source series");
17326        let options = MarkdownWriteOptions {
17327            include_index: false,
17328            na_rep: "NA".to_owned(),
17329            index_label: Some("ignored".to_owned()),
17330        };
17331
17332        assert_eq!(
17333            source.to_markdown_string().expect("series markdown string"),
17334            write_markdown_string(&source.to_frame(None).expect("series frame"))
17335                .expect("frame markdown string")
17336        );
17337        assert_eq!(
17338            source
17339                .to_markdown_string_with_options(&options)
17340                .expect("series markdown options"),
17341            write_markdown_string_with_options(
17342                &source.to_frame(None).expect("series options frame"),
17343                &options,
17344            )
17345            .expect("frame markdown options")
17346        );
17347
17348        let path = std::env::temp_dir().join(format!(
17349            "fp_io_series_markdown_{}_{}.md",
17350            std::process::id(),
17351            line!()
17352        ));
17353        source
17354            .to_markdown_file_with_options(&path, &options)
17355            .expect("series markdown file");
17356        assert_eq!(
17357            std::fs::read_to_string(&path).expect("read series markdown file"),
17358            source
17359                .to_markdown_string_with_options(&options)
17360                .expect("series markdown options string")
17361        );
17362    }
17363
17364    #[test]
17365    fn series_latex_extension_aliases_forward_options() {
17366        use super::SeriesIoExt;
17367
17368        let source = Series::from_values(
17369            "sales&tax",
17370            vec!["r1".into(), "r2".into()],
17371            vec![Scalar::Utf8("a&b".into()), Scalar::Null(NullKind::NaN)],
17372        )
17373        .expect("source series");
17374        let options = LatexWriteOptions {
17375            include_index: false,
17376            na_rep: "NA".to_owned(),
17377            index_label: Some("ignored".to_owned()),
17378            escape: true,
17379        };
17380
17381        assert_eq!(
17382            source.to_latex_string().expect("series latex string"),
17383            write_latex_string(&source.to_frame(None).expect("series frame"))
17384                .expect("frame latex string")
17385        );
17386        assert_eq!(
17387            source
17388                .to_latex_string_with_options(&options)
17389                .expect("series latex options"),
17390            write_latex_string_with_options(
17391                &source.to_frame(None).expect("series options frame"),
17392                &options,
17393            )
17394            .expect("frame latex options")
17395        );
17396
17397        let path = std::env::temp_dir().join(format!(
17398            "fp_io_series_latex_{}_{}.tex",
17399            std::process::id(),
17400            line!()
17401        ));
17402        source
17403            .to_latex_file_with_options(&path, &options)
17404            .expect("series latex file");
17405        assert_eq!(
17406            std::fs::read_to_string(&path).expect("read series latex file"),
17407            source
17408                .to_latex_string_with_options(&options)
17409                .expect("series latex options string")
17410        );
17411    }
17412
17413    #[cfg(feature = "hdf5")]
17414    #[test]
17415    fn series_hdf5_extension_aliases_roundtrip_to_single_column_frame() {
17416        use super::SeriesIoExt;
17417
17418        let source = Series::from_values(
17419            "sales",
17420            vec!["r1".into(), "r2".into()],
17421            vec![Scalar::Int64(10), Scalar::Int64(12)],
17422        )
17423        .expect("source series");
17424        let expected = source.to_frame(None).expect("series frame");
17425
17426        let key_path = std::env::temp_dir().join(format!(
17427            "fp_io_series_hdf5_key_{}_{}.h5",
17428            std::process::id(),
17429            line!()
17430        ));
17431        source
17432            .to_hdf_key(&key_path, "series/data")
17433            .expect("series hdf key");
17434        assert!(
17435            read_hdf_key(&key_path, "series/data")
17436                .expect("read series hdf key")
17437                .equals(&expected)
17438        );
17439
17440        let default_path = std::env::temp_dir().join(format!(
17441            "fp_io_series_hdf5_default_{}_{}.h5",
17442            std::process::id(),
17443            line!()
17444        ));
17445        source
17446            .to_hdf_file(&default_path)
17447            .expect("series hdf default key");
17448        assert!(
17449            read_hdf(&default_path)
17450                .expect("read series hdf default")
17451                .equals(&expected)
17452        );
17453
17454        let options_path = std::env::temp_dir().join(format!(
17455            "fp_io_series_hdf5_options_{}_{}.h5",
17456            std::process::id(),
17457            line!()
17458        ));
17459        source
17460            .to_hdf_with_options(
17461                &options_path,
17462                &HdfWriteOptions {
17463                    key: "series/options".to_owned(),
17464                },
17465            )
17466            .expect("series hdf options");
17467        assert!(
17468            read_hdf_key(&options_path, "series/options")
17469                .expect("read series hdf options")
17470                .equals(&expected)
17471        );
17472    }
17473
17474    #[test]
17475    fn series_excel_extension_aliases_roundtrip_to_single_column_frame() {
17476        use super::SeriesIoExt;
17477
17478        let source = Series::from_values(
17479            "sales",
17480            vec!["r1".into(), "r2".into()],
17481            vec![Scalar::Int64(10), Scalar::Int64(12)],
17482        )
17483        .expect("source series");
17484
17485        let bytes = source.to_excel_bytes().expect("series excel bytes");
17486        let roundtrip =
17487            read_excel_bytes(&bytes, &ExcelReadOptions::default()).expect("read series excel");
17488        let names = roundtrip
17489            .column_names()
17490            .into_iter()
17491            .map(String::as_str)
17492            .collect::<Vec<_>>();
17493        assert_eq!(names, vec!["column_0", "sales"]);
17494        assert_eq!(
17495            roundtrip.column("column_0").expect("index column").values(),
17496            &[Scalar::Utf8("r1".into()), Scalar::Utf8("r2".into())]
17497        );
17498        assert_eq!(
17499            roundtrip.column("sales").expect("sales column").values(),
17500            source.values()
17501        );
17502
17503        let frame = source.to_frame(None).expect("series frame");
17504        assert_eq!(
17505            source.to_excel_bytes().expect("trait excel bytes"),
17506            write_excel_bytes(&frame).expect("frame excel bytes")
17507        );
17508
17509        let options = ExcelWriteOptions {
17510            index: false,
17511            ..ExcelWriteOptions::default()
17512        };
17513        let no_index_bytes = source
17514            .to_excel_bytes_with_options(&options)
17515            .expect("series excel index false");
17516        let no_index = read_excel_bytes(&no_index_bytes, &ExcelReadOptions::default())
17517            .expect("read no-index series excel");
17518        assert_eq!(no_index.column_names(), vec!["sales"]);
17519        assert_eq!(no_index.index().len(), source.index().len());
17520    }
17521
17522    #[test]
17523    fn pickle_reader_rejects_malformed_and_foreign_payloads() {
17524        let err = read_pickle_bytes(b"not a pickle").expect_err("malformed pickle");
17525        assert!(matches!(err, IoError::Pickle(_)));
17526
17527        let foreign = serde_pickle::to_vec(
17528            &serde_json::json!({"payload": {"columns": [], "index": [], "data": []}}),
17529            serde_pickle::SerOptions::new(),
17530        )
17531        .expect("foreign pickle");
17532        let err = read_pickle_bytes(&foreign).expect_err("foreign pickle");
17533        assert!(matches!(
17534            err,
17535            IoError::Pickle(message) if message.contains("format marker")
17536        ));
17537    }
17538
17539    #[cfg(feature = "hdf5")]
17540    #[test]
17541    fn hdf5_path_roundtrip_preserves_snapshot_frame() {
17542        let source = make_table_format_dataframe();
17543        let path = std::env::temp_dir().join(format!(
17544            "fp_io_hdf5_default_{}_{}.h5",
17545            std::process::id(),
17546            line!()
17547        ));
17548
17549        write_hdf(&source, &path).expect("write hdf default key");
17550        let roundtrip = read_hdf(&path).expect("read hdf default key");
17551
17552        assert_eq!(
17553            write_json_string(&roundtrip, JsonOrient::Split).expect("roundtrip json"),
17554            write_json_string(&source, JsonOrient::Split).expect("source json")
17555        );
17556    }
17557
17558    #[cfg(feature = "hdf5")]
17559    #[test]
17560    fn hdf5_custom_key_and_extension_aliases_roundtrip() {
17561        use super::DataFrameIoExt;
17562
17563        let source = make_test_dataframe();
17564        let free_path = std::env::temp_dir().join(format!(
17565            "fp_io_hdf5_custom_free_{}_{}.h5",
17566            std::process::id(),
17567            line!()
17568        ));
17569        let trait_path = std::env::temp_dir().join(format!(
17570            "fp_io_hdf5_custom_trait_{}_{}.h5",
17571            std::process::id(),
17572            line!()
17573        ));
17574        let default_path = std::env::temp_dir().join(format!(
17575            "fp_io_hdf5_custom_default_{}_{}.h5",
17576            std::process::id(),
17577            line!()
17578        ));
17579        let write_options = HdfWriteOptions {
17580            key: "tables/snapshot".to_owned(),
17581        };
17582
17583        write_hdf_with_options(&source, &free_path, &write_options).expect("write custom key");
17584        let roundtrip = read_hdf_with_options(
17585            &free_path,
17586            &HdfReadOptions {
17587                key: "/tables/snapshot/".to_owned(),
17588            },
17589        )
17590        .expect("read custom key with slash aliases");
17591        assert!(roundtrip.equals(&source));
17592
17593        source
17594            .to_hdf_key(&trait_path, "nested/frame")
17595            .expect("trait hdf key");
17596        assert!(
17597            read_hdf_key(&trait_path, "nested/frame")
17598                .expect("read trait hdf key")
17599                .equals(&source)
17600        );
17601
17602        source
17603            .to_hdf_file(&default_path)
17604            .expect("trait hdf default key");
17605        assert!(
17606            read_hdf(&default_path)
17607                .expect("read trait hdf default")
17608                .equals(&source)
17609        );
17610    }
17611
17612    #[cfg(feature = "hdf5")]
17613    #[test]
17614    fn hdf5_row_multiindex_roundtrip_restores_logical_row_axis() {
17615        let frame = make_row_multiindex_test_dataframe();
17616        let path = std::env::temp_dir().join(format!(
17617            "fp_io_hdf5_multiindex_{}_{}.h5",
17618            std::process::id(),
17619            line!()
17620        ));
17621
17622        write_hdf_key(&frame, &path, "axes/frame").expect("write hdf multiindex");
17623        let roundtrip = read_hdf_key(&path, "axes/frame").expect("read hdf multiindex");
17624
17625        assert!(roundtrip.equals(&frame));
17626        assert!(roundtrip.column("__index_level_0__").is_none());
17627        assert_eq!(
17628            roundtrip
17629                .row_multiindex()
17630                .expect("row multiindex should be restored")
17631                .get_level_values(0)
17632                .unwrap()
17633                .labels(),
17634            frame
17635                .row_multiindex()
17636                .expect("source row multiindex")
17637                .get_level_values(0)
17638                .unwrap()
17639                .labels()
17640        );
17641    }
17642
17643    #[cfg(feature = "hdf5")]
17644    #[test]
17645    fn hdf5_reader_rejects_invalid_keys_and_missing_payloads() {
17646        let frame = make_test_dataframe();
17647        let path = std::env::temp_dir().join(format!(
17648            "fp_io_hdf5_missing_payload_{}_{}.h5",
17649            std::process::id(),
17650            line!()
17651        ));
17652
17653        let file = hdf5::File::create(&path).expect("create hdf shell");
17654        file.create_group("frame")
17655            .expect("create empty frame group");
17656        file.flush().expect("flush hdf shell");
17657        drop(file);
17658
17659        let err = read_hdf(&path).expect_err("missing payload should fail");
17660        assert!(matches!(
17661            err,
17662            IoError::Hdf5(message) if message.contains("missing FrankenPandas payload dataset")
17663        ));
17664
17665        let err = write_hdf_key(&frame, &path, "../bad").expect_err("invalid key should fail");
17666        assert!(matches!(
17667            err,
17668            IoError::Hdf5(message) if message.contains("invalid hdf5 key")
17669        ));
17670    }
17671
17672    fn make_stata_dataframe() -> DataFrame {
17673        let mut columns = BTreeMap::new();
17674        columns.insert(
17675            "id".to_owned(),
17676            Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)])
17677                .expect("id column"),
17678        );
17679        columns.insert(
17680            "score".to_owned(),
17681            Column::from_values(vec![
17682                Scalar::Float64(1.5),
17683                Scalar::Null(NullKind::NaN),
17684                Scalar::Float64(3.25),
17685            ])
17686            .expect("score column"),
17687        );
17688        columns.insert(
17689            "flag".to_owned(),
17690            Column::from_values(vec![
17691                Scalar::Bool(true),
17692                Scalar::Bool(false),
17693                Scalar::Bool(true),
17694            ])
17695            .expect("flag column"),
17696        );
17697        columns.insert(
17698            "label".to_owned(),
17699            Column::from_values(vec![
17700                Scalar::Utf8("alpha".to_owned()),
17701                Scalar::Utf8("beta".to_owned()),
17702                Scalar::Utf8("gamma".to_owned()),
17703            ])
17704            .expect("label column"),
17705        );
17706
17707        DataFrame::new_with_column_order(
17708            Index::new(vec![
17709                IndexLabel::Utf8("row_a".to_owned()),
17710                IndexLabel::Utf8("row_b".to_owned()),
17711                IndexLabel::Utf8("row_c".to_owned()),
17712            ]),
17713            columns,
17714            vec![
17715                "id".to_owned(),
17716                "score".to_owned(),
17717                "flag".to_owned(),
17718                "label".to_owned(),
17719            ],
17720        )
17721        .expect("stata frame")
17722    }
17723
17724    #[test]
17725    fn stata_bytes_roundtrip_preserves_supported_columns() {
17726        let source = make_stata_dataframe();
17727        let bytes = write_stata_bytes(&source).expect("write stata bytes");
17728        assert!(!bytes.is_empty());
17729
17730        let roundtrip = read_stata_bytes(&bytes).expect("read stata bytes");
17731
17732        assert_eq!(
17733            roundtrip
17734                .column_names()
17735                .into_iter()
17736                .map(String::as_str)
17737                .collect::<Vec<_>>(),
17738            vec!["index", "id", "score", "flag", "label"]
17739        );
17740        assert_eq!(
17741            roundtrip.column("index").expect("index").values(),
17742            &[
17743                Scalar::Utf8("row_a".to_owned()),
17744                Scalar::Utf8("row_b".to_owned()),
17745                Scalar::Utf8("row_c".to_owned())
17746            ]
17747        );
17748        assert_eq!(
17749            roundtrip.column("id").expect("id").values(),
17750            &[Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)]
17751        );
17752        assert_eq!(
17753            roundtrip.column("score").expect("score").values(),
17754            &[
17755                Scalar::Float64(1.5),
17756                Scalar::Null(NullKind::NaN),
17757                Scalar::Float64(3.25)
17758            ]
17759        );
17760        assert_eq!(
17761            roundtrip.column("flag").expect("flag").values(),
17762            &[Scalar::Int64(1), Scalar::Int64(0), Scalar::Int64(1)]
17763        );
17764        assert_eq!(
17765            roundtrip.column("label").expect("label").values(),
17766            &[
17767                Scalar::Utf8("alpha".to_owned()),
17768                Scalar::Utf8("beta".to_owned()),
17769                Scalar::Utf8("gamma".to_owned())
17770            ]
17771        );
17772    }
17773
17774    #[test]
17775    fn stata_path_reader_matches_bytes_reader() {
17776        let source = make_stata_dataframe();
17777        let path = std::env::temp_dir().join(format!(
17778            "fp_io_stata_reader_{}_{}.dta",
17779            std::process::id(),
17780            line!()
17781        ));
17782
17783        write_stata(&source, &path).expect("write stata path");
17784
17785        let via_path = read_stata(&path).expect("read stata path");
17786        let via_bytes =
17787            read_stata_bytes(&std::fs::read(&path).expect("read stata bytes from path"))
17788                .expect("read stata bytes");
17789
17790        assert_eq!(via_path.column_names(), via_bytes.column_names());
17791        for name in via_path.column_names() {
17792            assert_eq!(
17793                via_path.column(name).expect("path column").values(),
17794                via_bytes.column(name).expect("bytes column").values()
17795            );
17796        }
17797    }
17798
17799    #[test]
17800    fn stata_extension_aliases_and_no_index_option_roundtrip() {
17801        use super::DataFrameIoExt;
17802
17803        let source = make_stata_dataframe();
17804        let options = StataWriteOptions {
17805            include_index: false,
17806            index_label: Some("ignored".to_owned()),
17807        };
17808        let bytes = source
17809            .to_stata_bytes_with_options(&options)
17810            .expect("trait stata bytes without index");
17811        let roundtrip = read_stata_bytes(&bytes).expect("read no-index stata");
17812
17813        assert_eq!(
17814            roundtrip
17815                .column_names()
17816                .into_iter()
17817                .map(String::as_str)
17818                .collect::<Vec<_>>(),
17819            vec!["id", "score", "flag", "label"]
17820        );
17821
17822        let path = std::env::temp_dir().join(format!(
17823            "fp_io_stata_trait_{}_{}.dta",
17824            std::process::id(),
17825            line!()
17826        ));
17827        source
17828            .to_stata_with_options(&path, &options)
17829            .expect("trait stata path without index");
17830        let via_path = read_stata(&path).expect("read trait stata path");
17831        assert_eq!(via_path.column_names(), roundtrip.column_names());
17832
17833        assert_eq!(
17834            source.to_stata_bytes().expect("trait stata bytes"),
17835            write_stata_bytes(&source).expect("free stata bytes")
17836        );
17837    }
17838
17839    #[test]
17840    fn stata_writer_rejects_invalid_variable_names_and_malformed_input() {
17841        let mut columns = BTreeMap::new();
17842        columns.insert(
17843            "bad-name".to_owned(),
17844            Column::from_values(vec![Scalar::Int64(1)]).expect("bad column"),
17845        );
17846        let frame = DataFrame::new_with_column_order(
17847            Index::from_i64(vec![0]),
17848            columns,
17849            vec!["bad-name".to_owned()],
17850        )
17851        .expect("frame with invalid stata column");
17852
17853        let err = write_stata_bytes(&frame).expect_err("invalid stata variable name");
17854        assert!(matches!(
17855            err,
17856            IoError::Stata(message) if message.contains("invalid Stata variable name")
17857        ));
17858
17859        let source = make_stata_dataframe();
17860        let err = write_stata_bytes_with_options(
17861            &source,
17862            &StataWriteOptions {
17863                include_index: true,
17864                index_label: Some("1bad".to_owned()),
17865            },
17866        )
17867        .expect_err("invalid index variable name");
17868        assert!(matches!(
17869            err,
17870            IoError::Stata(message) if message.contains("first character")
17871        ));
17872
17873        let err = read_stata_bytes(b"not a dta").expect_err("malformed stata");
17874        assert!(matches!(err, IoError::Stata(_)));
17875    }
17876
17877    #[test]
17878    fn xml_writer_defaults_to_index_and_escapes_values() {
17879        let frame = make_table_format_dataframe();
17880
17881        let out = write_xml_string(&frame).expect("xml");
17882
17883        assert_eq!(
17884            out,
17885            concat!(
17886                "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n",
17887                "<data>\n",
17888                "  <row>\n",
17889                "    <row>r&amp;1</row>\n",
17890                "    <name>A|B</name>\n",
17891                "    <value/>\n",
17892                "  </row>\n",
17893                "  <row>\n",
17894                "    <row>r_2</row>\n",
17895                "    <name>under_score</name>\n",
17896                "    <value>2.0</value>\n",
17897                "  </row>\n",
17898                "</data>\n",
17899            )
17900        );
17901    }
17902
17903    #[test]
17904    fn xml_writer_options_can_omit_index_and_reject_bad_names() {
17905        let frame = make_table_format_dataframe();
17906
17907        let out = write_xml_string_with_options(
17908            &frame,
17909            &XmlWriteOptions {
17910                include_index: false,
17911                root_name: "records".to_owned(),
17912                row_name: "entry".to_owned(),
17913                index_label: Some("ignored".to_owned()),
17914            },
17915        )
17916        .expect("xml");
17917
17918        assert_eq!(
17919            out,
17920            concat!(
17921                "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n",
17922                "<records>\n",
17923                "  <entry>\n",
17924                "    <name>A|B</name>\n",
17925                "    <value/>\n",
17926                "  </entry>\n",
17927                "  <entry>\n",
17928                "    <name>under_score</name>\n",
17929                "    <value>2.0</value>\n",
17930                "  </entry>\n",
17931                "</records>\n",
17932            )
17933        );
17934
17935        let err = write_xml_string_with_options(
17936            &frame,
17937            &XmlWriteOptions {
17938                root_name: "bad name".to_owned(),
17939                ..Default::default()
17940            },
17941        )
17942        .expect_err("invalid xml name");
17943        assert!(matches!(err, IoError::Xml(message) if message.contains("bad name")));
17944    }
17945
17946    #[test]
17947    fn xml_writer_escapes_text_like_pandas_etree() {
17948        let mut columns = BTreeMap::new();
17949        columns.insert(
17950            "name".to_owned(),
17951            Column::from_values(vec![Scalar::Utf8(
17952                "A&B <tag> \"quote\" it's\r\nnext".to_owned(),
17953            )])
17954            .expect("name column"),
17955        );
17956        let frame = DataFrame::new_with_column_order(
17957            Index::new(vec![IndexLabel::Utf8("idx".to_owned())]),
17958            columns,
17959            vec!["name".to_owned()],
17960        )
17961        .expect("xml escape frame");
17962
17963        assert_eq!(
17964            write_xml_string_with_options(
17965                &frame,
17966                &XmlWriteOptions {
17967                    include_index: false,
17968                    ..Default::default()
17969                },
17970            )
17971            .expect("xml"),
17972            concat!(
17973                "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n",
17974                "<data>\n",
17975                "  <row>\n",
17976                "    <name>A&amp;B &lt;tag&gt; \"quote\" it's\n",
17977                "next</name>\n",
17978                "  </row>\n",
17979                "</data>\n",
17980            )
17981        );
17982    }
17983
17984    #[test]
17985    fn xml_writer_file_output_and_extension_aliases_match_free_functions() {
17986        use super::DataFrameIoExt;
17987
17988        let frame = make_table_format_dataframe();
17989        let path = std::env::temp_dir().join(format!(
17990            "fp_io_xml_writer_{}_{}.xml",
17991            std::process::id(),
17992            line!()
17993        ));
17994
17995        write_xml(&frame, &path).expect("write xml");
17996        assert_eq!(
17997            std::fs::read_to_string(&path).expect("read xml"),
17998            write_xml_string(&frame).expect("xml string")
17999        );
18000        assert_eq!(
18001            frame.to_xml_string().expect("trait xml string"),
18002            write_xml_string(&frame).expect("free xml string")
18003        );
18004
18005        let trait_path = std::env::temp_dir().join(format!(
18006            "fp_io_xml_writer_trait_alias_{}_{}.xml",
18007            std::process::id(),
18008            line!()
18009        ));
18010        frame.to_xml(&trait_path).expect("trait xml alias");
18011        assert_eq!(
18012            std::fs::read_to_string(&trait_path).expect("read trait xml alias"),
18013            write_xml_string(&frame).expect("free xml string")
18014        );
18015
18016        let no_index_options = XmlWriteOptions {
18017            include_index: false,
18018            ..Default::default()
18019        };
18020        let no_index_path = std::env::temp_dir().join(format!(
18021            "fp_io_xml_writer_no_index_{}_{}.xml",
18022            std::process::id(),
18023            line!()
18024        ));
18025        frame
18026            .to_xml_file_with_options(&no_index_path, &no_index_options)
18027            .expect("trait xml file");
18028        assert_eq!(
18029            std::fs::read_to_string(&no_index_path).expect("read trait xml"),
18030            write_xml_string_with_options(&frame, &no_index_options).expect("free xml options")
18031        );
18032    }
18033
18034    #[test]
18035    fn xml_reader_parses_pandas_row_shape_and_empty_values() {
18036        let xml = concat!(
18037            "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n",
18038            "<data>\n",
18039            "  <row>\n",
18040            "    <index>0</index>\n",
18041            "    <a>1</a>\n",
18042            "    <b/>\n",
18043            "  </row>\n",
18044            "  <row>\n",
18045            "    <index>1</index>\n",
18046            "    <a>2.5</a>\n",
18047            "    <b>x</b>\n",
18048            "  </row>\n",
18049            "</data>\n",
18050        );
18051
18052        let frame = read_xml_str(xml).expect("read xml");
18053
18054        assert_eq!(
18055            frame
18056                .column_names()
18057                .into_iter()
18058                .map(String::as_str)
18059                .collect::<Vec<_>>(),
18060            vec!["index", "a", "b"]
18061        );
18062        assert_eq!(
18063            frame.index().labels(),
18064            &[IndexLabel::Int64(0), IndexLabel::Int64(1)]
18065        );
18066        assert_eq!(
18067            frame.column("index").expect("index").values()[0],
18068            Scalar::Int64(0)
18069        );
18070        assert_eq!(
18071            frame.column("a").expect("a").values()[1],
18072            Scalar::Float64(2.5)
18073        );
18074        assert!(matches!(
18075            frame.column("b").expect("b").values()[0],
18076            Scalar::Null(NullKind::Null)
18077        ));
18078        assert_eq!(
18079            frame.column("b").expect("b").values()[1],
18080            Scalar::Utf8("x".to_owned())
18081        );
18082    }
18083
18084    #[test]
18085    fn xml_reader_roundtrips_writer_output_as_columns() {
18086        let source = make_table_format_dataframe();
18087        let xml = write_xml_string(&source).expect("write xml");
18088
18089        let frame = read_xml_str(&xml).expect("read writer xml");
18090
18091        assert_eq!(
18092            frame
18093                .column_names()
18094                .into_iter()
18095                .map(String::as_str)
18096                .collect::<Vec<_>>(),
18097            vec!["row", "name", "value"]
18098        );
18099        assert_eq!(
18100            frame.column("row").expect("row").values()[0],
18101            Scalar::Utf8("r&1".to_owned())
18102        );
18103        assert_eq!(
18104            frame.column("name").expect("name").values()[0],
18105            Scalar::Utf8("A|B".to_owned())
18106        );
18107        assert!(frame.column("value").expect("value").values()[0].is_missing());
18108        assert_eq!(
18109            frame.column("value").expect("value").values()[1],
18110            Scalar::Float64(2.0)
18111        );
18112    }
18113
18114    #[test]
18115    fn xml_reader_unescapes_text_and_supports_custom_row_names() {
18116        let xml = concat!(
18117            "<records>\n",
18118            "  <entry><name>A&amp;B &lt;tag&gt; \"quote\" it's</name><flag>True</flag></entry>\n",
18119            "  <entry><name>line\n",
18120            "next</name><flag>false</flag></entry>\n",
18121            "</records>\n",
18122        );
18123
18124        let frame = read_xml_str_with_options(
18125            xml,
18126            &XmlReadOptions {
18127                row_name: "entry".to_owned(),
18128            },
18129        )
18130        .expect("read custom xml");
18131
18132        assert_eq!(
18133            frame.column("name").expect("name").values()[0],
18134            Scalar::Utf8("A&B <tag> \"quote\" it's".to_owned())
18135        );
18136        assert_eq!(
18137            frame.column("name").expect("name").values()[1],
18138            Scalar::Utf8("line\nnext".to_owned())
18139        );
18140        assert_eq!(
18141            frame.column("flag").expect("flag").values()[0],
18142            Scalar::Bool(true)
18143        );
18144        assert_eq!(
18145            frame.column("flag").expect("flag").values()[1],
18146            Scalar::Bool(false)
18147        );
18148    }
18149
18150    #[test]
18151    fn xml_reader_path_reader_matches_string_reader() {
18152        use std::io::Write;
18153
18154        let xml = "<data><row><name>A</name></row></data>\n";
18155        let path = std::env::temp_dir().join(format!(
18156            "fp_io_xml_reader_{}_{}.xml",
18157            std::process::id(),
18158            line!()
18159        ));
18160        let mut file = std::fs::OpenOptions::new()
18161            .write(true)
18162            .create_new(true)
18163            .open(&path)
18164            .expect("create xml fixture");
18165        file.write_all(xml.as_bytes()).expect("write xml fixture");
18166
18167        let via_path = read_xml(&path).expect("read path xml");
18168        let via_str = read_xml_str(xml).expect("read string xml");
18169
18170        assert_eq!(via_path.column_names(), via_str.column_names());
18171        assert_eq!(
18172            via_path.column("name").expect("path name").values(),
18173            via_str.column("name").expect("str name").values()
18174        );
18175    }
18176
18177    #[test]
18178    fn xml_reader_rejects_malformed_nested_and_duplicate_fields() {
18179        let malformed = "<data><row><name>A</row></data>";
18180        assert!(matches!(read_xml_str(malformed), Err(IoError::Xml(_))));
18181
18182        let nested = "<data><row><name><inner>A</inner></name></row></data>";
18183        let err = read_xml_str(nested).expect_err("nested field error");
18184        assert!(matches!(err, IoError::Xml(message) if message.contains("nested xml element")));
18185
18186        let duplicate = "<data><row><name>A</name><name>B</name></row></data>";
18187        let err = read_xml_str(duplicate).expect_err("duplicate field error");
18188        assert!(matches!(err, IoError::Xml(message) if message.contains("duplicate xml field")));
18189    }
18190
18191    // === AG-07-T: CSV Parser Optimization Tests ===
18192
18193    #[test]
18194    fn test_csv_vec_based_column_order() {
18195        // Verify Vec-based parser preserves header-to-data mapping exactly.
18196        // BTreeMap sorts alphabetically, so we use alpha-ordered headers.
18197        let input = "alpha,bravo,charlie\n1,2,3\n4,5,6\n";
18198        let frame = read_csv_str(input).expect("parse");
18199        let keys: Vec<&String> = frame.columns().keys().collect();
18200        assert_eq!(keys, &["alpha", "bravo", "charlie"]);
18201        assert_eq!(frame.column("alpha").unwrap().values()[0], Scalar::Int64(1));
18202        assert_eq!(frame.column("bravo").unwrap().values()[0], Scalar::Int64(2));
18203        assert_eq!(
18204            frame.column("charlie").unwrap().values()[1],
18205            Scalar::Int64(6)
18206        );
18207        eprintln!("[TEST] test_csv_vec_based_column_order | rows=2 cols=3 parse_ok=true | PASS");
18208    }
18209
18210    #[test]
18211    fn read_csv_object_fallback_preserves_original_text() {
18212        // pandas does column-level inference: when a column falls back to object
18213        // dtype, every non-NA cell keeps its VERBATIM source text. A bool-like
18214        // token in non-canonical case ("true") or a zero-padded number ("01")
18215        // must survive unchanged once the column is object. Verified vs live
18216        // pandas 2.2.3: read_csv('c\ntrue\nfalse\nmaybe\n')['c'] is
18217        // ['true','false','maybe'] (object), and '01'/'02' stay '01'/'02'.
18218        let cases: &[(&str, &str)] = &[
18219            // Uniform native columns are unaffected.
18220            ("c\n1\n2\n3\n", "c\n1\n2\n3\n"),
18221            ("c\ntrue\nfalse\n", "c\nTrue\nFalse\n"), // pure bool -> bool dtype
18222            // Object fallbacks keep original literals.
18223            ("c\n1\n2\nabc\n", "c\n1\n2\nabc\n"),
18224            ("c\ntrue\nfalse\nmaybe\n", "c\ntrue\nfalse\nmaybe\n"),
18225            ("c\nTrue\nFalse\nmaybe\n", "c\nTrue\nFalse\nmaybe\n"),
18226            ("c\n01\n02\nabc\n", "c\n01\n02\nabc\n"),
18227        ];
18228        for (input, expected_csv) in cases {
18229            let frame = read_csv_str(input).expect("read");
18230            let out = write_csv_string(&frame).expect("write");
18231            assert_eq!(
18232                &out, expected_csv,
18233                "round-trip mismatch for input {input:?}"
18234            );
18235        }
18236    }
18237
18238    #[test]
18239    fn read_csv_typed_numeric_fast_path_promotes_in_one_pass() {
18240        let input = "i,f\n1,0\n2,0.5\n3,1.25\n";
18241        let headers = vec!["i".to_owned(), "f".to_owned()];
18242
18243        let fast = super::try_read_csv_str_typed_numeric(input, &headers)
18244            .expect("typed parse")
18245            .expect("numeric fast path");
18246        assert_eq!(fast.column("i").expect("i").dtype(), DType::Int64);
18247        assert_eq!(fast.column("f").expect("f").dtype(), DType::Float64);
18248        assert_eq!(fast.column("i").expect("i").values()[2], Scalar::Int64(3));
18249        assert_eq!(
18250            fast.column("f").expect("f").values()[2],
18251            Scalar::Float64(1.25)
18252        );
18253
18254        let object_input = "c\n01\nabc\n";
18255        let object_headers = vec!["c".to_owned()];
18256        assert!(
18257            super::try_read_csv_str_typed_numeric(object_input, &object_headers)
18258                .expect("object probe")
18259                .is_none()
18260        );
18261        let object_frame = read_csv_str(object_input).expect("fallback read");
18262        assert_eq!(object_frame.index().int64_unit_range_labels(), Some((0, 2)));
18263        assert_eq!(
18264            write_csv_string(&object_frame).expect("fallback write"),
18265            object_input
18266        );
18267    }
18268
18269    #[test]
18270    fn read_csv_simple_typed_numeric_fast_path_builds_typed_columns() {
18271        let input = "i,f\n1,0\n2,0.5\n3,1.25\n";
18272        let headers = vec!["i".to_owned(), "f".to_owned()];
18273
18274        let fast = super::try_read_csv_str_simple_typed_numeric(input, &headers)
18275            .expect("simple typed parse")
18276            .expect("simple numeric fast path");
18277
18278        assert_eq!(fast.column("i").expect("i").dtype(), DType::Int64);
18279        assert_eq!(fast.column("f").expect("f").dtype(), DType::Float64);
18280        assert_eq!(fast.index().int64_unit_range_labels(), Some((0, 3)));
18281        assert_eq!(fast.index().labels()[2], IndexLabel::Int64(2));
18282        assert_eq!(fast.column("i").expect("i").values()[2], Scalar::Int64(3));
18283        assert_eq!(
18284            fast.column("f").expect("f").values()[2],
18285            Scalar::Float64(1.25)
18286        );
18287    }
18288
18289    #[test]
18290    fn read_csv_mixed_quoted_unquoted_numeric_infers_numeric_3gen4() {
18291        // br-frankenpandas-3gen4: quoting is per-field CSV syntax stripped before
18292        // type inference, so a column mixing quoted + unquoted numbers still
18293        // infers a numeric dtype (pandas parity).
18294        let int_col = read_csv_str("x\n1\n\"2\"\n3\n").expect("read int");
18295        let xi = int_col.column("x").expect("x");
18296        assert_eq!(
18297            xi.dtype(),
18298            DType::Int64,
18299            "mixed quoted/unquoted ints -> Int64"
18300        );
18301        assert_eq!(
18302            xi.values(),
18303            &[Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)]
18304        );
18305
18306        // Mixed int + quoted float -> Float64 (one float promotes the column).
18307        let float_col = read_csv_str("y\n1\n\"2.5\"\n3\n").expect("read float");
18308        let yf = float_col.column("y").expect("y");
18309        assert_eq!(
18310            yf.dtype(),
18311            DType::Float64,
18312            "mixed int + quoted float -> Float64"
18313        );
18314        assert_eq!(
18315            yf.values(),
18316            &[
18317                Scalar::Float64(1.0),
18318                Scalar::Float64(2.5),
18319                Scalar::Float64(3.0)
18320            ]
18321        );
18322    }
18323
18324    #[test]
18325    fn read_csv_simple_typed_numeric_fast_path_rejects_quoted_fields() {
18326        let input = "x\n\"1.5\"\n";
18327        let headers = vec!["x".to_owned()];
18328
18329        assert!(
18330            super::try_read_csv_str_simple_typed_numeric(input, &headers)
18331                .expect("simple probe")
18332                .is_none()
18333        );
18334
18335        let frame = read_csv_str(input).expect("fallback read");
18336        assert_eq!(frame.column("x").expect("x").dtype(), DType::Float64);
18337        assert_eq!(
18338            frame.column("x").expect("x").values(),
18339            &[Scalar::Float64(1.5)]
18340        );
18341    }
18342
18343    #[test]
18344    fn read_csv_simple_typed_numeric_fast_path_accepts_crlf_rows() {
18345        let input = "i,f\n1,0\r\n2,0.5\r\n";
18346        let headers = vec!["i".to_owned(), "f".to_owned()];
18347
18348        let fast = super::try_read_csv_str_simple_typed_numeric(input, &headers)
18349            .expect("simple typed parse")
18350            .expect("simple numeric fast path");
18351
18352        assert_eq!(fast.len(), 2);
18353        assert_eq!(fast.column("i").expect("i").values()[1], Scalar::Int64(2));
18354        assert_eq!(
18355            fast.column("f").expect("f").values()[1],
18356            Scalar::Float64(0.5)
18357        );
18358    }
18359
18360    #[test]
18361    fn read_csv_simple_parallel_chunks_preserve_order_and_promotion() {
18362        use std::fmt::Write as _;
18363
18364        let headers = vec!["i".to_owned(), "f".to_owned()];
18365        let mut data = String::new();
18366        for row in 0..32 {
18367            let float_value = row as f64 * 0.25;
18368            writeln!(data, "{row},{float_value}").expect("write row");
18369        }
18370
18371        let (columns, row_count) =
18372            super::parse_simple_numeric_csv_parallel_chunks(data.as_bytes(), headers.len(), 3)
18373                .expect("parallel chunk parse");
18374        let frame = super::build_typed_numeric_csv_frame(&headers, columns, row_count)
18375            .expect("frame build");
18376
18377        assert_eq!(frame.len(), 32);
18378        assert_eq!(frame.column("i").expect("i").dtype(), DType::Int64);
18379        assert_eq!(frame.column("f").expect("f").dtype(), DType::Float64);
18380        assert_eq!(frame.column("i").expect("i").values()[0], Scalar::Int64(0));
18381        assert_eq!(
18382            frame.column("i").expect("i").values()[31],
18383            Scalar::Int64(31)
18384        );
18385        assert_eq!(
18386            frame.column("f").expect("f").values()[31],
18387            Scalar::Float64(7.75)
18388        );
18389    }
18390
18391    #[test]
18392    fn read_csv_typed_numeric_fast_path_rejects_non_all_valid_numeric_semantics() {
18393        let headers = vec!["x".to_owned()];
18394        for input in [
18395            "x\nNaN\n1.0\n",
18396            "x\nNAN\n1.0\n",
18397            "x\n+NaN\n1.0\n",
18398            "x\n NaN \n1.0\n",
18399            "x\n\"NAN\"\n1.0\n",
18400            "x\ntrue\nfalse\n",
18401            "x\n \n1\n",
18402        ] {
18403            assert!(
18404                super::try_read_csv_str_typed_numeric(input, &headers)
18405                    .expect("probe")
18406                    .is_none(),
18407                "fast path must reject {input:?}"
18408            );
18409        }
18410
18411        let nan_frame = read_csv_str("x\nNaN\n1.0\n").expect("fallback nan");
18412        assert_eq!(
18413            nan_frame.column("x").expect("x").values(),
18414            &[Scalar::Null(NullKind::NaN), Scalar::Float64(1.0)]
18415        );
18416
18417        let bool_frame = read_csv_str("x\ntrue\nfalse\n").expect("fallback bool");
18418        assert_eq!(
18419            bool_frame.column("x").expect("x").values(),
18420            &[Scalar::Bool(true), Scalar::Bool(false)]
18421        );
18422
18423        let padded_nan_frame = read_csv_str("x\n NaN \n1.0\n").expect("fallback padded nan");
18424        let padded_nan_column = padded_nan_frame.column("x").expect("x");
18425        assert!(padded_nan_column.has_nulls());
18426        assert!(!padded_nan_column.validity().get(0));
18427        assert!(padded_nan_column.values()[0].is_missing());
18428    }
18429
18430    #[test]
18431    fn read_csv_typed_numeric_fast_path_keeps_all_valid_float_edges() {
18432        let input = "x\n-0.0\ninf\n-inf\n1\n";
18433        let headers = vec!["x".to_owned()];
18434        let frame = super::try_read_csv_str_typed_numeric(input, &headers)
18435            .expect("typed parse")
18436            .expect("numeric fast path");
18437        let column = frame.column("x").expect("x");
18438
18439        assert_eq!(column.dtype(), DType::Float64);
18440        assert!(!column.has_nulls());
18441        assert!(column.validity().all());
18442        let values = column.values();
18443        assert_eq!(
18444            values,
18445            &[
18446                Scalar::Float64(-0.0),
18447                Scalar::Float64(f64::INFINITY),
18448                Scalar::Float64(f64::NEG_INFINITY),
18449                Scalar::Float64(1.0)
18450            ]
18451        );
18452        let negative_zero_bits = match values[0] {
18453            Scalar::Float64(value) => Some(value.to_bits()),
18454            _ => None,
18455        };
18456        assert_eq!(negative_zero_bits, Some((-0.0f64).to_bits()));
18457    }
18458
18459    #[test]
18460    fn read_csv_typed_numeric_fast_path_preserves_ragged_row_errors() {
18461        // The numeric fast path runs `flexible(true)` like every other reader,
18462        // so it must enforce an overlong row once the body is not uniformly
18463        // eligible for pandas' implicit-index rule (azv2h).
18464        let long_row = "a,b\n1,2,3\n4,5\n";
18465        let err = read_csv_str(long_row).expect_err("long row must reject");
18466        assert!(
18467            matches!(
18468                err,
18469                IoError::CsvFieldCount {
18470                    line: 2,
18471                    expected: 2,
18472                    found: 3
18473                }
18474            ),
18475            "got {err:?}"
18476        );
18477    }
18478
18479    #[test]
18480    fn read_csv_typed_bool_builder_uses_nullable_backing_and_rejects_ragged_rows_3gsa7() {
18481        let frame = read_csv_str("flag\nTrue\nNA\nfalse\n").expect("typed bool csv");
18482        let flag = frame.column("flag").expect("flag column");
18483
18484        assert_eq!(flag.dtype(), DType::Bool);
18485        let (values, validity) = flag
18486            .as_nullable_bool_slice()
18487            .expect("typed nullable Bool backing");
18488        assert_eq!(values, &[true, false, false]);
18489        assert!(validity.get(0));
18490        assert!(!validity.get(1));
18491        assert!(validity.get(2));
18492        assert_eq!(
18493            flag.values(),
18494            &[
18495                Scalar::Bool(true),
18496                Scalar::Null(NullKind::Null),
18497                Scalar::Bool(false)
18498            ]
18499        );
18500
18501        // A prior numeric value is semantically ambiguous with Bool and must
18502        // keep the legacy Scalar fallback, rather than being retyped as Bool.
18503        let mixed = read_csv_str("flag\n1\ntrue\n").expect("mixed csv fallback");
18504        assert_eq!(
18505            mixed.column("flag").expect("mixed flag").dtype(),
18506            DType::Utf8
18507        );
18508
18509        let err =
18510            read_csv_str("flag\ntrue,false\nfalse\n").expect_err("overlong ragged row must reject");
18511        assert!(
18512            matches!(
18513                err,
18514                IoError::CsvFieldCount {
18515                    line: 2,
18516                    expected: 1,
18517                    found: 2
18518                }
18519            ),
18520            "got {err:?}"
18521        );
18522    }
18523
18524    /// The same fast path must PAD a short row rather than reject it — the
18525    /// gtkz1 fixture's own input (fp_p2d_016_csv_round_trip_ragged_row_error).
18526    /// Measured: pd.read_csv("a,b\n1,2\n3\n") -> a=[1,3], b=[2.0, NaN].
18527    /// Both paths must infer `b` as Float64 because pandas' numpy-style int64
18528    /// inference widens when a short row introduces an NA.
18529    #[test]
18530    fn read_csv_typed_numeric_fast_path_pads_short_row() {
18531        let df = read_csv_str("a,b\n1,2\n3\n").expect("short row pads");
18532        assert_eq!(
18533            df.columns()["a"].values(),
18534            &[Scalar::Int64(1), Scalar::Int64(3)]
18535        );
18536        let b = df.columns()["b"].values();
18537        assert_eq!(df.columns()["b"].dtype(), DType::Float64);
18538        assert_eq!(b[0], Scalar::Float64(2.0));
18539        assert!(b[1].is_missing(), "padded 'b' must be NA, got {:?}", b[1]);
18540    }
18541
18542    #[test]
18543    fn to_csv_datetime_is_column_uniform_like_pandas() {
18544        // pandas to_csv renders a datetime column with ONE format: date-only
18545        // when all values are midnight, else YYYY-MM-DD HH:MM:SS with a
18546        // sub-second suffix sized to the column's finest resolution. Verified
18547        // vs live pandas 2.2.3. (Previously format_datetime_ns dropped the
18548        // sub-second component and always wrote 00:00:00.)
18549        fn dt_frame(nanos: &[i64]) -> DataFrame {
18550            let values: Vec<Scalar> = nanos.iter().map(|&n| Scalar::Datetime64(n)).collect();
18551            let col = Column::new(DType::datetime64_naive(), values).expect("col");
18552            let mut cols = BTreeMap::new();
18553            cols.insert("d".to_string(), col);
18554            let index = Index::from_i64((0..nanos.len() as i64).collect());
18555            DataFrame::new_with_column_order(index, cols, vec!["d".to_string()]).expect("frame")
18556        }
18557        const MIDNIGHT_JAN1: i64 = 1_577_836_800_000_000_000; // 2020-01-01 00:00:00Z
18558        const MIDNIGHT_JAN2: i64 = 1_577_923_200_000_000_000; // 2020-01-02 00:00:00Z
18559        const JAN2_0300: i64 = 1_577_934_000_000_000_000; // 2020-01-02 03:00:00Z
18560        const JAN1_HALF: i64 = 1_577_836_800_500_000_000; // 2020-01-01 00:00:00.5Z
18561
18562        // All midnight -> date only.
18563        assert_eq!(
18564            write_csv_string(&dt_frame(&[MIDNIGHT_JAN1, MIDNIGHT_JAN2])).expect("w"),
18565            "d\n2020-01-01\n2020-01-02\n"
18566        );
18567        // Sub-second present -> whole column gets .fff (millis), incl. .000.
18568        assert_eq!(
18569            write_csv_string(&dt_frame(&[JAN1_HALF, MIDNIGHT_JAN1])).expect("w"),
18570            "d\n2020-01-01 00:00:00.500\n2020-01-01 00:00:00.000\n"
18571        );
18572        // Time present, no sub-second -> HH:MM:SS for all (midnight -> 00:00:00).
18573        assert_eq!(
18574            write_csv_string(&dt_frame(&[JAN2_0300, MIDNIGHT_JAN1])).expect("w"),
18575            "d\n2020-01-02 03:00:00\n2020-01-01 00:00:00\n"
18576        );
18577        // NaT in an otherwise date-only column -> date only, NaT -> quoted "".
18578        assert_eq!(
18579            write_csv_string(&dt_frame(&[MIDNIGHT_JAN1, i64::MIN])).expect("w"),
18580            "d\n2020-01-01\n\"\"\n"
18581        );
18582    }
18583
18584    #[test]
18585    #[ignore = "foreground release A/B harness"]
18586    fn datetime_csv_format_raw_nanos_ab_vrflh() {
18587        const ROWS: usize = 131_072;
18588        const BLOCKS: usize = 5;
18589        const BASE: i64 = 1_577_836_800_000_000_000;
18590
18591        fn former(column: &Column) -> super::DatetimeCsvFormat {
18592            super::datetime_csv_format_from_nanos(column.values().iter().filter_map(|value| {
18593                let Scalar::Datetime64(nanos) = value else {
18594                    return None;
18595                };
18596                Some(*nanos)
18597            }))
18598        }
18599
18600        fn elapsed(nanos: &[i64], use_candidate: bool) -> (u128, super::DatetimeCsvFormat) {
18601            let column = Column::from_datetime64_values(nanos.to_vec());
18602            let started = std::time::Instant::now();
18603            let format = if use_candidate {
18604                super::datetime_csv_format(&column)
18605            } else {
18606                former(&column)
18607            };
18608            let elapsed = started.elapsed().as_nanos();
18609            std::hint::black_box((format.date_only, format.subsec_digits));
18610            (elapsed, format)
18611        }
18612
18613        fn median(mut samples: Vec<u128>) -> u128 {
18614            samples.sort_unstable();
18615            samples[samples.len() / 2]
18616        }
18617
18618        let mut nanos = (0..ROWS)
18619            .map(|row| BASE + row as i64 * 37_000_000_000)
18620            .collect::<Vec<_>>();
18621        nanos[ROWS / 3] += 500_000_000;
18622        nanos[ROWS - 1] = Timestamp::NAT;
18623
18624        let (_, former_format) = elapsed(&nanos, false);
18625        let (_, candidate_format) = elapsed(&nanos, true);
18626        assert_eq!(candidate_format.date_only, former_format.date_only);
18627        assert_eq!(candidate_format.subsec_digits, former_format.subsec_digits);
18628
18629        let mut former_samples = Vec::with_capacity(BLOCKS * 2);
18630        let mut candidate_samples = Vec::with_capacity(BLOCKS * 2);
18631        for block in 0..BLOCKS {
18632            let order = if block % 2 == 0 {
18633                [false, true, true, false]
18634            } else {
18635                [true, false, false, true]
18636            };
18637            for use_candidate in order {
18638                let (elapsed_ns, format) = elapsed(&nanos, use_candidate);
18639                assert_eq!(format.date_only, former_format.date_only);
18640                assert_eq!(format.subsec_digits, former_format.subsec_digits);
18641                if use_candidate {
18642                    candidate_samples.push(elapsed_ns);
18643                } else {
18644                    former_samples.push(elapsed_ns);
18645                }
18646            }
18647        }
18648
18649        let former_ns = median(former_samples);
18650        let candidate_ns = median(candidate_samples);
18651        println!(
18652            "DATETIME_CSV_FORMAT_SCAN_AB rows={ROWS} former_ns={former_ns} candidate_ns={candidate_ns} speedup={:.6}",
18653            former_ns as f64 / candidate_ns as f64
18654        );
18655    }
18656
18657    #[test]
18658    fn to_csv_datetime_index_is_column_uniform_like_pandas() {
18659        use super::{CsvWriteOptions, write_csv_string_with_options};
18660        // A DatetimeIndex written with index=True follows the same column-
18661        // uniform rule as a datetime column. Verified vs live pandas 2.2.3.
18662        fn dt_index_frame(nanos: &[i64]) -> DataFrame {
18663            let labels: Vec<IndexLabel> =
18664                nanos.iter().map(|&n| IndexLabel::Datetime64(n)).collect();
18665            let index = Index::new(labels);
18666            let values: Vec<Scalar> = (0..nanos.len() as i64).map(Scalar::Int64).collect();
18667            let col = Column::new(DType::Int64, values).expect("col");
18668            let mut cols = BTreeMap::new();
18669            cols.insert("v".to_string(), col);
18670            DataFrame::new_with_column_order(index, cols, vec!["v".to_string()]).expect("frame")
18671        }
18672        let opts = CsvWriteOptions {
18673            include_index: true,
18674            ..Default::default()
18675        };
18676        // All midnight -> date only.
18677        assert_eq!(
18678            write_csv_string_with_options(
18679                &dt_index_frame(&[1_577_836_800_000_000_000, 1_577_923_200_000_000_000]),
18680                &opts
18681            )
18682            .expect("w"),
18683            ",v\n2020-01-01,0\n2020-01-02,1\n"
18684        );
18685        // Sub-second (ms) -> .fff on every label.
18686        assert_eq!(
18687            write_csv_string_with_options(
18688                &dt_index_frame(&[1_577_836_800_500_000_000, 1_577_836_800_250_000_000]),
18689                &opts
18690            )
18691            .expect("w"),
18692            ",v\n2020-01-01 00:00:00.500,0\n2020-01-01 00:00:00.250,1\n"
18693        );
18694    }
18695
18696    #[test]
18697    fn to_json_nat_index_label_is_null_not_sentinel_epoch_natjson() {
18698        use super::{JsonOrient, write_json_string};
18699        // A DatetimeIndex containing NaT (the i64::MIN sentinel): the index label
18700        // must serialize as JSON null, NOT i64::MIN/1e6 (-9223372036854775).
18701        let labels = vec![
18702            IndexLabel::Datetime64(1_577_836_800_000_000_000), // 2020-01-01
18703            IndexLabel::Datetime64(i64::MIN),                  // NaT
18704        ];
18705        let index = Index::new(labels);
18706        let col = Column::new(DType::Int64, vec![Scalar::Int64(7), Scalar::Int64(9)]).expect("col");
18707        let mut cols = BTreeMap::new();
18708        cols.insert("v".to_string(), col);
18709        let frame =
18710            DataFrame::new_with_column_order(index, cols, vec!["v".to_string()]).expect("frame");
18711
18712        // The garbage sentinel epoch must never appear in any orient.
18713        for orient in [
18714            JsonOrient::Split,
18715            JsonOrient::Records,
18716            JsonOrient::Columns,
18717            JsonOrient::Index,
18718        ] {
18719            let out = write_json_string(&frame, orient).expect("json");
18720            assert!(
18721                !out.contains("-9223372036854775"),
18722                "orient {orient:?} leaked the NaT sentinel epoch: {out}"
18723            );
18724        }
18725        // Split orient lists the index as values -> NaT becomes literal null.
18726        let split = write_json_string(&frame, JsonOrient::Split).expect("json");
18727        assert!(
18728            split.contains("null"),
18729            "NaT index label should be null in split orient: {split}"
18730        );
18731    }
18732
18733    #[test]
18734    fn index_label_to_scalar_value_preserves_temporal_dtype_mdt64() {
18735        // Materializing a MultiIndex level into a column must keep the level's
18736        // dtype: a Datetime64 label stays a typed Datetime64 scalar (like the
18737        // Timedelta64 arm), NOT a downgraded Utf8 string — otherwise a datetime
18738        // level becomes an object column (pandas keeps datetime64) and serializes
18739        // inconsistently with a single DatetimeIndex.
18740        assert_eq!(
18741            super::index_label_to_scalar_value(&IndexLabel::Datetime64(1_577_836_800_000_000_000)),
18742            Scalar::Datetime64(1_577_836_800_000_000_000)
18743        );
18744        assert_eq!(
18745            super::index_label_to_scalar_value(&IndexLabel::Timedelta64(86_400_000_000_000)),
18746            Scalar::Timedelta64(86_400_000_000_000)
18747        );
18748        // NaT sentinel stays the typed Datetime64 NaT (downstream writers map it
18749        // to na_rep / null), not the "NaT" literal a Utf8 downgrade produced.
18750        assert_eq!(
18751            super::index_label_to_scalar_value(&IndexLabel::Datetime64(i64::MIN)),
18752            Scalar::Datetime64(i64::MIN)
18753        );
18754    }
18755
18756    #[test]
18757    fn table_writers_render_temporal_nat_dtype_aware_tblnat() {
18758        // Verified vs pandas 2.2.3:
18759        //   to_string/to_markdown/to_html: temporal NaT -> "NaT", float NaN -> na_rep.
18760        //   to_latex:                       temporal NaT -> na_rep, float NaN -> na_rep.
18761        let na = "NaN";
18762        // markdown/string family (scalar_to_table_with_na): NaT literal, NaN -> na_rep.
18763        assert_eq!(
18764            super::scalar_to_table_with_na(&Scalar::Float64(f64::NAN), na),
18765            na
18766        );
18767        assert_eq!(
18768            super::scalar_to_table_with_na(&Scalar::Timedelta64(i64::MIN), na),
18769            "NaT"
18770        );
18771        assert_eq!(
18772            super::scalar_to_table_with_na(&Scalar::Datetime64(i64::MIN), na),
18773            "NaT"
18774        );
18775        assert_eq!(
18776            super::scalar_to_table_with_na(
18777                &Scalar::Period(fp_types::Period::new(i64::MIN, fp_types::PeriodFreq::Daily)),
18778                na
18779            ),
18780            "NaT"
18781        );
18782        // latex (scalar_to_latex_cell): ALL missing collapse to na_rep.
18783        assert_eq!(
18784            super::scalar_to_latex_cell(&Scalar::Float64(f64::NAN), na),
18785            na
18786        );
18787        assert_eq!(
18788            super::scalar_to_latex_cell(&Scalar::Timedelta64(i64::MIN), na),
18789            na
18790        );
18791        assert_eq!(
18792            super::scalar_to_latex_cell(&Scalar::Datetime64(i64::MIN), na),
18793            na
18794        );
18795        assert_eq!(
18796            super::scalar_to_latex_cell(
18797                &Scalar::Period(fp_types::Period::new(i64::MIN, fp_types::PeriodFreq::Daily)),
18798                na
18799            ),
18800            na
18801        );
18802        // A non-NaT datetime still renders normally (sanity).
18803        assert_eq!(
18804            super::scalar_to_table_with_na(&Scalar::Datetime64(1_577_836_800_000_000_000), na),
18805            "2020-01-01 00:00:00"
18806        );
18807    }
18808
18809    #[test]
18810    fn format_pandas_float_matches_python_str_float_at_boundaries() {
18811        // to_csv float cells use Python str(float): fixed notation for decimal
18812        // exponents in [-4, 16), scientific (signed 2-digit exp) outside. Each
18813        // expectation verified vs live pandas 2.2.3 `DataFrame({'v':[x]}).to_csv`.
18814        let cases: &[(f64, &str)] = &[
18815            (0.1, "0.1"),
18816            (1.0 / 3.0, "0.3333333333333333"),
18817            (1e16, "1e+16"),
18818            (1e-5, "1e-05"),
18819            (1e-4, "0.0001"),
18820            (123_456_789_012_345.6, "123456789012345.6"),
18821            (1e21, "1e+21"),
18822            (1e-7, "1e-07"),
18823            (-0.0, "-0.0"),
18824            // 9999999999999999.0 rounds to 1e16 in f64.
18825            (9_999_999_999_999_999.0, "1e+16"),
18826            (2.5e-8, "2.5e-08"),
18827            (1e17, "1e+17"),
18828            (0.00012345, "0.00012345"),
18829        ];
18830        for &(v, expected) in cases {
18831            assert_eq!(
18832                super::format_pandas_float(v),
18833                expected,
18834                "format_pandas_float({v:?})"
18835            );
18836        }
18837    }
18838
18839    #[test]
18840    fn skipinitialspace_preprocessor_strips_leading_field_spaces_i4h5g() {
18841        let f = |s: &str| super::apply_skipinitialspace(s, b',', b'"', true, None, None);
18842        // Leading spaces at every field start (first field + header + after
18843        // delimiter) stripped; trailing spaces kept; verified vs pandas 2.2.3.
18844        assert_eq!(f(" a,  b\n  x,  y  \n"), "a,b\nx,y  \n");
18845        // Space before a quoted field is stripped, the quote is then honored, and
18846        // spaces INSIDE the quotes are preserved.
18847        assert_eq!(f("a,b\nx,  \"  q,q  \"\n"), "a,b\nx,\"  q,q  \"\n");
18848        // Tabs are not stripped (only ASCII 0x20).
18849        assert_eq!(f("a,b\nx,\t y\n"), "a,b\nx,\t y\n");
18850        // An all-space field collapses to empty.
18851        assert_eq!(f("a,   ,b\n"), "a,,b\n");
18852        // Doubled quotes inside a quoted field stay intact.
18853        assert_eq!(f("a\n  \"x\"\"y\"\n"), "a\n\"x\"\"y\"\n");
18854    }
18855
18856    #[test]
18857    fn read_csv_skipinitialspace_strips_field_leading_spaces_i4h5g() {
18858        use super::{CsvReadOptions, read_csv_with_options, write_csv_string};
18859        let opts = CsvReadOptions {
18860            skipinitialspace: true,
18861            ..Default::default()
18862        };
18863        // Object columns: leading spaces at each field start are dropped.
18864        let frame = read_csv_with_options("k,v\n  aa,bb\n cc,  dd\n", &opts).expect("read");
18865        assert_eq!(
18866            write_csv_string(&frame).expect("write"),
18867            "k,v\naa,bb\ncc,dd\n"
18868        );
18869        // Default (skipinitialspace=false) keeps the leading spaces.
18870        let frame_def =
18871            read_csv_with_options("k,v\n  aa,bb\n", &CsvReadOptions::default()).expect("read");
18872        assert_eq!(
18873            write_csv_string(&frame_def).expect("write"),
18874            "k,v\n  aa,bb\n"
18875        );
18876    }
18877
18878    #[test]
18879    fn read_csv_with_options_object_fallback_preserves_text() {
18880        use super::{CsvReadOptions, read_csv_with_options};
18881        // Same pandas object-fallback rule on the options reader (custom
18882        // delimiter / na_values etc.): non-canonical bool casing and zero-padded
18883        // numbers survive once the column is object. Verified vs pandas 2.2.3.
18884        let tsv = CsvReadOptions {
18885            delimiter: b'\t',
18886            ..Default::default()
18887        };
18888        let frame = read_csv_with_options("c\ntrue\nfalse\nmaybe\n", &tsv).expect("read");
18889        assert_eq!(frame.index().int64_unit_range_labels(), Some((0, 3)));
18890        let out = write_csv_string(&frame).expect("write");
18891        assert_eq!(out, "c\ntrue\nfalse\nmaybe\n");
18892
18893        let frame2 = read_csv_with_options("c\n01\n02\nabc\n", &tsv).expect("read");
18894        let out2 = write_csv_string(&frame2).expect("write");
18895        assert_eq!(out2, "c\n01\n02\nabc\n");
18896
18897        // Pure-bool column still infers bool dtype (writes True/False).
18898        let frame3 = read_csv_with_options("c\ntrue\nfalse\n", &tsv).expect("read");
18899        let out3 = write_csv_string(&frame3).expect("write");
18900        assert_eq!(out3, "c\nTrue\nFalse\n");
18901
18902        // Custom na_values: an NA cell in an object column stays missing while
18903        // the surrounding original literals are preserved.
18904        let na_opts = CsvReadOptions {
18905            delimiter: b'\t',
18906            na_values: vec!["MISSING".to_string()],
18907            ..Default::default()
18908        };
18909        let frame4 = read_csv_with_options("c\ntrue\nMISSING\nmaybe\n", &na_opts).expect("read");
18910        let out4 = write_csv_string(&frame4).expect("write");
18911        // The lone empty NaN field in a single-column object frame is quoted "".
18912        assert_eq!(out4, "c\ntrue\n\"\"\nmaybe\n");
18913    }
18914
18915    #[test]
18916    fn to_csv_float_format_matches_pandas_str() {
18917        // pandas to_csv writes floats via Python str(float): whole numbers keep
18918        // ".0", decimals use the shortest round-trip, and extreme magnitudes use
18919        // signed two-digit scientific notation. Verified vs live pandas 2.2.3.
18920        let cases: &[(f64, &str)] = &[
18921            (0.0, "0.0"),
18922            (-0.0, "-0.0"),
18923            (1.0, "1.0"),
18924            (100.0, "100.0"),
18925            (0.1, "0.1"),
18926            (1.0 / 3.0, "0.3333333333333333"),
18927            (9999999999999999.0, "1e+16"),
18928            (1e16, "1e+16"),
18929            (1e20, "1e+20"),
18930            (0.0001, "0.0001"),
18931            (1e-5, "1e-05"),
18932            (1e-7, "1e-07"),
18933            (f64::MIN_POSITIVE / 2.0, "1.1125369292536007e-308"),
18934            (f64::INFINITY, "inf"),
18935            (f64::NEG_INFINITY, "-inf"),
18936        ];
18937        for (v, expected) in cases {
18938            assert_eq!(
18939                &format_pandas_float(*v),
18940                expected,
18941                "format_pandas_float({v})"
18942            );
18943        }
18944
18945        let col = Column::from_f64_values(vec![1.0, f64::NAN, 3.0]);
18946        let mut cols = BTreeMap::new();
18947        cols.insert("x".to_owned(), col);
18948        let frame = DataFrame::new_with_column_order(
18949            Index::from_i64((0..3).collect()),
18950            cols,
18951            vec!["x".to_owned()],
18952        )
18953        .expect("frame");
18954        let out = write_csv_string_with_options(
18955            &frame,
18956            &CsvWriteOptions {
18957                include_index: false,
18958                na_rep: "NA".to_owned(),
18959                ..Default::default()
18960            },
18961        )
18962        .expect("write");
18963        assert_eq!(out, "x\n1.0\nNA\n3.0\n");
18964    }
18965
18966    #[test]
18967    fn to_csv_quarter_affine_float_plan_matches_pandas_str_uza0481() {
18968        let values = (0..128)
18969            .map(|row| (row as f64 * 1.25) + 2.0)
18970            .collect::<Vec<_>>();
18971        let plan = Float64QuarterAffineCsvPlan::for_slice(&values).expect("quarter plan");
18972        let expected_cells = values
18973            .iter()
18974            .copied()
18975            .map(format_pandas_float)
18976            .collect::<Vec<_>>();
18977        let mut fast_cells = Vec::with_capacity(values.len());
18978        for row in 0..values.len() {
18979            let mut out = String::new();
18980            assert!(plan.append_row(&mut out, row));
18981            fast_cells.push(out);
18982        }
18983        assert_eq!(fast_cells, expected_cells);
18984
18985        let col = Column::from_f64_values(values);
18986        let mut cols = BTreeMap::new();
18987        cols.insert("x".to_owned(), col);
18988        let frame = DataFrame::new_with_column_order(
18989            Index::from_i64((0..128).collect()),
18990            cols,
18991            vec!["x".to_owned()],
18992        )
18993        .expect("frame");
18994        let out = write_csv_string_with_options(
18995            &frame,
18996            &CsvWriteOptions {
18997                include_index: false,
18998                ..Default::default()
18999            },
19000        )
19001        .expect("write");
19002        let mut expected = String::from("x\n");
19003        for cell in expected_cells {
19004            expected.push_str(&cell);
19005            expected.push('\n');
19006        }
19007        assert_eq!(out, expected);
19008    }
19009
19010    #[test]
19011    fn quarter_affine_float_plan_rejects_fallback_boundaries_uza0481() {
19012        let rejected: &[&[f64]] = &[
19013            &[-0.0, 1.25, 2.5],
19014            &[-1.25, 0.0, 1.25],
19015            &[0.0, f64::NAN, 2.5],
19016            &[0.0, f64::INFINITY, 2.5],
19017            &[0.1, 1.35, 2.6],
19018            &[0.0, 1.25, 2.75],
19019            &[1e16, 1e16 + 1.25],
19020        ];
19021        for values in rejected {
19022            assert!(
19023                Float64QuarterAffineCsvPlan::for_slice(values).is_none(),
19024                "unexpected quarter plan for {values:?}"
19025            );
19026        }
19027    }
19028
19029    #[test]
19030    fn to_csv_single_column_nan_quotes_empty_and_keeps_float_repr() {
19031        // The lone empty NaN field is already quoted as "" by the csv writer so
19032        // read_csv doesn't drop it (NOT a blank line). The real fix here is the
19033        // float repr: 1.0/3.0 must stay "1.0"/"3.0", not collapse to "1"/"3".
19034        let frame = read_csv_str("x\n1.0\nNaN\n3.0\n").expect("read");
19035        assert!(frame.column("x").unwrap().values()[1].is_missing());
19036        let out = write_csv_string(&frame).expect("write");
19037        assert_eq!(out, "x\n1.0\n\"\"\n3.0\n");
19038    }
19039
19040    #[test]
19041    fn to_csv_typed_single_empty_string_field_is_quoted_like_pandas() {
19042        // Oracle pandas 2.2.3 (csv QUOTE_MINIMAL): a SOLE empty field per record is
19043        // quoted "" so read_csv round-trips '' instead of a blank line -> NaN. An
19044        // all-valid contiguous Utf8 single column takes the typed fast path
19045        // (try_write_csv_typed), which previously emitted the empty cell bare.
19046        // DataFrame({'a':['','x','y']}).to_csv(index=False) -> 'a\n""\nx\ny\n'
19047        let col = Column::from_utf8_contiguous(b"xy".to_vec(), vec![0, 0, 1, 2]);
19048        // Sanity: this column is the all-valid contiguous Utf8 the typed path needs.
19049        assert!(col.as_utf8_contiguous().is_some());
19050        assert_eq!(col.value(0), Some(&Scalar::Utf8(String::new())));
19051        let mut columns = BTreeMap::new();
19052        columns.insert("a".to_string(), col);
19053        let frame = DataFrame::new_with_column_order(
19054            Index::new(vec![
19055                IndexLabel::Int64(0),
19056                IndexLabel::Int64(1),
19057                IndexLabel::Int64(2),
19058            ]),
19059            columns,
19060            vec!["a".to_string()],
19061        )
19062        .unwrap();
19063        assert_eq!(write_csv_string(&frame).expect("write"), "a\n\"\"\nx\ny\n");
19064
19065        // Empty header for a sole column is quoted too (DataFrame({'':['a','b']})).
19066        let named = frame.rename_columns(&[("a", "")]).expect("rename");
19067        assert_eq!(
19068            write_csv_string(&named).expect("write2"),
19069            "\"\"\n\"\"\nx\ny\n"
19070        );
19071    }
19072
19073    #[test]
19074    fn to_csv_typed_multi_column_empty_string_stays_bare_like_pandas() {
19075        // With >1 field per record an empty field is NOT quoted (no blank-line
19076        // ambiguity): DataFrame({'a':['','x'],'b':['y','']}).to_csv(index=False)
19077        // -> 'a,b\n,y\nx,\n'.
19078        let mut columns = BTreeMap::new();
19079        columns.insert(
19080            "a".to_string(),
19081            Column::from_utf8_contiguous(b"x".to_vec(), vec![0, 0, 1]),
19082        );
19083        columns.insert(
19084            "b".to_string(),
19085            Column::from_utf8_contiguous(b"y".to_vec(), vec![0, 1, 1]),
19086        );
19087        let frame = DataFrame::new_with_column_order(
19088            Index::new(vec![IndexLabel::Int64(0), IndexLabel::Int64(1)]),
19089            columns,
19090            vec!["a".to_string(), "b".to_string()],
19091        )
19092        .unwrap();
19093        assert_eq!(write_csv_string(&frame).expect("write"), "a,b\n,y\nx,\n");
19094    }
19095
19096    #[test]
19097    fn to_csv_typed_mixed_columns_quote_alt_delimiter_property_7q396() {
19098        // Code-first property guard (br-frankenpandas-fp-io-csv-typed-writer-quote-property-7q396):
19099        // all-valid typed Int64/Float64 plus contiguous Utf8 must stay byte-exact
19100        // under QUOTE_MINIMAL when the delimiter changes and Utf8 cells contain
19101        // delimiter, quote, and newline characters.
19102        let mut columns = BTreeMap::new();
19103        columns.insert("i".to_string(), Column::from_i64_values(vec![-1, 0, 42, 7]));
19104        columns.insert(
19105            "f".to_string(),
19106            Column::from_f64_values(vec![1.0, 2.5, -0.0, 3.25]),
19107        );
19108
19109        let text = b"plainsemi;colonquote\"meline\nbreak".to_vec();
19110        let offsets = vec![0, 5, 15, 23, 33];
19111        let utf8 = Column::from_utf8_contiguous(text, offsets);
19112        assert!(utf8.as_utf8_contiguous().is_some());
19113        columns.insert("s".to_string(), utf8);
19114
19115        let frame = DataFrame::new_with_column_order(
19116            Index::new((0..4).map(IndexLabel::Int64).collect()),
19117            columns,
19118            vec!["i".to_string(), "f".to_string(), "s".to_string()],
19119        )
19120        .unwrap();
19121        let out = write_csv_string_with_options(
19122            &frame,
19123            &CsvWriteOptions {
19124                delimiter: b';',
19125                include_index: false,
19126                ..CsvWriteOptions::default()
19127            },
19128        )
19129        .expect("typed csv write");
19130
19131        assert_eq!(
19132            out,
19133            "i;f;s\n-1;1.0;plain\n0;2.5;\"semi;colon\"\n42;-0.0;\"quote\"\"me\"\n7;3.25;\"line\nbreak\"\n"
19134        );
19135    }
19136
19137    #[test]
19138    fn to_csv_typed_headerless_keeps_fast_path_for_quoted_column_name_up3yf() {
19139        // br-frankenpandas-fp-io-csv-headerless-quoted-name-typed-fast-pat-up3yf:
19140        // a quoted column name is unobservable when header=false, so it must not
19141        // force the all-valid typed writer off the fast path.
19142        let mut columns = BTreeMap::new();
19143        columns.insert(
19144            "needs,quote".to_string(),
19145            Column::from_i64_values(vec![1, 2]),
19146        );
19147        let frame = DataFrame::new_with_column_order(
19148            Index::new(vec![IndexLabel::Int64(0), IndexLabel::Int64(1)]),
19149            columns,
19150            vec!["needs,quote".to_string()],
19151        )
19152        .unwrap();
19153        let options = CsvWriteOptions {
19154            header: false,
19155            include_index: false,
19156            ..CsvWriteOptions::default()
19157        };
19158
19159        assert_eq!(
19160            super::try_write_csv_typed(&frame, &options).as_deref(),
19161            Some("1\n2\n")
19162        );
19163        assert_eq!(
19164            write_csv_string_with_options(&frame, &options).expect("write"),
19165            "1\n2\n"
19166        );
19167    }
19168
19169    #[test]
19170    fn to_csv_typed_quotes_header_names_without_fallback_ay42b() {
19171        // br-frankenpandas-fp-io-csv-typed-quoted-header-fast-path-4d9vn-ay42b:
19172        // emitted headers use the same QUOTE_MINIMAL rules as data cells, so
19173        // typed columns with quoted names can still bypass the generic writer.
19174        let mut columns = BTreeMap::new();
19175        columns.insert(
19176            "comma,name".to_string(),
19177            Column::from_i64_values(vec![1, 2]),
19178        );
19179        columns.insert(
19180            "quote\"name".to_string(),
19181            Column::from_f64_values(vec![1.0, 2.5]),
19182        );
19183        columns.insert(
19184            "line\nname".to_string(),
19185            Column::from_utf8_contiguous(b"xy".to_vec(), vec![0, 1, 2]),
19186        );
19187        let frame = DataFrame::new_with_column_order(
19188            Index::new(vec![IndexLabel::Int64(0), IndexLabel::Int64(1)]),
19189            columns,
19190            vec![
19191                "comma,name".to_string(),
19192                "quote\"name".to_string(),
19193                "line\nname".to_string(),
19194            ],
19195        )
19196        .unwrap();
19197        let expected = "\"comma,name\",\"quote\"\"name\",\"line\nname\"\n1,1.0,x\n2,2.5,y\n";
19198
19199        assert_eq!(
19200            super::try_write_csv_typed(&frame, &CsvWriteOptions::default()).as_deref(),
19201            Some(expected)
19202        );
19203        assert_eq!(write_csv_string(&frame).expect("write"), expected);
19204    }
19205
19206    #[test]
19207    fn to_csv_typed_handles_datetime_column_without_fallback_dtcsv() {
19208        // A Datetime64 column must stay on the typed fast path (previously any
19209        // datetime forced the whole frame to the generic writer). NaT renders as
19210        // na_rep; the column-uniform full-timestamp form is used because one
19211        // value is non-midnight.
19212        let v0 = 946_684_800_000_000_000i64; // 2000-01-01 00:00:00
19213        let v1 = v0 + 3_661_000_000_000; // 2000-01-01 01:01:01
19214        let mut columns = BTreeMap::new();
19215        columns.insert("a".to_string(), Column::from_i64_values(vec![10, 20, 30]));
19216        columns.insert(
19217            "b".to_string(),
19218            Column::from_f64_values(vec![1.5, 2.0, 3.5]),
19219        );
19220        columns.insert(
19221            "t".to_string(),
19222            Column::from_datetime64_values(vec![v0, v1, Timestamp::NAT]),
19223        );
19224        let frame = DataFrame::new_with_column_order(
19225            Index::new(vec![
19226                IndexLabel::Int64(0),
19227                IndexLabel::Int64(1),
19228                IndexLabel::Int64(2),
19229            ]),
19230            columns,
19231            vec!["a".to_string(), "b".to_string(), "t".to_string()],
19232        )
19233        .unwrap();
19234        let expected = "a,b,t\n10,1.5,2000-01-01 00:00:00\n20,2.0,2000-01-01 01:01:01\n30,3.5,\n";
19235        // Typed fast path fires (no datetime fallback) and is byte-identical to
19236        // the public writer (which routes through it).
19237        assert_eq!(
19238            super::try_write_csv_typed(&frame, &CsvWriteOptions::default()).as_deref(),
19239            Some(expected),
19240        );
19241        assert_eq!(write_csv_string(&frame).expect("write"), expected);
19242    }
19243
19244    #[test]
19245    fn to_csv_typed_emits_int64_index_without_fallback_a2uli() {
19246        // br-frankenpandas-fp-io-csv-typed-int64-index-fast-path-8m6qd-a2uli:
19247        // a simple Int64 index can be emitted directly without forcing typed
19248        // columns through per-cell Scalar materialization.
19249        let mut columns = BTreeMap::new();
19250        columns.insert("a".to_string(), Column::from_i64_values(vec![1, 2]));
19251        columns.insert("b".to_string(), Column::from_f64_values(vec![1.0, 2.5]));
19252        let frame = DataFrame::new_with_column_order(
19253            Index::from_i64(vec![10, 20]).set_name("row,id"),
19254            columns,
19255            vec!["a".to_string(), "b".to_string()],
19256        )
19257        .unwrap();
19258        let options = CsvWriteOptions {
19259            include_index: true,
19260            ..CsvWriteOptions::default()
19261        };
19262        let expected = "\"row,id\",a,b\n10,1,1.0\n20,2,2.5\n";
19263
19264        assert_eq!(
19265            super::try_write_csv_typed(&frame, &options).as_deref(),
19266            Some(expected)
19267        );
19268        assert_eq!(
19269            write_csv_string_with_options(&frame, &options).expect("write"),
19270            expected
19271        );
19272    }
19273
19274    #[test]
19275    fn to_csv_typed_int64_manual_decimal_boundaries_cnw1j() {
19276        // br-frankenpandas-fp-io-csv-int64-manual-decimal-emitter-5p8kx-cnw1j:
19277        // the stack decimal emitter must preserve Display bytes for every i64,
19278        // including the unsigned_abs corner at i64::MIN.
19279        let mut columns = BTreeMap::new();
19280        columns.insert(
19281            "v".to_string(),
19282            Column::from_i64_values(vec![i64::MIN, 0, i64::MAX]),
19283        );
19284        let frame = DataFrame::new_with_column_order(
19285            Index::from_i64(vec![-1, 0, 1]),
19286            columns,
19287            vec!["v".to_string()],
19288        )
19289        .unwrap();
19290        let options = CsvWriteOptions {
19291            include_index: true,
19292            index_label: Some("i".to_string()),
19293            ..CsvWriteOptions::default()
19294        };
19295        let expected = "i,v\n-1,-9223372036854775808\n0,0\n1,9223372036854775807\n";
19296
19297        assert_eq!(
19298            super::try_write_csv_typed(&frame, &options).as_deref(),
19299            Some(expected)
19300        );
19301        assert_eq!(
19302            write_csv_string_with_options(&frame, &options).expect("write"),
19303            expected
19304        );
19305    }
19306
19307    #[test]
19308    fn to_csv_typed_bool_column_stays_on_fast_path_48fwr() {
19309        // br-frankenpandas-fp-io-csv-typed-bool-column-fast-path-2k7hm-48fwr:
19310        // all-valid Bool columns have a typed backing and should emit pandas
19311        // True/False spelling without Scalar materialization.
19312        let mut columns = BTreeMap::new();
19313        columns.insert(
19314            "flag".to_string(),
19315            Column::from_bool_values(vec![true, false, true]),
19316        );
19317        columns.insert("value".to_string(), Column::from_i64_values(vec![7, 8, 9]));
19318        let frame = DataFrame::new_with_column_order(
19319            Index::from_i64(vec![100, 101, 102]),
19320            columns,
19321            vec!["flag".to_string(), "value".to_string()],
19322        )
19323        .unwrap();
19324        let options = CsvWriteOptions {
19325            include_index: true,
19326            index_label: Some("row".to_string()),
19327            ..CsvWriteOptions::default()
19328        };
19329        let expected = "row,flag,value\n100,True,7\n101,False,8\n102,True,9\n";
19330
19331        assert_eq!(
19332            super::try_write_csv_typed(&frame, &options).as_deref(),
19333            Some(expected)
19334        );
19335        assert_eq!(
19336            write_csv_string_with_options(&frame, &options).expect("write"),
19337            expected
19338        );
19339    }
19340
19341    #[test]
19342    fn test_csv_capacity_hint_reasonable() {
19343        // Generate a ~1MB CSV and verify it parses correctly.
19344        // The capacity hint (input.len / (cols*8)) should avoid excessive reallocs.
19345        let mut csv = String::with_capacity(1_100_000);
19346        csv.push_str("a,b,c,d,e\n");
19347        let target_rows = 50_000; // ~20 bytes/row * 50k ≈ 1MB
19348        for i in 0..target_rows {
19349            csv.push_str(&format!("{},{},{},{},{}\n", i, i * 2, i * 3, i * 4, i * 5));
19350        }
19351        assert!(csv.len() > 500_000, "CSV should be large");
19352
19353        let frame = read_csv_str(&csv).expect("parse large CSV");
19354        assert_eq!(frame.index().len(), target_rows);
19355        assert_eq!(frame.columns().len(), 5);
19356        // Spot-check last row
19357        assert_eq!(
19358            frame.column("a").unwrap().values()[target_rows - 1],
19359            Scalar::Int64((target_rows - 1) as i64)
19360        );
19361        eprintln!(
19362            "[TEST] test_csv_capacity_hint_reasonable | rows={target_rows} cols=5 parse_ok=true | PASS"
19363        );
19364    }
19365
19366    #[test]
19367    fn test_csv_empty_columns() {
19368        // CSV with headers but no data rows -> empty DataFrame with correct column names.
19369        let input = "x,y,z\n";
19370        let frame = read_csv_str(input).expect("parse");
19371        assert_eq!(frame.index().len(), 0);
19372        let keys: Vec<&String> = frame.columns().keys().collect();
19373        assert_eq!(keys, &["x", "y", "z"]);
19374        for col in frame.columns().values() {
19375            assert!(col.is_empty());
19376        }
19377        eprintln!("[TEST] test_csv_empty_columns | rows=0 cols=3 parse_ok=true | PASS");
19378    }
19379
19380    #[test]
19381    fn test_csv_comment_skips_lines() {
19382        let input = "# header comment\nname,age\n# inline comment\nalice,30\nbob,25\n";
19383        let options = CsvReadOptions {
19384            comment: Some(b'#'),
19385            ..CsvReadOptions::default()
19386        };
19387        let frame = read_csv_with_options(input, &options).expect("parse");
19388        assert_eq!(frame.index().len(), 2);
19389        let names: Vec<&String> = frame.column_names().into_iter().collect();
19390        assert_eq!(names, vec!["name", "age"]);
19391        assert_eq!(
19392            frame.column("name").unwrap().values()[0],
19393            Scalar::Utf8("alice".to_string())
19394        );
19395        assert_eq!(frame.column("age").unwrap().values()[1], Scalar::Int64(25));
19396    }
19397
19398    #[test]
19399    fn test_csv_comment_none_preserves_comment_lines() {
19400        // Without comment set, a leading "#"-line should become part of parsing
19401        // (and fail as duplicate/missing-headers or be treated as data).
19402        let input = "name,age\nalice,30\n";
19403        let frame = read_csv_with_options(input, &CsvReadOptions::default()).expect("parse");
19404        assert_eq!(frame.index().len(), 1);
19405    }
19406
19407    #[test]
19408    fn read_csv_with_default_options_matches_read_csv_str() {
19409        for input in [
19410            "i,f,s\n1,2.5,abc\n3,4.0,def\n",
19411            "flag\ntrue\nfalse\nmaybe\n",
19412        ] {
19413            let expected = read_csv_str(input).expect("default read");
19414            let actual =
19415                read_csv_with_options(input, &CsvReadOptions::default()).expect("options read");
19416
19417            assert_eq!(actual.index().len(), expected.index().len());
19418            assert_eq!(actual.column_names(), expected.column_names());
19419            for name in expected.column_names() {
19420                let expected_col = expected.column(name).expect("expected column");
19421                let actual_col = actual.column(name).expect("actual column");
19422                assert_eq!(actual_col.dtype(), expected_col.dtype());
19423                assert_eq!(actual_col.values(), expected_col.values());
19424            }
19425        }
19426    }
19427
19428    #[test]
19429    fn read_csv_str_cache_reuses_exact_successful_input() {
19430        let input = "x,y\n1,2.5\n3,4.5\n";
19431
19432        let first = read_csv_str(input).expect("first parse");
19433        let second = read_csv_str(input).expect("cached parse");
19434
19435        assert_eq!(second.index().len(), first.index().len());
19436        assert_eq!(second.column_names(), first.column_names());
19437        for name in first.column_names() {
19438            let first_col = first.column(name).expect("first column");
19439            let second_col = second.column(name).expect("second column");
19440            assert_eq!(second_col.dtype(), first_col.dtype());
19441            assert_eq!(second_col.values(), first_col.values());
19442        }
19443    }
19444
19445    #[test]
19446    fn read_csv_str_cache_is_content_addressed() {
19447        let mut input = String::from("x\n1\n2\n");
19448        let first = read_csv_str(&input).expect("first parse");
19449        assert_eq!(first.column("x").unwrap().values()[0], Scalar::Int64(1));
19450
19451        input.clear();
19452        input.push_str("x\n9\n10\n");
19453        let second = read_csv_str(&input).expect("changed-content parse");
19454
19455        assert_eq!(second.index().len(), 2);
19456        assert_eq!(second.column("x").unwrap().values()[0], Scalar::Int64(9));
19457        assert_eq!(second.column("x").unwrap().values()[1], Scalar::Int64(10));
19458    }
19459
19460    #[test]
19461    fn read_csv_no_na_cache_reuses_exact_successful_input() {
19462        let options = CsvReadOptions {
19463            na_filter: false,
19464            ..CsvReadOptions::default()
19465        };
19466        let input = "x,y\n1,2.5\n3,4.5\n";
19467
19468        let first = read_csv_with_options(input, &options).expect("first no-na parse");
19469        let second = read_csv_with_options(input, &options).expect("cached no-na parse");
19470
19471        assert_eq!(second.index().len(), first.index().len());
19472        assert_eq!(second.column_names(), first.column_names());
19473        for name in first.column_names() {
19474            let first_col = first.column(name).expect("first column");
19475            let second_col = second.column(name).expect("second column");
19476            assert_eq!(second_col.dtype(), first_col.dtype());
19477            assert_eq!(second_col.values(), first_col.values());
19478        }
19479    }
19480
19481    #[test]
19482    fn csv_parse_cache_keeps_default_and_no_na_modes_separate() {
19483        let input = "mode_sep_a,mode_sep_b\n11,12.5\n13,14.5\n";
19484        let no_na_options = CsvReadOptions {
19485            na_filter: false,
19486            ..CsvReadOptions::default()
19487        };
19488
19489        // This test asserts KEY SEPARATION, not cache retention, and the two need
19490        // different strengths of assertion.
19491        //
19492        // CSV_PARSE_CACHE is one global VecDeque holding CSV_PARSE_CACHE_MAX_ENTRIES
19493        // (2) entries, and 117 tests in this module parse CSVs. Under the default
19494        // parallel harness any of them can evict this test's entries between a store
19495        // and the matching lookup, so `.expect("... cache entry")` on a retention
19496        // lookup fails intermittently — it did, on the no-na entry, once a second
19497        // parse pushed the deque past two. That is the harness racing, not the cache
19498        // misbehaving: the whole file passes under `--test-threads=1`.
19499        //
19500        // So: assertions that can only fail because of a real bug stay strict, and
19501        // assertions that a concurrent eviction can legitimately defeat are guarded
19502        // on presence. Nothing real is given up. `input` is unique to this test, so
19503        // a hit under the wrong mode can only mean the two modes share a key, which
19504        // is exactly the defect this test exists to catch.
19505        let no_na_frame = read_csv_with_options(input, &no_na_options).expect("no-na parse");
19506
19507        // STRICT: a no-na parse must never satisfy a Default lookup for this input.
19508        // Eviction can only turn a Some into a None here, never a None into a Some,
19509        // so a failure is unambiguously a key collision.
19510        assert!(
19511            super::csv_parse_cache_lookup(super::CsvParseCacheMode::Default, input).is_none(),
19512            "a no-na parse populated the Default cache key: the two modes are not separated"
19513        );
19514
19515        let default_frame = read_csv_str(input).expect("default parse");
19516
19517        // STRICT, and the mirror of the above: a default parse must never satisfy a
19518        // no-na lookup with default-parsed content.
19519        assert!(
19520            super::csv_parse_cache_lookup(super::CsvParseCacheMode::NoNaNumeric, input)
19521                .is_none_or(|cached| cached.column("mode_sep_b").unwrap().values()
19522                    == no_na_frame.column("mode_sep_b").unwrap().values()),
19523            "the NoNaNumeric key returned default-parsed content: the modes are not separated"
19524        );
19525
19526        // GUARDED: whether an entry survived is a property of the eviction policy and
19527        // of what else is running. What must hold is that a surviving entry matches a
19528        // fresh parse in the same mode.
19529        if let Some(default_cached) =
19530            super::csv_parse_cache_lookup(super::CsvParseCacheMode::Default, input)
19531        {
19532            assert_eq!(default_cached.column_names(), default_frame.column_names());
19533            assert_eq!(
19534                default_cached.column("mode_sep_b").unwrap().values(),
19535                default_frame.column("mode_sep_b").unwrap().values()
19536            );
19537        }
19538        if let Some(no_na_cached) =
19539            super::csv_parse_cache_lookup(super::CsvParseCacheMode::NoNaNumeric, input)
19540        {
19541            assert_eq!(no_na_cached.column_names(), no_na_frame.column_names());
19542            assert_eq!(
19543                no_na_cached.column("mode_sep_b").unwrap().values(),
19544                no_na_frame.column("mode_sep_b").unwrap().values()
19545            );
19546        }
19547    }
19548
19549    #[test]
19550    fn csv_default_options_fast_path_excludes_behavioral_options() {
19551        assert!(super::csv_read_options_match_default_fast_path(
19552            &CsvReadOptions::default()
19553        ));
19554
19555        for options in [
19556            CsvReadOptions {
19557                delimiter: b'\t',
19558                ..CsvReadOptions::default()
19559            },
19560            CsvReadOptions {
19561                na_filter: false,
19562                ..CsvReadOptions::default()
19563            },
19564            CsvReadOptions {
19565                nrows: Some(1),
19566                ..CsvReadOptions::default()
19567            },
19568            CsvReadOptions {
19569                comment: Some(b'#'),
19570                ..CsvReadOptions::default()
19571            },
19572            CsvReadOptions {
19573                thousands: Some(b','),
19574                ..CsvReadOptions::default()
19575            },
19576        ] {
19577            assert!(!super::csv_read_options_match_default_fast_path(&options));
19578        }
19579    }
19580
19581    #[test]
19582    fn read_csv_no_na_filter_numeric_fast_path_preserves_numeric_columns() {
19583        let options = CsvReadOptions {
19584            na_filter: false,
19585            ..CsvReadOptions::default()
19586        };
19587        assert!(super::csv_read_options_match_no_na_numeric_fast_path(
19588            &options
19589        ));
19590
19591        let frame = read_csv_with_options("i,f\n1,2.5\n3,4\n", &options).expect("parse");
19592        assert_eq!(frame.len(), 2);
19593        assert_eq!(frame.column("i").expect("i").dtype(), DType::Int64);
19594        assert_eq!(frame.column("f").expect("f").dtype(), DType::Float64);
19595        assert_eq!(frame.column("i").expect("i").values()[1], Scalar::Int64(3));
19596        assert_eq!(
19597            frame.column("f").expect("f").values()[0],
19598            Scalar::Float64(2.5)
19599        );
19600    }
19601
19602    #[test]
19603    fn read_csv_no_na_filter_fast_path_falls_back_for_empty_field() {
19604        let options = CsvReadOptions {
19605            na_filter: false,
19606            ..CsvReadOptions::default()
19607        };
19608        let frame = read_csv_with_options("x,y\n1,\n2,3\n", &options).expect("parse");
19609        let y = frame.column("y").expect("y");
19610
19611        assert_eq!(y.dtype(), DType::Utf8);
19612        assert_eq!(y.values()[0], Scalar::Utf8(String::new()));
19613        assert_eq!(y.values()[1], Scalar::Utf8("3".to_owned()));
19614    }
19615
19616    #[test]
19617    fn test_csv_comment_custom_char() {
19618        let input = "% this is ignored\nname,age\nalice,30\n";
19619        let options = CsvReadOptions {
19620            comment: Some(b'%'),
19621            ..CsvReadOptions::default()
19622        };
19623        let frame = read_csv_with_options(input, &options).expect("parse");
19624        assert_eq!(frame.index().len(), 1);
19625        assert_eq!(
19626            frame.column("name").unwrap().values()[0],
19627            Scalar::Utf8("alice".to_string())
19628        );
19629    }
19630
19631    #[test]
19632    fn test_csv_thousands_strips_int_separator() {
19633        let input = "amount\n\"1,234,567\"\n\"42\"\n";
19634        let options = CsvReadOptions {
19635            thousands: Some(b','),
19636            ..CsvReadOptions::default()
19637        };
19638        let frame = read_csv_with_options(input, &options).expect("parse");
19639        assert_eq!(
19640            frame.column("amount").unwrap().values()[0],
19641            Scalar::Int64(1234567)
19642        );
19643        assert_eq!(
19644            frame.column("amount").unwrap().values()[1],
19645            Scalar::Int64(42)
19646        );
19647    }
19648
19649    #[test]
19650    fn test_csv_thousands_strips_float_with_custom_decimal() {
19651        // European convention: '.' as thousands, ',' as decimal.
19652        let input = "price\n\"1.234,56\"\n";
19653        let options = CsvReadOptions {
19654            thousands: Some(b'.'),
19655            decimal: b',',
19656            ..CsvReadOptions::default()
19657        };
19658        let frame = read_csv_with_options(input, &options).expect("parse");
19659        let v = frame.column("price").unwrap().values()[0].clone();
19660        assert!(matches!(v, Scalar::Float64(_)), "expected Float64");
19661        let Scalar::Float64(f) = v else { return };
19662        assert!((f - 1234.56).abs() < 1e-9);
19663    }
19664
19665    #[test]
19666    fn test_csv_thousands_none_keeps_separator_as_string() {
19667        // Without thousands set, "1,234" in a single field stays Utf8.
19668        let input = "amount\n\"1,234\"\n";
19669        let frame = read_csv_with_options(input, &CsvReadOptions::default()).expect("parse");
19670        assert_eq!(
19671            frame.column("amount").unwrap().values()[0],
19672            Scalar::Utf8("1,234".to_string())
19673        );
19674    }
19675
19676    #[test]
19677    fn test_csv_thousands_equal_to_decimal_is_ignored() {
19678        // pandas silently ignores thousands if it equals decimal.
19679        let input = "v\n\"1.234\"\n";
19680        let options = CsvReadOptions {
19681            thousands: Some(b'.'),
19682            decimal: b'.',
19683            ..CsvReadOptions::default()
19684        };
19685        let frame = read_csv_with_options(input, &options).expect("parse");
19686        let v = frame.column("v").unwrap().values()[0].clone();
19687        // thousands ignored → "1.234" parses as float 1.234
19688        assert!(matches!(v, Scalar::Float64(_)), "expected Float64");
19689        let Scalar::Float64(f) = v else { return };
19690        assert!((f - 1.234).abs() < 1e-9);
19691    }
19692
19693    #[test]
19694    fn test_csv_thousands_does_not_affect_non_numeric() {
19695        let input = "name\n\"a,b\"\n";
19696        let options = CsvReadOptions {
19697            thousands: Some(b','),
19698            ..CsvReadOptions::default()
19699        };
19700        let frame = read_csv_with_options(input, &options).expect("parse");
19701        assert_eq!(
19702            frame.column("name").unwrap().values()[0],
19703            Scalar::Utf8("a,b".to_string())
19704        );
19705    }
19706
19707    #[test]
19708    fn test_csv_quotechar_custom_single_quote() {
19709        let input = "name,remark\n'alice','loves, cats'\n";
19710        let options = CsvReadOptions {
19711            quotechar: b'\'',
19712            ..CsvReadOptions::default()
19713        };
19714        let frame = read_csv_with_options(input, &options).expect("parse");
19715        assert_eq!(
19716            frame.column("name").unwrap().values()[0],
19717            Scalar::Utf8("alice".to_string())
19718        );
19719        assert_eq!(
19720            frame.column("remark").unwrap().values()[0],
19721            Scalar::Utf8("loves, cats".to_string())
19722        );
19723    }
19724
19725    #[test]
19726    fn test_csv_doublequote_true_collapses_doubled_quotes() {
19727        // The field is `she said ""hi""` with doubled inner quotes.
19728        let input = "text\n\"she said \"\"hi\"\"\"\n";
19729        let frame = read_csv_with_options(input, &CsvReadOptions::default()).expect("parse");
19730        assert_eq!(
19731            frame.column("text").unwrap().values()[0],
19732            Scalar::Utf8("she said \"hi\"".to_string())
19733        );
19734    }
19735
19736    #[test]
19737    fn test_csv_doublequote_false_requires_escapechar() {
19738        // With doublequote=false and escapechar=\, \" escapes the quote.
19739        let input = "text\n\"hi\\\"there\"\n";
19740        let options = CsvReadOptions {
19741            doublequote: false,
19742            escapechar: Some(b'\\'),
19743            ..CsvReadOptions::default()
19744        };
19745        let frame = read_csv_with_options(input, &options).expect("parse");
19746        assert_eq!(
19747            frame.column("text").unwrap().values()[0],
19748            Scalar::Utf8("hi\"there".to_string())
19749        );
19750    }
19751
19752    #[test]
19753    fn test_csv_lineterminator_semicolon() {
19754        // Single-byte record separator '|'. No newlines in the data.
19755        let input = "a,b|1,x|2,y|3,z";
19756        let options = CsvReadOptions {
19757            lineterminator: Some(b'|'),
19758            ..CsvReadOptions::default()
19759        };
19760        let frame = read_csv_with_options(input, &options).expect("parse");
19761        assert_eq!(frame.index().len(), 3);
19762        assert_eq!(frame.column_names(), vec!["a", "b"]);
19763        assert_eq!(frame.column("a").unwrap().values()[2], Scalar::Int64(3));
19764    }
19765
19766    #[test]
19767    fn test_csv_lineterminator_default_none_accepts_crlf() {
19768        let input = "a,b\r\n1,x\r\n2,y\r\n";
19769        let frame = read_csv_with_options(input, &CsvReadOptions::default()).expect("parse");
19770        assert_eq!(frame.index().len(), 2);
19771    }
19772
19773    #[test]
19774    fn test_csv_lineterminator_interacts_with_skipfooter() {
19775        let input = "a|1|2|3|4|FOOTER";
19776        let options = CsvReadOptions {
19777            lineterminator: Some(b'|'),
19778            skipfooter: 1,
19779            ..CsvReadOptions::default()
19780        };
19781        let frame = read_csv_with_options(input, &options).expect("parse");
19782        // 5 data rows after header, footer drops 1 → 4 rows.
19783        assert_eq!(frame.index().len(), 4);
19784    }
19785
19786    #[test]
19787    fn test_csv_skipfooter_drops_trailing_rows() {
19788        let input = "a,b\n1,x\n2,y\n3,z\nTOTAL,summary\n";
19789        let options = CsvReadOptions {
19790            skipfooter: 1,
19791            ..CsvReadOptions::default()
19792        };
19793        let frame = read_csv_with_options(input, &options).expect("parse");
19794        assert_eq!(frame.index().len(), 3);
19795        assert_eq!(frame.column("a").unwrap().values()[2], Scalar::Int64(3));
19796    }
19797
19798    #[test]
19799    fn test_csv_skipfooter_zero_is_noop() {
19800        let input = "a,b\n1,x\n2,y\n";
19801        let frame_default =
19802            read_csv_with_options(input, &CsvReadOptions::default()).expect("parse");
19803        let options = CsvReadOptions {
19804            skipfooter: 0,
19805            ..CsvReadOptions::default()
19806        };
19807        let frame_zero = read_csv_with_options(input, &options).expect("parse");
19808        assert_eq!(frame_default.index().len(), frame_zero.index().len());
19809    }
19810
19811    #[test]
19812    fn test_csv_skipfooter_larger_than_data_clears_rows() {
19813        let input = "a,b\n1,x\n2,y\n";
19814        let options = CsvReadOptions {
19815            skipfooter: 10,
19816            ..CsvReadOptions::default()
19817        };
19818        let frame = read_csv_with_options(input, &options).expect("parse");
19819        assert_eq!(frame.index().len(), 0);
19820        // Columns and headers are still preserved.
19821        assert_eq!(frame.column_names().len(), 2);
19822    }
19823
19824    #[test]
19825    fn test_csv_skipfooter_with_nrows() {
19826        // nrows caps read to 4, then skipfooter drops last 1 → 3 rows.
19827        let input = "a\n1\n2\n3\n4\n5\n";
19828        let options = CsvReadOptions {
19829            nrows: Some(4),
19830            skipfooter: 1,
19831            ..CsvReadOptions::default()
19832        };
19833        let frame = read_csv_with_options(input, &options).expect("parse");
19834        assert_eq!(frame.index().len(), 3);
19835    }
19836
19837    #[test]
19838    fn test_csv_escapechar_none_default_keeps_backslash_literal() {
19839        // Without escapechar set, backslash is just a normal character.
19840        let input = "text\n\"foo\\bar\"\n";
19841        let frame = read_csv_with_options(input, &CsvReadOptions::default()).expect("parse");
19842        assert_eq!(
19843            frame.column("text").unwrap().values()[0],
19844            Scalar::Utf8("foo\\bar".to_string())
19845        );
19846    }
19847
19848    #[test]
19849    fn test_csv_single_column() {
19850        // CSV with one column, many rows -> correct parsing.
19851        let mut csv = String::from("value\n");
19852        for i in 0..500 {
19853            csv.push_str(&format!("{}\n", i));
19854        }
19855        let frame = read_csv_str(&csv).expect("parse");
19856        assert_eq!(frame.index().len(), 500);
19857        assert_eq!(frame.columns().len(), 1);
19858        assert_eq!(
19859            frame.column("value").unwrap().values()[499],
19860            Scalar::Int64(499)
19861        );
19862        eprintln!("[TEST] test_csv_single_column | rows=500 cols=1 parse_ok=true | PASS");
19863    }
19864
19865    #[test]
19866    fn test_csv_many_columns() {
19867        // CSV with 100+ columns -> all columns present, correct values.
19868        let col_count = 120;
19869        let headers: Vec<String> = (0..col_count).map(|i| format!("c{i:03}")).collect();
19870        let mut csv = headers.join(",");
19871        csv.push('\n');
19872        // 3 data rows
19873        for row in 0..3 {
19874            let vals: Vec<String> = (0..col_count)
19875                .map(|c| format!("{}", row * 1000 + c))
19876                .collect();
19877            csv.push_str(&vals.join(","));
19878            csv.push('\n');
19879        }
19880        let frame = read_csv_str(&csv).expect("parse");
19881        assert_eq!(frame.columns().len(), col_count);
19882        assert_eq!(frame.index().len(), 3);
19883        // Spot-check: c000 row 0 = 0, c119 row 2 = 2119
19884        assert_eq!(frame.column("c000").unwrap().values()[0], Scalar::Int64(0));
19885        assert_eq!(
19886            frame.column("c119").unwrap().values()[2],
19887            Scalar::Int64(2119)
19888        );
19889        eprintln!("[TEST] test_csv_many_columns | rows=3 cols={col_count} parse_ok=true | PASS");
19890    }
19891
19892    #[test]
19893    fn test_csv_mixed_dtypes() {
19894        // Columns with uniform int/float/string/bool/null -> correct type inference.
19895        let input = "ints,floats,strings,bools,nulls\n\
19896                     1,1.5,hello,true,\n\
19897                     2,2.7,world,false,\n\
19898                     3,3.14,foo,true,\n";
19899        let frame = read_csv_str(input).expect("parse");
19900
19901        let ints = frame.column("ints").unwrap();
19902        assert_eq!(ints.values()[0], Scalar::Int64(1));
19903
19904        let floats = frame.column("floats").unwrap();
19905        assert_eq!(floats.values()[1], Scalar::Float64(2.7));
19906
19907        let strings = frame.column("strings").unwrap();
19908        assert_eq!(strings.values()[2], Scalar::Utf8("foo".to_owned()));
19909
19910        let bools = frame.column("bools").unwrap();
19911        assert_eq!(bools.values()[0], Scalar::Bool(true));
19912        assert_eq!(bools.values()[1], Scalar::Bool(false));
19913
19914        // "nulls" column is all empty -> all null/NaN
19915        let nulls = frame.column("nulls").unwrap();
19916        for v in nulls.values() {
19917            assert!(v.is_missing(), "null column values should be missing");
19918        }
19919        eprintln!(
19920            "[TEST] test_csv_mixed_dtypes | rows=3 cols=5 parse_ok=true | dtype_per_col=[int64,float64,utf8,bool,null] | PASS"
19921        );
19922    }
19923
19924    #[test]
19925    fn test_csv_unicode_headers() {
19926        // CSV with unicode header names -> correct column names.
19927        let input = "名前,Größe,café\nAlice,170,latte\nBob,180,espresso\n";
19928        let frame = read_csv_str(input).expect("parse");
19929        assert!(frame.column("名前").is_some());
19930        assert!(frame.column("Größe").is_some());
19931        assert!(frame.column("café").is_some());
19932        assert_eq!(
19933            frame.column("名前").unwrap().values()[0],
19934            Scalar::Utf8("Alice".to_owned())
19935        );
19936        eprintln!("[TEST] test_csv_unicode_headers | rows=2 cols=3 parse_ok=true | PASS");
19937    }
19938
19939    #[test]
19940    fn test_csv_quoted_fields() {
19941        // CSV with quoted fields containing commas and newlines -> correct parsing.
19942        let input =
19943            "name,address\n\"Smith, John\",\"123 Main St\nApt 4\"\nJane,\"456 Oak, Suite 1\"\n";
19944        let frame = read_csv_str(input).expect("parse");
19945        assert_eq!(frame.index().len(), 2);
19946        assert_eq!(
19947            frame.column("name").unwrap().values()[0],
19948            Scalar::Utf8("Smith, John".to_owned())
19949        );
19950        // Quoted field with embedded newline
19951        let addr0 = &frame.column("address").unwrap().values()[0];
19952        assert!(
19953            matches!(addr0, Scalar::Utf8(s) if s.contains('\n')),
19954            "expected Utf8 containing embedded newline, got {addr0:?}"
19955        );
19956        eprintln!("[TEST] test_csv_quoted_fields | rows=2 cols=2 parse_ok=true | PASS");
19957    }
19958
19959    #[test]
19960    fn test_csv_trailing_newline() {
19961        // CSV with/without trailing newline -> identical DataFrame.
19962        let with = "a,b\n1,2\n3,4\n";
19963        let without = "a,b\n1,2\n3,4";
19964        let f1 = read_csv_str(with).expect("with newline");
19965        let f2 = read_csv_str(without).expect("without newline");
19966
19967        assert_eq!(f1.index().len(), f2.index().len());
19968        assert_eq!(f1.columns().len(), f2.columns().len());
19969        for key in f1.columns().keys() {
19970            let c1 = f1.column(key).unwrap();
19971            let c2 = f2.column(key).unwrap();
19972            assert_eq!(c1.values(), c2.values(), "column {key} mismatch");
19973        }
19974        eprintln!("[TEST] test_csv_trailing_newline | rows=2 cols=2 parse_ok=true | PASS");
19975    }
19976
19977    #[test]
19978    fn test_csv_round_trip_unchanged() {
19979        // read_csv_str then write_csv_string produces semantically equivalent output.
19980        let input = "id,name,score\n1,Alice,95.5\n2,Bob,87\n3,,100\n";
19981        let frame = read_csv_str(input).expect("read");
19982        let output = write_csv_string(&frame).expect("write");
19983        // Re-parse the output and compare
19984        let frame2 = read_csv_str(&output).expect("re-read");
19985        assert_eq!(frame.index().len(), frame2.index().len());
19986        for key in frame.columns().keys() {
19987            let c1 = frame.column(key).unwrap();
19988            let c2 = frame2.column(key).unwrap();
19989            assert!(
19990                c1.semantic_eq(c2),
19991                "column {key} not semantically equal after round-trip"
19992            );
19993        }
19994        eprintln!("[TEST] test_csv_round_trip_unchanged | rows=3 cols=3 parse_ok=true | PASS");
19995    }
19996
19997    #[test]
19998    fn test_write_csv_options_custom_delimiter() {
19999        let input = "a,b\n1,x\n2,y\n";
20000        let frame = read_csv_str(input).expect("read");
20001        let output = write_csv_string_with_options(
20002            &frame,
20003            &CsvWriteOptions {
20004                delimiter: b';',
20005                ..CsvWriteOptions::default()
20006            },
20007        )
20008        .expect("write");
20009        assert!(output.starts_with("a;b\n"));
20010        assert!(output.contains("1;x\n"));
20011        assert!(output.contains("2;y\n"));
20012    }
20013
20014    #[test]
20015    fn test_write_csv_options_na_rep_replaces_nulls() {
20016        let input = "id,name\n1,Alice\n2,\n";
20017        let frame = read_csv_str(input).expect("read");
20018        let output = write_csv_string_with_options(
20019            &frame,
20020            &CsvWriteOptions {
20021                na_rep: "NA".to_string(),
20022                ..CsvWriteOptions::default()
20023            },
20024        )
20025        .expect("write");
20026        // Second data row's name should render as NA, not empty.
20027        assert!(output.contains("2,NA\n"));
20028        assert!(!output.contains("2,\n"));
20029    }
20030
20031    #[test]
20032    fn test_write_csv_nullable_utf8_fast_matches_general() {
20033        // A nullable contiguous-Utf8 column (LazyNullableUtf8) now takes the fast typed
20034        // writer (FastCol::UN). It must produce BYTE-IDENTICAL output to the general
20035        // (Scalar + csv-record) writer, which an EAGER Utf8 column with the same data
20036        // falls to. Covers present/missing rows, empty strings, and QUOTE_MINIMAL
20037        // triggers (comma / quote / CR / LF), across default + na_rep + no-header +
20038        // single-column (empty-na quoting) configs.
20039        let rows: Vec<Option<&str>> = vec![
20040            Some("Alice"),
20041            None,
20042            Some("a,b"),     // comma ⇒ quoted
20043            Some("he\"llo"), // embedded quote ⇒ quoted + doubled
20044            Some(""),        // present empty string
20045            None,
20046            Some("line\nbrk"), // LF ⇒ quoted
20047            Some("tab\tok"),   // tab (not a QUOTE_MINIMAL trigger) ⇒ unquoted
20048            Some("plain"),
20049        ];
20050        let n = rows.len();
20051
20052        // Build the nullable Utf8 column two ways.
20053        let mut bytes: Vec<u8> = Vec::new();
20054        let mut offsets: Vec<usize> = vec![0];
20055        let mut validity = fp_columnar::ValidityMask::all_valid(n);
20056        let mut eager: Vec<Scalar> = Vec::with_capacity(n);
20057        for (i, r) in rows.iter().enumerate() {
20058            match r {
20059                Some(s) => {
20060                    bytes.extend_from_slice(s.as_bytes());
20061                    eager.push(Scalar::Utf8((*s).to_string()));
20062                }
20063                None => {
20064                    validity.set(i, false);
20065                    eager.push(Scalar::Null(fp_types::NullKind::Null));
20066                }
20067            }
20068            offsets.push(bytes.len());
20069        }
20070
20071        let mk = |name_col: Column| -> DataFrame {
20072            let mut cols = std::collections::BTreeMap::new();
20073            cols.insert(
20074                "id".to_string(),
20075                Column::from_i64_values_owned((0..n as i64).collect()),
20076            );
20077            cols.insert("name".to_string(), name_col);
20078            DataFrame::new_with_column_order(
20079                Index::new_known_unique_int64_unit_range(0, n),
20080                cols,
20081                vec!["id".to_string(), "name".to_string()],
20082            )
20083            .unwrap()
20084        };
20085        let frame_fast = mk(Column::from_utf8_values_with_validity(
20086            bytes, offsets, validity,
20087        ));
20088        let frame_general = mk(Column::from_values(eager).unwrap());
20089
20090        // The general frame's name column must be OFF the fast Utf8 path.
20091        let ctl = frame_general.column("name").unwrap();
20092        assert!(
20093            ctl.as_utf8_contiguous().is_none() && ctl.as_nullable_utf8_contiguous().is_none(),
20094            "control name column must be on the general writer"
20095        );
20096
20097        for options in [
20098            CsvWriteOptions::default(),
20099            CsvWriteOptions {
20100                na_rep: "NA".to_string(),
20101                ..CsvWriteOptions::default()
20102            },
20103            CsvWriteOptions {
20104                header: false,
20105                ..CsvWriteOptions::default()
20106            },
20107        ] {
20108            let fast = write_csv_string_with_options(&frame_fast, &options).expect("fast");
20109            let general = write_csv_string_with_options(&frame_general, &options).expect("general");
20110            assert_eq!(
20111                fast, general,
20112                "fast nullable-Utf8 CSV must byte-match the general writer"
20113            );
20114        }
20115
20116        // Single-column nullable Utf8 frame: exercises the empty-na `""` quoting on a
20117        // missing sole field.
20118        let single_fast = {
20119            let mut c = std::collections::BTreeMap::new();
20120            let mut b: Vec<u8> = Vec::new();
20121            let mut o: Vec<usize> = vec![0];
20122            let mut v = fp_columnar::ValidityMask::all_valid(n);
20123            for (i, r) in rows.iter().enumerate() {
20124                if let Some(s) = r {
20125                    b.extend_from_slice(s.as_bytes());
20126                } else {
20127                    v.set(i, false);
20128                }
20129                o.push(b.len());
20130            }
20131            c.insert(
20132                "name".to_string(),
20133                Column::from_utf8_values_with_validity(b, o, v),
20134            );
20135            DataFrame::new(Index::new_known_unique_int64_unit_range(0, n), c).unwrap()
20136        };
20137        let single_general = {
20138            let mut c = std::collections::BTreeMap::new();
20139            c.insert(
20140                "name".to_string(),
20141                Column::from_values(eager_clone(&rows)).unwrap(),
20142            );
20143            DataFrame::new(Index::new_known_unique_int64_unit_range(0, n), c).unwrap()
20144        };
20145        let f = write_csv_string(&single_fast).expect("fast single");
20146        let g = write_csv_string(&single_general).expect("general single");
20147        assert_eq!(
20148            f, g,
20149            "single-column nullable-Utf8 CSV must byte-match the general writer"
20150        );
20151    }
20152
20153    #[cfg(test)]
20154    fn eager_clone(rows: &[Option<&str>]) -> Vec<Scalar> {
20155        rows.iter()
20156            .map(|r| match r {
20157                Some(s) => Scalar::Utf8((*s).to_string()),
20158                None => Scalar::Null(fp_types::NullKind::Null),
20159            })
20160            .collect()
20161    }
20162
20163    #[test]
20164    fn test_write_json_nullable_utf8_fast_matches_serde() {
20165        // A nullable contiguous-Utf8 column (LazyNullableUtf8) now takes the typed JSON
20166        // fast writer (JCol::UN). It must produce BYTE-IDENTICAL output to the serde-tree
20167        // fallback, which an EAGER Utf8 column with the same data falls to. Covers
20168        // present/missing (→ null), empty strings, and JSON escape triggers (quote,
20169        // backslash, control byte) across Records + Columns orients.
20170        let rows: Vec<Option<&str>> = vec![
20171            Some("Alice"),
20172            None,
20173            Some("a\"b"),     // embedded quote ⇒ JSON-escaped
20174            Some("back\\sl"), // backslash ⇒ escaped
20175            Some(""),         // present empty string
20176            None,
20177            Some("tab\tnl\n"), // control bytes ⇒ escaped
20178            Some("héllo"),     // multi-byte UTF-8 (passes through)
20179            Some("plain"),
20180        ];
20181        let n = rows.len();
20182
20183        let mut bytes: Vec<u8> = Vec::new();
20184        let mut offsets: Vec<usize> = vec![0];
20185        let mut validity = fp_columnar::ValidityMask::all_valid(n);
20186        for (i, r) in rows.iter().enumerate() {
20187            if let Some(s) = r {
20188                bytes.extend_from_slice(s.as_bytes());
20189            } else {
20190                validity.set(i, false);
20191            }
20192            offsets.push(bytes.len());
20193        }
20194
20195        let mk = |name_col: Column| -> DataFrame {
20196            let mut cols = std::collections::BTreeMap::new();
20197            cols.insert(
20198                "id".to_string(),
20199                Column::from_i64_values_owned((0..n as i64).collect()),
20200            );
20201            cols.insert("name".to_string(), name_col);
20202            DataFrame::new_with_column_order(
20203                Index::new_known_unique_int64_unit_range(0, n),
20204                cols,
20205                vec!["id".to_string(), "name".to_string()],
20206            )
20207            .unwrap()
20208        };
20209        let frame_fast = mk(Column::from_utf8_values_with_validity(
20210            bytes, offsets, validity,
20211        ));
20212        let frame_general = mk(Column::from_values(eager_clone(&rows)).unwrap());
20213
20214        let ctl = frame_general.column("name").unwrap();
20215        assert!(
20216            ctl.as_utf8_contiguous().is_none() && ctl.as_nullable_utf8_contiguous().is_none(),
20217            "control name column must be on the serde tree"
20218        );
20219
20220        for orient in [JsonOrient::Records, JsonOrient::Columns] {
20221            let fast = write_json_string(&frame_fast, orient).expect("fast json");
20222            let general = write_json_string(&frame_general, orient).expect("general json");
20223            assert_eq!(
20224                fast, general,
20225                "fast nullable-Utf8 JSON ({orient:?}) must byte-match the serde tree"
20226            );
20227        }
20228    }
20229
20230    #[test]
20231    fn test_write_json_nullable_numeric_fast_matches_serde() {
20232        // Nullable Float64 (JCol::FN) and Int64 (JCol::IN) columns take the typed JSON
20233        // fast writer. Output must be BYTE-IDENTICAL to the serde tree (which the same
20234        // frame falls to when an EAGER Utf8 column forces it off the fast path). Covers:
20235        // validity-clear missing (→ null), valid-bit NaN (→ null), ±inf (→ null), whole
20236        // numbers, negatives, 1e20, i64::MIN/MAX; Records + Columns orients.
20237        let n = 9usize;
20238        let fdata: Vec<f64> = vec![
20239            1.0,
20240            -2.5,
20241            0.0,
20242            f64::NAN,
20243            1e20,
20244            f64::INFINITY,
20245            std::f64::consts::PI,
20246            f64::NEG_INFINITY,
20247            42.0,
20248        ];
20249        let mut fv = fp_columnar::ValidityMask::all_valid(n);
20250        fv.set(2, false); // validity-clear (data 0.0 → null)
20251        // slot 3 valid-bit NaN, slots 5/7 valid ±inf → all render null.
20252
20253        let idata: Vec<i64> = vec![0, i64::MIN, i64::MAX, -1, 1000, 0, -999999, 7, 123456789];
20254        let mut iv = fp_columnar::ValidityMask::all_valid(n);
20255        iv.set(0, false);
20256        iv.set(5, false);
20257
20258        // nullable Bool (JCol::BN): present ⇒ true/false, missing ⇒ null.
20259        let bdata: Vec<bool> = vec![true, false, true, false, true, false, true, false, true];
20260        let mut bv = fp_columnar::ValidityMask::all_valid(n);
20261        bv.set(2, false);
20262        bv.set(6, false);
20263
20264        let names: Vec<&str> = vec!["a", "b", "c", "d", "e", "f", "g", "h", "z"];
20265        let mut nb: Vec<u8> = Vec::new();
20266        let mut no: Vec<usize> = vec![0];
20267        for s in &names {
20268            nb.extend_from_slice(s.as_bytes());
20269            no.push(nb.len());
20270        }
20271        let eager_names: Vec<Scalar> = names
20272            .iter()
20273            .map(|s| Scalar::Utf8((*s).to_string()))
20274            .collect();
20275
20276        let mk = |name_col: Column| -> DataFrame {
20277            let mut cols = std::collections::BTreeMap::new();
20278            cols.insert(
20279                "f".to_string(),
20280                Column::from_f64_values_with_validity(fdata.clone(), fv.clone()),
20281            );
20282            cols.insert(
20283                "i".to_string(),
20284                Column::from_i64_values_with_validity(idata.clone(), iv.clone()),
20285            );
20286            cols.insert(
20287                "b".to_string(),
20288                Column::from_bool_values_with_validity(bdata.clone(), bv.clone()),
20289            );
20290            cols.insert("name".to_string(), name_col);
20291            DataFrame::new_with_column_order(
20292                Index::new_known_unique_int64_unit_range(0, n),
20293                cols,
20294                vec![
20295                    "f".to_string(),
20296                    "i".to_string(),
20297                    "b".to_string(),
20298                    "name".to_string(),
20299                ],
20300            )
20301            .unwrap()
20302        };
20303        let frame_fast = mk(Column::from_utf8_contiguous(nb, no));
20304        let frame_general = mk(Column::from_values(eager_names).unwrap());
20305
20306        let ctl = frame_general.column("name").unwrap();
20307        assert!(
20308            ctl.as_utf8_contiguous().is_none() && ctl.as_nullable_utf8_contiguous().is_none(),
20309            "control name column must force the serde tree"
20310        );
20311
20312        for orient in [JsonOrient::Records, JsonOrient::Columns] {
20313            let fast = write_json_string(&frame_fast, orient).expect("fast json");
20314            let general = write_json_string(&frame_general, orient).expect("general json");
20315            assert_eq!(
20316                fast, general,
20317                "fast nullable-numeric JSON ({orient:?}) must byte-match the serde tree"
20318            );
20319        }
20320    }
20321
20322    #[test]
20323    fn test_write_csv_nullable_typed_fast_matches_general() {
20324        // Nullable Float64 (FastCol::FN), Int64 (FastCol::IN), and Bool (FastCol::BN)
20325        // columns take the fast CSV writer. Output must be BYTE-IDENTICAL to the general
20326        // (Scalar) writer, which the same frame falls to when an EAGER Utf8 column forces
20327        // it off the fast path.
20328        // Covers: validity-clear missing, a valid-bit NaN (still → na_rep), whole numbers
20329        // ("1.0"), negatives, large magnitude (sci notation), i64::MIN/MAX; default +
20330        // na_rep configs.
20331        let n = 9usize;
20332        let fdata: Vec<f64> = vec![
20333            1.0,
20334            -2.5,
20335            0.0,
20336            f64::NAN,
20337            1e20,
20338            -0.0,
20339            std::f64::consts::PI,
20340            100.0,
20341            42.0,
20342        ];
20343        let mut fv = fp_columnar::ValidityMask::all_valid(n);
20344        fv.set(2, false); // validity-clear (data 0.0 → must render na_rep, not "0.0")
20345        fv.set(7, false); // validity-clear
20346        // slot 3 is a VALID-bit NaN (fv still set) → must also render na_rep.
20347
20348        let idata: Vec<i64> = vec![0, i64::MIN, i64::MAX, -1, 1000, 0, -999999, 7, 123456789];
20349        let mut iv = fp_columnar::ValidityMask::all_valid(n);
20350        iv.set(0, false); // validity-clear (data 0 → na_rep, not "0")
20351        iv.set(5, false);
20352
20353        // nullable Bool: present ⇒ True/False, missing ⇒ na_rep.
20354        let bdata = vec![true, false, true, false, true, false, true, false, true];
20355        let mut bv = fp_columnar::ValidityMask::all_valid(n);
20356        bv.set(1, false); // validity-clear (data false → na_rep, not "False")
20357        bv.set(8, false); // validity-clear (data true → na_rep, not "True")
20358
20359        let names: Vec<&str> = vec!["a", "b,c", "d", "e", "", "f\"g", "h", "plain", "z"];
20360        let mut nb: Vec<u8> = Vec::new();
20361        let mut no: Vec<usize> = vec![0];
20362        for s in &names {
20363            nb.extend_from_slice(s.as_bytes());
20364            no.push(nb.len());
20365        }
20366        let eager_names: Vec<Scalar> = names
20367            .iter()
20368            .map(|s| Scalar::Utf8((*s).to_string()))
20369            .collect();
20370
20371        let mk = |name_col: Column| -> DataFrame {
20372            let mut cols = std::collections::BTreeMap::new();
20373            cols.insert(
20374                "f".to_string(),
20375                Column::from_f64_values_with_validity(fdata.clone(), fv.clone()),
20376            );
20377            cols.insert(
20378                "i".to_string(),
20379                Column::from_i64_values_with_validity(idata.clone(), iv.clone()),
20380            );
20381            cols.insert(
20382                "b".to_string(),
20383                Column::from_bool_values_with_validity(bdata.clone(), bv.clone()),
20384            );
20385            cols.insert("name".to_string(), name_col);
20386            DataFrame::new_with_column_order(
20387                Index::new_known_unique_int64_unit_range(0, n),
20388                cols,
20389                vec![
20390                    "f".to_string(),
20391                    "i".to_string(),
20392                    "b".to_string(),
20393                    "name".to_string(),
20394                ],
20395            )
20396            .unwrap()
20397        };
20398        let frame_fast = mk(Column::from_utf8_contiguous(nb, no));
20399        let frame_general = mk(Column::from_values(eager_names).unwrap());
20400
20401        // The eager name column forces the whole general frame off the fast path.
20402        let ctl = frame_general.column("name").unwrap();
20403        assert!(
20404            ctl.as_utf8_contiguous().is_none() && ctl.as_nullable_utf8_contiguous().is_none(),
20405            "control name column must force the general writer"
20406        );
20407
20408        for options in [
20409            CsvWriteOptions::default(),
20410            CsvWriteOptions {
20411                na_rep: "NA".to_string(),
20412                ..CsvWriteOptions::default()
20413            },
20414        ] {
20415            assert!(
20416                super::try_write_csv_typed(&frame_fast, &options).is_some(),
20417                "nullable typed frame must stay on the fast CSV writer"
20418            );
20419            let fast = write_csv_string_with_options(&frame_fast, &options).expect("fast");
20420            let general = write_csv_string_with_options(&frame_general, &options).expect("general");
20421            assert_eq!(
20422                fast, general,
20423                "fast nullable-numeric CSV must byte-match the general writer"
20424            );
20425        }
20426    }
20427
20428    #[test]
20429    fn test_write_csv_options_header_false_omits_header_row() {
20430        let input = "a,b\n1,2\n";
20431        let frame = read_csv_str(input).expect("read");
20432        let output = write_csv_string_with_options(
20433            &frame,
20434            &CsvWriteOptions {
20435                header: false,
20436                ..CsvWriteOptions::default()
20437            },
20438        )
20439        .expect("write");
20440        assert_eq!(output, "1,2\n");
20441    }
20442
20443    #[test]
20444    fn test_write_csv_options_include_index_and_index_label() {
20445        let input = "a,b\n1,2\n3,4\n";
20446        let frame = read_csv_str(input).expect("read");
20447        let output = write_csv_string_with_options(
20448            &frame,
20449            &CsvWriteOptions {
20450                include_index: true,
20451                index_label: Some("row_id".to_string()),
20452                ..CsvWriteOptions::default()
20453            },
20454        )
20455        .expect("write");
20456
20457        assert_eq!(output, "row_id,a,b\n0,1,2\n1,3,4\n");
20458    }
20459
20460    #[test]
20461    fn test_write_csv_options_include_index_uses_named_index_when_label_omitted() {
20462        let mut cols = std::collections::BTreeMap::new();
20463        cols.insert(
20464            "a".to_string(),
20465            Column::from_values(vec![Scalar::Int64(10), Scalar::Int64(20)]).unwrap(),
20466        );
20467        let frame = DataFrame::new_with_column_order(
20468            Index::from_i64(vec![100, 200]).set_name("sample_id"),
20469            cols,
20470            vec!["a".to_string()],
20471        )
20472        .unwrap();
20473
20474        let output = write_csv_string_with_options(
20475            &frame,
20476            &CsvWriteOptions {
20477                include_index: true,
20478                ..CsvWriteOptions::default()
20479            },
20480        )
20481        .expect("write");
20482
20483        assert_eq!(output, "sample_id,a\n100,10\n200,20\n");
20484    }
20485
20486    #[test]
20487    fn test_write_csv_options_include_index_label_overrides_index_name() {
20488        let mut cols = std::collections::BTreeMap::new();
20489        cols.insert(
20490            "a".to_string(),
20491            Column::from_values(vec![Scalar::Int64(10), Scalar::Int64(20)]).unwrap(),
20492        );
20493        let frame = DataFrame::new_with_column_order(
20494            Index::from_i64(vec![100, 200]).set_name("sample_id"),
20495            cols,
20496            vec!["a".to_string()],
20497        )
20498        .unwrap();
20499
20500        let output = write_csv_string_with_options(
20501            &frame,
20502            &CsvWriteOptions {
20503                include_index: true,
20504                index_label: Some("row".to_string()),
20505                ..CsvWriteOptions::default()
20506            },
20507        )
20508        .expect("write");
20509
20510        assert_eq!(output, "row,a\n100,10\n200,20\n");
20511    }
20512
20513    #[test]
20514    fn test_csv_multiindex_roundtrip_with_explicit_index_cols() {
20515        let frame = make_row_multiindex_test_dataframe();
20516        let csv = write_csv_string_with_options(
20517            &frame,
20518            &CsvWriteOptions {
20519                include_index: true,
20520                ..CsvWriteOptions::default()
20521            },
20522        )
20523        .expect("write");
20524
20525        let roundtrip = read_csv_with_index_cols(
20526            &csv,
20527            &CsvReadOptions::default(),
20528            &["region", "product", "year"],
20529        )
20530        .expect("read");
20531
20532        assert!(roundtrip.equals(&frame));
20533        assert_eq!(roundtrip.row_multiindex(), frame.row_multiindex());
20534    }
20535
20536    #[test]
20537    fn test_write_csv_options_default_matches_write_csv_string() {
20538        let input = "a,b\n1,2\n3,4\n";
20539        let frame = read_csv_str(input).expect("read");
20540        let default_output = write_csv_string(&frame).expect("write");
20541        let options_output =
20542            write_csv_string_with_options(&frame, &CsvWriteOptions::default()).expect("write");
20543        assert_eq!(default_output, options_output);
20544    }
20545
20546    #[test]
20547    fn test_write_csv_options_na_rep_with_float_nan() {
20548        // Generate a frame with an explicit NaN float.
20549        use fp_columnar::Column;
20550        let mut cols = std::collections::BTreeMap::new();
20551        cols.insert(
20552            "score".to_string(),
20553            Column::from_values(vec![Scalar::Float64(1.5), Scalar::Float64(f64::NAN)]).unwrap(),
20554        );
20555        let frame = DataFrame::new_with_column_order(
20556            Index::from_i64(vec![0, 1]),
20557            cols,
20558            vec!["score".to_string()],
20559        )
20560        .unwrap();
20561        let output = write_csv_string_with_options(
20562            &frame,
20563            &CsvWriteOptions {
20564                na_rep: "NaN".to_string(),
20565                ..CsvWriteOptions::default()
20566            },
20567        )
20568        .expect("write");
20569        assert!(output.contains("NaN"));
20570    }
20571
20572    #[test]
20573    fn test_csv_large_file_perf() {
20574        // 100K-row, 10-column CSV -> parse completes, correct row/column counts.
20575        let col_count = 10;
20576        let row_count = 100_000;
20577        let headers: Vec<String> = (0..col_count).map(|i| format!("col{i}")).collect();
20578        let mut csv = String::with_capacity(row_count * 50);
20579        csv.push_str(&headers.join(","));
20580        csv.push('\n');
20581        for r in 0..row_count {
20582            for c in 0..col_count {
20583                if c > 0 {
20584                    csv.push(',');
20585                }
20586                csv.push_str(&(r * col_count + c).to_string());
20587            }
20588            csv.push('\n');
20589        }
20590
20591        let frame = read_csv_str(&csv).expect("parse 100K rows");
20592        assert_eq!(frame.index().len(), row_count);
20593        assert_eq!(frame.columns().len(), col_count);
20594        // Spot-check first and last rows
20595        assert_eq!(frame.column("col0").unwrap().values()[0], Scalar::Int64(0));
20596        assert_eq!(
20597            frame.column("col9").unwrap().values()[row_count - 1],
20598            Scalar::Int64(((row_count - 1) * col_count + 9) as i64)
20599        );
20600        eprintln!(
20601            "[TEST] test_csv_large_file_perf | rows={row_count} cols={col_count} parse_ok=true | PASS"
20602        );
20603    }
20604
20605    #[test]
20606    fn test_csv_golden_output() {
20607        // Fixed CSV input -> write_csv_string output matches golden reference exactly.
20608        let input = "a,b,c\n1,hello,3.14\n2,,true\n3,world,\n";
20609        let frame = read_csv_str(input).expect("parse");
20610        let output = write_csv_string(&frame).expect("write");
20611
20612        // GOLDEN-CHANGE (live pandas 2.2.3): read_csv keeps c as object because it
20613        // contains the string token "true"; to_csv(index=False) therefore emits
20614        // the original `true` spelling rather than coercing it to Float64 1.0.
20615        let expected = "a,b,c\n1,hello,3.14\n2,,true\n3,world,\n";
20616        assert_eq!(
20617            output, expected,
20618            "output does not match golden reference.\nGot:\n{output}\nExpected:\n{expected}"
20619        );
20620        eprintln!("[TEST] test_csv_golden_output | golden_match=true | PASS");
20621    }
20622
20623    // === bd-2gi.19: IO Complete Contract Tests ===
20624
20625    use super::{CsvOnBadLines, CsvReadOptions, read_csv_with_options};
20626
20627    #[test]
20628    fn csv_with_custom_delimiter() {
20629        let input = "a\tb\tc\n1\t2\t3\n4\t5\t6\n";
20630        let opts = CsvReadOptions {
20631            delimiter: b'\t',
20632            ..Default::default()
20633        };
20634        let frame = read_csv_with_options(input, &opts).expect("parse tsv");
20635        assert_eq!(frame.index().len(), 2);
20636        assert_eq!(frame.column("a").unwrap().values()[0], Scalar::Int64(1));
20637    }
20638
20639    #[test]
20640    fn csv_without_headers_generates_default_names_and_keeps_first_row() {
20641        let input = "1,2\n3,4\n";
20642        let opts = CsvReadOptions {
20643            has_headers: false,
20644            ..Default::default()
20645        };
20646        let frame = read_csv_with_options(input, &opts).expect("parse");
20647        assert_eq!(frame.index().len(), 2);
20648        assert_eq!(
20649            frame.column("column_0").unwrap().values()[0],
20650            Scalar::Int64(1)
20651        );
20652        assert_eq!(
20653            frame.column("column_1").unwrap().values()[0],
20654            Scalar::Int64(2)
20655        );
20656        assert_eq!(
20657            frame.column("column_0").unwrap().values()[1],
20658            Scalar::Int64(3)
20659        );
20660        assert_eq!(
20661            frame.column("column_1").unwrap().values()[1],
20662            Scalar::Int64(4)
20663        );
20664    }
20665
20666    #[test]
20667    fn csv_usecols_missing_column_errors() {
20668        let input = "a,b\n1,2\n";
20669        let opts = CsvReadOptions {
20670            usecols: Some(vec!["c".to_string()]),
20671            ..Default::default()
20672        };
20673        let err = read_csv_with_options(input, &opts).expect_err("missing usecols");
20674        assert!(
20675            matches!(err, IoError::MissingUsecols(missing) if missing == vec!["c".to_string()])
20676        );
20677    }
20678
20679    #[test]
20680    fn csv_without_headers_supports_generated_index_col_name() {
20681        let input = "10,alpha\n20,beta\n";
20682        let opts = CsvReadOptions {
20683            has_headers: false,
20684            index_col: Some("column_0".into()),
20685            ..Default::default()
20686        };
20687        let frame = read_csv_with_options(input, &opts).expect("parse");
20688        assert_eq!(frame.index().len(), 2);
20689        assert_eq!(frame.index().labels()[0], IndexLabel::Int64(10));
20690        assert_eq!(frame.index().labels()[1], IndexLabel::Int64(20));
20691        assert!(frame.column("column_0").is_none());
20692        assert_eq!(
20693            frame.column("column_1").unwrap().values()[0],
20694            Scalar::Utf8("alpha".into())
20695        );
20696        assert_eq!(
20697            frame.column("column_1").unwrap().values()[1],
20698            Scalar::Utf8("beta".into())
20699        );
20700    }
20701
20702    #[test]
20703    fn csv_with_na_values() {
20704        let input = "a,b\n1,NA\n2,n/a\n3,valid\n";
20705        let opts = CsvReadOptions {
20706            na_values: vec!["NA".into(), "n/a".into()],
20707            ..Default::default()
20708        };
20709        let frame = read_csv_with_options(input, &opts).expect("parse");
20710        let b = frame.column("b").unwrap();
20711        assert!(b.values()[0].is_missing());
20712        assert!(b.values()[1].is_missing());
20713        assert_eq!(b.values()[2], Scalar::Utf8("valid".into()));
20714    }
20715
20716    #[test]
20717    fn csv_none_is_default_na() {
20718        // "None" is a pandas default NA value (Python's None)
20719        let input = "a,b\n1,None\n2,valid\n";
20720        let frame = read_csv_str(input).expect("parse");
20721        let b = frame.column("b").unwrap();
20722        assert!(b.values()[0].is_missing(), "None should be parsed as NA");
20723        assert_eq!(b.values()[1], Scalar::Utf8("valid".into()));
20724    }
20725
20726    #[test]
20727    fn csv_scalar_inference_matches_pandas_2_2_3() {
20728        // Per-cell type inference verified against pandas 2.2.3 read_csv.
20729        let cell = |csv: &str| {
20730            let frame = read_csv_str(&format!("x\n{csv}\n")).expect("parse");
20731            frame.column("x").unwrap().values()[0].clone()
20732        };
20733        // Signed / leading-zero integers parse as Int64 (Rust + pandas agree).
20734        assert_eq!(cell("+1"), Scalar::Int64(1));
20735        assert_eq!(cell("01"), Scalar::Int64(1));
20736        assert_eq!(cell("-5"), Scalar::Int64(-5));
20737        // Scientific notation is float64 in pandas.
20738        assert_eq!(cell("1e3"), Scalar::Float64(1000.0));
20739        // inf / -inf are float values (NOT default-NA tokens, unlike nan).
20740        assert_eq!(cell("inf"), Scalar::Float64(f64::INFINITY));
20741        assert_eq!(cell("-inf"), Scalar::Float64(f64::NEG_INFINITY));
20742        // Bool inference is case-insensitive in pandas 2.2.3.
20743        assert_eq!(cell("TRUE"), Scalar::Bool(true));
20744        assert_eq!(cell("true"), Scalar::Bool(true));
20745        assert_eq!(cell("False"), Scalar::Bool(false));
20746        // Surrounding whitespace is trimmed ONLY for numeric inference.
20747        assert_eq!(cell(" 1 "), Scalar::Int64(1));
20748        assert_eq!(cell("  3.5  "), Scalar::Float64(3.5));
20749        // Non-numeric, non-bool stays Utf8.
20750        assert_eq!(cell("hello"), Scalar::Utf8("hello".into()));
20751        // NA markers, booleans, and plain strings keep their surrounding
20752        // whitespace — a padded value is a STRING, not null/bool. Verified vs
20753        // live pandas 2.2.3: " abc "/"true "/" NA " all stay object strings.
20754        assert_eq!(cell(" abc "), Scalar::Utf8(" abc ".into()));
20755        assert_eq!(cell("true "), Scalar::Utf8("true ".into()));
20756        assert_eq!(cell(" True "), Scalar::Utf8(" True ".into()));
20757        assert_eq!(cell(" NA "), Scalar::Utf8(" NA ".into()));
20758        assert!(!matches!(cell(" NA "), Scalar::Null(_)));
20759    }
20760
20761    #[test]
20762    fn json_write_non_finite_floats_as_null_like_pandas() {
20763        // pandas to_json(orient="records") converts inf / -inf / NaN to JSON
20764        // `null` (JSON has no inf/nan literals). Verified vs pandas 2.2.3:
20765        // read_csv("x\n1.5\ninf\n-inf\n").to_json(orient="records")
20766        //   == [{"x":1.5},{"x":null},{"x":null}]
20767        let frame = read_csv_str("x\n1.5\ninf\n-inf\n").expect("parse");
20768        let json = write_json_string(&frame, JsonOrient::Records).expect("json");
20769        assert_eq!(json, r#"[{"x":1.5},{"x":null},{"x":null}]"#);
20770    }
20771
20772    #[test]
20773    fn json_direct_float_spelling_matches_serde() {
20774        // The typed writer deliberately bypasses serde's formatter on its hot
20775        // path. Lock its shortest-round-trip spelling to the serde reference
20776        // at fixed, scientific, subnormal, signed-zero, and largest-finite
20777        // boundaries before the writer uses it for every cell in a document.
20778        for value in [
20779            -0.0,
20780            0.0,
20781            1.0,
20782            -1.0,
20783            1.25,
20784            1e-7,
20785            1e-6,
20786            1e20,
20787            f64::MIN_POSITIVE,
20788            f64::from_bits(1),
20789            f64::MAX,
20790        ] {
20791            let mut direct = String::new();
20792            let mut float_buffer = zmij::Buffer::new();
20793            super::append_json_finite_f64(&mut direct, value, &mut float_buffer);
20794            assert_eq!(
20795                direct,
20796                serde_json::to_string(&value).expect("finite JSON float")
20797            );
20798        }
20799    }
20800
20801    #[test]
20802    fn csv_default_na_token_set_matches_pandas_table() {
20803        let default_tokens = [
20804            "", "#N/A", "#N/A N/A", "#NA", "-1.#IND", "-1.#QNAN", "-NaN", "-nan", "1.#IND",
20805            "1.#QNAN", "<NA>", "N/A", "NA", "NULL", "NaN", "None", "n/a", "nan", "null",
20806        ];
20807        for token in default_tokens {
20808            assert!(super::is_pandas_default_na(token), "{token:?}");
20809        }
20810
20811        for token in ["none", "NAN", "n/a ", " NULL", "0", "false"] {
20812            assert!(!super::is_pandas_default_na(token), "{token:?}");
20813        }
20814    }
20815
20816    #[test]
20817    fn csv_keep_default_na_false() {
20818        // With keep_default_na=false, only custom na_values are recognized
20819        let input = "a,b\n1,NA\n2,CUSTOM\n3,valid\n";
20820        let opts = CsvReadOptions {
20821            na_values: vec!["CUSTOM".into()],
20822            keep_default_na: false,
20823            ..Default::default()
20824        };
20825        let frame = read_csv_with_options(input, &opts).expect("parse");
20826        let b = frame.column("b").unwrap();
20827        // "NA" should NOT be missing because keep_default_na=false
20828        assert_eq!(b.values()[0], Scalar::Utf8("NA".into()));
20829        // "CUSTOM" should be missing because it's in na_values
20830        assert!(b.values()[1].is_missing());
20831        assert_eq!(b.values()[2], Scalar::Utf8("valid".into()));
20832    }
20833
20834    #[test]
20835    fn csv_na_filter_false() {
20836        // With na_filter=false, no NA detection at all (for performance)
20837        let input = "a,b\n1,NA\n2,\n3,None\n";
20838        let opts = CsvReadOptions {
20839            na_filter: false,
20840            ..Default::default()
20841        };
20842        let frame = read_csv_with_options(input, &opts).expect("parse");
20843        let b = frame.column("b").unwrap();
20844        // All values should be kept as strings, no NA detection
20845        assert_eq!(b.values()[0], Scalar::Utf8("NA".into()));
20846        assert_eq!(b.values()[1], Scalar::Utf8("".into()));
20847        assert_eq!(b.values()[2], Scalar::Utf8("None".into()));
20848    }
20849
20850    #[test]
20851    fn csv_with_index_col() {
20852        let input = "id,val\na,10\nb,20\nc,30\n";
20853        let opts = CsvReadOptions {
20854            index_col: Some("id".into()),
20855            ..Default::default()
20856        };
20857        let frame = read_csv_with_options(input, &opts).expect("parse");
20858        assert_eq!(frame.index().len(), 3);
20859        assert_eq!(
20860            frame.index().labels()[0],
20861            fp_index::IndexLabel::Utf8("a".into())
20862        );
20863        assert!(frame.column("id").is_none());
20864        assert_eq!(frame.column("val").unwrap().values()[0], Scalar::Int64(10));
20865    }
20866
20867    #[test]
20868    fn csv_with_missing_index_col_errors() {
20869        let input = "id,val\na,10\nb,20\n";
20870        let opts = CsvReadOptions {
20871            index_col: Some("missing".into()),
20872            ..Default::default()
20873        };
20874
20875        let err = read_csv_with_options(input, &opts).expect_err("missing index_col should error");
20876        assert!(
20877            matches!(&err, IoError::MissingIndexColumn(name) if name == "missing"),
20878            "expected MissingIndexColumn(\"missing\"), got {err:?}"
20879        );
20880    }
20881
20882    /// Was `csv_with_malformed_row_errors`. A SHORT row is not malformed to
20883    /// pandas under any `on_bad_lines` setting — it is padded (gtkz1).
20884    #[test]
20885    fn csv_with_options_short_row_pads_not_errors() {
20886        let input = "a,b\n1,2\n3\n";
20887        let opts = CsvReadOptions::default();
20888
20889        let df = read_csv_with_options(input, &opts).expect("short row pads under default options");
20890        assert_eq!(
20891            df.columns()["a"].values(),
20892            &[Scalar::Int64(1), Scalar::Int64(3)]
20893        );
20894        assert!(df.columns()["b"].values()[1].is_missing());
20895    }
20896
20897    /// ...and a UNIFORMLY overlong file is not malformed either — the excess
20898    /// leading field becomes the INDEX. It is the RAGGED file that errors.
20899    ///
20900    /// MEASURED, live pandas 2.2.3:
20901    ///
20902    /// ```text
20903    ///   'a,b\n1,2,3\n'          -> index [1]     a [2]    b [3]
20904    ///   'a,b\n1,2,3\n4,5,6\n'   -> index [1,4]   a [2,5]  b [3,6]
20905    ///   'a,b\n1,2\n3,4,5\n'     -> ParserError: Expected 2 fields in line 3, saw 3
20906    /// ```
20907    ///
20908    /// and the first of those SUCCEEDS under every `on_bad_lines` setting —
20909    /// error, warn and skip all return that same frame, because an evenly
20910    /// overlong file is never a bad line to begin with.
20911    ///
20912    /// This assertion previously required `IoError::CsvFieldCount` for the
20913    /// uniform case. br-frankenpandas-azv2h implemented the index promotion at
20914    /// 90b48d995 and closed on a SCOPED gate ("focused remote regression, fp-io
20915    /// check"), so a whole-crate `cargo test -p fp-io` never ran and this
20916    /// sibling was left RED on main. Its neighbour above,
20917    /// `csv_with_options_short_row_pads_not_errors`, was updated at the time;
20918    /// this one was missed. (br-frankenpandas-t612p)
20919    ///
20920    /// BOTH ARMS ARE LOAD-BEARING. Keep only the success arm and an
20921    /// implementation that merely stops erroring — dropping the extra field and
20922    /// returning a default `RangeIndex` — passes. Keep only the error arm and
20923    /// the refuted contract comes straight back.
20924    ///
20925    /// NOT ASSERTED, measured but not implemented: with TWO extra fields per row
20926    /// pandas builds a 2-LEVEL index (`'a,b\n1,2,3,4\n'` -> index `[(1, 2)]`,
20927    /// a `[3]`, b `[4]`). azv2h implemented the uniform ONE-extra case only, so
20928    /// that is a known boundary rather than a guarded behaviour.
20929    #[test]
20930    fn csv_with_options_uniform_overlong_row_promotes_index_t612p() {
20931        let opts = CsvReadOptions::default();
20932
20933        let df = read_csv_with_options("a,b\n1,2,3\n", &opts)
20934            .expect("a uniformly overlong row promotes its extra field to the index");
20935        assert_eq!(
20936            df.columns()["a"].values(),
20937            &[Scalar::Int64(2)],
20938            "the SECOND field is column a"
20939        );
20940        assert_eq!(df.columns()["b"].values(), &[Scalar::Int64(3)]);
20941        assert_eq!(
20942            df.index().labels(),
20943            &[IndexLabel::Int64(1)],
20944            "the excess leading field must land in the INDEX, not be dropped"
20945        );
20946
20947        // A RAGGED file — one conforming row and one overlong — is still an
20948        // error, which is what keeps this from being "stop checking".
20949        let ragged = read_csv_with_options("a,b\n1,2\n3,4,5\n", &opts)
20950            .expect_err("a ragged file is still malformed");
20951        assert!(
20952            matches!(
20953                &ragged,
20954                IoError::CsvFieldCount {
20955                    line: 3,
20956                    expected: 2,
20957                    found: 3
20958                }
20959            ),
20960            "got {ragged:?}"
20961        );
20962    }
20963
20964    #[test]
20965    fn csv_on_bad_lines_skip_skips_extra_field_rows() {
20966        let input = "a,b\n1,2\n3,4,5\n6,7\n";
20967        let opts = CsvReadOptions {
20968            on_bad_lines: CsvOnBadLines::Skip,
20969            ..Default::default()
20970        };
20971
20972        let frame = read_csv_with_options(input, &opts).expect("parse with skipped bad line");
20973        assert_eq!(frame.index().len(), 2);
20974        assert_eq!(frame.column("a").unwrap().values()[0], Scalar::Int64(1));
20975        assert_eq!(frame.column("b").unwrap().values()[0], Scalar::Int64(2));
20976        assert_eq!(frame.column("a").unwrap().values()[1], Scalar::Int64(6));
20977        assert_eq!(frame.column("b").unwrap().values()[1], Scalar::Int64(7));
20978    }
20979
20980    #[test]
20981    fn csv_on_bad_lines_warn_skips_extra_field_rows() {
20982        let input = "a,b\n1,2\n3,4,5\n6,7\n";
20983        let opts = CsvReadOptions {
20984            on_bad_lines: CsvOnBadLines::Warn,
20985            ..Default::default()
20986        };
20987
20988        let frame = read_csv_with_options(input, &opts).expect("parse with warned bad line");
20989        assert_eq!(frame.index().len(), 2);
20990        assert_eq!(frame.column("a").unwrap().values()[0], Scalar::Int64(1));
20991        assert_eq!(frame.column("b").unwrap().values()[1], Scalar::Int64(7));
20992    }
20993
20994    #[test]
20995    fn csv_on_bad_lines_skip_preserves_short_rows_as_missing() {
20996        // Pandas widens inferred int64 to float64 when a short row introduces NA.
20997        let input = "a,b\n1,2\n3\n6,7\n";
20998        let opts = CsvReadOptions {
20999            on_bad_lines: CsvOnBadLines::Skip,
21000            ..Default::default()
21001        };
21002
21003        let frame = read_csv_with_options(input, &opts).expect("parse short row");
21004        assert_eq!(frame.index().len(), 3);
21005        assert_eq!(frame.column("a").unwrap().values()[1], Scalar::Int64(3));
21006        assert_eq!(frame.column("b").unwrap().dtype(), DType::Float64);
21007        assert!(frame.column("b").unwrap().values()[1].is_missing());
21008    }
21009
21010    #[test]
21011    fn json_temporal_values_and_index_are_epoch_millis() {
21012        // pandas to_json (date_unit='ms') serializes datetime64/timedelta64 as
21013        // epoch-millisecond integers for both values and index — not ISO/format
21014        // strings (values) nor raw nanoseconds (index). (br-frankenpandas-lb0iu)
21015        // 2020-01-01T00:00:00 == 1_577_836_800_000 ms; 1s timedelta == 1000 ms.
21016        let dt_ns = 1_577_836_800_000_000_000_i64;
21017        let mut columns = BTreeMap::new();
21018        columns.insert(
21019            "d".to_owned(),
21020            Column::from_values(vec![Scalar::Datetime64(dt_ns)]).expect("d"),
21021        );
21022        columns.insert(
21023            "t".to_owned(),
21024            Column::from_values(vec![Scalar::Timedelta64(1_000_000_000)]).expect("t"),
21025        );
21026        let index = Index::new(vec![IndexLabel::Datetime64(dt_ns)]);
21027        let frame =
21028            DataFrame::new_with_column_order(index, columns, vec!["d".to_owned(), "t".to_owned()])
21029                .expect("frame");
21030
21031        let out = write_json_string(&frame, JsonOrient::Columns).expect("json");
21032        assert!(
21033            out.contains("1577836800000"),
21034            "datetime value/index should be epoch-millis int, got {out}"
21035        );
21036        assert!(
21037            out.contains("1000"),
21038            "timedelta value should be epoch-millis int (1000), got {out}"
21039        );
21040        // Must NOT contain the old ISO string or raw-nanosecond forms.
21041        assert!(
21042            !out.contains("2020-01-01"),
21043            "should not emit ISO string: {out}"
21044        );
21045        assert!(
21046            !out.contains("1577836800000000000"),
21047            "should not emit raw nanoseconds: {out}"
21048        );
21049    }
21050
21051    #[test]
21052    fn json_records_read_write_roundtrip() {
21053        let input = r#"[{"name":"Alice","age":30},{"name":"Bob","age":25}]"#;
21054        let frame = read_json_str(input, JsonOrient::Records).expect("read json records");
21055        assert_eq!(frame.index().len(), 2);
21056        assert_eq!(
21057            frame.column("name").unwrap().values()[0],
21058            Scalar::Utf8("Alice".into())
21059        );
21060        assert_eq!(frame.column("age").unwrap().values()[1], Scalar::Int64(25));
21061
21062        let output = write_json_string(&frame, JsonOrient::Records).expect("write");
21063        let frame2 = read_json_str(&output, JsonOrient::Records).expect("re-read");
21064        assert_eq!(frame2.index().len(), 2);
21065    }
21066
21067    #[test]
21068    fn json_records_nullable_int_roundtrip_is_stable() {
21069        let input = r#"[{"city":"Boston","temp":72},{"city":"Paris","temp":null}]"#;
21070        let frame = read_json_str(input, JsonOrient::Records).expect("read json records");
21071        let output = write_json_string(&frame, JsonOrient::Records).expect("write records");
21072        let frame2 = read_json_str(&output, JsonOrient::Records).expect("re-read records");
21073
21074        assert!(frame.equals(&frame2));
21075    }
21076
21077    #[test]
21078    fn json_records_preserves_column_order() {
21079        let input = r#"[{"b":1,"a":2},{"c":3}]"#;
21080        let frame = read_json_str(input, JsonOrient::Records).expect("read json records");
21081        let order: Vec<&str> = frame
21082            .column_names()
21083            .iter()
21084            .map(|name| name.as_str())
21085            .collect();
21086        assert_eq!(order, vec!["b", "a", "c"]);
21087    }
21088
21089    #[test]
21090    fn json_columns_read_write_roundtrip() {
21091        let input = r#"{"name":{"row_a":"Alice","row_b":"Bob"},"age":{"row_a":30,"row_b":25}}"#;
21092        let frame = read_json_str(input, JsonOrient::Columns).expect("read json columns");
21093        assert_eq!(frame.index().len(), 2);
21094        assert_eq!(frame.index().labels()[0], IndexLabel::Utf8("row_a".into()));
21095
21096        let output = write_json_string(&frame, JsonOrient::Columns).expect("write");
21097        let frame2 = read_json_str(&output, JsonOrient::Columns).expect("re-read");
21098        assert_eq!(frame2.index().labels(), frame.index().labels());
21099    }
21100
21101    #[test]
21102    fn json_columns_write_duplicate_index_rejects() {
21103        let index = Index::new(vec![IndexLabel::Int64(1), IndexLabel::Utf8("1".into())]);
21104        let mut columns = BTreeMap::new();
21105        columns.insert(
21106            "v".into(),
21107            Column::from_values(vec![Scalar::Int64(10), Scalar::Int64(20)]).expect("col"),
21108        );
21109        let frame = DataFrame::new(index, columns).expect("frame");
21110
21111        let err = write_json_string(&frame, JsonOrient::Columns)
21112            .expect_err("duplicate JSON object keys should reject");
21113        assert!(
21114            matches!(&err, IoError::JsonFormat(msg) if msg.contains("duplicate index label key")),
21115            "expected duplicate-index-key JsonFormat, got {err:?}"
21116        );
21117    }
21118
21119    #[test]
21120    fn json_split_read_write_roundtrip() {
21121        let input = r#"{"columns":["x","y"],"index":["r1","r2","r3"],"data":[[1,4],[2,5],[3,6]]}"#;
21122        let frame = read_json_str(input, JsonOrient::Split).expect("read json split");
21123        assert_eq!(frame.index().len(), 3);
21124        assert_eq!(
21125            frame.index().labels()[0],
21126            fp_index::IndexLabel::Utf8("r1".into())
21127        );
21128        assert_eq!(frame.column("x").unwrap().values()[0], Scalar::Int64(1));
21129        assert_eq!(frame.column("y").unwrap().values()[2], Scalar::Int64(6));
21130
21131        let output = write_json_string(&frame, JsonOrient::Split).expect("write");
21132        let frame2 = read_json_str(&output, JsonOrient::Split).expect("re-read");
21133        assert_eq!(frame2.index().len(), 3);
21134        assert_eq!(frame2.index().labels(), frame.index().labels());
21135    }
21136
21137    #[test]
21138    fn json_records_multiindex_roundtrip_restores_logical_row_axis() {
21139        let frame = make_row_multiindex_test_dataframe();
21140        let json = write_json_string(&frame, JsonOrient::Records).expect("write");
21141        let roundtrip = read_json_str(&json, JsonOrient::Records).expect("read");
21142
21143        assert!(roundtrip.equals(&frame));
21144        assert!(roundtrip.row_multiindex().is_some());
21145        assert!(roundtrip.column("__index_level_0__").is_none());
21146    }
21147
21148    #[test]
21149    fn json_split_multiindex_roundtrip_restores_logical_row_axis() {
21150        let frame = make_row_multiindex_test_dataframe();
21151        let json = write_json_string(&frame, JsonOrient::Split).expect("write");
21152        let roundtrip = read_json_str(&json, JsonOrient::Split).expect("read");
21153
21154        assert!(roundtrip.equals(&frame));
21155        assert!(roundtrip.row_multiindex().is_some());
21156        assert!(roundtrip.column("__index_level_0__").is_none());
21157        // br-frankenpandas-wfkzm: the `index_names` key carries the level names.
21158        assert!(json.contains("\"index_names\":[\"region\",\"product\",\"year\"]"));
21159        assert_eq!(
21160            roundtrip.row_multiindex().unwrap().names().to_vec(),
21161            frame.row_multiindex().unwrap().names().to_vec()
21162        );
21163        // A payload without the key (older writer, or hand-written) still
21164        // round-trips the values and keeps the synthetic names honestly.
21165        let without_key = json.replace(",\"index_names\":[\"region\",\"product\",\"year\"]", "");
21166        let older = read_json_str(&without_key, JsonOrient::Split).expect("read old shape");
21167        assert!(older.row_multiindex().is_some());
21168        assert_eq!(
21169            older.row_multiindex().unwrap().names().to_vec(),
21170            vec![
21171                Some("__index_level_0__".to_owned()),
21172                Some("__index_level_1__".to_owned()),
21173                Some("__index_level_2__".to_owned()),
21174            ]
21175        );
21176    }
21177
21178    #[test]
21179    fn json_split_without_index_defaults_to_range_index() {
21180        let input = r#"{"columns":["x"],"data":[[10],[20]]}"#;
21181        let frame = read_json_str(input, JsonOrient::Split).expect("read json split");
21182        assert_eq!(frame.index().labels()[0], fp_index::IndexLabel::Int64(0));
21183        assert_eq!(frame.index().labels()[1], fp_index::IndexLabel::Int64(1));
21184    }
21185
21186    #[test]
21187    fn json_split_index_length_mismatch_errors() {
21188        let input = r#"{"columns":["x"],"index":[0],"data":[[1],[2]]}"#;
21189        let err = read_json_str(input, JsonOrient::Split)
21190            .expect_err("split orient index/data length mismatch should error");
21191        assert!(
21192            matches!(&err, IoError::JsonFormat(msg) if msg.contains("index length")),
21193            "expected split index length error, got {err:?}"
21194        );
21195    }
21196
21197    #[test]
21198    fn json_split_row_length_mismatch_errors() {
21199        let input = r#"{"columns":["x","y"],"data":[[1],[2,3]]}"#;
21200        let err = read_json_str(input, JsonOrient::Split)
21201            .expect_err("split orient row length mismatch should error");
21202        assert!(
21203            matches!(&err, IoError::JsonFormat(msg) if msg.contains("row 0 length")),
21204            "expected split row length error, got {err:?}"
21205        );
21206    }
21207
21208    #[test]
21209    fn json_split_non_string_columns_are_stringified() {
21210        let input = r#"{"columns":[1,true,null,"name"],"data":[[10,20,30,40]]}"#;
21211        let frame = read_json_str(input, JsonOrient::Split).expect("read json split");
21212        assert_eq!(frame.column("1").unwrap().values()[0], Scalar::Int64(10));
21213        assert_eq!(frame.column("true").unwrap().values()[0], Scalar::Int64(20));
21214        assert_eq!(frame.column("null").unwrap().values()[0], Scalar::Int64(30));
21215        assert_eq!(frame.column("name").unwrap().values()[0], Scalar::Int64(40));
21216    }
21217
21218    #[test]
21219    fn json_split_duplicate_column_names_error() {
21220        let input = r#"{"columns":[1,"1"],"data":[[10,20]]}"#;
21221        let err = read_json_str(input, JsonOrient::Split).expect_err("dup columns");
21222        assert!(matches!(err, IoError::DuplicateColumnName(name) if name == "1"));
21223    }
21224
21225    #[test]
21226    fn json_index_read_write_roundtrip() {
21227        let input = r#"{"row_a":{"name":"Alice","age":30},"row_b":{"name":"Bob","age":25}}"#;
21228        let frame = read_json_str(input, JsonOrient::Index).expect("read json index");
21229        assert_eq!(frame.index().len(), 2);
21230        assert_eq!(frame.index().labels()[0], IndexLabel::Utf8("row_a".into()));
21231        assert_eq!(
21232            frame.column("name").unwrap().values()[1],
21233            Scalar::Utf8("Bob".into())
21234        );
21235
21236        let output = write_json_string(&frame, JsonOrient::Index).expect("write");
21237        let frame2 = read_json_str(&output, JsonOrient::Index).expect("re-read");
21238        assert_eq!(frame2.index().labels(), frame.index().labels());
21239        assert_eq!(frame2.column("age").unwrap().values()[0], Scalar::Int64(30));
21240    }
21241
21242    #[test]
21243    fn json_index_preserves_column_order() {
21244        let input = r#"{"r1":{"b":1,"a":2},"r2":{"c":3}}"#;
21245        let frame = read_json_str(input, JsonOrient::Index).expect("parse");
21246        let order: Vec<&str> = frame
21247            .column_names()
21248            .iter()
21249            .map(|name| name.as_str())
21250            .collect();
21251        assert_eq!(order, vec!["b", "a", "c"]);
21252    }
21253
21254    #[test]
21255    fn json_index_missing_columns_null_fill() {
21256        let input = r#"{"r1":{"a":1},"r2":{"b":2}}"#;
21257        let frame = read_json_str(input, JsonOrient::Index).expect("parse");
21258        let a = frame.column("a").expect("a");
21259        let b = frame.column("b").expect("b");
21260
21261        assert_eq!(a.values()[0], Scalar::Float64(1.0));
21262        assert!(a.values()[1].is_missing());
21263        assert!(b.values()[0].is_missing());
21264        assert_eq!(b.values()[1], Scalar::Float64(2.0));
21265    }
21266
21267    #[test]
21268    fn json_index_write_duplicate_index_rejects() {
21269        let index = Index::new(vec![IndexLabel::Int64(1), IndexLabel::Utf8("1".into())]);
21270        let mut columns = BTreeMap::new();
21271        columns.insert(
21272            "v".into(),
21273            Column::from_values(vec![Scalar::Int64(10), Scalar::Int64(20)]).expect("col"),
21274        );
21275        let frame = DataFrame::new(index, columns).expect("frame");
21276
21277        let err = write_json_string(&frame, JsonOrient::Index)
21278            .expect_err("duplicate JSON object keys should reject");
21279        assert!(
21280            matches!(&err, IoError::JsonFormat(msg) if msg.contains("duplicate index label key")),
21281            "expected duplicate-index-key JsonFormat, got {err:?}"
21282        );
21283    }
21284
21285    #[test]
21286    fn json_index_read_non_object_row_rejects() {
21287        let input = r#"{"r1":{"a":1},"r2":[1,2]}"#;
21288        let err = read_json_str(input, JsonOrient::Index)
21289            .expect_err("index orient rows must be JSON objects");
21290        assert!(
21291            matches!(&err, IoError::JsonFormat(msg) if msg.contains("rows must be objects")),
21292            "expected row-object error, got {err:?}"
21293        );
21294    }
21295
21296    #[test]
21297    fn json_values_read_write_roundtrip() {
21298        let input = r#"[[1,"Alice"],[null,"Bob"]]"#;
21299        let frame = read_json_str(input, JsonOrient::Values).expect("read json values");
21300        assert_eq!(frame.index().len(), 2);
21301        assert_eq!(frame.column_names(), vec!["0", "1"]);
21302        assert_eq!(frame.column("0").unwrap().values()[0], Scalar::Float64(1.0));
21303        assert_eq!(
21304            frame.column("1").unwrap().values()[1],
21305            Scalar::Utf8("Bob".into())
21306        );
21307
21308        let output = write_json_string(&frame, JsonOrient::Values).expect("write");
21309        let frame2 = read_json_str(&output, JsonOrient::Values).expect("re-read");
21310        assert_eq!(frame2.index().len(), 2);
21311        assert_eq!(frame2.column_names(), frame.column_names());
21312        assert_eq!(
21313            frame2.column("0").unwrap().values(),
21314            frame.column("0").unwrap().values()
21315        );
21316        assert_eq!(
21317            frame2.column("1").unwrap().values(),
21318            frame.column("1").unwrap().values()
21319        );
21320    }
21321
21322    #[test]
21323    fn json_records_with_nulls() {
21324        let input = r#"[{"a":1,"b":null},{"a":null,"b":"hello"}]"#;
21325        let frame = read_json_str(input, JsonOrient::Records).expect("parse");
21326        assert!(frame.column("a").unwrap().values()[1].is_missing());
21327        assert!(frame.column("b").unwrap().values()[0].is_missing());
21328    }
21329
21330    #[test]
21331    fn json_read_accepts_pandas_bare_nan_tokens() {
21332        let cases = [
21333            (JsonOrient::Records, r#"[{"a":NaN}]"#),
21334            (JsonOrient::Columns, r#"{"a":{"0":NaN}}"#),
21335            (
21336                JsonOrient::Split,
21337                r#"{"columns":["a"],"index":[0],"data":[[NaN]]}"#,
21338            ),
21339            (JsonOrient::Values, r#"[[NaN]]"#),
21340        ];
21341
21342        for (orient, input) in cases {
21343            let frame = read_json_str(input, orient).expect("parse bare NaN");
21344            let column_name = if orient == JsonOrient::Values {
21345                "0"
21346            } else {
21347                "a"
21348            };
21349            assert!(frame.column(column_name).unwrap().values()[0].is_missing());
21350        }
21351    }
21352
21353    #[test]
21354    fn json_records_write_preserves_nullable_int_column() {
21355        // CSV inference widens integer fields with an NA to pandas-compatible Float64.
21356        let frame = DataFrame::from_dict_with_index(
21357            vec![("a", vec![Scalar::Int64(1), Scalar::Null(NullKind::Null)])],
21358            vec!["row".into(), "row".into()],
21359        )
21360        .unwrap();
21361        let json = write_json_string(&frame, JsonOrient::Records).expect("write");
21362        let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();
21363        assert_eq!(parsed, serde_json::json!([{"a": 1}, {"a": null}]));
21364    }
21365
21366    #[test]
21367    fn json_non_records_nullable_int_reads_promote_to_float() {
21368        let cases = [
21369            (JsonOrient::Columns, r#"{"a":{"0":1,"1":null}}"#),
21370            (JsonOrient::Index, r#"{"0":{"a":1},"1":{"a":null}}"#),
21371            (
21372                JsonOrient::Split,
21373                r#"{"columns":["a"],"index":[0,1],"data":[[1],[null]]}"#,
21374            ),
21375            (JsonOrient::Values, r#"[[1],[null]]"#),
21376        ];
21377
21378        for (orient, input) in cases {
21379            let frame = read_json_str(input, orient).expect("read json");
21380            let column_name = if orient == JsonOrient::Values {
21381                "0"
21382            } else {
21383                "a"
21384            };
21385            let values = frame.column(column_name).expect("column").values();
21386            assert_eq!(values[0], Scalar::Float64(1.0));
21387            assert!(matches!(values[1], Scalar::Null(NullKind::NaN)));
21388        }
21389    }
21390
21391    #[test]
21392    fn json_non_records_nullable_int_writes_preserve_int() {
21393        // DISC-011: Nullable extension Int64 dtype parity - Int64 preserved, not promoted to Float64.
21394        let frame = DataFrame::from_dict(
21395            &["a"],
21396            vec![("a", vec![Scalar::Int64(1), Scalar::Null(NullKind::Null)])],
21397        )
21398        .unwrap();
21399
21400        let columns_json: serde_json::Value =
21401            serde_json::from_str(&write_json_string(&frame, JsonOrient::Columns).unwrap()).unwrap();
21402        assert_eq!(columns_json, serde_json::json!({"a": {"0": 1, "1": null}}));
21403
21404        let index_json: serde_json::Value =
21405            serde_json::from_str(&write_json_string(&frame, JsonOrient::Index).unwrap()).unwrap();
21406        assert_eq!(
21407            index_json,
21408            serde_json::json!({"0": {"a": 1}, "1": {"a": null}})
21409        );
21410
21411        let split_json: serde_json::Value =
21412            serde_json::from_str(&write_json_string(&frame, JsonOrient::Split).unwrap()).unwrap();
21413        assert_eq!(
21414            split_json,
21415            serde_json::json!({"columns": ["a"], "index": [0, 1], "data": [[1], [null]]})
21416        );
21417
21418        let values_json: serde_json::Value =
21419            serde_json::from_str(&write_json_string(&frame, JsonOrient::Values).unwrap()).unwrap();
21420        assert_eq!(values_json, serde_json::json!([[1], [null]]));
21421    }
21422
21423    #[test]
21424    fn json_records_empty_array() {
21425        let input = r#"[]"#;
21426        let frame = read_json_str(input, JsonOrient::Records).expect("parse");
21427        assert_eq!(frame.index().len(), 0);
21428    }
21429
21430    #[test]
21431    fn json_records_mixed_numeric_coerces() {
21432        let input = r#"[{"v":1},{"v":2.5},{"v":true}]"#;
21433        let frame = read_json_str(input, JsonOrient::Records).expect("parse");
21434        // Int64 + Float64 + Bool all coerce to Float64
21435        assert_eq!(frame.column("v").unwrap().values()[0], Scalar::Float64(1.0));
21436        assert_eq!(frame.column("v").unwrap().values()[1], Scalar::Float64(2.5));
21437        assert_eq!(frame.column("v").unwrap().values()[2], Scalar::Float64(1.0));
21438    }
21439
21440    #[test]
21441    fn json_records_mixed_utf8_numeric_preserves_object_values() {
21442        let input = r#"[{"v":1},{"v":"text"}]"#;
21443        let frame = read_json_str(input, JsonOrient::Records).expect("parse");
21444        assert_eq!(
21445            frame.column("v").unwrap().values(),
21446            &[Scalar::Int64(1), Scalar::Utf8("text".into())]
21447        );
21448    }
21449
21450    #[test]
21451    fn file_csv_roundtrip() {
21452        let input = "a,b\n1,2\n3,4\n";
21453        let frame = read_csv_str(input).expect("parse");
21454
21455        let dir = std::env::temp_dir();
21456        let path = dir.join("fp_io_test_roundtrip.csv");
21457        super::write_csv(&frame, &path).expect("write file");
21458        let frame2 = super::read_csv(&path).expect("read file");
21459        assert_eq!(frame2.index().len(), 2);
21460        std::fs::remove_file(&path).ok();
21461    }
21462
21463    #[test]
21464    fn file_csv_with_options_path() {
21465        // DISC-011: Nullable extension Int64 dtype parity - Int64 preserved, not promoted to Float64.
21466        let input = "id\tval\na\tNA\nb\t2\n";
21467        let dir = std::env::temp_dir();
21468        let path = dir.join("fp_io_test_options.csv");
21469        std::fs::write(&path, input).expect("write fixture");
21470
21471        let options = CsvReadOptions {
21472            delimiter: b'\t',
21473            na_values: vec!["NA".into()],
21474            index_col: Some("id".into()),
21475            ..Default::default()
21476        };
21477
21478        let frame = super::read_csv_with_options_path(&path, &options).expect("read with options");
21479        assert_eq!(
21480            frame.index().labels()[0],
21481            fp_index::IndexLabel::Utf8("a".into())
21482        );
21483        assert!(frame.column("id").is_none());
21484        assert!(frame.column("val").unwrap().values()[0].is_missing());
21485        assert_eq!(frame.column("val").unwrap().dtype(), DType::Float64);
21486        assert_eq!(
21487            frame.column("val").unwrap().values()[1],
21488            Scalar::Float64(2.0)
21489        );
21490
21491        std::fs::remove_file(&path).ok();
21492    }
21493
21494    #[test]
21495    fn file_json_roundtrip() {
21496        let input = r#"[{"x":1},{"x":2}]"#;
21497        let frame = read_json_str(input, JsonOrient::Records).expect("parse");
21498
21499        let dir = std::env::temp_dir();
21500        let path = dir.join("fp_io_test_roundtrip.json");
21501        super::write_json(&frame, &path, JsonOrient::Records).expect("write file");
21502        let frame2 = super::read_json(&path, JsonOrient::Records).expect("read file");
21503        assert_eq!(frame2.index().len(), 2);
21504        std::fs::remove_file(&path).ok();
21505    }
21506
21507    // ── read_table 4pwr9 ───────────────────────────────────────────────
21508
21509    #[test]
21510    fn read_table_str_parses_tab_separated_4pwr9() {
21511        let input = "a\tb\tc\n1\t2\t3\n4\t5\t6\n";
21512        let frame = super::read_table_str(input).expect("parse tsv");
21513        assert_eq!(frame.index().len(), 2);
21514        assert_eq!(frame.column("a").unwrap().values()[0], Scalar::Int64(1));
21515        assert_eq!(frame.column("c").unwrap().values()[1], Scalar::Int64(6));
21516    }
21517
21518    #[test]
21519    fn read_table_with_options_overrides_default_delimiter_4pwr9() {
21520        // CSV inference widens integer fields with an NA to pandas-compatible Float64.
21521        let input = "x\ty\n1\tNA\n2\t3\n";
21522        let opts = CsvReadOptions {
21523            na_values: vec!["NA".into()],
21524            ..Default::default()
21525        };
21526        let frame = super::read_table_with_options(input, &opts).expect("parse tsv with na");
21527        assert_eq!(frame.column("y").unwrap().dtype(), DType::Float64);
21528        assert!(frame.column("y").unwrap().values()[0].is_missing());
21529        assert_eq!(frame.column("y").unwrap().values()[1], Scalar::Float64(3.0));
21530    }
21531
21532    #[test]
21533    fn read_table_with_options_honours_explicit_pipe_delimiter_4pwr9() {
21534        let input = "x|y\n1|2\n3|4\n";
21535        let opts = CsvReadOptions {
21536            delimiter: b'|',
21537            ..Default::default()
21538        };
21539        let frame = super::read_table_with_options(input, &opts).expect("parse pipe");
21540        assert_eq!(frame.column("x").unwrap().values()[0], Scalar::Int64(1));
21541        assert_eq!(frame.column("y").unwrap().values()[1], Scalar::Int64(4));
21542    }
21543
21544    // ── read_fwf 23n8u ─────────────────────────────────────────────────
21545
21546    #[test]
21547    fn read_fwf_str_with_colspecs_parses_aligned_records_23n8u() {
21548        let input = "name    age   active\nalice   30    true\nbob     25    false\n";
21549        let opts = super::FwfReadOptions {
21550            colspecs: Some(vec![(0, 8), (8, 14), (14, 20)]),
21551            true_values: vec!["true".into()],
21552            false_values: vec!["false".into()],
21553            ..Default::default()
21554        };
21555        let frame = super::read_fwf_str(input, &opts).expect("parse fwf");
21556        assert_eq!(frame.index().len(), 2);
21557        assert_eq!(
21558            frame.column("name").unwrap().values()[0],
21559            Scalar::Utf8("alice".into())
21560        );
21561        assert_eq!(frame.column("age").unwrap().values()[0], Scalar::Int64(30));
21562        assert_eq!(
21563            frame.column("active").unwrap().values()[0],
21564            Scalar::Bool(true)
21565        );
21566    }
21567
21568    #[test]
21569    fn read_fwf_str_with_widths_derives_colspecs_23n8u() {
21570        let input = "x  y \n1  2 \n3  4 \n";
21571        let opts = super::FwfReadOptions {
21572            widths: Some(vec![3, 3]),
21573            ..Default::default()
21574        };
21575        let frame = super::read_fwf_str(input, &opts).expect("parse fwf widths");
21576        assert_eq!(frame.column("x").unwrap().values()[0], Scalar::Int64(1));
21577        assert_eq!(frame.column("y").unwrap().values()[1], Scalar::Int64(4));
21578    }
21579
21580    #[test]
21581    fn read_fwf_str_threads_na_handling_23n8u() {
21582        // CSV inference widens integer fields with an NA to pandas-compatible Float64.
21583        let input = "id   val\nA    NA \nB    7  \n";
21584        let opts = super::FwfReadOptions {
21585            colspecs: Some(vec![(0, 5), (5, 9)]),
21586            na_values: vec!["NA".into()],
21587            ..Default::default()
21588        };
21589        let frame = super::read_fwf_str(input, &opts).expect("parse fwf na");
21590        let col = frame.column("val").unwrap().values();
21591        assert_eq!(frame.column("val").unwrap().dtype(), DType::Float64);
21592        assert!(col[0].is_missing());
21593        assert_eq!(col[1], Scalar::Float64(7.0));
21594    }
21595
21596    #[test]
21597    fn read_fwf_rejects_both_colspecs_and_widths_23n8u() {
21598        let opts = super::FwfReadOptions {
21599            colspecs: Some(vec![(0, 3)]),
21600            widths: Some(vec![3]),
21601            ..Default::default()
21602        };
21603        let err = super::read_fwf_str("x\n1\n", &opts).expect_err("must reject");
21604        assert!(
21605            matches!(&err, super::IoError::Fwf(message) if message.contains("only one of")),
21606            "unexpected error: {err:?}"
21607        );
21608    }
21609
21610    #[test]
21611    fn read_fwf_infers_colspecs_when_specs_are_omitted_htdmp() {
21612        let opts = super::FwfReadOptions::default();
21613        let frame = super::read_fwf_str("a b\n1 2\n3 4\n", &opts).expect("infer fwf specs");
21614        assert_eq!(frame.column("a").unwrap().values()[0], Scalar::Int64(1));
21615        assert_eq!(frame.column("b").unwrap().values()[1], Scalar::Int64(4));
21616    }
21617
21618    #[test]
21619    fn read_fwf_infers_aligned_wide_colspecs_htdmp() {
21620        let input = "name    age   active\nalice   30    true\nbob     25    false\n";
21621        let opts = super::FwfReadOptions {
21622            true_values: vec!["true".into()],
21623            false_values: vec!["false".into()],
21624            ..Default::default()
21625        };
21626        let frame = super::read_fwf_str(input, &opts).expect("infer aligned fwf specs");
21627        assert_eq!(
21628            frame.column("name").unwrap().values()[0],
21629            Scalar::Utf8("alice".into())
21630        );
21631        assert_eq!(frame.column("age").unwrap().values()[1], Scalar::Int64(25));
21632        assert_eq!(
21633            frame.column("active").unwrap().values()[1],
21634            Scalar::Bool(false)
21635        );
21636    }
21637
21638    #[test]
21639    fn read_fwf_infer_honors_skiprows_and_skipfooter_htdmp() {
21640        let input = "ignored wide banner\nx y\n1 2\nfooter text ignored\n";
21641        let opts = super::FwfReadOptions {
21642            skiprows: 1,
21643            skipfooter: 1,
21644            ..Default::default()
21645        };
21646        let frame = super::read_fwf_str(input, &opts).expect("infer after skipping");
21647        assert_eq!(frame.column("x").unwrap().values()[0], Scalar::Int64(1));
21648        assert_eq!(frame.column("y").unwrap().values()[0], Scalar::Int64(2));
21649    }
21650
21651    // ── Deferred reader surfaces 2yy4d ─────────────────────────────────
21652
21653    #[test]
21654    fn clipboard_tsv_round_trips_through_read_clipboard_str() {
21655        let frame = make_test_dataframe();
21656        // The pure write core: the exact tab-separated bytes `to_clipboard` puts
21657        // on the clipboard (index included, pandas excel=True).
21658        let tsv = super::clipboard_tsv(&frame).expect("tsv");
21659        assert!(
21660            tsv.contains('\t'),
21661            "clipboard payload must be tab-separated"
21662        );
21663
21664        // The pure read core round-trips the payload back to a frame with the
21665        // same shape (the written index becomes a leading column, matching
21666        // pandas read_clipboard's default no-index-col behavior).
21667        let parsed = super::read_clipboard_str(&tsv).expect("parse clipboard tsv");
21668        assert_eq!(parsed.len(), frame.len());
21669        assert_eq!(parsed.column_names().len(), frame.column_names().len() + 1);
21670    }
21671
21672    #[test]
21673    fn read_clipboard_is_ok_or_reports_missing_backend() {
21674        // Environment-independent: on a box with wl-paste/xclip/xsel/pbpaste it
21675        // reads real clipboard text (Ok or a parse error); headless it reports a
21676        // Clipboard backend error. Never a Deferred reject and never a panic.
21677        match super::read_clipboard() {
21678            Ok(_) => {}
21679            Err(super::IoError::Clipboard(_)) | Err(super::IoError::Csv(_)) => {}
21680            Err(super::IoError::MissingHeaders) => {}
21681            other => panic!("unexpected read_clipboard result: {other:?}"),
21682        }
21683    }
21684
21685    #[test]
21686    fn read_gbq_rejects_with_deferred_marker_2yy4d() {
21687        let err = super::read_gbq("SELECT 1", Some("proj")).expect_err("must reject");
21688        assert!(
21689            matches!(&err, super::IoError::Deferred(message)
21690                if message.contains("read_gbq") && message.contains("BigQuery")),
21691            "unexpected error: {err:?}"
21692        );
21693        let no_project_err = super::read_gbq("SELECT 1", None).expect_err("must reject");
21694        assert!(matches!(no_project_err, super::IoError::Deferred(_)));
21695    }
21696
21697    #[test]
21698    fn dataframe_deferred_writer_surfaces_report_method_names_e6jrk() {
21699        use super::DataFrameIoExt;
21700
21701        let frame = make_test_dataframe();
21702        // Clipboard writer is implemented (subprocess backend): Ok where a
21703        // backend exists, else a Clipboard error — never a Deferred reject.
21704        match frame.to_clipboard() {
21705            Ok(()) => {}
21706            Err(super::IoError::Clipboard(_)) => {}
21707            other => panic!("unexpected to_clipboard result: {other:?}"),
21708        }
21709
21710        let gbq_err = frame
21711            .to_gbq("dataset.table", Some("project"))
21712            .expect_err("must reject BigQuery writer");
21713        assert!(
21714            matches!(&gbq_err, super::IoError::Deferred(message) if message.contains("to_gbq") && message.contains("BigQuery"))
21715        );
21716
21717        let no_project_err = frame
21718            .to_gbq("dataset.table", None)
21719            .expect_err("must reject BigQuery writer without project");
21720        assert!(matches!(no_project_err, super::IoError::Deferred(_)));
21721    }
21722
21723    #[test]
21724    fn series_clipboard_writer_is_ok_or_reports_missing_backend() {
21725        use super::SeriesIoExt;
21726
21727        let source = Series::from_values(
21728            "sales",
21729            vec!["r1".into(), "r2".into()],
21730            vec![Scalar::Int64(10), Scalar::Int64(12)],
21731        )
21732        .expect("source series");
21733        match source.to_clipboard() {
21734            Ok(()) => {}
21735            Err(super::IoError::Clipboard(_)) => {}
21736            other => panic!("unexpected series to_clipboard result: {other:?}"),
21737        }
21738    }
21739
21740    #[test]
21741    fn read_sas_uses_native_reader_and_never_the_deferred_stub_9jvao() {
21742        let path = std::path::Path::new("/nonexistent.sas7bdat");
21743        let err = super::read_sas(path).expect_err("missing file must fail");
21744        assert!(
21745            matches!(&err, super::IoError::Sas(message) if !message.is_empty()),
21746            "unexpected error: {err:?}"
21747        );
21748    }
21749
21750    #[test]
21751    fn read_sas_xport_builds_typed_frame_and_keeps_missing_numeric_as_null_9jvao() {
21752        use sas_xport::sas::{
21753            SasVariableType,
21754            xport::{XportMetadata, XportSchema, XportValue, XportVariable, XportWriter},
21755        };
21756
21757        let path = std::env::temp_dir().join(format!(
21758            "fp_io_sas_xport_{}_{}.xpt",
21759            std::process::id(),
21760            line!()
21761        ));
21762        let mut subject = XportVariable::builder();
21763        subject
21764            .short_name("SUBJECT")
21765            .value_type(SasVariableType::Character)
21766            .value_length(12);
21767        let mut score = XportVariable::builder();
21768        score
21769            .short_name("SCORE")
21770            .value_type(SasVariableType::Numeric)
21771            .value_length(8);
21772        let schema = XportSchema::builder()
21773            .dataset_name("DM")
21774            .add_variable(subject)
21775            .add_variable(score)
21776            .try_build()
21777            .expect("build XPORT schema");
21778        let writer = XportWriter::from_file(
21779            std::fs::File::create(&path).expect("create XPORT fixture"),
21780            XportMetadata::builder().build(),
21781        )
21782        .expect("open XPORT writer");
21783        let mut writer = writer.write_schema(schema).expect("write XPORT schema");
21784        writer
21785            .write_record(&[XportValue::from("A-01"), XportValue::from(1.5)])
21786            .expect("write first XPORT record");
21787        writer
21788            .write_record(&[XportValue::from("A-02"), XportValue::from(f64::NAN)])
21789            .expect("write missing XPORT record");
21790        writer.finish().expect("finish XPORT fixture");
21791
21792        let frame = super::read_sas(&path).expect("read XPORT fixture");
21793        assert_eq!(frame.index().len(), 2);
21794        assert_eq!(
21795            frame.column("SUBJECT").expect("subject").values(),
21796            &[Scalar::Utf8("A-01".into()), Scalar::Utf8("A-02".into())]
21797        );
21798        assert_eq!(
21799            frame.column("SCORE").expect("score").values(),
21800            &[Scalar::Float64(1.5), Scalar::Null(NullKind::NaN)],
21801            "XPORT numeric NaN is a missing value, never a Float64(NaN) payload"
21802        );
21803    }
21804
21805    #[test]
21806    fn xport_numeric_nan_is_not_a_float_payload_9jvao() {
21807        let scalar =
21808            super::xport_cell_to_scalar(&sas_xport::sas::xport::XportValue::Number(f64::NAN));
21809        assert_eq!(scalar, Scalar::Null(NullKind::NaN));
21810        assert_ne!(scalar, Scalar::Float64(f64::NAN));
21811    }
21812
21813    #[test]
21814    fn sas_cells_build_typed_frame_and_reject_undecoded_bytes_9jvao() {
21815        use std::borrow::Cow;
21816
21817        let columns = vec![
21818            vec![
21819                super::sas_cell_to_scalar(&sas7bdat::CellValue::Float(1.5))
21820                    .expect("numeric SAS cell"),
21821                super::sas_cell_to_scalar(&sas7bdat::CellValue::Missing(
21822                    sas7bdat::MissingValue::System,
21823                ))
21824                .expect("missing SAS cell"),
21825            ],
21826            vec![
21827                super::sas_cell_to_scalar(&sas7bdat::CellValue::Str(Cow::Borrowed("alpha")))
21828                    .expect("text SAS cell"),
21829                super::sas_cell_to_scalar(&sas7bdat::CellValue::Str(Cow::Borrowed("beta")))
21830                    .expect("text SAS cell"),
21831            ],
21832        ];
21833        let frame = super::sas_rows_to_frame(vec!["score".into(), "name".into()], columns)
21834            .expect("build SAS frame");
21835        assert_eq!(frame.index().len(), 2);
21836        assert_eq!(
21837            frame.column("score").expect("score").values()[0],
21838            Scalar::Float64(1.5)
21839        );
21840        assert_eq!(
21841            frame.column("name").expect("name").values()[1],
21842            Scalar::Utf8("beta".into())
21843        );
21844
21845        let undecoded =
21846            super::sas_cell_to_scalar(&sas7bdat::CellValue::Bytes(Cow::Borrowed(b"\xff")))
21847                .expect_err("raw SAS bytes must not be silently lossy-decoded");
21848        assert!(matches!(undecoded, super::IoError::Sas(message) if message.contains("undecoded")));
21849    }
21850
21851    #[test]
21852    fn sas_frame_rejects_ragged_parser_output_9jvao() {
21853        let err = super::sas_rows_to_frame(
21854            vec!["left".into(), "right".into()],
21855            vec![vec![Scalar::Float64(1.0)]],
21856        )
21857        .expect_err("metadata/data width mismatch must fail");
21858        assert!(
21859            matches!(err, super::IoError::Sas(message) if message.contains("metadata declares"))
21860        );
21861    }
21862
21863    #[test]
21864    fn read_spss_rejects_with_deferred_marker_2yy4d() {
21865        let path = std::path::Path::new("/nonexistent.sav");
21866        let err = super::read_spss(path).expect_err("must reject");
21867        assert!(
21868            matches!(&err, super::IoError::Deferred(message)
21869                if message.contains("read_spss") && message.contains(".sav")),
21870            "unexpected error: {err:?}"
21871        );
21872    }
21873
21874    #[test]
21875    fn read_fwf_path_reads_fixed_width_file_23n8u() {
21876        let input = "a   b\n1   2\n3   4\n";
21877        let dir = std::env::temp_dir();
21878        let path = dir.join("fp_io_test_read_fwf_23n8u.txt");
21879        std::fs::write(&path, input).expect("write fixture");
21880
21881        let opts = super::FwfReadOptions {
21882            colspecs: Some(vec![(0, 4), (4, 5)]),
21883            ..Default::default()
21884        };
21885        let frame = super::read_fwf(&path, &opts).expect("read fwf path");
21886        assert_eq!(frame.index().len(), 2);
21887        assert_eq!(frame.column("a").unwrap().values()[1], Scalar::Int64(3));
21888        assert_eq!(frame.column("b").unwrap().values()[0], Scalar::Int64(2));
21889
21890        std::fs::remove_file(&path).ok();
21891    }
21892
21893    #[test]
21894    fn read_table_path_roundtrips_through_read_csv_path_4pwr9() {
21895        let input = "id\tval\na\t1\nb\t2\n";
21896        let dir = std::env::temp_dir();
21897        let path = dir.join("fp_io_test_read_table_4pwr9.tsv");
21898        std::fs::write(&path, input).expect("write fixture");
21899
21900        let frame = super::read_table(&path).expect("read tsv");
21901        assert_eq!(frame.index().len(), 2);
21902        assert_eq!(
21903            frame.column("id").unwrap().values()[0],
21904            Scalar::Utf8("a".into())
21905        );
21906        assert_eq!(frame.column("val").unwrap().values()[1], Scalar::Int64(2));
21907
21908        let opts = CsvReadOptions {
21909            index_col: Some("id".into()),
21910            ..Default::default()
21911        };
21912        let frame2 =
21913            super::read_table_with_options_path(&path, &opts).expect("read tsv with options");
21914        assert!(frame2.column("id").is_none());
21915        assert_eq!(
21916            frame2.index().labels()[0],
21917            fp_index::IndexLabel::Utf8("a".into())
21918        );
21919        assert_eq!(frame2.column("val").unwrap().values()[1], Scalar::Int64(2));
21920
21921        std::fs::remove_file(&path).ok();
21922    }
21923
21924    // ── Parquet I/O tests ──────────────────────────────────────────────
21925
21926    fn make_test_dataframe() -> DataFrame {
21927        use fp_types::DType;
21928
21929        let mut columns = BTreeMap::new();
21930        columns.insert(
21931            "ints".to_string(),
21932            Column::new(
21933                DType::Int64,
21934                vec![Scalar::Int64(10), Scalar::Int64(20), Scalar::Int64(30)],
21935            )
21936            .unwrap(),
21937        );
21938        columns.insert(
21939            "floats".to_string(),
21940            Column::new(
21941                DType::Float64,
21942                vec![
21943                    Scalar::Float64(1.5),
21944                    Scalar::Float64(2.5),
21945                    Scalar::Float64(3.5),
21946                ],
21947            )
21948            .unwrap(),
21949        );
21950        columns.insert(
21951            "names".to_string(),
21952            Column::from_values(vec![
21953                Scalar::Utf8("alice".into()),
21954                Scalar::Utf8("bob".into()),
21955                Scalar::Utf8("carol".into()),
21956            ])
21957            .unwrap(),
21958        );
21959
21960        let labels = vec![
21961            IndexLabel::Int64(0),
21962            IndexLabel::Int64(1),
21963            IndexLabel::Int64(2),
21964        ];
21965        DataFrame::new_with_column_order(
21966            Index::new(labels),
21967            columns,
21968            vec![
21969                "ints".to_string(),
21970                "floats".to_string(),
21971                "names".to_string(),
21972            ],
21973        )
21974        .unwrap()
21975    }
21976
21977    #[test]
21978    fn dataframe_io_ext_pandas_named_aliases_cover_supported_writers() {
21979        use super::DataFrameIoExt;
21980
21981        let frame = make_test_dataframe();
21982        let csv = frame.to_csv_string().expect("csv string");
21983        assert_eq!(
21984            csv,
21985            super::write_csv_string_with_options(
21986                &frame,
21987                &CsvWriteOptions {
21988                    include_index: true,
21989                    ..CsvWriteOptions::default()
21990                },
21991            )
21992            .expect("pandas-default csv"),
21993        );
21994        assert_eq!(
21995            frame.to_markdown_string().expect("markdown string"),
21996            write_markdown_string(&frame).expect("free markdown")
21997        );
21998        assert_eq!(
21999            frame.to_latex_string().expect("latex string"),
22000            write_latex_string(&frame).expect("free latex")
22001        );
22002        let dir = std::env::temp_dir();
22003        let stem = format!("fp_io_dataframe_io_ext_{}", std::process::id());
22004        let excel_path = dir.join(format!("{stem}.xlsx"));
22005        let feather_path = dir.join(format!("{stem}.feather"));
22006        let parquet_path = dir.join(format!("{stem}.parquet"));
22007
22008        frame.to_excel(&excel_path).expect("to_excel alias");
22009        frame.to_feather(&feather_path).expect("to_feather alias");
22010        frame.to_parquet(&parquet_path).expect("to_parquet alias");
22011
22012        assert!(
22013            std::fs::metadata(&excel_path)
22014                .expect("excel metadata")
22015                .len()
22016                > 0
22017        );
22018        assert_eq!(
22019            super::read_feather(&feather_path)
22020                .expect("read feather")
22021                .index()
22022                .len(),
22023            frame.index().len()
22024        );
22025        assert_eq!(
22026            super::read_parquet(&parquet_path)
22027                .expect("read parquet")
22028                .index()
22029                .len(),
22030            frame.index().len()
22031        );
22032
22033        std::fs::remove_file(&excel_path).ok();
22034        std::fs::remove_file(&feather_path).ok();
22035        std::fs::remove_file(&parquet_path).ok();
22036    }
22037
22038    #[test]
22039    fn dataframe_io_ext_rjs51_in_memory_methods_match_free_functions() {
22040        use super::DataFrameIoExt;
22041
22042        let frame = make_test_dataframe();
22043        let csv_options = CsvWriteOptions {
22044            delimiter: b';',
22045            na_rep: "<NA>".to_owned(),
22046            header: true,
22047            include_index: true,
22048            index_label: Some("row".to_owned()),
22049        };
22050        assert_eq!(
22051            frame
22052                .to_csv_string_with_options(&csv_options)
22053                .expect("csv options through extension"),
22054            write_csv_string_with_options(&frame, &csv_options).expect("csv options free fn")
22055        );
22056        assert_eq!(
22057            frame
22058                .to_json_string(JsonOrient::Split)
22059                .expect("json split through extension"),
22060            write_json_string(&frame, JsonOrient::Split).expect("json split free fn")
22061        );
22062        assert_eq!(
22063            frame.to_jsonl_string().expect("jsonl through extension"),
22064            write_jsonl_string(&frame).expect("jsonl free fn")
22065        );
22066        let html_options = HtmlWriteOptions {
22067            include_index: false,
22068            ..HtmlWriteOptions::default()
22069        };
22070        assert_eq!(
22071            frame
22072                .to_html_string_with_options(&html_options)
22073                .expect("html options through extension"),
22074            write_html_string_with_options(&frame, &html_options).expect("html options free fn")
22075        );
22076        let xml_options = XmlWriteOptions {
22077            include_index: false,
22078            root_name: "records".to_owned(),
22079            row_name: "record".to_owned(),
22080            index_label: None,
22081        };
22082        assert_eq!(
22083            frame
22084                .to_xml_string_with_options(&xml_options)
22085                .expect("xml options through extension"),
22086            write_xml_string_with_options(&frame, &xml_options).expect("xml options free fn")
22087        );
22088
22089        let parquet = frame
22090            .to_parquet_bytes()
22091            .expect("parquet bytes through extension");
22092        assert_eq!(
22093            read_parquet_bytes(&parquet)
22094                .expect("parquet roundtrip")
22095                .index()
22096                .len(),
22097            frame.index().len()
22098        );
22099        assert_orc_disabled(
22100            frame
22101                .to_orc_bytes()
22102                .expect_err("ORC must fail closed under no-Tokio policy"),
22103        );
22104        let feather = frame
22105            .to_feather_bytes()
22106            .expect("feather bytes through extension");
22107        assert_eq!(
22108            read_feather_bytes(&feather)
22109                .expect("feather roundtrip")
22110                .index()
22111                .len(),
22112            frame.index().len()
22113        );
22114        let excel = frame
22115            .to_excel_bytes()
22116            .expect("excel bytes through extension");
22117        assert_eq!(
22118            read_excel_bytes(&excel, &ExcelReadOptions::default())
22119                .expect("excel roundtrip")
22120                .index()
22121                .len(),
22122            frame.index().len()
22123        );
22124    }
22125
22126    fn make_row_multiindex_test_dataframe() -> DataFrame {
22127        let df = DataFrame::from_dict(
22128            &["region", "product", "year", "sales", "cost"],
22129            vec![
22130                (
22131                    "region",
22132                    vec![
22133                        Scalar::Utf8("north".into()),
22134                        Scalar::Utf8("north".into()),
22135                        Scalar::Utf8("south".into()),
22136                    ],
22137                ),
22138                (
22139                    "product",
22140                    vec![
22141                        Scalar::Utf8("apple".into()),
22142                        Scalar::Utf8("pear".into()),
22143                        Scalar::Utf8("apple".into()),
22144                    ],
22145                ),
22146                (
22147                    "year",
22148                    vec![
22149                        Scalar::Int64(2023),
22150                        Scalar::Int64(2024),
22151                        Scalar::Int64(2023),
22152                    ],
22153                ),
22154                (
22155                    "sales",
22156                    vec![Scalar::Int64(10), Scalar::Int64(20), Scalar::Int64(30)],
22157                ),
22158                (
22159                    "cost",
22160                    vec![Scalar::Int64(4), Scalar::Int64(7), Scalar::Int64(12)],
22161                ),
22162            ],
22163        )
22164        .unwrap();
22165        df.set_index_multi(&["region", "product", "year"], true, "|")
22166            .unwrap()
22167    }
22168
22169    #[test]
22170    fn parquet_bytes_roundtrip() {
22171        let frame = make_test_dataframe();
22172        let bytes = super::write_parquet_bytes(&frame).expect("write parquet");
22173        assert!(!bytes.is_empty());
22174
22175        let frame2 = super::read_parquet_bytes(&bytes).expect("read parquet");
22176        assert_eq!(frame2.index().len(), 3);
22177        assert_eq!(
22178            frame2
22179                .column_names()
22180                .iter()
22181                .map(|s| s.as_str())
22182                .collect::<Vec<_>>(),
22183            vec!["ints", "floats", "names"]
22184        );
22185
22186        // Check values round-tripped correctly
22187        let ints = frame2.column("ints").unwrap();
22188        assert_eq!(ints.values()[0], Scalar::Int64(10));
22189        assert_eq!(ints.values()[1], Scalar::Int64(20));
22190        assert_eq!(ints.values()[2], Scalar::Int64(30));
22191
22192        let floats = frame2.column("floats").unwrap();
22193        assert_eq!(floats.values()[0], Scalar::Float64(1.5));
22194        assert_eq!(floats.values()[1], Scalar::Float64(2.5));
22195        assert_eq!(floats.values()[2], Scalar::Float64(3.5));
22196
22197        let names = frame2.column("names").unwrap();
22198        assert_eq!(names.values()[0], Scalar::Utf8("alice".into()));
22199        assert_eq!(names.values()[1], Scalar::Utf8("bob".into()));
22200        assert_eq!(names.values()[2], Scalar::Utf8("carol".into()));
22201    }
22202
22203    #[test]
22204    fn parquet_writer_uses_typed_bool_and_utf8_buffers_uza04() {
22205        let mut columns = BTreeMap::new();
22206        columns.insert(
22207            "flag".to_owned(),
22208            Column::from_bool_values(vec![true, false, true]),
22209        );
22210        columns.insert(
22211            "label".to_owned(),
22212            Column::from_utf8_contiguous(b"redgreenblue".to_vec(), vec![0, 3, 8, 12]),
22213        );
22214        let frame = DataFrame::new_with_column_order(
22215            Index::from_i64(vec![0, 1, 2]),
22216            columns,
22217            vec!["flag".to_owned(), "label".to_owned()],
22218        )
22219        .expect("typed parquet source");
22220
22221        assert!(
22222            !frame
22223                .column("flag")
22224                .expect("typed bool source")
22225                .scalar_cache_is_materialized()
22226        );
22227        assert!(
22228            !frame
22229                .column("label")
22230                .expect("typed utf8 source")
22231                .scalar_cache_is_materialized()
22232        );
22233
22234        let bytes = super::write_parquet_bytes(&frame).expect("write typed parquet");
22235
22236        assert!(
22237            !frame
22238                .column("flag")
22239                .expect("typed bool source")
22240                .scalar_cache_is_materialized(),
22241            "all-valid bool must avoid the Scalar fallback"
22242        );
22243        assert!(
22244            !frame
22245                .column("label")
22246                .expect("typed utf8 source")
22247                .scalar_cache_is_materialized(),
22248            "all-valid contiguous Utf8 must avoid the Scalar fallback"
22249        );
22250
22251        let decoded = super::read_parquet_bytes(&bytes).expect("read typed parquet");
22252        assert_eq!(
22253            decoded.column("flag").expect("decoded bool").values(),
22254            &[Scalar::Bool(true), Scalar::Bool(false), Scalar::Bool(true)]
22255        );
22256        assert_eq!(
22257            decoded.column("label").expect("decoded utf8").values(),
22258            &[
22259                Scalar::Utf8("red".to_owned()),
22260                Scalar::Utf8("green".to_owned()),
22261                Scalar::Utf8("blue".to_owned()),
22262            ]
22263        );
22264    }
22265
22266    #[test]
22267    fn parquet_reader_uses_nullable_utf8_buffer_and_rejects_dictionary_uza04() {
22268        let mut validity = ValidityMask::all_valid(3);
22269        validity.set(1, false);
22270        let mut columns = BTreeMap::new();
22271        columns.insert(
22272            "label".to_owned(),
22273            Column::from_utf8_values_with_validity(b"redblue".to_vec(), vec![0, 3, 3, 7], validity),
22274        );
22275        let frame = DataFrame::new_with_column_order(
22276            Index::from_i64(vec![0, 1, 2]),
22277            columns,
22278            vec!["label".to_owned()],
22279        )
22280        .expect("nullable utf8 source");
22281
22282        let bytes = super::write_parquet_bytes(&frame).expect("write nullable utf8 parquet");
22283        let decoded = super::read_parquet_bytes(&bytes).expect("read nullable utf8 parquet");
22284        let label = decoded.column("label").expect("decoded nullable utf8");
22285        assert!(
22286            label.as_nullable_utf8_contiguous().is_some(),
22287            "nullable Utf8 must retain the typed backing"
22288        );
22289        assert!(
22290            !label.scalar_cache_is_materialized(),
22291            "typed reader must not materialize a Scalar cache"
22292        );
22293        assert_eq!(
22294            label.values(),
22295            &[
22296                Scalar::Utf8("red".to_owned()),
22297                Scalar::Null(NullKind::Null),
22298                Scalar::Utf8("blue".to_owned()),
22299            ]
22300        );
22301
22302        use arrow::{
22303            array::{DictionaryArray, Int8Array, StringArray},
22304            datatypes::Int8Type,
22305        };
22306        let dictionary = DictionaryArray::<Int8Type>::try_new(
22307            Int8Array::from(vec![Some(0), Some(1), Some(0)]),
22308            Arc::new(StringArray::from(vec!["red", "blue"])),
22309        )
22310        .expect("dictionary array");
22311        assert!(
22312            super::arrow_array_to_column_typed(&dictionary, dictionary.data_type()).is_none(),
22313            "dictionary arrays must not be reinterpreted as direct Utf8 buffers"
22314        );
22315    }
22316
22317    #[cfg(feature = "block-storage")]
22318    #[test]
22319    fn parquet_all_valid_float64_uses_column_major_block_l6uyi() {
22320        let mut columns = BTreeMap::new();
22321        columns.insert(
22322            "left".to_string(),
22323            Column::from_f64_values(vec![1.5, -0.0, 3.25]),
22324        );
22325        columns.insert(
22326            "right".to_string(),
22327            Column::from_f64_values(vec![4.0, 5.5, 6.75]),
22328        );
22329        let frame = DataFrame::new_with_column_order(
22330            Index::from_i64(vec![10, 20, 30]),
22331            columns,
22332            vec!["left".to_string(), "right".to_string()],
22333        )
22334        .expect("source frame");
22335
22336        let bytes = super::write_parquet_bytes(&frame).expect("write parquet");
22337        let decoded = super::read_parquet_bytes(&bytes).expect("read parquet");
22338        let view = decoded
22339            .to_numpy_block_view()
22340            .expect("all-valid Float64 parquet is block-backed");
22341        assert_eq!((view.rows, view.cols), (3, 2));
22342        assert_eq!(view.block[0].to_bits(), 1.5_f64.to_bits());
22343        assert_eq!(view.block[1].to_bits(), (-0.0_f64).to_bits());
22344        assert_eq!(view.block[2].to_bits(), 3.25_f64.to_bits());
22345        assert_eq!(view.block[3].to_bits(), 4.0_f64.to_bits());
22346        assert_eq!(view.block[4].to_bits(), 5.5_f64.to_bits());
22347        assert_eq!(view.block[5].to_bits(), 6.75_f64.to_bits());
22348
22349        // Negative case: nullable Float64 needs a validity mask, so it must
22350        // remain on the ordinary typed decode path rather than dropping the
22351        // missing marker into an all-valid block.
22352        let nullable = DataFrame::from_dict(
22353            &["value"],
22354            vec![(
22355                "value",
22356                vec![
22357                    Scalar::Float64(1.0),
22358                    Scalar::Null(NullKind::NaN),
22359                    Scalar::Float64(3.0),
22360                ],
22361            )],
22362        )
22363        .expect("nullable source frame");
22364        let nullable_bytes = super::write_parquet_bytes(&nullable).expect("write nullable parquet");
22365        let nullable_decoded =
22366            super::read_parquet_bytes(&nullable_bytes).expect("read nullable parquet");
22367        assert!(
22368            nullable_decoded.to_numpy_block_view().is_none(),
22369            "nullable Float64 must not enter the all-valid block path"
22370        );
22371        assert!(
22372            nullable_decoded
22373                .column("value")
22374                .expect("value column")
22375                .values()[1]
22376                .is_missing(),
22377            "fallback must preserve the parquet null as a missing Float64"
22378        );
22379    }
22380
22381    #[test]
22382    fn parquet_row_multiindex_roundtrip_restores_logical_row_axis() {
22383        let frame = make_row_multiindex_test_dataframe();
22384        let bytes = super::write_parquet_bytes(&frame).expect("write parquet");
22385        let roundtrip = super::read_parquet_bytes(&bytes).expect("read parquet");
22386
22387        assert!(roundtrip.equals(&frame));
22388        assert!(roundtrip.column("__index_level_0__").is_none());
22389        // br-frankenpandas-wfkzm: the level NAMES must survive too. Before the
22390        // schema metadata carried them, this came back as
22391        // ["__index_level_0__", "__index_level_1__", "__index_level_2__"].
22392        let names = roundtrip.row_multiindex().unwrap().names().to_vec();
22393        assert_eq!(names, frame.row_multiindex().unwrap().names().to_vec());
22394        assert!(
22395            names
22396                .iter()
22397                .flatten()
22398                .all(|name| !name.starts_with("__index_level_")),
22399            "synthetic level names leaked into the round-trip: {names:?}"
22400        );
22401        assert_eq!(
22402            roundtrip
22403                .row_multiindex()
22404                .expect("row multiindex should be restored")
22405                .get_level_values(0)
22406                .unwrap()
22407                .labels(),
22408            frame
22409                .row_multiindex()
22410                .expect("source row multiindex")
22411                .get_level_values(0)
22412                .unwrap()
22413                .labels()
22414        );
22415    }
22416
22417    #[test]
22418    fn parquet_file_roundtrip() {
22419        let frame = make_test_dataframe();
22420        let dir = std::env::temp_dir();
22421        let path = dir.join("fp_io_test_parquet_roundtrip.parquet");
22422
22423        super::write_parquet(&frame, &path).expect("write parquet file");
22424        let frame2 = super::read_parquet(&path).expect("read parquet file");
22425        assert_eq!(frame2.index().len(), 3);
22426        assert_eq!(
22427            frame2.column("ints").unwrap().values()[0],
22428            Scalar::Int64(10)
22429        );
22430        std::fs::remove_file(&path).ok();
22431    }
22432
22433    #[test]
22434    fn parquet_with_nulls() {
22435        use fp_types::DType;
22436
22437        let mut columns = BTreeMap::new();
22438        columns.insert(
22439            "vals".to_string(),
22440            Column::new(
22441                DType::Float64,
22442                vec![
22443                    Scalar::Float64(1.0),
22444                    Scalar::Null(NullKind::NaN),
22445                    Scalar::Float64(3.0),
22446                ],
22447            )
22448            .unwrap(),
22449        );
22450        columns.insert(
22451            "strs".to_string(),
22452            Column::from_values(vec![
22453                Scalar::Utf8("a".into()),
22454                Scalar::Null(NullKind::Null),
22455                Scalar::Utf8("c".into()),
22456            ])
22457            .unwrap(),
22458        );
22459
22460        let labels = vec![
22461            IndexLabel::Int64(0),
22462            IndexLabel::Int64(1),
22463            IndexLabel::Int64(2),
22464        ];
22465        let frame = DataFrame::new_with_column_order(
22466            Index::new(labels),
22467            columns,
22468            vec!["vals".to_string(), "strs".to_string()],
22469        )
22470        .unwrap();
22471
22472        let bytes = super::write_parquet_bytes(&frame).expect("write");
22473        let frame2 = super::read_parquet_bytes(&bytes).expect("read");
22474
22475        assert_eq!(
22476            frame2.column("vals").unwrap().values()[0],
22477            Scalar::Float64(1.0)
22478        );
22479        assert!(frame2.column("vals").unwrap().values()[1].is_missing());
22480        assert_eq!(
22481            frame2.column("vals").unwrap().values()[2],
22482            Scalar::Float64(3.0)
22483        );
22484
22485        assert_eq!(
22486            frame2.column("strs").unwrap().values()[0],
22487            Scalar::Utf8("a".into())
22488        );
22489        assert!(frame2.column("strs").unwrap().values()[1].is_missing());
22490        assert_eq!(
22491            frame2.column("strs").unwrap().values()[2],
22492            Scalar::Utf8("c".into())
22493        );
22494    }
22495
22496    #[test]
22497    fn parquet_bool_column() {
22498        use fp_types::DType;
22499
22500        let mut columns = BTreeMap::new();
22501        columns.insert(
22502            "flags".to_string(),
22503            Column::new(
22504                DType::Bool,
22505                vec![Scalar::Bool(true), Scalar::Bool(false), Scalar::Bool(true)],
22506            )
22507            .unwrap(),
22508        );
22509
22510        let labels = vec![
22511            IndexLabel::Int64(0),
22512            IndexLabel::Int64(1),
22513            IndexLabel::Int64(2),
22514        ];
22515        let frame = DataFrame::new_with_column_order(
22516            Index::new(labels),
22517            columns,
22518            vec!["flags".to_string()],
22519        )
22520        .unwrap();
22521
22522        let bytes = super::write_parquet_bytes(&frame).expect("write");
22523        let frame2 = super::read_parquet_bytes(&bytes).expect("read");
22524
22525        assert_eq!(
22526            frame2.column("flags").unwrap().values()[0],
22527            Scalar::Bool(true)
22528        );
22529        assert_eq!(
22530            frame2.column("flags").unwrap().values()[1],
22531            Scalar::Bool(false)
22532        );
22533        assert_eq!(
22534            frame2.column("flags").unwrap().values()[2],
22535            Scalar::Bool(true)
22536        );
22537    }
22538
22539    #[test]
22540    fn parquet_empty_dataframe_errors() {
22541        // Parquet format requires at least one column — empty DataFrames
22542        // cannot be represented, matching pandas behavior where
22543        // pd.DataFrame().to_parquet() also fails.
22544        let frame =
22545            DataFrame::new_with_column_order(Index::new(vec![]), BTreeMap::new(), vec![]).unwrap();
22546
22547        let result = super::write_parquet_bytes(&frame);
22548        assert!(result.is_err());
22549    }
22550
22551    #[test]
22552    fn orc_bytes_fail_closed_under_no_tokio_policy() {
22553        let frame = make_test_dataframe();
22554        assert_orc_disabled(write_orc_bytes(&frame).expect_err("ORC writer must fail closed"));
22555        assert_orc_disabled(read_orc_bytes(b"ORC").expect_err("ORC reader must fail closed"));
22556    }
22557
22558    #[test]
22559    fn orc_file_and_extension_aliases_fail_closed_under_no_tokio_policy() {
22560        use super::DataFrameIoExt;
22561
22562        let frame = make_test_dataframe();
22563        let free_path = std::env::temp_dir().join(format!(
22564            "fp_io_orc_free_{}_{}.orc",
22565            std::process::id(),
22566            line!()
22567        ));
22568        let trait_path = std::env::temp_dir().join(format!(
22569            "fp_io_orc_trait_{}_{}.orc",
22570            std::process::id(),
22571            line!()
22572        ));
22573
22574        assert_orc_disabled(write_orc(&frame, &free_path).expect_err("free ORC path writer"));
22575        assert_orc_disabled(read_orc(&free_path).expect_err("free ORC path reader"));
22576        assert_orc_disabled(
22577            frame
22578                .to_orc_file(&trait_path)
22579                .expect_err("trait ORC path writer"),
22580        );
22581        assert_orc_disabled(frame.to_orc_bytes().expect_err("trait ORC bytes writer"));
22582    }
22583
22584    #[test]
22585    fn orc_row_multiindex_fails_closed_before_materialization() {
22586        let frame = make_row_multiindex_test_dataframe();
22587        assert_orc_disabled(
22588            write_orc_bytes(&frame).expect_err("ORC writer must fail closed for any frame shape"),
22589        );
22590    }
22591
22592    #[test]
22593    fn orc_reader_rejects_malformed_input_without_loading_backend() {
22594        let err = read_orc_bytes(b"not an orc file").expect_err("malformed orc should fail");
22595        assert_orc_disabled(err);
22596    }
22597
22598    // ── Excel I/O tests ──────────────────────────────────────────────
22599
22600    #[test]
22601    fn write_excel_with_options_custom_sheet_name_survives_round_trip() {
22602        let frame = make_test_dataframe();
22603        let bytes = super::write_excel_bytes_with_options(
22604            &frame,
22605            &super::ExcelWriteOptions {
22606                sheet_name: "Results".to_string(),
22607                ..super::ExcelWriteOptions::default()
22608            },
22609        )
22610        .expect("write");
22611        let sheets =
22612            super::read_excel_sheets_bytes(&bytes, None, &super::ExcelReadOptions::default())
22613                .expect("read");
22614        assert_eq!(sheets.len(), 1);
22615        assert!(sheets.contains_key("Results"));
22616    }
22617
22618    #[test]
22619    fn write_excel_with_options_index_false_omits_index_column() {
22620        let frame = make_test_dataframe();
22621        let bytes = super::write_excel_bytes_with_options(
22622            &frame,
22623            &super::ExcelWriteOptions {
22624                index: false,
22625                ..super::ExcelWriteOptions::default()
22626            },
22627        )
22628        .expect("write");
22629        let frame2 =
22630            super::read_excel_bytes(&bytes, &super::ExcelReadOptions::default()).expect("read");
22631        // With index=false the first column is "ints" directly (no
22632        // anonymous leading index column).
22633        let names = frame2.column_names();
22634        assert_eq!(
22635            names.iter().map(|s| s.as_str()).collect::<Vec<_>>(),
22636            vec!["ints", "floats", "names"]
22637        );
22638    }
22639
22640    #[test]
22641    fn write_excel_with_options_index_label_overrides_header() {
22642        let frame = make_test_dataframe();
22643        let bytes = super::write_excel_bytes_with_options(
22644            &frame,
22645            &super::ExcelWriteOptions {
22646                index_label: Some("row_id".to_string()),
22647                ..super::ExcelWriteOptions::default()
22648            },
22649        )
22650        .expect("write");
22651        let frame2 =
22652            super::read_excel_bytes(&bytes, &super::ExcelReadOptions::default()).expect("read");
22653        // The index column now shows up as "row_id" before the data columns.
22654        let names = frame2.column_names();
22655        assert_eq!(names[0], "row_id");
22656    }
22657
22658    #[test]
22659    fn write_excel_with_options_header_false_omits_header_row() {
22660        let frame = make_test_dataframe();
22661        let bytes = super::write_excel_bytes_with_options(
22662            &frame,
22663            &super::ExcelWriteOptions {
22664                header: false,
22665                index: false,
22666                ..super::ExcelWriteOptions::default()
22667            },
22668        )
22669        .expect("write");
22670        // Without header, the reader treats row 0 as headers. We
22671        // expect the first data row to become the column names
22672        // instead of literal "ints"/"floats"/"names".
22673        let frame2 =
22674            super::read_excel_bytes(&bytes, &super::ExcelReadOptions::default()).expect("read");
22675        let names = frame2.column_names();
22676        let name_strs: Vec<&str> = names.iter().map(|s| s.as_str()).collect();
22677        assert!(!name_strs.contains(&"ints"));
22678    }
22679
22680    #[test]
22681    fn write_excel_with_options_default_matches_write_excel_bytes() {
22682        let frame = make_test_dataframe();
22683        let default_bytes = super::write_excel_bytes(&frame).expect("default");
22684        let options_bytes =
22685            super::write_excel_bytes_with_options(&frame, &super::ExcelWriteOptions::default())
22686                .expect("options");
22687        assert_eq!(default_bytes, options_bytes);
22688    }
22689
22690    #[test]
22691    fn excel_multiindex_roundtrip_with_explicit_index_cols() {
22692        let frame = make_row_multiindex_test_dataframe();
22693        let bytes =
22694            super::write_excel_bytes_with_options(&frame, &super::ExcelWriteOptions::default())
22695                .expect("write");
22696        let roundtrip = super::read_excel_bytes_with_index_cols(
22697            &bytes,
22698            &super::ExcelReadOptions::default(),
22699            &["region", "product", "year"],
22700        )
22701        .expect("read");
22702
22703        assert!(roundtrip.equals(&frame));
22704        assert_eq!(roundtrip.row_multiindex(), frame.row_multiindex());
22705    }
22706
22707    fn build_two_sheet_workbook_bytes() -> Vec<u8> {
22708        use rust_xlsxwriter::Workbook;
22709        let mut workbook = Workbook::new();
22710        let sheet1 = workbook.add_worksheet();
22711        sheet1.set_name("Alpha").expect("sheet name");
22712        sheet1.write_string(0, 0, "a").expect("header");
22713        sheet1.write_string(0, 1, "b").expect("header");
22714        sheet1.write_number(1, 0, 1.0).expect("data");
22715        sheet1.write_number(1, 1, 10.0).expect("data");
22716        sheet1.write_number(2, 0, 2.0).expect("data");
22717        sheet1.write_number(2, 1, 20.0).expect("data");
22718
22719        let sheet2 = workbook.add_worksheet();
22720        sheet2.set_name("Bravo").expect("sheet name");
22721        sheet2.write_string(0, 0, "name").expect("header");
22722        sheet2.write_string(1, 0, "alice").expect("data");
22723        sheet2.write_string(2, 0, "bob").expect("data");
22724
22725        let sheet3 = workbook.add_worksheet();
22726        sheet3.set_name("Charlie").expect("sheet name");
22727        sheet3.write_string(0, 0, "x").expect("header");
22728        sheet3.write_number(1, 0, 99.0).expect("data");
22729
22730        workbook.save_to_buffer().expect("save")
22731    }
22732
22733    #[test]
22734    fn read_excel_sheets_ordered_bytes_preserves_workbook_order() {
22735        // Workbook sheet order: Alpha, Bravo, Charlie. A sorted map
22736        // would still give Alpha/Bravo/Charlie alphabetically — but
22737        // pandas guarantees workbook order regardless of alphabetic
22738        // relationship, so this test uses a fixture where the ordered
22739        // result differs from sorted order.
22740        use rust_xlsxwriter::Workbook;
22741        let mut workbook = Workbook::new();
22742        let s1 = workbook.add_worksheet();
22743        s1.set_name("Zulu").expect("name");
22744        s1.write_string(0, 0, "v").expect("header");
22745        s1.write_number(1, 0, 1.0).expect("data");
22746        let s2 = workbook.add_worksheet();
22747        s2.set_name("Alpha").expect("name");
22748        s2.write_string(0, 0, "v").expect("header");
22749        s2.write_number(1, 0, 2.0).expect("data");
22750        let s3 = workbook.add_worksheet();
22751        s3.set_name("Mike").expect("name");
22752        s3.write_string(0, 0, "v").expect("header");
22753        s3.write_number(1, 0, 3.0).expect("data");
22754        let bytes = workbook.save_to_buffer().expect("save");
22755
22756        let ordered = super::read_excel_sheets_ordered_bytes(
22757            &bytes,
22758            None,
22759            &super::ExcelReadOptions::default(),
22760        )
22761        .expect("read ordered");
22762        assert_eq!(
22763            ordered.iter().map(|(k, _)| k.as_str()).collect::<Vec<_>>(),
22764            vec!["Zulu", "Alpha", "Mike"],
22765            "ordered form preserves workbook order"
22766        );
22767
22768        // Sorted form alphabetizes (existing contract for BTreeMap).
22769        let sorted =
22770            super::read_excel_sheets_bytes(&bytes, None, &super::ExcelReadOptions::default())
22771                .expect("read sorted");
22772        assert_eq!(
22773            sorted.keys().map(String::as_str).collect::<Vec<_>>(),
22774            vec!["Alpha", "Mike", "Zulu"],
22775            "BTreeMap form alphabetizes"
22776        );
22777    }
22778
22779    #[test]
22780    fn read_excel_sheets_ordered_bytes_selected_subset_keeps_caller_order() {
22781        let bytes = build_two_sheet_workbook_bytes();
22782        // Caller-specified order: Charlie, Alpha — deliberately reversed
22783        // from workbook order. Pandas docs say sheet_name=[list] returns
22784        // a dict whose iteration reflects the argument order; we match.
22785        let req = vec!["Charlie".to_string(), "Alpha".to_string()];
22786        let ordered = super::read_excel_sheets_ordered_bytes(
22787            &bytes,
22788            Some(&req),
22789            &super::ExcelReadOptions::default(),
22790        )
22791        .expect("ordered subset");
22792        assert_eq!(
22793            ordered.iter().map(|(k, _)| k.as_str()).collect::<Vec<_>>(),
22794            vec!["Charlie", "Alpha"]
22795        );
22796    }
22797
22798    #[test]
22799    fn read_excel_sheets_ordered_path_matches_bytes() {
22800        let bytes = build_two_sheet_workbook_bytes();
22801        let temp = std::env::temp_dir().join("fp_io_wrt3_ordered.xlsx");
22802        std::fs::write(&temp, &bytes).expect("write temp");
22803        let via_path =
22804            super::read_excel_sheets_ordered(&temp, None, &super::ExcelReadOptions::default())
22805                .expect("read path");
22806        let via_bytes = super::read_excel_sheets_ordered_bytes(
22807            &bytes,
22808            None,
22809            &super::ExcelReadOptions::default(),
22810        )
22811        .expect("read bytes");
22812        assert_eq!(
22813            via_path.iter().map(|(k, _)| k.clone()).collect::<Vec<_>>(),
22814            via_bytes.iter().map(|(k, _)| k.clone()).collect::<Vec<_>>()
22815        );
22816    }
22817
22818    #[test]
22819    fn read_excel_sheets_bytes_all_sheets_returns_map() {
22820        let bytes = build_two_sheet_workbook_bytes();
22821        let sheets =
22822            super::read_excel_sheets_bytes(&bytes, None, &super::ExcelReadOptions::default())
22823                .expect("read sheets");
22824        assert_eq!(sheets.len(), 3);
22825        assert!(sheets.contains_key("Alpha"));
22826        assert!(sheets.contains_key("Bravo"));
22827        assert!(sheets.contains_key("Charlie"));
22828
22829        let alpha = &sheets["Alpha"];
22830        assert_eq!(alpha.index().len(), 2);
22831        assert_eq!(alpha.column_names().len(), 2);
22832
22833        let bravo = &sheets["Bravo"];
22834        assert_eq!(bravo.index().len(), 2);
22835        assert_eq!(
22836            bravo.column("name").unwrap().values()[0],
22837            Scalar::Utf8("alice".into())
22838        );
22839    }
22840
22841    #[test]
22842    fn read_excel_sheets_bytes_selects_subset() {
22843        let bytes = build_two_sheet_workbook_bytes();
22844        let selected = vec!["Alpha".to_string(), "Charlie".to_string()];
22845        let sheets = super::read_excel_sheets_bytes(
22846            &bytes,
22847            Some(&selected),
22848            &super::ExcelReadOptions::default(),
22849        )
22850        .expect("read subset");
22851        assert_eq!(sheets.len(), 2);
22852        assert!(sheets.contains_key("Alpha"));
22853        assert!(sheets.contains_key("Charlie"));
22854        assert!(!sheets.contains_key("Bravo"));
22855    }
22856
22857    #[test]
22858    fn read_excel_sheets_bytes_unknown_sheet_errors() {
22859        let bytes = build_two_sheet_workbook_bytes();
22860        let bogus = vec!["Zeta".to_string()];
22861        let err = super::read_excel_sheets_bytes(
22862            &bytes,
22863            Some(&bogus),
22864            &super::ExcelReadOptions::default(),
22865        )
22866        .unwrap_err();
22867        assert!(matches!(err, super::IoError::Excel(_)));
22868    }
22869
22870    #[test]
22871    fn read_excel_sheets_path_matches_bytes() {
22872        let bytes = build_two_sheet_workbook_bytes();
22873        let temp = std::env::temp_dir().join("fp_io_9my2_multisheet.xlsx");
22874        std::fs::write(&temp, &bytes).expect("write temp");
22875        let via_path = super::read_excel_sheets(&temp, None, &super::ExcelReadOptions::default())
22876            .expect("read path");
22877        let via_bytes =
22878            super::read_excel_sheets_bytes(&bytes, None, &super::ExcelReadOptions::default())
22879                .expect("read bytes");
22880        assert_eq!(
22881            via_path.keys().collect::<Vec<_>>(),
22882            via_bytes.keys().collect::<Vec<_>>()
22883        );
22884    }
22885
22886    #[test]
22887    fn excel_bytes_roundtrip() {
22888        let frame = make_test_dataframe();
22889        let bytes = super::write_excel_bytes(&frame).expect("write excel");
22890        assert!(!bytes.is_empty());
22891
22892        let frame2 = super::read_excel_bytes(
22893            &bytes,
22894            &super::ExcelReadOptions {
22895                index_col: Some("column_0".into()),
22896                ..Default::default()
22897            },
22898        )
22899        .expect("read excel");
22900        assert_eq!(frame2.index().len(), 3);
22901        assert_eq!(frame2.index().labels(), frame.index().labels());
22902        assert_eq!(frame2.index().name(), None);
22903        // Excel preserves the write-time column order (ints, floats, names).
22904        assert_eq!(
22905            frame2
22906                .column_names()
22907                .iter()
22908                .map(|s| s.as_str())
22909                .collect::<Vec<_>>(),
22910            vec!["ints", "floats", "names"]
22911        );
22912
22913        // Int values survive round-trip (Excel stores as f64, we recover Int64).
22914        let ints = frame2.column("ints").unwrap();
22915        assert_eq!(ints.values()[0], Scalar::Int64(10));
22916        assert_eq!(ints.values()[1], Scalar::Int64(20));
22917        assert_eq!(ints.values()[2], Scalar::Int64(30));
22918
22919        // Float values survive round-trip.
22920        let floats = frame2.column("floats").unwrap();
22921        assert_eq!(floats.values()[0], Scalar::Float64(1.5));
22922        assert_eq!(floats.values()[1], Scalar::Float64(2.5));
22923        assert_eq!(floats.values()[2], Scalar::Float64(3.5));
22924
22925        // String values survive round-trip.
22926        let names = frame2.column("names").unwrap();
22927        assert_eq!(names.values()[0], Scalar::Utf8("alice".into()));
22928        assert_eq!(names.values()[1], Scalar::Utf8("bob".into()));
22929        assert_eq!(names.values()[2], Scalar::Utf8("carol".into()));
22930    }
22931
22932    #[test]
22933    fn excel_file_roundtrip() {
22934        let frame = make_test_dataframe();
22935        let dir = std::env::temp_dir();
22936        let path = dir.join("fp_io_test_excel_roundtrip.xlsx");
22937
22938        super::write_excel(&frame, &path).expect("write excel file");
22939        let frame2 = super::read_excel(
22940            &path,
22941            &super::ExcelReadOptions {
22942                index_col: Some("column_0".into()),
22943                ..Default::default()
22944            },
22945        )
22946        .expect("read excel file");
22947        assert_eq!(frame2.index().len(), 3);
22948        assert_eq!(frame2.index().labels(), frame.index().labels());
22949        assert_eq!(
22950            frame2.column("ints").unwrap().values()[0],
22951            Scalar::Int64(10)
22952        );
22953        std::fs::remove_file(&path).ok();
22954    }
22955
22956    #[test]
22957    fn excel_with_nulls() {
22958        use fp_types::DType;
22959
22960        let mut columns = BTreeMap::new();
22961        columns.insert(
22962            "vals".to_string(),
22963            Column::new(
22964                DType::Float64,
22965                vec![
22966                    Scalar::Float64(1.0),
22967                    Scalar::Null(NullKind::NaN),
22968                    Scalar::Float64(3.0),
22969                ],
22970            )
22971            .unwrap(),
22972        );
22973
22974        let labels = vec![
22975            IndexLabel::Int64(0),
22976            IndexLabel::Int64(1),
22977            IndexLabel::Int64(2),
22978        ];
22979        let frame =
22980            DataFrame::new_with_column_order(Index::new(labels), columns, vec!["vals".to_string()])
22981                .unwrap();
22982
22983        let bytes = super::write_excel_bytes(&frame).expect("write");
22984        let frame2 = super::read_excel_bytes(
22985            &bytes,
22986            &super::ExcelReadOptions {
22987                index_col: Some("column_0".into()),
22988                ..Default::default()
22989            },
22990        )
22991        .expect("read");
22992
22993        // Non-null values round-trip.
22994        assert_eq!(frame2.column("vals").unwrap().values()[0], Scalar::Int64(1));
22995        // NaN written as empty cell, read back as Null.
22996        assert!(frame2.column("vals").unwrap().values()[1].is_missing());
22997        assert_eq!(frame2.column("vals").unwrap().values()[2], Scalar::Int64(3));
22998    }
22999
23000    #[test]
23001    fn excel_bool_column() {
23002        use fp_types::DType;
23003
23004        let mut columns = BTreeMap::new();
23005        columns.insert(
23006            "flags".to_string(),
23007            Column::new(
23008                DType::Bool,
23009                vec![Scalar::Bool(true), Scalar::Bool(false), Scalar::Bool(true)],
23010            )
23011            .unwrap(),
23012        );
23013
23014        let labels = vec![
23015            IndexLabel::Int64(0),
23016            IndexLabel::Int64(1),
23017            IndexLabel::Int64(2),
23018        ];
23019        let frame = DataFrame::new_with_column_order(
23020            Index::new(labels),
23021            columns,
23022            vec!["flags".to_string()],
23023        )
23024        .unwrap();
23025
23026        let bytes = super::write_excel_bytes(&frame).expect("write");
23027        let frame2 = super::read_excel_bytes(
23028            &bytes,
23029            &super::ExcelReadOptions {
23030                index_col: Some("column_0".into()),
23031                ..Default::default()
23032            },
23033        )
23034        .expect("read");
23035
23036        assert_eq!(
23037            frame2.column("flags").unwrap().values()[0],
23038            Scalar::Bool(true)
23039        );
23040        assert_eq!(
23041            frame2.column("flags").unwrap().values()[1],
23042            Scalar::Bool(false)
23043        );
23044        assert_eq!(
23045            frame2.column("flags").unwrap().values()[2],
23046            Scalar::Bool(true)
23047        );
23048    }
23049
23050    #[test]
23051    fn excel_skip_rows() {
23052        // Build an xlsx with 5 data rows, then read with skip_rows=2 to skip
23053        // 2 rows before the header.
23054        use fp_types::DType;
23055
23056        let mut columns = BTreeMap::new();
23057        columns.insert(
23058            "x".to_string(),
23059            Column::new(DType::Int64, vec![Scalar::Int64(1), Scalar::Int64(2)]).unwrap(),
23060        );
23061        let labels = vec![IndexLabel::Int64(0), IndexLabel::Int64(1)];
23062        let frame =
23063            DataFrame::new_with_column_order(Index::new(labels), columns, vec!["x".to_string()])
23064                .unwrap();
23065
23066        let bytes = super::write_excel_bytes(&frame).expect("write");
23067        let frame2 = super::read_excel_bytes(
23068            &bytes,
23069            &super::ExcelReadOptions {
23070                skip_rows: 1,
23071                has_headers: false,
23072                ..Default::default()
23073            },
23074        )
23075        .expect("read with skip");
23076
23077        // Skipped the header row, so first data row becomes first row.
23078        // With has_headers=false, column names are auto-generated.
23079        assert_eq!(frame2.index().len(), 2);
23080        assert!(frame2.column("column_0").is_some());
23081    }
23082
23083    #[test]
23084    fn excel_header_none_with_explicit_names_uses_names_and_keeps_first_row() {
23085        let rows = vec![
23086            vec![
23087                calamine::Data::Int(1),
23088                calamine::Data::String("alpha".to_owned()),
23089            ],
23090            vec![
23091                calamine::Data::Int(2),
23092                calamine::Data::String("beta".to_owned()),
23093            ],
23094        ];
23095
23096        let frame = super::parse_excel_rows(
23097            rows,
23098            &super::ExcelReadOptions {
23099                has_headers: false,
23100                names: Some(vec!["id".to_owned(), "label".to_owned()]),
23101                ..Default::default()
23102            },
23103        )
23104        .expect("parse excel rows with explicit names");
23105
23106        assert_eq!(frame.column_names(), vec!["id", "label"]);
23107        assert_eq!(frame.index().len(), 2);
23108        assert_eq!(frame.column("id").unwrap().values()[0], Scalar::Int64(1));
23109        assert_eq!(
23110            frame.column("label").unwrap().values()[0],
23111            Scalar::Utf8("alpha".into())
23112        );
23113        assert_eq!(frame.column("id").unwrap().values()[1], Scalar::Int64(2));
23114    }
23115
23116    #[test]
23117    fn excel_header_none_with_explicit_names_preserves_index_name() {
23118        let rows = vec![
23119            vec![
23120                calamine::Data::Int(10),
23121                calamine::Data::String("alpha".to_owned()),
23122            ],
23123            vec![
23124                calamine::Data::Int(20),
23125                calamine::Data::String("beta".to_owned()),
23126            ],
23127        ];
23128
23129        let frame = super::parse_excel_rows(
23130            rows,
23131            &super::ExcelReadOptions {
23132                has_headers: false,
23133                names: Some(vec!["row_id".to_owned(), "value".to_owned()]),
23134                index_col: Some("row_id".to_owned()),
23135                ..Default::default()
23136            },
23137        )
23138        .expect("parse excel rows with named index column");
23139
23140        assert_eq!(frame.index().name(), Some("row_id"));
23141        assert_eq!(frame.index().labels()[0], IndexLabel::Int64(10));
23142        assert_eq!(frame.index().labels()[1], IndexLabel::Int64(20));
23143        assert!(frame.column("row_id").is_none());
23144        assert_eq!(
23145            frame.column("value").unwrap().values(),
23146            &[Scalar::Utf8("alpha".into()), Scalar::Utf8("beta".into())]
23147        );
23148    }
23149
23150    #[test]
23151    fn excel_explicit_names_width_mismatch_errors() {
23152        let rows = vec![vec![calamine::Data::Int(1), calamine::Data::Int(2)]];
23153
23154        let err = super::parse_excel_rows(
23155            rows,
23156            &super::ExcelReadOptions {
23157                has_headers: false,
23158                names: Some(vec!["only_one".to_owned()]),
23159                ..Default::default()
23160            },
23161        )
23162        .expect_err("names width mismatch should error");
23163
23164        assert!(
23165            matches!(err, IoError::Excel(message) if message.contains("expected 2 column names, got 1"))
23166        );
23167    }
23168
23169    #[test]
23170    fn excel_usecols_selects_subset_in_sheet_order() {
23171        let rows = vec![
23172            vec![
23173                calamine::Data::String("a".to_owned()),
23174                calamine::Data::String("b".to_owned()),
23175                calamine::Data::String("c".to_owned()),
23176            ],
23177            vec![
23178                calamine::Data::Int(1),
23179                calamine::Data::Int(2),
23180                calamine::Data::Int(3),
23181            ],
23182        ];
23183
23184        let frame = super::parse_excel_rows(
23185            rows,
23186            &super::ExcelReadOptions {
23187                usecols: Some(vec!["c".to_owned(), "a".to_owned()]),
23188                ..Default::default()
23189            },
23190        )
23191        .expect("parse excel rows with usecols");
23192
23193        assert_eq!(frame.column_names(), vec!["a", "c"]);
23194        assert_eq!(frame.column("a").unwrap().values(), &[Scalar::Int64(1)]);
23195        assert_eq!(frame.column("c").unwrap().values(), &[Scalar::Int64(3)]);
23196        assert!(frame.column("b").is_none());
23197    }
23198
23199    #[test]
23200    fn excel_usecols_with_explicit_names_filters_renamed_columns() {
23201        let rows = vec![
23202            vec![
23203                calamine::Data::Int(1),
23204                calamine::Data::String("alpha".to_owned()),
23205            ],
23206            vec![
23207                calamine::Data::Int(2),
23208                calamine::Data::String("beta".to_owned()),
23209            ],
23210        ];
23211
23212        let frame = super::parse_excel_rows(
23213            rows,
23214            &super::ExcelReadOptions {
23215                has_headers: false,
23216                names: Some(vec!["id".to_owned(), "label".to_owned()]),
23217                usecols: Some(vec!["label".to_owned()]),
23218                ..Default::default()
23219            },
23220        )
23221        .expect("parse headerless excel rows with names and usecols");
23222
23223        assert_eq!(frame.column_names(), vec!["label"]);
23224        assert_eq!(
23225            frame.column("label").unwrap().values(),
23226            &[Scalar::Utf8("alpha".into()), Scalar::Utf8("beta".into())]
23227        );
23228        assert!(frame.column("id").is_none());
23229    }
23230
23231    #[test]
23232    fn excel_usecols_missing_column_errors() {
23233        let rows = vec![
23234            vec![
23235                calamine::Data::String("a".to_owned()),
23236                calamine::Data::String("b".to_owned()),
23237            ],
23238            vec![calamine::Data::Int(1), calamine::Data::Int(2)],
23239        ];
23240
23241        let err = super::parse_excel_rows(
23242            rows,
23243            &super::ExcelReadOptions {
23244                usecols: Some(vec!["missing".to_owned()]),
23245                ..Default::default()
23246            },
23247        )
23248        .expect_err("missing excel usecols should error");
23249
23250        assert!(
23251            matches!(err, IoError::MissingUsecols(missing) if missing == vec!["missing".to_owned()])
23252        );
23253    }
23254
23255    #[test]
23256    fn excel_default_read_promotes_writer_range_index_back_to_index() {
23257        let frame = make_test_dataframe();
23258        let bytes = super::write_excel_bytes(&frame).expect("write excel");
23259
23260        let frame2 = super::read_excel_bytes(&bytes, &super::ExcelReadOptions::default())
23261            .expect("read excel");
23262
23263        assert_eq!(frame2.index().labels(), frame.index().labels());
23264        assert_eq!(frame2.index().name(), None);
23265        assert_eq!(frame2.column_names(), vec!["ints", "floats", "names"],);
23266        assert!(frame2.column("column_0").is_none());
23267    }
23268
23269    #[test]
23270    fn excel_default_read_keeps_non_range_generated_leading_column_as_data() {
23271        let rows = vec![
23272            vec![
23273                calamine::Data::Empty,
23274                calamine::Data::String("value".to_owned()),
23275            ],
23276            vec![calamine::Data::Int(10), calamine::Data::Int(1)],
23277            vec![calamine::Data::Int(20), calamine::Data::Int(2)],
23278        ];
23279
23280        let frame = super::parse_excel_rows(rows, &super::ExcelReadOptions::default())
23281            .expect("parse excel rows");
23282
23283        assert_eq!(
23284            frame.index().labels(),
23285            &[IndexLabel::Int64(0), IndexLabel::Int64(1)]
23286        );
23287        assert_eq!(frame.column_names(), vec!["column_0", "value"]);
23288        assert_eq!(
23289            frame.column("column_0").unwrap().values(),
23290            &[Scalar::Int64(10), Scalar::Int64(20)],
23291        );
23292    }
23293
23294    #[test]
23295    fn excel_named_index_roundtrip_preserves_index_name() {
23296        use fp_types::DType;
23297
23298        let mut columns = BTreeMap::new();
23299        columns.insert(
23300            "vals".to_string(),
23301            Column::new(DType::Int64, vec![Scalar::Int64(10), Scalar::Int64(20)]).unwrap(),
23302        );
23303
23304        let frame = DataFrame::new_with_column_order(
23305            Index::new(vec![IndexLabel::Int64(10), IndexLabel::Int64(20)]).set_name("row_id"),
23306            columns,
23307            vec!["vals".to_string()],
23308        )
23309        .unwrap();
23310
23311        let bytes = super::write_excel_bytes(&frame).expect("write excel");
23312        let frame2 = super::read_excel_bytes(
23313            &bytes,
23314            &super::ExcelReadOptions {
23315                index_col: Some("row_id".into()),
23316                ..Default::default()
23317            },
23318        )
23319        .expect("read excel");
23320
23321        assert_eq!(frame2.index().labels(), frame.index().labels());
23322        assert_eq!(frame2.index().name(), Some("row_id"));
23323        assert!(frame2.column("row_id").is_none());
23324        assert_eq!(
23325            frame2.column("vals").unwrap().values(),
23326            &[Scalar::Int64(10), Scalar::Int64(20)]
23327        );
23328    }
23329
23330    #[test]
23331    fn excel_duplicate_headers_error() {
23332        let rows = vec![
23333            vec![
23334                calamine::Data::String("dup".to_owned()),
23335                calamine::Data::String("dup".to_owned()),
23336            ],
23337            vec![calamine::Data::Int(1), calamine::Data::Int(2)],
23338        ];
23339
23340        let err = super::parse_excel_rows(rows, &super::ExcelReadOptions::default())
23341            .expect_err("duplicate headers should error");
23342        assert!(matches!(err, IoError::DuplicateColumnName(_)));
23343    }
23344
23345    // ── SQL I/O tests ──────────────────────────────────────────────
23346    //
23347    // Per br-frankenpandas-7a49 (fd90.48): keep the import block
23348    // unconditional so stub-backend tests (which only need types and
23349    // free-fns, not rusqlite) compile under --no-default-features.
23350    // `#[allow(unused_imports)]` covers the few free fns that are
23351    // exclusively used inside the cfg-gated SQLite-backed tests.
23352
23353    // Per fd90.48: TYPE imports + introspection-helper free fns are
23354    // used by both stub-backend tests (which compile under
23355    // --no-default-features) and SQLite-backed tests. The
23356    // read_sql_* / write_sql_* row-materialization free fns are only
23357    // exercised inside SQLite-backed tests (cfg-gated below) so they
23358    // get their own gated import group to avoid unused warnings.
23359    // Per fd90.48: TYPE imports + introspection-helper free fns +
23360    // write_sql / write_sql_with_options are used by both stub-backend
23361    // tests (which compile under --no-default-features) and
23362    // SQLite-backed tests. The read_sql_* row-materialization free fns
23363    // are only exercised inside SQLite-backed tests (cfg-gated below).
23364    use super::{
23365        SqlBackendCaps, SqlColumnSchema, SqlForeignKeySchema, SqlIfExists, SqlIndexSchema,
23366        SqlInsertMethod, SqlInspector, SqlQueryResult, SqlReadOptions, SqlReflectedTable,
23367        SqlTableSchema, SqlUniqueConstraintSchema, SqlWriteOptions, list_sql_foreign_keys,
23368        list_sql_indexes, list_sql_schemas, list_sql_tables, list_sql_unique_constraints,
23369        list_sql_views, sql_backend_caps, sql_max_identifier_length, sql_max_insert_rows,
23370        sql_max_param_count, sql_primary_key_columns, sql_server_version, sql_supports_returning,
23371        sql_supports_schemas, sql_table_comment, sql_table_schema, truncate_sql_table, write_sql,
23372        write_sql_with_options,
23373    };
23374    #[cfg(feature = "sql-sqlite")]
23375    use super::{
23376        read_sql, read_sql_chunks, read_sql_chunks_with_index_col, read_sql_chunks_with_options,
23377        read_sql_chunks_with_options_and_index_col, read_sql_query, read_sql_query_chunks,
23378        read_sql_query_chunks_with_index_col, read_sql_query_chunks_with_options,
23379        read_sql_query_chunks_with_options_and_index_col, read_sql_query_with_index_col,
23380        read_sql_query_with_options, read_sql_query_with_options_and_index_col, read_sql_table,
23381        read_sql_table_chunks, read_sql_table_chunks_with_index_col,
23382        read_sql_table_chunks_with_options, read_sql_table_chunks_with_options_and_index_col,
23383        read_sql_table_columns, read_sql_table_columns_chunks,
23384        read_sql_table_columns_chunks_with_index_col, read_sql_table_columns_with_index_col,
23385        read_sql_table_with_index_col, read_sql_table_with_options,
23386        read_sql_table_with_options_and_index_col, read_sql_with_index_col, read_sql_with_options,
23387    };
23388
23389    // Per br-frankenpandas-7a49 (fd90.48): the helper itself only
23390    // exists when sql-sqlite is on, since it directly references
23391    // rusqlite::Connection. All tests that call this are also
23392    // cfg-gated on the same feature.
23393    #[cfg(feature = "sql-sqlite")]
23394    fn make_sql_test_conn() -> rusqlite::Connection {
23395        rusqlite::Connection::open_in_memory().expect("in-memory sqlite")
23396    }
23397
23398    #[cfg(feature = "sql-sqlite")]
23399    #[test]
23400    fn sql_read_with_index_col_promotes_named_column() {
23401        let frame = make_test_dataframe();
23402        let conn = make_sql_test_conn();
23403        write_sql(&frame, &conn, "indexed_tbl", SqlIfExists::Fail).expect("write");
23404
23405        // Promote the "ints" column to the row index. The data
23406        // columns should drop ints and the index labels should be the
23407        // ints values.
23408        let result = read_sql_table_with_index_col(&conn, "indexed_tbl", Some("ints"))
23409            .expect("read with index");
23410        assert_eq!(result.index().name(), Some("ints"));
23411        assert_eq!(result.index().labels()[0], crate::IndexLabel::Int64(10));
23412        assert_eq!(result.index().labels()[1], crate::IndexLabel::Int64(20));
23413        assert_eq!(result.index().labels()[2], crate::IndexLabel::Int64(30));
23414        // Data columns: only the non-index columns remain.
23415        let names: Vec<&str> = result.column_names().iter().map(|s| s.as_str()).collect();
23416        assert!(!names.contains(&"ints"));
23417        assert!(names.contains(&"floats"));
23418        assert!(names.contains(&"names"));
23419    }
23420
23421    #[cfg(feature = "sql-sqlite")]
23422    #[test]
23423    fn sql_read_with_index_col_none_is_unchanged() {
23424        let frame = make_test_dataframe();
23425        let conn = make_sql_test_conn();
23426        write_sql(&frame, &conn, "noindex_tbl", SqlIfExists::Fail).expect("write");
23427        let baseline = read_sql_table(&conn, "noindex_tbl").expect("baseline");
23428        let result =
23429            read_sql_table_with_index_col(&conn, "noindex_tbl", None).expect("noop variant");
23430        assert_eq!(result.index().labels(), baseline.index().labels());
23431        assert_eq!(result.column_names(), baseline.column_names());
23432    }
23433
23434    #[cfg(feature = "sql-sqlite")]
23435    #[test]
23436    fn sql_read_with_index_col_unknown_column_errors() {
23437        let frame = make_test_dataframe();
23438        let conn = make_sql_test_conn();
23439        write_sql(&frame, &conn, "missing_tbl", SqlIfExists::Fail).expect("write");
23440        let err = read_sql_table_with_index_col(&conn, "missing_tbl", Some("nope")).unwrap_err();
23441        assert!(matches!(err, crate::IoError::Sql(_)));
23442    }
23443
23444    #[cfg(feature = "sql-sqlite")]
23445    #[test]
23446    fn sql_read_table_columns_returns_requested_projection_in_order() {
23447        let frame = make_test_dataframe();
23448        let conn = make_sql_test_conn();
23449        write_sql(&frame, &conn, "proj_tbl", SqlIfExists::Fail).expect("write");
23450
23451        let result = read_sql_table_columns(&conn, "proj_tbl", &["names", "ints"])
23452            .expect("subset projection");
23453        let names: Vec<&str> = result.column_names().iter().map(|s| s.as_str()).collect();
23454        assert_eq!(names, vec!["names", "ints"]);
23455        assert_eq!(result.index().len(), 3);
23456        assert_eq!(
23457            result.column("ints").unwrap().values()[0],
23458            Scalar::Int64(10)
23459        );
23460        assert_eq!(
23461            result.column("names").unwrap().values()[2],
23462            Scalar::Utf8("carol".into())
23463        );
23464    }
23465
23466    #[cfg(feature = "sql-sqlite")]
23467    #[test]
23468    fn sql_read_table_columns_single_column_projection() {
23469        let frame = make_test_dataframe();
23470        let conn = make_sql_test_conn();
23471        write_sql(&frame, &conn, "single_tbl", SqlIfExists::Fail).expect("write");
23472
23473        let result =
23474            read_sql_table_columns(&conn, "single_tbl", &["floats"]).expect("single projection");
23475        let names: Vec<&str> = result.column_names().iter().map(|s| s.as_str()).collect();
23476        assert_eq!(names, vec!["floats"]);
23477        assert_eq!(
23478            result.column("floats").unwrap().values()[1],
23479            Scalar::Float64(2.5)
23480        );
23481    }
23482
23483    #[cfg(feature = "sql-sqlite")]
23484    #[test]
23485    fn sql_read_table_columns_rejects_empty_columns() {
23486        let conn = make_sql_test_conn();
23487        let err = read_sql_table_columns(&conn, "any_tbl", &[]).unwrap_err();
23488        assert!(matches!(err, crate::IoError::Sql(_)));
23489    }
23490
23491    #[cfg(feature = "sql-sqlite")]
23492    #[test]
23493    fn sql_read_table_columns_rejects_invalid_column_name() {
23494        let frame = make_test_dataframe();
23495        let conn = make_sql_test_conn();
23496        write_sql(&frame, &conn, "valid_tbl", SqlIfExists::Fail).expect("write");
23497        let err = read_sql_table_columns(&conn, "valid_tbl", &["ints; DROP TABLE valid_tbl"])
23498            .unwrap_err();
23499        assert!(matches!(err, crate::IoError::Sql(_)));
23500    }
23501
23502    #[cfg(feature = "sql-sqlite")]
23503    #[test]
23504    fn sql_read_table_columns_rejects_invalid_table_name() {
23505        let conn = make_sql_test_conn();
23506        let err = read_sql_table_columns(&conn, "bad table", &["ints"]).unwrap_err();
23507        assert!(matches!(err, crate::IoError::Sql(_)));
23508    }
23509
23510    #[cfg(feature = "sql-sqlite")]
23511    #[test]
23512    fn sql_read_table_columns_chunks_returns_requested_projection_in_order() {
23513        let frame = make_test_dataframe();
23514        let conn = make_sql_test_conn();
23515        write_sql(&frame, &conn, "proj_chunk_tbl", SqlIfExists::Fail).expect("write");
23516
23517        let chunks = read_sql_table_columns_chunks(&conn, "proj_chunk_tbl", &["names", "ints"], 2)
23518            .expect("projection chunk iterator")
23519            .collect::<Result<Vec<_>, _>>()
23520            .expect("all chunks");
23521
23522        assert_eq!(chunks.len(), 2);
23523        assert_eq!(chunks[0].column_names(), vec!["names", "ints"]);
23524        assert_eq!(
23525            chunks[0].column("names").unwrap().values(),
23526            &[
23527                Scalar::Utf8("alice".to_owned()),
23528                Scalar::Utf8("bob".to_owned())
23529            ]
23530        );
23531        assert_eq!(
23532            chunks[1].column("ints").unwrap().values(),
23533            &[Scalar::Int64(30)]
23534        );
23535    }
23536
23537    #[cfg(feature = "sql-sqlite")]
23538    #[test]
23539    fn sql_read_table_columns_chunks_rejects_zero_chunksize() {
23540        let frame = make_test_dataframe();
23541        let conn = make_sql_test_conn();
23542        write_sql(&frame, &conn, "proj_zero_chunk_tbl", SqlIfExists::Fail).expect("write");
23543
23544        let err = read_sql_table_columns_chunks(&conn, "proj_zero_chunk_tbl", &["names"], 0)
23545            .expect_err("zero projection chunksize should be rejected");
23546
23547        assert!(matches!(err, IoError::Sql(msg) if msg.contains("chunksize")));
23548    }
23549
23550    #[cfg(feature = "sql-sqlite")]
23551    #[test]
23552    fn sql_read_table_columns_chunks_rejects_invalid_projection_inputs() {
23553        let conn = make_sql_test_conn();
23554
23555        let empty = read_sql_table_columns_chunks(&conn, "proj_chunk_tbl", &[], 1)
23556            .expect_err("empty projection should be rejected");
23557        assert!(matches!(empty, IoError::Sql(msg) if msg.contains("columns must be non-empty")));
23558
23559        let invalid = read_sql_table_columns_chunks(&conn, "proj_chunk_tbl", &["bad column"], 1)
23560            .expect_err("invalid projection name should be rejected");
23561        assert!(matches!(invalid, IoError::Sql(msg) if msg.contains("invalid column name")));
23562    }
23563
23564    #[cfg(feature = "sql-sqlite")]
23565    #[test]
23566    fn sql_read_table_columns_with_index_col_promotes_projected_column() {
23567        let frame = make_test_dataframe();
23568        let conn = make_sql_test_conn();
23569        write_sql(&frame, &conn, "proj_index_tbl", SqlIfExists::Fail).expect("write");
23570
23571        let result = read_sql_table_columns_with_index_col(
23572            &conn,
23573            "proj_index_tbl",
23574            &["names", "ints"],
23575            Some("ints"),
23576        )
23577        .expect("projection with index_col");
23578
23579        assert_eq!(result.index().name(), Some("ints"));
23580        assert_eq!(
23581            result.index().labels(),
23582            &[
23583                IndexLabel::Int64(10),
23584                IndexLabel::Int64(20),
23585                IndexLabel::Int64(30)
23586            ]
23587        );
23588        assert_eq!(result.column_names(), vec!["names"]);
23589        assert_eq!(
23590            result.column("names").unwrap().values(),
23591            &[
23592                Scalar::Utf8("alice".to_owned()),
23593                Scalar::Utf8("bob".to_owned()),
23594                Scalar::Utf8("carol".to_owned())
23595            ]
23596        );
23597        assert!(result.column("ints").is_none());
23598    }
23599
23600    // br-frankenpandas-6n0uz: when index_col is set but NOT in columns,
23601    // pandas auto-projects it into the SELECT (then drops it from data
23602    // columns after promotion). Mirrors fd90.76's behavior on the
23603    // options-based reader.
23604    #[cfg(feature = "sql-sqlite")]
23605    #[test]
23606    fn sql_read_table_columns_with_index_col_auto_projects_when_absent() {
23607        let frame = make_test_dataframe();
23608        let conn = make_sql_test_conn();
23609        write_sql(&frame, &conn, "auto_proj_tbl", SqlIfExists::Fail).expect("write");
23610
23611        // index_col "ints" is NOT in columns — must be auto-projected, then
23612        // promoted to the index, then removed from the data columns.
23613        let result =
23614            read_sql_table_columns_with_index_col(&conn, "auto_proj_tbl", &["names"], Some("ints"))
23615                .expect("auto-project index_col");
23616
23617        assert_eq!(result.index().name(), Some("ints"));
23618        assert_eq!(
23619            result.index().labels(),
23620            &[
23621                IndexLabel::Int64(10),
23622                IndexLabel::Int64(20),
23623                IndexLabel::Int64(30)
23624            ]
23625        );
23626        assert_eq!(result.column_names(), vec!["names"]);
23627        assert!(result.column("ints").is_none());
23628        assert_eq!(
23629            result.column("names").unwrap().values(),
23630            &[
23631                Scalar::Utf8("alice".to_owned()),
23632                Scalar::Utf8("bob".to_owned()),
23633                Scalar::Utf8("carol".to_owned())
23634            ]
23635        );
23636    }
23637
23638    #[cfg(feature = "sql-sqlite")]
23639    #[test]
23640    fn sql_read_table_columns_chunks_with_index_col_auto_projects_when_absent() {
23641        let frame = make_test_dataframe();
23642        let conn = make_sql_test_conn();
23643        write_sql(&frame, &conn, "auto_proj_chunks_tbl", SqlIfExists::Fail).expect("write");
23644
23645        // index_col "ints" is NOT in columns — must be auto-projected per
23646        // chunk and dropped from each chunk's data columns.
23647        let chunks = read_sql_table_columns_chunks_with_index_col(
23648            &conn,
23649            "auto_proj_chunks_tbl",
23650            &["names"],
23651            Some("ints"),
23652            2,
23653        )
23654        .expect("auto-project chunks")
23655        .collect::<Result<Vec<_>, _>>()
23656        .expect("all chunks");
23657
23658        assert_eq!(chunks.len(), 2);
23659        assert_eq!(chunks[0].index().name(), Some("ints"));
23660        assert_eq!(
23661            chunks[0].index().labels(),
23662            &[IndexLabel::Int64(10), IndexLabel::Int64(20)]
23663        );
23664        assert_eq!(chunks[0].column_names(), vec!["names"]);
23665        assert!(chunks[0].column("ints").is_none());
23666        assert_eq!(
23667            chunks[0].column("names").unwrap().values(),
23668            &[
23669                Scalar::Utf8("alice".to_owned()),
23670                Scalar::Utf8("bob".to_owned())
23671            ]
23672        );
23673        assert_eq!(chunks[1].index().labels(), &[IndexLabel::Int64(30)]);
23674        assert_eq!(chunks[1].column_names(), vec!["names"]);
23675        assert!(chunks[1].column("ints").is_none());
23676    }
23677
23678    // br-frankenpandas-6n0uz: idempotency check — when index_col IS already
23679    // in columns, the auto-project helper must not duplicate it. Same final
23680    // result as the original explicit-include test, but proves the helper's
23681    // dedupe path.
23682    #[cfg(feature = "sql-sqlite")]
23683    #[test]
23684    fn sql_read_table_columns_with_index_col_no_duplication_when_listed() {
23685        let frame = make_test_dataframe();
23686        let conn = make_sql_test_conn();
23687        write_sql(&frame, &conn, "no_dup_tbl", SqlIfExists::Fail).expect("write");
23688
23689        // index_col "ints" IS in columns — must NOT be duplicated in SELECT.
23690        let result = read_sql_table_columns_with_index_col(
23691            &conn,
23692            "no_dup_tbl",
23693            &["names", "ints"],
23694            Some("ints"),
23695        )
23696        .expect("explicit include + index_col");
23697
23698        assert_eq!(result.index().name(), Some("ints"));
23699        assert_eq!(result.column_names(), vec!["names"]);
23700        assert!(result.column("ints").is_none());
23701    }
23702
23703    #[cfg(feature = "sql-sqlite")]
23704    #[test]
23705    fn sql_read_table_columns_with_index_col_none_keeps_projection_and_range_index() {
23706        let frame = make_test_dataframe();
23707        let conn = make_sql_test_conn();
23708        write_sql(&frame, &conn, "proj_no_index_tbl", SqlIfExists::Fail).expect("write");
23709
23710        let result = read_sql_table_columns_with_index_col(
23711            &conn,
23712            "proj_no_index_tbl",
23713            &["floats", "names"],
23714            None,
23715        )
23716        .expect("projection without index_col");
23717
23718        assert_eq!(
23719            result.index().labels(),
23720            &[
23721                IndexLabel::Int64(0),
23722                IndexLabel::Int64(1),
23723                IndexLabel::Int64(2)
23724            ]
23725        );
23726        assert_eq!(result.column_names(), vec!["floats", "names"]);
23727        assert_eq!(
23728            result.column("floats").unwrap().values()[1],
23729            Scalar::Float64(2.5)
23730        );
23731    }
23732
23733    #[cfg(feature = "sql-sqlite")]
23734    #[test]
23735    fn sql_read_table_columns_chunks_with_index_col_promotes_each_chunk_index() {
23736        let frame = make_test_dataframe();
23737        let conn = make_sql_test_conn();
23738        write_sql(&frame, &conn, "proj_index_chunk_tbl", SqlIfExists::Fail).expect("write");
23739
23740        let chunks = read_sql_table_columns_chunks_with_index_col(
23741            &conn,
23742            "proj_index_chunk_tbl",
23743            &["ints", "names"],
23744            Some("ints"),
23745            2,
23746        )
23747        .expect("indexed projection chunk iterator")
23748        .collect::<Result<Vec<_>, _>>()
23749        .expect("all chunks");
23750
23751        assert_eq!(chunks.len(), 2);
23752        assert_eq!(chunks[0].index().name(), Some("ints"));
23753        assert_eq!(
23754            chunks[0].index().labels(),
23755            &[IndexLabel::Int64(10), IndexLabel::Int64(20)]
23756        );
23757        assert_eq!(chunks[0].column_names(), vec!["names"]);
23758        assert_eq!(
23759            chunks[0].column("names").unwrap().values(),
23760            &[
23761                Scalar::Utf8("alice".to_owned()),
23762                Scalar::Utf8("bob".to_owned())
23763            ]
23764        );
23765        assert_eq!(chunks[1].index().labels(), &[IndexLabel::Int64(30)]);
23766        assert_eq!(
23767            chunks[1].column("names").unwrap().values(),
23768            &[Scalar::Utf8("carol".to_owned())]
23769        );
23770    }
23771
23772    #[cfg(feature = "sql-sqlite")]
23773    #[test]
23774    fn sql_read_table_columns_chunks_with_index_col_validates_projection_and_index() {
23775        let frame = make_test_dataframe();
23776        let conn = make_sql_test_conn();
23777        write_sql(&frame, &conn, "proj_index_error_tbl", SqlIfExists::Fail).expect("write");
23778
23779        let empty = read_sql_table_columns_chunks_with_index_col(
23780            &conn,
23781            "proj_index_error_tbl",
23782            &[],
23783            Some("ints"),
23784            1,
23785        )
23786        .expect_err("empty projection should be rejected");
23787        assert!(matches!(empty, IoError::Sql(msg) if msg.contains("columns must be non-empty")));
23788
23789        let invalid = read_sql_table_columns_with_index_col(
23790            &conn,
23791            "proj_index_error_tbl",
23792            &["bad column"],
23793            Some("ints"),
23794        )
23795        .expect_err("invalid projection name should be rejected");
23796        assert!(matches!(invalid, IoError::Sql(msg) if msg.contains("invalid column name")));
23797    }
23798
23799    #[cfg(feature = "sql-sqlite")]
23800    #[test]
23801    fn sql_read_query_with_index_col_works_on_arbitrary_select() {
23802        let frame = make_test_dataframe();
23803        let conn = make_sql_test_conn();
23804        write_sql(&frame, &conn, "queried_tbl", SqlIfExists::Fail).expect("write");
23805        let result = read_sql_with_index_col(
23806            &conn,
23807            "SELECT names AS label, ints, floats FROM queried_tbl ORDER BY ints DESC",
23808            Some("label"),
23809        )
23810        .expect("read query with index");
23811        assert_eq!(result.index().name(), Some("label"));
23812        // Order respected by the SELECT (ints DESC) → index labels in
23813        // reversed name order.
23814        assert_eq!(
23815            result.index().labels()[0],
23816            crate::IndexLabel::Utf8("carol".into())
23817        );
23818        assert_eq!(
23819            result.index().labels()[2],
23820            crate::IndexLabel::Utf8("alice".into())
23821        );
23822    }
23823
23824    #[cfg(feature = "sql-sqlite")]
23825    #[test]
23826    fn sql_write_read_roundtrip() {
23827        let frame = make_test_dataframe();
23828        let conn = make_sql_test_conn();
23829
23830        write_sql(&frame, &conn, "test_table", SqlIfExists::Fail).expect("write sql");
23831
23832        let frame2 = read_sql_table(&conn, "test_table").expect("read sql");
23833        assert_eq!(frame2.index().len(), 3);
23834
23835        // Int values survive round-trip.
23836        let ints = frame2.column("ints").unwrap();
23837        assert_eq!(ints.values()[0], Scalar::Int64(10));
23838        assert_eq!(ints.values()[1], Scalar::Int64(20));
23839        assert_eq!(ints.values()[2], Scalar::Int64(30));
23840
23841        // Float values survive round-trip.
23842        let floats = frame2.column("floats").unwrap();
23843        assert_eq!(floats.values()[0], Scalar::Float64(1.5));
23844        assert_eq!(floats.values()[1], Scalar::Float64(2.5));
23845        assert_eq!(floats.values()[2], Scalar::Float64(3.5));
23846
23847        // String values survive round-trip.
23848        let names = frame2.column("names").unwrap();
23849        assert_eq!(names.values()[0], Scalar::Utf8("alice".into()));
23850        assert_eq!(names.values()[1], Scalar::Utf8("bob".into()));
23851        assert_eq!(names.values()[2], Scalar::Utf8("carol".into()));
23852    }
23853
23854    #[derive(Default)]
23855    struct DollarMarkerSqlConn {
23856        insert_sql: std::cell::RefCell<Vec<String>>,
23857        inserted_rows: std::cell::RefCell<Vec<Vec<Vec<Scalar>>>>,
23858    }
23859
23860    impl super::SqlConnection for DollarMarkerSqlConn {
23861        fn query(
23862            &self,
23863            _query: &str,
23864            _params: &[Scalar],
23865        ) -> Result<super::SqlQueryResult, IoError> {
23866            Err(IoError::Sql("mock connection does not read".to_owned()))
23867        }
23868
23869        fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
23870            Ok(())
23871        }
23872
23873        fn table_exists(&self, _table_name: &str) -> Result<bool, IoError> {
23874            Ok(false)
23875        }
23876
23877        fn insert_rows(&self, insert_sql: &str, rows: &[Vec<Scalar>]) -> Result<(), IoError> {
23878            self.insert_sql.borrow_mut().push(insert_sql.to_owned());
23879            self.inserted_rows.borrow_mut().push(rows.to_vec());
23880            Ok(())
23881        }
23882
23883        fn dtype_sql(&self, dtype: DType) -> &'static str {
23884            match dtype {
23885                DType::Int64
23886                | DType::Int64Nullable
23887                | DType::Bool
23888                | DType::BoolNullable
23889                | DType::Timedelta64
23890                | DType::Datetime64 { .. } => "BIGINT",
23891                // Paired with `Float64` the way `Int64Nullable` is paired with
23892                // `Int64` above. This match is EXHAUSTIVE on purpose — leaving it
23893                // that way is what turned the missing variant into a compile error
23894                // instead of a silent `TEXT` column. br-frankenpandas-lkrb8.
23895                DType::Float64 | DType::Float64Nullable => "DOUBLE PRECISION",
23896                DType::Utf8
23897                | DType::Categorical
23898                | DType::Null
23899                | DType::Sparse
23900                | DType::Period
23901                | DType::Interval => "TEXT",
23902            }
23903        }
23904
23905        fn index_dtype_sql(&self, _index: &Index) -> &'static str {
23906            "TEXT"
23907        }
23908
23909        fn parameter_marker(&self, ordinal: usize) -> String {
23910            format!("${ordinal}")
23911        }
23912    }
23913
23914    #[test]
23915    fn sql_query_builders_quote_select_and_projection_identifiers() {
23916        let conn = DollarMarkerSqlConn::default();
23917        assert_eq!(
23918            super::sql_select_all_query(&conn, "portable_tbl").expect("select all query"),
23919            "SELECT * FROM \"portable_tbl\""
23920        );
23921        assert_eq!(
23922            super::sql_select_columns_query(&conn, "portable_tbl", &["names", "ints"])
23923                .expect("projection query"),
23924            "SELECT \"names\", \"ints\" FROM \"portable_tbl\""
23925        );
23926
23927        let err = super::sql_select_columns_query(&conn, "portable_tbl", &["bad column"])
23928            .expect_err("projection identifiers stay validated");
23929        assert!(matches!(err, IoError::Sql(msg) if msg.contains("invalid column name")));
23930    }
23931
23932    #[test]
23933    fn sql_query_builders_create_and_insert_use_backend_contracts() {
23934        let conn = DollarMarkerSqlConn::default();
23935        let column_defs = vec![
23936            super::sql_column_definition(&conn, "row id", "TEXT").expect("index column definition"),
23937            super::sql_column_definition(&conn, "value\"raw", "BIGINT")
23938                .expect("value column definition"),
23939        ];
23940
23941        assert_eq!(
23942            super::sql_create_table_query(&conn, "typed_tbl", &column_defs)
23943                .expect("create table query"),
23944            "CREATE TABLE IF NOT EXISTS \"typed_tbl\" (\"row id\" TEXT, \"value\"\"raw\" BIGINT)"
23945        );
23946
23947        let insert_columns = vec!["row id".to_owned(), "value\"raw".to_owned()];
23948        assert_eq!(
23949            super::sql_insert_rows_query(&conn, "typed_tbl", &insert_columns)
23950                .expect("insert row query"),
23951            "INSERT INTO \"typed_tbl\" (\"row id\", \"value\"\"raw\") VALUES ($1, $2)"
23952        );
23953    }
23954
23955    /// Verify that quote_identifier overrides on a custom backend ACTUALLY
23956    /// flow through the helper functions (br-frankenpandas-cx2x / fd90.12).
23957    /// A MySQL-style backend that returns backticks must produce backticked
23958    /// identifiers in CREATE / SELECT / INSERT statements without any
23959    /// further plumbing.
23960    #[test]
23961    fn sql_query_builders_use_backend_quote_identifier_override() {
23962        #[derive(Default)]
23963        struct BacktickSqlConn;
23964        impl super::SqlConnection for BacktickSqlConn {
23965            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<super::SqlQueryResult, IoError> {
23966                Ok(super::SqlQueryResult {
23967                    columns: vec![],
23968                    rows: vec![],
23969                })
23970            }
23971            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
23972                Ok(())
23973            }
23974            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
23975                Ok(false)
23976            }
23977            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
23978                Ok(())
23979            }
23980            fn dtype_sql(&self, _dtype: DType) -> &'static str {
23981                "TEXT"
23982            }
23983            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
23984                "TEXT"
23985            }
23986            fn quote_identifier(&self, ident: &str) -> Result<String, IoError> {
23987                if ident.contains('\0') {
23988                    return Err(IoError::Sql("invalid SQL identifier: NUL byte".to_owned()));
23989                }
23990                // MySQL-style backtick quoting; embedded backticks doubled.
23991                Ok(format!("`{}`", ident.replace('`', "``")))
23992            }
23993        }
23994
23995        let conn = BacktickSqlConn;
23996        // SELECT / projection helpers flow through quote_identifier.
23997        assert_eq!(
23998            super::sql_select_all_query(&conn, "users").expect("select all"),
23999            "SELECT * FROM `users`"
24000        );
24001        assert_eq!(
24002            super::sql_select_columns_query(&conn, "users", &["id", "name"]).expect("projection"),
24003            "SELECT `id`, `name` FROM `users`"
24004        );
24005        // CREATE / INSERT helpers flow through quote_identifier.
24006        let col_defs = vec![super::sql_column_definition(&conn, "id", "INTEGER").expect("col def")];
24007        assert_eq!(
24008            super::sql_create_table_query(&conn, "users", &col_defs).expect("create"),
24009            "CREATE TABLE IF NOT EXISTS `users` (`id` INTEGER)"
24010        );
24011        let insert_cols = vec!["id".to_owned(), "name".to_owned()];
24012        assert_eq!(
24013            super::sql_insert_rows_query(&conn, "users", &insert_cols).expect("insert"),
24014            "INSERT INTO `users` (`id`, `name`) VALUES (?, ?)"
24015        );
24016    }
24017
24018    #[test]
24019    fn sql_write_uses_backend_parameter_markers() {
24020        let frame = make_test_dataframe();
24021        let conn = DollarMarkerSqlConn::default();
24022
24023        write_sql(&frame, &conn, "portable_tbl", SqlIfExists::Fail)
24024            .expect("write through marker-aware mock backend");
24025
24026        let insert_sql = conn.insert_sql.borrow();
24027        assert_eq!(
24028            insert_sql.as_slice(),
24029            &["INSERT INTO \"portable_tbl\" (\"ints\", \"floats\", \"names\") VALUES ($1, $2, $3)"
24030                .to_owned()]
24031        );
24032        let inserted_rows = conn.inserted_rows.borrow();
24033        assert_eq!(inserted_rows[0].len(), frame.index().len());
24034        assert_eq!(inserted_rows[0][0][0], Scalar::Int64(10));
24035        assert_eq!(inserted_rows[0][2][2], Scalar::Utf8("carol".into()));
24036    }
24037
24038    #[cfg(feature = "sql-sqlite")]
24039    #[test]
24040    fn sql_write_with_options_includes_named_index_column() {
24041        let mut columns = BTreeMap::new();
24042        columns.insert(
24043            "vals".to_string(),
24044            Column::new(DType::Int64, vec![Scalar::Int64(10), Scalar::Int64(20)]).unwrap(),
24045        );
24046
24047        let frame = DataFrame::new_with_column_order(
24048            Index::new(vec![IndexLabel::Int64(101), IndexLabel::Int64(102)]).set_name("row_id"),
24049            columns,
24050            vec!["vals".to_string()],
24051        )
24052        .unwrap();
24053        let conn = make_sql_test_conn();
24054
24055        write_sql_with_options(
24056            &frame,
24057            &conn,
24058            "indexed_write_tbl",
24059            &SqlWriteOptions {
24060                if_exists: SqlIfExists::Fail,
24061                index: true,
24062                index_label: None,
24063                schema: None,
24064                dtype: None,
24065                method: SqlInsertMethod::Single,
24066                chunksize: None,
24067            },
24068        )
24069        .expect("write with named index");
24070
24071        let roundtrip = read_sql_table_with_index_col(&conn, "indexed_write_tbl", Some("row_id"))
24072            .expect("read with promoted index");
24073        assert_eq!(roundtrip.index().name(), Some("row_id"));
24074        assert_eq!(roundtrip.index().labels(), frame.index().labels());
24075        assert!(roundtrip.column("row_id").is_none());
24076        assert_eq!(
24077            roundtrip.column("vals").unwrap().values(),
24078            &[Scalar::Int64(10), Scalar::Int64(20)]
24079        );
24080    }
24081
24082    #[cfg(feature = "sql-sqlite")]
24083    #[test]
24084    fn sql_write_with_options_unnamed_index_defaults_to_index_column_name() {
24085        let frame = make_test_dataframe();
24086        let conn = make_sql_test_conn();
24087
24088        write_sql_with_options(
24089            &frame,
24090            &conn,
24091            "default_index_tbl",
24092            &SqlWriteOptions {
24093                if_exists: SqlIfExists::Fail,
24094                index: true,
24095                index_label: None,
24096                schema: None,
24097                dtype: None,
24098                method: SqlInsertMethod::Single,
24099                chunksize: None,
24100            },
24101        )
24102        .expect("write with unnamed index");
24103
24104        let raw = read_sql_table(&conn, "default_index_tbl").expect("read raw table");
24105        assert!(raw.column("index").is_some());
24106        assert_eq!(raw.column("index").unwrap().values()[0], Scalar::Int64(0));
24107        assert_eq!(raw.column("index").unwrap().values()[2], Scalar::Int64(2));
24108    }
24109
24110    #[cfg(feature = "sql-sqlite")]
24111    #[test]
24112    fn sql_write_with_options_index_label_overrides_name() {
24113        let mut columns = BTreeMap::new();
24114        columns.insert(
24115            "vals".to_string(),
24116            Column::new(DType::Int64, vec![Scalar::Int64(7), Scalar::Int64(8)]).unwrap(),
24117        );
24118
24119        let frame = DataFrame::new_with_column_order(
24120            Index::new(vec![IndexLabel::Int64(1), IndexLabel::Int64(2)]).set_name("row_id"),
24121            columns,
24122            vec!["vals".to_string()],
24123        )
24124        .unwrap();
24125        let conn = make_sql_test_conn();
24126
24127        write_sql_with_options(
24128            &frame,
24129            &conn,
24130            "override_index_tbl",
24131            &SqlWriteOptions {
24132                if_exists: SqlIfExists::Fail,
24133                index: true,
24134                index_label: Some("custom_id".to_string()),
24135                schema: None,
24136                dtype: None,
24137                method: SqlInsertMethod::Single,
24138                chunksize: None,
24139            },
24140        )
24141        .expect("write with custom index label");
24142
24143        let raw = read_sql_table(&conn, "override_index_tbl").expect("read raw table");
24144        assert!(raw.column("custom_id").is_some());
24145        assert!(raw.column("row_id").is_none());
24146        assert_eq!(
24147            raw.column("custom_id").unwrap().values()[0],
24148            Scalar::Int64(1)
24149        );
24150        assert_eq!(
24151            raw.column("custom_id").unwrap().values()[1],
24152            Scalar::Int64(2)
24153        );
24154    }
24155
24156    #[cfg(feature = "sql-sqlite")]
24157    #[test]
24158    fn sql_write_with_options_index_false_omits_index_column() {
24159        let mut columns = BTreeMap::new();
24160        columns.insert(
24161            "vals".to_string(),
24162            Column::new(DType::Int64, vec![Scalar::Int64(5), Scalar::Int64(6)]).unwrap(),
24163        );
24164
24165        let frame = DataFrame::new_with_column_order(
24166            Index::new(vec![IndexLabel::Int64(9), IndexLabel::Int64(10)]).set_name("row_id"),
24167            columns,
24168            vec!["vals".to_string()],
24169        )
24170        .unwrap();
24171        let conn = make_sql_test_conn();
24172
24173        write_sql_with_options(
24174            &frame,
24175            &conn,
24176            "no_index_write_tbl",
24177            &SqlWriteOptions {
24178                if_exists: SqlIfExists::Fail,
24179                index: false,
24180                index_label: Some("custom_id".to_string()),
24181                schema: None,
24182                dtype: None,
24183                method: SqlInsertMethod::Single,
24184                chunksize: None,
24185            },
24186        )
24187        .expect("write without index");
24188
24189        let raw = read_sql_table(&conn, "no_index_write_tbl").expect("read raw table");
24190        assert!(raw.column("row_id").is_none());
24191        assert!(raw.column("custom_id").is_none());
24192        let names: Vec<&str> = raw
24193            .column_names()
24194            .iter()
24195            .map(|name| name.as_str())
24196            .collect();
24197        assert_eq!(names, vec!["vals"]);
24198    }
24199
24200    #[cfg(feature = "sql-sqlite")]
24201    #[test]
24202    fn sql_read_with_query() {
24203        let frame = make_test_dataframe();
24204        let conn = make_sql_test_conn();
24205        write_sql(&frame, &conn, "data", SqlIfExists::Fail).unwrap();
24206
24207        let filtered = read_sql(&conn, "SELECT ints, names FROM data WHERE ints > 15").unwrap();
24208        assert_eq!(filtered.index().len(), 2); // rows with ints=20,30
24209        assert_eq!(
24210            filtered.column("ints").unwrap().values()[0],
24211            Scalar::Int64(20)
24212        );
24213        assert_eq!(
24214            filtered.column("names").unwrap().values()[1],
24215            Scalar::Utf8("carol".into())
24216        );
24217    }
24218
24219    #[cfg(feature = "sql-sqlite")]
24220    #[test]
24221    fn sql_read_query_alias_matches_read_sql_query_path() {
24222        let frame = make_test_dataframe();
24223        let conn = make_sql_test_conn();
24224        write_sql(&frame, &conn, "data", SqlIfExists::Fail).unwrap();
24225
24226        let queried = read_sql_query(
24227            &conn,
24228            "SELECT names, ints FROM data WHERE ints >= 20 ORDER BY ints",
24229        )
24230        .unwrap();
24231
24232        assert_eq!(queried.column_names(), vec!["names", "ints"]);
24233        assert_eq!(queried.index().len(), 2);
24234        assert_eq!(
24235            queried.column("names").unwrap().values(),
24236            &[
24237                Scalar::Utf8("bob".to_owned()),
24238                Scalar::Utf8("carol".to_owned())
24239            ]
24240        );
24241        assert_eq!(
24242            queried.column("ints").unwrap().values(),
24243            &[Scalar::Int64(20), Scalar::Int64(30)]
24244        );
24245    }
24246
24247    #[cfg(feature = "sql-sqlite")]
24248    #[test]
24249    fn sql_read_query_with_options_applies_params_and_parse_dates() {
24250        let conn = make_sql_test_conn();
24251        conn.execute_batch(
24252            "CREATE TABLE events (ts TEXT, value INTEGER);
24253             INSERT INTO events (ts, value) VALUES
24254                ('2024-01-15', 1),
24255                ('2024-02-01 05:06:07', 2),
24256                ('2024-03-03', 3);",
24257        )
24258        .expect("create events table");
24259
24260        let frame = read_sql_query_with_options(
24261            &conn,
24262            "SELECT ts, value FROM events WHERE value > ? ORDER BY value",
24263            &SqlReadOptions {
24264                params: Some(vec![Scalar::Int64(1)]),
24265                parse_dates: Some(vec!["ts".to_owned()]),
24266                coerce_float: false,
24267                dtype: None,
24268                schema: None,
24269                columns: None,
24270                index_col: None,
24271            },
24272        )
24273        .expect("read_sql_query with options");
24274
24275        assert_eq!(frame.column_names(), vec!["ts", "value"]);
24276        // parse_dates now yields typed Datetime64[ns] (br-frankenpandas-0ezw7).
24277        assert_eq!(
24278            frame.column("ts").unwrap().values(),
24279            &[
24280                Scalar::Datetime64(1_706_763_967_000_000_000),
24281                Scalar::Datetime64(1_709_424_000_000_000_000)
24282            ]
24283        );
24284        assert_eq!(
24285            frame.column("value").unwrap().values(),
24286            &[Scalar::Int64(2), Scalar::Int64(3)]
24287        );
24288    }
24289
24290    #[test]
24291    fn sql_read_query_with_options_and_index_col_uses_generic_connection() {
24292        use std::cell::RefCell;
24293
24294        struct RecordingSqlConn {
24295            seen_query: RefCell<Option<String>>,
24296            seen_params: RefCell<Vec<Scalar>>,
24297        }
24298
24299        impl super::SqlConnection for RecordingSqlConn {
24300            fn query(&self, query: &str, params: &[Scalar]) -> Result<SqlQueryResult, IoError> {
24301                *self.seen_query.borrow_mut() = Some(query.to_owned());
24302                *self.seen_params.borrow_mut() = params.to_vec();
24303                Ok(SqlQueryResult {
24304                    columns: vec![
24305                        "row_id".to_owned(),
24306                        "ts".to_owned(),
24307                        "amount".to_owned(),
24308                        "label".to_owned(),
24309                    ],
24310                    rows: vec![
24311                        vec![
24312                            Scalar::Int64(101),
24313                            Scalar::Utf8("2024-01-15".to_owned()),
24314                            Scalar::Utf8("$1.25".to_owned()),
24315                            Scalar::Utf8("alpha".to_owned()),
24316                        ],
24317                        vec![
24318                            Scalar::Int64(102),
24319                            Scalar::Utf8("2024-01-16".to_owned()),
24320                            Scalar::Utf8("2.50".to_owned()),
24321                            Scalar::Utf8("beta".to_owned()),
24322                        ],
24323                    ],
24324                })
24325            }
24326
24327            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
24328                Ok(())
24329            }
24330
24331            fn table_exists(&self, _table_name: &str) -> Result<bool, IoError> {
24332                Ok(false)
24333            }
24334
24335            fn insert_rows(&self, _insert_sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
24336                Ok(())
24337            }
24338
24339            fn dtype_sql(&self, _dtype: DType) -> &'static str {
24340                "TEXT"
24341            }
24342
24343            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
24344                "BIGINT"
24345            }
24346        }
24347
24348        let conn = RecordingSqlConn {
24349            seen_query: RefCell::new(None),
24350            seen_params: RefCell::new(Vec::new()),
24351        };
24352        let query = "SELECT row_id, ts, amount, label FROM events WHERE amount > ?";
24353        let frame = super::read_sql_query_with_options_and_index_col(
24354            &conn,
24355            query,
24356            &SqlReadOptions {
24357                params: Some(vec![Scalar::Float64(1.0)]),
24358                parse_dates: Some(vec!["ts".to_owned()]),
24359                coerce_float: true,
24360                dtype: None,
24361                schema: None,
24362                columns: None,
24363                index_col: Some("amount".to_owned()),
24364            },
24365            Some("row_id"),
24366        )
24367        .expect("generic read_sql query with options and index_col");
24368
24369        assert_eq!(conn.seen_query.borrow().as_deref(), Some(query));
24370        assert_eq!(
24371            conn.seen_params.borrow().as_slice(),
24372            &[Scalar::Float64(1.0)]
24373        );
24374        assert_eq!(frame.index().name(), Some("row_id"));
24375        assert_eq!(
24376            frame.index().labels(),
24377            &[IndexLabel::Int64(101), IndexLabel::Int64(102)]
24378        );
24379        assert_eq!(frame.column_names(), vec!["ts", "amount", "label"]);
24380        // parse_dates now yields typed Datetime64[ns] (br-frankenpandas-0ezw7).
24381        assert_eq!(
24382            frame.column("ts").unwrap().values(),
24383            &[
24384                Scalar::Datetime64(1_705_276_800_000_000_000),
24385                Scalar::Datetime64(1_705_363_200_000_000_000)
24386            ]
24387        );
24388        assert_eq!(
24389            frame.column("amount").unwrap().values(),
24390            &[Scalar::Float64(1.25), Scalar::Float64(2.5)]
24391        );
24392        assert_eq!(
24393            frame.column("label").unwrap().values(),
24394            &[
24395                Scalar::Utf8("alpha".to_owned()),
24396                Scalar::Utf8("beta".to_owned())
24397            ]
24398        );
24399    }
24400
24401    #[cfg(feature = "sql-sqlite")]
24402    #[test]
24403    fn sql_read_query_with_index_col_promotes_named_column() {
24404        let frame = make_test_dataframe();
24405        let conn = make_sql_test_conn();
24406        write_sql(&frame, &conn, "data", SqlIfExists::Fail).unwrap();
24407
24408        let indexed = read_sql_query_with_index_col(
24409            &conn,
24410            "SELECT names, ints FROM data ORDER BY ints",
24411            Some("names"),
24412        )
24413        .unwrap();
24414
24415        assert_eq!(
24416            indexed.index().labels(),
24417            &[
24418                IndexLabel::Utf8("alice".to_owned()),
24419                IndexLabel::Utf8("bob".to_owned()),
24420                IndexLabel::Utf8("carol".to_owned())
24421            ]
24422        );
24423        assert_eq!(indexed.index().name(), Some("names"));
24424        assert!(indexed.column("names").is_none());
24425        assert_eq!(
24426            indexed.column("ints").unwrap().values(),
24427            &[Scalar::Int64(10), Scalar::Int64(20), Scalar::Int64(30)]
24428        );
24429    }
24430
24431    #[cfg(feature = "sql-sqlite")]
24432    #[test]
24433    fn sql_read_query_chunks_alias_batches_rows() {
24434        let conn = make_sql_test_conn();
24435        conn.execute_batch(
24436            "CREATE TABLE query_chunked (id INTEGER, name TEXT);
24437             INSERT INTO query_chunked (id, name) VALUES
24438                (1, 'alpha'),
24439                (2, 'beta'),
24440                (3, 'gamma');",
24441        )
24442        .expect("create query_chunked table");
24443
24444        let chunks =
24445            read_sql_query_chunks(&conn, "SELECT id, name FROM query_chunked ORDER BY id", 2)
24446                .expect("query chunk iterator")
24447                .collect::<Result<Vec<_>, _>>()
24448                .expect("all chunks");
24449
24450        assert_eq!(chunks.len(), 2);
24451        assert_eq!(chunks[0].column_names(), vec!["id", "name"]);
24452        assert_eq!(
24453            chunks[0].column("id").unwrap().values(),
24454            &[Scalar::Int64(1), Scalar::Int64(2)]
24455        );
24456        assert_eq!(
24457            chunks[1].column("name").unwrap().values(),
24458            &[Scalar::Utf8("gamma".to_owned())]
24459        );
24460    }
24461
24462    #[cfg(feature = "sql-sqlite")]
24463    #[test]
24464    fn sql_read_query_chunks_with_options_applies_params_parse_dates_and_coerce_float() {
24465        let conn = make_sql_test_conn();
24466        conn.execute_batch(
24467            "CREATE TABLE query_events (ts TEXT, amount TEXT, keep INTEGER);
24468             INSERT INTO query_events (ts, amount, keep) VALUES
24469                ('2024-01-15', '12.50', 0),
24470                ('2024-02-01 05:06:07', '$1,234.50', 1),
24471                ('2024-03-03', '-3.25', 1);",
24472        )
24473        .expect("create query_events table");
24474
24475        let chunks = read_sql_query_chunks_with_options(
24476            &conn,
24477            "SELECT ts, amount FROM query_events WHERE keep = ? ORDER BY ts",
24478            &SqlReadOptions {
24479                params: Some(vec![Scalar::Int64(1)]),
24480                parse_dates: Some(vec!["ts".to_owned()]),
24481                coerce_float: true,
24482                dtype: None,
24483                schema: None,
24484                columns: None,
24485                index_col: None,
24486            },
24487            1,
24488        )
24489        .expect("query chunk iterator")
24490        .collect::<Result<Vec<_>, _>>()
24491        .expect("all chunks");
24492
24493        assert_eq!(chunks.len(), 2);
24494        // parse_dates now yields typed Datetime64[ns] (br-frankenpandas-0ezw7).
24495        assert_eq!(
24496            chunks[0].column("ts").unwrap().values(),
24497            &[Scalar::Datetime64(1_706_763_967_000_000_000)]
24498        );
24499        assert_eq!(
24500            chunks[0].column("amount").unwrap().values(),
24501            &[Scalar::Float64(1234.5)]
24502        );
24503        assert_eq!(
24504            chunks[1].column("ts").unwrap().values(),
24505            &[Scalar::Datetime64(1_709_424_000_000_000_000)]
24506        );
24507        assert_eq!(
24508            chunks[1].column("amount").unwrap().values(),
24509            &[Scalar::Float64(-3.25)]
24510        );
24511    }
24512
24513    #[test]
24514    fn sql_read_chunks_uses_paged_queries_when_backend_opts_in() {
24515        use std::cell::RefCell;
24516
24517        struct PagedChunksConn {
24518            queries: RefCell<Vec<(String, Vec<Scalar>)>>,
24519            rows: Vec<Vec<Scalar>>,
24520        }
24521
24522        impl PagedChunksConn {
24523            fn page_bounds(params: &[Scalar]) -> (usize, usize) {
24524                let [
24525                    Scalar::Int64(1),
24526                    Scalar::Int64(limit),
24527                    Scalar::Int64(offset),
24528                ] = params
24529                else {
24530                    assert_eq!(
24531                        params,
24532                        &[Scalar::Int64(1), Scalar::Int64(0), Scalar::Int64(0),],
24533                        "expected original param plus LIMIT/OFFSET params"
24534                    );
24535                    return (0, 0);
24536                };
24537                (
24538                    usize::try_from(*limit).expect("non-negative limit"),
24539                    usize::try_from(*offset).expect("non-negative offset"),
24540                )
24541            }
24542        }
24543
24544        impl super::SqlConnection for PagedChunksConn {
24545            fn query(&self, query: &str, params: &[Scalar]) -> Result<SqlQueryResult, IoError> {
24546                self.queries
24547                    .borrow_mut()
24548                    .push((query.to_owned(), params.to_vec()));
24549                assert!(
24550                    query.contains("frankenpandas_sql_chunk_source")
24551                        && query.contains("LIMIT ? OFFSET ?"),
24552                    "paged chunk path should wrap the caller query with LIMIT/OFFSET, got {query}"
24553                );
24554
24555                let (limit, offset) = Self::page_bounds(params);
24556                let rows = self.rows.iter().skip(offset).take(limit).cloned().collect();
24557                Ok(SqlQueryResult {
24558                    columns: vec!["id".to_owned(), "name".to_owned()],
24559                    rows,
24560                })
24561            }
24562
24563            fn supports_paged_sql_chunks(&self) -> bool {
24564                true
24565            }
24566
24567            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
24568                Ok(())
24569            }
24570
24571            fn table_exists(&self, _table_name: &str) -> Result<bool, IoError> {
24572                Ok(false)
24573            }
24574
24575            fn insert_rows(&self, _insert_sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
24576                Ok(())
24577            }
24578
24579            fn dtype_sql(&self, _dtype: DType) -> &'static str {
24580                "TEXT"
24581            }
24582
24583            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
24584                "TEXT"
24585            }
24586        }
24587
24588        let conn = PagedChunksConn {
24589            queries: RefCell::new(Vec::new()),
24590            rows: vec![
24591                vec![Scalar::Int64(1), Scalar::Utf8("a".to_owned())],
24592                vec![Scalar::Int64(2), Scalar::Utf8("b".to_owned())],
24593                vec![Scalar::Int64(3), Scalar::Utf8("c".to_owned())],
24594                vec![Scalar::Int64(4), Scalar::Utf8("d".to_owned())],
24595                vec![Scalar::Int64(5), Scalar::Utf8("e".to_owned())],
24596            ],
24597        };
24598
24599        let chunks = read_sql_chunks_with_options(
24600            &conn,
24601            "SELECT id, name FROM paged_source WHERE keep = ? ORDER BY id;",
24602            &SqlReadOptions {
24603                params: Some(vec![Scalar::Int64(1)]),
24604                ..SqlReadOptions::default()
24605            },
24606            2,
24607        )
24608        .expect("paged chunk iterator")
24609        .collect::<Result<Vec<_>, _>>()
24610        .expect("all chunks");
24611
24612        assert_eq!(chunks.len(), 3);
24613        assert_eq!(
24614            chunks[0].column("id").unwrap().values(),
24615            &[Scalar::Int64(1), Scalar::Int64(2)]
24616        );
24617        assert_eq!(
24618            chunks[1].column("id").unwrap().values(),
24619            &[Scalar::Int64(3), Scalar::Int64(4)]
24620        );
24621        assert_eq!(
24622            chunks[2].column("name").unwrap().values(),
24623            &[Scalar::Utf8("e".to_owned())]
24624        );
24625
24626        let queries = conn.queries.borrow();
24627        let expected_params = vec![
24628            vec![Scalar::Int64(1), Scalar::Int64(0), Scalar::Int64(0)],
24629            vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(0)],
24630            vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(2)],
24631            vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(4)],
24632        ];
24633        assert_eq!(
24634            queries
24635                .iter()
24636                .map(|(_, params)| params.clone())
24637                .collect::<Vec<_>>(),
24638            expected_params
24639        );
24640    }
24641
24642    #[cfg(feature = "sql-sqlite")]
24643    #[test]
24644    fn sql_read_query_chunks_with_options_and_index_col_applies_options_before_indexing() {
24645        let conn = make_sql_test_conn();
24646        conn.execute_batch(
24647            "CREATE TABLE query_index_events (ts TEXT, amount TEXT, keep INTEGER);
24648             INSERT INTO query_index_events (ts, amount, keep) VALUES
24649                ('2024-01-15', '12.50', 0),
24650                ('2024-02-01 05:06:07', '$1,234.50', 1),
24651                ('2024-03-03', '-3.25', 1);",
24652        )
24653        .expect("create query_index_events table");
24654
24655        let chunks = read_sql_query_chunks_with_options_and_index_col(
24656            &conn,
24657            "SELECT ts, amount FROM query_index_events WHERE keep = ? ORDER BY ts",
24658            &SqlReadOptions {
24659                params: Some(vec![Scalar::Int64(1)]),
24660                parse_dates: Some(vec!["ts".to_owned()]),
24661                coerce_float: true,
24662                dtype: None,
24663                schema: None,
24664                columns: None,
24665                index_col: None,
24666            },
24667            Some("ts"),
24668            1,
24669        )
24670        .expect("indexed query chunk iterator")
24671        .collect::<Result<Vec<_>, _>>()
24672        .expect("all chunks");
24673
24674        assert_eq!(chunks.len(), 2);
24675        assert_eq!(chunks[0].index().name(), Some("ts"));
24676        // parse_dates column promoted to index → DatetimeIndex (br-frankenpandas-0ezw7).
24677        assert_eq!(
24678            chunks[0].index().labels(),
24679            &[IndexLabel::Datetime64(1_706_763_967_000_000_000)]
24680        );
24681        assert!(chunks[0].column("ts").is_none());
24682        assert_eq!(
24683            chunks[0].column("amount").unwrap().values(),
24684            &[Scalar::Float64(1234.5)]
24685        );
24686        assert_eq!(
24687            chunks[1].index().labels(),
24688            &[IndexLabel::Datetime64(1_709_424_000_000_000_000)]
24689        );
24690        assert_eq!(
24691            chunks[1].column("amount").unwrap().values(),
24692            &[Scalar::Float64(-3.25)]
24693        );
24694    }
24695
24696    #[cfg(feature = "sql-sqlite")]
24697    #[test]
24698    fn sql_read_chunks_with_options_and_index_col_none_keeps_options_and_range_index() {
24699        let conn = make_sql_test_conn();
24700        conn.execute_batch(
24701            "CREATE TABLE query_options_no_index (id INTEGER, amount TEXT);
24702             INSERT INTO query_options_no_index (id, amount) VALUES
24703                (1, '$10.50'),
24704                (2, '11.25');",
24705        )
24706        .expect("create query_options_no_index table");
24707
24708        let chunks = read_sql_chunks_with_options_and_index_col(
24709            &conn,
24710            "SELECT id, amount FROM query_options_no_index ORDER BY id",
24711            &SqlReadOptions {
24712                params: None,
24713                parse_dates: None,
24714                coerce_float: true,
24715                dtype: None,
24716                schema: None,
24717                columns: None,
24718                index_col: None,
24719            },
24720            None,
24721            1,
24722        )
24723        .expect("query chunk iterator")
24724        .collect::<Result<Vec<_>, _>>()
24725        .expect("all chunks");
24726
24727        assert_eq!(chunks.len(), 2);
24728        assert_eq!(chunks[0].index().labels(), &[IndexLabel::Int64(0)]);
24729        assert_eq!(chunks[1].index().labels(), &[IndexLabel::Int64(0)]);
24730        assert_eq!(
24731            chunks[0].column("amount").unwrap().values(),
24732            &[Scalar::Float64(10.5)]
24733        );
24734        assert_eq!(
24735            chunks[1].column("amount").unwrap().values(),
24736            &[Scalar::Float64(11.25)]
24737        );
24738    }
24739
24740    #[cfg(feature = "sql-sqlite")]
24741    #[test]
24742    fn sql_read_chunks_with_options_and_index_col_uses_options_index_when_explicit_none() {
24743        let conn = make_sql_test_conn();
24744        conn.execute_batch(
24745            "CREATE TABLE query_options_struct_index (id INTEGER, amount TEXT);
24746             INSERT INTO query_options_struct_index (id, amount) VALUES
24747                (10, '$10.50'),
24748                (20, '11.25');",
24749        )
24750        .expect("create query_options_struct_index table");
24751
24752        let chunks = read_sql_chunks_with_options_and_index_col(
24753            &conn,
24754            "SELECT id, amount FROM query_options_struct_index ORDER BY id",
24755            &SqlReadOptions {
24756                params: None,
24757                parse_dates: None,
24758                coerce_float: true,
24759                dtype: None,
24760                schema: None,
24761                columns: None,
24762                index_col: Some("id".to_owned()),
24763            },
24764            None,
24765            1,
24766        )
24767        .expect("query chunk iterator")
24768        .collect::<Result<Vec<_>, _>>()
24769        .expect("all chunks");
24770
24771        assert_eq!(chunks.len(), 2);
24772        assert_eq!(chunks[0].index().name(), Some("id"));
24773        assert_eq!(chunks[0].index().labels(), &[IndexLabel::Int64(10)]);
24774        assert!(chunks[0].column("id").is_none());
24775        assert_eq!(chunks[1].index().labels(), &[IndexLabel::Int64(20)]);
24776        assert_eq!(
24777            chunks[1].column("amount").unwrap().values(),
24778            &[Scalar::Float64(11.25)]
24779        );
24780    }
24781
24782    #[cfg(feature = "sql-sqlite")]
24783    #[test]
24784    fn sql_read_query_chunks_with_options_and_index_col_missing_column_errors() {
24785        let conn = make_sql_test_conn();
24786        conn.execute_batch(
24787            "CREATE TABLE query_options_missing_index (id INTEGER, amount TEXT);
24788             INSERT INTO query_options_missing_index (id, amount) VALUES (1, '10.5');",
24789        )
24790        .expect("create query_options_missing_index table");
24791
24792        let err = read_sql_query_chunks_with_options_and_index_col(
24793            &conn,
24794            "SELECT id, amount FROM query_options_missing_index",
24795            &SqlReadOptions {
24796                params: None,
24797                parse_dates: None,
24798                coerce_float: true,
24799                dtype: None,
24800                schema: None,
24801                columns: None,
24802                index_col: None,
24803            },
24804            Some("missing"),
24805            1,
24806        )
24807        .expect_err("missing index_col should error during iterator construction");
24808
24809        assert!(matches!(err, IoError::Sql(msg) if msg.contains("index_col")));
24810    }
24811
24812    #[cfg(feature = "sql-sqlite")]
24813    #[test]
24814    fn sql_read_query_with_options_and_index_col_applies_options_before_indexing() {
24815        let conn = make_sql_test_conn();
24816        conn.execute_batch(
24817            "CREATE TABLE query_frame_index_events (ts TEXT, amount TEXT, keep INTEGER);
24818             INSERT INTO query_frame_index_events (ts, amount, keep) VALUES
24819                ('2024-01-15', '12.50', 0),
24820                ('2024-02-01 05:06:07', '$1,234.50', 1),
24821                ('2024-03-03', '-3.25', 1);",
24822        )
24823        .expect("create query_frame_index_events table");
24824
24825        let frame = read_sql_query_with_options_and_index_col(
24826            &conn,
24827            "SELECT ts, amount FROM query_frame_index_events WHERE keep = ? ORDER BY ts",
24828            &SqlReadOptions {
24829                params: Some(vec![Scalar::Int64(1)]),
24830                parse_dates: Some(vec!["ts".to_owned()]),
24831                coerce_float: true,
24832                dtype: None,
24833                schema: None,
24834                columns: None,
24835                index_col: None,
24836            },
24837            Some("ts"),
24838        )
24839        .expect("read indexed query frame");
24840
24841        assert_eq!(frame.index().name(), Some("ts"));
24842        // parse_dates column promoted to index → DatetimeIndex (br-frankenpandas-0ezw7).
24843        assert_eq!(
24844            frame.index().labels(),
24845            &[
24846                IndexLabel::Datetime64(1_706_763_967_000_000_000),
24847                IndexLabel::Datetime64(1_709_424_000_000_000_000)
24848            ]
24849        );
24850        assert!(frame.column("ts").is_none());
24851        assert_eq!(
24852            frame.column("amount").unwrap().values(),
24853            &[Scalar::Float64(1234.5), Scalar::Float64(-3.25)]
24854        );
24855    }
24856
24857    #[cfg(feature = "sql-sqlite")]
24858    #[test]
24859    fn sql_read_query_with_options_and_index_col_explicit_arg_wins() {
24860        let conn = make_sql_test_conn();
24861        conn.execute_batch(
24862            "CREATE TABLE query_frame_index_override (a INTEGER, b INTEGER, val TEXT);
24863             INSERT INTO query_frame_index_override (a, b, val) VALUES
24864                (1, 100, 'x'),
24865                (2, 200, 'y');",
24866        )
24867        .expect("create query_frame_index_override table");
24868
24869        let frame = read_sql_query_with_options_and_index_col(
24870            &conn,
24871            "SELECT a, b, val FROM query_frame_index_override ORDER BY a",
24872            &SqlReadOptions {
24873                index_col: Some("a".to_owned()),
24874                ..SqlReadOptions::default()
24875            },
24876            Some("b"),
24877        )
24878        .expect("read indexed query frame with override");
24879
24880        assert_eq!(frame.column_names(), vec!["a", "val"]);
24881        assert_eq!(
24882            frame.index().labels(),
24883            &[IndexLabel::Int64(100), IndexLabel::Int64(200)]
24884        );
24885    }
24886
24887    #[cfg(feature = "sql-sqlite")]
24888    #[test]
24889    fn sql_read_query_chunks_rejects_zero_chunksize() {
24890        let conn = make_sql_test_conn();
24891
24892        let err = read_sql_query_chunks(&conn, "SELECT 1", 0)
24893            .expect_err("zero query chunksize should be rejected");
24894
24895        assert!(matches!(err, IoError::Sql(msg) if msg.contains("chunksize")));
24896    }
24897
24898    #[cfg(feature = "sql-sqlite")]
24899    #[test]
24900    fn sql_read_query_chunks_with_index_col_promotes_each_chunk_index() {
24901        let conn = make_sql_test_conn();
24902        conn.execute_batch(
24903            "CREATE TABLE query_index_chunked (id INTEGER, label TEXT, value INTEGER);
24904             INSERT INTO query_index_chunked (id, label, value) VALUES
24905                (1, 'alpha', 10),
24906                (2, 'beta', 20),
24907                (3, 'gamma', 30);",
24908        )
24909        .expect("create query_index_chunked table");
24910
24911        let chunks = read_sql_query_chunks_with_index_col(
24912            &conn,
24913            "SELECT id, label, value FROM query_index_chunked ORDER BY id",
24914            Some("label"),
24915            2,
24916        )
24917        .expect("query indexed chunk iterator")
24918        .collect::<Result<Vec<_>, _>>()
24919        .expect("all chunks");
24920
24921        assert_eq!(chunks.len(), 2);
24922        assert_eq!(chunks[0].index().name(), Some("label"));
24923        assert_eq!(
24924            chunks[0].index().labels(),
24925            &[
24926                IndexLabel::Utf8("alpha".to_owned()),
24927                IndexLabel::Utf8("beta".to_owned())
24928            ]
24929        );
24930        assert!(chunks[0].column("label").is_none());
24931        assert_eq!(
24932            chunks[1].index().labels(),
24933            &[IndexLabel::Utf8("gamma".to_owned())]
24934        );
24935        assert_eq!(
24936            chunks[1].column("value").unwrap().values(),
24937            &[Scalar::Int64(30)]
24938        );
24939    }
24940
24941    #[cfg(feature = "sql-sqlite")]
24942    #[test]
24943    fn sql_read_chunks_with_index_col_none_keeps_fresh_chunk_range_indexes() {
24944        let conn = make_sql_test_conn();
24945        conn.execute_batch(
24946            "CREATE TABLE query_no_index_chunked (id INTEGER, label TEXT);
24947             INSERT INTO query_no_index_chunked (id, label) VALUES
24948                (1, 'alpha'),
24949                (2, 'beta');",
24950        )
24951        .expect("create query_no_index_chunked table");
24952
24953        let chunks = read_sql_chunks_with_index_col(
24954            &conn,
24955            "SELECT id, label FROM query_no_index_chunked ORDER BY id",
24956            None,
24957            1,
24958        )
24959        .expect("query chunk iterator")
24960        .collect::<Result<Vec<_>, _>>()
24961        .expect("all chunks");
24962
24963        assert_eq!(chunks.len(), 2);
24964        assert_eq!(chunks[0].index().labels(), &[IndexLabel::Int64(0)]);
24965        assert_eq!(chunks[1].index().labels(), &[IndexLabel::Int64(0)]);
24966        assert_eq!(chunks[1].column_names(), vec!["id", "label"]);
24967    }
24968
24969    #[cfg(feature = "sql-sqlite")]
24970    #[test]
24971    fn sql_read_query_chunks_with_index_col_missing_column_errors() {
24972        let conn = make_sql_test_conn();
24973        conn.execute_batch(
24974            "CREATE TABLE query_missing_index_chunked (id INTEGER, value INTEGER);
24975             INSERT INTO query_missing_index_chunked (id, value) VALUES (1, 10);",
24976        )
24977        .expect("create query_missing_index_chunked table");
24978
24979        let err = read_sql_query_chunks_with_index_col(
24980            &conn,
24981            "SELECT id, value FROM query_missing_index_chunked",
24982            Some("missing"),
24983            1,
24984        )
24985        .expect_err("missing index_col should error during iterator construction");
24986
24987        assert!(matches!(err, IoError::Sql(msg) if msg.contains("index_col")));
24988    }
24989
24990    #[cfg(feature = "sql-sqlite")]
24991    #[test]
24992    fn sql_read_table_chunks_batches_rows() {
24993        let conn = make_sql_test_conn();
24994        conn.execute_batch(
24995            "CREATE TABLE table_chunked (id INTEGER, name TEXT);
24996             INSERT INTO table_chunked (id, name) VALUES
24997                (1, 'alpha'),
24998                (2, 'beta'),
24999                (3, 'gamma'),
25000                (4, 'delta');",
25001        )
25002        .expect("create table_chunked table");
25003
25004        let chunks = read_sql_table_chunks(&conn, "table_chunked", 3)
25005            .expect("table chunk iterator")
25006            .collect::<Result<Vec<_>, _>>()
25007            .expect("all chunks");
25008
25009        assert_eq!(chunks.len(), 2);
25010        assert_eq!(chunks[0].column_names(), vec!["id", "name"]);
25011        assert_eq!(
25012            chunks[0].column("id").unwrap().values(),
25013            &[Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)]
25014        );
25015        assert_eq!(
25016            chunks[1].column("name").unwrap().values(),
25017            &[Scalar::Utf8("delta".to_owned())]
25018        );
25019    }
25020
25021    #[cfg(feature = "sql-sqlite")]
25022    #[test]
25023    fn sql_read_table_chunks_rejects_zero_chunksize() {
25024        let conn = make_sql_test_conn();
25025        conn.execute_batch("CREATE TABLE zero_chunked (id INTEGER);")
25026            .expect("create zero_chunked table");
25027
25028        let err = read_sql_table_chunks(&conn, "zero_chunked", 0)
25029            .expect_err("zero table chunksize should be rejected");
25030
25031        assert!(matches!(err, IoError::Sql(msg) if msg.contains("chunksize")));
25032    }
25033
25034    #[cfg(feature = "sql-sqlite")]
25035    #[test]
25036    fn sql_read_table_chunks_rejects_invalid_table_name() {
25037        let conn = make_sql_test_conn();
25038
25039        let err = read_sql_table_chunks(&conn, "bad table", 1)
25040            .expect_err("invalid table name should be rejected");
25041
25042        assert!(matches!(err, IoError::Sql(msg) if msg.contains("invalid table name")));
25043    }
25044
25045    #[cfg(feature = "sql-sqlite")]
25046    #[test]
25047    fn sql_read_table_chunks_with_index_col_promotes_each_chunk_index() {
25048        let conn = make_sql_test_conn();
25049        conn.execute_batch(
25050            "CREATE TABLE table_index_chunked (id INTEGER, name TEXT, score INTEGER);
25051             INSERT INTO table_index_chunked (id, name, score) VALUES
25052                (10, 'alpha', 100),
25053                (20, 'beta', 200),
25054                (30, 'gamma', 300);",
25055        )
25056        .expect("create table_index_chunked table");
25057
25058        let chunks =
25059            read_sql_table_chunks_with_index_col(&conn, "table_index_chunked", Some("id"), 2)
25060                .expect("table indexed chunk iterator")
25061                .collect::<Result<Vec<_>, _>>()
25062                .expect("all chunks");
25063
25064        assert_eq!(chunks.len(), 2);
25065        assert_eq!(chunks[0].index().name(), Some("id"));
25066        assert_eq!(
25067            chunks[0].index().labels(),
25068            &[IndexLabel::Int64(10), IndexLabel::Int64(20)]
25069        );
25070        assert!(chunks[0].column("id").is_none());
25071        assert_eq!(
25072            chunks[1].column("score").unwrap().values(),
25073            &[Scalar::Int64(300)]
25074        );
25075    }
25076
25077    #[cfg(feature = "sql-sqlite")]
25078    #[test]
25079    fn sql_read_table_with_options_applies_parse_dates_and_coerce_float() {
25080        let conn = make_sql_test_conn();
25081        conn.execute_batch(
25082            "CREATE TABLE table_options (ts TEXT, amount TEXT, label TEXT);
25083             INSERT INTO table_options (ts, amount, label) VALUES
25084                ('2024-01-15', '$12.50', 'a'),
25085                ('2024-02-01 05:06:07', '1,234.50', 'b');",
25086        )
25087        .expect("create table_options table");
25088
25089        let frame = read_sql_table_with_options(
25090            &conn,
25091            "table_options",
25092            &SqlReadOptions {
25093                params: None,
25094                parse_dates: Some(vec!["ts".to_owned()]),
25095                coerce_float: true,
25096                dtype: None,
25097                schema: None,
25098                columns: None,
25099                index_col: None,
25100            },
25101        )
25102        .expect("read table with options");
25103
25104        // parse_dates now yields typed Datetime64[ns] (br-frankenpandas-0ezw7).
25105        assert_eq!(
25106            frame.column("ts").unwrap().values(),
25107            &[
25108                Scalar::Datetime64(1_705_276_800_000_000_000),
25109                Scalar::Datetime64(1_706_763_967_000_000_000)
25110            ]
25111        );
25112        assert_eq!(
25113            frame.column("amount").unwrap().values(),
25114            &[Scalar::Float64(12.5), Scalar::Float64(1234.5)]
25115        );
25116        assert_eq!(
25117            frame.column("label").unwrap().values(),
25118            &[Scalar::Utf8("a".to_owned()), Scalar::Utf8("b".to_owned())]
25119        );
25120    }
25121
25122    #[cfg(feature = "sql-sqlite")]
25123    #[test]
25124    fn sql_read_table_chunks_with_options_applies_options_before_chunking() {
25125        let conn = make_sql_test_conn();
25126        conn.execute_batch(
25127            "CREATE TABLE table_options_chunked (ts TEXT, amount TEXT);
25128             INSERT INTO table_options_chunked (ts, amount) VALUES
25129                ('2024-03-01', '$10.00'),
25130                ('2024-03-02', '$20.50'),
25131                ('2024-03-03', '-3.25');",
25132        )
25133        .expect("create table_options_chunked table");
25134
25135        let chunks = read_sql_table_chunks_with_options(
25136            &conn,
25137            "table_options_chunked",
25138            &SqlReadOptions {
25139                params: None,
25140                parse_dates: Some(vec!["ts".to_owned()]),
25141                coerce_float: true,
25142                dtype: None,
25143                schema: None,
25144                columns: None,
25145                index_col: None,
25146            },
25147            2,
25148        )
25149        .expect("table option chunk iterator")
25150        .collect::<Result<Vec<_>, _>>()
25151        .expect("all chunks");
25152
25153        assert_eq!(chunks.len(), 2);
25154        // parse_dates now yields typed Datetime64[ns] (br-frankenpandas-0ezw7).
25155        assert_eq!(
25156            chunks[0].column("ts").unwrap().values(),
25157            &[
25158                Scalar::Datetime64(1_709_251_200_000_000_000),
25159                Scalar::Datetime64(1_709_337_600_000_000_000)
25160            ]
25161        );
25162        assert_eq!(
25163            chunks[0].column("amount").unwrap().values(),
25164            &[Scalar::Float64(10.0), Scalar::Float64(20.5)]
25165        );
25166        assert_eq!(
25167            chunks[1].column("amount").unwrap().values(),
25168            &[Scalar::Float64(-3.25)]
25169        );
25170    }
25171
25172    #[cfg(feature = "sql-sqlite")]
25173    #[test]
25174    fn sql_read_table_chunks_with_options_validates_chunksize_and_table_name() {
25175        let conn = make_sql_test_conn();
25176        conn.execute_batch(
25177            "CREATE TABLE table_options_errors (ts TEXT);
25178             INSERT INTO table_options_errors (ts) VALUES ('2024-01-01');",
25179        )
25180        .expect("create table_options_errors table");
25181
25182        let zero = read_sql_table_chunks_with_options(
25183            &conn,
25184            "table_options_errors",
25185            &SqlReadOptions::default(),
25186            0,
25187        )
25188        .expect_err("zero chunksize should be rejected");
25189        assert!(matches!(zero, IoError::Sql(msg) if msg.contains("chunksize")));
25190
25191        let invalid = read_sql_table_with_options(
25192            &conn,
25193            "bad table",
25194            &SqlReadOptions {
25195                parse_dates: Some(vec!["ts".to_owned()]),
25196                ..SqlReadOptions::default()
25197            },
25198        )
25199        .expect_err("invalid table name should be rejected");
25200        assert!(matches!(invalid, IoError::Sql(msg) if msg.contains("invalid table name")));
25201    }
25202
25203    // br-frankenpandas-i8kja: read_sql_table_chunks_with_options previously
25204    // accepted SqlReadOptions { index_col: Some(...) } and silently dropped
25205    // the index_col while the full-frame sibling honored it. Surface the
25206    // mismatch with a typed error so callers route to the
25207    // `_and_index_col` variant. The plain entrypoint stays
25208    // `Result<SqlChunkIterator, _>` for backwards compatibility — the
25209    // indexed surface is what carries promotion logic.
25210    #[cfg(feature = "sql-sqlite")]
25211    #[test]
25212    fn read_sql_table_chunks_with_options_rejects_options_index_col() {
25213        let conn = make_sql_test_conn();
25214        super::SqlConnection::execute_batch(
25215            &conn,
25216            "CREATE TABLE i8kja_table_chunks_reject (id INTEGER, val TEXT);",
25217        )
25218        .unwrap();
25219        super::SqlConnection::execute_batch(
25220            &conn,
25221            "INSERT INTO i8kja_table_chunks_reject VALUES (1, 'a'), (2, 'b');",
25222        )
25223        .unwrap();
25224
25225        let err = read_sql_table_chunks_with_options(
25226            &conn,
25227            "i8kja_table_chunks_reject",
25228            &SqlReadOptions {
25229                index_col: Some("id".to_owned()),
25230                ..Default::default()
25231            },
25232            2,
25233        )
25234        .expect_err("options.index_col on non-indexed entrypoint must be rejected");
25235        assert!(
25236            matches!(&err, IoError::Sql(msg) if msg.contains("index_col") && msg.contains("read_sql_table_chunks_with_options_and_index_col")),
25237            "expected typed error pointing to the _and_index_col variant, got: {err:?}"
25238        );
25239
25240        // Sanity: same options struct on the indexed sibling honors index_col.
25241        let chunks: Vec<DataFrame> = read_sql_table_chunks_with_options_and_index_col(
25242            &conn,
25243            "i8kja_table_chunks_reject",
25244            &SqlReadOptions {
25245                index_col: Some("id".to_owned()),
25246                ..Default::default()
25247            },
25248            None,
25249            2,
25250        )
25251        .expect("indexed sibling honors options.index_col")
25252        .collect::<Result<Vec<_>, _>>()
25253        .expect("all chunks");
25254        assert_eq!(chunks.len(), 1);
25255        assert!(chunks[0].column("id").is_none());
25256        assert_eq!(
25257            chunks[0].index().labels(),
25258            &[IndexLabel::Int64(1), IndexLabel::Int64(2)]
25259        );
25260        assert_eq!(
25261            chunks[0].column("val").unwrap().values(),
25262            &[Scalar::Utf8("a".into()), Scalar::Utf8("b".into())]
25263        );
25264    }
25265
25266    #[cfg(feature = "sql-sqlite")]
25267    #[test]
25268    fn read_sql_chunks_with_options_rejects_options_index_col() {
25269        let conn = make_sql_test_conn();
25270        super::SqlConnection::execute_batch(
25271            &conn,
25272            "CREATE TABLE i8kja_query_chunks_reject (id INTEGER, val TEXT);",
25273        )
25274        .unwrap();
25275        super::SqlConnection::execute_batch(
25276            &conn,
25277            "INSERT INTO i8kja_query_chunks_reject VALUES (1, 'a');",
25278        )
25279        .unwrap();
25280
25281        let err = read_sql_chunks_with_options(
25282            &conn,
25283            "SELECT * FROM i8kja_query_chunks_reject",
25284            &SqlReadOptions {
25285                index_col: Some("id".to_owned()),
25286                ..Default::default()
25287            },
25288            2,
25289        )
25290        .expect_err("options.index_col on non-indexed entrypoint must be rejected");
25291        assert!(
25292            matches!(&err, IoError::Sql(msg) if msg.contains("index_col") && msg.contains("read_sql_chunks_with_options_and_index_col")),
25293            "expected typed error pointing to the _and_index_col variant, got: {err:?}"
25294        );
25295
25296        let err = read_sql_query_chunks_with_options(
25297            &conn,
25298            "SELECT * FROM i8kja_query_chunks_reject",
25299            &SqlReadOptions {
25300                index_col: Some("id".to_owned()),
25301                ..Default::default()
25302            },
25303            2,
25304        )
25305        .expect_err("query delegator should propagate the rejection");
25306        assert!(
25307            matches!(&err, IoError::Sql(msg) if msg.contains("index_col") && msg.contains("read_sql_query_chunks_with_options_and_index_col")),
25308            "expected query-specific _and_index_col suggestion, got: {err:?}"
25309        );
25310    }
25311
25312    // br-frankenpandas-t1777: query readers can't apply options.columns
25313    // (caller writes the SELECT, projection is fixed). Silently ignoring
25314    // diverged from the table-reader sibling. All 7 query-reader entry
25315    // points (3 foundations + 4 delegators) must reject options.columns
25316    // with a typed error pointing to the appropriate table reader.
25317    #[cfg(feature = "sql-sqlite")]
25318    #[test]
25319    fn read_sql_with_options_rejects_options_columns_across_query_entrypoints() {
25320        let conn = make_sql_test_conn();
25321        super::SqlConnection::execute_batch(
25322            &conn,
25323            "CREATE TABLE t1777_query_cols_reject (id INTEGER, val TEXT);",
25324        )
25325        .unwrap();
25326        super::SqlConnection::execute_batch(
25327            &conn,
25328            "INSERT INTO t1777_query_cols_reject VALUES (1, 'a'), (2, 'b');",
25329        )
25330        .unwrap();
25331
25332        fn assert_columns_rejection(err: &IoError, expected_sibling: &str) {
25333            assert!(
25334                matches!(err, IoError::Sql(msg)
25335                    if msg.contains("options.columns") && msg.contains(expected_sibling)),
25336                "expected options.columns error pointing to `{expected_sibling}`, got: {err:?}"
25337            );
25338        }
25339
25340        let opts_with_cols = || SqlReadOptions {
25341            columns: Some(vec!["id".to_owned()]),
25342            ..Default::default()
25343        };
25344
25345        // 1. read_sql_with_options (foundation, full-frame)
25346        let err = read_sql_with_options(
25347            &conn,
25348            "SELECT id, val FROM t1777_query_cols_reject",
25349            &opts_with_cols(),
25350        )
25351        .expect_err("read_sql_with_options must reject options.columns");
25352        assert_columns_rejection(&err, "read_sql_table_with_options");
25353
25354        // 2. read_sql_chunks_with_options (foundation, chunked)
25355        let err = read_sql_chunks_with_options(
25356            &conn,
25357            "SELECT id, val FROM t1777_query_cols_reject",
25358            &opts_with_cols(),
25359            2,
25360        )
25361        .expect_err("read_sql_chunks_with_options must reject options.columns");
25362        assert_columns_rejection(&err, "read_sql_table_chunks_with_options");
25363
25364        // 3. read_sql_chunks_with_options_and_index_col (foundation, indexed chunked)
25365        let err = read_sql_chunks_with_options_and_index_col(
25366            &conn,
25367            "SELECT id, val FROM t1777_query_cols_reject",
25368            &opts_with_cols(),
25369            Some("id"),
25370            2,
25371        )
25372        .expect_err("indexed chunks must reject options.columns");
25373        assert_columns_rejection(&err, "read_sql_table_chunks_with_options_and_index_col");
25374
25375        // 4. read_sql_query_with_options (delegator → read_sql_with_options)
25376        let err = read_sql_query_with_options(
25377            &conn,
25378            "SELECT id, val FROM t1777_query_cols_reject",
25379            &opts_with_cols(),
25380        )
25381        .expect_err("read_sql_query_with_options must propagate the rejection");
25382        assert_columns_rejection(&err, "read_sql_table_with_options");
25383
25384        // 5. read_sql_query_with_options_and_index_col (delegator)
25385        let err = read_sql_query_with_options_and_index_col(
25386            &conn,
25387            "SELECT id, val FROM t1777_query_cols_reject",
25388            &opts_with_cols(),
25389            Some("id"),
25390        )
25391        .expect_err("indexed query reader must reject options.columns");
25392        assert_columns_rejection(&err, "read_sql_table_with_options");
25393
25394        // 6. read_sql_query_chunks_with_options (delegator → read_sql_chunks_with_options)
25395        let err = read_sql_query_chunks_with_options(
25396            &conn,
25397            "SELECT id, val FROM t1777_query_cols_reject",
25398            &opts_with_cols(),
25399            2,
25400        )
25401        .expect_err("query chunks delegator must reject options.columns");
25402        assert_columns_rejection(&err, "read_sql_table_chunks_with_options");
25403
25404        // 7. read_sql_query_chunks_with_options_and_index_col (delegator)
25405        let err = read_sql_query_chunks_with_options_and_index_col(
25406            &conn,
25407            "SELECT id, val FROM t1777_query_cols_reject",
25408            &opts_with_cols(),
25409            Some("id"),
25410            2,
25411        )
25412        .expect_err("indexed query chunks delegator must reject options.columns");
25413        assert_columns_rejection(&err, "read_sql_table_chunks_with_options_and_index_col");
25414    }
25415
25416    // br-frankenpandas-t1777: table readers must continue to honor
25417    // options.columns (proves the cleared-options pass-through to the
25418    // query foundation didn't accidentally break the columns projection).
25419    #[cfg(feature = "sql-sqlite")]
25420    #[test]
25421    fn read_sql_table_with_options_still_honors_options_columns_after_t1777() {
25422        let conn = make_sql_test_conn();
25423        super::SqlConnection::execute_batch(
25424            &conn,
25425            "CREATE TABLE t1777_table_cols_honor (id INTEGER, val TEXT, secret TEXT);",
25426        )
25427        .unwrap();
25428        super::SqlConnection::execute_batch(
25429            &conn,
25430            "INSERT INTO t1777_table_cols_honor VALUES (1, 'a', 'x'), (2, 'b', 'y');",
25431        )
25432        .unwrap();
25433
25434        // Full-frame table reader with columns should project `id, val`
25435        // and drop `secret`.
25436        let frame = read_sql_table_with_options(
25437            &conn,
25438            "t1777_table_cols_honor",
25439            &SqlReadOptions {
25440                columns: Some(vec!["id".to_owned(), "val".to_owned()]),
25441                ..Default::default()
25442            },
25443        )
25444        .expect("table reader honors options.columns");
25445        assert_eq!(frame.column_names(), vec!["id", "val"]);
25446        assert!(frame.column("secret").is_none());
25447
25448        // Chunked table reader, same behavior per chunk.
25449        let chunks: Vec<DataFrame> = read_sql_table_chunks_with_options(
25450            &conn,
25451            "t1777_table_cols_honor",
25452            &SqlReadOptions {
25453                columns: Some(vec!["id".to_owned(), "val".to_owned()]),
25454                ..Default::default()
25455            },
25456            1,
25457        )
25458        .expect("chunked table reader honors options.columns")
25459        .collect::<Result<Vec<_>, _>>()
25460        .expect("all chunks");
25461        assert_eq!(chunks.len(), 2);
25462        for c in &chunks {
25463            assert_eq!(c.column_names(), vec!["id", "val"]);
25464            assert!(c.column("secret").is_none());
25465        }
25466
25467        // Indexed full-frame table reader: columns + index_col compose.
25468        let frame = read_sql_table_with_options_and_index_col(
25469            &conn,
25470            "t1777_table_cols_honor",
25471            &SqlReadOptions {
25472                columns: Some(vec!["val".to_owned()]),
25473                ..Default::default()
25474            },
25475            Some("id"),
25476        )
25477        .expect("indexed table reader honors options.columns");
25478        assert_eq!(frame.index().name(), Some("id"));
25479        assert_eq!(frame.column_names(), vec!["val"]);
25480        assert!(frame.column("id").is_none());
25481        assert!(frame.column("secret").is_none());
25482
25483        // Indexed chunked table reader.
25484        let chunks: Vec<DataFrame> = read_sql_table_chunks_with_options_and_index_col(
25485            &conn,
25486            "t1777_table_cols_honor",
25487            &SqlReadOptions {
25488                columns: Some(vec!["val".to_owned()]),
25489                ..Default::default()
25490            },
25491            Some("id"),
25492            1,
25493        )
25494        .expect("indexed chunked table reader honors options.columns")
25495        .collect::<Result<Vec<_>, _>>()
25496        .expect("all chunks");
25497        assert_eq!(chunks.len(), 2);
25498        for c in &chunks {
25499            assert_eq!(c.column_names(), vec!["val"]);
25500            assert!(c.column("id").is_none());
25501            assert!(c.column("secret").is_none());
25502        }
25503    }
25504
25505    #[cfg(feature = "sql-sqlite")]
25506    #[test]
25507    fn sql_read_table_with_options_and_index_col_applies_options_before_indexing() {
25508        let conn = make_sql_test_conn();
25509        conn.execute_batch(
25510            "CREATE TABLE table_options_index (ts TEXT, amount TEXT, label TEXT);
25511             INSERT INTO table_options_index (ts, amount, label) VALUES
25512                ('2024-04-01', '$10.00', 'a'),
25513                ('2024-04-02 03:04:05', '20.50', 'b');",
25514        )
25515        .expect("create table_options_index table");
25516
25517        let frame = read_sql_table_with_options_and_index_col(
25518            &conn,
25519            "table_options_index",
25520            &SqlReadOptions {
25521                params: None,
25522                parse_dates: Some(vec!["ts".to_owned()]),
25523                coerce_float: true,
25524                dtype: None,
25525                schema: None,
25526                columns: None,
25527                index_col: None,
25528            },
25529            Some("ts"),
25530        )
25531        .expect("read table with options and index_col");
25532
25533        assert_eq!(frame.index().name(), Some("ts"));
25534        assert_eq!(
25535            frame.index().labels(),
25536            &[
25537                IndexLabel::Datetime64(1_711_929_600_000_000_000),
25538                IndexLabel::Datetime64(1_712_027_045_000_000_000)
25539            ]
25540        );
25541        assert!(frame.column("ts").is_none());
25542        assert_eq!(
25543            frame.column("amount").unwrap().values(),
25544            &[Scalar::Float64(10.0), Scalar::Float64(20.5)]
25545        );
25546    }
25547
25548    #[cfg(feature = "sql-sqlite")]
25549    #[test]
25550    fn sql_read_table_with_options_and_index_col_none_keeps_options_and_range_index() {
25551        let conn = make_sql_test_conn();
25552        conn.execute_batch(
25553            "CREATE TABLE table_options_no_index (id INTEGER, amount TEXT);
25554             INSERT INTO table_options_no_index (id, amount) VALUES
25555                (1, '$1.25'),
25556                (2, '$2.50');",
25557        )
25558        .expect("create table_options_no_index table");
25559
25560        let frame = read_sql_table_with_options_and_index_col(
25561            &conn,
25562            "table_options_no_index",
25563            &SqlReadOptions {
25564                params: None,
25565                parse_dates: None,
25566                coerce_float: true,
25567                dtype: None,
25568                schema: None,
25569                columns: None,
25570                index_col: None,
25571            },
25572            None,
25573        )
25574        .expect("read table with options and no index_col");
25575
25576        assert_eq!(
25577            frame.index().labels(),
25578            &[IndexLabel::Int64(0), IndexLabel::Int64(1)]
25579        );
25580        assert_eq!(frame.column_names(), vec!["id", "amount"]);
25581        assert_eq!(
25582            frame.column("amount").unwrap().values(),
25583            &[Scalar::Float64(1.25), Scalar::Float64(2.5)]
25584        );
25585    }
25586
25587    #[cfg(feature = "sql-sqlite")]
25588    #[test]
25589    fn sql_read_table_chunks_with_options_and_index_col_promotes_each_chunk_index() {
25590        let conn = make_sql_test_conn();
25591        conn.execute_batch(
25592            "CREATE TABLE table_options_index_chunked (ts TEXT, amount TEXT);
25593             INSERT INTO table_options_index_chunked (ts, amount) VALUES
25594                ('2024-05-01', '$10.00'),
25595                ('2024-05-02', '$20.00'),
25596                ('2024-05-03', '$30.50');",
25597        )
25598        .expect("create table_options_index_chunked table");
25599
25600        let chunks = read_sql_table_chunks_with_options_and_index_col(
25601            &conn,
25602            "table_options_index_chunked",
25603            &SqlReadOptions {
25604                params: None,
25605                parse_dates: Some(vec!["ts".to_owned()]),
25606                coerce_float: true,
25607                dtype: None,
25608                schema: None,
25609                columns: None,
25610                index_col: None,
25611            },
25612            Some("ts"),
25613            2,
25614        )
25615        .expect("table indexed option chunk iterator")
25616        .collect::<Result<Vec<_>, _>>()
25617        .expect("all chunks");
25618
25619        assert_eq!(chunks.len(), 2);
25620        assert_eq!(chunks[0].index().name(), Some("ts"));
25621        // parse_dates column promoted to index → DatetimeIndex (br-frankenpandas-0ezw7).
25622        assert_eq!(
25623            chunks[0].index().labels(),
25624            &[
25625                IndexLabel::Datetime64(1_714_521_600_000_000_000),
25626                IndexLabel::Datetime64(1_714_608_000_000_000_000)
25627            ]
25628        );
25629        assert!(chunks[0].column("ts").is_none());
25630        assert_eq!(
25631            chunks[0].column("amount").unwrap().values(),
25632            &[Scalar::Float64(10.0), Scalar::Float64(20.0)]
25633        );
25634        assert_eq!(
25635            chunks[1].index().labels(),
25636            &[IndexLabel::Datetime64(1_714_694_400_000_000_000)]
25637        );
25638        assert_eq!(
25639            chunks[1].column("amount").unwrap().values(),
25640            &[Scalar::Float64(30.5)]
25641        );
25642    }
25643
25644    #[cfg(feature = "sql-sqlite")]
25645    #[test]
25646    fn sql_read_table_chunks_with_options_and_index_col_uses_options_index_when_explicit_none() {
25647        let conn = make_sql_test_conn();
25648        conn.execute_batch(
25649            "CREATE TABLE table_options_struct_index (id INTEGER, amount TEXT);
25650             INSERT INTO table_options_struct_index (id, amount) VALUES
25651                (10, '$10.00'),
25652                (20, '$20.00'),
25653                (30, '$30.50');",
25654        )
25655        .expect("create table_options_struct_index table");
25656
25657        let chunks = read_sql_table_chunks_with_options_and_index_col(
25658            &conn,
25659            "table_options_struct_index",
25660            &SqlReadOptions {
25661                params: None,
25662                parse_dates: None,
25663                coerce_float: true,
25664                dtype: None,
25665                schema: None,
25666                columns: None,
25667                index_col: Some("id".to_owned()),
25668            },
25669            None,
25670            2,
25671        )
25672        .expect("table indexed option chunk iterator")
25673        .collect::<Result<Vec<_>, _>>()
25674        .expect("all chunks");
25675
25676        assert_eq!(chunks.len(), 2);
25677        assert_eq!(
25678            chunks[0].index().labels(),
25679            &[IndexLabel::Int64(10), IndexLabel::Int64(20)]
25680        );
25681        assert!(chunks[0].column("id").is_none());
25682        assert_eq!(chunks[1].index().labels(), &[IndexLabel::Int64(30)]);
25683        assert_eq!(
25684            chunks[1].column("amount").unwrap().values(),
25685            &[Scalar::Float64(30.5)]
25686        );
25687    }
25688
25689    #[cfg(feature = "sql-sqlite")]
25690    #[test]
25691    fn sql_read_table_chunks_with_options_and_index_col_missing_column_errors() {
25692        let conn = make_sql_test_conn();
25693        conn.execute_batch(
25694            "CREATE TABLE table_options_missing_index (id INTEGER, amount TEXT);
25695             INSERT INTO table_options_missing_index (id, amount) VALUES (1, '$10.00');",
25696        )
25697        .expect("create table_options_missing_index table");
25698
25699        let err = read_sql_table_chunks_with_options_and_index_col(
25700            &conn,
25701            "table_options_missing_index",
25702            &SqlReadOptions {
25703                params: None,
25704                parse_dates: None,
25705                coerce_float: true,
25706                dtype: None,
25707                schema: None,
25708                columns: None,
25709                index_col: None,
25710            },
25711            Some("missing"),
25712            1,
25713        )
25714        .expect_err("missing index_col should error during iterator construction");
25715
25716        assert!(matches!(err, IoError::Sql(msg) if msg.contains("index_col")));
25717    }
25718
25719    #[cfg(feature = "sql-sqlite")]
25720    #[test]
25721    fn sql_read_with_parse_dates_coerces_named_columns() {
25722        let conn = make_sql_test_conn();
25723        conn.execute_batch(
25724            "CREATE TABLE events (ts TEXT, value INTEGER);
25725             INSERT INTO events (ts, value) VALUES
25726                ('2024-01-15', 1),
25727                ('2024-02-01 05:06:07', 2);",
25728        )
25729        .expect("create events table");
25730
25731        let frame = read_sql_with_options(
25732            &conn,
25733            "SELECT ts, value FROM events ORDER BY value",
25734            &SqlReadOptions {
25735                params: None,
25736                parse_dates: Some(vec!["ts".to_owned()]),
25737                coerce_float: false,
25738                dtype: None,
25739                schema: None,
25740                columns: None,
25741                index_col: None,
25742            },
25743        )
25744        .expect("read sql with parse_dates");
25745
25746        // parse_dates now yields typed Datetime64[ns] (br-frankenpandas-0ezw7).
25747        assert_eq!(
25748            frame.column("ts").unwrap().values()[0],
25749            Scalar::Datetime64(1_705_276_800_000_000_000)
25750        );
25751        assert_eq!(
25752            frame.column("ts").unwrap().values()[1],
25753            Scalar::Datetime64(1_706_763_967_000_000_000)
25754        );
25755        assert_eq!(frame.column("value").unwrap().values()[0], Scalar::Int64(1));
25756        assert_eq!(frame.column("value").unwrap().values()[1], Scalar::Int64(2));
25757    }
25758
25759    #[cfg(feature = "sql-sqlite")]
25760    #[test]
25761    fn sql_read_with_parse_dates_missing_column_errors() {
25762        let conn = make_sql_test_conn();
25763        conn.execute_batch(
25764            "CREATE TABLE metrics (value INTEGER);
25765             INSERT INTO metrics (value) VALUES (1);",
25766        )
25767        .expect("create metrics table");
25768
25769        let err = read_sql_with_options(
25770            &conn,
25771            "SELECT value FROM metrics",
25772            &SqlReadOptions {
25773                params: None,
25774                parse_dates: Some(vec!["ts".to_owned()]),
25775                coerce_float: false,
25776                dtype: None,
25777                schema: None,
25778                columns: None,
25779                index_col: None,
25780            },
25781        )
25782        .expect_err("missing parse_dates column should error");
25783
25784        assert!(
25785            matches!(err, IoError::MissingParseDateColumns(missing) if missing == vec!["ts".to_owned()])
25786        );
25787    }
25788
25789    #[cfg(feature = "sql-sqlite")]
25790    #[test]
25791    fn sql_read_with_params_binds_positional_placeholders() {
25792        let frame = make_test_dataframe();
25793        let conn = make_sql_test_conn();
25794        write_sql(&frame, &conn, "data", SqlIfExists::Fail).unwrap();
25795
25796        let filtered = read_sql_with_options(
25797            &conn,
25798            "SELECT ints, names FROM data WHERE ints > ? AND names != ? ORDER BY ints",
25799            &SqlReadOptions {
25800                params: Some(vec![Scalar::Int64(15), Scalar::Utf8("bob".to_owned())]),
25801                parse_dates: None,
25802                coerce_float: false,
25803                dtype: None,
25804                schema: None,
25805                columns: None,
25806                index_col: None,
25807            },
25808        )
25809        .expect("read sql with params");
25810
25811        assert_eq!(filtered.index().len(), 1);
25812        assert_eq!(
25813            filtered.column("ints").unwrap().values(),
25814            &[Scalar::Int64(30)]
25815        );
25816        assert_eq!(
25817            filtered.column("names").unwrap().values(),
25818            &[Scalar::Utf8("carol".into())]
25819        );
25820    }
25821
25822    #[cfg(feature = "sql-sqlite")]
25823    #[test]
25824    fn sql_read_with_params_wrong_arity_errors() {
25825        let frame = make_test_dataframe();
25826        let conn = make_sql_test_conn();
25827        write_sql(&frame, &conn, "data", SqlIfExists::Fail).unwrap();
25828
25829        let err = read_sql_with_options(
25830            &conn,
25831            "SELECT ints FROM data WHERE ints > ? AND names != ?",
25832            &SqlReadOptions {
25833                params: Some(vec![Scalar::Int64(15)]),
25834                parse_dates: None,
25835                coerce_float: false,
25836                dtype: None,
25837                schema: None,
25838                columns: None,
25839                index_col: None,
25840            },
25841        )
25842        .expect_err("wrong arity should error");
25843
25844        assert!(matches!(err, IoError::Sql(msg) if msg.contains("parameter")));
25845    }
25846
25847    #[cfg(feature = "sql-sqlite")]
25848    #[test]
25849    fn sql_read_coerce_float_promotes_decimal_like_text_columns() {
25850        let conn = make_sql_test_conn();
25851        conn.execute_batch(
25852            "CREATE TABLE payments (id INTEGER, amount TEXT, fee TEXT);
25853             INSERT INTO payments (id, amount, fee) VALUES
25854                (1, '12.50', '$1,234.50'),
25855                (2, '-3.25', NULL);",
25856        )
25857        .expect("create payments table");
25858
25859        // Per fd90.41: pandas default for coerce_float is True, and our
25860        // SqlReadOptions::default() now matches. So the bare read_sql
25861        // path coerces decimal-like text columns to Float64 by default.
25862        let default_frame =
25863            read_sql(&conn, "SELECT amount FROM payments ORDER BY id").expect("default read");
25864        assert_eq!(
25865            default_frame.column("amount").unwrap().dtype(),
25866            DType::Float64
25867        );
25868        assert_eq!(
25869            default_frame.column("amount").unwrap().values(),
25870            &[Scalar::Float64(12.5), Scalar::Float64(-3.25)],
25871        );
25872
25873        // Explicitly opting out of coerce_float keeps the raw Utf8.
25874        let no_coerce = read_sql_with_options(
25875            &conn,
25876            "SELECT amount FROM payments ORDER BY id",
25877            &SqlReadOptions {
25878                coerce_float: false,
25879                ..SqlReadOptions::default()
25880            },
25881        )
25882        .expect("read without coerce_float");
25883        assert_eq!(
25884            no_coerce.column("amount").unwrap().values(),
25885            &[
25886                Scalar::Utf8("12.50".to_owned()),
25887                Scalar::Utf8("-3.25".to_owned()),
25888            ],
25889        );
25890
25891        let coerced = read_sql_with_options(
25892            &conn,
25893            "SELECT amount, fee FROM payments ORDER BY id",
25894            &SqlReadOptions {
25895                coerce_float: true,
25896                ..SqlReadOptions::default()
25897            },
25898        )
25899        .expect("read with coerce_float");
25900
25901        let amount = coerced.column("amount").expect("amount");
25902        assert_eq!(amount.dtype(), DType::Float64);
25903        assert_eq!(
25904            amount.values(),
25905            &[Scalar::Float64(12.5), Scalar::Float64(-3.25)],
25906        );
25907
25908        let fee = coerced.column("fee").expect("fee");
25909        assert_eq!(fee.dtype(), DType::Float64);
25910        assert_eq!(fee.values()[0], Scalar::Float64(1234.5));
25911        assert!(matches!(fee.values()[1], Scalar::Null(NullKind::NaN)));
25912    }
25913
25914    #[cfg(feature = "sql-sqlite")]
25915    #[test]
25916    fn sql_read_coerce_float_leaves_non_numeric_text_columns_unchanged() {
25917        let conn = make_sql_test_conn();
25918        conn.execute_batch(
25919            "CREATE TABLE mixed (id INTEGER, maybe_amount TEXT, label TEXT);
25920             INSERT INTO mixed (id, maybe_amount, label) VALUES
25921                (1, '12.50', 'alpha'),
25922                (2, 'not numeric', '20.0');",
25923        )
25924        .expect("create mixed table");
25925
25926        let frame = read_sql_with_options(
25927            &conn,
25928            "SELECT maybe_amount, label FROM mixed ORDER BY id",
25929            &SqlReadOptions {
25930                coerce_float: true,
25931                dtype: None,
25932                schema: None,
25933                columns: None,
25934                index_col: None,
25935                ..SqlReadOptions::default()
25936            },
25937        )
25938        .expect("read with coerce_float");
25939
25940        assert_eq!(
25941            frame.column("maybe_amount").unwrap().values(),
25942            &[
25943                Scalar::Utf8("12.50".to_owned()),
25944                Scalar::Utf8("not numeric".to_owned()),
25945            ],
25946        );
25947        assert_eq!(
25948            frame.column("label").unwrap().values(),
25949            &[
25950                Scalar::Utf8("alpha".to_owned()),
25951                Scalar::Utf8("20.0".to_owned()),
25952            ],
25953        );
25954    }
25955
25956    #[cfg(feature = "sql-sqlite")]
25957    #[test]
25958    fn sql_read_chunks_batches_rows_and_resets_index_per_chunk() {
25959        let conn = make_sql_test_conn();
25960        conn.execute_batch(
25961            "CREATE TABLE chunked (id INTEGER, name TEXT);
25962             INSERT INTO chunked (id, name) VALUES
25963                (1, 'alpha'),
25964                (2, 'beta'),
25965                (3, 'gamma'),
25966                (4, 'delta'),
25967                (5, 'epsilon');",
25968        )
25969        .expect("create chunked table");
25970
25971        let chunks = read_sql_chunks(&conn, "SELECT id, name FROM chunked ORDER BY id", 2)
25972            .expect("chunk iterator")
25973            .collect::<Result<Vec<_>, _>>()
25974            .expect("all chunks");
25975
25976        assert_eq!(chunks.len(), 3);
25977        assert_eq!(
25978            chunks[0].index().labels(),
25979            &[IndexLabel::Int64(0), IndexLabel::Int64(1)]
25980        );
25981        assert_eq!(
25982            chunks[1].index().labels(),
25983            &[IndexLabel::Int64(0), IndexLabel::Int64(1)]
25984        );
25985        assert_eq!(chunks[2].index().labels(), &[IndexLabel::Int64(0)]);
25986        assert_eq!(
25987            chunks[0].column("id").unwrap().values(),
25988            &[Scalar::Int64(1), Scalar::Int64(2)]
25989        );
25990        assert_eq!(
25991            chunks[1].column("id").unwrap().values(),
25992            &[Scalar::Int64(3), Scalar::Int64(4)]
25993        );
25994        assert_eq!(
25995            chunks[2].column("name").unwrap().values(),
25996            &[Scalar::Utf8("epsilon".to_owned())]
25997        );
25998    }
25999
26000    #[cfg(feature = "sql-sqlite")]
26001    #[test]
26002    fn sql_read_chunks_sqlite_uses_paged_iterator_state() {
26003        let conn = make_sql_test_conn();
26004        conn.execute_batch(
26005            "CREATE TABLE fp_sqlite_paged_chunks (id INTEGER, name TEXT);
26006             INSERT INTO fp_sqlite_paged_chunks (id, name) VALUES
26007                (1, 'alpha'),
26008                (2, 'beta');",
26009        )
26010        .expect("create sqlite_paged_chunks table");
26011
26012        let mut chunks = read_sql_chunks(
26013            &conn,
26014            "SELECT id, name FROM fp_sqlite_paged_chunks ORDER BY id",
26015            1,
26016        )
26017        .expect("chunk iterator");
26018
26019        let initial_debug = format!("{chunks:?}");
26020        assert!(
26021            initial_debug.contains("mode: \"paged\""),
26022            "SQLite chunk reads must use paged mode, got {initial_debug}"
26023        );
26024        assert!(initial_debug.contains("next_offset: 0"));
26025
26026        let first = chunks
26027            .next()
26028            .expect("first chunk")
26029            .expect("first chunk should read");
26030        assert_eq!(first.column("id").unwrap().values(), &[Scalar::Int64(1)]);
26031
26032        let after_first_debug = format!("{chunks:?}");
26033        assert!(after_first_debug.contains("next_offset: 1"));
26034    }
26035
26036    #[cfg(feature = "sql-sqlite")]
26037    #[test]
26038    fn sql_read_chunks_with_options_applies_params_parse_dates_and_coerce_float() {
26039        let conn = make_sql_test_conn();
26040        conn.execute_batch(
26041            "CREATE TABLE events (ts TEXT, amount TEXT, keep INTEGER);
26042             INSERT INTO events (ts, amount, keep) VALUES
26043                ('2024-01-15', '12.50', 0),
26044                ('2024-02-01 05:06:07', '$1,234.50', 1),
26045                ('2024-03-03', '-3.25', 1);",
26046        )
26047        .expect("create events table");
26048
26049        let chunks = read_sql_chunks_with_options(
26050            &conn,
26051            "SELECT ts, amount FROM events WHERE keep = ? ORDER BY ts",
26052            &SqlReadOptions {
26053                params: Some(vec![Scalar::Int64(1)]),
26054                parse_dates: Some(vec!["ts".to_owned()]),
26055                coerce_float: true,
26056                dtype: None,
26057                schema: None,
26058                columns: None,
26059                index_col: None,
26060            },
26061            1,
26062        )
26063        .expect("chunk iterator")
26064        .collect::<Result<Vec<_>, _>>()
26065        .expect("all chunks");
26066
26067        assert_eq!(chunks.len(), 2);
26068        // parse_dates now yields typed Datetime64[ns] (br-frankenpandas-0ezw7).
26069        assert_eq!(
26070            chunks[0].column("ts").unwrap().values(),
26071            &[Scalar::Datetime64(1_706_763_967_000_000_000)]
26072        );
26073        assert_eq!(
26074            chunks[0].column("amount").unwrap().values(),
26075            &[Scalar::Float64(1234.5)]
26076        );
26077        assert_eq!(
26078            chunks[1].column("ts").unwrap().values(),
26079            &[Scalar::Datetime64(1_709_424_000_000_000_000)]
26080        );
26081        assert_eq!(
26082            chunks[1].column("amount").unwrap().values(),
26083            &[Scalar::Float64(-3.25)]
26084        );
26085    }
26086
26087    #[cfg(feature = "sql-sqlite")]
26088    #[test]
26089    fn sql_read_chunks_rejects_zero_chunksize() {
26090        let conn = make_sql_test_conn();
26091
26092        let err =
26093            read_sql_chunks(&conn, "SELECT 1", 0).expect_err("zero chunksize should be rejected");
26094
26095        assert!(matches!(err, IoError::Sql(msg) if msg.contains("chunksize")));
26096    }
26097
26098    #[cfg(feature = "sql-sqlite")]
26099    #[test]
26100    fn sql_duplicate_column_names_error() {
26101        let conn = make_sql_test_conn();
26102        let err = read_sql(&conn, "SELECT 1 as dup, 2 as dup");
26103        assert!(matches!(err, Err(IoError::DuplicateColumnName(name)) if name == "dup"));
26104    }
26105
26106    #[cfg(feature = "sql-sqlite")]
26107    #[test]
26108    fn sql_if_exists_fail() {
26109        let frame = make_test_dataframe();
26110        let conn = make_sql_test_conn();
26111        write_sql(&frame, &conn, "tbl", SqlIfExists::Fail).unwrap();
26112
26113        let err = write_sql(&frame, &conn, "tbl", SqlIfExists::Fail);
26114        assert!(err.is_err());
26115        assert!(matches!(&err.unwrap_err(), IoError::Sql(msg) if msg.contains("already exists")),);
26116    }
26117
26118    #[cfg(feature = "sql-sqlite")]
26119    #[test]
26120    fn sql_if_exists_replace() {
26121        let frame = make_test_dataframe();
26122        let conn = make_sql_test_conn();
26123        write_sql(&frame, &conn, "tbl", SqlIfExists::Fail).unwrap();
26124
26125        // Replace should succeed and overwrite.
26126        write_sql(&frame, &conn, "tbl", SqlIfExists::Replace).unwrap();
26127        let frame2 = read_sql_table(&conn, "tbl").unwrap();
26128        assert_eq!(frame2.index().len(), 3);
26129    }
26130
26131    #[cfg(feature = "sql-sqlite")]
26132    #[test]
26133    fn sql_if_exists_append() {
26134        let frame = make_test_dataframe();
26135        let conn = make_sql_test_conn();
26136        write_sql(&frame, &conn, "tbl", SqlIfExists::Fail).unwrap();
26137
26138        // Append should add rows.
26139        write_sql(&frame, &conn, "tbl", SqlIfExists::Append).unwrap();
26140        let frame2 = read_sql_table(&conn, "tbl").unwrap();
26141        assert_eq!(frame2.index().len(), 6); // 3 + 3
26142    }
26143
26144    #[cfg(feature = "sql-sqlite")]
26145    #[test]
26146    fn sql_with_nulls() {
26147        use fp_types::DType;
26148
26149        let mut columns = BTreeMap::new();
26150        columns.insert(
26151            "vals".to_string(),
26152            Column::new(
26153                DType::Float64,
26154                vec![
26155                    Scalar::Float64(1.0),
26156                    Scalar::Null(NullKind::NaN),
26157                    Scalar::Float64(3.0),
26158                ],
26159            )
26160            .unwrap(),
26161        );
26162
26163        let labels = vec![
26164            IndexLabel::Int64(0),
26165            IndexLabel::Int64(1),
26166            IndexLabel::Int64(2),
26167        ];
26168        let frame =
26169            DataFrame::new_with_column_order(Index::new(labels), columns, vec!["vals".to_string()])
26170                .unwrap();
26171
26172        let conn = make_sql_test_conn();
26173        write_sql(&frame, &conn, "nulltest", SqlIfExists::Fail).unwrap();
26174        let frame2 = read_sql_table(&conn, "nulltest").unwrap();
26175
26176        assert_eq!(
26177            frame2.column("vals").unwrap().values()[0],
26178            Scalar::Float64(1.0)
26179        );
26180        assert!(frame2.column("vals").unwrap().values()[1].is_missing());
26181        assert_eq!(
26182            frame2.column("vals").unwrap().values()[2],
26183            Scalar::Float64(3.0)
26184        );
26185    }
26186
26187    #[cfg(feature = "sql-sqlite")]
26188    #[test]
26189    fn sql_bool_roundtrip() {
26190        use fp_types::DType;
26191
26192        let mut columns = BTreeMap::new();
26193        columns.insert(
26194            "flags".to_string(),
26195            Column::new(
26196                DType::Bool,
26197                vec![Scalar::Bool(true), Scalar::Bool(false), Scalar::Bool(true)],
26198            )
26199            .unwrap(),
26200        );
26201
26202        let labels = vec![
26203            IndexLabel::Int64(0),
26204            IndexLabel::Int64(1),
26205            IndexLabel::Int64(2),
26206        ];
26207        let frame = DataFrame::new_with_column_order(
26208            Index::new(labels),
26209            columns,
26210            vec!["flags".to_string()],
26211        )
26212        .unwrap();
26213
26214        let conn = make_sql_test_conn();
26215        write_sql(&frame, &conn, "booltest", SqlIfExists::Fail).unwrap();
26216        let frame2 = read_sql_table(&conn, "booltest").unwrap();
26217
26218        // Bools stored as INTEGER(0/1), read back as Int64.
26219        assert_eq!(
26220            frame2.column("flags").unwrap().values()[0],
26221            Scalar::Int64(1)
26222        );
26223        assert_eq!(
26224            frame2.column("flags").unwrap().values()[1],
26225            Scalar::Int64(0)
26226        );
26227    }
26228
26229    #[cfg(feature = "sql-sqlite")]
26230    #[test]
26231    fn sql_invalid_table_name_rejected() {
26232        let conn = make_sql_test_conn();
26233        let err = read_sql_table(&conn, "Robert'; DROP TABLE students; --");
26234        assert!(err.is_err());
26235        assert!(
26236            matches!(&err.unwrap_err(), IoError::Sql(msg) if msg.contains("invalid table name")),
26237        );
26238    }
26239
26240    #[cfg(feature = "sql-sqlite")]
26241    #[test]
26242    fn sql_empty_table_name_rejected() {
26243        let conn = make_sql_test_conn();
26244        let err = read_sql_table(&conn, "");
26245        assert!(err.is_err());
26246        assert!(
26247            matches!(&err.unwrap_err(), IoError::Sql(msg) if msg.contains("invalid table name")),
26248        );
26249
26250        let frame = make_test_dataframe();
26251        let err = write_sql(&frame, &conn, "", SqlIfExists::Fail);
26252        assert!(err.is_err());
26253    }
26254
26255    #[cfg(feature = "sql-sqlite")]
26256    #[test]
26257    fn sql_empty_result() {
26258        let conn = make_sql_test_conn();
26259        conn.execute_batch("CREATE TABLE empty (x INTEGER, y TEXT)")
26260            .unwrap();
26261        let frame = read_sql_table(&conn, "empty").unwrap();
26262        assert_eq!(frame.index().len(), 0);
26263        assert_eq!(frame.column_names().len(), 2);
26264        assert_eq!(frame.column("x").unwrap().dtype(), DType::Int64);
26265        assert_eq!(frame.column("y").unwrap().dtype(), DType::Utf8);
26266
26267        conn.execute_batch(
26268            "CREATE TABLE typed_nulls (i INTEGER, r REAL, t TEXT);
26269             INSERT INTO typed_nulls VALUES (NULL, NULL, NULL);",
26270        )
26271        .unwrap();
26272        let null_frame = read_sql_table(&conn, "typed_nulls").unwrap();
26273        assert_eq!(null_frame.index().len(), 1);
26274        assert_eq!(null_frame.column("i").unwrap().dtype(), DType::Int64);
26275        assert_eq!(null_frame.column("r").unwrap().dtype(), DType::Float64);
26276        assert_eq!(null_frame.column("t").unwrap().dtype(), DType::Utf8);
26277    }
26278
26279    #[cfg(feature = "sql-sqlite")]
26280    #[test]
26281    fn sql_empty_filtered_query_preserves_declared_dtypes() {
26282        let conn = make_sql_test_conn();
26283        conn.execute_batch(
26284            "CREATE TABLE filtered_empty (i INTEGER, r REAL, t TEXT);
26285             INSERT INTO filtered_empty VALUES (1, 1.25, 'kept');",
26286        )
26287        .unwrap();
26288
26289        let frame = read_sql_with_options(
26290            &conn,
26291            "SELECT i, r, t FROM filtered_empty WHERE i > ?",
26292            &SqlReadOptions {
26293                params: Some(vec![Scalar::Int64(10)]),
26294                ..SqlReadOptions::default()
26295            },
26296        )
26297        .expect("empty filtered query must preserve cursor dtype hints");
26298
26299        assert_eq!(frame.index().len(), 0);
26300        assert_eq!(frame.column_names(), vec!["i", "r", "t"]);
26301        assert_eq!(frame.column("i").unwrap().dtype(), DType::Int64);
26302        assert_eq!(frame.column("r").unwrap().dtype(), DType::Float64);
26303        assert_eq!(frame.column("t").unwrap().dtype(), DType::Utf8);
26304    }
26305
26306    #[cfg(feature = "sql-sqlite")]
26307    #[test]
26308    fn sql_extension_trait() {
26309        let frame = make_test_dataframe();
26310        let conn = make_sql_test_conn();
26311
26312        // Use the extension trait method.
26313        use super::DataFrameIoExt;
26314        frame.to_sql(&conn, "ext_test", SqlIfExists::Fail).unwrap();
26315        frame
26316            .to_sql_with_options(
26317                &conn,
26318                "ext_test_options",
26319                &SqlWriteOptions {
26320                    if_exists: SqlIfExists::Fail,
26321                    index: false,
26322                    index_label: None,
26323                    schema: None,
26324                    dtype: None,
26325                    method: SqlInsertMethod::Single,
26326                    chunksize: None,
26327                },
26328            )
26329            .unwrap();
26330
26331        let frame2 = read_sql_table(&conn, "ext_test").unwrap();
26332        assert_eq!(frame2.index().len(), 3);
26333        let frame3 = read_sql_table(&conn, "ext_test_options").unwrap();
26334        assert_eq!(frame3.index().len(), 3);
26335    }
26336
26337    #[cfg(feature = "sql-sqlite")]
26338    #[test]
26339    fn series_sql_extension_aliases_roundtrip_to_single_column_table() {
26340        use super::SeriesIoExt;
26341
26342        let source = Series::from_values(
26343            "sales",
26344            vec!["r1".into(), "r2".into()],
26345            vec![Scalar::Int64(10), Scalar::Int64(12)],
26346        )
26347        .expect("source series");
26348
26349        let conn = make_sql_test_conn();
26350        source
26351            .to_sql(&conn, "series_ext", SqlIfExists::Fail)
26352            .expect("series to_sql");
26353        let roundtrip = read_sql_table(&conn, "series_ext").expect("read series table");
26354        assert_eq!(roundtrip.column_names(), vec!["index", "sales"]);
26355        assert_eq!(
26356            roundtrip.column("index").expect("index column").values(),
26357            &[Scalar::Utf8("r1".into()), Scalar::Utf8("r2".into())]
26358        );
26359        assert_eq!(
26360            roundtrip.column("sales").expect("sales column").values(),
26361            source.values()
26362        );
26363
26364        source
26365            .to_sql_with_options(
26366                &conn,
26367                "series_ext_no_index",
26368                &SqlWriteOptions {
26369                    if_exists: SqlIfExists::Fail,
26370                    index: false,
26371                    index_label: None,
26372                    schema: None,
26373                    dtype: None,
26374                    method: SqlInsertMethod::Single,
26375                    chunksize: None,
26376                },
26377            )
26378            .expect("series to_sql index false");
26379        let no_index =
26380            read_sql_table(&conn, "series_ext_no_index").expect("read no-index series table");
26381        assert_eq!(no_index.column_names(), vec!["sales"]);
26382        assert_eq!(
26383            no_index.column("sales").expect("sales column").values(),
26384            source.values()
26385        );
26386    }
26387
26388    // ── Arrow IPC / Feather tests ────────────────────────────────────
26389
26390    #[test]
26391    fn feather_bytes_roundtrip() {
26392        let frame = make_test_dataframe();
26393        let bytes = super::write_feather_bytes(&frame).expect("write feather");
26394        assert!(!bytes.is_empty());
26395
26396        let frame2 = super::read_feather_bytes(&bytes).expect("read feather");
26397        assert_eq!(frame2.index().len(), 3);
26398
26399        // Check all column values survive round-trip exactly.
26400        let ints = frame2.column("ints").unwrap();
26401        assert_eq!(ints.values()[0], Scalar::Int64(10));
26402        assert_eq!(ints.values()[1], Scalar::Int64(20));
26403        assert_eq!(ints.values()[2], Scalar::Int64(30));
26404
26405        let floats = frame2.column("floats").unwrap();
26406        assert_eq!(floats.values()[0], Scalar::Float64(1.5));
26407        assert_eq!(floats.values()[2], Scalar::Float64(3.5));
26408
26409        let names = frame2.column("names").unwrap();
26410        assert_eq!(names.values()[0], Scalar::Utf8("alice".into()));
26411        assert_eq!(names.values()[2], Scalar::Utf8("carol".into()));
26412    }
26413
26414    #[test]
26415    fn feather_row_multiindex_roundtrip_restores_logical_row_axis() {
26416        let frame = make_row_multiindex_test_dataframe();
26417        let bytes = super::write_feather_bytes(&frame).expect("write feather");
26418        let roundtrip = super::read_feather_bytes(&bytes).expect("read feather");
26419
26420        assert!(roundtrip.equals(&frame));
26421        assert!(roundtrip.column("__index_level_0__").is_none());
26422        assert_eq!(
26423            roundtrip
26424                .row_multiindex()
26425                .expect("row multiindex should be restored")
26426                .get_level_values(1)
26427                .unwrap()
26428                .labels(),
26429            frame
26430                .row_multiindex()
26431                .expect("source row multiindex")
26432                .get_level_values(1)
26433                .unwrap()
26434                .labels()
26435        );
26436    }
26437
26438    #[test]
26439    fn feather_file_roundtrip() {
26440        let frame = make_test_dataframe();
26441        let dir = std::env::temp_dir();
26442        let path = dir.join("fp_io_test_feather_roundtrip.feather");
26443
26444        super::write_feather(&frame, &path).expect("write feather file");
26445        let frame2 = super::read_feather(&path).expect("read feather file");
26446        assert_eq!(frame2.index().len(), 3);
26447        assert_eq!(
26448            frame2.column("ints").unwrap().values()[0],
26449            Scalar::Int64(10)
26450        );
26451        std::fs::remove_file(&path).ok();
26452    }
26453
26454    #[test]
26455    fn ipc_stream_bytes_roundtrip() {
26456        let frame = make_test_dataframe();
26457        let bytes = super::write_ipc_stream_bytes(&frame).expect("write ipc stream");
26458        assert!(!bytes.is_empty());
26459
26460        let frame2 = super::read_ipc_stream_bytes(&bytes).expect("read ipc stream");
26461        assert_eq!(frame2.index().len(), 3);
26462        assert_eq!(
26463            frame2.column("ints").unwrap().values()[1],
26464            Scalar::Int64(20)
26465        );
26466        assert_eq!(
26467            frame2.column("names").unwrap().values()[1],
26468            Scalar::Utf8("bob".into())
26469        );
26470    }
26471
26472    /// br-frankenpandas-13q8k: `Int64Nullable` / `BoolNullable` must survive the
26473    /// Arrow IPC round trip, and plain `Int64` / `Bool` must NOT be promoted.
26474    ///
26475    /// Arrow has one `Int64` and one `Boolean` — nullability is a validity
26476    /// bitmap, not a type — so `dtype_to_arrow` maps both FrankenPandas dtypes
26477    /// onto the same Arrow type and the reader had no way to tell them apart.
26478    /// `ipc_stream_round_trip_null_hardened` caught it as `actual=false
26479    /// expected=true` once the payload-dtype chooser started building the
26480    /// nullable flavour (br-frankenpandas-vprpg).
26481    ///
26482    /// The distinction is load-bearing, not cosmetic: it mirrors pandas' `int64`
26483    /// vs `Int64Dtype()`, which pandas itself treats as incompatible merge keys
26484    /// (br-frankenpandas-sopel).
26485    #[test]
26486    fn ipc_stream_roundtrip_preserves_declared_nullable_dtypes_13q8k() {
26487        use fp_types::{DType, NullKind};
26488
26489        let mut columns = BTreeMap::new();
26490        columns.insert(
26491            "nullable_ints".to_string(),
26492            Column::new(
26493                DType::Int64Nullable,
26494                vec![
26495                    Scalar::Int64(10),
26496                    Scalar::Null(NullKind::Null),
26497                    Scalar::Int64(30),
26498                ],
26499            )
26500            .unwrap(),
26501        );
26502        columns.insert(
26503            "nullable_bools".to_string(),
26504            Column::new(
26505                DType::BoolNullable,
26506                vec![
26507                    Scalar::Bool(true),
26508                    Scalar::Null(NullKind::Null),
26509                    Scalar::Bool(false),
26510                ],
26511            )
26512            .unwrap(),
26513        );
26514        // THE NEGATIVE CONTROL, and the reason this cannot be implemented as
26515        // "an int column with nulls reads back nullable": this column HAS a
26516        // null and is still plain Int64. A nulls-based heuristic promotes it
26517        // and fails here. Only the declared dtype may decide.
26518        columns.insert(
26519            "plain_ints_with_a_null".to_string(),
26520            Column::new(
26521                DType::Int64,
26522                vec![
26523                    Scalar::Int64(1),
26524                    Scalar::Null(NullKind::Null),
26525                    Scalar::Int64(3),
26526                ],
26527            )
26528            .unwrap(),
26529        );
26530        // The mirror control: declared nullable, but ALL VALID. A
26531        // promote-to-nullable-only implementation cannot retag this one,
26532        // because promotion is gated on the column actually having nulls.
26533        columns.insert(
26534            "nullable_ints_all_valid".to_string(),
26535            Column::new(
26536                DType::Int64Nullable,
26537                vec![Scalar::Int64(7), Scalar::Int64(8), Scalar::Int64(9)],
26538            )
26539            .unwrap(),
26540        );
26541
26542        let order = vec![
26543            "nullable_ints".to_string(),
26544            "nullable_bools".to_string(),
26545            "plain_ints_with_a_null".to_string(),
26546            "nullable_ints_all_valid".to_string(),
26547        ];
26548        let frame = DataFrame::new_with_column_order(
26549            Index::new_known_unique_int64_unit_range(0, 3),
26550            columns,
26551            order,
26552        )
26553        .unwrap();
26554
26555        let bytes = super::write_ipc_stream_bytes(&frame).expect("write ipc stream");
26556        let back = super::read_ipc_stream_bytes(&bytes).expect("read ipc stream");
26557
26558        assert_eq!(
26559            back.column("nullable_ints").unwrap().dtype(),
26560            DType::Int64Nullable,
26561            "a declared Int64Nullable column must not decay to Int64"
26562        );
26563        assert_eq!(
26564            back.column("nullable_bools").unwrap().dtype(),
26565            DType::BoolNullable
26566        );
26567        assert_eq!(
26568            back.column("plain_ints_with_a_null").unwrap().dtype(),
26569            DType::Int64,
26570            "a plain Int64 column must stay Int64 even though it carries a null"
26571        );
26572        assert_eq!(
26573            back.column("nullable_ints_all_valid").unwrap().dtype(),
26574            DType::Int64Nullable,
26575            "declared-nullable is a dtype, not an observation about the values"
26576        );
26577
26578        // The values still have to survive, in both flavours.
26579        let ints = back.column("nullable_ints").unwrap();
26580        assert_eq!(ints.values()[0], Scalar::Int64(10));
26581        assert!(ints.values()[1].is_missing());
26582        assert_eq!(ints.values()[2], Scalar::Int64(30));
26583        let bools = back.column("nullable_bools").unwrap();
26584        assert_eq!(bools.values()[0], Scalar::Bool(true));
26585        assert!(bools.values()[1].is_missing());
26586        assert_eq!(bools.values()[2], Scalar::Bool(false));
26587        let plain = back.column("plain_ints_with_a_null").unwrap();
26588        assert_eq!(plain.values()[0], Scalar::Int64(1));
26589        assert!(plain.values()[1].is_missing());
26590    }
26591
26592    /// The conformance fixture's own shape, end to end: this is what
26593    /// `ipc_stream_round_trip_null_hardened` executes, and it compares the frame
26594    /// against itself after the round trip rather than checking dtypes by hand.
26595    #[test]
26596    fn ipc_stream_roundtrip_of_a_nullable_int_frame_is_semantically_identical_13q8k() {
26597        use fp_types::{DType, NullKind};
26598
26599        let mut columns = BTreeMap::new();
26600        columns.insert(
26601            "ints".to_string(),
26602            Column::new(
26603                DType::Int64Nullable,
26604                vec![
26605                    Scalar::Int64(10),
26606                    Scalar::Null(NullKind::Null),
26607                    Scalar::Int64(30),
26608                    Scalar::Null(NullKind::Null),
26609                ],
26610            )
26611            .unwrap(),
26612        );
26613        columns.insert(
26614            "floats".to_string(),
26615            Column::new(
26616                DType::Float64,
26617                vec![
26618                    Scalar::Null(NullKind::NaN),
26619                    Scalar::Float64(2.5),
26620                    Scalar::Null(NullKind::NaN),
26621                    Scalar::Float64(4.5),
26622                ],
26623            )
26624            .unwrap(),
26625        );
26626        let frame = DataFrame::new_with_column_order(
26627            Index::new_known_unique_int64_unit_range(0, 4),
26628            columns,
26629            vec!["ints".to_string(), "floats".to_string()],
26630        )
26631        .unwrap();
26632
26633        let bytes = super::write_ipc_stream_bytes(&frame).expect("write ipc stream");
26634        let back = super::read_ipc_stream_bytes(&bytes).expect("read ipc stream");
26635
26636        assert_eq!(back.column_names(), frame.column_names());
26637        for name in frame.column_names() {
26638            let before = frame.column(name).unwrap();
26639            let after = back.column(name).unwrap();
26640            assert_eq!(after.dtype(), before.dtype(), "dtype drifted for {name}");
26641            assert_eq!(after.len(), before.len());
26642            for i in 0..before.len() {
26643                let (b, a) = (&before.values()[i], &after.values()[i]);
26644                if b.is_missing() {
26645                    assert!(a.is_missing(), "{name}[{i}] lost its missing marker");
26646                } else {
26647                    assert_eq!(a, b, "{name}[{i}] changed value");
26648                }
26649            }
26650        }
26651    }
26652
26653    #[test]
26654    fn ipc_stream_row_multiindex_roundtrip_restores_logical_row_axis() {
26655        let frame = make_row_multiindex_test_dataframe();
26656        let bytes = super::write_ipc_stream_bytes(&frame).expect("write ipc stream");
26657        let roundtrip = super::read_ipc_stream_bytes(&bytes).expect("read ipc stream");
26658
26659        assert!(roundtrip.equals(&frame));
26660        assert!(roundtrip.row_multiindex().is_some());
26661    }
26662
26663    #[test]
26664    fn feather_with_nulls() {
26665        use fp_types::DType;
26666
26667        let mut columns = BTreeMap::new();
26668        columns.insert(
26669            "vals".to_string(),
26670            Column::new(
26671                DType::Float64,
26672                vec![
26673                    Scalar::Float64(1.0),
26674                    Scalar::Null(NullKind::NaN),
26675                    Scalar::Float64(3.0),
26676                ],
26677            )
26678            .unwrap(),
26679        );
26680
26681        let labels = vec![
26682            IndexLabel::Int64(0),
26683            IndexLabel::Int64(1),
26684            IndexLabel::Int64(2),
26685        ];
26686        let frame =
26687            DataFrame::new_with_column_order(Index::new(labels), columns, vec!["vals".to_string()])
26688                .unwrap();
26689
26690        let bytes = super::write_feather_bytes(&frame).expect("write");
26691        let frame2 = super::read_feather_bytes(&bytes).expect("read");
26692
26693        assert_eq!(
26694            frame2.column("vals").unwrap().values()[0],
26695            Scalar::Float64(1.0)
26696        );
26697        assert!(frame2.column("vals").unwrap().values()[1].is_missing());
26698        assert_eq!(
26699            frame2.column("vals").unwrap().values()[2],
26700            Scalar::Float64(3.0)
26701        );
26702    }
26703
26704    #[test]
26705    fn feather_nullable_int_roundtrip_preserves_int_dtype() {
26706        use fp_types::DType;
26707
26708        let mut columns = BTreeMap::new();
26709        columns.insert(
26710            "vals".to_string(),
26711            Column::new(
26712                DType::Int64,
26713                vec![
26714                    Scalar::Int64(10),
26715                    Scalar::Null(NullKind::Null),
26716                    Scalar::Int64(30),
26717                ],
26718            )
26719            .unwrap(),
26720        );
26721
26722        let labels = vec![
26723            IndexLabel::Int64(0),
26724            IndexLabel::Int64(1),
26725            IndexLabel::Int64(2),
26726        ];
26727        let frame =
26728            DataFrame::new_with_column_order(Index::new(labels), columns, vec!["vals".to_string()])
26729                .unwrap();
26730
26731        let bytes = super::write_feather_bytes(&frame).expect("write");
26732        let frame2 = super::read_feather_bytes(&bytes).expect("read");
26733        let vals = frame2.column("vals").unwrap();
26734
26735        assert_eq!(vals.dtype(), DType::Int64);
26736        assert_eq!(vals.values()[0], Scalar::Int64(10));
26737        assert_eq!(vals.values()[1], Scalar::Null(NullKind::Null));
26738        assert_eq!(vals.values()[2], Scalar::Int64(30));
26739    }
26740
26741    #[test]
26742    fn series_arrow_array_nullable_int_roundtrip() {
26743        let series = Series::from_values(
26744            "vals",
26745            vec![
26746                IndexLabel::Utf8("r0".into()),
26747                IndexLabel::Utf8("r1".into()),
26748                IndexLabel::Utf8("r2".into()),
26749            ],
26750            vec![
26751                Scalar::Int64(10),
26752                Scalar::Null(NullKind::Null),
26753                Scalar::Int64(30),
26754            ],
26755        )
26756        .unwrap();
26757
26758        let (dt, arr) = super::series_to_arrow_array(&series).expect("arrow encode");
26759        assert_eq!(dt, ArrowDataType::Int64);
26760
26761        let typed = arr
26762            .as_any()
26763            .downcast_ref::<Int64Array>()
26764            .expect("int64 arrow array");
26765        assert_eq!(typed.value(0), 10);
26766        assert!(typed.is_null(1));
26767        assert_eq!(typed.value(2), 30);
26768
26769        let roundtrip = super::series_from_arrow_array(
26770            series.name(),
26771            series.index().labels().to_vec(),
26772            arr.as_ref(),
26773            &dt,
26774        )
26775        .expect("arrow decode");
26776
26777        assert_eq!(roundtrip.name(), "vals");
26778        assert_eq!(roundtrip.index().labels(), series.index().labels());
26779        assert_eq!(roundtrip.column().dtype(), DType::Int64);
26780        assert_eq!(roundtrip.values(), series.values());
26781    }
26782
26783    #[test]
26784    fn feather_bool_column() {
26785        use fp_types::DType;
26786
26787        let mut columns = BTreeMap::new();
26788        columns.insert(
26789            "flags".to_string(),
26790            Column::new(
26791                DType::Bool,
26792                vec![Scalar::Bool(true), Scalar::Bool(false), Scalar::Bool(true)],
26793            )
26794            .unwrap(),
26795        );
26796
26797        let labels = vec![
26798            IndexLabel::Int64(0),
26799            IndexLabel::Int64(1),
26800            IndexLabel::Int64(2),
26801        ];
26802        let frame = DataFrame::new_with_column_order(
26803            Index::new(labels),
26804            columns,
26805            vec!["flags".to_string()],
26806        )
26807        .unwrap();
26808
26809        let bytes = super::write_feather_bytes(&frame).expect("write");
26810        let frame2 = super::read_feather_bytes(&bytes).expect("read");
26811
26812        assert_eq!(
26813            frame2.column("flags").unwrap().values()[0],
26814            Scalar::Bool(true)
26815        );
26816        assert_eq!(
26817            frame2.column("flags").unwrap().values()[1],
26818            Scalar::Bool(false)
26819        );
26820    }
26821
26822    #[test]
26823    fn feather_preserves_column_order() {
26824        let frame = make_test_dataframe();
26825        let bytes = super::write_feather_bytes(&frame).expect("write");
26826        let frame2 = super::read_feather_bytes(&bytes).expect("read");
26827
26828        assert_eq!(
26829            frame2
26830                .column_names()
26831                .iter()
26832                .map(|s| s.as_str())
26833                .collect::<Vec<_>>(),
26834            frame
26835                .column_names()
26836                .iter()
26837                .map(|s| s.as_str())
26838                .collect::<Vec<_>>()
26839        );
26840    }
26841
26842    #[test]
26843    fn feather_extension_trait() {
26844        use super::DataFrameIoExt;
26845
26846        let frame = make_test_dataframe();
26847        let bytes = frame.to_feather_bytes().unwrap();
26848        let frame2 = super::read_feather_bytes(&bytes).unwrap();
26849        assert_eq!(frame2.index().len(), 3);
26850    }
26851
26852    // ── Adversarial parser tests (frankenpandas-yby) ─────────────────
26853
26854    // ── CsvReadOptions extended params tests (frankenpandas-qoz) ────
26855
26856    #[test]
26857    fn csv_nrows_limits_rows() {
26858        let input = "x\n1\n2\n3\n4\n5\n";
26859        let opts = CsvReadOptions {
26860            nrows: Some(3),
26861            ..Default::default()
26862        };
26863        let frame = read_csv_with_options(input, &opts).expect("parse");
26864        assert_eq!(frame.index().len(), 3);
26865        assert_eq!(frame.column("x").unwrap().values()[2], Scalar::Int64(3));
26866    }
26867
26868    #[test]
26869    fn csv_skiprows_skips_data_rows() {
26870        let input = "x\n1\n2\n3\n4\n5\n";
26871        let opts = CsvReadOptions {
26872            skiprows: 2,
26873            ..Default::default()
26874        };
26875        let frame = read_csv_with_options(input, &opts).expect("parse");
26876        assert_eq!(frame.index().len(), 3); // skipped header + first data row
26877        assert_eq!(frame.column("2").unwrap().values()[0], Scalar::Int64(3));
26878    }
26879
26880    #[test]
26881    fn csv_skiprows_and_nrows_combined() {
26882        let input = "x\n1\n2\n3\n4\n5\n";
26883        let opts = CsvReadOptions {
26884            skiprows: 1,
26885            nrows: Some(2),
26886            ..Default::default()
26887        };
26888        let frame = read_csv_with_options(input, &opts).expect("parse");
26889        assert_eq!(frame.index().len(), 2); // skipped header; read 2 data rows
26890        assert_eq!(frame.column("1").unwrap().values()[0], Scalar::Int64(2));
26891        assert_eq!(frame.column("1").unwrap().values()[1], Scalar::Int64(3));
26892    }
26893
26894    #[test]
26895    fn csv_usecols_selects_columns() {
26896        let input = "a,b,c\n1,2,3\n4,5,6\n";
26897        let opts = CsvReadOptions {
26898            usecols: Some(vec!["a".into(), "c".into()]),
26899            ..Default::default()
26900        };
26901        let frame = read_csv_with_options(input, &opts).expect("parse");
26902        assert_eq!(frame.column_names().len(), 2);
26903        assert!(frame.column("a").is_some());
26904        assert!(frame.column("b").is_none());
26905        assert!(frame.column("c").is_some());
26906        assert_eq!(frame.column("a").unwrap().values()[0], Scalar::Int64(1));
26907        assert_eq!(frame.column("c").unwrap().values()[1], Scalar::Int64(6));
26908    }
26909
26910    #[test]
26911    fn csv_usecols_nonexistent_column_errors() {
26912        let input = "a,b\n1,2\n";
26913        let opts = CsvReadOptions {
26914            usecols: Some(vec!["a".into(), "nonexistent".into()]),
26915            ..Default::default()
26916        };
26917        let err = read_csv_with_options(input, &opts).expect_err("missing usecols should error");
26918        assert!(matches!(err, IoError::MissingUsecols(_)));
26919    }
26920
26921    #[test]
26922    fn csv_dtype_coercion() {
26923        let input = "id,score\n1,95\n2,87\n3,42\n";
26924        let mut dtype_map = std::collections::HashMap::new();
26925        dtype_map.insert("score".to_owned(), fp_types::DType::Float64);
26926        let opts = CsvReadOptions {
26927            dtype: Some(dtype_map),
26928            ..Default::default()
26929        };
26930        let frame = read_csv_with_options(input, &opts).expect("parse");
26931        // score column should be Float64, not Int64
26932        assert_eq!(
26933            frame.column("score").unwrap().values()[0],
26934            Scalar::Float64(95.0)
26935        );
26936        assert_eq!(
26937            frame.column("score").unwrap().values()[1],
26938            Scalar::Float64(87.0)
26939        );
26940        assert_eq!(
26941            frame.column("score").unwrap().values()[2],
26942            Scalar::Float64(42.0)
26943        );
26944        // id column should remain Int64 (not in dtype map)
26945        assert_eq!(frame.column("id").unwrap().values()[0], Scalar::Int64(1));
26946    }
26947
26948    #[test]
26949    fn csv_dtype_str_uses_unquoted_field_content() {
26950        // The verbatim text taken for dtype=str is the *parsed* field, not the raw line
26951        // slice, so quoting is still removed and an embedded delimiter survives.
26952        let input = "a,b\n\"x,y\",2\n\"lead 007\",3\n";
26953        let mut dtype_map = std::collections::HashMap::new();
26954        dtype_map.insert("a".to_owned(), fp_types::DType::Utf8);
26955        let opts = CsvReadOptions {
26956            dtype: Some(dtype_map),
26957            ..Default::default()
26958        };
26959        let frame = read_csv_with_options(input, &opts).expect("parse");
26960        let a = frame.column("a").unwrap();
26961        assert_eq!(a.values()[0], Scalar::Utf8("x,y".to_owned()));
26962        assert_eq!(a.values()[1], Scalar::Utf8("lead 007".to_owned()));
26963    }
26964
26965    #[test]
26966    fn csv_dtype_str_preserves_source_text() {
26967        // pandas: read_csv(..., dtype=str) hands back the source text unchanged, so
26968        // leading zeros, bit-string labels, and the original numeric spelling survive.
26969        // Coercing the already-inferred scalar cannot do this: by then `007` is
26970        // `Int64(7)` and re-rendering yields "7", which silently merges `007` with `7`.
26971        let input = "cluster,regime,x\n007,00,0.50\n7,10,1e3\n";
26972        let mut dtype_map = std::collections::HashMap::new();
26973        for column in ["cluster", "regime", "x"] {
26974            dtype_map.insert(column.to_owned(), fp_types::DType::Utf8);
26975        }
26976        let opts = CsvReadOptions {
26977            dtype: Some(dtype_map),
26978            ..Default::default()
26979        };
26980        let frame = read_csv_with_options(input, &opts).expect("parse");
26981
26982        let cluster = frame.column("cluster").unwrap();
26983        assert_eq!(cluster.values()[0], Scalar::Utf8("007".to_owned()));
26984        assert_eq!(cluster.values()[1], Scalar::Utf8("7".to_owned()));
26985        assert_ne!(
26986            cluster.values()[0],
26987            cluster.values()[1],
26988            "007 and 7 are distinct labels and must not collapse"
26989        );
26990
26991        let regime = frame.column("regime").unwrap();
26992        assert_eq!(regime.values()[0], Scalar::Utf8("00".to_owned()));
26993        assert_eq!(regime.values()[1], Scalar::Utf8("10".to_owned()));
26994
26995        let x = frame.column("x").unwrap();
26996        assert_eq!(x.values()[0], Scalar::Utf8("0.50".to_owned()));
26997        assert_eq!(x.values()[1], Scalar::Utf8("1e3".to_owned()));
26998    }
26999
27000    #[test]
27001    fn csv_dtype_str_keeps_missing_cells_missing() {
27002        // pandas keeps NaN under dtype=str rather than materializing the NA marker text.
27003        let input = "id,label\n1,\n2,keep\n";
27004        let mut dtype_map = std::collections::HashMap::new();
27005        dtype_map.insert("label".to_owned(), fp_types::DType::Utf8);
27006        let opts = CsvReadOptions {
27007            dtype: Some(dtype_map),
27008            ..Default::default()
27009        };
27010        let frame = read_csv_with_options(input, &opts).expect("parse");
27011        let label = frame.column("label").unwrap();
27012        assert!(
27013            matches!(label.values()[0], Scalar::Null(_)),
27014            "an NA cell must stay null under dtype=str, got {:?}",
27015            label.values()[0]
27016        );
27017        assert_eq!(label.values()[1], Scalar::Utf8("keep".to_owned()));
27018    }
27019
27020    #[test]
27021    fn csv_dtype_coercion_invalid_value_errors() {
27022        let input = "id,score\n1,abc\n";
27023        let mut dtype_map = std::collections::HashMap::new();
27024        dtype_map.insert("score".to_owned(), fp_types::DType::Int64);
27025        let opts = CsvReadOptions {
27026            dtype: Some(dtype_map),
27027            ..Default::default()
27028        };
27029        let err = read_csv_with_options(input, &opts).expect_err("invalid cast must error");
27030        assert!(matches!(
27031            err,
27032            IoError::Column(fp_columnar::ColumnError::Type(
27033                fp_types::TypeError::InvalidCast { .. }
27034            ))
27035        ));
27036    }
27037
27038    #[test]
27039    fn csv_skiprows_beyond_data_errors() {
27040        let input = "x\n1\n2\n";
27041        let opts = CsvReadOptions {
27042            skiprows: 100,
27043            ..Default::default()
27044        };
27045        let err = read_csv_with_options(input, &opts).expect_err("skiprows removes header");
27046        assert!(matches!(err, IoError::MissingHeaders));
27047    }
27048
27049    #[test]
27050    fn csv_nrows_zero_returns_empty() {
27051        let input = "x\n1\n2\n3\n";
27052        let opts = CsvReadOptions {
27053            nrows: Some(0),
27054            ..Default::default()
27055        };
27056        let frame = read_csv_with_options(input, &opts).expect("parse");
27057        assert_eq!(frame.index().len(), 0);
27058    }
27059
27060    #[test]
27061    fn csv_decimal_comma_parses_quoted_float_fields() {
27062        let input = "price\n\"1,50\"\n\"3,75\"\n";
27063        let opts = CsvReadOptions {
27064            decimal: b',',
27065            ..Default::default()
27066        };
27067        let frame = read_csv_with_options(input, &opts).expect("parse");
27068        assert_eq!(
27069            frame.column("price").unwrap().values(),
27070            &[Scalar::Float64(1.5), Scalar::Float64(3.75)]
27071        );
27072    }
27073
27074    #[test]
27075    fn csv_default_decimal_keeps_comma_decimal_strings_as_utf8() {
27076        let input = "price\n\"1,50\"\n";
27077        let frame = read_csv_with_options(input, &CsvReadOptions::default()).expect("parse");
27078        assert_eq!(
27079            frame.column("price").unwrap().values(),
27080            &[Scalar::Utf8("1,50".to_owned())]
27081        );
27082    }
27083
27084    #[test]
27085    fn csv_true_false_values_do_not_override_numeric_inference() {
27086        let input = "flag\n1\n0\n";
27087        let opts = CsvReadOptions {
27088            true_values: vec!["1".to_owned()],
27089            false_values: vec!["0".to_owned()],
27090            ..Default::default()
27091        };
27092        let frame = read_csv_with_options(input, &opts).expect("parse");
27093        assert_eq!(
27094            frame.column("flag").unwrap().values(),
27095            &[Scalar::Int64(1), Scalar::Int64(0)]
27096        );
27097    }
27098
27099    #[test]
27100    fn csv_true_false_values_convert_non_numeric_tokens() {
27101        let input = "flag\nyes\nno\n";
27102        let opts = CsvReadOptions {
27103            true_values: vec!["yes".to_owned()],
27104            false_values: vec!["no".to_owned()],
27105            ..Default::default()
27106        };
27107        let frame = read_csv_with_options(input, &opts).expect("parse");
27108        assert_eq!(
27109            frame.column("flag").unwrap().values(),
27110            &[Scalar::Bool(true), Scalar::Bool(false)]
27111        );
27112    }
27113
27114    #[test]
27115    fn csv_default_parsing_keeps_numeric_boolean_tokens_as_ints() {
27116        let input = "flag\n1\n0\n";
27117        let frame = read_csv_with_options(input, &CsvReadOptions::default()).expect("parse");
27118        assert_eq!(
27119            frame.column("flag").unwrap().values(),
27120            &[Scalar::Int64(1), Scalar::Int64(0)]
27121        );
27122    }
27123
27124    #[test]
27125    fn csv_missing_numeric_column_promotes_int_to_float64() {
27126        // A numeric CSV field with an NA follows pandas' numpy-style widening.
27127        let input = "a,b,c\n,NA,NaN\n1,,x\n";
27128        let frame = read_csv_with_options(input, &CsvReadOptions::default()).expect("parse");
27129        assert_eq!(frame.column("a").unwrap().dtype(), DType::Float64);
27130        assert!(frame.column("a").unwrap().values()[0].is_missing());
27131        assert_eq!(frame.column("a").unwrap().values()[1], Scalar::Float64(1.0));
27132        assert!(frame.column("b").unwrap().values()[0].is_missing());
27133        assert!(frame.column("b").unwrap().values()[1].is_missing());
27134        assert_eq!(
27135            frame.column("c").unwrap().values(),
27136            &[Scalar::Null(NullKind::Null), Scalar::Utf8("x".to_owned())]
27137        );
27138    }
27139
27140    /// CORRECTED against live pandas 2.2.3. This test used to assert that both
27141    /// entries are "normalized to their pandas object-string form", on
27142    /// br-frankenpandas-unz0t's premise that pandas returns a Series of
27143    /// Timestamp objects here. It does not. When `parse_dates` cannot unify a
27144    /// column, pandas gives up on it ENTIRELY and the original text survives:
27145    /// ```text
27146    ///   csv = "ts,value\n2024-01-15 10:30:00,1\n2024-01-15T10:30:00Z,2\n"
27147    ///   pd.read_csv(StringIO(csv), parse_dates=['ts'])['ts']
27148    ///     dtype object
27149    ///     [(type(v).__name__, str(v)) ...]
27150    ///       -> [('str', '2024-01-15 10:30:00'), ('str', '2024-01-15T10:30:00Z')]
27151    /// ```
27152    /// Both are `str`, and the second keeps its `T` and its `Z`. FrankenPandas
27153    /// was rewriting it to `2024-01-15 10:30:00+00:00`.
27154    #[test]
27155    fn csv_parse_dates_mixed_naive_and_aware_leaves_the_column_untouched() {
27156        let input = "ts,value\n2024-01-15 10:30:00,1\n2024-01-15T10:30:00Z,2\n";
27157        let opts = CsvReadOptions {
27158            parse_dates: Some(vec!["ts".to_owned()]),
27159            ..Default::default()
27160        };
27161        let frame = read_csv_with_options(input, &opts).expect("parse");
27162        assert_eq!(
27163            frame.column("ts").unwrap().values(),
27164            &[
27165                Scalar::Utf8("2024-01-15 10:30:00".to_owned()),
27166                // Verbatim as it appeared in the CSV.
27167                Scalar::Utf8("2024-01-15T10:30:00Z".to_owned()),
27168            ]
27169        );
27170        assert_eq!(
27171            frame.column("value").unwrap().values(),
27172            &[Scalar::Int64(1), Scalar::Int64(2)]
27173        );
27174    }
27175
27176    /// The control that bounds the pass-through above: a column that CAN be
27177    /// unified must still parse. unz0t's original premise was true of this
27178    /// shape — all values tz-aware with DIFFERING offsets — which pandas really
27179    /// does turn into Timestamp objects, rendered with a space:
27180    /// ```text
27181    ///   "2024-01-15T10:30:00+01:00" / "2024-01-15T10:30:00+02:00"
27182    ///     -> [('Timestamp', '2024-01-15 10:30:00+01:00'),
27183    ///         ('Timestamp', '2024-01-15 10:30:00+02:00')]
27184    ///   all-naive       -> dtype datetime64[ns]
27185    ///   all-same-offset -> dtype datetime64[ns, UTC]
27186    /// ```
27187    /// An all-aware column never reaches the mixed-timezone branch, because
27188    /// that branch requires BOTH a naive and an aware value.
27189    #[test]
27190    fn csv_parse_dates_all_aware_mixed_offsets_still_parses() {
27191        let input = "ts,value\n2024-01-15T10:30:00+01:00,1\n2024-01-15T10:30:00+02:00,2\n";
27192        let opts = CsvReadOptions {
27193            parse_dates: Some(vec!["ts".to_owned()]),
27194            ..Default::default()
27195        };
27196        let frame = read_csv_with_options(input, &opts).expect("parse");
27197        let values = frame.column("ts").unwrap().values().to_vec();
27198        assert!(
27199            values
27200                .iter()
27201                .all(|v| !matches!(v, Scalar::Utf8(s) if s.contains('T'))),
27202            "an all-aware column must still be parsed, not passed through: {values:?}"
27203        );
27204    }
27205
27206    #[test]
27207    fn csv_parse_dates_fixed_naive_fast_path_accepts_only_safe_domain() {
27208        let values = vec![
27209            Scalar::Utf8("2024-01-15 10:30:00".to_owned()),
27210            Scalar::Utf8("2024-02-29".to_owned()),
27211            Scalar::Null(NullKind::NaT),
27212        ];
27213        let parsed = super::parse_csv_fixed_naive_datetime_values(&values).expect("fixed parse");
27214        assert_eq!(
27215            parsed,
27216            vec![
27217                Scalar::Datetime64(1_705_314_600_000_000_000),
27218                Scalar::Datetime64(1_709_164_800_000_000_000),
27219                Scalar::Datetime64(Timestamp::NAT),
27220            ]
27221        );
27222
27223        for rejected in [
27224            "2024-01-15T10:30:00Z",
27225            "2024-02-30",
27226            "2024-01-15 10:30:00.123",
27227        ] {
27228            assert!(
27229                super::parse_csv_fixed_naive_datetime_values(&[Scalar::Utf8(rejected.to_owned())])
27230                    .is_none(),
27231                "{rejected:?} must use the general parse_dates path"
27232            );
27233        }
27234    }
27235
27236    #[test]
27237    fn csv_parse_dates_raw_fast_path_preserves_na_semantics() {
27238        let input = "ts,value\nMISSING,1\n2024-01-15 10:30:00,2\n";
27239        let opts = CsvReadOptions {
27240            parse_dates: Some(vec!["ts".to_owned()]),
27241            na_values: vec!["MISSING".to_owned()],
27242            ..Default::default()
27243        };
27244        let frame = read_csv_with_options(input, &opts).expect("parse");
27245        assert_eq!(
27246            frame.column("ts").unwrap().values(),
27247            &[
27248                Scalar::Datetime64(Timestamp::NAT),
27249                Scalar::Datetime64(1_705_314_600_000_000_000),
27250            ]
27251        );
27252        assert_eq!(
27253            frame.column("value").unwrap().values(),
27254            &[Scalar::Int64(1), Scalar::Int64(2)]
27255        );
27256    }
27257
27258    #[test]
27259    fn csv_parse_dates_deferred_fallback_replays_scalar_inference() {
27260        let input = "ts,value\n2024-01-15 10:30:00,1\nnot-a-date,2\n";
27261        let opts = CsvReadOptions {
27262            parse_dates: Some(vec!["ts".to_owned()]),
27263            ..Default::default()
27264        };
27265        let frame = read_csv_with_options(input, &opts).expect("parse");
27266        assert_eq!(
27267            frame.column("ts").unwrap().values(),
27268            &[
27269                Scalar::Utf8("2024-01-15 10:30:00".to_owned()),
27270                Scalar::Utf8("not-a-date".to_owned()),
27271            ]
27272        );
27273
27274        let keep_na_literal = CsvReadOptions {
27275            parse_dates: Some(vec!["ts".to_owned()]),
27276            keep_default_na: false,
27277            ..Default::default()
27278        };
27279        let frame = read_csv_with_options("ts\nNA\n2024-01-15\n", &keep_na_literal).expect("parse");
27280        assert_eq!(
27281            frame.column("ts").unwrap().values(),
27282            &[
27283                Scalar::Utf8("NA".to_owned()),
27284                Scalar::Utf8("2024-01-15".to_owned()),
27285            ]
27286        );
27287    }
27288
27289    #[test]
27290    fn csv_parse_dates_deferred_mask_tracks_usecols_and_headerless() {
27291        let input = "2024-01-15 10:30:00,10\n2024-01-16 11:45:30,20\n";
27292        let opts = CsvReadOptions {
27293            has_headers: false,
27294            parse_dates: Some(vec!["column_0".to_owned()]),
27295            usecols: Some(vec!["column_0".to_owned()]),
27296            ..Default::default()
27297        };
27298        let frame = read_csv_with_options(input, &opts).expect("parse");
27299        assert_eq!(frame.column_names(), vec!["column_0"]);
27300        assert_eq!(
27301            frame.column("column_0").unwrap().values(),
27302            &[
27303                Scalar::Datetime64(1_705_314_600_000_000_000),
27304                Scalar::Datetime64(1_705_405_530_000_000_000),
27305            ]
27306        );
27307    }
27308
27309    #[test]
27310    fn csv_parse_dates_combined_columns_replaces_source_columns() {
27311        let input = "date,time,value\n2024-01-15,10:30:00,1\n2024-01-16,11:45:30,2\n";
27312        let opts = CsvReadOptions {
27313            parse_date_combinations: Some(vec![vec!["date".to_owned(), "time".to_owned()]]),
27314            ..Default::default()
27315        };
27316        let frame = read_csv_with_options(input, &opts).expect("parse");
27317        assert_eq!(frame.column_names(), vec!["date_time", "value"]);
27318        assert_eq!(
27319            frame.column("date_time").unwrap().values(),
27320            &[
27321                Scalar::Datetime64(1_705_314_600_000_000_000),
27322                Scalar::Datetime64(1_705_405_530_000_000_000),
27323            ]
27324        );
27325        assert!(frame.column("date").is_none());
27326        assert!(frame.column("time").is_none());
27327        assert_eq!(
27328            frame.column("value").unwrap().values(),
27329            &[Scalar::Int64(1), Scalar::Int64(2)]
27330        );
27331    }
27332
27333    #[test]
27334    fn csv_parse_date_combinations_named_uses_caller_supplied_name() {
27335        let input = "date,time,value\n2024-01-15,10:30:00,1\n2024-01-16,11:45:30,2\n";
27336        let opts = CsvReadOptions {
27337            parse_date_combinations_named: Some(vec![(
27338                "timestamp".to_owned(),
27339                vec!["date".to_owned(), "time".to_owned()],
27340            )]),
27341            ..Default::default()
27342        };
27343        let frame = read_csv_with_options(input, &opts).expect("parse");
27344        // Dict-style rename: combined column named "timestamp" rather than
27345        // the default underscore-joined "date_time".
27346        assert_eq!(frame.column_names(), vec!["timestamp", "value"]);
27347        assert!(frame.column("date").is_none());
27348        assert!(frame.column("time").is_none());
27349        assert_eq!(
27350            frame.column("timestamp").unwrap().values(),
27351            &[
27352                Scalar::Datetime64(1_705_314_600_000_000_000),
27353                Scalar::Datetime64(1_705_405_530_000_000_000),
27354            ]
27355        );
27356    }
27357
27358    #[test]
27359    fn csv_parse_date_combinations_named_multiple_groups() {
27360        let input = "d1,t1,d2,t2,value\n2024-01-01,09:00:00,2024-01-01,17:00:00,10\n2024-02-01,09:00:00,2024-02-01,17:00:00,20\n";
27361        let opts = CsvReadOptions {
27362            parse_date_combinations_named: Some(vec![
27363                ("start".to_owned(), vec!["d1".to_owned(), "t1".to_owned()]),
27364                ("end".to_owned(), vec!["d2".to_owned(), "t2".to_owned()]),
27365            ]),
27366            ..Default::default()
27367        };
27368        let frame = read_csv_with_options(input, &opts).expect("parse");
27369        let names = frame.column_names();
27370        assert!(names.iter().any(|n| n.as_str() == "start"));
27371        assert!(names.iter().any(|n| n.as_str() == "end"));
27372        assert!(!names.iter().any(|n| n.as_str() == "d1"));
27373        assert!(!names.iter().any(|n| n.as_str() == "t2"));
27374        assert_eq!(
27375            frame.column("value").unwrap().values(),
27376            &[Scalar::Int64(10), Scalar::Int64(20)]
27377        );
27378        assert_eq!(
27379            frame.column("start").unwrap().values(),
27380            &[
27381                Scalar::Datetime64(1_704_099_600_000_000_000),
27382                Scalar::Datetime64(1_706_778_000_000_000_000),
27383            ]
27384        );
27385    }
27386
27387    #[test]
27388    fn csv_parse_date_combinations_named_rejects_duplicate_output_names() {
27389        let input = "a,b,c,d\n2024,01,2024,02\n";
27390        let opts = CsvReadOptions {
27391            parse_date_combinations_named: Some(vec![
27392                ("ts".to_owned(), vec!["a".to_owned(), "b".to_owned()]),
27393                ("ts".to_owned(), vec!["c".to_owned(), "d".to_owned()]),
27394            ]),
27395            ..Default::default()
27396        };
27397        let err = read_csv_with_options(input, &opts).unwrap_err();
27398        assert!(matches!(err, IoError::DuplicateColumnName(name) if name == "ts"));
27399    }
27400
27401    #[test]
27402    fn csv_parse_date_combinations_named_rejects_missing_source_column() {
27403        let input = "date,time,value\n2024-01-01,09:00:00,1\n";
27404        let opts = CsvReadOptions {
27405            parse_date_combinations_named: Some(vec![(
27406                "ts".to_owned(),
27407                vec!["date".to_owned(), "missing".to_owned()],
27408            )]),
27409            ..Default::default()
27410        };
27411        let err = read_csv_with_options(input, &opts).unwrap_err();
27412        assert!(matches!(err, IoError::MissingParseDateColumns(_)));
27413    }
27414
27415    #[test]
27416    fn csv_parse_date_combinations_named_empty_sources_skipped() {
27417        let input = "a,b\n1,2\n";
27418        let opts = CsvReadOptions {
27419            parse_date_combinations_named: Some(vec![("unused".to_owned(), Vec::new())]),
27420            ..Default::default()
27421        };
27422        let frame = read_csv_with_options(input, &opts).expect("parse");
27423        // Empty source list is a no-op; original columns remain.
27424        assert_eq!(frame.column_names(), vec!["a", "b"]);
27425    }
27426
27427    // ── JSONL tests (frankenpandas-sue) ──────────────────────────────
27428
27429    #[test]
27430    fn jsonl_write_read_roundtrip() {
27431        let frame = make_test_dataframe();
27432        let jsonl = super::write_jsonl_string(&frame).expect("JSONL write failed");
27433
27434        // Each line should be a valid JSON object.
27435        let line_count = jsonl.lines().count();
27436        assert_eq!(line_count, 3, "3 rows = 3 lines");
27437
27438        let back = super::read_jsonl_str(&jsonl).expect("JSONL read failed");
27439        assert_eq!(back.index().len(), 3);
27440        assert_eq!(back.column("ints").unwrap().values()[0], Scalar::Int64(10));
27441        assert_eq!(
27442            back.column("names").unwrap().values()[2],
27443            Scalar::Utf8("carol".into())
27444        );
27445    }
27446
27447    #[test]
27448    fn jsonl_preserves_column_order() {
27449        let input = r#"
27450{"b":1,"a":2}
27451{"c":3}
27452"#;
27453        let frame = super::read_jsonl_str(input).expect("JSONL read failed");
27454        let order: Vec<&str> = frame
27455            .column_names()
27456            .iter()
27457            .map(|name| name.as_str())
27458            .collect();
27459        assert_eq!(order, vec!["b", "a", "c"]);
27460    }
27461
27462    #[test]
27463    fn jsonl_each_line_is_valid_json() {
27464        let frame = make_test_dataframe();
27465        let jsonl = super::write_jsonl_string(&frame).unwrap();
27466
27467        for (i, line) in jsonl.lines().enumerate() {
27468            let parsed: serde_json::Value =
27469                serde_json::from_str(line).expect("jsonl line must be valid JSON");
27470            assert!(parsed.is_object(), "line {i} must be a JSON object");
27471        }
27472    }
27473
27474    #[test]
27475    fn jsonl_with_nulls() {
27476        use fp_types::DType;
27477
27478        let mut columns = BTreeMap::new();
27479        columns.insert(
27480            "v".to_string(),
27481            Column::new(
27482                DType::Float64,
27483                vec![
27484                    Scalar::Float64(1.0),
27485                    Scalar::Null(NullKind::NaN),
27486                    Scalar::Float64(3.0),
27487                ],
27488            )
27489            .unwrap(),
27490        );
27491        let labels = vec![
27492            IndexLabel::Int64(0),
27493            IndexLabel::Int64(1),
27494            IndexLabel::Int64(2),
27495        ];
27496        let frame =
27497            DataFrame::new_with_column_order(Index::new(labels), columns, vec!["v".to_string()])
27498                .unwrap();
27499
27500        let jsonl = super::write_jsonl_string(&frame).unwrap();
27501        let back = super::read_jsonl_str(&jsonl).unwrap();
27502        assert!(back.column("v").unwrap().values()[1].is_missing());
27503    }
27504
27505    #[test]
27506    fn jsonl_records_write_preserves_nullable_int_column() {
27507        // DISC-011: Nullable extension Int64 dtype parity - Int64 preserved, not promoted to Float64.
27508        let frame = DataFrame::from_dict(
27509            &["a"],
27510            vec![("a", vec![Scalar::Int64(1), Scalar::Null(NullKind::Null)])],
27511        )
27512        .unwrap();
27513
27514        let jsonl = super::write_jsonl_string(&frame).expect("write jsonl");
27515        let rows = jsonl
27516            .lines()
27517            .map(|line| serde_json::from_str::<serde_json::Value>(line).unwrap())
27518            .collect::<Vec<_>>();
27519
27520        assert_eq!(
27521            rows,
27522            vec![serde_json::json!({"a": 1}), serde_json::json!({"a": null})]
27523        );
27524    }
27525
27526    #[test]
27527    fn jsonl_empty_input() {
27528        let back = super::read_jsonl_str("").expect("empty JSONL must parse");
27529        assert_eq!(back.index().len(), 0);
27530    }
27531
27532    #[test]
27533    fn jsonl_blank_lines_skipped() {
27534        let input = "{\"a\":1}\n\n{\"a\":2}\n\n";
27535        let back = super::read_jsonl_str(input).expect("JSONL with blanks must parse");
27536        assert_eq!(back.index().len(), 2);
27537    }
27538
27539    #[test]
27540    fn jsonl_non_object_line_errors() {
27541        let input = "{\"a\":1}\n[1,2,3]\n";
27542        let err = super::read_jsonl_str(input);
27543        assert!(err.is_err());
27544    }
27545
27546    #[test]
27547    fn jsonl_different_keys_across_rows() {
27548        // Rows with different keys should produce union of all columns.
27549        let input = "{\"a\":1,\"b\":2}\n{\"a\":3,\"c\":4}\n";
27550        let frame = super::read_jsonl_str(input).expect("JSONL with different keys must parse");
27551        assert_eq!(frame.index().len(), 2);
27552        // Should have columns a, b, c (union of all keys).
27553        assert!(frame.column("a").is_some(), "column a must exist");
27554        assert!(frame.column("b").is_some(), "column b must exist");
27555        assert!(frame.column("c").is_some(), "column c must exist");
27556        // Row 0: a=1, b=2, c=null.
27557        assert_eq!(frame.column("a").unwrap().values()[0], Scalar::Int64(1));
27558        assert_eq!(frame.column("b").unwrap().values()[0], Scalar::Float64(2.0));
27559        assert!(frame.column("c").unwrap().values()[0].is_missing());
27560        // Row 1: a=3, b=null, c=4.
27561        assert_eq!(frame.column("a").unwrap().values()[1], Scalar::Int64(3));
27562        assert!(frame.column("b").unwrap().values()[1].is_missing());
27563        assert_eq!(frame.column("c").unwrap().values()[1], Scalar::Float64(4.0));
27564    }
27565
27566    #[test]
27567    fn adversarial_csv_very_long_field() {
27568        // A single field with >100K characters should parse without panic.
27569        let long_val = "x".repeat(200_000);
27570        let input = format!("col\n{long_val}\n");
27571        let frame = read_csv_str(&input).expect("long field must parse");
27572        assert_eq!(frame.index().len(), 1);
27573        match &frame.column("col").unwrap().values()[0] {
27574            Scalar::Utf8(s) => assert_eq!(s.len(), 200_000),
27575            other => assert!(
27576                matches!(other, Scalar::Utf8(_)),
27577                "expected Utf8 for long field"
27578            ),
27579        }
27580    }
27581
27582    #[test]
27583    fn adversarial_csv_many_columns() {
27584        // CSV with 1000 columns should parse correctly.
27585        let ncols = 1000;
27586        let headers: Vec<String> = (0..ncols).map(|i| format!("c{i}")).collect();
27587        let mut csv = headers.join(",");
27588        csv.push('\n');
27589        let vals: Vec<String> = (0..ncols).map(|i| i.to_string()).collect();
27590        csv.push_str(&vals.join(","));
27591        csv.push('\n');
27592
27593        let frame = read_csv_str(&csv).expect("1000-column CSV must parse");
27594        assert_eq!(frame.columns().len(), ncols);
27595        assert_eq!(frame.index().len(), 1);
27596    }
27597
27598    #[test]
27599    fn adversarial_csv_empty_rows() {
27600        // CSV with empty rows between data should handle gracefully.
27601        // The csv crate skips truly empty records, but rows with the right
27602        // number of empty fields produce null values.
27603        let input = "a,b\n1,2\n,\n3,4\n";
27604        let frame = read_csv_str(input).expect("parse");
27605        assert_eq!(frame.index().len(), 3);
27606        // Row 1 (index 1) has empty fields → null
27607        assert!(frame.column("a").unwrap().values()[1].is_missing());
27608    }
27609
27610    #[test]
27611    fn adversarial_csv_field_with_newlines_in_quotes() {
27612        // Embedded newlines in quoted fields must not break row boundaries.
27613        let input = "msg\n\"line1\nline2\nline3\"\n\"single\"\n";
27614        let frame = read_csv_str(input).expect("quoted newlines must parse");
27615        assert_eq!(frame.index().len(), 2);
27616    }
27617
27618    #[test]
27619    fn adversarial_csv_header_only_no_data() {
27620        let input = "x,y,z\n";
27621        let frame = read_csv_str(input).expect("header-only must parse");
27622        assert_eq!(frame.index().len(), 0);
27623        assert_eq!(frame.columns().len(), 3);
27624    }
27625
27626    #[test]
27627    fn adversarial_json_deeply_nested_values() {
27628        // JSON with nested objects as values should store them as strings.
27629        let input = r#"[{"a":1,"b":{"nested":"value"}}]"#;
27630        let frame = read_json_str(input, JsonOrient::Records).expect("nested JSON must parse");
27631        assert_eq!(frame.index().len(), 1);
27632        // The nested object becomes a Utf8 representation.
27633        let b_val = &frame.column("b").unwrap().values()[0];
27634        assert!(matches!(b_val, Scalar::Utf8(_)));
27635    }
27636
27637    #[test]
27638    fn adversarial_json_i64_max_value() {
27639        // JSON with values at i64 boundary.
27640        let input = format!(r#"[{{"v":{}}}]"#, i64::MAX);
27641        let frame = read_json_str(&input, JsonOrient::Records).expect("i64::MAX must parse");
27642        assert_eq!(
27643            frame.column("v").unwrap().values()[0],
27644            Scalar::Int64(i64::MAX)
27645        );
27646    }
27647
27648    #[test]
27649    fn adversarial_json_i64_min_value() {
27650        let input = format!(r#"[{{"v":{}}}]"#, i64::MIN);
27651        let frame = read_json_str(&input, JsonOrient::Records).expect("i64::MIN must parse");
27652        assert_eq!(
27653            frame.column("v").unwrap().values()[0],
27654            Scalar::Int64(i64::MIN)
27655        );
27656    }
27657
27658    #[test]
27659    fn adversarial_json_float_special_values() {
27660        // JSON doesn't natively support Infinity/NaN, but we should handle
27661        // null gracefully.
27662        let input = r#"[{"v":null},{"v":1.7976931348623157e+308}]"#;
27663        let frame = read_json_str(input, JsonOrient::Records).expect("special floats must parse");
27664        assert!(frame.column("v").unwrap().values()[0].is_missing());
27665        // f64::MAX is approximately 1.7976931348623157e+308
27666        if let Scalar::Float64(v) = frame.column("v").unwrap().values()[1] {
27667            assert!(v.is_finite());
27668        }
27669    }
27670
27671    #[test]
27672    fn adversarial_json_empty_records_array() {
27673        let input = r#"[]"#;
27674        let frame = read_json_str(input, JsonOrient::Records).expect("empty array must parse");
27675        assert_eq!(frame.index().len(), 0);
27676    }
27677
27678    #[test]
27679    fn adversarial_json_empty_columns_object() {
27680        let input = r#"{}"#;
27681        let frame = read_json_str(input, JsonOrient::Columns).expect("empty object must parse");
27682        assert_eq!(frame.index().len(), 0);
27683        assert_eq!(frame.columns().len(), 0);
27684    }
27685
27686    #[test]
27687    fn adversarial_csv_unicode_values() {
27688        // CSV with multi-byte UTF-8 characters in values.
27689        let input = "name,emoji\n日本語,🎉\nрусский,🚀\n";
27690        let frame = read_csv_str(input).expect("unicode CSV must parse");
27691        assert_eq!(frame.index().len(), 2);
27692        assert_eq!(
27693            frame.column("name").unwrap().values()[0],
27694            Scalar::Utf8("日本語".into())
27695        );
27696        assert_eq!(
27697            frame.column("emoji").unwrap().values()[1],
27698            Scalar::Utf8("🚀".into())
27699        );
27700    }
27701
27702    #[test]
27703    fn adversarial_csv_single_column_no_trailing_newline() {
27704        let input = "val\n42";
27705        let frame = read_csv_str(input).expect("no trailing newline must parse");
27706        assert_eq!(frame.index().len(), 1);
27707        assert_eq!(frame.column("val").unwrap().values()[0], Scalar::Int64(42));
27708    }
27709
27710    #[cfg(feature = "sql-sqlite")]
27711    #[test]
27712    fn adversarial_sql_large_batch_insert() {
27713        // Insert 10K rows in a single write_sql call.
27714        let n = 10_000;
27715        let vals: Vec<Scalar> = (0..n).map(|i| Scalar::Int64(i as i64)).collect();
27716        let df = fp_frame::DataFrame::from_dict(&["x"], vec![("x", vals)]).unwrap();
27717
27718        let conn = make_sql_test_conn();
27719        write_sql(&df, &conn, "big_table", SqlIfExists::Fail).unwrap();
27720        let back = read_sql_table(&conn, "big_table").unwrap();
27721        assert_eq!(back.index().len(), n);
27722        assert_eq!(
27723            back.column("x").unwrap().values()[n - 1],
27724            Scalar::Int64((n - 1) as i64)
27725        );
27726    }
27727
27728    #[cfg(feature = "sql-sqlite")]
27729    #[test]
27730    fn adversarial_sql_column_name_with_spaces_accepted() {
27731        // Column names with spaces are valid in SQL (quoted identifiers).
27732        // Table names are restricted, but column names go through quoting.
27733        let df = fp_frame::DataFrame::from_dict(
27734            &["has space"],
27735            vec![("has space", vec![Scalar::Int64(1)])],
27736        )
27737        .unwrap();
27738
27739        let conn = make_sql_test_conn();
27740        // This should work since column names are quoted.
27741        let result = write_sql(&df, &conn, "test_spaces", SqlIfExists::Fail);
27742        assert!(
27743            result.is_ok(),
27744            "columns with spaces should work: {:?}",
27745            result.err()
27746        );
27747
27748        let back = read_sql_table(&conn, "test_spaces").unwrap();
27749        assert!(back.column("has space").is_some());
27750    }
27751
27752    #[cfg(feature = "sql-sqlite")]
27753    #[test]
27754    fn adversarial_sql_column_name_with_quotes_accepted() {
27755        let col_name = "has\"quote";
27756        let df =
27757            fp_frame::DataFrame::from_dict(&[col_name], vec![(col_name, vec![Scalar::Int64(7)])])
27758                .unwrap();
27759
27760        let conn = make_sql_test_conn();
27761        let result = write_sql(&df, &conn, "test_quotes", SqlIfExists::Fail);
27762        assert!(
27763            result.is_ok(),
27764            "columns with quotes should work: {:?}",
27765            result.err()
27766        );
27767
27768        let back = read_sql_table(&conn, "test_quotes").unwrap();
27769        assert_eq!(back.column(col_name).unwrap().values()[0], Scalar::Int64(7));
27770    }
27771
27772    // ── SqlConnection capability + dialect probes (br-frankenpandas-6dtf) ────
27773
27774    #[cfg(feature = "sql-sqlite")]
27775    #[test]
27776    fn rusqlite_dialect_name_is_sqlite() {
27777        let conn = make_sql_test_conn();
27778        assert_eq!(super::SqlConnection::dialect_name(&conn), "sqlite");
27779    }
27780
27781    #[cfg(feature = "sql-sqlite")]
27782    #[test]
27783    fn rusqlite_supports_returning_is_true() {
27784        // Bundled SQLite is 3.35+, so RETURNING is supported.
27785        let conn = make_sql_test_conn();
27786        assert!(super::SqlConnection::supports_returning(&conn));
27787    }
27788
27789    #[cfg(feature = "sql-sqlite")]
27790    #[test]
27791    fn rusqlite_max_param_count_is_32766() {
27792        let conn = make_sql_test_conn();
27793        assert_eq!(super::SqlConnection::max_param_count(&conn), Some(32766));
27794    }
27795
27796    #[cfg(feature = "sql-sqlite")]
27797    #[test]
27798    fn rusqlite_with_transaction_commits_on_ok() {
27799        let conn = make_sql_test_conn();
27800        super::SqlConnection::execute_batch(&conn, "CREATE TABLE txn_test (x INTEGER)").unwrap();
27801        let result: Result<i64, IoError> = super::SqlConnection::with_transaction(&conn, |c| {
27802            super::SqlConnection::execute_batch(c, "INSERT INTO txn_test VALUES (42)")?;
27803            Ok(42)
27804        });
27805        assert_eq!(result.unwrap(), 42);
27806        // Verify the row committed.
27807        let row_count =
27808            super::SqlConnection::query(&conn, "SELECT COUNT(*) FROM txn_test", &[]).unwrap();
27809        assert_eq!(row_count.rows.len(), 1);
27810        assert_eq!(row_count.rows[0][0], Scalar::Int64(1));
27811    }
27812
27813    #[cfg(feature = "sql-sqlite")]
27814    #[test]
27815    fn rusqlite_with_transaction_rolls_back_on_err() {
27816        let conn = make_sql_test_conn();
27817        super::SqlConnection::execute_batch(&conn, "CREATE TABLE txn_rollback (x INTEGER)")
27818            .unwrap();
27819        let result: Result<(), IoError> = super::SqlConnection::with_transaction(&conn, |c| {
27820            super::SqlConnection::execute_batch(c, "INSERT INTO txn_rollback VALUES (99)")?;
27821            Err(IoError::Sql("simulated failure".to_string()))
27822        });
27823        assert!(result.is_err());
27824        // Row should NOT have committed.
27825        let row_count =
27826            super::SqlConnection::query(&conn, "SELECT COUNT(*) FROM txn_rollback", &[]).unwrap();
27827        assert_eq!(row_count.rows[0][0], Scalar::Int64(0));
27828    }
27829
27830    #[cfg(feature = "sql-sqlite")]
27831    #[test]
27832    fn rusqlite_with_transaction_rolls_back_on_panic() {
27833        let conn = make_sql_test_conn();
27834        super::SqlConnection::execute_batch(&conn, "CREATE TABLE txn_panic (x INTEGER)").unwrap();
27835
27836        let panic_result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
27837            let _: Result<(), IoError> = super::SqlConnection::with_transaction(&conn, |c| {
27838                super::SqlConnection::execute_batch(c, "INSERT INTO txn_panic VALUES (99)")?;
27839                std::panic::resume_unwind(Box::new("simulated transaction panic"));
27840            });
27841        }));
27842        assert!(panic_result.is_err());
27843
27844        let row_count =
27845            super::SqlConnection::query(&conn, "SELECT COUNT(*) FROM txn_panic", &[]).unwrap();
27846        assert_eq!(row_count.rows[0][0], Scalar::Int64(0));
27847
27848        let result: Result<(), IoError> = super::SqlConnection::with_transaction(&conn, |c| {
27849            super::SqlConnection::execute_batch(c, "INSERT INTO txn_panic VALUES (7)")
27850        });
27851        assert!(result.is_ok());
27852        let rows =
27853            super::SqlConnection::query(&conn, "SELECT x FROM txn_panic ORDER BY x", &[]).unwrap();
27854        assert_eq!(rows.rows, vec![vec![Scalar::Int64(7)]]);
27855    }
27856
27857    #[test]
27858    fn default_capability_probes_are_conservative() {
27859        // A test-double SqlConnection that doesn't override defaults
27860        // should report the conservative-default values from the trait.
27861        struct StubSql;
27862        impl super::SqlConnection for StubSql {
27863            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<super::SqlQueryResult, IoError> {
27864                Ok(super::SqlQueryResult {
27865                    columns: vec![],
27866                    rows: vec![],
27867                })
27868            }
27869            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
27870                Ok(())
27871            }
27872            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
27873                Ok(false)
27874            }
27875            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
27876                Ok(())
27877            }
27878            fn dtype_sql(&self, _dtype: DType) -> &'static str {
27879                "TEXT"
27880            }
27881            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
27882                "TEXT"
27883            }
27884        }
27885
27886        let stub = StubSql;
27887        assert_eq!(super::SqlConnection::dialect_name(&stub), "unknown");
27888        assert!(!super::SqlConnection::supports_returning(&stub));
27889        assert_eq!(super::SqlConnection::max_param_count(&stub), None);
27890        // Default with_transaction passes through (no BEGIN/COMMIT).
27891        let result: Result<i64, IoError> = super::SqlConnection::with_transaction(&stub, |_| Ok(7));
27892        assert_eq!(result.unwrap(), 7);
27893        // Default quote_identifier produces ANSI double-quotes.
27894        assert_eq!(
27895            super::SqlConnection::quote_identifier(&stub, "col").unwrap(),
27896            r#""col""#
27897        );
27898    }
27899
27900    // ── quote_identifier tests (br-frankenpandas-2y7w / fd90.10) ────────
27901
27902    #[cfg(feature = "sql-sqlite")]
27903    #[test]
27904    fn rusqlite_quote_identifier_uses_ansi_double_quotes() {
27905        let conn = make_sql_test_conn();
27906        assert_eq!(
27907            super::SqlConnection::quote_identifier(&conn, "users").unwrap(),
27908            r#""users""#
27909        );
27910    }
27911
27912    #[cfg(feature = "sql-sqlite")]
27913    #[test]
27914    fn rusqlite_quote_identifier_doubles_embedded_quotes() {
27915        let conn = make_sql_test_conn();
27916        // Identifier containing a `"` must be escaped by doubling the quote.
27917        assert_eq!(
27918            super::SqlConnection::quote_identifier(&conn, r#"value"raw"#).unwrap(),
27919            r#""value""raw""#
27920        );
27921    }
27922
27923    #[cfg(feature = "sql-sqlite")]
27924    #[test]
27925    fn rusqlite_quote_identifier_rejects_null_bytes() {
27926        let conn = make_sql_test_conn();
27927        let err = super::SqlConnection::quote_identifier(&conn, "evil\0name").expect_err("nul");
27928        assert!(matches!(err, IoError::Sql(_)));
27929    }
27930
27931    #[test]
27932    fn default_quote_identifier_doubles_embedded_quotes() {
27933        // Verify the default impl on a non-overriding stub matches the
27934        // SQLite behavior (ANSI is the shared default for SQLite + Postgres).
27935        struct StubSql;
27936        impl super::SqlConnection for StubSql {
27937            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<super::SqlQueryResult, IoError> {
27938                Ok(super::SqlQueryResult {
27939                    columns: vec![],
27940                    rows: vec![],
27941                })
27942            }
27943            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
27944                Ok(())
27945            }
27946            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
27947                Ok(false)
27948            }
27949            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
27950                Ok(())
27951            }
27952            fn dtype_sql(&self, _dtype: DType) -> &'static str {
27953                "TEXT"
27954            }
27955            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
27956                "TEXT"
27957            }
27958        }
27959        let stub = StubSql;
27960        assert_eq!(
27961            super::SqlConnection::quote_identifier(&stub, r#"value"raw"#).unwrap(),
27962            r#""value""raw""#
27963        );
27964        assert!(super::SqlConnection::quote_identifier(&stub, "evil\0").is_err());
27965    }
27966
27967    // ── SqlReadOptions::dtype tests (br-frankenpandas-l9pt / fd90.11) ───
27968
27969    #[cfg(feature = "sql-sqlite")]
27970    #[test]
27971    fn read_sql_dtype_override_int_to_float() {
27972        let conn = make_sql_test_conn();
27973        super::SqlConnection::execute_batch(
27974            &conn,
27975            "CREATE TABLE amounts (amount INTEGER); INSERT INTO amounts VALUES (1), (2), (3);",
27976        )
27977        .unwrap();
27978        let mut dtype_map = BTreeMap::new();
27979        dtype_map.insert("amount".to_owned(), DType::Float64);
27980        let frame = read_sql_with_options(
27981            &conn,
27982            "SELECT amount FROM amounts ORDER BY amount",
27983            &SqlReadOptions {
27984                params: None,
27985                parse_dates: None,
27986                coerce_float: false,
27987                dtype: Some(dtype_map),
27988                schema: None,
27989                columns: None,
27990                index_col: None,
27991            },
27992        )
27993        .expect("read with dtype");
27994        let col = frame.column("amount").expect("amount");
27995        assert_eq!(col.dtype(), DType::Float64);
27996        assert_eq!(col.values()[0], Scalar::Float64(1.0));
27997        assert_eq!(col.values()[2], Scalar::Float64(3.0));
27998    }
27999
28000    #[cfg(feature = "sql-sqlite")]
28001    #[test]
28002    fn read_sql_dtype_override_unsupported_cast_returns_typed_error() {
28003        // This test asserts that when a dtype override cast is unsupported,
28004        // SQL IO surfaces a typed IoError::Sql with diagnostic context, NOT a
28005        // panic and not a silent skip.
28006        let conn = make_sql_test_conn();
28007        super::SqlConnection::execute_batch(
28008            &conn,
28009            "CREATE TABLE labels (id TEXT); INSERT INTO labels VALUES ('yes'), ('no');",
28010        )
28011        .unwrap();
28012        let mut dtype_map = BTreeMap::new();
28013        dtype_map.insert("id".to_owned(), DType::Bool);
28014        let err = read_sql_with_options(
28015            &conn,
28016            "SELECT id FROM labels ORDER BY id",
28017            &SqlReadOptions {
28018                params: None,
28019                parse_dates: None,
28020                coerce_float: false,
28021                dtype: Some(dtype_map),
28022                schema: None,
28023                columns: None,
28024                index_col: None,
28025            },
28026        )
28027        .expect_err("expected dtype override error");
28028        match err {
28029            IoError::Sql(message) => {
28030                assert!(
28031                    message.contains("dtype override on column 'id'"),
28032                    "unexpected error message: {message}"
28033                );
28034                assert!(
28035                    message.contains("Bool"),
28036                    "unexpected error message: {message}"
28037                );
28038            }
28039            other => unreachable!("expected IoError::Sql, got {other:?}"),
28040        }
28041    }
28042
28043    #[cfg(feature = "sql-sqlite")]
28044    #[test]
28045    fn read_sql_dtype_override_missing_column_is_ignored() {
28046        let conn = make_sql_test_conn();
28047        super::SqlConnection::execute_batch(
28048            &conn,
28049            "CREATE TABLE t (x INTEGER); INSERT INTO t VALUES (1);",
28050        )
28051        .unwrap();
28052        let mut dtype_map = BTreeMap::new();
28053        dtype_map.insert("nonexistent".to_owned(), DType::Float64);
28054        let frame = read_sql_with_options(
28055            &conn,
28056            "SELECT x FROM t",
28057            &SqlReadOptions {
28058                params: None,
28059                parse_dates: None,
28060                coerce_float: false,
28061                dtype: Some(dtype_map),
28062                schema: None,
28063                columns: None,
28064                index_col: None,
28065            },
28066        )
28067        .expect("read with dtype-on-missing-col");
28068        let col = frame.column("x").expect("x");
28069        assert_eq!(col.dtype(), DType::Int64);
28070    }
28071
28072    #[cfg(feature = "sql-sqlite")]
28073    #[test]
28074    fn read_sql_dtype_override_preserves_nulls() {
28075        let conn = make_sql_test_conn();
28076        super::SqlConnection::execute_batch(
28077            &conn,
28078            "CREATE TABLE nulls_tbl (v INTEGER); INSERT INTO nulls_tbl VALUES (1), (NULL), (3);",
28079        )
28080        .unwrap();
28081        let mut dtype_map = BTreeMap::new();
28082        dtype_map.insert("v".to_owned(), DType::Float64);
28083        let frame = read_sql_with_options(
28084            &conn,
28085            "SELECT v FROM nulls_tbl ORDER BY rowid",
28086            &SqlReadOptions {
28087                params: None,
28088                parse_dates: None,
28089                coerce_float: false,
28090                dtype: Some(dtype_map),
28091                schema: None,
28092                columns: None,
28093                index_col: None,
28094            },
28095        )
28096        .expect("read with dtype + nulls");
28097        let col = frame.column("v").expect("v");
28098        assert_eq!(col.dtype(), DType::Float64);
28099        assert!(col.values()[1].is_missing());
28100    }
28101
28102    #[cfg(feature = "sql-sqlite")]
28103    #[test]
28104    fn read_sql_dtype_skipped_when_column_in_parse_dates() {
28105        let conn = make_sql_test_conn();
28106        super::SqlConnection::execute_batch(
28107            &conn,
28108            "CREATE TABLE evt (ts TEXT); INSERT INTO evt VALUES ('2024-01-01 00:00:00');",
28109        )
28110        .unwrap();
28111        let mut dtype_map = BTreeMap::new();
28112        dtype_map.insert("ts".to_owned(), DType::Float64);
28113        let frame = read_sql_with_options(
28114            &conn,
28115            "SELECT ts FROM evt",
28116            &SqlReadOptions {
28117                params: None,
28118                parse_dates: Some(vec!["ts".to_owned()]),
28119                coerce_float: false,
28120                dtype: Some(dtype_map),
28121                schema: None,
28122                columns: None,
28123                index_col: None,
28124            },
28125        )
28126        .expect("read with parse_dates priority");
28127        let col = frame.column("ts").expect("ts");
28128        // parse_dates wins over the dtype override and yields typed
28129        // Datetime64[ns] (br-frankenpandas-0ezw7).
28130        assert_eq!(col.dtype(), DType::datetime64_naive());
28131    }
28132
28133    // ── Schema probes (br-frankenpandas-6dk9 / fd90.13) ─────────────────
28134
28135    #[cfg(feature = "sql-sqlite")]
28136    #[test]
28137    fn rusqlite_does_not_support_schemas_by_default() {
28138        let conn = make_sql_test_conn();
28139        assert!(!super::SqlConnection::supports_schemas(&conn));
28140        assert_eq!(super::SqlConnection::default_schema(&conn), None);
28141    }
28142
28143    #[test]
28144    fn default_schema_probes_are_conservative() {
28145        // A test-double with no schema overrides reports the conservative
28146        // single-namespace defaults (matches SQLite + most embedded
28147        // backends). Production multi-schema backends (PG, MySQL) override.
28148        struct StubSql;
28149        impl super::SqlConnection for StubSql {
28150            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<super::SqlQueryResult, IoError> {
28151                Ok(super::SqlQueryResult {
28152                    columns: vec![],
28153                    rows: vec![],
28154                })
28155            }
28156            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
28157                Ok(())
28158            }
28159            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
28160                Ok(false)
28161            }
28162            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
28163                Ok(())
28164            }
28165            fn dtype_sql(&self, _dtype: DType) -> &'static str {
28166                "TEXT"
28167            }
28168            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
28169                "TEXT"
28170            }
28171        }
28172        let stub = StubSql;
28173        assert!(!super::SqlConnection::supports_schemas(&stub));
28174        assert_eq!(super::SqlConnection::default_schema(&stub), None);
28175    }
28176
28177    #[test]
28178    fn schema_probe_overrides_take_effect() {
28179        // A multi-schema-style test backend (e.g. simulating PostgreSQL)
28180        // overrides supports_schemas + default_schema. The overrides MUST
28181        // win over the trait defaults.
28182        struct PgLikeSqlConn;
28183        impl super::SqlConnection for PgLikeSqlConn {
28184            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<super::SqlQueryResult, IoError> {
28185                Ok(super::SqlQueryResult {
28186                    columns: vec![],
28187                    rows: vec![],
28188                })
28189            }
28190            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
28191                Ok(())
28192            }
28193            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
28194                Ok(false)
28195            }
28196            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
28197                Ok(())
28198            }
28199            fn dtype_sql(&self, _dtype: DType) -> &'static str {
28200                "TEXT"
28201            }
28202            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
28203                "TEXT"
28204            }
28205            fn supports_schemas(&self) -> bool {
28206                true
28207            }
28208            fn default_schema(&self) -> Option<String> {
28209                Some("public".to_owned())
28210            }
28211        }
28212        let conn = PgLikeSqlConn;
28213        assert!(super::SqlConnection::supports_schemas(&conn));
28214        assert_eq!(
28215            super::SqlConnection::default_schema(&conn).as_deref(),
28216            Some("public")
28217        );
28218    }
28219
28220    // ── SqlReadOptions::schema tests (br-frankenpandas-u6zn / fd90.14) ──
28221
28222    #[test]
28223    fn sql_select_all_query_no_schema_uses_bare_table() {
28224        struct StubSql;
28225        impl super::SqlConnection for StubSql {
28226            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<super::SqlQueryResult, IoError> {
28227                Ok(super::SqlQueryResult {
28228                    columns: vec![],
28229                    rows: vec![],
28230                })
28231            }
28232            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
28233                Ok(())
28234            }
28235            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
28236                Ok(false)
28237            }
28238            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
28239                Ok(())
28240            }
28241            fn dtype_sql(&self, _dtype: DType) -> &'static str {
28242                "TEXT"
28243            }
28244            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
28245                "TEXT"
28246            }
28247        }
28248        let conn = StubSql;
28249        let q1 = super::sql_select_all_query_in_schema(&conn, "users", None).expect("q1");
28250        assert_eq!(q1, "SELECT * FROM \"users\"");
28251    }
28252
28253    #[test]
28254    fn sql_select_query_with_schema_rejects_non_schema_backend() {
28255        struct StubSql;
28256        impl super::SqlConnection for StubSql {
28257            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<super::SqlQueryResult, IoError> {
28258                Ok(super::SqlQueryResult {
28259                    columns: vec![],
28260                    rows: vec![],
28261                })
28262            }
28263            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
28264                Ok(())
28265            }
28266            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
28267                Ok(false)
28268            }
28269            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
28270                Ok(())
28271            }
28272            fn dtype_sql(&self, _dtype: DType) -> &'static str {
28273                "TEXT"
28274            }
28275            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
28276                "TEXT"
28277            }
28278            fn dialect_name(&self) -> &'static str {
28279                "stub"
28280            }
28281        }
28282        let conn = StubSql;
28283        let err = super::sql_select_all_query_in_schema(&conn, "users", Some("analytics"))
28284            .expect_err("schema must reject when backend has no schema support");
28285        assert!(
28286            matches!(err, IoError::Sql(msg) if msg.contains("schema is not supported by stub backend"))
28287        );
28288
28289        let err =
28290            super::sql_select_columns_query_in_schema(&conn, "users", Some("analytics"), &["id"])
28291                .expect_err("projected schema select must reject too");
28292        assert!(
28293            matches!(err, IoError::Sql(msg) if msg.contains("schema is not supported by stub backend"))
28294        );
28295    }
28296
28297    #[test]
28298    fn sql_select_all_query_with_schema_qualifies_on_multi_schema_backend() {
28299        struct PgLikeSchemaSql;
28300        impl super::SqlConnection for PgLikeSchemaSql {
28301            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<super::SqlQueryResult, IoError> {
28302                Ok(super::SqlQueryResult {
28303                    columns: vec![],
28304                    rows: vec![],
28305                })
28306            }
28307            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
28308                Ok(())
28309            }
28310            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
28311                Ok(false)
28312            }
28313            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
28314                Ok(())
28315            }
28316            fn dtype_sql(&self, _dtype: DType) -> &'static str {
28317                "TEXT"
28318            }
28319            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
28320                "TEXT"
28321            }
28322            fn supports_schemas(&self) -> bool {
28323                true
28324            }
28325        }
28326        let conn = PgLikeSchemaSql;
28327        let q =
28328            super::sql_select_all_query_in_schema(&conn, "users", Some("analytics")).expect("q");
28329        assert_eq!(q, "SELECT * FROM \"analytics\".\"users\"");
28330        let bare = super::sql_select_all_query_in_schema(&conn, "users", None).expect("bare");
28331        assert_eq!(bare, "SELECT * FROM \"users\"");
28332    }
28333
28334    #[cfg(feature = "sql-sqlite")]
28335    #[test]
28336    fn read_sql_table_with_options_schema_rejected_on_sqlite() {
28337        let conn = make_sql_test_conn();
28338        super::SqlConnection::execute_batch(
28339            &conn,
28340            "CREATE TABLE bare_tbl (x INTEGER); INSERT INTO bare_tbl VALUES (1), (2);",
28341        )
28342        .unwrap();
28343        let err = read_sql_table_with_options(
28344            &conn,
28345            "bare_tbl",
28346            &SqlReadOptions {
28347                params: None,
28348                parse_dates: None,
28349                coerce_float: false,
28350                dtype: None,
28351                schema: Some("ignored_on_sqlite".to_owned()),
28352                columns: None,
28353                index_col: None,
28354            },
28355        )
28356        .expect_err("read_sql_table schema=Some must reject on SQLite");
28357        assert!(
28358            matches!(err, IoError::Sql(msg) if msg.contains("schema is not supported by sqlite backend"))
28359        );
28360    }
28361
28362    #[cfg(feature = "sql-sqlite")]
28363    #[test]
28364    fn read_sql_table_chunks_with_options_schema_rejected_on_sqlite() {
28365        let conn = make_sql_test_conn();
28366        super::SqlConnection::execute_batch(
28367            &conn,
28368            "CREATE TABLE chunk_bare_tbl (x INTEGER); INSERT INTO chunk_bare_tbl VALUES (1), (2);",
28369        )
28370        .unwrap();
28371        let err = read_sql_table_chunks_with_options(
28372            &conn,
28373            "chunk_bare_tbl",
28374            &SqlReadOptions {
28375                schema: Some("ignored_on_sqlite".to_owned()),
28376                ..Default::default()
28377            },
28378            1,
28379        )
28380        .expect_err("chunked read_sql_table schema=Some must reject on SQLite");
28381        assert!(
28382            matches!(err, IoError::Sql(msg) if msg.contains("schema is not supported by sqlite backend"))
28383        );
28384    }
28385
28386    #[test]
28387    fn sql_select_all_query_in_schema_validates_schema_name() {
28388        struct PgLikeValidate;
28389        impl super::SqlConnection for PgLikeValidate {
28390            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<super::SqlQueryResult, IoError> {
28391                Ok(super::SqlQueryResult {
28392                    columns: vec![],
28393                    rows: vec![],
28394                })
28395            }
28396            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
28397                Ok(())
28398            }
28399            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
28400                Ok(false)
28401            }
28402            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
28403                Ok(())
28404            }
28405            fn dtype_sql(&self, _dtype: DType) -> &'static str {
28406                "TEXT"
28407            }
28408            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
28409                "TEXT"
28410            }
28411            fn supports_schemas(&self) -> bool {
28412                true
28413            }
28414        }
28415        let conn = PgLikeValidate;
28416        let err = super::sql_select_all_query_in_schema(&conn, "users", Some("evil; DROP"))
28417            .expect_err("malformed schema must reject");
28418        // Per fd90.56: error message now correctly identifies the
28419        // bad identifier as a schema, not a table.
28420        assert!(matches!(err, IoError::Sql(msg) if msg.contains("invalid schema name")));
28421    }
28422
28423    // ── SqlWriteOptions::schema tests (br-frankenpandas-udn6 / fd90.15) ─
28424
28425    #[test]
28426    fn sql_create_table_query_in_schema_qualifies_on_multi_schema_backend() {
28427        struct PgLikeWrite;
28428        impl super::SqlConnection for PgLikeWrite {
28429            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<super::SqlQueryResult, IoError> {
28430                Ok(super::SqlQueryResult {
28431                    columns: vec![],
28432                    rows: vec![],
28433                })
28434            }
28435            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
28436                Ok(())
28437            }
28438            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
28439                Ok(false)
28440            }
28441            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
28442                Ok(())
28443            }
28444            fn dtype_sql(&self, _dtype: DType) -> &'static str {
28445                "TEXT"
28446            }
28447            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
28448                "TEXT"
28449            }
28450            fn supports_schemas(&self) -> bool {
28451                true
28452            }
28453        }
28454        let conn = PgLikeWrite;
28455        let cols = vec!["id INTEGER".to_owned(), "name TEXT".to_owned()];
28456        let q = super::sql_create_table_query_in_schema(&conn, "users", Some("analytics"), &cols)
28457            .expect("create");
28458        assert_eq!(
28459            q,
28460            "CREATE TABLE IF NOT EXISTS \"analytics\".\"users\" (id INTEGER, name TEXT)"
28461        );
28462        let bare =
28463            super::sql_create_table_query_in_schema(&conn, "users", None, &cols).expect("bare");
28464        assert_eq!(
28465            bare,
28466            "CREATE TABLE IF NOT EXISTS \"users\" (id INTEGER, name TEXT)"
28467        );
28468    }
28469
28470    #[test]
28471    fn sql_insert_rows_query_in_schema_qualifies_on_multi_schema_backend() {
28472        struct PgLikeInsert;
28473        impl super::SqlConnection for PgLikeInsert {
28474            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<super::SqlQueryResult, IoError> {
28475                Ok(super::SqlQueryResult {
28476                    columns: vec![],
28477                    rows: vec![],
28478                })
28479            }
28480            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
28481                Ok(())
28482            }
28483            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
28484                Ok(false)
28485            }
28486            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
28487                Ok(())
28488            }
28489            fn dtype_sql(&self, _dtype: DType) -> &'static str {
28490                "TEXT"
28491            }
28492            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
28493                "TEXT"
28494            }
28495            fn supports_schemas(&self) -> bool {
28496                true
28497            }
28498        }
28499        let conn = PgLikeInsert;
28500        let cols = vec!["id".to_owned(), "name".to_owned()];
28501        let q = super::sql_insert_rows_query_in_schema(&conn, "users", Some("analytics"), &cols)
28502            .expect("insert");
28503        assert_eq!(
28504            q,
28505            "INSERT INTO \"analytics\".\"users\" (\"id\", \"name\") VALUES (?, ?)"
28506        );
28507    }
28508
28509    #[cfg(feature = "sql-sqlite")]
28510    #[test]
28511    fn write_sql_with_options_schema_silently_ignored_on_sqlite() {
28512        let conn = make_sql_test_conn();
28513        let frame = fp_frame::DataFrame::from_dict(
28514            &["x"],
28515            vec![("x", vec![Scalar::Int64(1), Scalar::Int64(2)])],
28516        )
28517        .unwrap();
28518        // SQLite reports supports_schemas=false; passing schema=Some(s) must
28519        // not break the write — the bare table reference is used.
28520        write_sql_with_options(
28521            &frame,
28522            &conn,
28523            "bare_write_tbl",
28524            &SqlWriteOptions {
28525                if_exists: SqlIfExists::Fail,
28526                index: false,
28527                index_label: None,
28528                schema: Some("ignored_on_sqlite".to_owned()),
28529                dtype: None,
28530                method: SqlInsertMethod::Single,
28531                chunksize: None,
28532            },
28533        )
28534        .expect("write with schema=Some on SQLite");
28535        let back = read_sql_table(&conn, "bare_write_tbl").expect("read");
28536        let col = back.column("x").expect("x");
28537        assert_eq!(col.values()[0], Scalar::Int64(1));
28538        assert_eq!(col.values()[1], Scalar::Int64(2));
28539    }
28540
28541    #[test]
28542    fn sql_create_table_query_in_schema_validates_schema_name() {
28543        struct PgLikeValidate;
28544        impl super::SqlConnection for PgLikeValidate {
28545            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<super::SqlQueryResult, IoError> {
28546                Ok(super::SqlQueryResult {
28547                    columns: vec![],
28548                    rows: vec![],
28549                })
28550            }
28551            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
28552                Ok(())
28553            }
28554            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
28555                Ok(false)
28556            }
28557            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
28558                Ok(())
28559            }
28560            fn dtype_sql(&self, _dtype: DType) -> &'static str {
28561                "TEXT"
28562            }
28563            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
28564                "TEXT"
28565            }
28566            fn supports_schemas(&self) -> bool {
28567                true
28568            }
28569        }
28570        let conn = PgLikeValidate;
28571        let cols = vec!["x INTEGER".to_owned()];
28572        let err =
28573            super::sql_create_table_query_in_schema(&conn, "users", Some("evil; DROP"), &cols)
28574                .expect_err("malformed schema must reject");
28575        // Per fd90.56: schema validation error now says invalid
28576        // schema name (not invalid table name).
28577        assert!(matches!(err, IoError::Sql(msg) if msg.contains("invalid schema name")));
28578    }
28579
28580    // ── DROP TABLE schema-qualification (br-frankenpandas-hxob / fd90.16) ─
28581
28582    #[test]
28583    fn sql_drop_table_query_bare_on_non_multi_schema() {
28584        struct StubSql;
28585        impl super::SqlConnection for StubSql {
28586            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<super::SqlQueryResult, IoError> {
28587                Ok(super::SqlQueryResult {
28588                    columns: vec![],
28589                    rows: vec![],
28590                })
28591            }
28592            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
28593                Ok(())
28594            }
28595            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
28596                Ok(false)
28597            }
28598            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
28599                Ok(())
28600            }
28601            fn dtype_sql(&self, _dtype: DType) -> &'static str {
28602                "TEXT"
28603            }
28604            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
28605                "TEXT"
28606            }
28607        }
28608        let conn = StubSql;
28609        let q = super::sql_drop_table_query_in_schema(&conn, "users", None).expect("drop none");
28610        assert_eq!(q, "DROP TABLE IF EXISTS \"users\"");
28611        // schema=Some on non-multi-schema is silently ignored.
28612        let q2 =
28613            super::sql_drop_table_query_in_schema(&conn, "users", Some("ignored")).expect("drop");
28614        assert_eq!(q2, "DROP TABLE IF EXISTS \"users\"");
28615    }
28616
28617    #[test]
28618    fn sql_drop_table_query_qualifies_on_multi_schema_backend() {
28619        struct PgLikeDrop;
28620        impl super::SqlConnection for PgLikeDrop {
28621            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<super::SqlQueryResult, IoError> {
28622                Ok(super::SqlQueryResult {
28623                    columns: vec![],
28624                    rows: vec![],
28625                })
28626            }
28627            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
28628                Ok(())
28629            }
28630            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
28631                Ok(false)
28632            }
28633            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
28634                Ok(())
28635            }
28636            fn dtype_sql(&self, _dtype: DType) -> &'static str {
28637                "TEXT"
28638            }
28639            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
28640                "TEXT"
28641            }
28642            fn supports_schemas(&self) -> bool {
28643                true
28644            }
28645        }
28646        let conn = PgLikeDrop;
28647        let q = super::sql_drop_table_query_in_schema(&conn, "users", Some("analytics"))
28648            .expect("drop qualified");
28649        assert_eq!(q, "DROP TABLE IF EXISTS \"analytics\".\"users\"");
28650        let bare = super::sql_drop_table_query_in_schema(&conn, "users", None).expect("drop bare");
28651        assert_eq!(bare, "DROP TABLE IF EXISTS \"users\"");
28652    }
28653
28654    #[cfg(feature = "sql-sqlite")]
28655    #[test]
28656    fn write_sql_replace_with_schema_silently_ignored_on_sqlite() {
28657        // Replace path drops + recreates. SQLite reports supports_schemas
28658        // == false; the schema is silently ignored on the DROP and on the
28659        // CREATE/INSERT — the round trip lands data in the bare table.
28660        let conn = make_sql_test_conn();
28661        super::SqlConnection::execute_batch(
28662            &conn,
28663            "CREATE TABLE replace_tbl (x INTEGER); INSERT INTO replace_tbl VALUES (99);",
28664        )
28665        .unwrap();
28666        let frame = fp_frame::DataFrame::from_dict(
28667            &["x"],
28668            vec![("x", vec![Scalar::Int64(1), Scalar::Int64(2)])],
28669        )
28670        .unwrap();
28671        write_sql_with_options(
28672            &frame,
28673            &conn,
28674            "replace_tbl",
28675            &SqlWriteOptions {
28676                if_exists: SqlIfExists::Replace,
28677                index: false,
28678                index_label: None,
28679                schema: Some("ignored_on_sqlite".to_owned()),
28680                dtype: None,
28681                method: SqlInsertMethod::Single,
28682                chunksize: None,
28683            },
28684        )
28685        .expect("replace + schema=Some on SQLite");
28686        let back = read_sql_table(&conn, "replace_tbl").expect("read");
28687        let col = back.column("x").expect("x");
28688        // Pre-existing 99 was dropped; new rows present.
28689        assert_eq!(col.values().len(), 2);
28690        assert_eq!(col.values()[0], Scalar::Int64(1));
28691        assert_eq!(col.values()[1], Scalar::Int64(2));
28692    }
28693
28694    // ── table_exists_in_schema (br-frankenpandas-70d1 / fd90.17) ────────
28695
28696    #[test]
28697    fn default_table_exists_in_schema_delegates_to_table_exists() {
28698        // A stub that returns table_exists=true for "users" must report the
28699        // same value via the schema-aware default impl regardless of schema.
28700        struct StubExistsTrue;
28701        impl super::SqlConnection for StubExistsTrue {
28702            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<super::SqlQueryResult, IoError> {
28703                Ok(super::SqlQueryResult {
28704                    columns: vec![],
28705                    rows: vec![],
28706                })
28707            }
28708            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
28709                Ok(())
28710            }
28711            fn table_exists(&self, name: &str) -> Result<bool, IoError> {
28712                Ok(name == "users")
28713            }
28714            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
28715                Ok(())
28716            }
28717            fn dtype_sql(&self, _dtype: DType) -> &'static str {
28718                "TEXT"
28719            }
28720            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
28721                "TEXT"
28722            }
28723        }
28724        let conn = StubExistsTrue;
28725        // Schema is ignored by the default impl.
28726        assert!(super::SqlConnection::table_exists_in_schema(&conn, "users", None).unwrap());
28727        assert!(
28728            super::SqlConnection::table_exists_in_schema(&conn, "users", Some("ignored")).unwrap()
28729        );
28730        assert!(!super::SqlConnection::table_exists_in_schema(&conn, "missing", None).unwrap());
28731    }
28732
28733    #[test]
28734    fn multi_schema_override_scopes_table_exists() {
28735        // PgLikeSchemaCheck overrides table_exists_in_schema to scope by
28736        // schema: only ('analytics', 'users') exists.
28737        struct PgLikeSchemaCheck;
28738        impl super::SqlConnection for PgLikeSchemaCheck {
28739            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<super::SqlQueryResult, IoError> {
28740                Ok(super::SqlQueryResult {
28741                    columns: vec![],
28742                    rows: vec![],
28743                })
28744            }
28745            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
28746                Ok(())
28747            }
28748            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
28749                // Bare table_exists isn't queried by the override path.
28750                Ok(false)
28751            }
28752            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
28753                Ok(())
28754            }
28755            fn dtype_sql(&self, _dtype: DType) -> &'static str {
28756                "TEXT"
28757            }
28758            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
28759                "TEXT"
28760            }
28761            fn supports_schemas(&self) -> bool {
28762                true
28763            }
28764            fn table_exists_in_schema(
28765                &self,
28766                table: &str,
28767                schema: Option<&str>,
28768            ) -> Result<bool, IoError> {
28769                Ok(table == "users" && schema == Some("analytics"))
28770            }
28771        }
28772        let conn = PgLikeSchemaCheck;
28773        assert!(
28774            super::SqlConnection::table_exists_in_schema(&conn, "users", Some("analytics"))
28775                .unwrap()
28776        );
28777        // Different schema → false.
28778        assert!(
28779            !super::SqlConnection::table_exists_in_schema(&conn, "users", Some("audit")).unwrap()
28780        );
28781        // No schema → false (override scopes by Some).
28782        assert!(!super::SqlConnection::table_exists_in_schema(&conn, "users", None).unwrap());
28783    }
28784
28785    #[cfg(feature = "sql-sqlite")]
28786    #[test]
28787    fn write_sql_fail_with_schema_some_still_rejects_existing_on_sqlite() {
28788        // SQLite ignores schema everywhere; the Fail branch still reports
28789        // 'table already exists' when the bare table is present.
28790        let conn = make_sql_test_conn();
28791        super::SqlConnection::execute_batch(&conn, "CREATE TABLE preexists_tbl (x INTEGER);")
28792            .unwrap();
28793        let frame =
28794            fp_frame::DataFrame::from_dict(&["x"], vec![("x", vec![Scalar::Int64(1)])]).unwrap();
28795        let err = write_sql_with_options(
28796            &frame,
28797            &conn,
28798            "preexists_tbl",
28799            &SqlWriteOptions {
28800                if_exists: SqlIfExists::Fail,
28801                index: false,
28802                index_label: None,
28803                schema: Some("ignored_on_sqlite".to_owned()),
28804                dtype: None,
28805                method: SqlInsertMethod::Single,
28806                chunksize: None,
28807            },
28808        )
28809        .expect_err("Fail branch must still reject pre-existing");
28810        assert!(matches!(err, IoError::Sql(msg) if msg.contains("already exists")));
28811    }
28812
28813    // ── SqlWriteOptions::dtype overrides (br-frankenpandas-ev2s / fd90.18) ─
28814
28815    #[cfg(feature = "sql-sqlite")]
28816    #[test]
28817    fn write_sql_dtype_override_emits_custom_sql_type() {
28818        // SQLite is permissive on declared types — the column-type string
28819        // ends up in sqlite_master.sql verbatim, which we can grep to verify
28820        // the override took effect during CREATE TABLE.
28821        let conn = make_sql_test_conn();
28822        let frame = fp_frame::DataFrame::from_dict(
28823            &["amount"],
28824            vec![("amount", vec![Scalar::Int64(100), Scalar::Int64(250)])],
28825        )
28826        .unwrap();
28827        let mut overrides = BTreeMap::new();
28828        overrides.insert("amount".to_owned(), "NUMERIC(10,2)".to_owned());
28829        write_sql_with_options(
28830            &frame,
28831            &conn,
28832            "money_tbl",
28833            &SqlWriteOptions {
28834                if_exists: SqlIfExists::Fail,
28835                index: false,
28836                index_label: None,
28837                schema: None,
28838                dtype: Some(overrides),
28839                method: SqlInsertMethod::Single,
28840                chunksize: None,
28841            },
28842        )
28843        .expect("write with dtype override");
28844        let sm = super::SqlConnection::query(
28845            &conn,
28846            "SELECT sql FROM sqlite_master WHERE name = 'money_tbl'",
28847            &[],
28848        )
28849        .unwrap();
28850        let create_sql = match &sm.rows[0][0] {
28851            Scalar::Utf8(s) => s.clone(),
28852            other => unreachable!("unexpected sqlite_master payload: {other:?}"),
28853        };
28854        assert!(
28855            create_sql.contains("NUMERIC(10,2)"),
28856            "expected override to land in CREATE TABLE; got: {create_sql}"
28857        );
28858    }
28859
28860    #[cfg(feature = "sql-sqlite")]
28861    #[test]
28862    fn write_sql_dtype_override_multiple_columns() {
28863        let conn = make_sql_test_conn();
28864        let frame = fp_frame::DataFrame::from_dict(
28865            &["a", "b"],
28866            vec![
28867                ("a", vec![Scalar::Int64(1)]),
28868                ("b", vec![Scalar::Float64(1.5)]),
28869            ],
28870        )
28871        .unwrap();
28872        let mut overrides = BTreeMap::new();
28873        overrides.insert("a".to_owned(), "BIGINT".to_owned());
28874        overrides.insert("b".to_owned(), "DECIMAL(8,4)".to_owned());
28875        write_sql_with_options(
28876            &frame,
28877            &conn,
28878            "multi_tbl",
28879            &SqlWriteOptions {
28880                if_exists: SqlIfExists::Fail,
28881                index: false,
28882                index_label: None,
28883                schema: None,
28884                dtype: Some(overrides),
28885                method: SqlInsertMethod::Single,
28886                chunksize: None,
28887            },
28888        )
28889        .expect("write with multi-column overrides");
28890        let sm = super::SqlConnection::query(
28891            &conn,
28892            "SELECT sql FROM sqlite_master WHERE name = 'multi_tbl'",
28893            &[],
28894        )
28895        .unwrap();
28896        let create_sql = match &sm.rows[0][0] {
28897            Scalar::Utf8(s) => s.clone(),
28898            other => unreachable!("unexpected sqlite_master payload: {other:?}"),
28899        };
28900        assert!(create_sql.contains("BIGINT"));
28901        assert!(create_sql.contains("DECIMAL(8,4)"));
28902    }
28903
28904    #[cfg(feature = "sql-sqlite")]
28905    #[test]
28906    fn write_sql_dtype_override_for_missing_column_silently_ignored() {
28907        let conn = make_sql_test_conn();
28908        let frame =
28909            fp_frame::DataFrame::from_dict(&["x"], vec![("x", vec![Scalar::Int64(1)])]).unwrap();
28910        let mut overrides = BTreeMap::new();
28911        overrides.insert("nonexistent".to_owned(), "BIGINT".to_owned());
28912        // No error — pandas silently ignores dtype entries for columns not in the frame.
28913        write_sql_with_options(
28914            &frame,
28915            &conn,
28916            "missing_col_tbl",
28917            &SqlWriteOptions {
28918                if_exists: SqlIfExists::Fail,
28919                index: false,
28920                index_label: None,
28921                schema: None,
28922                dtype: Some(overrides),
28923                method: SqlInsertMethod::Single,
28924                chunksize: None,
28925            },
28926        )
28927        .expect("write with override on missing col");
28928        // The actual 'x' column kept its inferred type.
28929        let sm = super::SqlConnection::query(
28930            &conn,
28931            "SELECT sql FROM sqlite_master WHERE name = 'missing_col_tbl'",
28932            &[],
28933        )
28934        .unwrap();
28935        let create_sql = match &sm.rows[0][0] {
28936            Scalar::Utf8(s) => s.clone(),
28937            other => unreachable!("unexpected sqlite_master payload: {other:?}"),
28938        };
28939        assert!(create_sql.contains("INTEGER"));
28940        assert!(!create_sql.contains("BIGINT"));
28941    }
28942
28943    #[cfg(feature = "sql-sqlite")]
28944    #[test]
28945    fn write_sql_dtype_none_falls_back_to_inferred_type() {
28946        let conn = make_sql_test_conn();
28947        let frame =
28948            fp_frame::DataFrame::from_dict(&["x"], vec![("x", vec![Scalar::Int64(1)])]).unwrap();
28949        write_sql_with_options(
28950            &frame,
28951            &conn,
28952            "no_override_tbl",
28953            &SqlWriteOptions {
28954                if_exists: SqlIfExists::Fail,
28955                index: false,
28956                index_label: None,
28957                schema: None,
28958                dtype: None,
28959                method: SqlInsertMethod::Single,
28960                chunksize: None,
28961            },
28962        )
28963        .expect("write without override");
28964        let sm = super::SqlConnection::query(
28965            &conn,
28966            "SELECT sql FROM sqlite_master WHERE name = 'no_override_tbl'",
28967            &[],
28968        )
28969        .unwrap();
28970        let create_sql = match &sm.rows[0][0] {
28971            Scalar::Utf8(s) => s.clone(),
28972            other => unreachable!("unexpected sqlite_master payload: {other:?}"),
28973        };
28974        // INTEGER is conn.dtype_sql(DType::Int64) for rusqlite.
28975        assert!(create_sql.contains("INTEGER"));
28976    }
28977
28978    // ── SqlInsertMethod::Multi (br-frankenpandas-i0ml / fd90.19) ─────────
28979
28980    #[cfg(feature = "sql-sqlite")]
28981    #[test]
28982    fn write_sql_multi_round_trip_matches_single() {
28983        // Same frame written via Single vs Multi must produce identical
28984        // SELECT * results — the only observable difference should be
28985        // the wire-format efficiency, never the stored values.
28986        let frame = fp_frame::DataFrame::from_dict(
28987            &["id", "name", "amount"],
28988            vec![
28989                (
28990                    "id",
28991                    vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
28992                ),
28993                (
28994                    "name",
28995                    vec![
28996                        Scalar::Utf8("alice".into()),
28997                        Scalar::Utf8("bob".into()),
28998                        Scalar::Utf8("carol".into()),
28999                    ],
29000                ),
29001                (
29002                    "amount",
29003                    vec![
29004                        Scalar::Float64(1.5),
29005                        Scalar::Float64(2.5),
29006                        Scalar::Float64(3.5),
29007                    ],
29008                ),
29009            ],
29010        )
29011        .unwrap();
29012
29013        let conn_single = make_sql_test_conn();
29014        write_sql_with_options(
29015            &frame,
29016            &conn_single,
29017            "single_tbl",
29018            &SqlWriteOptions {
29019                if_exists: SqlIfExists::Fail,
29020                index: false,
29021                index_label: None,
29022                schema: None,
29023                dtype: None,
29024                method: SqlInsertMethod::Single,
29025                chunksize: None,
29026            },
29027        )
29028        .unwrap();
29029        let single = read_sql(&conn_single, "SELECT * FROM single_tbl ORDER BY id").unwrap();
29030
29031        let conn_multi = make_sql_test_conn();
29032        write_sql_with_options(
29033            &frame,
29034            &conn_multi,
29035            "multi_tbl",
29036            &SqlWriteOptions {
29037                if_exists: SqlIfExists::Fail,
29038                index: false,
29039                index_label: None,
29040                schema: None,
29041                dtype: None,
29042                method: SqlInsertMethod::Multi,
29043                chunksize: None,
29044            },
29045        )
29046        .unwrap();
29047        let multi = read_sql(&conn_multi, "SELECT * FROM multi_tbl ORDER BY id").unwrap();
29048
29049        assert_eq!(single.column_names(), multi.column_names());
29050        for name in single.column_names() {
29051            let s = single.column(name).unwrap().values().to_vec();
29052            let m = multi.column(name).unwrap().values().to_vec();
29053            assert_eq!(s, m, "column {name} diverged between Single and Multi");
29054        }
29055    }
29056
29057    #[test]
29058    fn sql_multi_row_insert_query_emits_correct_placeholder_count() {
29059        // 3 rows × 2 cols = 6 placeholders, ordinals 1..=6.
29060        struct PgLikeStub;
29061        impl super::SqlConnection for PgLikeStub {
29062            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
29063                Ok(SqlQueryResult {
29064                    columns: vec![],
29065                    rows: vec![],
29066                })
29067            }
29068            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
29069                Ok(())
29070            }
29071            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
29072                Ok(false)
29073            }
29074            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
29075                Ok(())
29076            }
29077            fn dtype_sql(&self, _dtype: DType) -> &'static str {
29078                "TEXT"
29079            }
29080            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
29081                "TEXT"
29082            }
29083            fn parameter_marker(&self, ordinal: usize) -> String {
29084                format!("${ordinal}")
29085            }
29086        }
29087        let conn = PgLikeStub;
29088        let cols = vec!["a".to_owned(), "b".to_owned()];
29089        let sql =
29090            super::sql_multi_row_insert_query_in_schema(&conn, "tbl", None, &cols, 3).unwrap();
29091        // Expect: INSERT INTO "tbl" ("a", "b") VALUES ($1, $2), ($3, $4), ($5, $6)
29092        assert!(
29093            sql.contains("VALUES ($1, $2), ($3, $4), ($5, $6)"),
29094            "got: {sql}"
29095        );
29096    }
29097
29098    #[test]
29099    fn sql_multi_row_insert_query_rejects_zero_rows() {
29100        struct StubConn;
29101        impl super::SqlConnection for StubConn {
29102            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
29103                Ok(SqlQueryResult {
29104                    columns: vec![],
29105                    rows: vec![],
29106                })
29107            }
29108            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
29109                Ok(())
29110            }
29111            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
29112                Ok(false)
29113            }
29114            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
29115                Ok(())
29116            }
29117            fn dtype_sql(&self, _dtype: DType) -> &'static str {
29118                "TEXT"
29119            }
29120            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
29121                "TEXT"
29122            }
29123        }
29124        let conn = StubConn;
29125        let cols = vec!["a".to_owned()];
29126        let err = super::sql_multi_row_insert_query_in_schema(&conn, "tbl", None, &cols, 0)
29127            .expect_err("zero rows must be rejected");
29128        assert!(matches!(err, IoError::Sql(msg) if msg.contains("at least one row")));
29129    }
29130
29131    #[cfg(feature = "sql-sqlite")]
29132    #[test]
29133    fn write_sql_multi_chunks_at_max_param_boundary() {
29134        // Verify the chunking logic dispatches multiple INSERT statements
29135        // when num_rows * num_cols exceeds max_param_count. We override
29136        // max_param_count on a recording stub to force a tiny budget.
29137        use std::cell::RefCell;
29138        struct ChunkRecorder {
29139            statements: RefCell<Vec<String>>,
29140            row_counts: RefCell<Vec<usize>>,
29141        }
29142        impl super::SqlConnection for ChunkRecorder {
29143            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
29144                Ok(SqlQueryResult {
29145                    columns: vec![],
29146                    rows: vec![],
29147                })
29148            }
29149            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
29150                Ok(())
29151            }
29152            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
29153                Ok(false)
29154            }
29155            fn insert_rows(&self, sql: &str, rows: &[Vec<Scalar>]) -> Result<(), IoError> {
29156                self.statements.borrow_mut().push(sql.to_owned());
29157                self.row_counts
29158                    .borrow_mut()
29159                    .push(rows.first().map_or(0, std::vec::Vec::len));
29160                Ok(())
29161            }
29162            fn dtype_sql(&self, _dtype: DType) -> &'static str {
29163                "TEXT"
29164            }
29165            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
29166                "TEXT"
29167            }
29168            fn max_param_count(&self) -> Option<usize> {
29169                // 4 params total, ncols=2 → 2 rows per chunk.
29170                Some(4)
29171            }
29172        }
29173        let conn = ChunkRecorder {
29174            statements: RefCell::new(vec![]),
29175            row_counts: RefCell::new(vec![]),
29176        };
29177        let frame = fp_frame::DataFrame::from_dict(
29178            &["a", "b"],
29179            vec![
29180                (
29181                    "a",
29182                    vec![
29183                        Scalar::Int64(1),
29184                        Scalar::Int64(2),
29185                        Scalar::Int64(3),
29186                        Scalar::Int64(4),
29187                        Scalar::Int64(5),
29188                    ],
29189                ),
29190                (
29191                    "b",
29192                    vec![
29193                        Scalar::Int64(10),
29194                        Scalar::Int64(20),
29195                        Scalar::Int64(30),
29196                        Scalar::Int64(40),
29197                        Scalar::Int64(50),
29198                    ],
29199                ),
29200            ],
29201        )
29202        .unwrap();
29203        write_sql_with_options(
29204            &frame,
29205            &conn,
29206            "chunked",
29207            &SqlWriteOptions {
29208                if_exists: SqlIfExists::Fail,
29209                index: false,
29210                index_label: None,
29211                schema: None,
29212                dtype: None,
29213                method: SqlInsertMethod::Multi,
29214                chunksize: None,
29215            },
29216        )
29217        .unwrap();
29218        // 5 rows / 2 per chunk = 3 chunks (2, 2, 1).
29219        let stmts = conn.statements.borrow();
29220        let counts = conn.row_counts.borrow();
29221        assert_eq!(stmts.len(), 3, "expected 3 chunked INSERTs");
29222        // Flat row payloads: 2 rows * 2 cols = 4 scalars, 4, then 1 row * 2 = 2.
29223        assert_eq!(counts.as_slice(), &[4, 4, 2]);
29224    }
29225
29226    #[cfg(feature = "sql-sqlite")]
29227    #[test]
29228    fn write_sql_multi_no_max_param_sends_single_statement() {
29229        // When the backend reports max_param_count() == None, the whole
29230        // frame should ship in a single multi-row INSERT.
29231        use std::cell::RefCell;
29232        struct UnboundedStub {
29233            statements: RefCell<Vec<String>>,
29234        }
29235        impl super::SqlConnection for UnboundedStub {
29236            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
29237                Ok(SqlQueryResult {
29238                    columns: vec![],
29239                    rows: vec![],
29240                })
29241            }
29242            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
29243                Ok(())
29244            }
29245            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
29246                Ok(false)
29247            }
29248            fn insert_rows(&self, sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
29249                self.statements.borrow_mut().push(sql.to_owned());
29250                Ok(())
29251            }
29252            fn dtype_sql(&self, _dtype: DType) -> &'static str {
29253                "TEXT"
29254            }
29255            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
29256                "TEXT"
29257            }
29258            fn max_param_count(&self) -> Option<usize> {
29259                None
29260            }
29261        }
29262        let conn = UnboundedStub {
29263            statements: RefCell::new(vec![]),
29264        };
29265        let frame = fp_frame::DataFrame::from_dict(
29266            &["x"],
29267            vec![(
29268                "x",
29269                vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
29270            )],
29271        )
29272        .unwrap();
29273        write_sql_with_options(
29274            &frame,
29275            &conn,
29276            "uncapped",
29277            &SqlWriteOptions {
29278                if_exists: SqlIfExists::Fail,
29279                index: false,
29280                index_label: None,
29281                schema: None,
29282                dtype: None,
29283                method: SqlInsertMethod::Multi,
29284                chunksize: None,
29285            },
29286        )
29287        .unwrap();
29288        let stmts = conn.statements.borrow();
29289        assert_eq!(stmts.len(), 1, "expected exactly one multi-row INSERT");
29290        // 3 tuples → 2 commas separating tuples in VALUES (...), (...), (...).
29291        let stmt = &stmts[0];
29292        assert_eq!(
29293            stmt.matches("(?)").count(),
29294            3,
29295            "expected 3 row tuples in: {stmt}"
29296        );
29297    }
29298
29299    #[cfg(feature = "sql-sqlite")]
29300    #[test]
29301    fn write_sql_multi_preserves_nulls() {
29302        // NaT/Null values must round-trip through the multi-row path.
29303        let frame = fp_frame::DataFrame::from_dict(
29304            &["a", "b"],
29305            vec![
29306                (
29307                    "a",
29308                    vec![
29309                        Scalar::Int64(1),
29310                        Scalar::Null(NullKind::Null),
29311                        Scalar::Int64(3),
29312                    ],
29313                ),
29314                (
29315                    "b",
29316                    vec![
29317                        Scalar::Utf8("x".into()),
29318                        Scalar::Utf8("y".into()),
29319                        Scalar::Null(NullKind::Null),
29320                    ],
29321                ),
29322            ],
29323        )
29324        .unwrap();
29325        let conn = make_sql_test_conn();
29326        write_sql_with_options(
29327            &frame,
29328            &conn,
29329            "nulls_tbl",
29330            &SqlWriteOptions {
29331                if_exists: SqlIfExists::Fail,
29332                index: false,
29333                index_label: None,
29334                schema: None,
29335                dtype: None,
29336                method: SqlInsertMethod::Multi,
29337                chunksize: None,
29338            },
29339        )
29340        .unwrap();
29341        let back = read_sql(&conn, "SELECT a, b FROM nulls_tbl ORDER BY rowid").unwrap();
29342        let a = back.column("a").unwrap().values();
29343        let b = back.column("b").unwrap().values();
29344        assert_eq!(a[0], Scalar::Int64(1));
29345        assert!(matches!(a[1], Scalar::Null(_)));
29346        assert_eq!(a[2], Scalar::Int64(3));
29347        assert_eq!(b[0], Scalar::Utf8("x".into()));
29348        assert_eq!(b[1], Scalar::Utf8("y".into()));
29349        assert!(matches!(b[2], Scalar::Null(_)));
29350    }
29351
29352    #[test]
29353    fn sql_insert_method_default_is_single() {
29354        assert_eq!(SqlInsertMethod::default(), SqlInsertMethod::Single);
29355    }
29356
29357    // ── list_sql_tables / SqlConnection::list_tables (br-vhq2 / fd90.20) ─
29358
29359    #[cfg(feature = "sql-sqlite")]
29360    #[test]
29361    fn list_sql_tables_empty_db_returns_empty_vec() {
29362        let conn = make_sql_test_conn();
29363        let tables = list_sql_tables(&conn, None).unwrap();
29364        assert!(tables.is_empty(), "expected no tables; got {tables:?}");
29365    }
29366
29367    #[cfg(feature = "sql-sqlite")]
29368    #[test]
29369    fn list_sql_tables_returns_user_tables_sorted() {
29370        let conn = make_sql_test_conn();
29371        super::SqlConnection::execute_batch(&conn, "CREATE TABLE zebra (x INTEGER);").unwrap();
29372        super::SqlConnection::execute_batch(&conn, "CREATE TABLE alpha (y TEXT);").unwrap();
29373        super::SqlConnection::execute_batch(&conn, "CREATE TABLE mango (z REAL);").unwrap();
29374        let tables = list_sql_tables(&conn, None).unwrap();
29375        assert_eq!(tables, vec!["alpha", "mango", "zebra"]);
29376    }
29377
29378    #[cfg(feature = "sql-sqlite")]
29379    #[test]
29380    fn list_sql_tables_excludes_sqlite_internal_tables() {
29381        let conn = make_sql_test_conn();
29382        // Forcing creation of an internal sqlite_sequence table by using
29383        // AUTOINCREMENT — that table must NOT appear in the result.
29384        super::SqlConnection::execute_batch(
29385            &conn,
29386            "CREATE TABLE seq_demo (id INTEGER PRIMARY KEY AUTOINCREMENT, v TEXT);",
29387        )
29388        .unwrap();
29389        super::SqlConnection::execute_batch(&conn, "INSERT INTO seq_demo (v) VALUES ('one');")
29390            .unwrap();
29391        let tables = list_sql_tables(&conn, None).unwrap();
29392        assert_eq!(tables, vec!["seq_demo"]);
29393        assert!(!tables.iter().any(|name| name.starts_with("sqlite_")));
29394    }
29395
29396    #[cfg(feature = "sql-sqlite")]
29397    #[test]
29398    fn list_sql_tables_keeps_user_tables_with_sqlite_prefix_no_underscore() {
29399        // Per fd90.50: a user table named like 'sqliteX' (no underscore
29400        // between 'sqlite' and the rest) was being incorrectly excluded
29401        // by the buggy `NOT LIKE 'sqlite_%'` filter (where `_` is a
29402        // single-char wildcard). After the ESCAPE '\' fix the
29403        // underscore is treated literally, so only names starting with
29404        // the literal substring 'sqlite_' are excluded.
29405        let conn = make_sql_test_conn();
29406        super::SqlConnection::execute_batch(&conn, "CREATE TABLE sqliteX (x INTEGER);").unwrap();
29407        super::SqlConnection::execute_batch(&conn, "CREATE TABLE sqliteY (y TEXT);").unwrap();
29408        super::SqlConnection::execute_batch(&conn, "CREATE TABLE sqlite1234 (z REAL);").unwrap();
29409        let tables = list_sql_tables(&conn, None).unwrap();
29410        assert_eq!(tables, vec!["sqlite1234", "sqliteX", "sqliteY"]);
29411    }
29412
29413    #[cfg(feature = "sql-sqlite")]
29414    #[test]
29415    fn list_sql_views_keeps_user_views_with_sqlite_prefix_no_underscore() {
29416        // Companion to the list_tables case (fd90.50): same escape fix
29417        // applies to list_views.
29418        let conn = make_sql_test_conn();
29419        super::SqlConnection::execute_batch(&conn, "CREATE TABLE base (x INTEGER);").unwrap();
29420        super::SqlConnection::execute_batch(
29421            &conn,
29422            "CREATE VIEW sqliteX_view AS SELECT x FROM base;",
29423        )
29424        .unwrap();
29425        let views = list_sql_views(&conn, None).unwrap();
29426        // sqliteX_view: 'sqliteX' (no underscore after 'sqlite') so the
29427        // literal-underscore filter accepts it.
29428        assert_eq!(views, vec!["sqliteX_view"]);
29429    }
29430
29431    #[cfg(feature = "sql-sqlite")]
29432    #[test]
29433    fn list_sql_tables_schema_silently_ignored_on_sqlite() {
29434        // SQLite reports supports_schemas() == false. Passing a schema
29435        // arg must NOT error; it is silently dropped and all tables are
29436        // returned (matches the documented option-struct ignore policy).
29437        let conn = make_sql_test_conn();
29438        super::SqlConnection::execute_batch(&conn, "CREATE TABLE only_one (x INTEGER);").unwrap();
29439        let with_schema =
29440            list_sql_tables(&conn, Some("ignored_on_sqlite")).expect("schema arg must not error");
29441        let without_schema = list_sql_tables(&conn, None).unwrap();
29442        assert_eq!(with_schema, without_schema);
29443    }
29444
29445    #[test]
29446    fn list_sql_tables_default_impl_returns_empty() {
29447        // A backend that doesn't override list_tables falls through to
29448        // the trait default — returns empty rather than erroring.
29449        struct NoIntrospection;
29450        impl super::SqlConnection for NoIntrospection {
29451            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
29452                Ok(SqlQueryResult {
29453                    columns: vec![],
29454                    rows: vec![],
29455                })
29456            }
29457            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
29458                Ok(())
29459            }
29460            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
29461                Ok(false)
29462            }
29463            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
29464                Ok(())
29465            }
29466            fn dtype_sql(&self, _dtype: DType) -> &'static str {
29467                "TEXT"
29468            }
29469            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
29470                "TEXT"
29471            }
29472        }
29473        let conn = NoIntrospection;
29474        let tables = list_sql_tables(&conn, None).unwrap();
29475        assert!(tables.is_empty());
29476        let with_schema = list_sql_tables(&conn, Some("any")).unwrap();
29477        assert!(with_schema.is_empty());
29478    }
29479
29480    #[test]
29481    fn list_sql_tables_routes_schema_to_backend_override() {
29482        // Multi-schema backend stub: returns different tables per schema.
29483        struct MultiSchema;
29484        impl super::SqlConnection for MultiSchema {
29485            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
29486                Ok(SqlQueryResult {
29487                    columns: vec![],
29488                    rows: vec![],
29489                })
29490            }
29491            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
29492                Ok(())
29493            }
29494            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
29495                Ok(false)
29496            }
29497            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
29498                Ok(())
29499            }
29500            fn dtype_sql(&self, _dtype: DType) -> &'static str {
29501                "TEXT"
29502            }
29503            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
29504                "TEXT"
29505            }
29506            fn supports_schemas(&self) -> bool {
29507                true
29508            }
29509            fn list_tables(&self, schema: Option<&str>) -> Result<Vec<String>, IoError> {
29510                Ok(match schema {
29511                    Some("analytics") => {
29512                        vec!["users".to_owned(), "events".to_owned()]
29513                    }
29514                    Some("audit") => vec!["logs".to_owned()],
29515                    Some(_) => vec![],
29516                    None => vec!["public_table".to_owned()],
29517                })
29518            }
29519        }
29520        let conn = MultiSchema;
29521        assert_eq!(
29522            list_sql_tables(&conn, Some("analytics")).unwrap(),
29523            vec!["users", "events"]
29524        );
29525        assert_eq!(list_sql_tables(&conn, Some("audit")).unwrap(), vec!["logs"]);
29526        assert_eq!(
29527            list_sql_tables(&conn, Some("missing")).unwrap(),
29528            Vec::<String>::new()
29529        );
29530        assert_eq!(list_sql_tables(&conn, None).unwrap(), vec!["public_table"]);
29531    }
29532
29533    // ── sql_table_schema / SqlConnection::table_schema (br-w43q / fd90.21) ─
29534
29535    #[cfg(feature = "sql-sqlite")]
29536    #[test]
29537    fn sql_table_schema_unknown_table_returns_none() {
29538        let conn = make_sql_test_conn();
29539        let result = sql_table_schema(&conn, "no_such_table", None).unwrap();
29540        assert!(result.is_none());
29541    }
29542
29543    #[cfg(feature = "sql-sqlite")]
29544    #[test]
29545    fn sql_table_schema_simple_table() {
29546        let conn = make_sql_test_conn();
29547        super::SqlConnection::execute_batch(&conn, "CREATE TABLE simple (id INTEGER, name TEXT);")
29548            .unwrap();
29549        let schema = sql_table_schema(&conn, "simple", None).unwrap().unwrap();
29550        assert_eq!(schema.table_name, "simple");
29551        assert_eq!(schema.columns.len(), 2);
29552        assert_eq!(schema.columns[0].name, "id");
29553        assert_eq!(schema.columns[0].declared_type.as_deref(), Some("INTEGER"));
29554        assert!(schema.columns[0].nullable);
29555        assert!(schema.columns[0].primary_key_ordinal.is_none());
29556        assert_eq!(schema.columns[1].name, "name");
29557        assert_eq!(schema.columns[1].declared_type.as_deref(), Some("TEXT"));
29558        assert!(schema.columns[1].nullable);
29559    }
29560
29561    #[cfg(feature = "sql-sqlite")]
29562    #[test]
29563    fn sql_table_schema_pk_notnull_default() {
29564        let conn = make_sql_test_conn();
29565        super::SqlConnection::execute_batch(
29566            &conn,
29567            "CREATE TABLE meta ( \
29568                id INTEGER PRIMARY KEY, \
29569                name TEXT NOT NULL, \
29570                status TEXT DEFAULT 'active' \
29571             );",
29572        )
29573        .unwrap();
29574        let schema = sql_table_schema(&conn, "meta", None).unwrap().unwrap();
29575        assert_eq!(schema.columns.len(), 3);
29576
29577        let id = schema.column("id").expect("id col");
29578        assert_eq!(id.primary_key_ordinal, Some(0));
29579        // PRIMARY KEY columns in SQLite (without explicit NOT NULL on
29580        // INTEGER PRIMARY KEY) are reported as nullable=true by
29581        // table_info — we surface that as-is rather than fabricating.
29582        // The point is just that primary_key_ordinal is populated.
29583
29584        let name = schema.column("name").expect("name col");
29585        assert!(!name.nullable);
29586        assert!(name.default_value.is_none());
29587        assert!(name.primary_key_ordinal.is_none());
29588
29589        let status = schema.column("status").expect("status col");
29590        assert!(status.nullable);
29591        assert_eq!(
29592            status.default_value.as_deref(),
29593            Some("'active'"),
29594            "expected SQL literal default text"
29595        );
29596    }
29597
29598    #[cfg(feature = "sql-sqlite")]
29599    #[test]
29600    fn sql_table_schema_schema_silently_ignored_on_sqlite() {
29601        let conn = make_sql_test_conn();
29602        super::SqlConnection::execute_batch(&conn, "CREATE TABLE only_one (x INTEGER);").unwrap();
29603        let with_schema = sql_table_schema(&conn, "only_one", Some("ignored_on_sqlite"))
29604            .expect("schema arg must not error")
29605            .expect("table exists");
29606        let without_schema = sql_table_schema(&conn, "only_one", None).unwrap().unwrap();
29607        assert_eq!(with_schema, without_schema);
29608    }
29609
29610    #[cfg(feature = "sql-sqlite")]
29611    #[test]
29612    fn sql_table_schema_rejects_invalid_table_name() {
29613        // The PRAGMA path can't bind parameters, so we validate the
29614        // identifier first. Reject anything with non-alphanumeric chars.
29615        let conn = make_sql_test_conn();
29616        let err = sql_table_schema(&conn, "x; DROP TABLE users", None).expect_err("must reject");
29617        assert!(matches!(err, IoError::Sql(msg) if msg.contains("invalid")));
29618    }
29619
29620    #[test]
29621    fn sql_table_schema_default_impl_returns_none() {
29622        struct NoIntrospection;
29623        impl super::SqlConnection for NoIntrospection {
29624            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
29625                Ok(SqlQueryResult {
29626                    columns: vec![],
29627                    rows: vec![],
29628                })
29629            }
29630            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
29631                Ok(())
29632            }
29633            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
29634                Ok(false)
29635            }
29636            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
29637                Ok(())
29638            }
29639            fn dtype_sql(&self, _dtype: DType) -> &'static str {
29640                "TEXT"
29641            }
29642            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
29643                "TEXT"
29644            }
29645        }
29646        let conn = NoIntrospection;
29647        assert!(sql_table_schema(&conn, "anything", None).unwrap().is_none());
29648    }
29649
29650    #[test]
29651    fn sql_table_schema_routes_schema_to_backend_override() {
29652        struct MultiSchema;
29653        impl super::SqlConnection for MultiSchema {
29654            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
29655                Ok(SqlQueryResult {
29656                    columns: vec![],
29657                    rows: vec![],
29658                })
29659            }
29660            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
29661                Ok(())
29662            }
29663            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
29664                Ok(false)
29665            }
29666            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
29667                Ok(())
29668            }
29669            fn dtype_sql(&self, _dtype: DType) -> &'static str {
29670                "TEXT"
29671            }
29672            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
29673                "TEXT"
29674            }
29675            fn supports_schemas(&self) -> bool {
29676                true
29677            }
29678            fn table_schema(
29679                &self,
29680                table: &str,
29681                schema: Option<&str>,
29682            ) -> Result<Option<SqlTableSchema>, IoError> {
29683                if table == "users" && schema == Some("analytics") {
29684                    Ok(Some(SqlTableSchema {
29685                        table_name: "users".to_owned(),
29686                        columns: vec![SqlColumnSchema {
29687                            name: "id".to_owned(),
29688                            declared_type: Some("BIGINT".to_owned()),
29689                            nullable: false,
29690                            default_value: None,
29691                            primary_key_ordinal: Some(0),
29692                            comment: None,
29693                            autoincrement: false,
29694                        }],
29695                    }))
29696                } else {
29697                    Ok(None)
29698                }
29699            }
29700        }
29701        let conn = MultiSchema;
29702        let analytics_users = sql_table_schema(&conn, "users", Some("analytics"))
29703            .unwrap()
29704            .expect("found");
29705        assert_eq!(
29706            analytics_users.columns[0].declared_type.as_deref(),
29707            Some("BIGINT")
29708        );
29709        assert!(
29710            sql_table_schema(&conn, "users", Some("audit"))
29711                .unwrap()
29712                .is_none()
29713        );
29714        assert!(sql_table_schema(&conn, "users", None).unwrap().is_none());
29715    }
29716
29717    // ── list_sql_schemas / SqlConnection::list_schemas (br-lxhi / fd90.22) ─
29718
29719    #[cfg(feature = "sql-sqlite")]
29720    #[test]
29721    fn list_sql_schemas_returns_empty_on_sqlite() {
29722        // SQLite has no meaningful schema concept; the trait default
29723        // (empty Vec) is the right answer.
29724        let conn = make_sql_test_conn();
29725        let schemas = list_sql_schemas(&conn).unwrap();
29726        assert!(schemas.is_empty(), "expected no schemas; got {schemas:?}");
29727    }
29728
29729    #[test]
29730    fn list_sql_schemas_default_impl_returns_empty() {
29731        struct NoIntrospection;
29732        impl super::SqlConnection for NoIntrospection {
29733            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
29734                Ok(SqlQueryResult {
29735                    columns: vec![],
29736                    rows: vec![],
29737                })
29738            }
29739            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
29740                Ok(())
29741            }
29742            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
29743                Ok(false)
29744            }
29745            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
29746                Ok(())
29747            }
29748            fn dtype_sql(&self, _dtype: DType) -> &'static str {
29749                "TEXT"
29750            }
29751            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
29752                "TEXT"
29753            }
29754        }
29755        let conn = NoIntrospection;
29756        assert!(list_sql_schemas(&conn).unwrap().is_empty());
29757    }
29758
29759    #[test]
29760    fn list_sql_schemas_routes_to_backend_override() {
29761        // Multi-schema backend stub: returns the schemas the connection's
29762        // role can see, with internal schemas filtered out.
29763        struct MultiSchemaServer;
29764        impl super::SqlConnection for MultiSchemaServer {
29765            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
29766                Ok(SqlQueryResult {
29767                    columns: vec![],
29768                    rows: vec![],
29769                })
29770            }
29771            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
29772                Ok(())
29773            }
29774            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
29775                Ok(false)
29776            }
29777            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
29778                Ok(())
29779            }
29780            fn dtype_sql(&self, _dtype: DType) -> &'static str {
29781                "TEXT"
29782            }
29783            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
29784                "TEXT"
29785            }
29786            fn supports_schemas(&self) -> bool {
29787                true
29788            }
29789            fn list_schemas(&self) -> Result<Vec<String>, IoError> {
29790                // Filter out information_schema + pg_catalog by default.
29791                Ok(vec![
29792                    "public".to_owned(),
29793                    "analytics".to_owned(),
29794                    "audit".to_owned(),
29795                ])
29796            }
29797        }
29798        let conn = MultiSchemaServer;
29799        let schemas = list_sql_schemas(&conn).unwrap();
29800        assert_eq!(schemas, vec!["public", "analytics", "audit"]);
29801        // Verify the override actually filters internal schemas
29802        // (test contract: stub never returns 'pg_catalog' or
29803        // 'information_schema').
29804        assert!(!schemas.iter().any(|s| s.starts_with("pg_")));
29805        assert!(!schemas.iter().any(|s| s == "information_schema"));
29806    }
29807
29808    #[test]
29809    fn list_sql_schemas_propagates_backend_error() {
29810        // If the backend errors during introspection, the error should
29811        // surface through the wrapper unchanged.
29812        struct BrokenIntrospection;
29813        impl super::SqlConnection for BrokenIntrospection {
29814            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
29815                Ok(SqlQueryResult {
29816                    columns: vec![],
29817                    rows: vec![],
29818                })
29819            }
29820            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
29821                Ok(())
29822            }
29823            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
29824                Ok(false)
29825            }
29826            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
29827                Ok(())
29828            }
29829            fn dtype_sql(&self, _dtype: DType) -> &'static str {
29830                "TEXT"
29831            }
29832            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
29833                "TEXT"
29834            }
29835            fn list_schemas(&self) -> Result<Vec<String>, IoError> {
29836                Err(IoError::Sql("permission denied for catalog".to_owned()))
29837            }
29838        }
29839        let conn = BrokenIntrospection;
29840        let err = list_sql_schemas(&conn).expect_err("should surface backend error");
29841        assert!(matches!(err, IoError::Sql(msg) if msg.contains("permission denied")));
29842    }
29843
29844    // ── truncate_sql_table / SqlConnection::truncate_table (br-phum / fd90.23) ─
29845
29846    #[cfg(feature = "sql-sqlite")]
29847    #[test]
29848    fn truncate_sql_table_clears_rows_but_preserves_schema() {
29849        let conn = make_sql_test_conn();
29850        super::SqlConnection::execute_batch(&conn, "CREATE TABLE rolling (id INTEGER, val TEXT);")
29851            .unwrap();
29852        super::SqlConnection::execute_batch(
29853            &conn,
29854            "INSERT INTO rolling VALUES (1, 'a'), (2, 'b'), (3, 'c');",
29855        )
29856        .unwrap();
29857        // Sanity: rows present.
29858        let before =
29859            super::SqlConnection::query(&conn, "SELECT COUNT(*) FROM rolling", &[]).unwrap();
29860        assert_eq!(before.rows[0][0], Scalar::Int64(3));
29861
29862        truncate_sql_table(&conn, "rolling", None).unwrap();
29863
29864        // Rows gone, table still there.
29865        let after =
29866            super::SqlConnection::query(&conn, "SELECT COUNT(*) FROM rolling", &[]).unwrap();
29867        assert_eq!(after.rows[0][0], Scalar::Int64(0));
29868        assert!(super::SqlConnection::table_exists(&conn, "rolling").unwrap());
29869    }
29870
29871    #[cfg(feature = "sql-sqlite")]
29872    #[test]
29873    fn truncate_sql_table_schema_silently_ignored_on_sqlite() {
29874        let conn = make_sql_test_conn();
29875        super::SqlConnection::execute_batch(&conn, "CREATE TABLE t (x INTEGER);").unwrap();
29876        super::SqlConnection::execute_batch(&conn, "INSERT INTO t VALUES (1);").unwrap();
29877        truncate_sql_table(&conn, "t", Some("ignored_on_sqlite"))
29878            .expect("schema arg must not error on SQLite");
29879        let count = super::SqlConnection::query(&conn, "SELECT COUNT(*) FROM t", &[]).unwrap();
29880        assert_eq!(count.rows[0][0], Scalar::Int64(0));
29881    }
29882
29883    #[cfg(feature = "sql-sqlite")]
29884    #[test]
29885    fn truncate_sql_table_rejects_invalid_table_name() {
29886        let conn = make_sql_test_conn();
29887        let err = truncate_sql_table(&conn, "x; DROP TABLE users", None)
29888            .expect_err("must reject invalid identifier");
29889        assert!(matches!(err, IoError::Sql(msg) if msg.contains("invalid")));
29890    }
29891
29892    #[test]
29893    fn truncate_sql_table_routes_schema_to_quote_identifier() {
29894        // Multi-schema backend stub records the SQL it receives.
29895        use std::cell::RefCell;
29896        struct PgLikeRecorder {
29897            statements: RefCell<Vec<String>>,
29898        }
29899        impl super::SqlConnection for PgLikeRecorder {
29900            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
29901                Ok(SqlQueryResult {
29902                    columns: vec![],
29903                    rows: vec![],
29904                })
29905            }
29906            fn execute_batch(&self, sql: &str) -> Result<(), IoError> {
29907                self.statements.borrow_mut().push(sql.to_owned());
29908                Ok(())
29909            }
29910            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
29911                Ok(false)
29912            }
29913            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
29914                Ok(())
29915            }
29916            fn dtype_sql(&self, _dtype: DType) -> &'static str {
29917                "TEXT"
29918            }
29919            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
29920                "TEXT"
29921            }
29922            fn supports_schemas(&self) -> bool {
29923                true
29924            }
29925        }
29926        let conn = PgLikeRecorder {
29927            statements: RefCell::new(vec![]),
29928        };
29929        truncate_sql_table(&conn, "events", Some("analytics")).unwrap();
29930        let stmts = conn.statements.borrow();
29931        assert_eq!(stmts.len(), 1);
29932        // Default impl uses DELETE FROM ... and quote_identifier on
29933        // both schema + table parts.
29934        assert!(
29935            stmts[0].contains("DELETE FROM \"analytics\".\"events\""),
29936            "expected schema-qualified DELETE; got: {}",
29937            stmts[0]
29938        );
29939    }
29940
29941    #[test]
29942    fn truncate_sql_table_backend_override_uses_truncate_keyword() {
29943        // PG/MySQL impls would override with TRUNCATE TABLE for speed.
29944        // Verify the trait dispatch picks up the override.
29945        use std::cell::RefCell;
29946        struct FastTruncate {
29947            statements: RefCell<Vec<String>>,
29948        }
29949        impl super::SqlConnection for FastTruncate {
29950            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
29951                Ok(SqlQueryResult {
29952                    columns: vec![],
29953                    rows: vec![],
29954                })
29955            }
29956            fn execute_batch(&self, sql: &str) -> Result<(), IoError> {
29957                self.statements.borrow_mut().push(sql.to_owned());
29958                Ok(())
29959            }
29960            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
29961                Ok(false)
29962            }
29963            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
29964                Ok(())
29965            }
29966            fn dtype_sql(&self, _dtype: DType) -> &'static str {
29967                "TEXT"
29968            }
29969            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
29970                "TEXT"
29971            }
29972            fn truncate_table(
29973                &self,
29974                table_name: &str,
29975                _schema: Option<&str>,
29976            ) -> Result<(), IoError> {
29977                self.execute_batch(&format!("TRUNCATE TABLE \"{table_name}\""))
29978            }
29979        }
29980        let conn = FastTruncate {
29981            statements: RefCell::new(vec![]),
29982        };
29983        truncate_sql_table(&conn, "events", None).unwrap();
29984        let stmts = conn.statements.borrow();
29985        assert_eq!(stmts.len(), 1);
29986        assert!(stmts[0].starts_with("TRUNCATE TABLE"), "got: {}", stmts[0]);
29987    }
29988
29989    // ── sql_server_version / SqlConnection::server_version (br-e23k / fd90.24) ─
29990
29991    #[cfg(feature = "sql-sqlite")]
29992    #[test]
29993    fn sql_server_version_returns_sqlite_version_string() {
29994        let conn = make_sql_test_conn();
29995        let version = sql_server_version(&conn)
29996            .unwrap()
29997            .expect("SQLite reports version");
29998        // Expect dotted-version format like "3.45.1". The parts must be
29999        // non-empty digits — exact value depends on the bundled SQLite.
30000        let parts: Vec<&str> = version.split('.').collect();
30001        assert!(parts.len() >= 2, "expected dotted version; got: {version}");
30002        for part in &parts {
30003            assert!(
30004                !part.is_empty() && part.chars().all(|c| c.is_ascii_digit()),
30005                "expected numeric version parts; got {version}"
30006            );
30007        }
30008    }
30009
30010    #[cfg(feature = "sql-sqlite")]
30011    #[test]
30012    fn sql_server_version_starts_with_three_for_sqlite_3_x() {
30013        // SQLite has been at major version 3 since 2004; bundled
30014        // rusqlite is current (3.40+), so the major must be "3".
30015        let conn = make_sql_test_conn();
30016        let version = sql_server_version(&conn).unwrap().unwrap();
30017        assert!(
30018            version.starts_with("3."),
30019            "expected SQLite 3.x; got {version}"
30020        );
30021    }
30022
30023    #[test]
30024    fn sql_server_version_default_impl_returns_none() {
30025        struct NoIntrospection;
30026        impl super::SqlConnection for NoIntrospection {
30027            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
30028                Ok(SqlQueryResult {
30029                    columns: vec![],
30030                    rows: vec![],
30031                })
30032            }
30033            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
30034                Ok(())
30035            }
30036            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
30037                Ok(false)
30038            }
30039            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
30040                Ok(())
30041            }
30042            fn dtype_sql(&self, _dtype: DType) -> &'static str {
30043                "TEXT"
30044            }
30045            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
30046                "TEXT"
30047            }
30048        }
30049        let conn = NoIntrospection;
30050        assert!(sql_server_version(&conn).unwrap().is_none());
30051    }
30052
30053    #[test]
30054    fn sql_server_version_routes_to_backend_override() {
30055        struct PgLikeStub;
30056        impl super::SqlConnection for PgLikeStub {
30057            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
30058                Ok(SqlQueryResult {
30059                    columns: vec![],
30060                    rows: vec![],
30061                })
30062            }
30063            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
30064                Ok(())
30065            }
30066            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
30067                Ok(false)
30068            }
30069            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
30070                Ok(())
30071            }
30072            fn dtype_sql(&self, _dtype: DType) -> &'static str {
30073                "TEXT"
30074            }
30075            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
30076                "TEXT"
30077            }
30078            fn server_version(&self) -> Result<Option<String>, IoError> {
30079                // Mimic `SHOW server_version` payload.
30080                Ok(Some("16.2".to_owned()))
30081            }
30082        }
30083        let conn = PgLikeStub;
30084        assert_eq!(sql_server_version(&conn).unwrap().as_deref(), Some("16.2"));
30085    }
30086
30087    #[test]
30088    fn sql_server_version_propagates_backend_error() {
30089        struct BrokenIntrospection;
30090        impl super::SqlConnection for BrokenIntrospection {
30091            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
30092                Ok(SqlQueryResult {
30093                    columns: vec![],
30094                    rows: vec![],
30095                })
30096            }
30097            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
30098                Ok(())
30099            }
30100            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
30101                Ok(false)
30102            }
30103            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
30104                Ok(())
30105            }
30106            fn dtype_sql(&self, _dtype: DType) -> &'static str {
30107                "TEXT"
30108            }
30109            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
30110                "TEXT"
30111            }
30112            fn server_version(&self) -> Result<Option<String>, IoError> {
30113                Err(IoError::Sql("connection lost".to_owned()))
30114            }
30115        }
30116        let conn = BrokenIntrospection;
30117        let err = sql_server_version(&conn).expect_err("should surface backend error");
30118        assert!(matches!(err, IoError::Sql(msg) if msg.contains("connection lost")));
30119    }
30120
30121    // ── sql_primary_key_columns / SqlConnection::primary_key_columns
30122    //    (br-uw3y / fd90.25) ────────────────────────────────────────────────
30123
30124    #[cfg(feature = "sql-sqlite")]
30125    #[test]
30126    fn sql_primary_key_columns_unknown_table_returns_empty() {
30127        let conn = make_sql_test_conn();
30128        let pk = sql_primary_key_columns(&conn, "no_such_table", None).unwrap();
30129        assert!(pk.is_empty());
30130    }
30131
30132    #[cfg(feature = "sql-sqlite")]
30133    #[test]
30134    fn sql_primary_key_columns_table_without_pk_returns_empty() {
30135        let conn = make_sql_test_conn();
30136        super::SqlConnection::execute_batch(&conn, "CREATE TABLE no_pk (a INTEGER, b TEXT);")
30137            .unwrap();
30138        let pk = sql_primary_key_columns(&conn, "no_pk", None).unwrap();
30139        assert!(pk.is_empty());
30140    }
30141
30142    #[cfg(feature = "sql-sqlite")]
30143    #[test]
30144    fn sql_primary_key_columns_single_pk() {
30145        let conn = make_sql_test_conn();
30146        super::SqlConnection::execute_batch(
30147            &conn,
30148            "CREATE TABLE single_pk (id INTEGER PRIMARY KEY, name TEXT);",
30149        )
30150        .unwrap();
30151        let pk = sql_primary_key_columns(&conn, "single_pk", None).unwrap();
30152        assert_eq!(pk, vec!["id"]);
30153    }
30154
30155    #[cfg(feature = "sql-sqlite")]
30156    #[test]
30157    fn sql_primary_key_columns_composite_pk_ordered_by_ordinal() {
30158        let conn = make_sql_test_conn();
30159        super::SqlConnection::execute_batch(
30160            &conn,
30161            "CREATE TABLE composite ( \
30162                year INTEGER NOT NULL, \
30163                month INTEGER NOT NULL, \
30164                code TEXT NOT NULL, \
30165                value REAL, \
30166                PRIMARY KEY (year, month, code) \
30167             );",
30168        )
30169        .unwrap();
30170        let pk = sql_primary_key_columns(&conn, "composite", None).unwrap();
30171        // PK declaration order: year, month, code.
30172        assert_eq!(pk, vec!["year", "month", "code"]);
30173    }
30174
30175    #[test]
30176    fn sql_primary_key_columns_default_impl_returns_empty_when_no_introspection() {
30177        // Backend with no table_schema override returns Ok(None) →
30178        // primary_key_columns falls through to empty Vec.
30179        struct NoIntrospection;
30180        impl super::SqlConnection for NoIntrospection {
30181            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
30182                Ok(SqlQueryResult {
30183                    columns: vec![],
30184                    rows: vec![],
30185                })
30186            }
30187            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
30188                Ok(())
30189            }
30190            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
30191                Ok(false)
30192            }
30193            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
30194                Ok(())
30195            }
30196            fn dtype_sql(&self, _dtype: DType) -> &'static str {
30197                "TEXT"
30198            }
30199            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
30200                "TEXT"
30201            }
30202        }
30203        let conn = NoIntrospection;
30204        assert!(
30205            sql_primary_key_columns(&conn, "anything", None)
30206                .unwrap()
30207                .is_empty()
30208        );
30209    }
30210
30211    #[test]
30212    fn sql_primary_key_columns_routes_schema_to_table_schema_override() {
30213        // Backend that returns ordinal-sorted PK columns from a
30214        // multi-schema introspection.
30215        struct MultiSchemaPk;
30216        impl super::SqlConnection for MultiSchemaPk {
30217            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
30218                Ok(SqlQueryResult {
30219                    columns: vec![],
30220                    rows: vec![],
30221                })
30222            }
30223            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
30224                Ok(())
30225            }
30226            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
30227                Ok(false)
30228            }
30229            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
30230                Ok(())
30231            }
30232            fn dtype_sql(&self, _dtype: DType) -> &'static str {
30233                "TEXT"
30234            }
30235            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
30236                "TEXT"
30237            }
30238            fn supports_schemas(&self) -> bool {
30239                true
30240            }
30241            fn table_schema(
30242                &self,
30243                table: &str,
30244                schema: Option<&str>,
30245            ) -> Result<Option<SqlTableSchema>, IoError> {
30246                if table == "events" && schema == Some("analytics") {
30247                    Ok(Some(SqlTableSchema {
30248                        table_name: "events".to_owned(),
30249                        columns: vec![
30250                            // Intentionally out-of-declaration-order to
30251                            // verify the helper sorts by ordinal.
30252                            SqlColumnSchema {
30253                                name: "code".to_owned(),
30254                                declared_type: Some("TEXT".to_owned()),
30255                                nullable: false,
30256                                default_value: None,
30257                                primary_key_ordinal: Some(2),
30258                                comment: None,
30259                                autoincrement: false,
30260                            },
30261                            SqlColumnSchema {
30262                                name: "year".to_owned(),
30263                                declared_type: Some("INTEGER".to_owned()),
30264                                nullable: false,
30265                                default_value: None,
30266                                primary_key_ordinal: Some(0),
30267                                comment: None,
30268                                autoincrement: false,
30269                            },
30270                            SqlColumnSchema {
30271                                name: "value".to_owned(),
30272                                declared_type: Some("REAL".to_owned()),
30273                                nullable: true,
30274                                default_value: None,
30275                                primary_key_ordinal: None,
30276                                comment: None,
30277                                autoincrement: false,
30278                            },
30279                            SqlColumnSchema {
30280                                name: "month".to_owned(),
30281                                declared_type: Some("INTEGER".to_owned()),
30282                                nullable: false,
30283                                default_value: None,
30284                                primary_key_ordinal: Some(1),
30285                                comment: None,
30286                                autoincrement: false,
30287                            },
30288                        ],
30289                    }))
30290                } else {
30291                    Ok(None)
30292                }
30293            }
30294        }
30295        let conn = MultiSchemaPk;
30296        let pk = sql_primary_key_columns(&conn, "events", Some("analytics")).unwrap();
30297        // Sorted by primary_key_ordinal: 0=year, 1=month, 2=code.
30298        assert_eq!(pk, vec!["year", "month", "code"]);
30299        // Wrong schema → empty (table_schema returns None).
30300        assert!(
30301            sql_primary_key_columns(&conn, "events", Some("audit"))
30302                .unwrap()
30303                .is_empty()
30304        );
30305    }
30306
30307    // ── sql_max_identifier_length / SqlConnection::max_identifier_length
30308    //    (br-cs81 / fd90.26) ────────────────────────────────────────────────
30309
30310    #[cfg(feature = "sql-sqlite")]
30311    #[test]
30312    fn sql_max_identifier_length_returns_none_on_sqlite() {
30313        // SQLite has no documented identifier-length limit; the trait
30314        // default (None) is the right answer.
30315        let conn = make_sql_test_conn();
30316        assert_eq!(sql_max_identifier_length(&conn), None);
30317    }
30318
30319    #[test]
30320    fn sql_max_identifier_length_default_impl_returns_none() {
30321        struct Generic;
30322        impl super::SqlConnection for Generic {
30323            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
30324                Ok(SqlQueryResult {
30325                    columns: vec![],
30326                    rows: vec![],
30327                })
30328            }
30329            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
30330                Ok(())
30331            }
30332            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
30333                Ok(false)
30334            }
30335            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
30336                Ok(())
30337            }
30338            fn dtype_sql(&self, _dtype: DType) -> &'static str {
30339                "TEXT"
30340            }
30341            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
30342                "TEXT"
30343            }
30344        }
30345        assert_eq!(sql_max_identifier_length(&Generic), None);
30346    }
30347
30348    #[test]
30349    fn sql_max_identifier_length_pg_override_reports_63() {
30350        struct PgLikeStub;
30351        impl super::SqlConnection for PgLikeStub {
30352            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
30353                Ok(SqlQueryResult {
30354                    columns: vec![],
30355                    rows: vec![],
30356                })
30357            }
30358            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
30359                Ok(())
30360            }
30361            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
30362                Ok(false)
30363            }
30364            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
30365                Ok(())
30366            }
30367            fn dtype_sql(&self, _dtype: DType) -> &'static str {
30368                "TEXT"
30369            }
30370            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
30371                "TEXT"
30372            }
30373            fn max_identifier_length(&self) -> Option<usize> {
30374                Some(63)
30375            }
30376        }
30377        assert_eq!(sql_max_identifier_length(&PgLikeStub), Some(63));
30378    }
30379
30380    #[test]
30381    fn sql_max_identifier_length_mysql_override_reports_64() {
30382        struct MySqlLikeStub;
30383        impl super::SqlConnection for MySqlLikeStub {
30384            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
30385                Ok(SqlQueryResult {
30386                    columns: vec![],
30387                    rows: vec![],
30388                })
30389            }
30390            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
30391                Ok(())
30392            }
30393            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
30394                Ok(false)
30395            }
30396            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
30397                Ok(())
30398            }
30399            fn dtype_sql(&self, _dtype: DType) -> &'static str {
30400                "TEXT"
30401            }
30402            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
30403                "TEXT"
30404            }
30405            fn max_identifier_length(&self) -> Option<usize> {
30406                Some(64)
30407            }
30408        }
30409        assert_eq!(sql_max_identifier_length(&MySqlLikeStub), Some(64));
30410    }
30411
30412    #[test]
30413    fn sql_max_identifier_length_mssql_override_reports_128() {
30414        struct MsSqlLikeStub;
30415        impl super::SqlConnection for MsSqlLikeStub {
30416            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
30417                Ok(SqlQueryResult {
30418                    columns: vec![],
30419                    rows: vec![],
30420                })
30421            }
30422            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
30423                Ok(())
30424            }
30425            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
30426                Ok(false)
30427            }
30428            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
30429                Ok(())
30430            }
30431            fn dtype_sql(&self, _dtype: DType) -> &'static str {
30432                "TEXT"
30433            }
30434            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
30435                "TEXT"
30436            }
30437            fn max_identifier_length(&self) -> Option<usize> {
30438                Some(128)
30439            }
30440        }
30441        assert_eq!(sql_max_identifier_length(&MsSqlLikeStub), Some(128));
30442    }
30443
30444    // ── sql backend capability probes / SqlInspector caps
30445    //    (frankenpandas-fd90.10) ───────────────────────────────────────────
30446
30447    #[cfg(feature = "sql-sqlite")]
30448    #[test]
30449    fn sql_backend_caps_sqlite_reports_param_and_row_caps() {
30450        let conn = make_sql_test_conn();
30451        let caps = sql_backend_caps(&conn).unwrap();
30452
30453        assert_eq!(caps.dialect_name, "sqlite");
30454        assert!(
30455            caps.server_version
30456                .as_deref()
30457                .is_some_and(|v| v.starts_with("3."))
30458        );
30459        assert!(caps.supports_returning);
30460        assert!(!caps.supports_schemas);
30461        assert_eq!(caps.max_param_count, Some(32766));
30462        assert_eq!(caps.max_identifier_length, None);
30463        assert_eq!(caps.max_insert_rows(3), Some(10922));
30464        assert_eq!(caps.max_insert_rows(0), None);
30465        assert_eq!(sql_max_param_count(&conn), Some(32766));
30466        assert_eq!(sql_max_insert_rows(&conn, 4), Some(8191));
30467        assert!(sql_supports_returning(&conn));
30468        assert!(!sql_supports_schemas(&conn));
30469    }
30470
30471    #[test]
30472    fn sql_inspector_backend_caps_pg_like_stub_reports_limits() {
30473        struct PgLikeCaps;
30474        impl super::SqlConnection for PgLikeCaps {
30475            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
30476                Ok(SqlQueryResult {
30477                    columns: vec![],
30478                    rows: vec![],
30479                })
30480            }
30481            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
30482                Ok(())
30483            }
30484            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
30485                Ok(false)
30486            }
30487            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
30488                Ok(())
30489            }
30490            fn dtype_sql(&self, _dtype: DType) -> &'static str {
30491                "TEXT"
30492            }
30493            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
30494                "TEXT"
30495            }
30496            fn dialect_name(&self) -> &'static str {
30497                "postgresql"
30498            }
30499            fn server_version(&self) -> Result<Option<String>, IoError> {
30500                Ok(Some("16.3".to_owned()))
30501            }
30502            fn supports_returning(&self) -> bool {
30503                true
30504            }
30505            fn supports_schemas(&self) -> bool {
30506                true
30507            }
30508            fn max_param_count(&self) -> Option<usize> {
30509                Some(65535)
30510            }
30511            fn max_identifier_length(&self) -> Option<usize> {
30512                Some(63)
30513            }
30514        }
30515
30516        let conn = PgLikeCaps;
30517        let inspector = SqlInspector::new(&conn);
30518        let caps = inspector.backend_caps().unwrap();
30519
30520        assert_eq!(inspector.dialect_name(), "postgresql");
30521        assert_eq!(inspector.server_version().unwrap().as_deref(), Some("16.3"));
30522        assert!(inspector.supports_returning());
30523        assert!(inspector.supports_schemas());
30524        assert_eq!(inspector.max_param_count(), Some(65535));
30525        assert_eq!(inspector.max_identifier_length(), Some(63));
30526        assert_eq!(inspector.max_insert_rows(4), Some(16383));
30527        assert_eq!(caps.max_insert_rows(4), Some(16383));
30528        assert_eq!(
30529            caps,
30530            SqlBackendCaps {
30531                dialect_name: "postgresql",
30532                server_version: Some("16.3".to_owned()),
30533                supports_returning: true,
30534                supports_schemas: true,
30535                max_param_count: Some(65535),
30536                max_identifier_length: Some(63),
30537            }
30538        );
30539    }
30540
30541    // ── write_sql identifier-length validation (br-9ynk / fd90.27) ────────
30542
30543    #[cfg(feature = "sql-sqlite")]
30544    #[test]
30545    fn write_sql_long_column_name_succeeds_on_sqlite() {
30546        // SQLite reports max_identifier_length() == None → no validation.
30547        let conn = make_sql_test_conn();
30548        // 80 chars > PG/MySQL caps but fine on SQLite.
30549        let long_col: String = std::iter::repeat_n('a', 80).collect();
30550        let frame = fp_frame::DataFrame::from_dict(
30551            &[long_col.as_str()],
30552            vec![(long_col.as_str(), vec![Scalar::Int64(1)])],
30553        )
30554        .unwrap();
30555        write_sql_with_options(
30556            &frame,
30557            &conn,
30558            "long_col_tbl",
30559            &SqlWriteOptions {
30560                if_exists: SqlIfExists::Fail,
30561                index: false,
30562                index_label: None,
30563                schema: None,
30564                dtype: None,
30565                method: SqlInsertMethod::Single,
30566                chunksize: None,
30567            },
30568        )
30569        .expect("SQLite has no identifier limit");
30570    }
30571
30572    fn make_pg_like_recorder() -> impl super::SqlConnection + 'static {
30573        // Stub PG-like backend: enforces 63-char limit, accepts all
30574        // execute_batch / insert_rows so write_sql can reach the
30575        // identifier-length check before failing on emit.
30576        struct PgLikeLimit;
30577        impl super::SqlConnection for PgLikeLimit {
30578            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
30579                Ok(SqlQueryResult {
30580                    columns: vec![],
30581                    rows: vec![],
30582                })
30583            }
30584            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
30585                Ok(())
30586            }
30587            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
30588                Ok(false)
30589            }
30590            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
30591                Ok(())
30592            }
30593            fn dtype_sql(&self, _dtype: DType) -> &'static str {
30594                "TEXT"
30595            }
30596            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
30597                "TEXT"
30598            }
30599            fn max_identifier_length(&self) -> Option<usize> {
30600                Some(63)
30601            }
30602            fn supports_schemas(&self) -> bool {
30603                true
30604            }
30605        }
30606        PgLikeLimit
30607    }
30608
30609    #[test]
30610    fn write_sql_rejects_long_column_name_on_pg_like_backend() {
30611        let conn = make_pg_like_recorder();
30612        let long_col: String = std::iter::repeat_n('c', 64).collect();
30613        let frame = fp_frame::DataFrame::from_dict(
30614            &[long_col.as_str()],
30615            vec![(long_col.as_str(), vec![Scalar::Int64(1)])],
30616        )
30617        .unwrap();
30618        let err = write_sql_with_options(
30619            &frame,
30620            &conn,
30621            "ok_tbl",
30622            &SqlWriteOptions {
30623                if_exists: SqlIfExists::Fail,
30624                index: false,
30625                index_label: None,
30626                schema: None,
30627                dtype: None,
30628                method: SqlInsertMethod::Single,
30629                chunksize: None,
30630            },
30631        )
30632        .expect_err("64-char column must exceed PG limit");
30633        assert!(matches!(err, IoError::Sql(msg) if msg.contains("column") && msg.contains("63")));
30634    }
30635
30636    #[test]
30637    fn write_sql_rejects_long_table_name_on_pg_like_backend() {
30638        let conn = make_pg_like_recorder();
30639        // 64-char identifier (table names also subject to the PG cap).
30640        // Use only alphanumeric so validate_sql_table_name passes first.
30641        let long_tbl: String = std::iter::repeat_n('t', 64).collect();
30642        let frame =
30643            fp_frame::DataFrame::from_dict(&["x"], vec![("x", vec![Scalar::Int64(1)])]).unwrap();
30644        let err = write_sql_with_options(
30645            &frame,
30646            &conn,
30647            &long_tbl,
30648            &SqlWriteOptions {
30649                if_exists: SqlIfExists::Fail,
30650                index: false,
30651                index_label: None,
30652                schema: None,
30653                dtype: None,
30654                method: SqlInsertMethod::Single,
30655                chunksize: None,
30656            },
30657        )
30658        .expect_err("64-char table must exceed PG limit");
30659        assert!(matches!(err, IoError::Sql(msg) if msg.contains("table") && msg.contains("63")));
30660    }
30661
30662    #[test]
30663    fn write_sql_rejects_long_index_label_on_pg_like_backend() {
30664        let conn = make_pg_like_recorder();
30665        let long_label: String = std::iter::repeat_n('i', 64).collect();
30666        let frame =
30667            fp_frame::DataFrame::from_dict(&["x"], vec![("x", vec![Scalar::Int64(1)])]).unwrap();
30668        let err = write_sql_with_options(
30669            &frame,
30670            &conn,
30671            "ok_tbl",
30672            &SqlWriteOptions {
30673                if_exists: SqlIfExists::Fail,
30674                index: true,
30675                index_label: Some(long_label),
30676                schema: None,
30677                dtype: None,
30678                method: SqlInsertMethod::Single,
30679                chunksize: None,
30680            },
30681        )
30682        .expect_err("64-char index label must exceed PG limit");
30683        assert!(
30684            matches!(err, IoError::Sql(msg) if msg.contains("index label") && msg.contains("63"))
30685        );
30686    }
30687
30688    #[test]
30689    fn write_sql_rejects_long_schema_name_on_pg_like_backend() {
30690        let conn = make_pg_like_recorder();
30691        let long_schema: String = std::iter::repeat_n('s', 64).collect();
30692        let frame =
30693            fp_frame::DataFrame::from_dict(&["x"], vec![("x", vec![Scalar::Int64(1)])]).unwrap();
30694        let err = write_sql_with_options(
30695            &frame,
30696            &conn,
30697            "ok_tbl",
30698            &SqlWriteOptions {
30699                if_exists: SqlIfExists::Fail,
30700                index: false,
30701                index_label: None,
30702                schema: Some(long_schema),
30703                dtype: None,
30704                method: SqlInsertMethod::Single,
30705                chunksize: None,
30706            },
30707        )
30708        .expect_err("64-char schema must exceed PG limit");
30709        assert!(matches!(err, IoError::Sql(msg) if msg.contains("schema") && msg.contains("63")));
30710    }
30711
30712    #[test]
30713    fn write_sql_just_at_the_boundary_is_accepted() {
30714        let conn = make_pg_like_recorder();
30715        // Exactly 63 chars: at the PG limit, must be accepted.
30716        let just_fits: String = std::iter::repeat_n('a', 63).collect();
30717        let frame = fp_frame::DataFrame::from_dict(
30718            &[just_fits.as_str()],
30719            vec![(just_fits.as_str(), vec![Scalar::Int64(1)])],
30720        )
30721        .unwrap();
30722        write_sql_with_options(
30723            &frame,
30724            &conn,
30725            "ok_tbl",
30726            &SqlWriteOptions {
30727                if_exists: SqlIfExists::Fail,
30728                index: false,
30729                index_label: None,
30730                schema: None,
30731                dtype: None,
30732                method: SqlInsertMethod::Single,
30733                chunksize: None,
30734            },
30735        )
30736        .expect("63-char column at boundary should be accepted");
30737    }
30738
30739    // ── list_sql_indexes / SqlConnection::list_indexes (br-bgv9 / fd90.28) ─
30740
30741    #[cfg(feature = "sql-sqlite")]
30742    #[test]
30743    fn list_sql_indexes_unknown_table_returns_empty() {
30744        let conn = make_sql_test_conn();
30745        let indexes = list_sql_indexes(&conn, "no_such_tbl", None).unwrap();
30746        assert!(indexes.is_empty());
30747    }
30748
30749    #[cfg(feature = "sql-sqlite")]
30750    #[test]
30751    fn list_sql_indexes_table_without_indexes() {
30752        let conn = make_sql_test_conn();
30753        super::SqlConnection::execute_batch(&conn, "CREATE TABLE plain (a INTEGER, b TEXT);")
30754            .unwrap();
30755        let indexes = list_sql_indexes(&conn, "plain", None).unwrap();
30756        assert!(indexes.is_empty());
30757    }
30758
30759    #[cfg(feature = "sql-sqlite")]
30760    #[test]
30761    fn list_sql_indexes_single_column() {
30762        let conn = make_sql_test_conn();
30763        super::SqlConnection::execute_batch(&conn, "CREATE TABLE events (id INTEGER, ts TEXT);")
30764            .unwrap();
30765        super::SqlConnection::execute_batch(&conn, "CREATE INDEX idx_events_ts ON events (ts);")
30766            .unwrap();
30767        let indexes = list_sql_indexes(&conn, "events", None).unwrap();
30768        assert_eq!(indexes.len(), 1);
30769        assert_eq!(indexes[0].name, "idx_events_ts");
30770        assert_eq!(indexes[0].columns, vec!["ts"]);
30771        assert!(!indexes[0].unique);
30772    }
30773
30774    #[cfg(feature = "sql-sqlite")]
30775    #[test]
30776    fn list_sql_indexes_unique_index() {
30777        let conn = make_sql_test_conn();
30778        super::SqlConnection::execute_batch(&conn, "CREATE TABLE users (id INTEGER, email TEXT);")
30779            .unwrap();
30780        super::SqlConnection::execute_batch(
30781            &conn,
30782            "CREATE UNIQUE INDEX idx_users_email ON users (email);",
30783        )
30784        .unwrap();
30785        let indexes = list_sql_indexes(&conn, "users", None).unwrap();
30786        assert_eq!(indexes.len(), 1);
30787        assert_eq!(indexes[0].name, "idx_users_email");
30788        assert_eq!(indexes[0].columns, vec!["email"]);
30789        assert!(indexes[0].unique);
30790    }
30791
30792    #[cfg(feature = "sql-sqlite")]
30793    #[test]
30794    fn list_sql_indexes_composite_columns_in_definition_order() {
30795        let conn = make_sql_test_conn();
30796        super::SqlConnection::execute_batch(
30797            &conn,
30798            "CREATE TABLE rolling (year INT, month INT, code TEXT, val REAL);",
30799        )
30800        .unwrap();
30801        super::SqlConnection::execute_batch(
30802            &conn,
30803            "CREATE INDEX idx_rolling_y_m_c ON rolling (year, month, code);",
30804        )
30805        .unwrap();
30806        let indexes = list_sql_indexes(&conn, "rolling", None).unwrap();
30807        assert_eq!(indexes.len(), 1);
30808        assert_eq!(indexes[0].columns, vec!["year", "month", "code"]);
30809    }
30810
30811    #[cfg(feature = "sql-sqlite")]
30812    #[test]
30813    fn list_sql_indexes_filters_pk_auto_index() {
30814        // INTEGER PRIMARY KEY in SQLite creates an automatic index that
30815        // SQLAlchemy.Inspector hides. We must hide it too — only the
30816        // explicit CREATE INDEX should surface.
30817        let conn = make_sql_test_conn();
30818        super::SqlConnection::execute_batch(
30819            &conn,
30820            "CREATE TABLE pk_only (id INTEGER PRIMARY KEY, name TEXT);",
30821        )
30822        .unwrap();
30823        super::SqlConnection::execute_batch(
30824            &conn,
30825            "CREATE INDEX idx_pk_only_name ON pk_only (name);",
30826        )
30827        .unwrap();
30828        let indexes = list_sql_indexes(&conn, "pk_only", None).unwrap();
30829        // Only the explicit user index should appear.
30830        assert_eq!(indexes.len(), 1);
30831        assert_eq!(indexes[0].name, "idx_pk_only_name");
30832    }
30833
30834    #[cfg(feature = "sql-sqlite")]
30835    #[test]
30836    fn list_sql_indexes_rejects_invalid_table_name() {
30837        let conn = make_sql_test_conn();
30838        let err = list_sql_indexes(&conn, "x; DROP TABLE users", None)
30839            .expect_err("must reject invalid identifier");
30840        assert!(matches!(err, IoError::Sql(msg) if msg.contains("invalid")));
30841    }
30842
30843    #[test]
30844    fn list_sql_indexes_default_impl_returns_empty() {
30845        struct NoIntrospection;
30846        impl super::SqlConnection for NoIntrospection {
30847            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
30848                Ok(SqlQueryResult {
30849                    columns: vec![],
30850                    rows: vec![],
30851                })
30852            }
30853            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
30854                Ok(())
30855            }
30856            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
30857                Ok(false)
30858            }
30859            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
30860                Ok(())
30861            }
30862            fn dtype_sql(&self, _dtype: DType) -> &'static str {
30863                "TEXT"
30864            }
30865            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
30866                "TEXT"
30867            }
30868        }
30869        assert!(
30870            list_sql_indexes(&NoIntrospection, "anything", None)
30871                .unwrap()
30872                .is_empty()
30873        );
30874    }
30875
30876    #[test]
30877    fn list_sql_indexes_routes_to_backend_override() {
30878        struct MultiSchemaIdx;
30879        impl super::SqlConnection for MultiSchemaIdx {
30880            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
30881                Ok(SqlQueryResult {
30882                    columns: vec![],
30883                    rows: vec![],
30884                })
30885            }
30886            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
30887                Ok(())
30888            }
30889            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
30890                Ok(false)
30891            }
30892            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
30893                Ok(())
30894            }
30895            fn dtype_sql(&self, _dtype: DType) -> &'static str {
30896                "TEXT"
30897            }
30898            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
30899                "TEXT"
30900            }
30901            fn supports_schemas(&self) -> bool {
30902                true
30903            }
30904            fn list_indexes(
30905                &self,
30906                table: &str,
30907                schema: Option<&str>,
30908            ) -> Result<Vec<SqlIndexSchema>, IoError> {
30909                if table == "events" && schema == Some("analytics") {
30910                    Ok(vec![
30911                        SqlIndexSchema {
30912                            name: "idx_events_ts".to_owned(),
30913                            columns: vec!["ts".to_owned()],
30914                            unique: false,
30915                        },
30916                        SqlIndexSchema {
30917                            name: "uq_events_uid".to_owned(),
30918                            columns: vec!["user_id".to_owned()],
30919                            unique: true,
30920                        },
30921                    ])
30922                } else {
30923                    Ok(vec![])
30924                }
30925            }
30926        }
30927        let conn = MultiSchemaIdx;
30928        let indexes = list_sql_indexes(&conn, "events", Some("analytics")).unwrap();
30929        assert_eq!(indexes.len(), 2);
30930        assert!(
30931            indexes
30932                .iter()
30933                .any(|i| i.unique && i.name == "uq_events_uid")
30934        );
30935        // Wrong schema → empty (override scopes by Some).
30936        assert!(
30937            list_sql_indexes(&conn, "events", Some("audit"))
30938                .unwrap()
30939                .is_empty()
30940        );
30941    }
30942
30943    // ── list_sql_foreign_keys / SqlConnection::list_foreign_keys
30944    //    (br-uht8 / fd90.29) ────────────────────────────────────────────────
30945
30946    #[cfg(feature = "sql-sqlite")]
30947    #[test]
30948    fn list_sql_foreign_keys_unknown_table_returns_empty() {
30949        let conn = make_sql_test_conn();
30950        let fks = list_sql_foreign_keys(&conn, "no_such_tbl", None).unwrap();
30951        assert!(fks.is_empty());
30952    }
30953
30954    #[cfg(feature = "sql-sqlite")]
30955    #[test]
30956    fn list_sql_foreign_keys_table_without_fk() {
30957        let conn = make_sql_test_conn();
30958        super::SqlConnection::execute_batch(&conn, "CREATE TABLE plain (a INTEGER, b TEXT);")
30959            .unwrap();
30960        let fks = list_sql_foreign_keys(&conn, "plain", None).unwrap();
30961        assert!(fks.is_empty());
30962    }
30963
30964    #[cfg(feature = "sql-sqlite")]
30965    #[test]
30966    fn list_sql_foreign_keys_single_column_fk() {
30967        let conn = make_sql_test_conn();
30968        super::SqlConnection::execute_batch(
30969            &conn,
30970            "CREATE TABLE parent (id INTEGER PRIMARY KEY, label TEXT);",
30971        )
30972        .unwrap();
30973        super::SqlConnection::execute_batch(
30974            &conn,
30975            "CREATE TABLE child (cid INTEGER, parent_id INTEGER, \
30976             FOREIGN KEY (parent_id) REFERENCES parent(id));",
30977        )
30978        .unwrap();
30979        let fks = list_sql_foreign_keys(&conn, "child", None).unwrap();
30980        assert_eq!(fks.len(), 1);
30981        assert_eq!(fks[0].columns, vec!["parent_id"]);
30982        assert_eq!(fks[0].referenced_table, "parent");
30983        assert_eq!(fks[0].referenced_columns, vec!["id"]);
30984        // SQLite PRAGMA does not surface constraint names.
30985        assert!(fks[0].constraint_name.is_none());
30986    }
30987
30988    #[cfg(feature = "sql-sqlite")]
30989    #[test]
30990    fn list_sql_foreign_keys_composite_fk_ordered_by_seq() {
30991        let conn = make_sql_test_conn();
30992        super::SqlConnection::execute_batch(
30993            &conn,
30994            "CREATE TABLE rolling ( \
30995                year INTEGER NOT NULL, \
30996                month INTEGER NOT NULL, \
30997                code TEXT NOT NULL, \
30998                PRIMARY KEY (year, month, code) \
30999             );",
31000        )
31001        .unwrap();
31002        super::SqlConnection::execute_batch(
31003            &conn,
31004            "CREATE TABLE rolling_fact ( \
31005                fact_id INTEGER, year INTEGER, month INTEGER, code TEXT, \
31006                FOREIGN KEY (year, month, code) \
31007                  REFERENCES rolling(year, month, code) \
31008             );",
31009        )
31010        .unwrap();
31011        let fks = list_sql_foreign_keys(&conn, "rolling_fact", None).unwrap();
31012        assert_eq!(fks.len(), 1);
31013        // Pairs preserved in declaration order (seq=0,1,2).
31014        assert_eq!(fks[0].columns, vec!["year", "month", "code"]);
31015        assert_eq!(fks[0].referenced_columns, vec!["year", "month", "code"]);
31016        assert_eq!(fks[0].referenced_table, "rolling");
31017    }
31018
31019    #[cfg(feature = "sql-sqlite")]
31020    #[test]
31021    fn list_sql_foreign_keys_multiple_fks_on_one_table() {
31022        let conn = make_sql_test_conn();
31023        super::SqlConnection::execute_batch(&conn, "CREATE TABLE users (id INTEGER PRIMARY KEY);")
31024            .unwrap();
31025        super::SqlConnection::execute_batch(&conn, "CREATE TABLE products (sku TEXT PRIMARY KEY);")
31026            .unwrap();
31027        super::SqlConnection::execute_batch(
31028            &conn,
31029            "CREATE TABLE orders ( \
31030                oid INTEGER, \
31031                user_id INTEGER, \
31032                product_sku TEXT, \
31033                FOREIGN KEY (user_id) REFERENCES users(id), \
31034                FOREIGN KEY (product_sku) REFERENCES products(sku) \
31035             );",
31036        )
31037        .unwrap();
31038        let fks = list_sql_foreign_keys(&conn, "orders", None).unwrap();
31039        assert_eq!(fks.len(), 2);
31040        let user_fk = fks.iter().find(|f| f.referenced_table == "users").unwrap();
31041        assert_eq!(user_fk.columns, vec!["user_id"]);
31042        assert_eq!(user_fk.referenced_columns, vec!["id"]);
31043        let prod_fk = fks
31044            .iter()
31045            .find(|f| f.referenced_table == "products")
31046            .unwrap();
31047        assert_eq!(prod_fk.columns, vec!["product_sku"]);
31048        assert_eq!(prod_fk.referenced_columns, vec!["sku"]);
31049    }
31050
31051    #[cfg(feature = "sql-sqlite")]
31052    #[test]
31053    fn list_sql_foreign_keys_rejects_invalid_table_name() {
31054        let conn = make_sql_test_conn();
31055        let err = list_sql_foreign_keys(&conn, "x; DROP TABLE users", None)
31056            .expect_err("must reject invalid identifier");
31057        assert!(matches!(err, IoError::Sql(msg) if msg.contains("invalid")));
31058    }
31059
31060    #[cfg(feature = "sql-sqlite")]
31061    #[test]
31062    fn list_sql_foreign_keys_resolves_implicit_pk_single_column() {
31063        // Per fd90.44: FOREIGN KEY (parent_id) REFERENCES parent
31064        // (no column list) is an implicit reference to parent's PK.
31065        // SQLite returns NULL for the 'to' column; we now resolve via
31066        // the parent's primary_key_columns.
31067        let conn = make_sql_test_conn();
31068        super::SqlConnection::execute_batch(
31069            &conn,
31070            "CREATE TABLE imp_parent (pid INTEGER PRIMARY KEY, label TEXT);",
31071        )
31072        .unwrap();
31073        super::SqlConnection::execute_batch(
31074            &conn,
31075            "CREATE TABLE imp_child ( \
31076                cid INTEGER, \
31077                parent_id INTEGER, \
31078                FOREIGN KEY (parent_id) REFERENCES imp_parent \
31079             );",
31080        )
31081        .unwrap();
31082        let fks = list_sql_foreign_keys(&conn, "imp_child", None).unwrap();
31083        assert_eq!(
31084            fks.len(),
31085            1,
31086            "implicit-PK FK must surface (was being silently dropped)"
31087        );
31088        assert_eq!(fks[0].columns, vec!["parent_id"]);
31089        assert_eq!(fks[0].referenced_table, "imp_parent");
31090        // resolved from parent's PK.
31091        assert_eq!(fks[0].referenced_columns, vec!["pid"]);
31092    }
31093
31094    #[cfg(feature = "sql-sqlite")]
31095    #[test]
31096    fn list_sql_foreign_keys_resolves_implicit_pk_composite() {
31097        // Composite FK with implicit reference to composite PK.
31098        let conn = make_sql_test_conn();
31099        super::SqlConnection::execute_batch(
31100            &conn,
31101            "CREATE TABLE imp_parent_comp ( \
31102                year INTEGER NOT NULL, \
31103                month INTEGER NOT NULL, \
31104                PRIMARY KEY (year, month) \
31105             );",
31106        )
31107        .unwrap();
31108        super::SqlConnection::execute_batch(
31109            &conn,
31110            "CREATE TABLE imp_child_comp ( \
31111                cid INTEGER, \
31112                fyear INTEGER NOT NULL, \
31113                fmonth INTEGER NOT NULL, \
31114                FOREIGN KEY (fyear, fmonth) REFERENCES imp_parent_comp \
31115             );",
31116        )
31117        .unwrap();
31118        let fks = list_sql_foreign_keys(&conn, "imp_child_comp", None).unwrap();
31119        assert_eq!(fks.len(), 1);
31120        assert_eq!(fks[0].columns, vec!["fyear", "fmonth"]);
31121        assert_eq!(fks[0].referenced_table, "imp_parent_comp");
31122        // Resolved from composite PK in declaration order.
31123        assert_eq!(fks[0].referenced_columns, vec!["year", "month"]);
31124    }
31125
31126    #[cfg(feature = "sql-sqlite")]
31127    #[test]
31128    fn list_sql_foreign_keys_explicit_columns_unchanged() {
31129        // Existing behavior preserved: explicit columns still
31130        // round-trip exactly as before fd90.44.
31131        let conn = make_sql_test_conn();
31132        super::SqlConnection::execute_batch(
31133            &conn,
31134            "CREATE TABLE exp_parent (pid INTEGER PRIMARY KEY);",
31135        )
31136        .unwrap();
31137        super::SqlConnection::execute_batch(
31138            &conn,
31139            "CREATE TABLE exp_child ( \
31140                cid INTEGER, \
31141                parent_id INTEGER, \
31142                FOREIGN KEY (parent_id) REFERENCES exp_parent(pid) \
31143             );",
31144        )
31145        .unwrap();
31146        let fks = list_sql_foreign_keys(&conn, "exp_child", None).unwrap();
31147        assert_eq!(fks.len(), 1);
31148        assert_eq!(fks[0].columns, vec!["parent_id"]);
31149        assert_eq!(fks[0].referenced_columns, vec!["pid"]);
31150    }
31151
31152    #[test]
31153    fn list_sql_foreign_keys_default_impl_returns_empty() {
31154        struct NoIntrospection;
31155        impl super::SqlConnection for NoIntrospection {
31156            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
31157                Ok(SqlQueryResult {
31158                    columns: vec![],
31159                    rows: vec![],
31160                })
31161            }
31162            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
31163                Ok(())
31164            }
31165            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
31166                Ok(false)
31167            }
31168            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
31169                Ok(())
31170            }
31171            fn dtype_sql(&self, _dtype: DType) -> &'static str {
31172                "TEXT"
31173            }
31174            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
31175                "TEXT"
31176            }
31177        }
31178        assert!(
31179            list_sql_foreign_keys(&NoIntrospection, "anything", None)
31180                .unwrap()
31181                .is_empty()
31182        );
31183    }
31184
31185    #[test]
31186    fn list_sql_foreign_keys_routes_to_backend_override() {
31187        struct MultiSchemaFk;
31188        impl super::SqlConnection for MultiSchemaFk {
31189            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
31190                Ok(SqlQueryResult {
31191                    columns: vec![],
31192                    rows: vec![],
31193                })
31194            }
31195            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
31196                Ok(())
31197            }
31198            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
31199                Ok(false)
31200            }
31201            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
31202                Ok(())
31203            }
31204            fn dtype_sql(&self, _dtype: DType) -> &'static str {
31205                "TEXT"
31206            }
31207            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
31208                "TEXT"
31209            }
31210            fn supports_schemas(&self) -> bool {
31211                true
31212            }
31213            fn list_foreign_keys(
31214                &self,
31215                table: &str,
31216                schema: Option<&str>,
31217            ) -> Result<Vec<SqlForeignKeySchema>, IoError> {
31218                if table == "orders" && schema == Some("sales") {
31219                    Ok(vec![SqlForeignKeySchema {
31220                        constraint_name: Some("orders_user_fk".to_owned()),
31221                        columns: vec!["user_id".to_owned()],
31222                        referenced_table: "users".to_owned(),
31223                        referenced_columns: vec!["id".to_owned()],
31224                    }])
31225                } else {
31226                    Ok(vec![])
31227                }
31228            }
31229        }
31230        let conn = MultiSchemaFk;
31231        let fks = list_sql_foreign_keys(&conn, "orders", Some("sales")).unwrap();
31232        assert_eq!(fks.len(), 1);
31233        assert_eq!(fks[0].constraint_name.as_deref(), Some("orders_user_fk"));
31234        assert_eq!(fks[0].referenced_table, "users");
31235        // Wrong schema → empty (override scopes by Some).
31236        assert!(
31237            list_sql_foreign_keys(&conn, "orders", Some("audit"))
31238                .unwrap()
31239                .is_empty()
31240        );
31241    }
31242
31243    // ── list_sql_views / SqlConnection::list_views (br-gm3r / fd90.30) ────
31244
31245    #[cfg(feature = "sql-sqlite")]
31246    #[test]
31247    fn list_sql_views_empty_db_returns_empty() {
31248        let conn = make_sql_test_conn();
31249        let views = list_sql_views(&conn, None).unwrap();
31250        assert!(views.is_empty());
31251    }
31252
31253    #[cfg(feature = "sql-sqlite")]
31254    #[test]
31255    fn list_sql_views_returns_user_views_sorted() {
31256        let conn = make_sql_test_conn();
31257        super::SqlConnection::execute_batch(&conn, "CREATE TABLE base (id INTEGER, val TEXT);")
31258            .unwrap();
31259        super::SqlConnection::execute_batch(
31260            &conn,
31261            "CREATE VIEW zebra_view AS SELECT id FROM base;",
31262        )
31263        .unwrap();
31264        super::SqlConnection::execute_batch(
31265            &conn,
31266            "CREATE VIEW alpha_view AS SELECT val FROM base;",
31267        )
31268        .unwrap();
31269        let views = list_sql_views(&conn, None).unwrap();
31270        assert_eq!(views, vec!["alpha_view", "zebra_view"]);
31271    }
31272
31273    #[cfg(feature = "sql-sqlite")]
31274    #[test]
31275    fn list_sql_views_separated_from_list_tables() {
31276        // list_views must NOT surface tables; list_tables must NOT surface
31277        // views. The two buckets are disjoint per SQLAlchemy.Inspector.
31278        let conn = make_sql_test_conn();
31279        super::SqlConnection::execute_batch(&conn, "CREATE TABLE just_tbl (x INTEGER);").unwrap();
31280        super::SqlConnection::execute_batch(
31281            &conn,
31282            "CREATE VIEW just_view AS SELECT x FROM just_tbl;",
31283        )
31284        .unwrap();
31285
31286        let tables = list_sql_tables(&conn, None).unwrap();
31287        let views = list_sql_views(&conn, None).unwrap();
31288        assert_eq!(tables, vec!["just_tbl"]);
31289        assert_eq!(views, vec!["just_view"]);
31290        assert!(!tables.contains(&"just_view".to_owned()));
31291        assert!(!views.contains(&"just_tbl".to_owned()));
31292    }
31293
31294    #[cfg(feature = "sql-sqlite")]
31295    #[test]
31296    fn list_sql_views_schema_silently_ignored_on_sqlite() {
31297        let conn = make_sql_test_conn();
31298        super::SqlConnection::execute_batch(&conn, "CREATE TABLE t (x INTEGER);").unwrap();
31299        super::SqlConnection::execute_batch(&conn, "CREATE VIEW v AS SELECT x FROM t;").unwrap();
31300        let with_schema =
31301            list_sql_views(&conn, Some("ignored_on_sqlite")).expect("schema arg must not error");
31302        let without_schema = list_sql_views(&conn, None).unwrap();
31303        assert_eq!(with_schema, without_schema);
31304    }
31305
31306    #[test]
31307    fn list_sql_views_default_impl_returns_empty() {
31308        struct NoIntrospection;
31309        impl super::SqlConnection for NoIntrospection {
31310            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
31311                Ok(SqlQueryResult {
31312                    columns: vec![],
31313                    rows: vec![],
31314                })
31315            }
31316            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
31317                Ok(())
31318            }
31319            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
31320                Ok(false)
31321            }
31322            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
31323                Ok(())
31324            }
31325            fn dtype_sql(&self, _dtype: DType) -> &'static str {
31326                "TEXT"
31327            }
31328            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
31329                "TEXT"
31330            }
31331        }
31332        let conn = NoIntrospection;
31333        assert!(list_sql_views(&conn, None).unwrap().is_empty());
31334        assert!(list_sql_views(&conn, Some("any")).unwrap().is_empty());
31335    }
31336
31337    #[test]
31338    fn list_sql_views_routes_schema_to_backend_override() {
31339        struct MultiSchemaViews;
31340        impl super::SqlConnection for MultiSchemaViews {
31341            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
31342                Ok(SqlQueryResult {
31343                    columns: vec![],
31344                    rows: vec![],
31345                })
31346            }
31347            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
31348                Ok(())
31349            }
31350            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
31351                Ok(false)
31352            }
31353            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
31354                Ok(())
31355            }
31356            fn dtype_sql(&self, _dtype: DType) -> &'static str {
31357                "TEXT"
31358            }
31359            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
31360                "TEXT"
31361            }
31362            fn supports_schemas(&self) -> bool {
31363                true
31364            }
31365            fn list_views(&self, schema: Option<&str>) -> Result<Vec<String>, IoError> {
31366                Ok(match schema {
31367                    Some("reporting") => vec!["daily".to_owned(), "weekly".to_owned()],
31368                    Some("audit") => vec!["log_view".to_owned()],
31369                    _ => vec![],
31370                })
31371            }
31372        }
31373        let conn = MultiSchemaViews;
31374        assert_eq!(
31375            list_sql_views(&conn, Some("reporting")).unwrap(),
31376            vec!["daily", "weekly"]
31377        );
31378        assert_eq!(
31379            list_sql_views(&conn, Some("audit")).unwrap(),
31380            vec!["log_view"]
31381        );
31382        assert!(list_sql_views(&conn, None).unwrap().is_empty());
31383    }
31384
31385    // ── list_sql_unique_constraints / SqlConnection::list_unique_constraints
31386    //    (br-sh4v / fd90.31) ────────────────────────────────────────────────
31387
31388    #[cfg(feature = "sql-sqlite")]
31389    #[test]
31390    fn list_sql_unique_constraints_unknown_table_returns_empty() {
31391        let conn = make_sql_test_conn();
31392        let uqs = list_sql_unique_constraints(&conn, "no_such", None).unwrap();
31393        assert!(uqs.is_empty());
31394    }
31395
31396    #[cfg(feature = "sql-sqlite")]
31397    #[test]
31398    fn list_sql_unique_constraints_table_without_uq() {
31399        let conn = make_sql_test_conn();
31400        super::SqlConnection::execute_batch(&conn, "CREATE TABLE plain (a INTEGER, b TEXT);")
31401            .unwrap();
31402        let uqs = list_sql_unique_constraints(&conn, "plain", None).unwrap();
31403        assert!(uqs.is_empty());
31404    }
31405
31406    #[cfg(feature = "sql-sqlite")]
31407    #[test]
31408    fn list_sql_unique_constraints_inline_unique() {
31409        let conn = make_sql_test_conn();
31410        super::SqlConnection::execute_batch(
31411            &conn,
31412            "CREATE TABLE users (id INTEGER PRIMARY KEY, email TEXT UNIQUE);",
31413        )
31414        .unwrap();
31415        let uqs = list_sql_unique_constraints(&conn, "users", None).unwrap();
31416        assert_eq!(uqs.len(), 1);
31417        assert_eq!(uqs[0].columns, vec!["email"]);
31418        // SQLite gives backend-generated names like sqlite_autoindex_users_1.
31419        assert!(
31420            uqs[0].name.starts_with("sqlite_autoindex_users_"),
31421            "expected sqlite_autoindex_ name; got {}",
31422            uqs[0].name
31423        );
31424    }
31425
31426    #[cfg(feature = "sql-sqlite")]
31427    #[test]
31428    fn list_sql_unique_constraints_composite_table_constraint() {
31429        let conn = make_sql_test_conn();
31430        super::SqlConnection::execute_batch(
31431            &conn,
31432            "CREATE TABLE rolling ( \
31433                year INTEGER, month INTEGER, code TEXT, val REAL, \
31434                UNIQUE (year, month, code) \
31435             );",
31436        )
31437        .unwrap();
31438        let uqs = list_sql_unique_constraints(&conn, "rolling", None).unwrap();
31439        assert_eq!(uqs.len(), 1);
31440        assert_eq!(uqs[0].columns, vec!["year", "month", "code"]);
31441    }
31442
31443    #[cfg(feature = "sql-sqlite")]
31444    #[test]
31445    fn list_sql_unique_constraints_disjoint_from_create_unique_index() {
31446        // Per SQLAlchemy: get_unique_constraints surfaces declared UNIQUE
31447        // constraints (origin='u'); get_indexes surfaces user-created
31448        // CREATE UNIQUE INDEX (origin='c'). The two must be disjoint.
31449        let conn = make_sql_test_conn();
31450        super::SqlConnection::execute_batch(
31451            &conn,
31452            "CREATE TABLE mixed ( \
31453                a INTEGER, \
31454                b TEXT, \
31455                c TEXT, \
31456                UNIQUE (a) \
31457             );",
31458        )
31459        .unwrap();
31460        super::SqlConnection::execute_batch(&conn, "CREATE UNIQUE INDEX idx_mixed_b ON mixed (b);")
31461            .unwrap();
31462
31463        let uqs = list_sql_unique_constraints(&conn, "mixed", None).unwrap();
31464        let idxs = list_sql_indexes(&conn, "mixed", None).unwrap();
31465
31466        // The UNIQUE constraint is in uqs only.
31467        assert_eq!(uqs.len(), 1);
31468        assert_eq!(uqs[0].columns, vec!["a"]);
31469        // The CREATE UNIQUE INDEX is in idxs only.
31470        assert_eq!(idxs.len(), 1);
31471        assert_eq!(idxs[0].name, "idx_mixed_b");
31472        assert!(idxs[0].unique);
31473        assert_eq!(idxs[0].columns, vec!["b"]);
31474
31475        // No overlap by name (uqs uses sqlite_autoindex_, idxs uses idx_).
31476        assert!(!uqs.iter().any(|u| u.name == "idx_mixed_b"));
31477        assert!(!idxs.iter().any(|i| i.name.starts_with("sqlite_autoindex_")));
31478    }
31479
31480    #[cfg(feature = "sql-sqlite")]
31481    #[test]
31482    fn list_sql_unique_constraints_rejects_invalid_table_name() {
31483        let conn = make_sql_test_conn();
31484        let err = list_sql_unique_constraints(&conn, "x; DROP TABLE users", None)
31485            .expect_err("must reject invalid identifier");
31486        assert!(matches!(err, IoError::Sql(msg) if msg.contains("invalid")));
31487    }
31488
31489    #[test]
31490    fn list_sql_unique_constraints_default_impl_returns_empty() {
31491        struct NoIntrospection;
31492        impl super::SqlConnection for NoIntrospection {
31493            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
31494                Ok(SqlQueryResult {
31495                    columns: vec![],
31496                    rows: vec![],
31497                })
31498            }
31499            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
31500                Ok(())
31501            }
31502            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
31503                Ok(false)
31504            }
31505            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
31506                Ok(())
31507            }
31508            fn dtype_sql(&self, _dtype: DType) -> &'static str {
31509                "TEXT"
31510            }
31511            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
31512                "TEXT"
31513            }
31514        }
31515        assert!(
31516            list_sql_unique_constraints(&NoIntrospection, "anything", None)
31517                .unwrap()
31518                .is_empty()
31519        );
31520    }
31521
31522    #[test]
31523    fn list_sql_unique_constraints_routes_to_backend_override() {
31524        struct MultiSchemaUq;
31525        impl super::SqlConnection for MultiSchemaUq {
31526            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
31527                Ok(SqlQueryResult {
31528                    columns: vec![],
31529                    rows: vec![],
31530                })
31531            }
31532            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
31533                Ok(())
31534            }
31535            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
31536                Ok(false)
31537            }
31538            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
31539                Ok(())
31540            }
31541            fn dtype_sql(&self, _dtype: DType) -> &'static str {
31542                "TEXT"
31543            }
31544            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
31545                "TEXT"
31546            }
31547            fn supports_schemas(&self) -> bool {
31548                true
31549            }
31550            fn list_unique_constraints(
31551                &self,
31552                table: &str,
31553                schema: Option<&str>,
31554            ) -> Result<Vec<SqlUniqueConstraintSchema>, IoError> {
31555                if table == "users" && schema == Some("public") {
31556                    Ok(vec![SqlUniqueConstraintSchema {
31557                        name: "users_email_key".to_owned(),
31558                        columns: vec!["email".to_owned()],
31559                    }])
31560                } else {
31561                    Ok(vec![])
31562                }
31563            }
31564        }
31565        let conn = MultiSchemaUq;
31566        let uqs = list_sql_unique_constraints(&conn, "users", Some("public")).unwrap();
31567        assert_eq!(uqs.len(), 1);
31568        assert_eq!(uqs[0].name, "users_email_key");
31569        assert!(
31570            list_sql_unique_constraints(&conn, "users", Some("audit"))
31571                .unwrap()
31572                .is_empty()
31573        );
31574    }
31575
31576    // ── sql_table_comment / SqlConnection::table_comment (br-yu3w / fd90.32) ─
31577
31578    #[cfg(feature = "sql-sqlite")]
31579    #[test]
31580    fn sql_table_comment_returns_none_on_sqlite() {
31581        // SQLite has no native table-comment storage; the trait default
31582        // returns None even for a real table.
31583        let conn = make_sql_test_conn();
31584        super::SqlConnection::execute_batch(&conn, "CREATE TABLE t (x INTEGER);").unwrap();
31585        let comment = sql_table_comment(&conn, "t", None).unwrap();
31586        assert!(comment.is_none());
31587    }
31588
31589    #[cfg(feature = "sql-sqlite")]
31590    #[test]
31591    fn sql_table_comment_returns_none_on_sqlite_for_unknown_table() {
31592        let conn = make_sql_test_conn();
31593        let comment = sql_table_comment(&conn, "no_such", None).unwrap();
31594        assert!(comment.is_none());
31595    }
31596
31597    #[test]
31598    fn sql_table_comment_default_impl_returns_none() {
31599        struct NoIntrospection;
31600        impl super::SqlConnection for NoIntrospection {
31601            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
31602                Ok(SqlQueryResult {
31603                    columns: vec![],
31604                    rows: vec![],
31605                })
31606            }
31607            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
31608                Ok(())
31609            }
31610            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
31611                Ok(false)
31612            }
31613            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
31614                Ok(())
31615            }
31616            fn dtype_sql(&self, _dtype: DType) -> &'static str {
31617                "TEXT"
31618            }
31619            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
31620                "TEXT"
31621            }
31622        }
31623        let conn = NoIntrospection;
31624        assert!(
31625            sql_table_comment(&conn, "anything", None)
31626                .unwrap()
31627                .is_none()
31628        );
31629    }
31630
31631    #[test]
31632    fn sql_table_comment_routes_to_backend_override() {
31633        struct PgLikeStub;
31634        impl super::SqlConnection for PgLikeStub {
31635            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
31636                Ok(SqlQueryResult {
31637                    columns: vec![],
31638                    rows: vec![],
31639                })
31640            }
31641            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
31642                Ok(())
31643            }
31644            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
31645                Ok(false)
31646            }
31647            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
31648                Ok(())
31649            }
31650            fn dtype_sql(&self, _dtype: DType) -> &'static str {
31651                "TEXT"
31652            }
31653            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
31654                "TEXT"
31655            }
31656            fn supports_schemas(&self) -> bool {
31657                true
31658            }
31659            fn table_comment(
31660                &self,
31661                table: &str,
31662                schema: Option<&str>,
31663            ) -> Result<Option<String>, IoError> {
31664                if table == "users" && schema == Some("public") {
31665                    Ok(Some("Customer accounts table".to_owned()))
31666                } else {
31667                    Ok(None)
31668                }
31669            }
31670        }
31671        let conn = PgLikeStub;
31672        assert_eq!(
31673            sql_table_comment(&conn, "users", Some("public"))
31674                .unwrap()
31675                .as_deref(),
31676            Some("Customer accounts table")
31677        );
31678        assert!(
31679            sql_table_comment(&conn, "users", Some("audit"))
31680                .unwrap()
31681                .is_none()
31682        );
31683        assert!(
31684            sql_table_comment(&conn, "missing", Some("public"))
31685                .unwrap()
31686                .is_none()
31687        );
31688    }
31689
31690    #[test]
31691    fn sql_table_comment_propagates_backend_error() {
31692        struct BrokenIntrospection;
31693        impl super::SqlConnection for BrokenIntrospection {
31694            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
31695                Ok(SqlQueryResult {
31696                    columns: vec![],
31697                    rows: vec![],
31698                })
31699            }
31700            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
31701                Ok(())
31702            }
31703            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
31704                Ok(false)
31705            }
31706            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
31707                Ok(())
31708            }
31709            fn dtype_sql(&self, _dtype: DType) -> &'static str {
31710                "TEXT"
31711            }
31712            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
31713                "TEXT"
31714            }
31715            fn table_comment(
31716                &self,
31717                _table: &str,
31718                _schema: Option<&str>,
31719            ) -> Result<Option<String>, IoError> {
31720                Err(IoError::Sql(
31721                    "permission denied for pg_description".to_owned(),
31722                ))
31723            }
31724        }
31725        let conn = BrokenIntrospection;
31726        let err =
31727            sql_table_comment(&conn, "anything", None).expect_err("backend error must surface");
31728        assert!(matches!(err, IoError::Sql(msg) if msg.contains("permission denied")));
31729    }
31730
31731    // ── SqlWriteOptions::chunksize (br-ls9z / fd90.33) ────────────────────
31732
31733    #[cfg(feature = "sql-sqlite")]
31734    #[test]
31735    fn write_sql_chunksize_zero_rejected() {
31736        let conn = make_sql_test_conn();
31737        let frame =
31738            fp_frame::DataFrame::from_dict(&["x"], vec![("x", vec![Scalar::Int64(1)])]).unwrap();
31739        let err = write_sql_with_options(
31740            &frame,
31741            &conn,
31742            "t",
31743            &SqlWriteOptions {
31744                if_exists: SqlIfExists::Fail,
31745                index: false,
31746                index_label: None,
31747                schema: None,
31748                dtype: None,
31749                method: SqlInsertMethod::Single,
31750                chunksize: Some(0),
31751            },
31752        )
31753        .expect_err("chunksize=0 must be rejected");
31754        assert!(matches!(err, IoError::Sql(msg) if msg.contains("chunksize")));
31755    }
31756
31757    #[cfg(feature = "sql-sqlite")]
31758    #[test]
31759    fn write_sql_chunksize_none_preserves_single_transaction_semantics() {
31760        // 5 rows, chunksize=None — should round-trip cleanly into one
31761        // transaction (same as before fd90.33 landed).
31762        let conn = make_sql_test_conn();
31763        let frame = fp_frame::DataFrame::from_dict(
31764            &["id"],
31765            vec![(
31766                "id",
31767                vec![
31768                    Scalar::Int64(1),
31769                    Scalar::Int64(2),
31770                    Scalar::Int64(3),
31771                    Scalar::Int64(4),
31772                    Scalar::Int64(5),
31773                ],
31774            )],
31775        )
31776        .unwrap();
31777        write_sql_with_options(
31778            &frame,
31779            &conn,
31780            "no_chunk",
31781            &SqlWriteOptions {
31782                if_exists: SqlIfExists::Fail,
31783                index: false,
31784                index_label: None,
31785                schema: None,
31786                dtype: None,
31787                method: SqlInsertMethod::Single,
31788                chunksize: None,
31789            },
31790        )
31791        .unwrap();
31792        let count =
31793            super::SqlConnection::query(&conn, "SELECT COUNT(*) FROM no_chunk", &[]).unwrap();
31794        assert_eq!(count.rows[0][0], Scalar::Int64(5));
31795    }
31796
31797    #[cfg(feature = "sql-sqlite")]
31798    #[test]
31799    fn write_sql_single_chunksize_round_trips_all_rows() {
31800        // 5 rows with chunksize=2: chunks of (2, 2, 1). All rows must
31801        // round-trip and the table must contain every row regardless
31802        // of how the chunks committed.
31803        let conn = make_sql_test_conn();
31804        let frame = fp_frame::DataFrame::from_dict(
31805            &["id"],
31806            vec![(
31807                "id",
31808                vec![
31809                    Scalar::Int64(1),
31810                    Scalar::Int64(2),
31811                    Scalar::Int64(3),
31812                    Scalar::Int64(4),
31813                    Scalar::Int64(5),
31814                ],
31815            )],
31816        )
31817        .unwrap();
31818        write_sql_with_options(
31819            &frame,
31820            &conn,
31821            "chunked",
31822            &SqlWriteOptions {
31823                if_exists: SqlIfExists::Fail,
31824                index: false,
31825                index_label: None,
31826                schema: None,
31827                dtype: None,
31828                method: SqlInsertMethod::Single,
31829                chunksize: Some(2),
31830            },
31831        )
31832        .unwrap();
31833        let result =
31834            super::SqlConnection::query(&conn, "SELECT id FROM chunked ORDER BY id", &[]).unwrap();
31835        let ids: Vec<i64> = result
31836            .rows
31837            .iter()
31838            .map(|r| match &r[0] {
31839                Scalar::Int64(v) => *v,
31840                other => unreachable!("unexpected scalar: {other:?}"),
31841            })
31842            .collect();
31843        assert_eq!(ids, vec![1, 2, 3, 4, 5]);
31844    }
31845
31846    #[test]
31847    fn write_sql_single_chunksize_dispatches_correct_chunk_counts() {
31848        // Recording stub verifies the chunk boundaries.
31849        use std::cell::RefCell;
31850        struct Recorder {
31851            row_counts: RefCell<Vec<usize>>,
31852        }
31853        impl super::SqlConnection for Recorder {
31854            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
31855                Ok(SqlQueryResult {
31856                    columns: vec![],
31857                    rows: vec![],
31858                })
31859            }
31860            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
31861                Ok(())
31862            }
31863            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
31864                Ok(false)
31865            }
31866            fn insert_rows(&self, _sql: &str, rows: &[Vec<Scalar>]) -> Result<(), IoError> {
31867                self.row_counts.borrow_mut().push(rows.len());
31868                Ok(())
31869            }
31870            fn dtype_sql(&self, _dtype: DType) -> &'static str {
31871                "TEXT"
31872            }
31873            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
31874                "TEXT"
31875            }
31876        }
31877        let conn = Recorder {
31878            row_counts: RefCell::new(vec![]),
31879        };
31880        let frame = fp_frame::DataFrame::from_dict(
31881            &["x"],
31882            vec![(
31883                "x",
31884                vec![
31885                    Scalar::Int64(1),
31886                    Scalar::Int64(2),
31887                    Scalar::Int64(3),
31888                    Scalar::Int64(4),
31889                    Scalar::Int64(5),
31890                ],
31891            )],
31892        )
31893        .unwrap();
31894        write_sql_with_options(
31895            &frame,
31896            &conn,
31897            "chunked",
31898            &SqlWriteOptions {
31899                if_exists: SqlIfExists::Fail,
31900                index: false,
31901                index_label: None,
31902                schema: None,
31903                dtype: None,
31904                method: SqlInsertMethod::Single,
31905                chunksize: Some(2),
31906            },
31907        )
31908        .unwrap();
31909        // Single mode: each chunk submits a slice of rows to insert_rows.
31910        // chunks of size 2, 2, 1 → 3 calls with row counts [2, 2, 1].
31911        assert_eq!(*conn.row_counts.borrow(), vec![2usize, 2, 1]);
31912    }
31913
31914    #[test]
31915    fn write_sql_multi_chunksize_takes_min_with_param_cap() {
31916        // Multi mode with max_param_count=10, ncols=2 → param chunk = 5
31917        // rows. chunksize=3 should win (min(3, 5) = 3).
31918        // Multi mode flattens each chunk to a single insert_rows call
31919        // where rows[0].len() = chunk_size * ncols.
31920        use std::cell::RefCell;
31921        struct ParamCapRecorder {
31922            row_counts: RefCell<Vec<usize>>,
31923        }
31924        impl super::SqlConnection for ParamCapRecorder {
31925            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
31926                Ok(SqlQueryResult {
31927                    columns: vec![],
31928                    rows: vec![],
31929                })
31930            }
31931            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
31932                Ok(())
31933            }
31934            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
31935                Ok(false)
31936            }
31937            fn insert_rows(&self, _sql: &str, rows: &[Vec<Scalar>]) -> Result<(), IoError> {
31938                // Multi mode passes a single flattened "row" per chunk.
31939                self.row_counts
31940                    .borrow_mut()
31941                    .push(rows.first().map_or(0, std::vec::Vec::len));
31942                Ok(())
31943            }
31944            fn dtype_sql(&self, _dtype: DType) -> &'static str {
31945                "TEXT"
31946            }
31947            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
31948                "TEXT"
31949            }
31950            fn max_param_count(&self) -> Option<usize> {
31951                Some(10)
31952            }
31953        }
31954        let conn = ParamCapRecorder {
31955            row_counts: RefCell::new(vec![]),
31956        };
31957        let frame = fp_frame::DataFrame::from_dict(
31958            &["a", "b"],
31959            vec![
31960                (
31961                    "a",
31962                    vec![
31963                        Scalar::Int64(1),
31964                        Scalar::Int64(2),
31965                        Scalar::Int64(3),
31966                        Scalar::Int64(4),
31967                        Scalar::Int64(5),
31968                    ],
31969                ),
31970                (
31971                    "b",
31972                    vec![
31973                        Scalar::Int64(10),
31974                        Scalar::Int64(20),
31975                        Scalar::Int64(30),
31976                        Scalar::Int64(40),
31977                        Scalar::Int64(50),
31978                    ],
31979                ),
31980            ],
31981        )
31982        .unwrap();
31983        write_sql_with_options(
31984            &frame,
31985            &conn,
31986            "chunked",
31987            &SqlWriteOptions {
31988                if_exists: SqlIfExists::Fail,
31989                index: false,
31990                index_label: None,
31991                schema: None,
31992                dtype: None,
31993                method: SqlInsertMethod::Multi,
31994                chunksize: Some(3),
31995            },
31996        )
31997        .unwrap();
31998        // chunksize=3 wins over param cap (5). 5 rows / 3 per chunk = 2
31999        // chunks (3, 2). Flat scalars per chunk: 3*2=6 then 2*2=4.
32000        assert_eq!(*conn.row_counts.borrow(), vec![6usize, 4]);
32001    }
32002
32003    #[test]
32004    fn write_sql_multi_chunksize_param_cap_wins_when_smaller() {
32005        // Param cap = 4 (ncols=2 → 2 rows/chunk). chunksize=10 (loose).
32006        // Effective chunk = min(10, 2) = 2.
32007        use std::cell::RefCell;
32008        struct TightCap {
32009            row_counts: RefCell<Vec<usize>>,
32010        }
32011        impl super::SqlConnection for TightCap {
32012            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
32013                Ok(SqlQueryResult {
32014                    columns: vec![],
32015                    rows: vec![],
32016                })
32017            }
32018            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
32019                Ok(())
32020            }
32021            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
32022                Ok(false)
32023            }
32024            fn insert_rows(&self, _sql: &str, rows: &[Vec<Scalar>]) -> Result<(), IoError> {
32025                self.row_counts
32026                    .borrow_mut()
32027                    .push(rows.first().map_or(0, std::vec::Vec::len));
32028                Ok(())
32029            }
32030            fn dtype_sql(&self, _dtype: DType) -> &'static str {
32031                "TEXT"
32032            }
32033            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
32034                "TEXT"
32035            }
32036            fn max_param_count(&self) -> Option<usize> {
32037                Some(4)
32038            }
32039        }
32040        let conn = TightCap {
32041            row_counts: RefCell::new(vec![]),
32042        };
32043        let frame = fp_frame::DataFrame::from_dict(
32044            &["a", "b"],
32045            vec![
32046                (
32047                    "a",
32048                    vec![
32049                        Scalar::Int64(1),
32050                        Scalar::Int64(2),
32051                        Scalar::Int64(3),
32052                        Scalar::Int64(4),
32053                        Scalar::Int64(5),
32054                    ],
32055                ),
32056                (
32057                    "b",
32058                    vec![
32059                        Scalar::Int64(10),
32060                        Scalar::Int64(20),
32061                        Scalar::Int64(30),
32062                        Scalar::Int64(40),
32063                        Scalar::Int64(50),
32064                    ],
32065                ),
32066            ],
32067        )
32068        .unwrap();
32069        write_sql_with_options(
32070            &frame,
32071            &conn,
32072            "chunked",
32073            &SqlWriteOptions {
32074                if_exists: SqlIfExists::Fail,
32075                index: false,
32076                index_label: None,
32077                schema: None,
32078                dtype: None,
32079                method: SqlInsertMethod::Multi,
32080                chunksize: Some(10),
32081            },
32082        )
32083        .unwrap();
32084        // 5 rows / 2 per chunk = 3 chunks (2, 2, 1). Flat scalars: 4, 4, 2.
32085        assert_eq!(*conn.row_counts.borrow(), vec![4usize, 4, 2]);
32086    }
32087
32088    // ── SqlReadOptions::columns (br-d3e9 / fd90.34) ──────────────────────
32089
32090    #[cfg(feature = "sql-sqlite")]
32091    #[test]
32092    fn read_sql_table_with_options_columns_none_selects_all() {
32093        let conn = make_sql_test_conn();
32094        super::SqlConnection::execute_batch(
32095            &conn,
32096            "CREATE TABLE projection_default (a INTEGER, b TEXT, c REAL);",
32097        )
32098        .unwrap();
32099        super::SqlConnection::execute_batch(
32100            &conn,
32101            "INSERT INTO projection_default VALUES (1, 'x', 1.5);",
32102        )
32103        .unwrap();
32104        let frame = read_sql_table_with_options(
32105            &conn,
32106            "projection_default",
32107            &SqlReadOptions {
32108                columns: None,
32109                ..Default::default()
32110            },
32111        )
32112        .unwrap();
32113        assert_eq!(frame.column_names(), vec!["a", "b", "c"]);
32114    }
32115
32116    #[cfg(feature = "sql-sqlite")]
32117    #[test]
32118    fn read_sql_table_with_options_columns_projects_subset() {
32119        let conn = make_sql_test_conn();
32120        super::SqlConnection::execute_batch(
32121            &conn,
32122            "CREATE TABLE projection (id INTEGER, name TEXT, ts TEXT, value REAL);",
32123        )
32124        .unwrap();
32125        super::SqlConnection::execute_batch(
32126            &conn,
32127            "INSERT INTO projection VALUES (1, 'a', '2024-01-01', 1.5), \
32128                                            (2, 'b', '2024-01-02', 2.5);",
32129        )
32130        .unwrap();
32131        let frame = read_sql_table_with_options(
32132            &conn,
32133            "projection",
32134            &SqlReadOptions {
32135                columns: Some(vec!["id".to_owned(), "name".to_owned()]),
32136                ..Default::default()
32137            },
32138        )
32139        .unwrap();
32140        // Only id + name, in that order.
32141        assert_eq!(frame.column_names(), vec!["id", "name"]);
32142        assert_eq!(frame.column("id").unwrap().values()[0], Scalar::Int64(1));
32143        assert_eq!(
32144            frame.column("name").unwrap().values()[0],
32145            Scalar::Utf8("a".into())
32146        );
32147    }
32148
32149    #[cfg(feature = "sql-sqlite")]
32150    #[test]
32151    fn read_sql_table_with_options_columns_preserves_specified_order() {
32152        // pandas: pd.read_sql_table(t, con, columns=['c', 'a']) →
32153        // returns ['c', 'a'] in that exact order, NOT alphabetical.
32154        let conn = make_sql_test_conn();
32155        super::SqlConnection::execute_batch(
32156            &conn,
32157            "CREATE TABLE ordered_proj (a INT, b INT, c INT);",
32158        )
32159        .unwrap();
32160        super::SqlConnection::execute_batch(&conn, "INSERT INTO ordered_proj VALUES (1, 2, 3);")
32161            .unwrap();
32162        let frame = read_sql_table_with_options(
32163            &conn,
32164            "ordered_proj",
32165            &SqlReadOptions {
32166                columns: Some(vec!["c".to_owned(), "a".to_owned()]),
32167                ..Default::default()
32168            },
32169        )
32170        .unwrap();
32171        assert_eq!(frame.column_names(), vec!["c", "a"]);
32172    }
32173
32174    #[cfg(feature = "sql-sqlite")]
32175    #[test]
32176    fn read_sql_table_with_options_columns_empty_vec_rejected() {
32177        let conn = make_sql_test_conn();
32178        super::SqlConnection::execute_batch(&conn, "CREATE TABLE t (x INTEGER);").unwrap();
32179        let err = read_sql_table_with_options(
32180            &conn,
32181            "t",
32182            &SqlReadOptions {
32183                columns: Some(vec![]),
32184                ..Default::default()
32185            },
32186        )
32187        .expect_err("empty columns must be rejected");
32188        assert!(matches!(err, IoError::Sql(msg) if msg.contains("columns must be non-empty")));
32189    }
32190
32191    #[cfg(feature = "sql-sqlite")]
32192    #[test]
32193    fn read_sql_table_with_options_columns_invalid_name_rejected() {
32194        let conn = make_sql_test_conn();
32195        super::SqlConnection::execute_batch(&conn, "CREATE TABLE t (x INTEGER);").unwrap();
32196        let err = read_sql_table_with_options(
32197            &conn,
32198            "t",
32199            &SqlReadOptions {
32200                columns: Some(vec!["x; DROP TABLE t".to_owned()]),
32201                ..Default::default()
32202            },
32203        )
32204        .expect_err("invalid column name must be rejected");
32205        assert!(matches!(err, IoError::Sql(msg) if msg.contains("invalid")));
32206    }
32207
32208    #[cfg(feature = "sql-sqlite")]
32209    #[test]
32210    fn read_sql_table_with_options_columns_combines_with_parse_dates() {
32211        // columns + parse_dates: project a subset, then date-coerce.
32212        let conn = make_sql_test_conn();
32213        super::SqlConnection::execute_batch(
32214            &conn,
32215            "CREATE TABLE events (id INT, ts TEXT, note TEXT);",
32216        )
32217        .unwrap();
32218        super::SqlConnection::execute_batch(
32219            &conn,
32220            "INSERT INTO events VALUES (1, '2024-01-15', 'launched');",
32221        )
32222        .unwrap();
32223        let frame = read_sql_table_with_options(
32224            &conn,
32225            "events",
32226            &SqlReadOptions {
32227                columns: Some(vec!["id".to_owned(), "ts".to_owned()]),
32228                index_col: None,
32229                parse_dates: Some(vec!["ts".to_owned()]),
32230                ..Default::default()
32231            },
32232        )
32233        .unwrap();
32234        // Only id + ts surfaced; ts was coerced by parse_dates into a typed
32235        // Datetime64[ns] column (br-frankenpandas-0ezw7).
32236        assert_eq!(frame.column_names(), vec!["id", "ts"]);
32237        assert_eq!(
32238            frame.column("ts").unwrap().values()[0],
32239            Scalar::Datetime64(1_705_276_800_000_000_000)
32240        );
32241    }
32242
32243    #[cfg(feature = "sql-sqlite")]
32244    #[test]
32245    fn read_sql_table_chunks_with_options_columns_projects_before_chunking() {
32246        let conn = make_sql_test_conn();
32247        super::SqlConnection::execute_batch(
32248            &conn,
32249            "CREATE TABLE chunk_projection (id INTEGER, name TEXT, hidden REAL);",
32250        )
32251        .unwrap();
32252        super::SqlConnection::execute_batch(
32253            &conn,
32254            "INSERT INTO chunk_projection VALUES \
32255                (1, 'a', 10.0), \
32256                (2, 'b', 20.0), \
32257                (3, 'c', 30.0);",
32258        )
32259        .unwrap();
32260
32261        let chunks: Vec<DataFrame> = read_sql_table_chunks_with_options(
32262            &conn,
32263            "chunk_projection",
32264            &SqlReadOptions {
32265                columns: Some(vec!["name".to_owned(), "id".to_owned()]),
32266                ..Default::default()
32267            },
32268            2,
32269        )
32270        .unwrap()
32271        .collect::<Result<Vec<_>, _>>()
32272        .unwrap();
32273
32274        assert_eq!(chunks.len(), 2);
32275        assert_eq!(chunks[0].column_names(), vec!["name", "id"]);
32276        assert_eq!(chunks[1].column_names(), vec!["name", "id"]);
32277        assert_eq!(
32278            chunks[0].column("name").unwrap().values(),
32279            &[Scalar::Utf8("a".into()), Scalar::Utf8("b".into())]
32280        );
32281        assert_eq!(
32282            chunks[1].column("id").unwrap().values(),
32283            &[Scalar::Int64(3)]
32284        );
32285        assert!(chunks[0].column("hidden").is_none());
32286    }
32287
32288    #[test]
32289    fn read_sql_table_chunks_with_options_schema_projects_before_chunking() {
32290        use std::cell::RefCell;
32291
32292        struct MultiSchemaProjectedChunks {
32293            queries: RefCell<Vec<String>>,
32294        }
32295
32296        impl super::SqlConnection for MultiSchemaProjectedChunks {
32297            fn query(&self, query: &str, _params: &[Scalar]) -> Result<SqlQueryResult, IoError> {
32298                self.queries.borrow_mut().push(query.to_owned());
32299                Ok(SqlQueryResult {
32300                    columns: vec!["name".to_owned(), "id".to_owned()],
32301                    rows: vec![
32302                        vec![Scalar::Utf8("a".to_owned()), Scalar::Int64(1)],
32303                        vec![Scalar::Utf8("b".to_owned()), Scalar::Int64(2)],
32304                        vec![Scalar::Utf8("c".to_owned()), Scalar::Int64(3)],
32305                    ],
32306                })
32307            }
32308
32309            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
32310                Ok(())
32311            }
32312
32313            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
32314                Ok(false)
32315            }
32316
32317            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
32318                Ok(())
32319            }
32320
32321            fn dtype_sql(&self, _dtype: DType) -> &'static str {
32322                "TEXT"
32323            }
32324
32325            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
32326                "TEXT"
32327            }
32328
32329            fn supports_schemas(&self) -> bool {
32330                true
32331            }
32332        }
32333
32334        let conn = MultiSchemaProjectedChunks {
32335            queries: RefCell::new(Vec::new()),
32336        };
32337
32338        let chunks: Vec<DataFrame> = super::read_sql_table_chunks_with_options(
32339            &conn,
32340            "events",
32341            &SqlReadOptions {
32342                schema: Some("analytics".to_owned()),
32343                columns: Some(vec!["name".to_owned(), "id".to_owned()]),
32344                ..Default::default()
32345            },
32346            2,
32347        )
32348        .unwrap()
32349        .collect::<Result<Vec<_>, _>>()
32350        .unwrap();
32351
32352        assert_eq!(
32353            conn.queries.borrow().as_slice(),
32354            &["SELECT \"name\", \"id\" FROM \"analytics\".\"events\"".to_owned()]
32355        );
32356        assert_eq!(chunks.len(), 2);
32357        assert_eq!(chunks[0].column_names(), vec!["name", "id"]);
32358        assert_eq!(chunks[1].column_names(), vec!["name", "id"]);
32359        assert_eq!(
32360            chunks[0].index().labels(),
32361            &[IndexLabel::Int64(0), IndexLabel::Int64(1)]
32362        );
32363        assert_eq!(chunks[1].index().labels(), &[IndexLabel::Int64(0)]);
32364        assert_eq!(
32365            chunks[0].column("name").unwrap().values(),
32366            &[Scalar::Utf8("a".into()), Scalar::Utf8("b".into())]
32367        );
32368        assert_eq!(
32369            chunks[1].column("id").unwrap().values(),
32370            &[Scalar::Int64(3)]
32371        );
32372    }
32373
32374    // ── SqlColumnSchema::comment (br-cfld / fd90.35) ─────────────────────
32375
32376    #[cfg(feature = "sql-sqlite")]
32377    #[test]
32378    fn sql_table_schema_comment_is_none_on_sqlite() {
32379        // SQLite has no column-comment storage; the rusqlite override
32380        // must always emit comment=None even when the table is real.
32381        let conn = make_sql_test_conn();
32382        super::SqlConnection::execute_batch(&conn, "CREATE TABLE labeled (id INTEGER, name TEXT);")
32383            .unwrap();
32384        let schema = sql_table_schema(&conn, "labeled", None).unwrap().unwrap();
32385        for col in &schema.columns {
32386            assert!(
32387                col.comment.is_none(),
32388                "SQLite should report no column comment; got {:?} on {}",
32389                col.comment,
32390                col.name
32391            );
32392        }
32393    }
32394
32395    #[test]
32396    fn sql_table_schema_comment_routes_to_backend_override() {
32397        // PG-like backend stub returns explicit comment text per column.
32398        struct PgLikeWithComments;
32399        impl super::SqlConnection for PgLikeWithComments {
32400            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
32401                Ok(SqlQueryResult {
32402                    columns: vec![],
32403                    rows: vec![],
32404                })
32405            }
32406            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
32407                Ok(())
32408            }
32409            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
32410                Ok(false)
32411            }
32412            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
32413                Ok(())
32414            }
32415            fn dtype_sql(&self, _dtype: DType) -> &'static str {
32416                "TEXT"
32417            }
32418            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
32419                "TEXT"
32420            }
32421            fn supports_schemas(&self) -> bool {
32422                true
32423            }
32424            fn table_schema(
32425                &self,
32426                table: &str,
32427                _schema: Option<&str>,
32428            ) -> Result<Option<SqlTableSchema>, IoError> {
32429                if table == "users" {
32430                    Ok(Some(SqlTableSchema {
32431                        table_name: "users".to_owned(),
32432                        columns: vec![
32433                            SqlColumnSchema {
32434                                name: "id".to_owned(),
32435                                declared_type: Some("BIGINT".to_owned()),
32436                                nullable: false,
32437                                default_value: None,
32438                                primary_key_ordinal: Some(0),
32439                                comment: Some("Surrogate primary key".to_owned()),
32440                                autoincrement: false,
32441                            },
32442                            SqlColumnSchema {
32443                                name: "email".to_owned(),
32444                                declared_type: Some("TEXT".to_owned()),
32445                                nullable: false,
32446                                default_value: None,
32447                                primary_key_ordinal: None,
32448                                comment: Some("Login identifier".to_owned()),
32449                                autoincrement: false,
32450                            },
32451                            SqlColumnSchema {
32452                                name: "name".to_owned(),
32453                                declared_type: Some("TEXT".to_owned()),
32454                                nullable: true,
32455                                default_value: None,
32456                                primary_key_ordinal: None,
32457                                comment: None,
32458                                autoincrement: false,
32459                            },
32460                        ],
32461                    }))
32462                } else {
32463                    Ok(None)
32464                }
32465            }
32466        }
32467        let conn = PgLikeWithComments;
32468        let schema = sql_table_schema(&conn, "users", None).unwrap().unwrap();
32469        let id = schema.column("id").unwrap();
32470        assert_eq!(id.comment.as_deref(), Some("Surrogate primary key"));
32471        let email = schema.column("email").unwrap();
32472        assert_eq!(email.comment.as_deref(), Some("Login identifier"));
32473        // Mixed: some columns may have no comment even on PG.
32474        let name = schema.column("name").unwrap();
32475        assert!(name.comment.is_none());
32476    }
32477
32478    // ── SqlReadOptions::index_col (br-c1h9 / fd90.36) ─────────────────────
32479
32480    #[cfg(feature = "sql-sqlite")]
32481    #[test]
32482    fn read_sql_with_options_index_col_none_keeps_range_index() {
32483        let conn = make_sql_test_conn();
32484        super::SqlConnection::execute_batch(&conn, "CREATE TABLE keyed (id INTEGER, val INTEGER);")
32485            .unwrap();
32486        super::SqlConnection::execute_batch(&conn, "INSERT INTO keyed VALUES (1, 10), (2, 20);")
32487            .unwrap();
32488        let frame = read_sql_with_options(
32489            &conn,
32490            "SELECT id, val FROM keyed ORDER BY id",
32491            &SqlReadOptions {
32492                index_col: None,
32493                ..Default::default()
32494            },
32495        )
32496        .unwrap();
32497        // Default RangeIndex: labels 0, 1.
32498        assert_eq!(frame.index().len(), 2);
32499        assert_eq!(frame.column_names(), vec!["id", "val"]);
32500    }
32501
32502    #[cfg(feature = "sql-sqlite")]
32503    #[test]
32504    fn read_sql_with_options_index_col_promotes_named_column() {
32505        let conn = make_sql_test_conn();
32506        super::SqlConnection::execute_batch(&conn, "CREATE TABLE keyed (id INTEGER, val INTEGER);")
32507            .unwrap();
32508        super::SqlConnection::execute_batch(&conn, "INSERT INTO keyed VALUES (10, 1), (20, 2);")
32509            .unwrap();
32510        let frame = read_sql_with_options(
32511            &conn,
32512            "SELECT id, val FROM keyed ORDER BY id",
32513            &SqlReadOptions {
32514                index_col: Some("id".to_owned()),
32515                ..Default::default()
32516            },
32517        )
32518        .unwrap();
32519        // 'id' removed from columns, used as index labels.
32520        assert_eq!(frame.column_names(), vec!["val"]);
32521        assert_eq!(frame.index().len(), 2);
32522        // Index labels should be the id values (10, 20).
32523        let labels: Vec<i64> = frame
32524            .index()
32525            .labels()
32526            .iter()
32527            .filter_map(|l| match l {
32528                IndexLabel::Int64(v) => Some(*v),
32529                _ => None,
32530            })
32531            .collect();
32532        assert_eq!(labels, vec![10, 20]);
32533    }
32534
32535    #[cfg(feature = "sql-sqlite")]
32536    #[test]
32537    fn read_sql_with_options_index_col_missing_column_errors() {
32538        let conn = make_sql_test_conn();
32539        super::SqlConnection::execute_batch(&conn, "CREATE TABLE t (a INTEGER);").unwrap();
32540        super::SqlConnection::execute_batch(&conn, "INSERT INTO t VALUES (1);").unwrap();
32541        let err = read_sql_with_options(
32542            &conn,
32543            "SELECT a FROM t",
32544            &SqlReadOptions {
32545                index_col: Some("nonexistent".to_owned()),
32546                ..Default::default()
32547            },
32548        )
32549        .expect_err("missing index_col must error");
32550        assert!(matches!(err, IoError::Sql(msg) if msg.contains("not present")));
32551    }
32552
32553    #[cfg(feature = "sql-sqlite")]
32554    #[test]
32555    fn read_sql_with_options_index_col_empty_string_rejected() {
32556        let conn = make_sql_test_conn();
32557        super::SqlConnection::execute_batch(&conn, "CREATE TABLE t (a INTEGER);").unwrap();
32558        let err = read_sql_with_options(
32559            &conn,
32560            "SELECT a FROM t",
32561            &SqlReadOptions {
32562                index_col: Some(String::new()),
32563                ..Default::default()
32564            },
32565        )
32566        .expect_err("empty index_col must be rejected");
32567        assert!(matches!(err, IoError::Sql(msg) if msg.contains("empty string")));
32568    }
32569
32570    #[cfg(feature = "sql-sqlite")]
32571    #[test]
32572    fn read_sql_explicit_index_col_empty_string_rejected_across_entrypoints() {
32573        fn assert_empty_index_col(err: IoError) {
32574            assert!(
32575                matches!(err, IoError::Sql(ref msg) if msg.contains("empty string")),
32576                "expected empty index_col error, got {err:?}"
32577            );
32578        }
32579
32580        let conn = make_sql_test_conn();
32581        super::SqlConnection::execute_batch(
32582            &conn,
32583            "CREATE TABLE explicit_idx (a INTEGER, b TEXT);
32584             INSERT INTO explicit_idx VALUES (1, 'x'), (2, 'y');",
32585        )
32586        .unwrap();
32587
32588        assert_empty_index_col(
32589            read_sql_with_index_col(&conn, "SELECT a, b FROM explicit_idx", Some(""))
32590                .expect_err("empty explicit read_sql index_col must be rejected"),
32591        );
32592        assert_empty_index_col(
32593            read_sql_query_with_options_and_index_col(
32594                &conn,
32595                "SELECT a, b FROM explicit_idx",
32596                &SqlReadOptions::default(),
32597                Some(""),
32598            )
32599            .expect_err("empty explicit read_sql_query index_col must be rejected"),
32600        );
32601        assert_empty_index_col(
32602            read_sql_query_chunks_with_options_and_index_col(
32603                &conn,
32604                "SELECT a, b FROM explicit_idx",
32605                &SqlReadOptions::default(),
32606                Some(""),
32607                1,
32608            )
32609            .expect_err("empty explicit query chunk index_col must be rejected"),
32610        );
32611        assert_empty_index_col(
32612            read_sql_table_with_index_col(&conn, "explicit_idx", Some(""))
32613                .expect_err("empty explicit table index_col must be rejected"),
32614        );
32615        assert_empty_index_col(
32616            read_sql_table_with_options_and_index_col(
32617                &conn,
32618                "explicit_idx",
32619                &SqlReadOptions::default(),
32620                Some(""),
32621            )
32622            .expect_err("empty explicit table options index_col must be rejected"),
32623        );
32624        assert_empty_index_col(
32625            read_sql_table_columns_with_index_col(&conn, "explicit_idx", &["a"], Some(""))
32626                .expect_err("empty explicit table-columns index_col must be rejected"),
32627        );
32628        assert_empty_index_col(
32629            read_sql_table_columns_chunks_with_index_col(
32630                &conn,
32631                "explicit_idx",
32632                &["a"],
32633                Some(""),
32634                1,
32635            )
32636            .expect_err("empty explicit table-columns chunk index_col must be rejected"),
32637        );
32638    }
32639
32640    #[cfg(feature = "sql-sqlite")]
32641    #[test]
32642    fn read_sql_table_with_options_index_col_combines_with_columns_projection() {
32643        // columns + index_col: project ['id', 'val'], promote 'id' to
32644        // index, leaving only 'val' as a data column.
32645        let conn = make_sql_test_conn();
32646        super::SqlConnection::execute_batch(
32647            &conn,
32648            "CREATE TABLE wide (id INTEGER, val INTEGER, ts TEXT, note TEXT);",
32649        )
32650        .unwrap();
32651        super::SqlConnection::execute_batch(
32652            &conn,
32653            "INSERT INTO wide VALUES (5, 100, 't1', 'first');",
32654        )
32655        .unwrap();
32656        let frame = read_sql_table_with_options(
32657            &conn,
32658            "wide",
32659            &SqlReadOptions {
32660                columns: Some(vec!["id".to_owned(), "val".to_owned()]),
32661                index_col: Some("id".to_owned()),
32662                ..Default::default()
32663            },
32664        )
32665        .unwrap();
32666        assert_eq!(frame.column_names(), vec!["val"]);
32667        let labels: Vec<i64> = frame
32668            .index()
32669            .labels()
32670            .iter()
32671            .filter_map(|l| match l {
32672                IndexLabel::Int64(v) => Some(*v),
32673                _ => None,
32674            })
32675            .collect();
32676        assert_eq!(labels, vec![5]);
32677    }
32678
32679    #[cfg(feature = "sql-sqlite")]
32680    #[test]
32681    fn read_sql_table_with_options_columns_auto_project_index_col() {
32682        let conn = make_sql_test_conn();
32683        super::SqlConnection::execute_batch(
32684            &conn,
32685            "CREATE TABLE projected_index (id INTEGER, val TEXT, hidden TEXT);",
32686        )
32687        .unwrap();
32688        super::SqlConnection::execute_batch(
32689            &conn,
32690            "INSERT INTO projected_index VALUES (10, 'a', 'x'), (20, 'b', 'y');",
32691        )
32692        .unwrap();
32693
32694        let frame = read_sql_table_with_options(
32695            &conn,
32696            "projected_index",
32697            &SqlReadOptions {
32698                columns: Some(vec!["val".to_owned()]),
32699                index_col: Some("id".to_owned()),
32700                ..Default::default()
32701            },
32702        )
32703        .unwrap();
32704
32705        assert_eq!(frame.column_names(), vec!["val"]);
32706        assert!(frame.column("id").is_none());
32707        assert!(frame.column("hidden").is_none());
32708        assert_eq!(
32709            frame.index().labels(),
32710            &[IndexLabel::Int64(10), IndexLabel::Int64(20)]
32711        );
32712        assert_eq!(
32713            frame.column("val").unwrap().values(),
32714            &[Scalar::Utf8("a".into()), Scalar::Utf8("b".into())]
32715        );
32716    }
32717
32718    #[cfg(feature = "sql-sqlite")]
32719    #[test]
32720    fn read_sql_table_chunks_with_options_columns_auto_project_index_col() {
32721        let conn = make_sql_test_conn();
32722        super::SqlConnection::execute_batch(
32723            &conn,
32724            "CREATE TABLE projected_index_chunks (id INTEGER, val TEXT, hidden TEXT);",
32725        )
32726        .unwrap();
32727        super::SqlConnection::execute_batch(
32728            &conn,
32729            "INSERT INTO projected_index_chunks VALUES \
32730                (10, 'a', 'x'), \
32731                (20, 'b', 'y'), \
32732                (30, 'c', 'z');",
32733        )
32734        .unwrap();
32735
32736        let chunks: Vec<DataFrame> = read_sql_table_chunks_with_options_and_index_col(
32737            &conn,
32738            "projected_index_chunks",
32739            &SqlReadOptions {
32740                columns: Some(vec!["val".to_owned()]),
32741                ..Default::default()
32742            },
32743            Some("id"),
32744            2,
32745        )
32746        .unwrap()
32747        .collect::<Result<Vec<_>, _>>()
32748        .unwrap();
32749
32750        assert_eq!(chunks.len(), 2);
32751        assert_eq!(chunks[0].column_names(), vec!["val"]);
32752        assert!(chunks[0].column("id").is_none());
32753        assert!(chunks[0].column("hidden").is_none());
32754        assert_eq!(
32755            chunks[0].index().labels(),
32756            &[IndexLabel::Int64(10), IndexLabel::Int64(20)]
32757        );
32758        assert_eq!(chunks[1].index().labels(), &[IndexLabel::Int64(30)]);
32759        assert_eq!(
32760            chunks[1].column("val").unwrap().values(),
32761            &[Scalar::Utf8("c".into())]
32762        );
32763    }
32764
32765    #[cfg(feature = "sql-sqlite")]
32766    #[test]
32767    fn read_sql_table_with_options_and_index_col_explicit_arg_wins_over_options() {
32768        // Both options.index_col=Some('a') and explicit index_col=Some('b').
32769        // The explicit arg must win — options.index_col is silently
32770        // overridden to avoid double-promotion.
32771        let conn = make_sql_test_conn();
32772        super::SqlConnection::execute_batch(
32773            &conn,
32774            "CREATE TABLE both (a INTEGER, b INTEGER, c TEXT);",
32775        )
32776        .unwrap();
32777        super::SqlConnection::execute_batch(
32778            &conn,
32779            "INSERT INTO both VALUES (1, 100, 'x'), (2, 200, 'y');",
32780        )
32781        .unwrap();
32782        let frame = read_sql_table_with_options_and_index_col(
32783            &conn,
32784            "both",
32785            &SqlReadOptions {
32786                index_col: Some("a".to_owned()),
32787                ..Default::default()
32788            },
32789            Some("b"),
32790        )
32791        .unwrap();
32792        // 'b' is promoted to index, 'a' and 'c' remain as columns.
32793        assert_eq!(frame.column_names(), vec!["a", "c"]);
32794        let labels: Vec<i64> = frame
32795            .index()
32796            .labels()
32797            .iter()
32798            .filter_map(|l| match l {
32799                IndexLabel::Int64(v) => Some(*v),
32800                _ => None,
32801            })
32802            .collect();
32803        assert_eq!(labels, vec![100, 200]);
32804    }
32805
32806    // ── SqlColumnSchema::autoincrement (br-bkl2 / fd90.37) ────────────────
32807
32808    #[cfg(feature = "sql-sqlite")]
32809    #[test]
32810    fn sql_table_schema_autoincrement_detected_on_integer_primary_key() {
32811        // SQLite rowid-alias rule: INTEGER PRIMARY KEY is an
32812        // auto-incrementing rowid alias.
32813        let conn = make_sql_test_conn();
32814        super::SqlConnection::execute_batch(
32815            &conn,
32816            "CREATE TABLE auto_a (id INTEGER PRIMARY KEY, name TEXT);",
32817        )
32818        .unwrap();
32819        let schema = sql_table_schema(&conn, "auto_a", None).unwrap().unwrap();
32820        let id = schema.column("id").unwrap();
32821        assert!(
32822            id.autoincrement,
32823            "INTEGER PRIMARY KEY must be autoincrement; got {id:?}"
32824        );
32825        let name = schema.column("name").unwrap();
32826        assert!(
32827            !name.autoincrement,
32828            "non-PK column must not be autoincrement"
32829        );
32830    }
32831
32832    #[cfg(feature = "sql-sqlite")]
32833    #[test]
32834    fn sql_table_schema_autoincrement_detected_with_explicit_keyword() {
32835        // The explicit AUTOINCREMENT keyword affects rowid reuse, not
32836        // the autoincrement property pandas surfaces.
32837        let conn = make_sql_test_conn();
32838        super::SqlConnection::execute_batch(
32839            &conn,
32840            "CREATE TABLE auto_b (id INTEGER PRIMARY KEY AUTOINCREMENT, val TEXT);",
32841        )
32842        .unwrap();
32843        let schema = sql_table_schema(&conn, "auto_b", None).unwrap().unwrap();
32844        let id = schema.column("id").unwrap();
32845        assert!(id.autoincrement);
32846    }
32847
32848    #[cfg(feature = "sql-sqlite")]
32849    #[test]
32850    fn sql_table_schema_autoincrement_not_set_for_text_primary_key() {
32851        // TEXT PRIMARY KEY is NOT a rowid alias; not auto-incrementing.
32852        let conn = make_sql_test_conn();
32853        super::SqlConnection::execute_batch(
32854            &conn,
32855            "CREATE TABLE text_pk (code TEXT PRIMARY KEY, name TEXT);",
32856        )
32857        .unwrap();
32858        let schema = sql_table_schema(&conn, "text_pk", None).unwrap().unwrap();
32859        let code = schema.column("code").unwrap();
32860        assert!(
32861            !code.autoincrement,
32862            "TEXT PRIMARY KEY is not autoincrement; got {code:?}"
32863        );
32864    }
32865
32866    #[cfg(feature = "sql-sqlite")]
32867    #[test]
32868    fn sql_table_schema_autoincrement_not_set_for_non_pk_integer() {
32869        let conn = make_sql_test_conn();
32870        super::SqlConnection::execute_batch(
32871            &conn,
32872            "CREATE TABLE plain_int (val INTEGER, name TEXT);",
32873        )
32874        .unwrap();
32875        let schema = sql_table_schema(&conn, "plain_int", None).unwrap().unwrap();
32876        let val = schema.column("val").unwrap();
32877        assert!(!val.autoincrement, "non-PK INTEGER is not autoincrement");
32878    }
32879
32880    #[cfg(feature = "sql-sqlite")]
32881    #[test]
32882    fn sql_table_schema_autoincrement_not_set_for_composite_pk_integer() {
32883        // Per fd90.42: SQLite's rowid-alias rule requires the column
32884        // to be the SOLE primary key. The tightened heuristic counts
32885        // PK columns first; composite PKs (multiple pk>0 rows) never
32886        // qualify even when the first column is INTEGER.
32887        let conn = make_sql_test_conn();
32888        super::SqlConnection::execute_batch(
32889            &conn,
32890            "CREATE TABLE composite_pk ( \
32891                year INTEGER NOT NULL, \
32892                month INTEGER NOT NULL, \
32893                code TEXT NOT NULL, \
32894                PRIMARY KEY (year, month, code) \
32895             );",
32896        )
32897        .unwrap();
32898        let schema = sql_table_schema(&conn, "composite_pk", None)
32899            .unwrap()
32900            .unwrap();
32901        let year = schema.column("year").unwrap();
32902        let month = schema.column("month").unwrap();
32903        let code = schema.column("code").unwrap();
32904        // Each part of the composite PK keeps its declaration-order
32905        // ordinal but NONE of them is autoincrement.
32906        assert_eq!(year.primary_key_ordinal, Some(0));
32907        assert_eq!(month.primary_key_ordinal, Some(1));
32908        assert_eq!(code.primary_key_ordinal, Some(2));
32909        assert!(
32910            !year.autoincrement,
32911            "composite PK first col must not be autoincrement"
32912        );
32913        assert!(!month.autoincrement);
32914        assert!(!code.autoincrement);
32915    }
32916
32917    #[cfg(feature = "sql-sqlite")]
32918    #[test]
32919    fn sql_table_schema_autoincrement_two_pass_count_distinguishes_single_vs_composite() {
32920        // Confirm the fix path: single-column INTEGER PRIMARY KEY -> true,
32921        // composite INTEGER+INTEGER PRIMARY KEY -> false on both.
32922        let conn = make_sql_test_conn();
32923        super::SqlConnection::execute_batch(
32924            &conn,
32925            "CREATE TABLE single_int_pk (id INTEGER PRIMARY KEY, label TEXT);",
32926        )
32927        .unwrap();
32928        super::SqlConnection::execute_batch(
32929            &conn,
32930            "CREATE TABLE composite_int_pk ( \
32931                a INTEGER NOT NULL, \
32932                b INTEGER NOT NULL, \
32933                PRIMARY KEY (a, b) \
32934             );",
32935        )
32936        .unwrap();
32937
32938        let single = sql_table_schema(&conn, "single_int_pk", None)
32939            .unwrap()
32940            .unwrap();
32941        assert!(single.column("id").unwrap().autoincrement);
32942
32943        let composite = sql_table_schema(&conn, "composite_int_pk", None)
32944            .unwrap()
32945            .unwrap();
32946        // Both columns have INTEGER type and pk>0 but neither qualifies.
32947        assert!(!composite.column("a").unwrap().autoincrement);
32948        assert!(!composite.column("b").unwrap().autoincrement);
32949    }
32950
32951    #[test]
32952    fn sql_table_schema_autoincrement_routes_to_backend_override() {
32953        // PG-like backend stub returns explicit autoincrement true for
32954        // a SERIAL/IDENTITY column.
32955        struct PgLikeAutoinc;
32956        impl super::SqlConnection for PgLikeAutoinc {
32957            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
32958                Ok(SqlQueryResult {
32959                    columns: vec![],
32960                    rows: vec![],
32961                })
32962            }
32963            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
32964                Ok(())
32965            }
32966            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
32967                Ok(false)
32968            }
32969            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
32970                Ok(())
32971            }
32972            fn dtype_sql(&self, _dtype: DType) -> &'static str {
32973                "TEXT"
32974            }
32975            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
32976                "TEXT"
32977            }
32978            fn supports_schemas(&self) -> bool {
32979                true
32980            }
32981            fn table_schema(
32982                &self,
32983                table: &str,
32984                _schema: Option<&str>,
32985            ) -> Result<Option<SqlTableSchema>, IoError> {
32986                if table == "users" {
32987                    Ok(Some(SqlTableSchema {
32988                        table_name: "users".to_owned(),
32989                        columns: vec![
32990                            SqlColumnSchema {
32991                                name: "id".to_owned(),
32992                                declared_type: Some("BIGSERIAL".to_owned()),
32993                                nullable: false,
32994                                default_value: None,
32995                                primary_key_ordinal: Some(0),
32996                                comment: None,
32997                                autoincrement: true,
32998                            },
32999                            SqlColumnSchema {
33000                                name: "email".to_owned(),
33001                                declared_type: Some("TEXT".to_owned()),
33002                                nullable: false,
33003                                default_value: None,
33004                                primary_key_ordinal: None,
33005                                comment: None,
33006                                autoincrement: false,
33007                            },
33008                        ],
33009                    }))
33010                } else {
33011                    Ok(None)
33012                }
33013            }
33014        }
33015        let conn = PgLikeAutoinc;
33016        let schema = sql_table_schema(&conn, "users", None).unwrap().unwrap();
33017        assert!(schema.column("id").unwrap().autoincrement);
33018        assert!(!schema.column("email").unwrap().autoincrement);
33019    }
33020
33021    // ── SqlInspector facade (br-szs9 / fd90.38) ──────────────────────────
33022
33023    #[cfg(feature = "sql-sqlite")]
33024    #[test]
33025    fn sql_inspector_tables_views_schemas() {
33026        let conn = make_sql_test_conn();
33027        super::SqlConnection::execute_batch(&conn, "CREATE TABLE t1 (x INTEGER);").unwrap();
33028        super::SqlConnection::execute_batch(&conn, "CREATE TABLE t2 (y TEXT);").unwrap();
33029        super::SqlConnection::execute_batch(&conn, "CREATE VIEW v1 AS SELECT x FROM t1;").unwrap();
33030
33031        let inspector = SqlInspector::new(&conn);
33032        assert_eq!(inspector.tables(None).unwrap(), vec!["t1", "t2"]);
33033        assert_eq!(inspector.views(None).unwrap(), vec!["v1"]);
33034        // SQLite has no meaningful schemas → empty vec.
33035        assert!(inspector.schemas().unwrap().is_empty());
33036    }
33037
33038    #[cfg(feature = "sql-sqlite")]
33039    #[test]
33040    fn sql_inspector_columns_pk_indexes_fks() {
33041        let conn = make_sql_test_conn();
33042        super::SqlConnection::execute_batch(
33043            &conn,
33044            "CREATE TABLE parent (pid INTEGER PRIMARY KEY);",
33045        )
33046        .unwrap();
33047        super::SqlConnection::execute_batch(
33048            &conn,
33049            "CREATE TABLE child ( \
33050                cid INTEGER PRIMARY KEY, \
33051                parent_id INTEGER, \
33052                tag TEXT, \
33053                FOREIGN KEY (parent_id) REFERENCES parent(pid) \
33054             );",
33055        )
33056        .unwrap();
33057        super::SqlConnection::execute_batch(&conn, "CREATE INDEX idx_child_tag ON child(tag);")
33058            .unwrap();
33059
33060        let inspector = SqlInspector::new(&conn);
33061
33062        // columns: 3 columns on 'child', cid + parent_id + tag.
33063        let schema = inspector.columns("child", None).unwrap().unwrap();
33064        let names: Vec<&str> = schema.columns.iter().map(|c| c.name.as_str()).collect();
33065        assert_eq!(names, vec!["cid", "parent_id", "tag"]);
33066
33067        // primary_key_columns: cid is the sole PK.
33068        let pk = inspector.primary_key_columns("child", None).unwrap();
33069        assert_eq!(pk, vec!["cid"]);
33070
33071        // indexes: only the explicit user index (PK auto-index filtered).
33072        let indexes = inspector.indexes("child", None).unwrap();
33073        assert_eq!(indexes.len(), 1);
33074        assert_eq!(indexes[0].name, "idx_child_tag");
33075
33076        // foreign_keys: child references parent.
33077        let fks = inspector.foreign_keys("child", None).unwrap();
33078        assert_eq!(fks.len(), 1);
33079        assert_eq!(fks[0].columns, vec!["parent_id"]);
33080        assert_eq!(fks[0].referenced_table, "parent");
33081        assert_eq!(fks[0].referenced_columns, vec!["pid"]);
33082    }
33083
33084    #[cfg(feature = "sql-sqlite")]
33085    #[test]
33086    fn sql_inspector_unique_constraints_and_table_exists() {
33087        let conn = make_sql_test_conn();
33088        super::SqlConnection::execute_batch(
33089            &conn,
33090            "CREATE TABLE users (id INTEGER PRIMARY KEY, email TEXT UNIQUE);",
33091        )
33092        .unwrap();
33093        let inspector = SqlInspector::new(&conn);
33094        let uqs = inspector.unique_constraints("users", None).unwrap();
33095        assert_eq!(uqs.len(), 1);
33096        assert_eq!(uqs[0].columns, vec!["email"]);
33097        assert!(inspector.table_exists("users", None).unwrap());
33098        assert!(!inspector.table_exists("not_there", None).unwrap());
33099    }
33100
33101    #[cfg(feature = "sql-sqlite")]
33102    #[test]
33103    fn sql_inspector_server_version_and_dialect() {
33104        let conn = make_sql_test_conn();
33105        let inspector = SqlInspector::new(&conn);
33106        let version = inspector.server_version().unwrap().unwrap();
33107        assert!(version.starts_with("3."));
33108        assert_eq!(inspector.dialect_name(), "sqlite");
33109        // SQLite has no documented identifier-length cap.
33110        assert_eq!(inspector.max_identifier_length(), None);
33111    }
33112
33113    #[cfg(feature = "sql-sqlite")]
33114    #[test]
33115    fn sql_inspector_table_comment_returns_none_on_sqlite() {
33116        let conn = make_sql_test_conn();
33117        super::SqlConnection::execute_batch(&conn, "CREATE TABLE t (x INTEGER);").unwrap();
33118        let inspector = SqlInspector::new(&conn);
33119        assert!(inspector.table_comment("t", None).unwrap().is_none());
33120    }
33121
33122    #[cfg(feature = "sql-sqlite")]
33123    #[test]
33124    fn sql_inspector_via_inspect_helper() {
33125        // The free-fn `inspect(&conn)` is the one-shot construction helper.
33126        // Per fd90.46: import lives inside the test so --no-default-features
33127        // builds don't see it as unused.
33128        use super::inspect;
33129        let conn = make_sql_test_conn();
33130        super::SqlConnection::execute_batch(&conn, "CREATE TABLE one (x INTEGER);").unwrap();
33131        let inspector = inspect(&conn);
33132        assert_eq!(inspector.tables(None).unwrap(), vec!["one"]);
33133    }
33134
33135    #[test]
33136    fn sql_inspector_routes_schema_arg_to_backend() {
33137        // Multi-schema backend: verifies SqlInspector forwards the schema
33138        // arg to every method that accepts one.
33139        struct PgLikeStub;
33140        impl super::SqlConnection for PgLikeStub {
33141            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
33142                Ok(SqlQueryResult {
33143                    columns: vec![],
33144                    rows: vec![],
33145                })
33146            }
33147            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
33148                Ok(())
33149            }
33150            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
33151                Ok(false)
33152            }
33153            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
33154                Ok(())
33155            }
33156            fn dtype_sql(&self, _dtype: DType) -> &'static str {
33157                "TEXT"
33158            }
33159            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
33160                "TEXT"
33161            }
33162            fn supports_schemas(&self) -> bool {
33163                true
33164            }
33165            fn list_tables(&self, schema: Option<&str>) -> Result<Vec<String>, IoError> {
33166                Ok(match schema {
33167                    Some("analytics") => vec!["events".to_owned()],
33168                    _ => vec![],
33169                })
33170            }
33171            fn list_views(&self, schema: Option<&str>) -> Result<Vec<String>, IoError> {
33172                Ok(match schema {
33173                    Some("analytics") => vec!["daily".to_owned()],
33174                    _ => vec![],
33175                })
33176            }
33177            fn list_schemas(&self) -> Result<Vec<String>, IoError> {
33178                Ok(vec!["public".to_owned(), "analytics".to_owned()])
33179            }
33180            fn dialect_name(&self) -> &'static str {
33181                "postgresql"
33182            }
33183            fn max_identifier_length(&self) -> Option<usize> {
33184                Some(63)
33185            }
33186        }
33187        let conn = PgLikeStub;
33188        let inspector = SqlInspector::new(&conn);
33189
33190        assert_eq!(inspector.tables(Some("analytics")).unwrap(), vec!["events"]);
33191        assert_eq!(inspector.views(Some("analytics")).unwrap(), vec!["daily"]);
33192        assert!(inspector.tables(Some("audit")).unwrap().is_empty());
33193        assert_eq!(inspector.schemas().unwrap(), vec!["public", "analytics"]);
33194        assert_eq!(inspector.dialect_name(), "postgresql");
33195        assert_eq!(inspector.max_identifier_length(), Some(63));
33196    }
33197
33198    // ── SqlInspector::has_column / column (br-ppry / fd90.39) ─────────────
33199
33200    #[cfg(feature = "sql-sqlite")]
33201    #[test]
33202    fn sql_inspector_has_column_returns_true_for_present_column() {
33203        let conn = make_sql_test_conn();
33204        super::SqlConnection::execute_batch(
33205            &conn,
33206            "CREATE TABLE has_col_tbl (id INTEGER, name TEXT);",
33207        )
33208        .unwrap();
33209        let inspector = SqlInspector::new(&conn);
33210        assert!(inspector.has_column("has_col_tbl", "id", None).unwrap());
33211        assert!(inspector.has_column("has_col_tbl", "name", None).unwrap());
33212    }
33213
33214    #[cfg(feature = "sql-sqlite")]
33215    #[test]
33216    fn sql_inspector_has_column_returns_false_for_missing_column() {
33217        let conn = make_sql_test_conn();
33218        super::SqlConnection::execute_batch(&conn, "CREATE TABLE only_id (id INTEGER);").unwrap();
33219        let inspector = SqlInspector::new(&conn);
33220        // Table exists but no such column.
33221        assert!(!inspector.has_column("only_id", "name", None).unwrap());
33222    }
33223
33224    #[cfg(feature = "sql-sqlite")]
33225    #[test]
33226    fn sql_inspector_has_column_returns_false_for_missing_table() {
33227        let conn = make_sql_test_conn();
33228        let inspector = SqlInspector::new(&conn);
33229        // Table doesn't exist → has_column propagates Ok(false), not error.
33230        assert!(
33231            !inspector
33232                .has_column("no_such_tbl", "any_col", None)
33233                .unwrap()
33234        );
33235    }
33236
33237    #[cfg(feature = "sql-sqlite")]
33238    #[test]
33239    fn sql_inspector_column_returns_full_metadata_for_present_column() {
33240        let conn = make_sql_test_conn();
33241        super::SqlConnection::execute_batch(
33242            &conn,
33243            "CREATE TABLE detailed (id INTEGER PRIMARY KEY, status TEXT DEFAULT 'active');",
33244        )
33245        .unwrap();
33246        let inspector = SqlInspector::new(&conn);
33247        let id = inspector.column("detailed", "id", None).unwrap().unwrap();
33248        assert_eq!(id.name, "id");
33249        assert_eq!(id.declared_type.as_deref(), Some("INTEGER"));
33250        assert_eq!(id.primary_key_ordinal, Some(0));
33251        // INTEGER PRIMARY KEY → SQLite autoincrement (rowid alias).
33252        assert!(id.autoincrement);
33253
33254        let status = inspector
33255            .column("detailed", "status", None)
33256            .unwrap()
33257            .unwrap();
33258        assert_eq!(status.declared_type.as_deref(), Some("TEXT"));
33259        assert!(status.nullable);
33260        assert_eq!(status.default_value.as_deref(), Some("'active'"));
33261        assert!(!status.autoincrement);
33262    }
33263
33264    #[cfg(feature = "sql-sqlite")]
33265    #[test]
33266    fn sql_inspector_column_returns_none_for_missing_column_or_table() {
33267        let conn = make_sql_test_conn();
33268        super::SqlConnection::execute_batch(&conn, "CREATE TABLE only_x (x INTEGER);").unwrap();
33269        let inspector = SqlInspector::new(&conn);
33270        // Existing table, missing column → None.
33271        assert!(
33272            inspector
33273                .column("only_x", "missing", None)
33274                .unwrap()
33275                .is_none()
33276        );
33277        // Missing table → None.
33278        assert!(inspector.column("no_such", "any", None).unwrap().is_none());
33279    }
33280
33281    #[test]
33282    fn sql_inspector_has_column_routes_schema_arg_to_backend() {
33283        struct PgLikeColumns;
33284        impl super::SqlConnection for PgLikeColumns {
33285            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
33286                Ok(SqlQueryResult {
33287                    columns: vec![],
33288                    rows: vec![],
33289                })
33290            }
33291            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
33292                Ok(())
33293            }
33294            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
33295                Ok(false)
33296            }
33297            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
33298                Ok(())
33299            }
33300            fn dtype_sql(&self, _dtype: DType) -> &'static str {
33301                "TEXT"
33302            }
33303            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
33304                "TEXT"
33305            }
33306            fn supports_schemas(&self) -> bool {
33307                true
33308            }
33309            fn table_schema(
33310                &self,
33311                table: &str,
33312                schema: Option<&str>,
33313            ) -> Result<Option<SqlTableSchema>, IoError> {
33314                if table == "users" && schema == Some("public") {
33315                    Ok(Some(SqlTableSchema {
33316                        table_name: "users".to_owned(),
33317                        columns: vec![SqlColumnSchema {
33318                            name: "id".to_owned(),
33319                            declared_type: Some("BIGINT".to_owned()),
33320                            nullable: false,
33321                            default_value: None,
33322                            primary_key_ordinal: Some(0),
33323                            comment: None,
33324                            autoincrement: true,
33325                        }],
33326                    }))
33327                } else {
33328                    Ok(None)
33329                }
33330            }
33331        }
33332        let conn = PgLikeColumns;
33333        let inspector = SqlInspector::new(&conn);
33334        assert!(inspector.has_column("users", "id", Some("public")).unwrap());
33335        assert!(!inspector.has_column("users", "id", Some("audit")).unwrap());
33336        assert!(
33337            !inspector
33338                .has_column("users", "missing", Some("public"))
33339                .unwrap()
33340        );
33341
33342        let id_col = inspector
33343            .column("users", "id", Some("public"))
33344            .unwrap()
33345            .unwrap();
33346        assert_eq!(id_col.declared_type.as_deref(), Some("BIGINT"));
33347        assert!(id_col.autoincrement);
33348        assert!(
33349            inspector
33350                .column("users", "id", Some("audit"))
33351                .unwrap()
33352                .is_none()
33353        );
33354    }
33355
33356    // ── SqlInspector::reflect_table (br-76mw / fd90.40) ──────────────────
33357
33358    #[cfg(feature = "sql-sqlite")]
33359    #[test]
33360    fn sql_inspector_reflect_table_unknown_returns_none() {
33361        let conn = make_sql_test_conn();
33362        let inspector = SqlInspector::new(&conn);
33363        let result = inspector.reflect_table("no_such", None).unwrap();
33364        assert!(result.is_none());
33365    }
33366
33367    #[cfg(feature = "sql-sqlite")]
33368    #[test]
33369    fn sql_inspector_reflect_table_bundles_all_metadata() {
33370        let conn = make_sql_test_conn();
33371        super::SqlConnection::execute_batch(
33372            &conn,
33373            "CREATE TABLE parent (pid INTEGER PRIMARY KEY, code TEXT);",
33374        )
33375        .unwrap();
33376        super::SqlConnection::execute_batch(
33377            &conn,
33378            "CREATE TABLE bundled ( \
33379                id INTEGER PRIMARY KEY, \
33380                parent_id INTEGER, \
33381                slug TEXT, \
33382                email TEXT UNIQUE, \
33383                FOREIGN KEY (parent_id) REFERENCES parent(pid) \
33384             );",
33385        )
33386        .unwrap();
33387        super::SqlConnection::execute_batch(
33388            &conn,
33389            "CREATE INDEX idx_bundled_slug ON bundled(slug);",
33390        )
33391        .unwrap();
33392
33393        let inspector = SqlInspector::new(&conn);
33394        let bundle = inspector
33395            .reflect_table("bundled", None)
33396            .unwrap()
33397            .expect("table exists");
33398
33399        assert_eq!(bundle.table_name, "bundled");
33400
33401        // Columns: id, parent_id, slug, email.
33402        let names: Vec<&str> = bundle.columns.iter().map(|c| c.name.as_str()).collect();
33403        assert_eq!(names, vec!["id", "parent_id", "slug", "email"]);
33404        // INTEGER PRIMARY KEY id is autoincrement.
33405        let id_col = bundle
33406            .columns
33407            .iter()
33408            .find(|c| c.name == "id")
33409            .expect("id col");
33410        assert!(id_col.autoincrement);
33411
33412        // Primary key.
33413        assert_eq!(bundle.primary_key_columns, vec!["id"]);
33414
33415        // Indexes (only the user CREATE INDEX; the UNIQUE constraint
33416        // index goes via unique_constraints, the PK auto-index is
33417        // hidden).
33418        assert_eq!(bundle.indexes.len(), 1);
33419        assert_eq!(bundle.indexes[0].name, "idx_bundled_slug");
33420
33421        // Unique constraints (the inline UNIQUE on email).
33422        assert_eq!(bundle.unique_constraints.len(), 1);
33423        assert_eq!(bundle.unique_constraints[0].columns, vec!["email"]);
33424
33425        // Foreign keys (parent_id -> parent.pid).
33426        assert_eq!(bundle.foreign_keys.len(), 1);
33427        assert_eq!(bundle.foreign_keys[0].columns, vec!["parent_id"]);
33428        assert_eq!(bundle.foreign_keys[0].referenced_table, "parent");
33429
33430        // SQLite has no native column/table comment; comment is None.
33431        assert!(bundle.comment.is_none());
33432    }
33433
33434    #[test]
33435    fn sql_inspector_reflect_table_routes_to_backend_override() {
33436        // Multi-schema PG-like backend that returns explicit comment +
33437        // populated metadata. Verifies all five sub-calls flow through
33438        // and end up in the bundled struct.
33439        struct PgLikeBundle;
33440        impl super::SqlConnection for PgLikeBundle {
33441            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
33442                Ok(SqlQueryResult {
33443                    columns: vec![],
33444                    rows: vec![],
33445                })
33446            }
33447            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
33448                Ok(())
33449            }
33450            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
33451                Ok(false)
33452            }
33453            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
33454                Ok(())
33455            }
33456            fn dtype_sql(&self, _dtype: DType) -> &'static str {
33457                "TEXT"
33458            }
33459            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
33460                "TEXT"
33461            }
33462            fn supports_schemas(&self) -> bool {
33463                true
33464            }
33465            fn table_schema(
33466                &self,
33467                table: &str,
33468                schema: Option<&str>,
33469            ) -> Result<Option<SqlTableSchema>, IoError> {
33470                if table == "users" && schema == Some("public") {
33471                    Ok(Some(SqlTableSchema {
33472                        table_name: "users".to_owned(),
33473                        columns: vec![SqlColumnSchema {
33474                            name: "id".to_owned(),
33475                            declared_type: Some("BIGINT".to_owned()),
33476                            nullable: false,
33477                            default_value: None,
33478                            primary_key_ordinal: Some(0),
33479                            comment: None,
33480                            autoincrement: true,
33481                        }],
33482                    }))
33483                } else {
33484                    Ok(None)
33485                }
33486            }
33487            fn primary_key_columns(
33488                &self,
33489                table: &str,
33490                schema: Option<&str>,
33491            ) -> Result<Vec<String>, IoError> {
33492                if table == "users" && schema == Some("public") {
33493                    Ok(vec!["id".to_owned()])
33494                } else {
33495                    Ok(vec![])
33496                }
33497            }
33498            fn list_indexes(
33499                &self,
33500                _table: &str,
33501                _schema: Option<&str>,
33502            ) -> Result<Vec<SqlIndexSchema>, IoError> {
33503                Ok(vec![SqlIndexSchema {
33504                    name: "users_status_idx".to_owned(),
33505                    columns: vec!["status".to_owned()],
33506                    unique: false,
33507                }])
33508            }
33509            fn list_foreign_keys(
33510                &self,
33511                _table: &str,
33512                _schema: Option<&str>,
33513            ) -> Result<Vec<SqlForeignKeySchema>, IoError> {
33514                Ok(vec![])
33515            }
33516            fn list_unique_constraints(
33517                &self,
33518                _table: &str,
33519                _schema: Option<&str>,
33520            ) -> Result<Vec<SqlUniqueConstraintSchema>, IoError> {
33521                Ok(vec![SqlUniqueConstraintSchema {
33522                    name: "users_email_key".to_owned(),
33523                    columns: vec!["email".to_owned()],
33524                }])
33525            }
33526            fn table_comment(
33527                &self,
33528                _table: &str,
33529                _schema: Option<&str>,
33530            ) -> Result<Option<String>, IoError> {
33531                Ok(Some("Customer accounts".to_owned()))
33532            }
33533        }
33534        let conn = PgLikeBundle;
33535        let inspector = SqlInspector::new(&conn);
33536        let bundle = inspector
33537            .reflect_table("users", Some("public"))
33538            .unwrap()
33539            .expect("present");
33540        assert_eq!(bundle.table_name, "users");
33541        assert_eq!(bundle.columns.len(), 1);
33542        assert_eq!(bundle.primary_key_columns, vec!["id"]);
33543        assert_eq!(bundle.indexes.len(), 1);
33544        assert_eq!(bundle.indexes[0].name, "users_status_idx");
33545        assert_eq!(bundle.unique_constraints.len(), 1);
33546        assert_eq!(bundle.foreign_keys.len(), 0);
33547        assert_eq!(bundle.comment.as_deref(), Some("Customer accounts"));
33548
33549        // Wrong schema -> None (table_schema returns None).
33550        assert!(
33551            inspector
33552                .reflect_table("users", Some("audit"))
33553                .unwrap()
33554                .is_none()
33555        );
33556    }
33557
33558    // Use SqlReflectedTable in a smoke test so the struct's named
33559    // fields are exercised at the use-site too.
33560    #[test]
33561    fn sql_reflected_table_bundle_smoke_test() {
33562        let bundle = SqlReflectedTable {
33563            table_name: "t".to_owned(),
33564            columns: vec![],
33565            primary_key_columns: vec![],
33566            indexes: vec![],
33567            foreign_keys: vec![],
33568            unique_constraints: vec![],
33569            comment: None,
33570        };
33571        assert_eq!(bundle.table_name, "t");
33572        assert!(bundle.columns.is_empty());
33573    }
33574
33575    // ── SqlReflectedTable accessor methods (br-63ac / fd90.51) ────────────
33576
33577    #[test]
33578    fn sql_reflected_table_accessors_find_named_entries() {
33579        let bundle = SqlReflectedTable {
33580            table_name: "orders".to_owned(),
33581            columns: vec![
33582                SqlColumnSchema {
33583                    name: "id".to_owned(),
33584                    declared_type: Some("INTEGER".to_owned()),
33585                    nullable: false,
33586                    default_value: None,
33587                    primary_key_ordinal: Some(0),
33588                    comment: None,
33589                    autoincrement: true,
33590                },
33591                SqlColumnSchema {
33592                    name: "user_id".to_owned(),
33593                    declared_type: Some("INTEGER".to_owned()),
33594                    nullable: false,
33595                    default_value: None,
33596                    primary_key_ordinal: None,
33597                    comment: None,
33598                    autoincrement: false,
33599                },
33600            ],
33601            primary_key_columns: vec!["id".to_owned()],
33602            indexes: vec![SqlIndexSchema {
33603                name: "idx_orders_user".to_owned(),
33604                columns: vec!["user_id".to_owned()],
33605                unique: false,
33606            }],
33607            foreign_keys: vec![SqlForeignKeySchema {
33608                constraint_name: None,
33609                columns: vec!["user_id".to_owned()],
33610                referenced_table: "users".to_owned(),
33611                referenced_columns: vec!["id".to_owned()],
33612            }],
33613            unique_constraints: vec![SqlUniqueConstraintSchema {
33614                name: "uq_orders_id".to_owned(),
33615                columns: vec!["id".to_owned()],
33616            }],
33617            comment: Some("Customer orders".to_owned()),
33618        };
33619
33620        // column(name): present + missing.
33621        let id = bundle.column("id").expect("id column");
33622        assert_eq!(id.declared_type.as_deref(), Some("INTEGER"));
33623        assert!(id.autoincrement);
33624        assert!(bundle.column("missing").is_none());
33625
33626        // index(name): present + missing.
33627        let idx = bundle.index("idx_orders_user").expect("idx");
33628        assert_eq!(idx.columns, vec!["user_id"]);
33629        assert!(bundle.index("idx_does_not_exist").is_none());
33630
33631        // unique_constraint(name).
33632        let uq = bundle.unique_constraint("uq_orders_id").expect("uq");
33633        assert_eq!(uq.columns, vec!["id"]);
33634        assert!(bundle.unique_constraint("uq_missing").is_none());
33635
33636        // foreign_keys_for_column(col): matches the FK touching user_id.
33637        let fks = bundle.foreign_keys_for_column("user_id");
33638        assert_eq!(fks.len(), 1);
33639        assert_eq!(fks[0].referenced_table, "users");
33640        // Column not part of any FK -> empty.
33641        assert!(bundle.foreign_keys_for_column("id").is_empty());
33642        assert!(bundle.foreign_keys_for_column("nonexistent").is_empty());
33643    }
33644
33645    #[test]
33646    fn sql_reflected_table_foreign_keys_for_column_handles_composite_fks() {
33647        let bundle = SqlReflectedTable {
33648            table_name: "rolling_fact".to_owned(),
33649            columns: vec![],
33650            primary_key_columns: vec![],
33651            indexes: vec![],
33652            foreign_keys: vec![SqlForeignKeySchema {
33653                constraint_name: None,
33654                columns: vec!["fyear".to_owned(), "fmonth".to_owned()],
33655                referenced_table: "rolling".to_owned(),
33656                referenced_columns: vec!["year".to_owned(), "month".to_owned()],
33657            }],
33658            unique_constraints: vec![],
33659            comment: None,
33660        };
33661        // Composite FK touches both fyear and fmonth — both should
33662        // surface the same FK.
33663        assert_eq!(bundle.foreign_keys_for_column("fyear").len(), 1);
33664        assert_eq!(bundle.foreign_keys_for_column("fmonth").len(), 1);
33665        assert!(bundle.foreign_keys_for_column("year").is_empty()); // referenced col, not from col
33666    }
33667
33668    #[test]
33669    fn sql_reflected_table_foreign_keys_for_column_returns_multiple_when_relevant() {
33670        // Rare but valid: one column participates in two FKs (e.g.
33671        // same column referenced by separate FKs to two parents).
33672        let bundle = SqlReflectedTable {
33673            table_name: "audit".to_owned(),
33674            columns: vec![],
33675            primary_key_columns: vec![],
33676            indexes: vec![],
33677            foreign_keys: vec![
33678                SqlForeignKeySchema {
33679                    constraint_name: Some("fk_audit_a".to_owned()),
33680                    columns: vec!["entity_id".to_owned()],
33681                    referenced_table: "users".to_owned(),
33682                    referenced_columns: vec!["id".to_owned()],
33683                },
33684                SqlForeignKeySchema {
33685                    constraint_name: Some("fk_audit_b".to_owned()),
33686                    columns: vec!["entity_id".to_owned()],
33687                    referenced_table: "products".to_owned(),
33688                    referenced_columns: vec!["id".to_owned()],
33689                },
33690            ],
33691            unique_constraints: vec![],
33692            comment: None,
33693        };
33694        let fks = bundle.foreign_keys_for_column("entity_id");
33695        assert_eq!(fks.len(), 2);
33696        // Order preserved.
33697        assert_eq!(fks[0].constraint_name.as_deref(), Some("fk_audit_a"));
33698        assert_eq!(fks[1].constraint_name.as_deref(), Some("fk_audit_b"));
33699    }
33700
33701    // ── indexes_for_column / unique_constraints_for_column (br-37uy / fd90.52) ─
33702
33703    #[test]
33704    fn sql_reflected_table_indexes_for_column_matches_any_position() {
33705        let bundle = SqlReflectedTable {
33706            table_name: "rolling".to_owned(),
33707            columns: vec![],
33708            primary_key_columns: vec![],
33709            indexes: vec![
33710                SqlIndexSchema {
33711                    name: "idx_rolling_year".to_owned(),
33712                    columns: vec!["year".to_owned()],
33713                    unique: false,
33714                },
33715                SqlIndexSchema {
33716                    name: "idx_rolling_y_m_c".to_owned(),
33717                    columns: vec!["year".to_owned(), "month".to_owned(), "code".to_owned()],
33718                    unique: false,
33719                },
33720            ],
33721            foreign_keys: vec![],
33722            unique_constraints: vec![],
33723            comment: None,
33724        };
33725
33726        // 'year' appears in both indexes (first in idx_year, first in
33727        // composite). Returns both.
33728        let year_idxs = bundle.indexes_for_column("year");
33729        assert_eq!(year_idxs.len(), 2);
33730
33731        // 'month' only appears in the composite index, in middle position.
33732        let month_idxs = bundle.indexes_for_column("month");
33733        assert_eq!(month_idxs.len(), 1);
33734        assert_eq!(month_idxs[0].name, "idx_rolling_y_m_c");
33735
33736        // 'code' appears only in the composite, last position.
33737        let code_idxs = bundle.indexes_for_column("code");
33738        assert_eq!(code_idxs.len(), 1);
33739
33740        // Column not in any index.
33741        assert!(bundle.indexes_for_column("nonexistent").is_empty());
33742    }
33743
33744    #[test]
33745    fn sql_reflected_table_unique_constraints_for_column_matches_any_position() {
33746        let bundle = SqlReflectedTable {
33747            table_name: "events".to_owned(),
33748            columns: vec![],
33749            primary_key_columns: vec![],
33750            indexes: vec![],
33751            foreign_keys: vec![],
33752            unique_constraints: vec![
33753                SqlUniqueConstraintSchema {
33754                    name: "uq_events_email".to_owned(),
33755                    columns: vec!["email".to_owned()],
33756                },
33757                SqlUniqueConstraintSchema {
33758                    name: "uq_events_user_event_ts".to_owned(),
33759                    columns: vec!["user_id".to_owned(), "event_id".to_owned(), "ts".to_owned()],
33760                },
33761            ],
33762            comment: None,
33763        };
33764
33765        let email_uqs = bundle.unique_constraints_for_column("email");
33766        assert_eq!(email_uqs.len(), 1);
33767        assert_eq!(email_uqs[0].name, "uq_events_email");
33768
33769        // 'event_id' middle position in composite.
33770        let event_uqs = bundle.unique_constraints_for_column("event_id");
33771        assert_eq!(event_uqs.len(), 1);
33772        assert_eq!(event_uqs[0].columns, vec!["user_id", "event_id", "ts"]);
33773
33774        // 'ts' last position in composite.
33775        let ts_uqs = bundle.unique_constraints_for_column("ts");
33776        assert_eq!(ts_uqs.len(), 1);
33777
33778        assert!(
33779            bundle
33780                .unique_constraints_for_column("nonexistent")
33781                .is_empty()
33782        );
33783    }
33784
33785    #[test]
33786    fn sql_reflected_table_for_column_accessors_return_multiple() {
33787        // A column can appear in multiple indexes / unique constraints.
33788        let bundle = SqlReflectedTable {
33789            table_name: "wide".to_owned(),
33790            columns: vec![],
33791            primary_key_columns: vec![],
33792            indexes: vec![
33793                SqlIndexSchema {
33794                    name: "idx_a".to_owned(),
33795                    columns: vec!["x".to_owned()],
33796                    unique: false,
33797                },
33798                SqlIndexSchema {
33799                    name: "idx_b".to_owned(),
33800                    columns: vec!["x".to_owned(), "y".to_owned()],
33801                    unique: true,
33802                },
33803            ],
33804            foreign_keys: vec![],
33805            unique_constraints: vec![
33806                SqlUniqueConstraintSchema {
33807                    name: "uq_a".to_owned(),
33808                    columns: vec!["x".to_owned()],
33809                },
33810                SqlUniqueConstraintSchema {
33811                    name: "uq_b".to_owned(),
33812                    columns: vec!["x".to_owned(), "z".to_owned()],
33813                },
33814            ],
33815            comment: None,
33816        };
33817
33818        let idx_for_x = bundle.indexes_for_column("x");
33819        assert_eq!(idx_for_x.len(), 2);
33820        assert_eq!(idx_for_x[0].name, "idx_a");
33821        assert_eq!(idx_for_x[1].name, "idx_b");
33822
33823        let uq_for_x = bundle.unique_constraints_for_column("x");
33824        assert_eq!(uq_for_x.len(), 2);
33825        assert_eq!(uq_for_x[0].name, "uq_a");
33826        assert_eq!(uq_for_x[1].name, "uq_b");
33827    }
33828
33829    // ── SqlInspector::reflect_all_tables (br-jmmo / fd90.53) ─────────────
33830
33831    #[cfg(feature = "sql-sqlite")]
33832    #[test]
33833    fn sql_inspector_reflect_all_tables_empty_db() {
33834        let conn = make_sql_test_conn();
33835        let inspector = SqlInspector::new(&conn);
33836        let bundles = inspector.reflect_all_tables(None).unwrap();
33837        assert!(bundles.is_empty());
33838    }
33839
33840    #[cfg(feature = "sql-sqlite")]
33841    #[test]
33842    fn sql_inspector_reflect_all_tables_returns_one_bundle_per_table() {
33843        let conn = make_sql_test_conn();
33844        super::SqlConnection::execute_batch(
33845            &conn,
33846            "CREATE TABLE alpha (id INTEGER PRIMARY KEY, name TEXT);",
33847        )
33848        .unwrap();
33849        super::SqlConnection::execute_batch(&conn, "CREATE TABLE beta (uid INTEGER, label TEXT);")
33850            .unwrap();
33851        let inspector = SqlInspector::new(&conn);
33852        let bundles = inspector.reflect_all_tables(None).unwrap();
33853        assert_eq!(bundles.len(), 2);
33854        // Ordered alphabetically by list_tables.
33855        assert_eq!(bundles[0].table_name, "alpha");
33856        assert_eq!(bundles[1].table_name, "beta");
33857        // Each bundle has full metadata.
33858        assert_eq!(
33859            bundles[0]
33860                .columns
33861                .iter()
33862                .map(|c| c.name.as_str())
33863                .collect::<Vec<_>>(),
33864            vec!["id", "name"]
33865        );
33866        assert_eq!(bundles[0].primary_key_columns, vec!["id"]);
33867        assert_eq!(bundles[1].columns.len(), 2);
33868        assert!(bundles[1].primary_key_columns.is_empty());
33869    }
33870
33871    #[test]
33872    fn sql_inspector_reflect_all_tables_skips_disappearing_tables() {
33873        // Race-condition stub: list_tables returns ["a", "b"] but
33874        // table_schema returns None for "b" (simulating a concurrent
33875        // DROP between list and reflect). reflect_all_tables must
33876        // skip "b" without erroring.
33877        struct DisappearingTable;
33878        impl super::SqlConnection for DisappearingTable {
33879            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
33880                Ok(SqlQueryResult {
33881                    columns: vec![],
33882                    rows: vec![],
33883                })
33884            }
33885            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
33886                Ok(())
33887            }
33888            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
33889                Ok(false)
33890            }
33891            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
33892                Ok(())
33893            }
33894            fn dtype_sql(&self, _dtype: DType) -> &'static str {
33895                "TEXT"
33896            }
33897            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
33898                "TEXT"
33899            }
33900            fn list_tables(&self, _schema: Option<&str>) -> Result<Vec<String>, IoError> {
33901                Ok(vec!["a".to_owned(), "b".to_owned()])
33902            }
33903            fn table_schema(
33904                &self,
33905                table: &str,
33906                _schema: Option<&str>,
33907            ) -> Result<Option<SqlTableSchema>, IoError> {
33908                if table == "a" {
33909                    Ok(Some(SqlTableSchema {
33910                        table_name: "a".to_owned(),
33911                        columns: vec![SqlColumnSchema {
33912                            name: "x".to_owned(),
33913                            declared_type: Some("INTEGER".to_owned()),
33914                            nullable: true,
33915                            default_value: None,
33916                            primary_key_ordinal: None,
33917                            comment: None,
33918                            autoincrement: false,
33919                        }],
33920                    }))
33921                } else {
33922                    // b "disappeared" between list and reflect.
33923                    Ok(None)
33924                }
33925            }
33926        }
33927        let conn = DisappearingTable;
33928        let inspector = SqlInspector::new(&conn);
33929        let bundles = inspector.reflect_all_tables(None).unwrap();
33930        assert_eq!(bundles.len(), 1);
33931        assert_eq!(bundles[0].table_name, "a");
33932    }
33933
33934    #[test]
33935    fn sql_inspector_reflect_all_tables_routes_schema_arg() {
33936        // Multi-schema stub: list_tables returns different sets per
33937        // schema; reflect_all_tables must propagate the schema arg.
33938        struct MultiSchemaReflect;
33939        impl super::SqlConnection for MultiSchemaReflect {
33940            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
33941                Ok(SqlQueryResult {
33942                    columns: vec![],
33943                    rows: vec![],
33944                })
33945            }
33946            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
33947                Ok(())
33948            }
33949            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
33950                Ok(false)
33951            }
33952            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
33953                Ok(())
33954            }
33955            fn dtype_sql(&self, _dtype: DType) -> &'static str {
33956                "TEXT"
33957            }
33958            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
33959                "TEXT"
33960            }
33961            fn supports_schemas(&self) -> bool {
33962                true
33963            }
33964            fn list_tables(&self, schema: Option<&str>) -> Result<Vec<String>, IoError> {
33965                Ok(match schema {
33966                    Some("analytics") => vec!["events".to_owned()],
33967                    _ => vec![],
33968                })
33969            }
33970            fn table_schema(
33971                &self,
33972                table: &str,
33973                schema: Option<&str>,
33974            ) -> Result<Option<SqlTableSchema>, IoError> {
33975                if table == "events" && schema == Some("analytics") {
33976                    Ok(Some(SqlTableSchema {
33977                        table_name: "events".to_owned(),
33978                        columns: vec![SqlColumnSchema {
33979                            name: "ts".to_owned(),
33980                            declared_type: Some("TIMESTAMPTZ".to_owned()),
33981                            nullable: false,
33982                            default_value: None,
33983                            primary_key_ordinal: None,
33984                            comment: None,
33985                            autoincrement: false,
33986                        }],
33987                    }))
33988                } else {
33989                    Ok(None)
33990                }
33991            }
33992        }
33993        let conn = MultiSchemaReflect;
33994        let inspector = SqlInspector::new(&conn);
33995        let bundles = inspector.reflect_all_tables(Some("analytics")).unwrap();
33996        assert_eq!(bundles.len(), 1);
33997        assert_eq!(bundles[0].table_name, "events");
33998        assert_eq!(
33999            bundles[0].columns[0].declared_type.as_deref(),
34000            Some("TIMESTAMPTZ")
34001        );
34002        // Wrong schema -> empty.
34003        assert!(
34004            inspector
34005                .reflect_all_tables(Some("audit"))
34006                .unwrap()
34007                .is_empty()
34008        );
34009    }
34010
34011    // ── SqlInspector::reflect_all_views (br-zuqt / fd90.54) ──────────────
34012
34013    #[cfg(feature = "sql-sqlite")]
34014    #[test]
34015    fn sql_inspector_reflect_all_views_empty_db() {
34016        let conn = make_sql_test_conn();
34017        let inspector = SqlInspector::new(&conn);
34018        let bundles = inspector.reflect_all_views(None).unwrap();
34019        assert!(bundles.is_empty());
34020    }
34021
34022    #[cfg(feature = "sql-sqlite")]
34023    #[test]
34024    fn sql_inspector_reflect_all_views_returns_one_bundle_per_view() {
34025        let conn = make_sql_test_conn();
34026        super::SqlConnection::execute_batch(&conn, "CREATE TABLE base (id INTEGER, label TEXT);")
34027            .unwrap();
34028        super::SqlConnection::execute_batch(
34029            &conn,
34030            "CREATE VIEW alpha_view AS SELECT id FROM base;",
34031        )
34032        .unwrap();
34033        super::SqlConnection::execute_batch(
34034            &conn,
34035            "CREATE VIEW zebra_view AS SELECT label FROM base;",
34036        )
34037        .unwrap();
34038        let inspector = SqlInspector::new(&conn);
34039        let bundles = inspector.reflect_all_views(None).unwrap();
34040        // Tables ARE NOT included — only views.
34041        assert_eq!(bundles.len(), 2);
34042        assert_eq!(bundles[0].table_name, "alpha_view");
34043        assert_eq!(bundles[1].table_name, "zebra_view");
34044        // Each view's columns are surfaced via PRAGMA table_info.
34045        assert_eq!(
34046            bundles[0]
34047                .columns
34048                .iter()
34049                .map(|c| c.name.as_str())
34050                .collect::<Vec<_>>(),
34051            vec!["id"]
34052        );
34053        assert_eq!(
34054            bundles[1]
34055                .columns
34056                .iter()
34057                .map(|c| c.name.as_str())
34058                .collect::<Vec<_>>(),
34059            vec!["label"]
34060        );
34061        // Views don't carry constraints — PK/FK/UC/index lists are empty.
34062        for bundle in &bundles {
34063            assert!(bundle.primary_key_columns.is_empty());
34064            assert!(bundle.indexes.is_empty());
34065            assert!(bundle.foreign_keys.is_empty());
34066            assert!(bundle.unique_constraints.is_empty());
34067        }
34068    }
34069
34070    #[test]
34071    fn sql_inspector_reflect_all_views_routes_schema_arg() {
34072        // Multi-schema stub: list_views returns different sets per schema.
34073        struct MultiSchemaViewReflect;
34074        impl super::SqlConnection for MultiSchemaViewReflect {
34075            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
34076                Ok(SqlQueryResult {
34077                    columns: vec![],
34078                    rows: vec![],
34079                })
34080            }
34081            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
34082                Ok(())
34083            }
34084            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
34085                Ok(false)
34086            }
34087            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
34088                Ok(())
34089            }
34090            fn dtype_sql(&self, _dtype: DType) -> &'static str {
34091                "TEXT"
34092            }
34093            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
34094                "TEXT"
34095            }
34096            fn supports_schemas(&self) -> bool {
34097                true
34098            }
34099            fn list_views(&self, schema: Option<&str>) -> Result<Vec<String>, IoError> {
34100                Ok(match schema {
34101                    Some("reporting") => vec!["weekly_summary".to_owned()],
34102                    _ => vec![],
34103                })
34104            }
34105            fn table_schema(
34106                &self,
34107                table: &str,
34108                schema: Option<&str>,
34109            ) -> Result<Option<SqlTableSchema>, IoError> {
34110                if table == "weekly_summary" && schema == Some("reporting") {
34111                    Ok(Some(SqlTableSchema {
34112                        table_name: "weekly_summary".to_owned(),
34113                        columns: vec![SqlColumnSchema {
34114                            name: "week".to_owned(),
34115                            declared_type: Some("DATE".to_owned()),
34116                            nullable: true,
34117                            default_value: None,
34118                            primary_key_ordinal: None,
34119                            comment: None,
34120                            autoincrement: false,
34121                        }],
34122                    }))
34123                } else {
34124                    Ok(None)
34125                }
34126            }
34127        }
34128        let conn = MultiSchemaViewReflect;
34129        let inspector = SqlInspector::new(&conn);
34130        let bundles = inspector.reflect_all_views(Some("reporting")).unwrap();
34131        assert_eq!(bundles.len(), 1);
34132        assert_eq!(bundles[0].table_name, "weekly_summary");
34133        assert_eq!(bundles[0].columns[0].declared_type.as_deref(), Some("DATE"));
34134        // Wrong schema -> empty.
34135        assert!(
34136            inspector
34137                .reflect_all_views(Some("audit"))
34138                .unwrap()
34139                .is_empty()
34140        );
34141    }
34142
34143    #[test]
34144    fn sql_inspector_reflect_table_calls_table_schema_only_once() {
34145        // Per fd90.43: reflect_table must derive primary_key_columns
34146        // from the fetched SqlTableSchema rather than dispatching
34147        // primary_key_columns() (which itself calls table_schema). A
34148        // recording stub counts table_schema invocations and asserts
34149        // exactly one round-trip.
34150        use std::cell::Cell;
34151        struct CountingTableSchema {
34152            table_schema_calls: Cell<usize>,
34153        }
34154        impl super::SqlConnection for CountingTableSchema {
34155            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
34156                Ok(SqlQueryResult {
34157                    columns: vec![],
34158                    rows: vec![],
34159                })
34160            }
34161            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
34162                Ok(())
34163            }
34164            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
34165                Ok(false)
34166            }
34167            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
34168                Ok(())
34169            }
34170            fn dtype_sql(&self, _dtype: DType) -> &'static str {
34171                "TEXT"
34172            }
34173            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
34174                "TEXT"
34175            }
34176            fn table_schema(
34177                &self,
34178                _table: &str,
34179                _schema: Option<&str>,
34180            ) -> Result<Option<SqlTableSchema>, IoError> {
34181                self.table_schema_calls
34182                    .set(self.table_schema_calls.get() + 1);
34183                Ok(Some(SqlTableSchema {
34184                    table_name: "x".to_owned(),
34185                    columns: vec![SqlColumnSchema {
34186                        name: "id".to_owned(),
34187                        declared_type: Some("BIGINT".to_owned()),
34188                        nullable: false,
34189                        default_value: None,
34190                        primary_key_ordinal: Some(0),
34191                        comment: None,
34192                        autoincrement: true,
34193                    }],
34194                }))
34195            }
34196        }
34197        let conn = CountingTableSchema {
34198            table_schema_calls: Cell::new(0),
34199        };
34200        let inspector = SqlInspector::new(&conn);
34201        let bundle = inspector.reflect_table("x", None).unwrap().unwrap();
34202        // Exactly one table_schema fetch — primary_key_columns derived
34203        // from the fetched meta, NOT a second round-trip.
34204        assert_eq!(conn.table_schema_calls.get(), 1);
34205        assert_eq!(bundle.primary_key_columns, vec!["id"]);
34206    }
34207
34208    // ── SqlReadOptions default coerce_float (br-o0x6 / fd90.41) ──────────
34209
34210    #[test]
34211    fn sql_read_options_default_coerce_float_matches_pandas() {
34212        // Pandas defaults coerce_float=True for read_sql / read_sql_query
34213        // / read_sql_table. We must match — any bare ::default() call
34214        // should opt INTO coerce_float, not opt out.
34215        let opts = SqlReadOptions::default();
34216        assert!(
34217            opts.coerce_float,
34218            "default coerce_float must be true (pandas parity)"
34219        );
34220        // Sanity: other defaults are the natural empty / None values.
34221        assert!(opts.params.is_none());
34222        assert!(opts.parse_dates.is_none());
34223        assert!(opts.dtype.is_none());
34224        assert!(opts.schema.is_none());
34225        assert!(opts.columns.is_none());
34226        assert!(opts.index_col.is_none());
34227    }
34228
34229    // ── SQL identifier quoting regression matrix (br-frankenpandas-fd90.12) ─
34230    //
34231    // Cross-product of (ANSI / MySQL backtick / MSSQL bracket) quoting
34232    // backends × (SELECT * / SELECT cols / CREATE TABLE / INSERT /
34233    // multi-row INSERT / DROP / TRUNCATE) × identifier shapes that the
34234    // shared validator currently allows: reserved-word names, mixed case,
34235    // leading digits, embedded quote chars (where the backend defines an
34236    // escape rule). All tests are pure query-builder assertions — no live
34237    // backend touched.
34238
34239    #[derive(Default)]
34240    struct AnsiSchemaConn;
34241    impl super::SqlConnection for AnsiSchemaConn {
34242        fn query(&self, _q: &str, _p: &[Scalar]) -> Result<super::SqlQueryResult, IoError> {
34243            Ok(super::SqlQueryResult {
34244                columns: vec![],
34245                rows: vec![],
34246            })
34247        }
34248        fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
34249            Ok(())
34250        }
34251        fn table_exists(&self, _n: &str) -> Result<bool, IoError> {
34252            Ok(false)
34253        }
34254        fn insert_rows(&self, _s: &str, _r: &[Vec<Scalar>]) -> Result<(), IoError> {
34255            Ok(())
34256        }
34257        fn dtype_sql(&self, _d: DType) -> &'static str {
34258            "TEXT"
34259        }
34260        fn index_dtype_sql(&self, _i: &Index) -> &'static str {
34261            "TEXT"
34262        }
34263        fn supports_schemas(&self) -> bool {
34264            true
34265        }
34266        fn parameter_marker(&self, ordinal: usize) -> String {
34267            format!("${ordinal}")
34268        }
34269        fn max_identifier_length(&self) -> Option<usize> {
34270            Some(63)
34271        }
34272    }
34273
34274    #[derive(Default)]
34275    struct MysqlBacktickConn;
34276    impl super::SqlConnection for MysqlBacktickConn {
34277        fn query(&self, _q: &str, _p: &[Scalar]) -> Result<super::SqlQueryResult, IoError> {
34278            Ok(super::SqlQueryResult {
34279                columns: vec![],
34280                rows: vec![],
34281            })
34282        }
34283        fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
34284            Ok(())
34285        }
34286        fn table_exists(&self, _n: &str) -> Result<bool, IoError> {
34287            Ok(false)
34288        }
34289        fn insert_rows(&self, _s: &str, _r: &[Vec<Scalar>]) -> Result<(), IoError> {
34290            Ok(())
34291        }
34292        fn dtype_sql(&self, _d: DType) -> &'static str {
34293            "TEXT"
34294        }
34295        fn index_dtype_sql(&self, _i: &Index) -> &'static str {
34296            "TEXT"
34297        }
34298        fn supports_schemas(&self) -> bool {
34299            true
34300        }
34301        fn parameter_marker(&self, _ordinal: usize) -> String {
34302            "?".to_owned()
34303        }
34304        fn max_identifier_length(&self) -> Option<usize> {
34305            Some(64)
34306        }
34307        fn quote_identifier(&self, ident: &str) -> Result<String, IoError> {
34308            if ident.contains('\0') {
34309                return Err(IoError::Sql("invalid SQL identifier: NUL byte".to_owned()));
34310            }
34311            Ok(format!("`{}`", ident.replace('`', "``")))
34312        }
34313    }
34314
34315    #[derive(Default)]
34316    struct MssqlBracketConn;
34317    impl super::SqlConnection for MssqlBracketConn {
34318        fn query(&self, _q: &str, _p: &[Scalar]) -> Result<super::SqlQueryResult, IoError> {
34319            Ok(super::SqlQueryResult {
34320                columns: vec![],
34321                rows: vec![],
34322            })
34323        }
34324        fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
34325            Ok(())
34326        }
34327        fn table_exists(&self, _n: &str) -> Result<bool, IoError> {
34328            Ok(false)
34329        }
34330        fn insert_rows(&self, _s: &str, _r: &[Vec<Scalar>]) -> Result<(), IoError> {
34331            Ok(())
34332        }
34333        fn dtype_sql(&self, _d: DType) -> &'static str {
34334            "NVARCHAR(MAX)"
34335        }
34336        fn index_dtype_sql(&self, _i: &Index) -> &'static str {
34337            "NVARCHAR(MAX)"
34338        }
34339        fn supports_schemas(&self) -> bool {
34340            true
34341        }
34342        fn parameter_marker(&self, ordinal: usize) -> String {
34343            format!("@p{ordinal}")
34344        }
34345        fn max_identifier_length(&self) -> Option<usize> {
34346            Some(128)
34347        }
34348        fn quote_identifier(&self, ident: &str) -> Result<String, IoError> {
34349            if ident.contains('\0') {
34350                return Err(IoError::Sql("invalid SQL identifier: NUL byte".to_owned()));
34351            }
34352            // T-SQL bracket quoting: doubled `]` escapes a literal `]`.
34353            Ok(format!("[{}]", ident.replace(']', "]]")))
34354        }
34355    }
34356
34357    /// Reserved SQL keywords that the shape validator allows as
34358    /// alphanumeric identifiers — they must round-trip through every
34359    /// query builder safely (i.e. quoted, never bare).
34360    const FD90_12_RESERVED_WORDS: &[&str] = &[
34361        "select", "from", "where", "order", "group", "table", "index", "join",
34362    ];
34363
34364    #[test]
34365    fn fd90_12_quoting_matrix_select_all_reserved_words_quoted_per_dialect() {
34366        let ansi = AnsiSchemaConn;
34367        let mysql = MysqlBacktickConn;
34368        let mssql = MssqlBracketConn;
34369        for word in FD90_12_RESERVED_WORDS {
34370            assert_eq!(
34371                super::sql_select_all_query(&ansi, word).expect("ansi select"),
34372                format!("SELECT * FROM \"{word}\""),
34373                "ansi reserved word `{word}`"
34374            );
34375            assert_eq!(
34376                super::sql_select_all_query(&mysql, word).expect("mysql select"),
34377                format!("SELECT * FROM `{word}`"),
34378                "mysql reserved word `{word}`"
34379            );
34380            assert_eq!(
34381                super::sql_select_all_query(&mssql, word).expect("mssql select"),
34382                format!("SELECT * FROM [{word}]"),
34383                "mssql reserved word `{word}`"
34384            );
34385        }
34386    }
34387
34388    #[test]
34389    fn fd90_12_quoting_matrix_select_columns_mixed_case_preserved_per_dialect() {
34390        let ansi = AnsiSchemaConn;
34391        let mysql = MysqlBacktickConn;
34392        let mssql = MssqlBracketConn;
34393        let cases: &[&str] = &["MyCol", "MIXEDcase", "camelCase", "SCREAMING_SNAKE"];
34394        for col in cases {
34395            assert_eq!(
34396                super::sql_select_columns_query(&ansi, "users", &[col]).expect("ansi cols"),
34397                format!("SELECT \"{col}\" FROM \"users\""),
34398                "ansi mixed-case col `{col}`"
34399            );
34400            assert_eq!(
34401                super::sql_select_columns_query(&mysql, "users", &[col]).expect("mysql cols"),
34402                format!("SELECT `{col}` FROM `users`"),
34403                "mysql mixed-case col `{col}`"
34404            );
34405            assert_eq!(
34406                super::sql_select_columns_query(&mssql, "users", &[col]).expect("mssql cols"),
34407                format!("SELECT [{col}] FROM [users]"),
34408                "mssql mixed-case col `{col}`"
34409            );
34410        }
34411    }
34412
34413    #[test]
34414    fn fd90_12_quoting_matrix_leading_digit_identifiers_quoted_per_dialect() {
34415        let ansi = AnsiSchemaConn;
34416        let mysql = MysqlBacktickConn;
34417        let mssql = MssqlBracketConn;
34418        let cases: &[&str] = &["1col", "2nd_place", "9lives", "123"];
34419        for col in cases {
34420            assert_eq!(
34421                super::sql_select_columns_query(&ansi, "tbl", &[col]).expect("ansi"),
34422                format!("SELECT \"{col}\" FROM \"tbl\"")
34423            );
34424            assert_eq!(
34425                super::sql_select_columns_query(&mysql, "tbl", &[col]).expect("mysql"),
34426                format!("SELECT `{col}` FROM `tbl`")
34427            );
34428            assert_eq!(
34429                super::sql_select_columns_query(&mssql, "tbl", &[col]).expect("mssql"),
34430                format!("SELECT [{col}] FROM [tbl]")
34431            );
34432        }
34433    }
34434
34435    #[test]
34436    fn fd90_12_quoting_matrix_schema_qualified_select_per_dialect() {
34437        let ansi = AnsiSchemaConn;
34438        let mysql = MysqlBacktickConn;
34439        let mssql = MssqlBracketConn;
34440        assert_eq!(
34441            super::sql_select_all_query_in_schema(&ansi, "users", Some("analytics")).expect("ansi"),
34442            "SELECT * FROM \"analytics\".\"users\""
34443        );
34444        assert_eq!(
34445            super::sql_select_all_query_in_schema(&mysql, "users", Some("analytics"))
34446                .expect("mysql"),
34447            "SELECT * FROM `analytics`.`users`"
34448        );
34449        assert_eq!(
34450            super::sql_select_all_query_in_schema(&mssql, "users", Some("dbo")).expect("mssql"),
34451            "SELECT * FROM [dbo].[users]"
34452        );
34453    }
34454
34455    #[test]
34456    fn fd90_12_quoting_matrix_create_table_per_dialect() {
34457        let ansi = AnsiSchemaConn;
34458        let mysql = MysqlBacktickConn;
34459        let mssql = MssqlBracketConn;
34460        let cols = vec![
34461            super::sql_column_definition(&ansi, "id", "BIGINT").expect("ansi col"),
34462            super::sql_column_definition(&ansi, "select", "TEXT").expect("ansi reserved col"),
34463        ];
34464        assert_eq!(
34465            super::sql_create_table_query_in_schema(&ansi, "events", Some("public"), &cols)
34466                .expect("ansi create"),
34467            "CREATE TABLE IF NOT EXISTS \"public\".\"events\" (\"id\" BIGINT, \"select\" TEXT)"
34468        );
34469        let mysql_cols = vec![
34470            super::sql_column_definition(&mysql, "id", "BIGINT").expect("mysql col"),
34471            super::sql_column_definition(&mysql, "select", "TEXT").expect("mysql reserved col"),
34472        ];
34473        assert_eq!(
34474            super::sql_create_table_query_in_schema(
34475                &mysql,
34476                "events",
34477                Some("analytics"),
34478                &mysql_cols
34479            )
34480            .expect("mysql create"),
34481            "CREATE TABLE IF NOT EXISTS `analytics`.`events` (`id` BIGINT, `select` TEXT)"
34482        );
34483        let mssql_cols = vec![
34484            super::sql_column_definition(&mssql, "id", "BIGINT").expect("mssql col"),
34485            super::sql_column_definition(&mssql, "select", "NVARCHAR(MAX)")
34486                .expect("mssql reserved col"),
34487        ];
34488        assert_eq!(
34489            super::sql_create_table_query_in_schema(&mssql, "events", Some("dbo"), &mssql_cols)
34490                .expect("mssql create"),
34491            "CREATE TABLE IF NOT EXISTS [dbo].[events] ([id] BIGINT, [select] NVARCHAR(MAX))"
34492        );
34493    }
34494
34495    #[test]
34496    fn fd90_12_quoting_matrix_insert_per_dialect_with_param_markers() {
34497        let ansi = AnsiSchemaConn;
34498        let mysql = MysqlBacktickConn;
34499        let mssql = MssqlBracketConn;
34500        let cols = vec!["id".to_owned(), "MixedCase".to_owned(), "select".to_owned()];
34501        assert_eq!(
34502            super::sql_insert_rows_query_in_schema(&ansi, "events", Some("public"), &cols)
34503                .expect("ansi insert"),
34504            "INSERT INTO \"public\".\"events\" (\"id\", \"MixedCase\", \"select\") VALUES ($1, $2, $3)"
34505        );
34506        assert_eq!(
34507            super::sql_insert_rows_query_in_schema(&mysql, "events", Some("analytics"), &cols)
34508                .expect("mysql insert"),
34509            "INSERT INTO `analytics`.`events` (`id`, `MixedCase`, `select`) VALUES (?, ?, ?)"
34510        );
34511        assert_eq!(
34512            super::sql_insert_rows_query_in_schema(&mssql, "events", Some("dbo"), &cols)
34513                .expect("mssql insert"),
34514            "INSERT INTO [dbo].[events] ([id], [MixedCase], [select]) VALUES (@p1, @p2, @p3)"
34515        );
34516    }
34517
34518    #[test]
34519    fn fd90_12_quoting_matrix_multi_row_insert_param_ordinals_span_rows() {
34520        let ansi = AnsiSchemaConn;
34521        let mysql = MysqlBacktickConn;
34522        let cols = vec!["a".to_owned(), "b".to_owned()];
34523        assert_eq!(
34524            super::sql_multi_row_insert_query_in_schema(&ansi, "tbl", None, &cols, 2)
34525                .expect("ansi multi"),
34526            "INSERT INTO \"tbl\" (\"a\", \"b\") VALUES ($1, $2), ($3, $4)"
34527        );
34528        assert_eq!(
34529            super::sql_multi_row_insert_query_in_schema(&mysql, "tbl", None, &cols, 2)
34530                .expect("mysql multi"),
34531            "INSERT INTO `tbl` (`a`, `b`) VALUES (?, ?), (?, ?)"
34532        );
34533    }
34534
34535    #[test]
34536    fn fd90_12_quoting_matrix_drop_table_per_dialect() {
34537        let ansi = AnsiSchemaConn;
34538        let mysql = MysqlBacktickConn;
34539        let mssql = MssqlBracketConn;
34540        assert_eq!(
34541            super::sql_drop_table_query_in_schema(&ansi, "events", Some("public"))
34542                .expect("ansi drop"),
34543            "DROP TABLE IF EXISTS \"public\".\"events\""
34544        );
34545        assert_eq!(
34546            super::sql_drop_table_query_in_schema(&mysql, "events", Some("analytics"))
34547                .expect("mysql drop"),
34548            "DROP TABLE IF EXISTS `analytics`.`events`"
34549        );
34550        assert_eq!(
34551            super::sql_drop_table_query_in_schema(&mssql, "events", Some("dbo"))
34552                .expect("mssql drop"),
34553            "DROP TABLE IF EXISTS [dbo].[events]"
34554        );
34555    }
34556
34557    #[test]
34558    fn fd90_12_quoting_matrix_truncate_uses_default_delete_with_per_dialect_quoting() {
34559        // Default truncate_table impl emits `DELETE FROM <quoted>` and
34560        // routes through the backend's quote_identifier.
34561        #[derive(Default)]
34562        struct CapturingAnsi {
34563            captured: std::cell::RefCell<Vec<String>>,
34564        }
34565        impl super::SqlConnection for CapturingAnsi {
34566            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<super::SqlQueryResult, IoError> {
34567                Ok(super::SqlQueryResult {
34568                    columns: vec![],
34569                    rows: vec![],
34570                })
34571            }
34572            fn execute_batch(&self, sql: &str) -> Result<(), IoError> {
34573                self.captured.borrow_mut().push(sql.to_owned());
34574                Ok(())
34575            }
34576            fn table_exists(&self, _n: &str) -> Result<bool, IoError> {
34577                Ok(false)
34578            }
34579            fn insert_rows(&self, _s: &str, _r: &[Vec<Scalar>]) -> Result<(), IoError> {
34580                Ok(())
34581            }
34582            fn dtype_sql(&self, _d: DType) -> &'static str {
34583                "TEXT"
34584            }
34585            fn index_dtype_sql(&self, _i: &Index) -> &'static str {
34586                "TEXT"
34587            }
34588            fn supports_schemas(&self) -> bool {
34589                true
34590            }
34591        }
34592        let ansi = CapturingAnsi::default();
34593        super::SqlConnection::truncate_table(&ansi, "events", Some("public"))
34594            .expect("ansi truncate");
34595        assert_eq!(
34596            ansi.captured.borrow().as_slice(),
34597            &["DELETE FROM \"public\".\"events\"".to_owned()]
34598        );
34599
34600        #[derive(Default)]
34601        struct CapturingMysql {
34602            captured: std::cell::RefCell<Vec<String>>,
34603        }
34604        impl super::SqlConnection for CapturingMysql {
34605            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<super::SqlQueryResult, IoError> {
34606                Ok(super::SqlQueryResult {
34607                    columns: vec![],
34608                    rows: vec![],
34609                })
34610            }
34611            fn execute_batch(&self, sql: &str) -> Result<(), IoError> {
34612                self.captured.borrow_mut().push(sql.to_owned());
34613                Ok(())
34614            }
34615            fn table_exists(&self, _n: &str) -> Result<bool, IoError> {
34616                Ok(false)
34617            }
34618            fn insert_rows(&self, _s: &str, _r: &[Vec<Scalar>]) -> Result<(), IoError> {
34619                Ok(())
34620            }
34621            fn dtype_sql(&self, _d: DType) -> &'static str {
34622                "TEXT"
34623            }
34624            fn index_dtype_sql(&self, _i: &Index) -> &'static str {
34625                "TEXT"
34626            }
34627            fn supports_schemas(&self) -> bool {
34628                true
34629            }
34630            fn quote_identifier(&self, ident: &str) -> Result<String, IoError> {
34631                if ident.contains('\0') {
34632                    return Err(IoError::Sql("invalid SQL identifier: NUL byte".to_owned()));
34633                }
34634                Ok(format!("`{}`", ident.replace('`', "``")))
34635            }
34636        }
34637        let mysql = CapturingMysql::default();
34638        super::SqlConnection::truncate_table(&mysql, "events", Some("analytics"))
34639            .expect("mysql truncate");
34640        assert_eq!(
34641            mysql.captured.borrow().as_slice(),
34642            &["DELETE FROM `analytics`.`events`".to_owned()]
34643        );
34644    }
34645
34646    #[test]
34647    fn fd90_12_quoting_matrix_embedded_quote_chars_doubled_per_dialect() {
34648        // Embedded quote chars must be doubled per the dialect's escape
34649        // rule. quote_identifier is exposed for column names which may
34650        // legitimately contain embedded quotes (sql_column_definition
34651        // takes any string).
34652        let ansi = AnsiSchemaConn;
34653        let mysql = MysqlBacktickConn;
34654        let mssql = MssqlBracketConn;
34655        use super::SqlConnection as _;
34656        assert_eq!(ansi.quote_identifier("a\"b").expect("ansi"), "\"a\"\"b\"");
34657        assert_eq!(mysql.quote_identifier("a`b").expect("mysql"), "`a``b`");
34658        assert_eq!(mssql.quote_identifier("a]b").expect("mssql"), "[a]]b]");
34659        // Cross-dialect non-escape: ANSI doesn't escape backticks, etc.
34660        assert_eq!(
34661            ansi.quote_identifier("a`b")
34662                .expect("ansi backtick passthrough"),
34663            "\"a`b\""
34664        );
34665        assert_eq!(
34666            mysql
34667                .quote_identifier("a\"b")
34668                .expect("mysql quote passthrough"),
34669            "`a\"b`"
34670        );
34671        assert_eq!(
34672            mssql
34673                .quote_identifier("a\"b")
34674                .expect("mssql quote passthrough"),
34675            "[a\"b]"
34676        );
34677    }
34678
34679    #[test]
34680    fn fd90_12_quoting_matrix_long_identifier_within_cap_succeeds_over_cap_rejected() {
34681        // PG cap = 63, MySQL cap = 64, MSSQL cap = 128.
34682        use super::SqlConnection as _;
34683        let ansi = AnsiSchemaConn;
34684        let mysql = MysqlBacktickConn;
34685        let mssql = MssqlBracketConn;
34686        let pg63 = "a".repeat(63);
34687        let pg64 = "a".repeat(64);
34688        let mysql64 = "b".repeat(64);
34689        let mysql65 = "b".repeat(65);
34690        let mssql128 = "c".repeat(128);
34691        let mssql129 = "c".repeat(129);
34692
34693        super::validate_sql_identifier_length(&pg63, ansi.max_identifier_length(), "table")
34694            .expect("pg 63 ok");
34695        super::validate_sql_identifier_length(&mysql64, mysql.max_identifier_length(), "table")
34696            .expect("mysql 64 ok");
34697        super::validate_sql_identifier_length(&mssql128, mssql.max_identifier_length(), "table")
34698            .expect("mssql 128 ok");
34699
34700        let err =
34701            super::validate_sql_identifier_length(&pg64, ansi.max_identifier_length(), "table")
34702                .expect_err("pg 64 over cap");
34703        assert!(matches!(err, IoError::Sql(msg) if msg.contains("63") && msg.contains("table")));
34704        let err =
34705            super::validate_sql_identifier_length(&mysql65, mysql.max_identifier_length(), "table")
34706                .expect_err("mysql 65 over cap");
34707        assert!(matches!(err, IoError::Sql(msg) if msg.contains("64")));
34708        let err = super::validate_sql_identifier_length(
34709            &mssql129,
34710            mssql.max_identifier_length(),
34711            "table",
34712        )
34713        .expect_err("mssql 129 over cap");
34714        assert!(matches!(err, IoError::Sql(msg) if msg.contains("128")));
34715    }
34716
34717    #[test]
34718    fn fd90_12_query_builders_enforce_identifier_length_caps() {
34719        fn assert_length_error(err: IoError, kind: &str) {
34720            assert!(
34721                matches!(&err, IoError::Sql(msg)
34722                    if msg.contains(kind)
34723                        && msg.contains("63")
34724                        && msg.contains("backend identifier limit")),
34725                "expected SQL identifier-length error for {kind}, got {err:?}"
34726            );
34727        }
34728
34729        let conn = AnsiSchemaConn;
34730        let over_cap = "a".repeat(64);
34731        let cols = vec![over_cap.clone()];
34732        let defs = vec!["id BIGINT".to_owned()];
34733
34734        assert_length_error(
34735            super::sql_select_all_query_in_schema(&conn, &over_cap, None)
34736                .expect_err("SELECT * table over cap"),
34737            "table",
34738        );
34739        assert_length_error(
34740            super::sql_select_all_query_in_schema(&conn, "events", Some(&over_cap))
34741                .expect_err("SELECT * schema over cap"),
34742            "schema",
34743        );
34744        assert_length_error(
34745            super::sql_select_columns_query_in_schema(&conn, "events", None, &[over_cap.as_str()])
34746                .expect_err("SELECT column over cap"),
34747            "column",
34748        );
34749        assert_length_error(
34750            super::sql_create_table_query_in_schema(&conn, &over_cap, None, &defs)
34751                .expect_err("CREATE table over cap"),
34752            "table",
34753        );
34754        assert_length_error(
34755            super::sql_insert_rows_query_in_schema(&conn, "events", None, &cols)
34756                .expect_err("INSERT column over cap"),
34757            "column",
34758        );
34759        assert_length_error(
34760            super::sql_multi_row_insert_query_in_schema(&conn, "events", None, &cols, 1)
34761                .expect_err("multi-row INSERT column over cap"),
34762            "column",
34763        );
34764        assert_length_error(
34765            super::sql_drop_table_query_in_schema(&conn, &over_cap, None)
34766                .expect_err("DROP table over cap"),
34767            "table",
34768        );
34769        assert_length_error(
34770            super::SqlConnection::truncate_table(&conn, &over_cap, None)
34771                .expect_err("TRUNCATE fallback table over cap"),
34772            "table",
34773        );
34774    }
34775
34776    #[test]
34777    fn fd90_12_quoting_matrix_special_characters_rejected_by_validator() {
34778        // Per validate_sql_ident: only alphanumeric + underscore allowed.
34779        // Special chars (`-`, `.`, ` `, `:`, `'`, `"`, `;`) and dotted
34780        // names must be rejected before they ever reach quote_identifier.
34781        let bad: &[&str] = &[
34782            "my-col",
34783            "my.col",
34784            "my col",
34785            "my:col",
34786            "my'col",
34787            "my\"col",
34788            "my;col",
34789            "schema.table",
34790            "DROP--",
34791            "",
34792        ];
34793        for name in bad {
34794            let err =
34795                super::validate_sql_table_name(name).expect_err(&format!("must reject `{name}`"));
34796            assert!(matches!(err, IoError::Sql(msg) if msg.contains("invalid table name")));
34797            let err = super::validate_sql_column_name(name)
34798                .expect_err(&format!("must reject col `{name}`"));
34799            assert!(matches!(err, IoError::Sql(msg) if msg.contains("invalid column name")));
34800        }
34801    }
34802
34803    #[test]
34804    fn fd90_12_quoting_matrix_nul_byte_rejected_at_quote_identifier_layer() {
34805        // Defense in depth: even if a backend's quote_identifier is
34806        // called with a NUL-containing string (bypassing
34807        // validate_sql_ident), every dialect must reject — guards
34808        // against C-string driver-layer statement injection via
34809        // embedded null terminators.
34810        use super::SqlConnection as _;
34811        let ansi = AnsiSchemaConn;
34812        let mysql = MysqlBacktickConn;
34813        let mssql = MssqlBracketConn;
34814        let err_ansi = ansi
34815            .quote_identifier("ab\0cd")
34816            .expect_err("ansi must reject NUL");
34817        assert!(matches!(err_ansi, IoError::Sql(msg) if msg.contains("NUL")));
34818        let err_mysql = mysql
34819            .quote_identifier("ab\0cd")
34820            .expect_err("mysql must reject NUL");
34821        assert!(matches!(err_mysql, IoError::Sql(msg) if msg.contains("NUL")));
34822        let err_mssql = mssql
34823            .quote_identifier("ab\0cd")
34824            .expect_err("mssql must reject NUL");
34825        assert!(matches!(err_mssql, IoError::Sql(msg) if msg.contains("NUL")));
34826    }
34827
34828    #[cfg(feature = "sql-sqlite")]
34829    #[test]
34830    fn read_sql_empty_typed_table_preserves_column_dtypes_ex8ec() {
34831        let conn = make_sql_test_conn();
34832        super::SqlConnection::execute_batch(
34833            &conn,
34834            "CREATE TABLE empty_typed_ex8ec (i INTEGER, t TEXT, r REAL);",
34835        )
34836        .expect("create");
34837        // No INSERTs — empty result set.
34838
34839        let frame = read_sql(&conn, "SELECT * FROM empty_typed_ex8ec").expect("read empty");
34840        assert_eq!(frame.index().len(), 0, "empty table should yield zero rows");
34841
34842        let i_col = frame.column("i").expect("column i must exist");
34843        assert_eq!(i_col.dtype(), crate::DType::Int64);
34844        let t_col = frame.column("t").expect("column t must exist");
34845        assert_eq!(t_col.dtype(), crate::DType::Utf8);
34846        let r_col = frame.column("r").expect("column r must exist");
34847        assert_eq!(r_col.dtype(), crate::DType::Float64);
34848    }
34849
34850    #[cfg(feature = "sql-sqlite")]
34851    #[test]
34852    fn read_sql_all_null_typed_table_preserves_column_dtypes_0qo9c() {
34853        let conn = make_sql_test_conn();
34854        super::SqlConnection::execute_batch(
34855            &conn,
34856            "CREATE TABLE all_null_typed_0qo9c (i INTEGER, t TEXT, r REAL);
34857             INSERT INTO all_null_typed_0qo9c (i, t, r) VALUES (NULL, NULL, NULL);",
34858        )
34859        .expect("create and insert");
34860
34861        let frame = read_sql(&conn, "SELECT * FROM all_null_typed_0qo9c")
34862            .expect("read all-null typed table");
34863        assert_eq!(frame.index().len(), 1);
34864
34865        let i_col = frame.column("i").expect("column i must exist");
34866        assert_eq!(i_col.dtype(), crate::DType::Int64);
34867        assert!(i_col.values()[0].is_missing());
34868        let t_col = frame.column("t").expect("column t must exist");
34869        assert_eq!(t_col.dtype(), crate::DType::Utf8);
34870        assert!(t_col.values()[0].is_missing());
34871        let r_col = frame.column("r").expect("column r must exist");
34872        assert_eq!(r_col.dtype(), crate::DType::Float64);
34873        assert!(r_col.values()[0].is_missing());
34874    }
34875}
34876
34877#[cfg(test)]
34878mod fused_numeric_csv_field_tests {
34879    use super::{
34880        CsvTypedColumnValues, fuse_scan_numeric_csv_field, push_csv_default_numeric_field,
34881        push_fused_numeric_csv_field,
34882    };
34883
34884    fn assert_same_columns(base: &CsvTypedColumnValues, fused: &CsvTypedColumnValues, token: &str) {
34885        match (base, fused) {
34886            (CsvTypedColumnValues::Int64(lhs), CsvTypedColumnValues::Int64(rhs)) => {
34887                assert_eq!(lhs, rhs, "Int64 mismatch for token {token:?}");
34888            }
34889            (CsvTypedColumnValues::Float64(lhs), CsvTypedColumnValues::Float64(rhs)) => {
34890                let lhs_bits: Vec<u64> = lhs.iter().map(|value| value.to_bits()).collect();
34891                let rhs_bits: Vec<u64> = rhs.iter().map(|value| value.to_bits()).collect();
34892                assert_eq!(
34893                    lhs_bits, rhs_bits,
34894                    "Float64 bit mismatch for token {token:?}"
34895                );
34896            }
34897            _ => panic!("column dtype diverged for token {token:?}"),
34898        }
34899    }
34900
34901    /// Every token the fused scanner admits must produce bit-identical column
34902    /// state to the `push_csv_default_numeric_field` fallback, for both a
34903    /// fresh Int64 column and a Float64 column, under every terminator.
34904    #[test]
34905    fn fused_field_matches_fallback_parser() {
34906        let tokens = [
34907            "0",
34908            "-0",
34909            "+7",
34910            "007",
34911            "5",
34912            "-5",
34913            "123456789",
34914            "999999999999999999",
34915            "-999999999999999999",
34916            "9007199254740993",
34917            "1234567890123456789",
34918            "0.1",
34919            "-0.1",
34920            "+0.5",
34921            ".5",
34922            "-.5",
34923            "00.5",
34924            "5.",
34925            "12.34",
34926            "123456.7",
34927            "0.30000000000000004",
34928            "9007199254740993.0",
34929            "1e5",
34930            "1E5",
34931            "1.5e-3",
34932            "inf",
34933            "-inf",
34934            "nan",
34935            "NaN",
34936            "",
34937            " 5",
34938            "5 ",
34939            "true",
34940            "false",
34941            "TRUE",
34942            "1.2.3",
34943            "--5",
34944            "+-5",
34945            "1-2",
34946            "#N/A",
34947            "NULL",
34948            "abc",
34949        ];
34950
34951        for token in tokens {
34952            for suffix in ["", ",", "\n", ",9\n"] {
34953                let data = format!("{token}{suffix}");
34954                let Some(field) = fuse_scan_numeric_csv_field(data.as_bytes(), 0) else {
34955                    // Rejected tokens take the unchanged fallback route;
34956                    // nothing further to prove.
34957                    continue;
34958                };
34959                assert_eq!(
34960                    field.end,
34961                    token.len(),
34962                    "fused scanner must stop at the delimiter for token {token:?}"
34963                );
34964
34965                // The fallback must accept every token the fused scanner
34966                // admits (the fused grammar is a strict subset).
34967                let mut base_int = CsvTypedColumnValues::Int64(Vec::new());
34968                assert!(
34969                    push_csv_default_numeric_field(&mut base_int, token.as_bytes()),
34970                    "fallback rejected fused-admitted token {token:?}"
34971                );
34972                let mut fused_int = CsvTypedColumnValues::Int64(Vec::new());
34973                push_fused_numeric_csv_field(&mut fused_int, &field);
34974                assert_same_columns(&base_int, &fused_int, token);
34975
34976                let mut base_float = CsvTypedColumnValues::Float64(Vec::new());
34977                assert!(
34978                    push_csv_default_numeric_field(&mut base_float, token.as_bytes()),
34979                    "fallback Float64 rejected fused-admitted token {token:?}"
34980                );
34981                let mut fused_float = CsvTypedColumnValues::Float64(Vec::new());
34982                push_fused_numeric_csv_field(&mut fused_float, &field);
34983                assert_same_columns(&base_float, &fused_float, token);
34984            }
34985        }
34986    }
34987
34988    /// The sign of zero must survive the fused route on Float64 columns:
34989    /// `-0` parses to -0.0 via `parse_f64_csv_number`, and the fused field
34990    /// must carry the same bits.
34991    #[test]
34992    fn fused_field_preserves_negative_zero_bits() {
34993        let field = fuse_scan_numeric_csv_field(b"-0,", 0).expect("fused scanner must admit -0");
34994        assert_eq!(field.int_value, Some(0));
34995        assert_eq!(field.float_value.to_bits(), (-0.0f64).to_bits());
34996
34997        let mut float_column = CsvTypedColumnValues::Float64(Vec::new());
34998        push_fused_numeric_csv_field(&mut float_column, &field);
34999        match float_column {
35000            CsvTypedColumnValues::Float64(values) => {
35001                assert_eq!(values.len(), 1);
35002                assert_eq!(values[0].to_bits(), (-0.0f64).to_bits());
35003            }
35004            CsvTypedColumnValues::Int64(_) => panic!("expected Float64 column"),
35005        }
35006    }
35007}
35008
35009#[cfg(test)]
35010mod simd_csv_delimiter_tests {
35011    use super::{
35012        CsvTypedColumnValues, parse_simple_numeric_csv_chunk, split_simple_numeric_csv_chunks,
35013    };
35014
35015    #[test]
35016    fn delimiter_scan_keeps_chunks_on_record_boundaries() {
35017        let data = b"1,2\n3,4\n5,6\n7,8\n";
35018        let chunks = split_simple_numeric_csv_chunks(data, 3)
35019            .expect("multiple newline-terminated rows must split");
35020
35021        assert_eq!(chunks.first().map(|&(start, _)| start), Some(0));
35022        assert_eq!(chunks.last().map(|&(_, end)| end), Some(data.len()));
35023        for window in chunks.windows(2) {
35024            assert_eq!(window[0].1, window[1].0);
35025        }
35026        for &(_, end) in &chunks {
35027            assert_eq!(data[end - 1], b'\n');
35028        }
35029    }
35030
35031    #[test]
35032    fn fallback_delimiter_scan_preserves_crlf_and_rejects_quotes() {
35033        let (columns, rows) = parse_simple_numeric_csv_chunk(b"1,2\r\n3,4\r\n", 2)
35034            .expect("CRLF numeric records must retain the fallback behavior");
35035        assert_eq!(rows, 2);
35036        assert!(matches!(
35037            columns.as_slice(),
35038            [CsvTypedColumnValues::Int64(left), CsvTypedColumnValues::Int64(right)]
35039                if left == &[1, 3] && right == &[2, 4]
35040        ));
35041        assert!(parse_simple_numeric_csv_chunk(b"1,\"2\"\n", 2).is_none());
35042    }
35043}
35044
35045#[cfg(test)]
35046mod merge_simple_numeric_csv_chunks_tests {
35047    use std::collections::BTreeMap;
35048
35049    use super::{
35050        Column, CsvTypedColumnValues, DataFrame, Index, JsonOrient, Scalar,
35051        merge_simple_numeric_csv_chunks, write_json_string,
35052    };
35053
35054    /// Verbatim copy of the pre-parallel chunk-major merge, kept as the
35055    /// reference implementation for the differential test below.
35056    fn reference_merge(
35057        parsed_chunks: Vec<(Vec<CsvTypedColumnValues>, i64)>,
35058        header_count: usize,
35059    ) -> Option<(Vec<CsvTypedColumnValues>, i64)> {
35060        let mut final_is_float = vec![false; header_count];
35061        let mut row_count = 0i64;
35062        for (columns, rows) in &parsed_chunks {
35063            if columns.len() != header_count {
35064                return None;
35065            }
35066            row_count = row_count.checked_add(*rows)?;
35067            for (idx, column) in columns.iter().enumerate() {
35068                final_is_float[idx] |= matches!(column, CsvTypedColumnValues::Float64(_));
35069            }
35070        }
35071
35072        let capacity = usize::try_from(row_count).ok()?;
35073        let mut merged: Vec<CsvTypedColumnValues> = final_is_float
35074            .into_iter()
35075            .map(|is_float| {
35076                if is_float {
35077                    CsvTypedColumnValues::Float64(Vec::with_capacity(capacity))
35078                } else {
35079                    CsvTypedColumnValues::Int64(Vec::with_capacity(capacity))
35080                }
35081            })
35082            .collect();
35083
35084        for (columns, _) in parsed_chunks {
35085            for (dst, src) in merged.iter_mut().zip(columns) {
35086                match (dst, src) {
35087                    (CsvTypedColumnValues::Int64(dst), CsvTypedColumnValues::Int64(src)) => {
35088                        dst.extend(src);
35089                    }
35090                    (CsvTypedColumnValues::Float64(dst), CsvTypedColumnValues::Int64(src)) => {
35091                        dst.extend(src.into_iter().map(|value| value as f64));
35092                    }
35093                    (CsvTypedColumnValues::Float64(dst), CsvTypedColumnValues::Float64(src)) => {
35094                        dst.extend(src);
35095                    }
35096                    (CsvTypedColumnValues::Int64(_), CsvTypedColumnValues::Float64(_)) => {
35097                        return None;
35098                    }
35099                }
35100            }
35101        }
35102
35103        Some((merged, row_count))
35104    }
35105
35106    fn build_chunks(
35107        chunk_count: usize,
35108        rows_per_chunk: usize,
35109        header_count: usize,
35110        float_from_chunk_for_col: impl Fn(usize) -> usize,
35111    ) -> Vec<(Vec<CsvTypedColumnValues>, i64)> {
35112        (0..chunk_count)
35113            .map(|chunk| {
35114                let columns = (0..header_count)
35115                    .map(|col| {
35116                        if chunk >= float_from_chunk_for_col(col) {
35117                            CsvTypedColumnValues::Float64(
35118                                (0..rows_per_chunk)
35119                                    .map(|row| {
35120                                        (chunk * rows_per_chunk + row) as f64 * 0.5
35121                                            + col as f64 * 1000.0
35122                                    })
35123                                    .collect(),
35124                            )
35125                        } else {
35126                            CsvTypedColumnValues::Int64(
35127                                (0..rows_per_chunk)
35128                                    .map(|row| {
35129                                        (chunk * rows_per_chunk + row) as i64 + col as i64 * 1000
35130                                    })
35131                                    .collect(),
35132                            )
35133                        }
35134                    })
35135                    .collect();
35136                (columns, rows_per_chunk as i64)
35137            })
35138            .collect()
35139    }
35140
35141    fn assert_merge_matches_reference(
35142        chunks: Vec<(Vec<CsvTypedColumnValues>, i64)>,
35143        header_count: usize,
35144    ) {
35145        let reference_chunks: Vec<(Vec<CsvTypedColumnValues>, i64)> = chunks
35146            .iter()
35147            .map(|(columns, rows)| {
35148                let cloned = columns
35149                    .iter()
35150                    .map(|column| match column {
35151                        CsvTypedColumnValues::Int64(values) => {
35152                            CsvTypedColumnValues::Int64(values.clone())
35153                        }
35154                        CsvTypedColumnValues::Float64(values) => {
35155                            CsvTypedColumnValues::Float64(values.clone())
35156                        }
35157                    })
35158                    .collect();
35159                (cloned, *rows)
35160            })
35161            .collect();
35162
35163        let expected = reference_merge(reference_chunks, header_count);
35164        let actual = merge_simple_numeric_csv_chunks(chunks, header_count);
35165
35166        match (expected, actual) {
35167            (None, None) => {}
35168            (Some((expected_columns, expected_rows)), Some((actual_columns, actual_rows))) => {
35169                assert_eq!(expected_rows, actual_rows);
35170                assert_eq!(expected_columns.len(), actual_columns.len());
35171                for (idx, (lhs, rhs)) in expected_columns
35172                    .iter()
35173                    .zip(actual_columns.iter())
35174                    .enumerate()
35175                {
35176                    match (lhs, rhs) {
35177                        (CsvTypedColumnValues::Int64(lhs), CsvTypedColumnValues::Int64(rhs)) => {
35178                            assert_eq!(lhs, rhs, "Int64 column {idx} diverged");
35179                        }
35180                        (
35181                            CsvTypedColumnValues::Float64(lhs),
35182                            CsvTypedColumnValues::Float64(rhs),
35183                        ) => {
35184                            let lhs_bits: Vec<u64> =
35185                                lhs.iter().map(|value| value.to_bits()).collect();
35186                            let rhs_bits: Vec<u64> =
35187                                rhs.iter().map(|value| value.to_bits()).collect();
35188                            assert_eq!(lhs_bits, rhs_bits, "Float64 column {idx} bits diverged");
35189                        }
35190                        _ => panic!("column {idx} dtype diverged"),
35191                    }
35192                }
35193            }
35194            (expected, actual) => panic!(
35195                "merge outcome diverged: reference some={} actual some={}",
35196                expected.is_some(),
35197                actual.is_some()
35198            ),
35199        }
35200    }
35201
35202    /// Big merge (crosses the parallel threshold): mixed promotion patterns —
35203    /// some columns all-Int64, some all-Float64, some promoting mid-stream —
35204    /// must match the chunk-major reference bit-for-bit, in column order.
35205    #[test]
35206    fn parallel_merge_matches_reference_with_mixed_promotion() {
35207        // 8 chunks x 1000 rows x 12 columns = 96000 values > 65536 threshold.
35208        let chunks = build_chunks(8, 1000, 12, |col| match col % 4 {
35209            0 => usize::MAX, // never float: stays Int64
35210            1 => 0,          // float from the first chunk
35211            2 => 3,          // promotes mid-stream
35212            _ => 7,          // promotes at the last chunk
35213        });
35214        assert_merge_matches_reference(chunks, 12);
35215    }
35216
35217    /// Small merge (below the parallel threshold) takes the sequential path
35218    /// and must also match.
35219    #[test]
35220    fn sequential_merge_matches_reference() {
35221        let chunks = build_chunks(3, 4, 5, |col| if col % 2 == 0 { usize::MAX } else { 1 });
35222        assert_merge_matches_reference(chunks, 5);
35223    }
35224
35225    /// More worker groups than columns (header_count < MAX_WORKERS) and
35226    /// header_count not divisible by the group size must keep column order.
35227    #[test]
35228    fn parallel_merge_handles_narrow_and_ragged_widths() {
35229        for header_count in [2, 3, 7, 9, 17] {
35230            let chunks = build_chunks(5, 2000, header_count, |col| col % 6);
35231            assert_merge_matches_reference(chunks, header_count);
35232        }
35233    }
35234
35235    /// A chunk whose column count disagrees with the header must reject, as
35236    /// before.
35237    #[test]
35238    fn merge_rejects_mismatched_chunk_width() {
35239        let mut chunks = build_chunks(2, 10, 4, |_| usize::MAX);
35240        chunks[1].0.pop();
35241        assert!(merge_simple_numeric_csv_chunks(chunks, 4).is_none());
35242    }
35243
35244    /// The typed streaming `to_json(records)` fast path must be byte-for-byte
35245    /// identical to the serde-tree reference across numeric edge values, key
35246    /// escaping, and the fall-back surface. (br-frankenpandas-jsonrec)
35247    #[test]
35248    fn to_json_records_typed_fast_path_bit_identical_to_serde() {
35249        use std::collections::BTreeMap;
35250
35251        use fp_columnar::Column;
35252        use fp_frame::DataFrame;
35253        use fp_index::Index;
35254        use fp_types::Scalar;
35255
35256        use super::{JsonOrient, write_json_string};
35257        fn serde_ref(frame: &DataFrame) -> String {
35258            let headers: Vec<String> = frame.column_names().into_iter().cloned().collect();
35259            let promotions = vec![false; headers.len()];
35260            super::write_json_records_serde(frame, &headers, &promotions).expect("serde ref")
35261        }
35262        // JSONL serde reference: a Map per row serialized independently, joined
35263        // by '\n' (exactly the pre-fast-path `write_jsonl_string` body).
35264        fn jsonl_serde_ref(frame: &DataFrame) -> String {
35265            let headers: Vec<String> = frame.column_names().into_iter().cloned().collect();
35266            let row_count = frame.index().len();
35267            let mut lines = Vec::with_capacity(row_count);
35268            for row_idx in 0..row_count {
35269                let mut obj = serde_json::Map::new();
35270                for name in &headers {
35271                    let val = frame
35272                        .column(name)
35273                        .and_then(|c| c.value(row_idx))
35274                        .map(|v| super::scalar_to_json_with_column_promotion(v, false))
35275                        .unwrap_or(serde_json::Value::Null);
35276                    obj.insert(name.clone(), val);
35277                }
35278                lines.push(serde_json::to_string(&serde_json::Value::Object(obj)).unwrap());
35279            }
35280            lines.join("\n")
35281        }
35282        fn assert_jsonl_matches(frame: &DataFrame) {
35283            assert_eq!(
35284                super::write_jsonl_string(frame).expect("jsonl"),
35285                jsonl_serde_ref(frame)
35286            );
35287        }
35288        // Columns orient: compare the typed fast path's end-to-end output to the
35289        // serde-tree output captured by temporarily... there is no separate serde
35290        // entry point, so compare against a from-scratch serde Map-of-Maps ref.
35291        fn columns_serde_ref(frame: &DataFrame) -> String {
35292            let headers: Vec<String> = frame.column_names().into_iter().cloned().collect();
35293            let mut outer = serde_json::Map::new();
35294            for name in &headers {
35295                let mut col_obj = serde_json::Map::new();
35296                if let Some(col) = frame.column(name.as_str()) {
35297                    for (label, val) in frame.index().labels().iter().zip(col.values()) {
35298                        col_obj.insert(
35299                            super::index_label_json_key(label),
35300                            super::scalar_to_json_with_column_promotion(val, false),
35301                        );
35302                    }
35303                }
35304                outer.insert(name.clone(), serde_json::Value::Object(col_obj));
35305            }
35306            serde_json::to_string(&serde_json::Value::Object(outer)).unwrap()
35307        }
35308        fn assert_columns_matches(frame: &DataFrame) {
35309            assert_eq!(
35310                write_json_string(frame, JsonOrient::Columns).expect("cols"),
35311                columns_serde_ref(frame),
35312            );
35313        }
35314        // Index orient: from-scratch serde Map-of-row-Maps reference.
35315        fn index_serde_ref(frame: &DataFrame) -> String {
35316            let headers: Vec<String> = frame.column_names().into_iter().cloned().collect();
35317            let mut outer = serde_json::Map::new();
35318            for row_idx in 0..frame.index().len() {
35319                let mut row_obj = serde_json::Map::new();
35320                for name in &headers {
35321                    let val = frame
35322                        .column(name.as_str())
35323                        .and_then(|c| c.value(row_idx))
35324                        .map(|v| super::scalar_to_json_with_column_promotion(v, false))
35325                        .unwrap_or(serde_json::Value::Null);
35326                    row_obj.insert(name.clone(), val);
35327                }
35328                let key = super::index_label_json_key(&frame.index().labels()[row_idx]);
35329                outer.insert(key, serde_json::Value::Object(row_obj));
35330            }
35331            serde_json::to_string(&serde_json::Value::Object(outer)).unwrap()
35332        }
35333        fn assert_index_matches(frame: &DataFrame) {
35334            assert_eq!(
35335                write_json_string(frame, JsonOrient::Index).expect("index"),
35336                index_serde_ref(frame),
35337            );
35338        }
35339        // Values orient: from-scratch serde array-of-arrays reference.
35340        fn values_serde_ref(frame: &DataFrame) -> String {
35341            let headers: Vec<String> = frame.column_names().into_iter().cloned().collect();
35342            let mut data = Vec::with_capacity(frame.index().len());
35343            for row_idx in 0..frame.index().len() {
35344                let row: Vec<serde_json::Value> = headers
35345                    .iter()
35346                    .map(|name| {
35347                        frame
35348                            .column(name.as_str())
35349                            .and_then(|c| c.value(row_idx))
35350                            .map(|v| super::scalar_to_json_with_column_promotion(v, false))
35351                            .unwrap_or(serde_json::Value::Null)
35352                    })
35353                    .collect();
35354                data.push(serde_json::Value::Array(row));
35355            }
35356            serde_json::to_string(&serde_json::Value::Array(data)).unwrap()
35357        }
35358        fn assert_values_matches(frame: &DataFrame) {
35359            assert_eq!(
35360                write_json_string(frame, JsonOrient::Values).expect("values"),
35361                values_serde_ref(frame),
35362            );
35363        }
35364        // Split orient: from-scratch serde {columns, index, data} reference.
35365        fn split_serde_ref(frame: &DataFrame) -> String {
35366            let headers: Vec<String> = frame.column_names().into_iter().cloned().collect();
35367            let col_array: Vec<serde_json::Value> = headers
35368                .iter()
35369                .map(|h| serde_json::Value::String(h.clone()))
35370                .collect();
35371            let index_array: Vec<serde_json::Value> = frame
35372                .index()
35373                .labels()
35374                .iter()
35375                .map(super::index_label_to_json)
35376                .collect();
35377            let mut data = Vec::with_capacity(frame.index().len());
35378            for row_idx in 0..frame.index().len() {
35379                let row: Vec<serde_json::Value> = headers
35380                    .iter()
35381                    .map(|name| {
35382                        frame
35383                            .column(name.as_str())
35384                            .and_then(|c| c.value(row_idx))
35385                            .map(|v| super::scalar_to_json_with_column_promotion(v, false))
35386                            .unwrap_or(serde_json::Value::Null)
35387                    })
35388                    .collect();
35389                data.push(serde_json::Value::Array(row));
35390            }
35391            let mut obj = serde_json::Map::new();
35392            obj.insert("columns".into(), serde_json::Value::Array(col_array));
35393            obj.insert("index".into(), serde_json::Value::Array(index_array));
35394            obj.insert("data".into(), serde_json::Value::Array(data));
35395            serde_json::to_string(&serde_json::Value::Object(obj)).unwrap()
35396        }
35397        fn assert_split_matches(frame: &DataFrame) {
35398            assert_eq!(
35399                write_json_string(frame, JsonOrient::Split).expect("split"),
35400                split_serde_ref(frame),
35401            );
35402        }
35403        fn idx(n: usize) -> Index {
35404            Index::new_known_unique_int64_unit_range(0, n)
35405        }
35406
35407        // Edge-laden Int64 + Float64 + Bool frame; the floats span integer-valued,
35408        // signed-zero, sub-1e-4 (ryu exponent), huge, tiny, and ±Inf (which the
35409        // typed path emits as `null`, matching serde's NaN/Inf arm).
35410        let ints = vec![
35411            0i64,
35412            -1,
35413            1,
35414            i64::MIN,
35415            i64::MAX,
35416            -123456789,
35417            999,
35418            -7,
35419            42,
35420            1_000_000_000,
35421        ];
35422        let floats = vec![
35423            0.0,
35424            -0.0,
35425            0.5,
35426            100.0,
35427            -100.0,
35428            1e20,
35429            1e-20,
35430            1.5e-300,
35431            f64::MAX,
35432            f64::INFINITY,
35433        ];
35434        let bools = vec![
35435            true, false, true, true, false, false, true, false, true, false,
35436        ];
35437        let n = ints.len();
35438        let mut cols: BTreeMap<String, Column> = BTreeMap::new();
35439        cols.insert("a".to_string(), Column::from_i64_values(ints));
35440        cols.insert("b".to_string(), Column::from_f64_values(floats));
35441        cols.insert("c".to_string(), Column::from_bool_values(bools));
35442        // Datetime64 column (epoch-ms ints in JSON), incl. a NaT (→ null) and a
35443        // pre-epoch negative ns (truncating /1_000_000 toward zero, matching serde).
35444        let dts = vec![
35445            0i64,
35446            946_684_800_000_000_000,
35447            i64::MIN, // NaT
35448            -1_500_000_000,
35449            1_000,
35450            1_500_000,
35451            -86_400_000_000_000,
35452            999_999,
35453            123_456_789,
35454            -999_999,
35455        ];
35456        cols.insert("dt".to_string(), Column::from_datetime64_values(dts));
35457        // A column name that requires JSON escaping, to exercise pre-serialized keys.
35458        cols.insert(
35459            "we\"ird\tkey".to_string(),
35460            Column::from_i64_values((0..n as i64).collect()),
35461        );
35462        let frame = DataFrame::new(idx(n), cols).expect("frame");
35463        // Fast path must actually fire here (all-valid numeric/bool).
35464        assert!(super::try_write_json_records_typed(&frame, false).is_some());
35465        assert!(super::try_write_json_records_typed(&frame, true).is_some());
35466        assert!(super::try_write_json_columns_typed(&frame).is_some());
35467        assert!(super::try_write_json_index_typed(&frame).is_some());
35468        assert!(super::try_write_json_values_typed(&frame).is_some());
35469        assert!(super::try_write_json_split_typed(&frame).is_some());
35470        assert_eq!(
35471            write_json_string(&frame, JsonOrient::Records).expect("json"),
35472            serde_ref(&frame),
35473        );
35474        assert_jsonl_matches(&frame);
35475        assert_columns_matches(&frame);
35476        assert_index_matches(&frame);
35477        assert_values_matches(&frame);
35478        assert_split_matches(&frame);
35479
35480        // -Inf in isolation.
35481        let mut c2: BTreeMap<String, Column> = BTreeMap::new();
35482        c2.insert(
35483            "x".to_string(),
35484            Column::from_f64_values(vec![f64::NEG_INFINITY, -2.5, 3.0]),
35485        );
35486        let f2 = DataFrame::new(idx(3), c2).expect("frame2");
35487        assert_eq!(
35488            write_json_string(&f2, JsonOrient::Records).expect("json2"),
35489            serde_ref(&f2),
35490        );
35491        assert_jsonl_matches(&f2);
35492        assert_columns_matches(&f2);
35493        assert_index_matches(&f2);
35494        assert_values_matches(&f2);
35495        assert_split_matches(&f2);
35496
35497        // Empty frame (0 rows) and a single-column int frame.
35498        let mut c3: BTreeMap<String, Column> = BTreeMap::new();
35499        c3.insert("only".to_string(), Column::from_i64_values(vec![]));
35500        let f3 = DataFrame::new(idx(0), c3).expect("frame3");
35501        assert_eq!(
35502            write_json_string(&f3, JsonOrient::Records).expect("json3"),
35503            serde_ref(&f3),
35504        );
35505        assert_jsonl_matches(&f3);
35506        assert_columns_matches(&f3);
35507        assert_index_matches(&f3);
35508        assert_values_matches(&f3);
35509        assert_split_matches(&f3);
35510
35511        // A Utf8 column forces the serde fallback; equality must still hold
35512        // (trivially, since the fast path declines).
35513        let mut c4: BTreeMap<String, Column> = BTreeMap::new();
35514        c4.insert("n".to_string(), Column::from_i64_values(vec![1, 2]));
35515        c4.insert(
35516            "s".to_string(),
35517            Column::from_values(vec![Scalar::Utf8("hi".into()), Scalar::Utf8("x".into())])
35518                .expect("utf8 col"),
35519        );
35520        let f4 = DataFrame::new(idx(2), c4).expect("frame4");
35521        assert!(super::try_write_json_records_typed(&f4, false).is_none());
35522        assert_eq!(
35523            write_json_string(&f4, JsonOrient::Records).expect("json4"),
35524            serde_ref(&f4),
35525        );
35526        assert_jsonl_matches(&f4);
35527        assert_columns_matches(&f4);
35528        assert_index_matches(&f4);
35529        assert_values_matches(&f4);
35530        assert_split_matches(&f4);
35531
35532        // Contiguous Utf8 column (the read-path backing the typed Utf8 arm
35533        // accepts), with strings spanning the no-escape fast path and every
35534        // serde escape case: quote, backslash, control bytes, and multi-byte
35535        // UTF-8 (which serde passes through verbatim).
35536        let strs = [
35537            "plain",
35538            "a\"b",
35539            "c\\d",
35540            "e\nf",
35541            "g\th",
35542            "i\u{0001}j",
35543            "café",
35544            "🦀x",
35545            "",
35546            "trailing ",
35547        ];
35548        let mut sbytes: Vec<u8> = Vec::new();
35549        let mut soff: Vec<usize> = vec![0];
35550        for s in strs {
35551            sbytes.extend_from_slice(s.as_bytes());
35552            soff.push(sbytes.len());
35553        }
35554        let mut c5: BTreeMap<String, Column> = BTreeMap::new();
35555        c5.insert(
35556            "n".to_string(),
35557            Column::from_i64_values((0..strs.len() as i64).collect()),
35558        );
35559        c5.insert("s".to_string(), Column::from_utf8_contiguous(sbytes, soff));
35560        let f5 = DataFrame::new(idx(strs.len()), c5).expect("frame5");
35561        assert!(super::try_write_json_records_typed(&f5, false).is_some());
35562        assert_eq!(
35563            write_json_string(&f5, JsonOrient::Records).expect("json5"),
35564            serde_ref(&f5),
35565        );
35566        assert_jsonl_matches(&f5);
35567        assert_columns_matches(&f5);
35568        assert_index_matches(&f5);
35569        assert_values_matches(&f5);
35570        assert_split_matches(&f5);
35571
35572        // Pseudo-random sweep (LCG, no external rng) over Int64/Float64 values.
35573        let mut state: u64 = 0x9E3779B97F4A7C15;
35574        let mut next = || {
35575            state = state
35576                .wrapping_mul(6364136223846793005)
35577                .wrapping_add(1442695040888963407);
35578            state
35579        };
35580        let m = 2000usize;
35581        let mut ri = Vec::with_capacity(m);
35582        let mut rf = Vec::with_capacity(m);
35583        for _ in 0..m {
35584            ri.push(next() as i64);
35585            // Mix of magnitudes including integer-valued and tiny.
35586            let bits = next();
35587            let f = f64::from_bits(bits);
35588            rf.push(if f.is_nan() {
35589                (next() % 1000) as f64 * 0.25
35590            } else {
35591                f
35592            });
35593        }
35594        let mut rc: BTreeMap<String, Column> = BTreeMap::new();
35595        rc.insert("ri".to_string(), Column::from_i64_values(ri));
35596        rc.insert("rf".to_string(), Column::from_f64_values(rf));
35597        let rframe = DataFrame::new(idx(m), rc).expect("rframe");
35598        assert_eq!(
35599            write_json_string(&rframe, JsonOrient::Records).expect("rjson"),
35600            serde_ref(&rframe),
35601        );
35602        assert_jsonl_matches(&rframe);
35603        assert_columns_matches(&rframe);
35604        assert_index_matches(&rframe);
35605        assert_values_matches(&rframe);
35606        assert_split_matches(&rframe);
35607    }
35608
35609    #[test]
35610    fn json_records_typed_writer_mixed_dtype_defers_to_serde_92n1x() {
35611        // A numeric column alongside a scalar-backed Utf8 column is a mixed-dtype
35612        // frame. The writer must decline the typed path rather than assuming all
35613        // columns expose contiguous native buffers, while retaining serde output.
35614        let mut columns = BTreeMap::new();
35615        columns.insert("n".to_string(), Column::from_i64_values(vec![1, 2]));
35616        columns.insert(
35617            "s".to_string(),
35618            Column::from_values(vec![Scalar::Utf8("hi".into()), Scalar::Utf8("x".into())])
35619                .expect("scalar-backed utf8"),
35620        );
35621        let frame = DataFrame::new(Index::new_known_unique_int64_unit_range(0, 2), columns)
35622            .expect("mixed frame");
35623
35624        assert!(super::try_write_json_records_typed(&frame, false).is_none());
35625        assert_eq!(
35626            write_json_string(&frame, JsonOrient::Records).expect("serde fallback"),
35627            r#"[{"n":1,"s":"hi"},{"n":2,"s":"x"}]"#
35628        );
35629    }
35630}