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    #[error("csv index column '{0}' not found in headers")]
143    MissingIndexColumn(String),
144    #[error("duplicate column name '{0}'")]
145    DuplicateColumnName(String),
146    #[error("usecols contains missing columns: {0:?}")]
147    MissingUsecols(Vec<String>),
148    #[error("parse_dates contains missing columns: {0:?}")]
149    MissingParseDateColumns(Vec<String>),
150    #[error("json format error: {0}")]
151    JsonFormat(String),
152    #[error("parquet error: {0}")]
153    Parquet(String),
154    #[error("orc error: {0}")]
155    Orc(String),
156    #[error("hdf5 error: {0}")]
157    Hdf5(String),
158    #[error("excel error: {0}")]
159    Excel(String),
160    #[error("html error: {0}")]
161    Html(String),
162    #[error("xml error: {0}")]
163    Xml(String),
164    #[error("pickle error: {0}")]
165    Pickle(String),
166    #[error("stata error: {0}")]
167    Stata(String),
168    #[error("fwf error: {0}")]
169    Fwf(String),
170    #[error("deferred reader: {0}")]
171    Deferred(String),
172    #[error("arrow ipc error: {0}")]
173    Arrow(String),
174    #[error("sql error: {0}")]
175    Sql(String),
176    #[error("clipboard error: {0}")]
177    Clipboard(String),
178    #[error(transparent)]
179    Csv(#[from] csv::Error),
180    #[error(transparent)]
181    Json(#[from] serde_json::Error),
182    #[error(transparent)]
183    Io(#[from] std::io::Error),
184    #[error(transparent)]
185    Utf8(#[from] std::string::FromUtf8Error),
186    #[error(transparent)]
187    Column(#[from] ColumnError),
188    #[error(transparent)]
189    Frame(#[from] FrameError),
190    #[error(transparent)]
191    Index(#[from] IndexError),
192}
193
194const ORC_NO_TOKIO_MESSAGE: &str =
195    "ORC I/O is disabled until a Tokio-free native ORC backend is available";
196
197fn orc_no_tokio_error() -> IoError {
198    IoError::Orc(ORC_NO_TOKIO_MESSAGE.to_owned())
199}
200
201#[derive(Debug, Clone, Copy, PartialEq, Eq)]
202pub enum JsonOrient {
203    Records,
204    Columns,
205    Index,
206    Split,
207    Values,
208}
209
210#[derive(Debug, Clone, Copy, PartialEq, Eq)]
211pub enum CsvOnBadLines {
212    Error,
213    Warn,
214    Skip,
215}
216
217#[derive(Debug, Clone)]
218pub struct CsvReadOptions {
219    pub delimiter: u8,
220    pub has_headers: bool,
221    /// Additional NA values to recognize beyond the pandas defaults.
222    pub na_values: Vec<String>,
223    /// Whether to include the default NaN values when parsing data.
224    /// If `na_values` are specified and `keep_default_na` is false, only the
225    /// specified `na_values` will be treated as NA.
226    /// Matches pandas `keep_default_na` parameter. Default: true.
227    pub keep_default_na: bool,
228    /// Detect missing value markers (empty strings and the value of na_values).
229    /// In data without any NAs, passing `na_filter=false` can improve performance.
230    /// Matches pandas `na_filter` parameter. Default: true.
231    pub na_filter: bool,
232    pub index_col: Option<String>,
233    /// Read only these columns (by name). `None` means read all.
234    /// Matches pandas `usecols` parameter.
235    pub usecols: Option<Vec<String>>,
236    /// Maximum number of data rows to read. `None` means read all.
237    /// Matches pandas `nrows` parameter.
238    pub nrows: Option<usize>,
239    /// Number of initial lines to skip at the start of the file (including
240    /// the header line when `has_headers` is true).
241    /// Matches pandas `skiprows` parameter (when given as int).
242    pub skiprows: usize,
243    /// Force specific dtypes for columns. Map of column name -> DType.
244    /// Matches pandas `dtype` parameter.
245    pub dtype: Option<std::collections::HashMap<String, DType>>,
246    /// Column names to coerce via pandas-style parse_dates handling.
247    /// Currently supports explicit column-name selection.
248    pub parse_dates: Option<Vec<String>>,
249    /// Column groups to combine and coerce via pandas-style parse_dates handling.
250    /// Each group replaces its source columns with a new `<a>_<b>_...` datetime column.
251    pub parse_date_combinations: Option<Vec<Vec<String>>>,
252    /// Named column groups to combine and parse as datetime, matching
253    /// `pd.read_csv(parse_dates={'new_name': ['year', 'month', 'day']})`.
254    /// Each `(new_name, [source_cols])` entry replaces its source columns
255    /// with a single combined datetime column using the caller-supplied
256    /// name instead of the default `<a>_<b>_...` joined form.
257    pub parse_date_combinations_named: Option<Vec<(String, Vec<String>)>>,
258    /// Character whose lines are treated as comments and skipped entirely.
259    /// Must be a single byte (ASCII); multi-byte characters are rejected.
260    /// Matches pandas `comment` parameter. Default: `None`.
261    pub comment: Option<u8>,
262    /// Additional string values to coerce to `true` during CSV parsing.
263    /// Matches pandas `true_values` parameter.
264    pub true_values: Vec<String>,
265    /// Additional string values to coerce to `false` during CSV parsing.
266    /// Matches pandas `false_values` parameter.
267    pub false_values: Vec<String>,
268    /// Character to recognize as the decimal separator when parsing floats.
269    /// Matches pandas `decimal` parameter. Default: `.`.
270    pub decimal: u8,
271    /// How to handle rows with more fields than the header width.
272    /// Matches pandas `on_bad_lines` parameter for the supported
273    /// `error`/`warn`/`skip` modes.
274    pub on_bad_lines: CsvOnBadLines,
275    /// Thousands separator stripped from numeric fields before parsing.
276    /// Matches pandas `thousands` parameter. Must differ from `decimal`
277    /// (otherwise the option is silently ignored, matching pandas).
278    pub thousands: Option<u8>,
279    /// Number of trailing data rows to drop (after the header is
280    /// consumed). Matches pandas `skipfooter` parameter. Default: `0`.
281    pub skipfooter: usize,
282    /// Character used to quote fields that contain the delimiter, a
283    /// newline, or the quote character itself. Defaults to `"` (ASCII
284    /// double-quote). Matches pandas `quotechar` parameter.
285    pub quotechar: u8,
286    /// Character used to escape the quote character inside a quoted
287    /// field when `doublequote` is false. `None` disables backslash-
288    /// style escaping entirely. Matches pandas `escapechar` parameter.
289    pub escapechar: Option<u8>,
290    /// When true (the default), a doubled quote character inside a
291    /// quoted field is interpreted as a single literal quote. When
292    /// false, `escapechar` must be used to quote the quote character.
293    /// Matches pandas `doublequote` parameter.
294    pub doublequote: bool,
295    /// Custom single-byte line terminator. When set, the reader treats
296    /// only that byte as a record separator (instead of CRLF/LF).
297    /// Matches pandas `lineterminator` (C-engine only). `None` keeps
298    /// the default CRLF/LF handling.
299    pub lineterminator: Option<u8>,
300    /// When true, skip ASCII spaces (0x20 only, not tabs) immediately after a
301    /// delimiter and at each field start, before quote handling. Matches pandas
302    /// `skipinitialspace` (default false). Trailing spaces are preserved; spaces
303    /// inside quoted fields are preserved; a space-then-quote field (`   "x,y"`)
304    /// is parsed as the quoted value.
305    pub skipinitialspace: bool,
306}
307
308impl Default for CsvReadOptions {
309    fn default() -> Self {
310        Self {
311            delimiter: b',',
312            has_headers: true,
313            na_values: Vec::new(),
314            keep_default_na: true,
315            na_filter: true,
316            index_col: None,
317            usecols: None,
318            nrows: None,
319            skiprows: 0,
320            dtype: None,
321            parse_dates: None,
322            parse_date_combinations: None,
323            parse_date_combinations_named: None,
324            comment: None,
325            true_values: Vec::new(),
326            false_values: Vec::new(),
327            decimal: b'.',
328            on_bad_lines: CsvOnBadLines::Error,
329            thousands: None,
330            quotechar: b'"',
331            escapechar: None,
332            doublequote: true,
333            skipfooter: 0,
334            lineterminator: None,
335            skipinitialspace: false,
336        }
337    }
338}
339
340fn csv_read_options_match_default_shape(options: &CsvReadOptions, na_filter: bool) -> bool {
341    options.delimiter == b','
342        && options.has_headers
343        && options.na_values.is_empty()
344        && options.keep_default_na
345        && options.na_filter == na_filter
346        && options.index_col.is_none()
347        && options.usecols.is_none()
348        && options.nrows.is_none()
349        && options.skiprows == 0
350        && options.dtype.is_none()
351        && options.parse_dates.is_none()
352        && options.parse_date_combinations.is_none()
353        && options.parse_date_combinations_named.is_none()
354        && options.comment.is_none()
355        && options.true_values.is_empty()
356        && options.false_values.is_empty()
357        && options.decimal == b'.'
358        && options.on_bad_lines == CsvOnBadLines::Error
359        && options.thousands.is_none()
360        && options.skipfooter == 0
361        && options.quotechar == b'"'
362        && options.escapechar.is_none()
363        && options.doublequote
364        && options.lineterminator.is_none()
365}
366
367fn csv_read_options_match_default_fast_path(options: &CsvReadOptions) -> bool {
368    csv_read_options_match_default_shape(options, true)
369}
370
371fn csv_read_options_match_no_na_numeric_fast_path(options: &CsvReadOptions) -> bool {
372    csv_read_options_match_default_shape(options, false)
373}
374
375/// Options for [`read_fwf_str`] and [`read_fwf`].
376///
377/// Callers can supply either `colspecs` (explicit `(start, end)`
378/// character ranges, end-exclusive, matching pandas) or `widths`
379/// (per-column character widths that get translated to cumulative
380/// colspecs). When both are omitted, `read_fwf` infers colspecs from
381/// non-whitespace runs across the non-skipped input lines.
382#[derive(Debug, Clone)]
383pub struct FwfReadOptions {
384    /// Explicit `(start, end)` column ranges in characters. End is
385    /// exclusive, matching pandas. Mutually exclusive with `widths`.
386    pub colspecs: Option<Vec<(usize, usize)>>,
387    /// Per-column character widths. Translated to colspecs by cumulative
388    /// sum. Mutually exclusive with `colspecs`.
389    pub widths: Option<Vec<usize>>,
390    pub has_headers: bool,
391    pub na_values: Vec<String>,
392    pub keep_default_na: bool,
393    pub na_filter: bool,
394    pub index_col: Option<String>,
395    pub usecols: Option<Vec<String>>,
396    pub nrows: Option<usize>,
397    pub skiprows: usize,
398    pub dtype: Option<std::collections::HashMap<String, DType>>,
399    pub parse_dates: Option<Vec<String>>,
400    pub true_values: Vec<String>,
401    pub false_values: Vec<String>,
402    pub decimal: u8,
403    pub thousands: Option<u8>,
404    pub skipfooter: usize,
405}
406
407impl Default for FwfReadOptions {
408    fn default() -> Self {
409        Self {
410            colspecs: None,
411            widths: None,
412            has_headers: true,
413            na_values: Vec::new(),
414            keep_default_na: true,
415            na_filter: true,
416            index_col: None,
417            usecols: None,
418            nrows: None,
419            skiprows: 0,
420            dtype: None,
421            parse_dates: None,
422            true_values: Vec::new(),
423            false_values: Vec::new(),
424            decimal: b'.',
425            thousands: None,
426            skipfooter: 0,
427        }
428    }
429}
430
431fn infer_fwf_colspecs(
432    input: &str,
433    options: &FwfReadOptions,
434) -> Result<Vec<(usize, usize)>, IoError> {
435    let mut candidate_lines: Vec<&str> = input.lines().skip(options.skiprows).collect();
436    if options.skipfooter > 0 {
437        let retained = candidate_lines.len().saturating_sub(options.skipfooter);
438        candidate_lines.truncate(retained);
439    }
440
441    let candidate_lines: Vec<&str> = candidate_lines
442        .into_iter()
443        .filter(|line| !line.trim().is_empty())
444        .collect();
445    if candidate_lines.is_empty() {
446        return Err(IoError::Fwf(
447            "cannot infer fixed-width colspecs from empty input".to_owned(),
448        ));
449    }
450
451    let max_width = candidate_lines
452        .iter()
453        .map(|line| line.chars().count())
454        .max()
455        .unwrap_or(0);
456    let mut occupied = vec![false; max_width];
457    for line in candidate_lines {
458        for (idx, ch) in line.chars().enumerate() {
459            if !ch.is_whitespace()
460                && let Some(slot) = occupied.get_mut(idx)
461            {
462                *slot = true;
463            }
464        }
465    }
466
467    let mut specs = Vec::new();
468    let mut idx = 0usize;
469    while idx < occupied.len() {
470        while idx < occupied.len() && !occupied.get(idx).copied().unwrap_or(false) {
471            idx += 1;
472        }
473        if idx == occupied.len() {
474            break;
475        }
476        let start = idx;
477        while idx < occupied.len() && occupied.get(idx).copied().unwrap_or(false) {
478            idx += 1;
479        }
480        specs.push((start, idx));
481    }
482
483    if specs.is_empty() {
484        return Err(IoError::Fwf(
485            "cannot infer fixed-width colspecs from whitespace-only input".to_owned(),
486        ));
487    }
488    Ok(specs)
489}
490
491fn resolve_fwf_colspecs(
492    input: &str,
493    options: &FwfReadOptions,
494) -> Result<Vec<(usize, usize)>, IoError> {
495    match (&options.colspecs, &options.widths) {
496        (Some(_), Some(_)) => Err(IoError::Fwf(
497            "You must specify only one of 'widths' and 'colspecs'".to_owned(),
498        )),
499        (Some(specs), None) => {
500            for &(start, end) in specs {
501                if start > end {
502                    return Err(IoError::Fwf(format!(
503                        "colspecs entry ({start}, {end}) is inverted"
504                    )));
505                }
506            }
507            Ok(specs.clone())
508        }
509        (None, Some(widths)) => {
510            let mut specs = Vec::with_capacity(widths.len());
511            let mut cursor = 0usize;
512            for &w in widths {
513                let next = cursor.checked_add(w).ok_or_else(|| {
514                    IoError::Fwf("widths overflow when computing colspecs".to_owned())
515                })?;
516                specs.push((cursor, next));
517                cursor = next;
518            }
519            Ok(specs)
520        }
521        (None, None) => infer_fwf_colspecs(input, options),
522    }
523}
524
525fn fwf_lines_to_csv(input: &str, colspecs: &[(usize, usize)]) -> String {
526    let mut out = String::new();
527    for line in input.split_terminator('\n') {
528        let line = line.strip_suffix('\r').unwrap_or(line);
529        let chars: Vec<char> = line.chars().collect();
530        let mut first = true;
531        for &(start, end) in colspecs {
532            if !first {
533                out.push(',');
534            }
535            first = false;
536            let slice: String = if start >= chars.len() {
537                String::new()
538            } else {
539                let real_end = end.min(chars.len());
540                chars[start..real_end].iter().collect()
541            };
542            let trimmed = slice.trim();
543            out.push('"');
544            for c in trimmed.chars() {
545                if c == '"' {
546                    out.push('"');
547                }
548                out.push(c);
549            }
550            out.push('"');
551        }
552        out.push('\n');
553    }
554    out
555}
556
557fn fwf_csv_options(options: &FwfReadOptions) -> CsvReadOptions {
558    CsvReadOptions {
559        delimiter: b',',
560        has_headers: options.has_headers,
561        na_values: options.na_values.clone(),
562        keep_default_na: options.keep_default_na,
563        na_filter: options.na_filter,
564        index_col: options.index_col.clone(),
565        usecols: options.usecols.clone(),
566        nrows: options.nrows,
567        skiprows: options.skiprows,
568        dtype: options.dtype.clone(),
569        parse_dates: options.parse_dates.clone(),
570        parse_date_combinations: None,
571        parse_date_combinations_named: None,
572        comment: None,
573        true_values: options.true_values.clone(),
574        false_values: options.false_values.clone(),
575        decimal: options.decimal,
576        on_bad_lines: CsvOnBadLines::Error,
577        thousands: options.thousands,
578        quotechar: b'"',
579        escapechar: None,
580        doublequote: true,
581        skipfooter: options.skipfooter,
582        lineterminator: None,
583        skipinitialspace: false,
584    }
585}
586
587/// Parse a fixed-width string, matching `pd.read_fwf(io.StringIO(s), ...)`.
588///
589/// Tokens are sliced by character index, then trimmed of leading and
590/// trailing whitespace before being threaded through the standard CSV
591/// scalar-coercion path. When `colspecs` and `widths` are omitted, the
592/// ranges are inferred from non-whitespace runs across the input.
593pub fn read_fwf_str(input: &str, options: &FwfReadOptions) -> Result<DataFrame, IoError> {
594    let colspecs = resolve_fwf_colspecs(input, options)?;
595    let csv_input = fwf_lines_to_csv(input, &colspecs);
596    let csv_options = fwf_csv_options(options);
597    read_csv_with_options(&csv_input, &csv_options)
598}
599
600/// Build a CSV column from per-cell parsed scalars, but preserve original text
601/// when the column infers to object (`Utf8`) dtype.
602///
603/// pandas does column-level inference: a column becomes a single dtype, and when
604/// it falls back to object every non-NA cell keeps its VERBATIM source text. FP
605/// parses per cell (`"true"` → `Bool`, `"01"` → `Int64(1)`), so without this the
606/// object-fallback column would re-stringify those scalars canonically — writing
607/// `"True"`/`"1"` where pandas keeps `"true"`/`"01"`. When the inferred dtype is
608/// `Utf8`, rebuild the column straight from `raw` (NA cells stay null) so the
609/// original literals survive. Native (non-object) columns are unaffected.
610///
611/// Missingness is read back from the parsed column's own values rather than
612/// re-detecting NA tokens, so this works for both the default reader and the
613/// options reader (which honors a configurable na/keep_default_na token set):
614/// a cell is null in the rebuilt column iff it parsed to a missing scalar.
615/// `raw` must be positionally aligned with `values` (same length).
616/// Adapt a `&[String]` raw-text column (the options-path representation) to the
617/// contiguous `(bytes, offsets)` form that [`build_csv_object_aware_column`]
618/// consumes. Keeps a single object-aware builder without converting the whole
619/// options path to contiguous capture.
620fn strings_to_contiguous_raw(raw: &[String]) -> (Vec<u8>, Vec<usize>) {
621    let total: usize = raw.iter().map(String::len).sum();
622    let mut bytes = Vec::with_capacity(total);
623    let mut offsets = Vec::with_capacity(raw.len() + 1);
624    offsets.push(0usize);
625    for s in raw {
626        bytes.extend_from_slice(s.as_bytes());
627        offsets.push(bytes.len());
628    }
629    (bytes, offsets)
630}
631
632fn build_csv_object_aware_column(
633    values: Vec<Scalar>,
634    raw_bytes: &[u8],
635    raw_offsets: &[usize],
636) -> Result<Column, IoError> {
637    let column = Column::from_values(values)?;
638    if column.dtype() == DType::Float64 {
639        let normalized = column
640            .values()
641            .iter()
642            .map(|value| match value {
643                Scalar::Null(_) => Scalar::Null(NullKind::NaN),
644                other => other.clone(),
645            })
646            .collect();
647        return Ok(Column::new(DType::Float64, normalized)?);
648    }
649    // Only a Utf8-result column consults the verbatim raw text (to preserve the
650    // original literal of numeric-coerced cells, e.g. "05" / "5.0"). `raw_offsets`
651    // has one more entry than the row count; a mismatch means the raw buffer is
652    // absent/short, so fall back to the parsed column unchanged.
653    let raw_len = raw_offsets.len().saturating_sub(1);
654    if column.dtype() == DType::Utf8 && column.values().len() == raw_len {
655        let rebuilt: Vec<Scalar> = column
656            .values()
657            .iter()
658            .enumerate()
659            .map(|(i, parsed)| {
660                if parsed.is_missing() {
661                    Scalar::Null(NullKind::Null)
662                } else {
663                    let field = &raw_bytes[raw_offsets[i]..raw_offsets[i + 1]];
664                    // Fields originate from a `&str` CSV input, so every slice is
665                    // valid UTF-8 on ASCII delimiter/quote boundaries.
666                    Scalar::Utf8(String::from_utf8_lossy(field).into_owned())
667                }
668            })
669            .collect();
670        return Ok(Column::new(DType::Utf8, rebuilt)?);
671    }
672    Ok(column)
673}
674
675enum CsvTypedColumnValues {
676    Int64(Vec<i64>),
677    Float64(Vec<f64>),
678}
679
680const SIMPLE_NUMERIC_CSV_PARALLEL_MIN_BYTES: usize = 1 << 20;
681const SIMPLE_NUMERIC_CSV_PARALLEL_MAX_WORKERS: usize = 8;
682
683fn trim_ascii_field(mut field: &[u8]) -> &[u8] {
684    while let Some((first, rest)) = field.split_first() {
685        if first.is_ascii_whitespace() {
686            field = rest;
687        } else {
688            break;
689        }
690    }
691    while let Some((last, rest)) = field.split_last() {
692        if last.is_ascii_whitespace() {
693            field = rest;
694        } else {
695            break;
696        }
697    }
698    field
699}
700
701fn is_pandas_default_na_bytes(field: &[u8]) -> bool {
702    const DEFAULT_NA_VALUES: &[&[u8]] = &[
703        b"",
704        b"#N/A",
705        b"#N/A N/A",
706        b"#NA",
707        b"-1.#IND",
708        b"-1.#QNAN",
709        b"-NaN",
710        b"-nan",
711        b"1.#IND",
712        b"1.#QNAN",
713        b"<NA>",
714        b"N/A",
715        b"NA",
716        b"NULL",
717        b"NaN",
718        b"None",
719        b"n/a",
720        b"nan",
721        b"null",
722    ];
723    DEFAULT_NA_VALUES.contains(&field)
724}
725
726fn eq_ignore_ascii_case_bytes(field: &[u8], expected: &[u8]) -> bool {
727    field.len() == expected.len()
728        && field
729            .iter()
730            .zip(expected)
731            .all(|(lhs, rhs)| lhs.eq_ignore_ascii_case(rhs))
732}
733
734fn has_float_marker(field: &[u8]) -> bool {
735    field.iter().any(|byte| matches!(byte, b'.' | b'e' | b'E'))
736}
737
738fn parse_i64_ascii(field: &[u8]) -> Option<i64> {
739    if field.is_ascii() {
740        std::str::from_utf8(field).ok()?.parse::<i64>().ok()
741    } else {
742        None
743    }
744}
745
746fn parse_f64_csv_number(field: &[u8]) -> Option<f64> {
747    match fast_float2::parse::<f64, _>(field) {
748        Ok(value) => Some(value),
749        Err(_) if field.is_ascii() => std::str::from_utf8(field).ok()?.parse::<f64>().ok(),
750        Err(_) => None,
751    }
752}
753
754/// Exact powers of ten for the fused decimal fast path. Every entry up to
755/// 10^18 is exactly representable in f64, so dividing an exact mantissa by an
756/// entry is a single correctly-rounded operation.
757const FUSED_DECIMAL_POW10: [f64; 19] = [
758    1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16,
759    1e17, 1e18,
760];
761
762/// One CSV field admitted by the fused scanner/parser.
763struct FusedNumericField {
764    /// `Some` when the field is a plain optionally-signed integer; mirrors the
765    /// `parse_i64_ascii` route of `push_csv_default_numeric_field`.
766    int_value: Option<i64>,
767    /// The field value as `f64`, bit-identical to `parse_f64_csv_number` on
768    /// the same bytes (including the sign of zero, e.g. `-0` -> -0.0).
769    float_value: f64,
770    /// Index of the terminating delimiter (`,` or `\n`) or `data.len()`.
771    end: usize,
772}
773
774/// Scans one CSV field starting at `start`, fusing delimiter detection with
775/// decimal digit accumulation in a single pass over the bytes.
776///
777/// Admits only `[+-]?digits[.digits]` tokens with at most 18 mantissa digits
778/// (so the `u64` accumulator and the `i64` integer route can never overflow)
779/// and, for fractional values, a mantissa of at most 2^53 (so it is exactly
780/// representable in `f64`). Under those gates the computed value is provably
781/// bit-identical to the fallback parser: the mantissa and the power of ten
782/// are both exact in `f64`, so the single division (or `u64 -> f64`
783/// round-to-nearest-even conversion for integers) yields the correctly
784/// rounded value of the decimal token — the same contract `fast_float2` and
785/// `str::parse::<f64>` guarantee. Anything else (NA tokens, booleans,
786/// whitespace, exponents, overlong or malformed numbers, quotes, CR) returns
787/// `None` and must take the existing per-field fallback route.
788#[inline]
789fn fuse_scan_numeric_csv_field(data: &[u8], start: usize) -> Option<FusedNumericField> {
790    let mut pos = start;
791    let mut negative = false;
792    match data.get(pos) {
793        Some(b'-') => {
794            negative = true;
795            pos += 1;
796        }
797        Some(b'+') => pos += 1,
798        _ => {}
799    }
800
801    let mut mantissa: u64 = 0;
802    let mut digits = 0usize;
803    let mut frac_digits = 0usize;
804    let mut seen_dot = false;
805    loop {
806        match data.get(pos) {
807            Some(&byte @ b'0'..=b'9') => {
808                if digits == 18 {
809                    return None;
810                }
811                mantissa = mantissa * 10 + u64::from(byte - b'0');
812                digits += 1;
813                frac_digits += usize::from(seen_dot);
814                pos += 1;
815            }
816            Some(b'.') if !seen_dot => {
817                seen_dot = true;
818                pos += 1;
819            }
820            Some(b',' | b'\n') | None => break,
821            Some(_) => return None,
822        }
823    }
824
825    if digits == 0 || (seen_dot && frac_digits == 0) {
826        return None;
827    }
828
829    if seen_dot {
830        if mantissa > (1u64 << 53) {
831            return None;
832        }
833        let magnitude = mantissa as f64 / FUSED_DECIMAL_POW10[frac_digits];
834        Some(FusedNumericField {
835            int_value: None,
836            float_value: if negative { -magnitude } else { magnitude },
837            end: pos,
838        })
839    } else {
840        // digits <= 18 => mantissa < 10^18 < i64::MAX, so the cast is exact.
841        let int_magnitude = mantissa as i64;
842        let float_magnitude = mantissa as f64;
843        Some(FusedNumericField {
844            int_value: Some(if negative {
845                -int_magnitude
846            } else {
847                int_magnitude
848            }),
849            float_value: if negative {
850                -float_magnitude
851            } else {
852                float_magnitude
853            },
854            end: pos,
855        })
856    }
857}
858
859/// Pushes a fused numeric field with the exact dtype/promotion semantics of
860/// `push_csv_default_numeric_field`: integers keep an Int64 column while any
861/// fractional value promotes it to Float64; Float64 columns always take the
862/// `f64` form of the token (which is how the fallback parses them too).
863#[inline]
864fn push_fused_numeric_csv_field(values: &mut CsvTypedColumnValues, field: &FusedNumericField) {
865    match values {
866        CsvTypedColumnValues::Int64(out) => {
867            if let Some(value) = field.int_value {
868                out.push(value);
869            } else {
870                let mut promoted = Vec::with_capacity(out.capacity());
871                promoted.extend(out.iter().copied().map(|value| value as f64));
872                promoted.push(field.float_value);
873                *values = CsvTypedColumnValues::Float64(promoted);
874            }
875        }
876        CsvTypedColumnValues::Float64(out) => out.push(field.float_value),
877    }
878}
879
880fn push_csv_default_numeric_field(values: &mut CsvTypedColumnValues, field: &[u8]) -> bool {
881    if is_pandas_default_na_bytes(field) {
882        return false;
883    }
884
885    let trimmed = trim_ascii_field(field);
886    if trimmed.is_empty()
887        || eq_ignore_ascii_case_bytes(field, b"true")
888        || eq_ignore_ascii_case_bytes(field, b"false")
889    {
890        return false;
891    }
892
893    match values {
894        CsvTypedColumnValues::Int64(out) => {
895            if !has_float_marker(trimmed)
896                && let Some(value) = parse_i64_ascii(trimmed)
897            {
898                out.push(value);
899                true
900            } else {
901                match parse_f64_csv_number(trimmed) {
902                    Some(value) if !value.is_nan() => {
903                        let mut promoted = Vec::with_capacity(out.capacity());
904                        promoted.extend(out.iter().copied().map(|value| value as f64));
905                        promoted.push(value);
906                        *values = CsvTypedColumnValues::Float64(promoted);
907                        true
908                    }
909                    Some(_) | None => false,
910                }
911            }
912        }
913        CsvTypedColumnValues::Float64(out) => match parse_f64_csv_number(trimmed) {
914            Some(value) if !value.is_nan() => {
915                out.push(value);
916                true
917            }
918            Some(_) | None => false,
919        },
920    }
921}
922
923fn csv_default_unit_range_index(row_count: i64) -> Index {
924    let row_len = usize::try_from(row_count).expect("CSV row count must be non-negative");
925    Index::new_known_unique_int64_unit_range(0, row_len)
926}
927
928fn build_typed_numeric_csv_frame(
929    headers: &[String],
930    typed_columns: Vec<CsvTypedColumnValues>,
931    row_count: i64,
932) -> Result<DataFrame, IoError> {
933    let mut out_columns = BTreeMap::new();
934    let mut column_order = Vec::with_capacity(headers.len());
935    for (name, values) in headers.iter().cloned().zip(typed_columns) {
936        let column = match values {
937            CsvTypedColumnValues::Int64(values) => Column::from_i64_values(values),
938            CsvTypedColumnValues::Float64(values) => Column::from_f64_values(values),
939        };
940        out_columns.insert(name.clone(), column);
941        column_order.push(name);
942    }
943
944    let index = csv_default_unit_range_index(row_count);
945    DataFrame::new_with_column_order(index, out_columns, column_order).map_err(IoError::from)
946}
947
948fn simple_numeric_csv_parallel_worker_count(data_len: usize) -> usize {
949    if data_len < SIMPLE_NUMERIC_CSV_PARALLEL_MIN_BYTES {
950        return 1;
951    }
952    std::thread::available_parallelism()
953        .map_or(1, std::num::NonZeroUsize::get)
954        .min(SIMPLE_NUMERIC_CSV_PARALLEL_MAX_WORKERS)
955}
956
957fn split_simple_numeric_csv_chunks(
958    data: &[u8],
959    worker_count: usize,
960) -> Option<Vec<(usize, usize)>> {
961    if worker_count < 2 || data.is_empty() {
962        return None;
963    }
964
965    let target_len = data.len().div_ceil(worker_count);
966    let mut chunks = Vec::with_capacity(worker_count);
967    let mut start = 0usize;
968    while start < data.len() {
969        let mut end = start.saturating_add(target_len).min(data.len());
970        if end < data.len() {
971            let relative_newline = data[end..].iter().position(|byte| *byte == b'\n')?;
972            end += relative_newline + 1;
973        }
974        if end <= start {
975            return None;
976        }
977        chunks.push((start, end));
978        start = end;
979    }
980
981    (chunks.len() > 1).then_some(chunks)
982}
983
984fn parse_simple_numeric_csv_chunk(
985    data: &[u8],
986    header_count: usize,
987) -> Option<(Vec<CsvTypedColumnValues>, i64)> {
988    let row_hint = data.len() / (header_count * 8).max(1);
989    let mut typed_columns: Vec<CsvTypedColumnValues> = (0..header_count)
990        .map(|_| CsvTypedColumnValues::Int64(Vec::with_capacity(row_hint)))
991        .collect();
992    let mut row_count: i64 = 0;
993    let mut column_idx = 0usize;
994    let mut pos = 0usize;
995
996    while pos < data.len() {
997        if column_idx >= header_count {
998            return None;
999        }
1000        let field_end = if let Some(field) = fuse_scan_numeric_csv_field(data, pos) {
1001            push_fused_numeric_csv_field(&mut typed_columns[column_idx], &field);
1002            field.end
1003        } else {
1004            // Fallback: locate the delimiter with the original abort rules
1005            // (quote or bare CR anywhere rejects the whole chunk) and route
1006            // the raw field through the general numeric field parser.
1007            let mut idx = pos;
1008            let end = loop {
1009                match data.get(idx) {
1010                    None | Some(b',' | b'\n') => break idx,
1011                    Some(b'"') => return None,
1012                    Some(b'\r') if data.get(idx + 1).copied() != Some(b'\n') => return None,
1013                    Some(_) => idx += 1,
1014                }
1015            };
1016            if !push_csv_default_numeric_field(&mut typed_columns[column_idx], &data[pos..end]) {
1017                return None;
1018            }
1019            end
1020        };
1021
1022        match data.get(field_end).copied() {
1023            Some(b',') => {
1024                column_idx += 1;
1025                if column_idx >= header_count {
1026                    return None;
1027                }
1028            }
1029            // A newline or end-of-data both terminate the row.
1030            Some(b'\n') | None => {
1031                if column_idx + 1 != header_count {
1032                    return None;
1033                }
1034                row_count += 1;
1035                column_idx = 0;
1036            }
1037            // Unreachable: both field routes stop only at `,`/`\n`/EOF.
1038            Some(_) => return None,
1039        }
1040        pos = field_end + 1;
1041    }
1042
1043    // A chunk that ends mid-row (e.g. trailing comma) is malformed.
1044    if column_idx != 0 {
1045        return None;
1046    }
1047
1048    (row_count > 0).then_some((typed_columns, row_count))
1049}
1050
1051/// Merges one output column from its per-chunk source vectors, in chunk
1052/// order. Mirrors the original chunk-major merge arms exactly: Int64 sources
1053/// append to an Int64 column or widen (`value as f64`) into a Float64 column;
1054/// a Float64 source reaching an Int64 column is a contract violation (the
1055/// promotion pre-scan forbids it) and rejects the merge.
1056fn merge_one_simple_numeric_csv_column(
1057    is_float: bool,
1058    capacity: usize,
1059    sources: Vec<CsvTypedColumnValues>,
1060) -> Option<CsvTypedColumnValues> {
1061    if is_float {
1062        let mut out = Vec::with_capacity(capacity);
1063        for src in sources {
1064            match src {
1065                CsvTypedColumnValues::Int64(src) => {
1066                    out.extend(src.into_iter().map(|value| value as f64));
1067                }
1068                CsvTypedColumnValues::Float64(src) => out.extend(src),
1069            }
1070        }
1071        Some(CsvTypedColumnValues::Float64(out))
1072    } else {
1073        let mut out = Vec::with_capacity(capacity);
1074        for src in sources {
1075            match src {
1076                CsvTypedColumnValues::Int64(src) => out.extend(src),
1077                CsvTypedColumnValues::Float64(_) => return None,
1078            }
1079        }
1080        Some(CsvTypedColumnValues::Int64(out))
1081    }
1082}
1083
1084/// Minimum total value count before the chunk merge fans out to threads;
1085/// below this the scoped-spawn overhead outweighs the copy it hides.
1086const SIMPLE_NUMERIC_CSV_PARALLEL_MERGE_MIN_VALUES: usize = 1 << 16;
1087
1088fn merge_simple_numeric_csv_chunks(
1089    parsed_chunks: Vec<(Vec<CsvTypedColumnValues>, i64)>,
1090    header_count: usize,
1091) -> Option<(Vec<CsvTypedColumnValues>, i64)> {
1092    let mut final_is_float = vec![false; header_count];
1093    let mut row_count = 0i64;
1094    for (columns, rows) in &parsed_chunks {
1095        if columns.len() != header_count {
1096            return None;
1097        }
1098        row_count = row_count.checked_add(*rows)?;
1099        for (idx, column) in columns.iter().enumerate() {
1100            final_is_float[idx] |= matches!(column, CsvTypedColumnValues::Float64(_));
1101        }
1102    }
1103
1104    let capacity = usize::try_from(row_count).ok()?;
1105
1106    // Transpose chunk-major ownership to column-major: per_column[j] holds
1107    // column j's source vector from every chunk, in chunk order. This moves
1108    // only Vec headers — no value data is copied.
1109    let mut per_column: Vec<Vec<CsvTypedColumnValues>> = (0..header_count)
1110        .map(|_| Vec::with_capacity(parsed_chunks.len()))
1111        .collect();
1112    for (columns, _) in parsed_chunks {
1113        for (slot, column) in per_column.iter_mut().zip(columns) {
1114            slot.push(column);
1115        }
1116    }
1117
1118    let parallel = header_count >= 2
1119        && capacity
1120            .checked_mul(header_count)
1121            .is_some_and(|total| total >= SIMPLE_NUMERIC_CSV_PARALLEL_MERGE_MIN_VALUES);
1122    if !parallel {
1123        let mut merged = Vec::with_capacity(header_count);
1124        for (is_float, sources) in final_is_float.iter().copied().zip(per_column) {
1125            merged.push(merge_one_simple_numeric_csv_column(
1126                is_float, capacity, sources,
1127            )?);
1128        }
1129        return Some((merged, row_count));
1130    }
1131
1132    // Fan the per-column merges out over contiguous column groups so output
1133    // order is preserved by construction; each group thread runs the same
1134    // sequential per-column merge.
1135    let worker_count = header_count.min(SIMPLE_NUMERIC_CSV_PARALLEL_MAX_WORKERS);
1136    let group_size = header_count.div_ceil(worker_count);
1137    let mut groups: Vec<(usize, Vec<Vec<CsvTypedColumnValues>>)> = Vec::new();
1138    let mut group_start = 0usize;
1139    let mut remaining = per_column;
1140    while !remaining.is_empty() {
1141        let take = group_size.min(remaining.len());
1142        let rest = remaining.split_off(take);
1143        groups.push((group_start, remaining));
1144        group_start += take;
1145        remaining = rest;
1146    }
1147
1148    let final_is_float = &final_is_float;
1149    let merged_groups = std::thread::scope(|scope| {
1150        let handles: Vec<_> = groups
1151            .into_iter()
1152            .map(|(start, sources_group)| {
1153                scope.spawn(move || {
1154                    let mut merged_group = Vec::with_capacity(sources_group.len());
1155                    for (offset, sources) in sources_group.into_iter().enumerate() {
1156                        merged_group.push(merge_one_simple_numeric_csv_column(
1157                            final_is_float[start + offset],
1158                            capacity,
1159                            sources,
1160                        )?);
1161                    }
1162                    Some(merged_group)
1163                })
1164            })
1165            .collect();
1166
1167        let mut merged_groups = Vec::with_capacity(handles.len());
1168        for handle in handles {
1169            merged_groups.push(handle.join().ok().flatten()?);
1170        }
1171        Some(merged_groups)
1172    })?;
1173
1174    let mut merged = Vec::with_capacity(header_count);
1175    for group in merged_groups {
1176        merged.extend(group);
1177    }
1178
1179    Some((merged, row_count))
1180}
1181
1182fn parse_simple_numeric_csv_parallel_chunks(
1183    data: &[u8],
1184    header_count: usize,
1185    worker_count: usize,
1186) -> Option<(Vec<CsvTypedColumnValues>, i64)> {
1187    let chunks = split_simple_numeric_csv_chunks(data, worker_count)?;
1188    let parsed_chunks = std::thread::scope(|scope| {
1189        let handles: Vec<_> = chunks
1190            .iter()
1191            .map(|&(start, end)| {
1192                let chunk = &data[start..end];
1193                scope.spawn(move || parse_simple_numeric_csv_chunk(chunk, header_count))
1194            })
1195            .collect();
1196
1197        let mut parsed = Vec::with_capacity(handles.len());
1198        for handle in handles {
1199            let result = handle.join().ok().flatten()?;
1200            parsed.push(result);
1201        }
1202        Some(parsed)
1203    })?;
1204
1205    merge_simple_numeric_csv_chunks(parsed_chunks, header_count)
1206}
1207
1208fn try_read_csv_str_simple_typed_numeric_parallel(
1209    data: &[u8],
1210    headers: &[String],
1211    header_count: usize,
1212) -> Result<Option<DataFrame>, IoError> {
1213    let worker_count = simple_numeric_csv_parallel_worker_count(data.len());
1214    let Some((typed_columns, row_count)) =
1215        parse_simple_numeric_csv_parallel_chunks(data, header_count, worker_count)
1216    else {
1217        return Ok(None);
1218    };
1219
1220    build_typed_numeric_csv_frame(headers, typed_columns, row_count).map(Some)
1221}
1222
1223fn try_read_csv_str_simple_typed_numeric(
1224    input: &str,
1225    headers: &[String],
1226) -> Result<Option<DataFrame>, IoError> {
1227    let header_count = headers.len();
1228    if header_count == 0 {
1229        return Ok(None);
1230    }
1231
1232    let bytes = input.as_bytes();
1233    let Some(header_end) = bytes.iter().position(|byte| *byte == b'\n') else {
1234        return Ok(None);
1235    };
1236    if bytes[..header_end]
1237        .iter()
1238        .any(|byte| matches!(byte, b'"' | b'\r'))
1239    {
1240        return Ok(None);
1241    }
1242
1243    let data = &bytes[header_end + 1..];
1244    if data.is_empty() {
1245        return Ok(None);
1246    }
1247
1248    if let Some(frame) =
1249        try_read_csv_str_simple_typed_numeric_parallel(data, headers, header_count)?
1250    {
1251        return Ok(Some(frame));
1252    }
1253
1254    let Some((typed_columns, row_count)) = parse_simple_numeric_csv_chunk(data, header_count)
1255    else {
1256        return Ok(None);
1257    };
1258
1259    build_typed_numeric_csv_frame(headers, typed_columns, row_count).map(Some)
1260}
1261
1262fn try_read_csv_str_typed_numeric(
1263    input: &str,
1264    headers: &[String],
1265) -> Result<Option<DataFrame>, IoError> {
1266    let header_count = headers.len();
1267    if header_count == 0 {
1268        return Ok(None);
1269    }
1270
1271    let mut reader = ReaderBuilder::new()
1272        .has_headers(true)
1273        .from_reader(input.as_bytes());
1274    let _ = reader.headers().map_err(IoError::from)?;
1275
1276    let row_hint = input.len() / (header_count * 8).max(1);
1277    let mut typed_columns: Vec<CsvTypedColumnValues> = (0..header_count)
1278        .map(|_| CsvTypedColumnValues::Int64(Vec::with_capacity(row_hint)))
1279        .collect();
1280    let mut row_count: i64 = 0;
1281    for row in reader.byte_records() {
1282        let record = row?;
1283        for (idx, column) in typed_columns.iter_mut().enumerate() {
1284            let field = record.get(idx).unwrap_or_default();
1285            if !push_csv_default_numeric_field(column, field) {
1286                return Ok(None);
1287            }
1288        }
1289        row_count += 1;
1290    }
1291
1292    if row_count == 0 {
1293        return Ok(None);
1294    }
1295
1296    build_typed_numeric_csv_frame(headers, typed_columns, row_count).map(Some)
1297}
1298
1299fn try_read_csv_with_options_no_na_numeric_fast_path(
1300    input: &str,
1301) -> Result<Option<DataFrame>, IoError> {
1302    let mut reader = ReaderBuilder::new()
1303        .has_headers(true)
1304        .from_reader(input.as_bytes());
1305
1306    let headers_record = reader.headers().cloned().map_err(IoError::from)?;
1307    if headers_record.is_empty() {
1308        return Err(IoError::MissingHeaders);
1309    }
1310    let headers: Vec<String> = headers_record.iter().map(ToOwned::to_owned).collect();
1311    reject_duplicate_headers(&headers)?;
1312
1313    try_read_csv_str_simple_typed_numeric(input, &headers)
1314}
1315
1316const CSV_PARSE_CACHE_MAX_ENTRIES: usize = 2;
1317const CSV_PARSE_CACHE_MAX_INPUT_BYTES: usize = 32 * 1024 * 1024;
1318
1319#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1320enum CsvParseCacheMode {
1321    Default,
1322    NoNaNumeric,
1323}
1324
1325#[derive(Clone)]
1326struct CsvParseCacheEntry {
1327    mode: CsvParseCacheMode,
1328    input: Arc<str>,
1329    // Arc so the cache critical section only bumps a refcount; the O(data)
1330    // DataFrame deep-clone happens OUTSIDE the global lock (concurrency
1331    // audit 2026-06-07: the under-lock clone serialized every concurrent
1332    // read_csv — including cache MISSES — behind one reader's deep clone).
1333    frame: Arc<DataFrame>,
1334}
1335
1336static CSV_PARSE_CACHE: OnceLock<Mutex<VecDeque<CsvParseCacheEntry>>> = OnceLock::new();
1337
1338fn csv_parse_cache() -> &'static Mutex<VecDeque<CsvParseCacheEntry>> {
1339    CSV_PARSE_CACHE.get_or_init(|| Mutex::new(VecDeque::new()))
1340}
1341
1342fn csv_parse_cache_entry_matches(
1343    entry: &CsvParseCacheEntry,
1344    mode: CsvParseCacheMode,
1345    input: &str,
1346) -> bool {
1347    entry.mode == mode
1348        && entry.input.len() == input.len()
1349        && entry.input.as_bytes() == input.as_bytes()
1350}
1351
1352fn csv_parse_cache_lookup(mode: CsvParseCacheMode, input: &str) -> Option<DataFrame> {
1353    if input.len() > CSV_PARSE_CACHE_MAX_INPUT_BYTES {
1354        return None;
1355    }
1356
1357    // Hold the lock only for the lookup + LRU bump (Arc refcount ops); the
1358    // deep clone for the caller happens after release.
1359    let shared: Arc<DataFrame> = {
1360        let mut cache = csv_parse_cache().lock().ok()?;
1361        let pos = cache
1362            .iter()
1363            .position(|entry| csv_parse_cache_entry_matches(entry, mode, input))?;
1364        if pos == 0 {
1365            Arc::clone(&cache.front()?.frame)
1366        } else {
1367            let entry = cache.remove(pos)?;
1368            let frame = Arc::clone(&entry.frame);
1369            cache.push_front(entry);
1370            frame
1371        }
1372    };
1373    Some((*shared).clone())
1374}
1375
1376fn csv_parse_cache_store(mode: CsvParseCacheMode, input: &str, frame: &DataFrame) {
1377    if input.len() > CSV_PARSE_CACHE_MAX_INPUT_BYTES {
1378        return;
1379    }
1380
1381    // Deep-clone into the Arc BEFORE taking the lock (see lookup).
1382    let shared = Arc::new(frame.clone());
1383    let owned_input = Arc::<str>::from(input);
1384
1385    let Ok(mut cache) = csv_parse_cache().lock() else {
1386        return;
1387    };
1388
1389    if let Some(pos) = cache
1390        .iter()
1391        .position(|entry| csv_parse_cache_entry_matches(entry, mode, input))
1392    {
1393        cache.remove(pos);
1394    }
1395
1396    cache.push_front(CsvParseCacheEntry {
1397        mode,
1398        input: owned_input,
1399        frame: shared,
1400    });
1401
1402    while cache.len() > CSV_PARSE_CACHE_MAX_ENTRIES {
1403        cache.pop_back();
1404    }
1405}
1406
1407fn read_csv_str_uncached(input: &str) -> Result<DataFrame, IoError> {
1408    let mut reader = ReaderBuilder::new()
1409        .has_headers(true)
1410        .from_reader(input.as_bytes());
1411
1412    let headers_record = reader.headers().cloned().map_err(IoError::from)?;
1413
1414    if headers_record.is_empty() {
1415        return Err(IoError::MissingHeaders);
1416    }
1417    let headers: Vec<String> = headers_record.iter().map(ToOwned::to_owned).collect();
1418    reject_duplicate_headers(&headers)?;
1419
1420    if let Some(frame) = try_read_csv_str_simple_typed_numeric(input, &headers)? {
1421        return Ok(frame);
1422    }
1423
1424    if let Some(frame) = try_read_csv_str_typed_numeric(input, &headers)? {
1425        return Ok(frame);
1426    }
1427
1428    // AG-07: Vec-based column accumulation (O(1) per cell vs O(log c) BTreeMap).
1429    // Capacity hint from byte length avoids reallocation for typical CSVs.
1430    let header_count = headers.len();
1431    let row_hint = input.len() / (header_count * 8).max(1);
1432    // Keep each cell's original text so an object-fallback column can preserve
1433    // the verbatim literal like pandas (see build_csv_object_aware_column). Stored
1434    // as ONE contiguous byte buffer + offsets per column rather than a
1435    // `Vec<String>` — the per-cell `field.to_owned()` was ~1.5M small-string
1436    // mallocs on a mixed 500k×3 CSV (~36% of the parse). `raw` is consulted ONLY
1437    // for a Utf8-result column (numeric/bool columns never read it), and the
1438    // contiguous form is indexed identically there. (br-frankenpandas csv-raw-contig)
1439    let mut raw_bytes: Vec<Vec<u8>> = (0..header_count)
1440        .map(|_| Vec::with_capacity(row_hint * 8))
1441        .collect();
1442    let mut raw_offsets: Vec<Vec<usize>> = (0..header_count)
1443        .map(|_| {
1444            let mut v = Vec::with_capacity(row_hint + 1);
1445            v.push(0usize);
1446            v
1447        })
1448        .collect();
1449
1450    // Per-column typed accumulator (br-frankenpandas csv-typed-numeric-col): a
1451    // mixed CSV bails the frame-wide numeric fast paths, so historically EVERY
1452    // column round-tripped through a `Vec<Scalar>` (parse_scalar per cell + a
1453    // from_values re-scan) — even a purely-numeric column sitting next to one
1454    // Utf8 column. Accumulate each column into a typed Int64/Float64 buffer and,
1455    // the instant a cell is a null / bool / non-numeric-text (an AMBIGUOUS
1456    // promotion — fp's from_values keeps int+null as NULLABLE Int64, coerces
1457    // int+bool to Int64, etc.; see the probe in the commit msg), drop that column
1458    // to `Fallback` and rebuild it via the UNCHANGED Scalar path from the raw
1459    // bytes (already captured for verbatim). A pure-numeric-no-null column then
1460    // emits its typed column directly, bit-identical to from_values over the
1461    // equivalent Scalars: all-Int64 → Int64 (from_i64_values), any-Float64-no-null
1462    // → Float64 with ints coerced to `x as f64` (from_f64_values) — exactly what
1463    // Column::from_values + build_csv_object_aware_column produce for those inputs.
1464    // `valid: None` = all-valid so far (the common fast case, no per-cell bit
1465    // tracking); `Some(mask)` = at least one NA has appeared. A numeric column
1466    // with nulls stays typed — fp's from_values keeps int+null as NULLABLE Int64
1467    // and float+null as Float64, and build_csv_object_aware_column normalizes a
1468    // Float null to NaN; `from_{i64,f64}_values_with_validity` reproduce those
1469    // exactly (Int64 missing → Null(Null); Float64 missing → Null(NaN); verified).
1470    enum ColAcc {
1471        Int(Vec<i64>, Option<Vec<bool>>),
1472        Float(Vec<f64>, Option<Vec<bool>>),
1473        Fallback,
1474    }
1475    let mut accs: Vec<ColAcc> = (0..header_count)
1476        .map(|_| ColAcc::Int(Vec::with_capacity(row_hint), None))
1477        .collect();
1478
1479    let mut row_count: i64 = 0;
1480    for row in reader.records() {
1481        let record = row?;
1482        for idx in 0..header_count {
1483            let field = record.get(idx).unwrap_or_default();
1484            raw_bytes[idx].extend_from_slice(field.as_bytes());
1485            raw_offsets[idx].push(raw_bytes[idx].len());
1486            let acc = &mut accs[idx];
1487            if matches!(acc, ColAcc::Fallback) {
1488                continue;
1489            }
1490            // Mirror parse_scalar's decision order EXACTLY: NA (untrimmed) →
1491            // Int64(trimmed) → Float64(trimmed) → else (bool/text) = ambiguous.
1492            if is_pandas_default_na(field) {
1493                match acc {
1494                    ColAcc::Int(buf, valid) => {
1495                        valid
1496                            .get_or_insert_with(|| vec![true; buf.len()])
1497                            .push(false);
1498                        buf.push(0);
1499                    }
1500                    ColAcc::Float(buf, valid) => {
1501                        valid
1502                            .get_or_insert_with(|| vec![true; buf.len()])
1503                            .push(false);
1504                        buf.push(0.0);
1505                    }
1506                    ColAcc::Fallback => {}
1507                }
1508                continue;
1509            }
1510            let trimmed = field.trim();
1511            if let Ok(v) = trimmed.parse::<i64>() {
1512                match acc {
1513                    ColAcc::Int(buf, valid) => {
1514                        buf.push(v);
1515                        if let Some(vv) = valid {
1516                            vv.push(true);
1517                        }
1518                    }
1519                    ColAcc::Float(buf, valid) => {
1520                        buf.push(v as f64);
1521                        if let Some(vv) = valid {
1522                            vv.push(true);
1523                        }
1524                    }
1525                    ColAcc::Fallback => {}
1526                }
1527            } else if let Ok(v) = trimmed.parse::<f64>() {
1528                match acc {
1529                    ColAcc::Int(buf, valid) => {
1530                        let mut promoted: Vec<f64> = buf.iter().map(|&i| i as f64).collect();
1531                        promoted.push(v);
1532                        if let Some(vv) = valid.as_mut() {
1533                            vv.push(true);
1534                        }
1535                        *acc = ColAcc::Float(promoted, valid.take());
1536                    }
1537                    ColAcc::Float(buf, valid) => {
1538                        buf.push(v);
1539                        if let Some(vv) = valid {
1540                            vv.push(true);
1541                        }
1542                    }
1543                    ColAcc::Fallback => {}
1544                }
1545            } else {
1546                *acc = ColAcc::Fallback;
1547            }
1548        }
1549        row_count += 1;
1550    }
1551
1552    // Build a ValidityMask from a per-row bool vec (all-true entries are the
1553    // default). Returns None if every entry is valid (caller uses the all-valid
1554    // constructor) or if none are (caller falls back — an all-NA column is Null
1555    // dtype in the Scalar path, not typed).
1556    fn validity_from_bools(valid: &[bool]) -> Option<fp_columnar::ValidityMask> {
1557        if valid.iter().all(|&b| b) {
1558            return None;
1559        }
1560        let mut mask = fp_columnar::ValidityMask::all_valid(valid.len());
1561        for (i, &ok) in valid.iter().enumerate() {
1562            if !ok {
1563                mask.set(i, false);
1564            }
1565        }
1566        Some(mask)
1567    }
1568
1569    let mut out_columns = BTreeMap::new();
1570    let mut column_order = Vec::with_capacity(header_count);
1571    for (idx, acc) in accs.into_iter().enumerate() {
1572        let name = headers.get(idx).cloned().unwrap_or_default();
1573        // An empty (0-row) or all-NA numeric column is Null/empty dtype in the
1574        // Scalar path, not Int64 — route it to the fallback for exact parity.
1575        let has_value = |buf_len: usize, valid: &Option<Vec<bool>>| -> bool {
1576            buf_len > 0 && valid.as_ref().is_none_or(|v| v.iter().any(|&b| b))
1577        };
1578        let column = match acc {
1579            // Typed fast paths (all-valid OR nullable): taken when every cell was
1580            // clean-numeric (possibly NA), so the output dtype is unambiguous.
1581            ColAcc::Int(buf, valid) if has_value(buf.len(), &valid) => {
1582                match valid.as_deref().and_then(validity_from_bools) {
1583                    Some(mask) => Column::from_i64_values_with_validity(buf, mask),
1584                    None => Column::from_i64_values(buf),
1585                }
1586            }
1587            ColAcc::Float(buf, valid) if has_value(buf.len(), &valid) => {
1588                match valid.as_deref().and_then(validity_from_bools) {
1589                    Some(mask) => Column::from_f64_values_with_validity(buf, mask),
1590                    None => Column::from_f64_values(buf),
1591                }
1592            }
1593            // Any ambiguous cell, all-NA, or empty → exact legacy path from raw.
1594            _ => {
1595                let raw_b = &raw_bytes[idx];
1596                let raw_o = &raw_offsets[idx];
1597                let mut values = Vec::with_capacity(raw_o.len().saturating_sub(1));
1598                for w in raw_o.windows(2) {
1599                    let field = std::str::from_utf8(&raw_b[w[0]..w[1]])
1600                        .expect("csv fields originate from a &str input");
1601                    values.push(parse_scalar(field));
1602                }
1603                build_csv_object_aware_column(values, raw_b, raw_o)?
1604            }
1605        };
1606        out_columns.insert(name.clone(), column);
1607        column_order.push(name);
1608    }
1609
1610    let index = csv_default_unit_range_index(row_count);
1611    Ok(DataFrame::new_with_column_order(
1612        index,
1613        out_columns,
1614        column_order,
1615    )?)
1616}
1617
1618pub fn read_csv_str(input: &str) -> Result<DataFrame, IoError> {
1619    if let Some(frame) = csv_parse_cache_lookup(CsvParseCacheMode::Default, input) {
1620        return Ok(frame);
1621    }
1622
1623    let frame = read_csv_str_uncached(input)?;
1624    csv_parse_cache_store(CsvParseCacheMode::Default, input, &frame);
1625    Ok(frame)
1626}
1627
1628pub fn write_csv_string(frame: &DataFrame) -> Result<String, IoError> {
1629    write_csv_string_with_options(frame, &CsvWriteOptions::default())
1630}
1631
1632pub fn write_markdown_string(frame: &DataFrame) -> Result<String, IoError> {
1633    write_markdown_string_with_options(frame, &MarkdownWriteOptions::default())
1634}
1635
1636pub fn write_latex_string(frame: &DataFrame) -> Result<String, IoError> {
1637    write_latex_string_with_options(frame, &LatexWriteOptions::default())
1638}
1639
1640pub fn write_html_string(frame: &DataFrame) -> Result<String, IoError> {
1641    write_html_string_with_options(frame, &HtmlWriteOptions::default())
1642}
1643
1644pub fn write_xml_string(frame: &DataFrame) -> Result<String, IoError> {
1645    write_xml_string_with_options(frame, &XmlWriteOptions::default())
1646}
1647
1648pub fn write_pickle_bytes(frame: &DataFrame) -> Result<Vec<u8>, IoError> {
1649    write_pickle_bytes_with_options(frame, &PickleWriteOptions::default())
1650}
1651
1652pub fn write_stata_bytes(frame: &DataFrame) -> Result<Vec<u8>, IoError> {
1653    write_stata_bytes_with_options(frame, &StataWriteOptions::default())
1654}
1655
1656/// Options controlling CSV serialization.
1657///
1658/// Mirrors the subset of pandas `DataFrame.to_csv` parameters that do
1659/// not depend on file IO (that layer is handled by `write_csv`).
1660#[derive(Debug, Clone)]
1661pub struct CsvWriteOptions {
1662    /// Field delimiter. Matches pandas `sep`. Default: `,`.
1663    pub delimiter: u8,
1664    /// String written for missing values. Matches pandas `na_rep`. Default: `""`.
1665    pub na_rep: String,
1666    /// If false, the header row is omitted. Matches pandas `header=False`.
1667    pub header: bool,
1668    /// If true, include the index as the first column. Matches pandas `index`.
1669    pub include_index: bool,
1670    /// Optional label for the index column header. Matches pandas `index_label`.
1671    /// When omitted, a named index uses its name and an unnamed index writes an
1672    /// empty header cell.
1673    pub index_label: Option<String>,
1674}
1675
1676impl Default for CsvWriteOptions {
1677    fn default() -> Self {
1678        Self {
1679            delimiter: b',',
1680            na_rep: String::new(),
1681            header: true,
1682            include_index: false,
1683            index_label: None,
1684        }
1685    }
1686}
1687
1688/// Options controlling Markdown table serialization.
1689///
1690/// Covers the pure string subset of pandas `DataFrame.to_markdown`.
1691#[derive(Debug, Clone)]
1692pub struct MarkdownWriteOptions {
1693    /// If true, include the index as the first column. Default: true.
1694    pub include_index: bool,
1695    /// String written for missing values. Default: `"NaN"`.
1696    pub na_rep: String,
1697    /// Optional label for the index column header.
1698    pub index_label: Option<String>,
1699}
1700
1701impl Default for MarkdownWriteOptions {
1702    fn default() -> Self {
1703        Self {
1704            include_index: true,
1705            na_rep: "NaN".to_owned(),
1706            index_label: None,
1707        }
1708    }
1709}
1710
1711/// Options controlling LaTeX table serialization.
1712///
1713/// Covers the pure string subset of pandas `DataFrame.to_latex`.
1714#[derive(Debug, Clone)]
1715pub struct LatexWriteOptions {
1716    /// If true, include the index as the first column. Default: true.
1717    pub include_index: bool,
1718    /// String written for missing values. Default: `"NaN"`.
1719    pub na_rep: String,
1720    /// Optional label for the index-name row.
1721    pub index_label: Option<String>,
1722    /// Escape LaTeX metacharacters in headers and cells.
1723    pub escape: bool,
1724}
1725
1726impl Default for LatexWriteOptions {
1727    fn default() -> Self {
1728        Self {
1729            include_index: true,
1730            na_rep: "NaN".to_owned(),
1731            index_label: None,
1732            escape: false,
1733        }
1734    }
1735}
1736
1737/// Options controlling HTML table serialization.
1738///
1739/// Covers the pure string subset of pandas `DataFrame.to_html`.
1740#[derive(Debug, Clone)]
1741pub struct HtmlWriteOptions {
1742    /// If true, include the index as the first column. Default: true.
1743    pub include_index: bool,
1744    /// String written for missing values. Matches pandas `na_rep`.
1745    /// Default: `"NaN"`.
1746    pub na_rep: String,
1747    /// Additional CSS classes appended to pandas' default `dataframe` class.
1748    /// Entries may contain whitespace-separated class names.
1749    pub classes: Vec<String>,
1750    /// Optional `id` attribute for the `<table>` element.
1751    pub table_id: Option<String>,
1752    /// Optional border value. `Some(0)` and `None` omit the border attribute.
1753    pub border: Option<u32>,
1754    /// Optional header text alignment. Defaults to pandas' `"right"`.
1755    pub justify: Option<String>,
1756    /// Escape HTML-sensitive characters in headers, index labels, and cells.
1757    pub escape: bool,
1758    /// Convert URL-like string values to anchors.
1759    pub render_links: bool,
1760}
1761
1762impl Default for HtmlWriteOptions {
1763    fn default() -> Self {
1764        Self {
1765            include_index: true,
1766            na_rep: "NaN".to_owned(),
1767            classes: Vec::new(),
1768            table_id: None,
1769            border: Some(1),
1770            justify: None,
1771            escape: true,
1772            render_links: false,
1773        }
1774    }
1775}
1776
1777/// Options controlling HTML table parsing.
1778///
1779/// Covers the first-table subset of pandas `read_html` for already-fetched
1780/// HTML strings and local files. Network fetching, JavaScript execution, and
1781/// rowspan/colspan expansion are intentionally out of scope for this slice.
1782#[derive(Debug, Clone, Default)]
1783pub struct HtmlReadOptions {
1784    /// Zero-based table index to parse. Default: `0`.
1785    pub table_index: usize,
1786}
1787
1788/// Pickle protocol used by [`write_pickle_bytes_with_options`].
1789#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1790pub enum PickleProtocol {
1791    /// Python pickle protocol 2, compatible with Python 2 and 3.
1792    V2,
1793    /// Python pickle protocol 3, the serde-pickle default.
1794    V3,
1795}
1796
1797/// Options controlling Pickle serialization.
1798///
1799/// This surface serializes a versioned FrankenPandas DataFrame envelope. It
1800/// does not try to emit arbitrary pandas Python objects.
1801#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1802pub struct PickleWriteOptions {
1803    /// Pickle protocol to emit. Default: protocol 3.
1804    pub protocol: PickleProtocol,
1805}
1806
1807impl Default for PickleWriteOptions {
1808    fn default() -> Self {
1809        Self {
1810            protocol: PickleProtocol::V3,
1811        }
1812    }
1813}
1814
1815/// Options controlling Pickle deserialization.
1816#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
1817pub struct PickleReadOptions {
1818    /// Decode legacy protocol 0-2 STRING opcodes as UTF-8. Default: false.
1819    pub decode_legacy_strings: bool,
1820}
1821
1822/// Default HDF5 group key used by [`read_hdf`] and [`write_hdf`].
1823pub const DEFAULT_HDF5_KEY: &str = "frame";
1824
1825#[cfg(feature = "hdf5")]
1826const HDF5_PAYLOAD_DATASET: &str = "__frankenpandas_dataframe_pickle_v1";
1827
1828/// Options controlling HDF5 path reads.
1829///
1830/// The current HDF5 surface stores the versioned FrankenPandas DataFrame
1831/// snapshot envelope under a keyed group. This deliberately preserves index,
1832/// row multiindex, dtype, and null semantics before native PyTables-compatible
1833/// table layouts land.
1834#[derive(Debug, Clone, PartialEq, Eq)]
1835pub struct HdfReadOptions {
1836    /// HDF5 group key to read. Default: [`DEFAULT_HDF5_KEY`].
1837    pub key: String,
1838}
1839
1840impl Default for HdfReadOptions {
1841    fn default() -> Self {
1842        Self {
1843            key: DEFAULT_HDF5_KEY.to_owned(),
1844        }
1845    }
1846}
1847
1848/// Options controlling HDF5 path writes.
1849#[derive(Debug, Clone, PartialEq, Eq)]
1850pub struct HdfWriteOptions {
1851    /// HDF5 group key to write. Default: [`DEFAULT_HDF5_KEY`].
1852    pub key: String,
1853}
1854
1855impl Default for HdfWriteOptions {
1856    fn default() -> Self {
1857        Self {
1858            key: DEFAULT_HDF5_KEY.to_owned(),
1859        }
1860    }
1861}
1862
1863/// Options controlling Stata DTA serialization.
1864#[derive(Debug, Clone, PartialEq, Eq)]
1865pub struct StataWriteOptions {
1866    /// Include the DataFrame index as the first Stata variable. Default: true.
1867    pub include_index: bool,
1868    /// Optional index variable name. Default: `"index"`.
1869    pub index_label: Option<String>,
1870}
1871
1872impl Default for StataWriteOptions {
1873    fn default() -> Self {
1874        Self {
1875            include_index: true,
1876            index_label: None,
1877        }
1878    }
1879}
1880
1881/// Options controlling XML serialization.
1882///
1883/// Covers the writer-only default shape of pandas `DataFrame.to_xml`.
1884#[derive(Debug, Clone)]
1885pub struct XmlWriteOptions {
1886    /// If true, include the index as the first field in each row. Default: true.
1887    pub include_index: bool,
1888    /// XML root element name. Default: `"data"`.
1889    pub root_name: String,
1890    /// XML row element name. Default: `"row"`.
1891    pub row_name: String,
1892    /// Optional index element name. When omitted, use the index name or
1893    /// pandas' default `"index"`.
1894    pub index_label: Option<String>,
1895}
1896
1897impl Default for XmlWriteOptions {
1898    fn default() -> Self {
1899        Self {
1900            include_index: true,
1901            root_name: "data".to_owned(),
1902            row_name: "row".to_owned(),
1903            index_label: None,
1904        }
1905    }
1906}
1907
1908/// Options controlling XML parsing.
1909///
1910/// Covers the row-oriented subset produced by pandas `DataFrame.to_xml`.
1911#[derive(Debug, Clone)]
1912pub struct XmlReadOptions {
1913    /// XML element name representing one DataFrame row. Default: `"row"`.
1914    pub row_name: String,
1915}
1916
1917impl Default for XmlReadOptions {
1918    fn default() -> Self {
1919        Self {
1920            row_name: "row".to_owned(),
1921        }
1922    }
1923}
1924
1925/// Serialize a DataFrame to CSV with explicit options.
1926///
1927/// Matches `pd.DataFrame.to_csv(sep, na_rep, header, index, index_label)`
1928/// for the in-memory string form. Null and NaN-like values are
1929/// substituted with `options.na_rep`; all other scalars use the same
1930/// stringification as the default `write_csv_string`.
1931/// Fast path for `write_csv_string_with_options` when every column is an
1932/// all-valid Int64/Float64 typed buffer and the index is not emitted. Returns
1933/// `None` (caller uses the general `csv`-crate path) when any column is not a
1934/// numeric typed slice, the index is requested, the delimiter is non-ASCII, or
1935/// a header name would need quoting. The produced bytes are identical to the
1936/// general writer (see the call-site note). (br-frankenpandas-qk2i9)
1937#[derive(Debug, Clone, Copy)]
1938struct Float64QuarterAffineCsvPlan {
1939    start_scaled: i64,
1940    step_scaled: i64,
1941}
1942
1943impl Float64QuarterAffineCsvPlan {
1944    fn for_slice(values: &[f64]) -> Option<Self> {
1945        let first = scaled_nonnegative_quarter(values.first().copied()?)?;
1946        let second = values
1947            .get(1)
1948            .copied()
1949            .map(scaled_nonnegative_quarter)
1950            .unwrap_or(Some(first))?;
1951        let step_scaled = second.checked_sub(first)?;
1952        if step_scaled < 0 {
1953            return None;
1954        }
1955
1956        let plan = Self {
1957            start_scaled: first,
1958            step_scaled,
1959        };
1960        for (row, &value) in values.iter().enumerate() {
1961            if scaled_nonnegative_quarter(value)? != plan.scaled_at(row)? {
1962                return None;
1963            }
1964        }
1965        Some(plan)
1966    }
1967
1968    fn scaled_at(self, row: usize) -> Option<i64> {
1969        let row = i64::try_from(row).ok()?;
1970        self.start_scaled
1971            .checked_add(self.step_scaled.checked_mul(row)?)
1972    }
1973
1974    fn append_row(self, out: &mut String, row: usize) -> bool {
1975        let Some(scaled) = self.scaled_at(row) else {
1976            return false;
1977        };
1978        append_quarter_scaled_pandas_float(out, scaled);
1979        true
1980    }
1981}
1982
1983fn scaled_nonnegative_quarter(value: f64) -> Option<i64> {
1984    const MAX_EXACT_SCALED: f64 = 9_007_199_254_740_992.0;
1985
1986    if !value.is_finite() || value.is_sign_negative() {
1987        return None;
1988    }
1989    let scaled = value * 4.0;
1990    if !scaled.is_finite()
1991        || scaled > MAX_EXACT_SCALED
1992        || scaled.fract().to_bits() != 0.0f64.to_bits()
1993    {
1994        return None;
1995    }
1996    let scaled_i64 = scaled as i64;
1997    if (scaled_i64 as f64).to_bits() == scaled.to_bits() {
1998        Some(scaled_i64)
1999    } else {
2000        None
2001    }
2002}
2003
2004fn append_quarter_scaled_pandas_float(out: &mut String, scaled: i64) {
2005    debug_assert!(scaled >= 0);
2006    let mut whole = (scaled / 4) as u64;
2007    let rem = scaled % 4;
2008
2009    // Manual decimal emitter (br-frankenpandas-uza04.84): the quarter-affine
2010    // whole part previously went through `write!(out, "{whole}")`, i.e. the
2011    // core::fmt::write + i64 Display machinery (Formatter dispatch, padding
2012    // checks) the profile flagged as the residual hot path. Here we write the
2013    // whole digits and the fixed fractional suffix into one stack buffer and
2014    // emit a single push_str — byte-identical output, no fmt dispatch. `whole`
2015    // is non-negative (scaled >= 0) so no sign handling is needed; max 20 u64
2016    // digits + a 3-byte ".75" suffix fit in 23 bytes.
2017    let mut buf = [0u8; 23];
2018    let suffix: &[u8] = match rem {
2019        1 => b".25",
2020        2 => b".5",
2021        3 => b".75",
2022        _ => b".0",
2023    };
2024    let mut end = buf.len() - suffix.len();
2025    buf[end..].copy_from_slice(suffix);
2026
2027    // Whole digits, written right-to-left immediately before the suffix.
2028    let mut start = end;
2029    loop {
2030        start -= 1;
2031        buf[start] = b'0' + (whole % 10) as u8;
2032        whole /= 10;
2033        if whole == 0 {
2034            break;
2035        }
2036    }
2037    end = buf.len();
2038    out.push_str(std::str::from_utf8(&buf[start..end]).unwrap_or("0.0"));
2039}
2040
2041fn append_csv_minimal_field(out: &mut String, field: &str, delim: u8, quote_empty_single: bool) {
2042    if quote_empty_single && field.is_empty() {
2043        out.push_str("\"\"");
2044    } else if field
2045        .bytes()
2046        .any(|b| b == delim || b == b'"' || b == b'\n' || b == b'\r')
2047    {
2048        out.push('"');
2049        for ch in field.chars() {
2050            if ch == '"' {
2051                out.push_str("\"\"");
2052            } else {
2053                out.push(ch);
2054            }
2055        }
2056        out.push('"');
2057    } else {
2058        out.push_str(field);
2059    }
2060}
2061
2062fn append_i64_decimal(out: &mut String, value: i64) {
2063    let mut n = value.unsigned_abs();
2064    let mut buf = [0u8; 20];
2065    let mut start = buf.len();
2066    loop {
2067        start -= 1;
2068        buf[start] = b'0' + (n % 10) as u8;
2069        n /= 10;
2070        if n == 0 {
2071            break;
2072        }
2073    }
2074    if value < 0 {
2075        start -= 1;
2076        buf[start] = b'-';
2077    }
2078    out.push_str(std::str::from_utf8(&buf[start..]).unwrap_or(""));
2079}
2080
2081fn try_write_csv_typed(frame: &DataFrame, options: &CsvWriteOptions) -> Option<String> {
2082    let delim = options.delimiter;
2083    if !delim.is_ascii() {
2084        return None;
2085    }
2086    let delim_c = delim as char;
2087
2088    let headers: Vec<&String> = frame.column_names().into_iter().collect();
2089    let n = frame.index().len();
2090    let index_labels = if options.include_index {
2091        if frame.row_multiindex().is_some() {
2092            return None;
2093        }
2094        let labels = frame.index().labels();
2095        if labels.len() != n
2096            || labels
2097                .iter()
2098                .any(|label| !matches!(label, IndexLabel::Int64(_)))
2099        {
2100            return None;
2101        }
2102        Some(labels)
2103    } else {
2104        None
2105    };
2106
2107    enum FastCol<'a> {
2108        F {
2109            values: &'a [f64],
2110            quarter_plan: Option<Float64QuarterAffineCsvPlan>,
2111        },
2112        I(&'a [i64]),
2113        B(&'a [bool]),
2114        // All-valid contiguous Utf8: (bytes, offsets) with row r =
2115        // bytes[offsets[r]..offsets[r+1]].
2116        U(&'a [u8], &'a [usize]),
2117        // NULLABLE contiguous Utf8: (bytes, offsets, validity). A present row
2118        // (validity.get(r)) renders its span; a missing row renders na_rep — so a
2119        // string column WITH nulls no longer forces the WHOLE frame off the fast path.
2120        UN(&'a [u8], &'a [usize], &'a fp_columnar::ValidityMask),
2121        // NULLABLE Float64: (data, validity). A present row (validity.get(r) AND
2122        // non-NaN) renders format_pandas_float; a missing row (validity-clear OR a
2123        // valid-bit NaN — both `is_missing` for Float64) renders na_rep.
2124        FN(&'a [f64], &'a fp_columnar::ValidityMask),
2125        // NULLABLE Int64: (data, validity). Present → decimal; missing → na_rep.
2126        // Int64 has no NaN, so missingness is the validity bit alone.
2127        IN(&'a [i64], &'a fp_columnar::ValidityMask),
2128        // NULLABLE Bool: (data, validity). Present → True/False; missing → na_rep.
2129        BN(&'a [bool], &'a fp_columnar::ValidityMask),
2130        // All-valid (no validity-mask null) Datetime64 ns + the column-uniform
2131        // to_csv format; NaT sentinels render as na_rep inline.
2132        Dt(&'a [i64], DatetimeCsvFormat),
2133    }
2134    let mut cols: Vec<FastCol<'_>> = Vec::with_capacity(headers.len());
2135    for name in &headers {
2136        let column = frame.column(name)?;
2137        if let Some(s) = column.as_f64_slice() {
2138            if s.len() != n {
2139                return None;
2140            }
2141            cols.push(FastCol::F {
2142                values: s,
2143                quarter_plan: Float64QuarterAffineCsvPlan::for_slice(s),
2144            });
2145        } else if let Some(s) = column.as_i64_slice() {
2146            if s.len() != n {
2147                return None;
2148            }
2149            cols.push(FastCol::I(s));
2150        } else if let Some(s) = column.as_bool_slice() {
2151            if s.len() != n {
2152                return None;
2153            }
2154            cols.push(FastCol::B(s));
2155        } else if let Some((bytes, offsets)) = column.as_utf8_contiguous() {
2156            if offsets.len() != n + 1 {
2157                return None;
2158            }
2159            cols.push(FastCol::U(bytes, offsets));
2160        } else if let Some((bytes, offsets)) = column.as_nullable_utf8_contiguous() {
2161            // Nullable contiguous Utf8: present rows render their span, missing rows
2162            // (validity-clear) render na_rep — so one null-bearing string column no
2163            // longer disables the fast writer for the whole frame.
2164            if offsets.len() != n + 1 {
2165                return None;
2166            }
2167            cols.push(FastCol::UN(bytes, offsets, column.validity()));
2168        } else if let Some((s, validity)) = column.as_f64_slice_with_validity() {
2169            // Nullable Float64: the all-valid `as_f64_slice` above bailed (any NaN or
2170            // mask-null), so a null-bearing float column would otherwise force the whole
2171            // frame off the fast path. Render present slots and na_rep at missing ones.
2172            if s.len() != n {
2173                return None;
2174            }
2175            cols.push(FastCol::FN(s, validity));
2176        } else if let Some((s, validity)) = column.as_i64_slice_with_validity() {
2177            // Nullable Int64 sibling (no NaN — missingness is the validity bit alone).
2178            if s.len() != n {
2179                return None;
2180            }
2181            cols.push(FastCol::IN(s, validity));
2182        } else if let Some((s, validity)) = column.as_nullable_bool_slice() {
2183            // Nullable Bool sibling: present ⇒ True/False, missing ⇒ na_rep.
2184            if s.len() != n {
2185                return None;
2186            }
2187            cols.push(FastCol::BN(s, validity));
2188        } else if column.dtype() == DType::Datetime64 {
2189            // A validity-mask null (data slot ≠ NaT) would diverge from the
2190            // general path's `Scalar::Null` → na_rep; require no mask-nulls. NaT
2191            // sentinels (kept AS DATA by an all-valid backing) are rendered as
2192            // na_rep inline, matching scalar_to_csv_cell.
2193            let s = column.as_datetime64_slice()?;
2194            if s.len() != n || column.has_nulls() {
2195                return None;
2196            }
2197            cols.push(FastCol::Dt(s, datetime_csv_format(column)));
2198        } else {
2199            return None;
2200        }
2201    }
2202
2203    // csv QUOTE_MINIMAL (matched by the general WriterBuilder path) quotes a field
2204    // as `""` when it is the SOLE field in its record and would otherwise be empty,
2205    // so the line is not an ambiguous blank that read_csv decodes as zero fields.
2206    // A record has one field when there is exactly one emitted index/column field.
2207    let field_count = cols.len() + usize::from(options.include_index);
2208    let single_field = field_count == 1;
2209    let mut out = String::with_capacity(n.saturating_mul(field_count).saturating_mul(8) + 64);
2210    if options.header {
2211        let mut wrote_field = false;
2212        if options.include_index {
2213            let index_header = resolve_csv_index_header(frame, options);
2214            append_csv_minimal_field(&mut out, &index_header, delim, single_field);
2215            wrote_field = true;
2216        }
2217        for (i, h) in headers.iter().enumerate() {
2218            if wrote_field || i > 0 {
2219                out.push(delim_c);
2220            }
2221            append_csv_minimal_field(&mut out, h.as_str(), delim, single_field);
2222            wrote_field = true;
2223        }
2224        out.push('\n');
2225    }
2226    // Per-row-range writer (br-frankenpandas-csvpar): writes rows `[lo, hi)` into
2227    // `dst`, reading ONLY the shared read-only typed slices, so each row's bytes are
2228    // independent of chunk boundaries. Shared by the serial and chunked-parallel
2229    // drivers below — the parallel concat is byte-for-byte identical to the serial
2230    // output (header + rows 0..n in order).
2231    let write_range = |lo: usize, hi: usize, dst: &mut String| {
2232        for r in lo..hi {
2233            if let Some(labels) = index_labels
2234                && let IndexLabel::Int64(v) = &labels[r]
2235            {
2236                append_i64_decimal(dst, *v);
2237            }
2238            for (c, col) in cols.iter().enumerate() {
2239                if c > 0 || index_labels.is_some() {
2240                    dst.push(delim_c);
2241                }
2242                match col {
2243                    // Float64 uses format_pandas_float (Python str(float): keeps
2244                    // "1.0", signed 2-digit sci notation) — EXACTLY what
2245                    // scalar_to_csv_with_na uses, NOT Rust's Display (which drops the
2246                    // ".0"). as_f64_slice yields an all-valid (NaN-free) buffer so the
2247                    // NaN branch never fires; kept for defensive parity.
2248                    FastCol::F {
2249                        values,
2250                        quarter_plan,
2251                    } => {
2252                        if quarter_plan.is_some_and(|plan| plan.append_row(dst, r)) {
2253                            continue;
2254                        }
2255                        let v = values[r];
2256                        if v.is_nan() {
2257                            // Unreachable in practice (as_f64_slice is NaN-free), but kept
2258                            // isomorphic with the general path: a sole empty na_rep is quoted.
2259                            if single_field && options.na_rep.is_empty() {
2260                                dst.push_str("\"\"");
2261                            } else {
2262                                dst.push_str(&options.na_rep);
2263                            }
2264                        } else {
2265                            write_pandas_float(dst, v);
2266                        }
2267                    }
2268                    // Int64 formats via the hand-rolled append_i64_decimal fast path
2269                    // (byte-identical to Rust Display / scalar_to_csv's `v.to_string()`,
2270                    // but writes straight into `dst` with no temporary String alloc — so
2271                    // this is already optimal; don't "speed it up" with to_string/itoa).
2272                    FastCol::I(s) => {
2273                        append_i64_decimal(dst, s[r]);
2274                    }
2275                    // Bool uses pandas to_csv spelling: capitalized True/False.
2276                    FastCol::B(s) => {
2277                        dst.push_str(if s[r] { "True" } else { "False" });
2278                    }
2279                    // Utf8 cell: the raw &str (= Scalar::Utf8's value in scalar_to_csv),
2280                    // CSV-quoted only when it contains the delimiter, a quote, CR, or
2281                    // LF — pandas/csv QUOTE_MINIMAL, with internal quotes doubled.
2282                    FastCol::U(bytes, offsets) => {
2283                        let field = &bytes[offsets[r]..offsets[r + 1]];
2284                        // SAFETY-FREE: contiguous Utf8 backing is valid UTF-8.
2285                        let field = std::str::from_utf8(field).unwrap_or("");
2286                        append_csv_minimal_field(dst, field, delim, single_field);
2287                    }
2288                    // Nullable Utf8 cell: a present row (validity-set) renders its span
2289                    // exactly like `FastCol::U`; a missing row renders na_rep with the same
2290                    // sole-empty-field quoting as the Dt NaT / F NaN arms (isomorphic with
2291                    // the general path's `Scalar::Null` → na_rep).
2292                    FastCol::UN(bytes, offsets, validity) => {
2293                        if validity.get(r) {
2294                            let field = &bytes[offsets[r]..offsets[r + 1]];
2295                            let field = std::str::from_utf8(field).unwrap_or("");
2296                            append_csv_minimal_field(dst, field, delim, single_field);
2297                        } else if single_field && options.na_rep.is_empty() {
2298                            dst.push_str("\"\"");
2299                        } else {
2300                            dst.push_str(&options.na_rep);
2301                        }
2302                    }
2303                    // Nullable Float64: a present, non-NaN row renders like FastCol::F
2304                    // (write_pandas_float == format_pandas_float in scalar_to_csv_with_na);
2305                    // a missing row (validity-clear OR valid-bit NaN — both is_missing for
2306                    // Float64) renders na_rep with the same sole-empty-field quoting.
2307                    FastCol::FN(s, validity) => {
2308                        let v = s[r];
2309                        if validity.get(r) && !v.is_nan() {
2310                            write_pandas_float(dst, v);
2311                        } else if single_field && options.na_rep.is_empty() {
2312                            dst.push_str("\"\"");
2313                        } else {
2314                            dst.push_str(&options.na_rep);
2315                        }
2316                    }
2317                    // Nullable Int64: present ⇒ decimal (== FastCol::I / scalar_to_csv);
2318                    // missing (validity-clear) ⇒ na_rep.
2319                    FastCol::IN(s, validity) => {
2320                        if validity.get(r) {
2321                            append_i64_decimal(dst, s[r]);
2322                        } else if single_field && options.na_rep.is_empty() {
2323                            dst.push_str("\"\"");
2324                        } else {
2325                            dst.push_str(&options.na_rep);
2326                        }
2327                    }
2328                    // Nullable Bool: present ⇒ True/False (== FastCol::B / scalar_to_csv);
2329                    // missing (validity-clear) ⇒ na_rep.
2330                    FastCol::BN(s, validity) => {
2331                        if validity.get(r) {
2332                            dst.push_str(if s[r] { "True" } else { "False" });
2333                        } else if single_field && options.na_rep.is_empty() {
2334                            dst.push_str("\"\"");
2335                        } else {
2336                            dst.push_str(&options.na_rep);
2337                        }
2338                    }
2339                    // Datetime64: NaT → na_rep (isomorphic with the F NaN arm's sole
2340                    // empty-na quoting); else the column-uniform format string, routed
2341                    // through QUOTE_MINIMAL exactly like scalar_to_csv_cell's output.
2342                    FastCol::Dt(s, fmt) => {
2343                        let v = s[r];
2344                        if v == Timestamp::NAT {
2345                            if single_field && options.na_rep.is_empty() {
2346                                dst.push_str("\"\"");
2347                            } else {
2348                                dst.push_str(&options.na_rep);
2349                            }
2350                        } else {
2351                            let rendered = format_datetime_csv(v, *fmt);
2352                            append_csv_minimal_field(dst, &rendered, delim, single_field);
2353                        }
2354                    }
2355                }
2356            }
2357            dst.push('\n');
2358        }
2359    };
2360
2361    // Chunked-parallel serialization: for a large frame, format contiguous row
2362    // ranges into per-thread buffers and concatenate them IN ORDER onto `out`
2363    // (which already holds the header). ryu float formatting is CPU-bound and the
2364    // rows are independent, so this scales with available cores; bit-identical to
2365    // the serial `write_range(0, n)` since chunk boundaries don't affect row bytes.
2366    const CSV_PAR_MIN_ROWS: usize = 50_000;
2367    const CSV_PAR_MIN_ROWS_PER_WORKER: usize = 16_384;
2368    let workers = if n >= CSV_PAR_MIN_ROWS {
2369        std::thread::available_parallelism()
2370            .map_or(1, std::num::NonZeroUsize::get)
2371            .min(16)
2372            .min(n / CSV_PAR_MIN_ROWS_PER_WORKER)
2373            .max(1)
2374    } else {
2375        1
2376    };
2377    if workers >= 2 {
2378        let chunk = n.div_ceil(workers);
2379        let write_range = &write_range;
2380        let parts: Vec<String> = std::thread::scope(|scope| {
2381            let mut handles = Vec::with_capacity(workers);
2382            let mut start = 0;
2383            while start < n {
2384                let end = (start + chunk).min(n);
2385                handles.push(scope.spawn(move || {
2386                    let mut buf = String::with_capacity(
2387                        (end - start).saturating_mul(field_count).saturating_mul(8) + 16,
2388                    );
2389                    write_range(start, end, &mut buf);
2390                    buf
2391                }));
2392                start = end;
2393            }
2394            handles
2395                .into_iter()
2396                .map(|h| h.join().expect("csv writer thread"))
2397                .collect()
2398        });
2399        for p in parts {
2400            out.push_str(&p);
2401        }
2402    } else {
2403        write_range(0, n, &mut out);
2404    }
2405    Some(out)
2406}
2407
2408pub fn write_csv_string_with_options(
2409    frame: &DataFrame,
2410    options: &CsvWriteOptions,
2411) -> Result<String, IoError> {
2412    if options.include_index && frame.row_multiindex().is_some() {
2413        let materialized = materialize_named_row_multiindex_columns(frame)?;
2414        let mut nested_options = options.clone();
2415        nested_options.include_index = false;
2416        nested_options.index_label = None;
2417        return write_csv_string_with_options(&materialized, &nested_options);
2418    }
2419
2420    // Typed fast path (br-frankenpandas-qk2i9): when every column is an all-valid
2421    // Int64/Float64 typed slice or all-valid contiguous Utf8 (and the index is
2422    // not written), format the cells straight from the contiguous typed buffers,
2423    // skipping the per-column `Vec<Scalar>` materialization + per-cell `String` +
2424    // `csv` record machinery. Byte-for-byte identical to the general writer:
2425    // floats via write_pandas_float (= scalar_to_csv_with_na), Int64 Display
2426    // (= scalar_to_csv), Utf8 QUOTE_MINIMAL with doubled quotes, terminator `\n`,
2427    // and only taken when header names need no quoting.
2428    if let Some(out) = try_write_csv_typed(frame, options) {
2429        return Ok(out);
2430    }
2431
2432    let mut writer = WriterBuilder::new()
2433        .delimiter(options.delimiter)
2434        .from_writer(Vec::new());
2435
2436    let headers = frame
2437        .column_names()
2438        .into_iter()
2439        .cloned()
2440        .collect::<Vec<_>>();
2441    if options.header {
2442        let mut header_row =
2443            Vec::with_capacity(headers.len() + if options.include_index { 1 } else { 0 });
2444        if options.include_index {
2445            header_row.push(resolve_csv_index_header(frame, options));
2446        }
2447        header_row.extend(headers.iter().cloned());
2448        writer.write_record(&header_row)?;
2449    }
2450
2451    // Pre-compute each datetime column's column-uniform to_csv format (pandas
2452    // renders a datetime column with one date-only/seconds/sub-second form).
2453    let dt_formats: Vec<Option<DatetimeCsvFormat>> = headers
2454        .iter()
2455        .map(|name| {
2456            frame.column(name).and_then(|column| {
2457                (column.dtype() == DType::Datetime64).then(|| datetime_csv_format(column))
2458            })
2459        })
2460        .collect();
2461    // A DatetimeIndex follows the same column-uniform rule when written.
2462    let index_dt_format = if options.include_index {
2463        index_datetime_csv_format(frame)
2464    } else {
2465        None
2466    };
2467
2468    for row_idx in 0..frame.index().len() {
2469        let mut row = Vec::with_capacity(headers.len() + if options.include_index { 1 } else { 0 });
2470        if options.include_index {
2471            row.push(index_label_csv_string(frame, row_idx, index_dt_format)?);
2472        }
2473        row.extend(headers.iter().enumerate().map(|(col_idx, name)| {
2474            let value = frame.column(name).and_then(|column| column.value(row_idx));
2475            match value {
2476                Some(scalar) => scalar_to_csv_cell(scalar, &options.na_rep, dt_formats[col_idx]),
2477                None => options.na_rep.clone(),
2478            }
2479        }));
2480        writer.write_record(&row)?;
2481    }
2482
2483    let bytes = writer.into_inner().map_err(|err| err.into_error())?;
2484    Ok(String::from_utf8(bytes)?)
2485}
2486
2487/// Serialize a DataFrame to a GitHub-style Markdown table.
2488///
2489/// This covers pandas' pure formatter path without taking a dependency on
2490/// Python's optional `tabulate` package.
2491pub fn write_markdown_string_with_options(
2492    frame: &DataFrame,
2493    options: &MarkdownWriteOptions,
2494) -> Result<String, IoError> {
2495    if options.include_index && frame.row_multiindex().is_some() {
2496        let materialized = materialize_named_row_multiindex_columns(frame)?;
2497        let mut nested_options = options.clone();
2498        nested_options.include_index = false;
2499        nested_options.index_label = None;
2500        return write_markdown_string_with_options(&materialized, &nested_options);
2501    }
2502
2503    let headers = frame
2504        .column_names()
2505        .into_iter()
2506        .cloned()
2507        .collect::<Vec<_>>();
2508    let table_width = headers.len() + usize::from(options.include_index);
2509    let mut out = String::new();
2510
2511    let mut header_row = Vec::with_capacity(table_width);
2512    if options.include_index {
2513        header_row.push(resolve_table_index_header(
2514            frame,
2515            options.index_label.as_deref(),
2516        ));
2517    }
2518    header_row.extend(headers.iter().cloned());
2519    push_markdown_row(&mut out, &header_row);
2520
2521    let separator = vec!["---".to_owned(); table_width];
2522    push_markdown_row(&mut out, &separator);
2523
2524    for row_idx in 0..frame.index().len() {
2525        let mut row = Vec::with_capacity(table_width);
2526        if options.include_index {
2527            row.push(index_label_string(frame, row_idx)?);
2528        }
2529        row.extend(headers.iter().map(|name| {
2530            let value = frame.column(name).and_then(|column| column.value(row_idx));
2531            match value {
2532                Some(scalar) => scalar_to_table_with_na(scalar, &options.na_rep),
2533                None => options.na_rep.clone(),
2534            }
2535        }));
2536        push_markdown_row(&mut out, &row);
2537    }
2538
2539    Ok(out)
2540}
2541
2542/// Serialize a DataFrame to a booktabs-compatible LaTeX tabular block.
2543pub fn write_latex_string_with_options(
2544    frame: &DataFrame,
2545    options: &LatexWriteOptions,
2546) -> Result<String, IoError> {
2547    if options.include_index && frame.row_multiindex().is_some() {
2548        let materialized = materialize_named_row_multiindex_columns(frame)?;
2549        let mut nested_options = options.clone();
2550        nested_options.include_index = false;
2551        nested_options.index_label = None;
2552        return write_latex_string_with_options(&materialized, &nested_options);
2553    }
2554
2555    let headers = frame
2556        .column_names()
2557        .into_iter()
2558        .cloned()
2559        .collect::<Vec<_>>();
2560    let table_width = headers.len() + usize::from(options.include_index);
2561    let mut out = String::new();
2562
2563    out.push_str("\\begin{tabular}{");
2564    out.push_str(&"l".repeat(table_width));
2565    out.push_str("}\n\\toprule\n");
2566
2567    let mut header_row = Vec::with_capacity(table_width);
2568    if options.include_index {
2569        header_row.push(String::new());
2570    }
2571    header_row.extend(headers.iter().cloned());
2572    push_latex_row(&mut out, &header_row, options.escape);
2573
2574    if options.include_index {
2575        let index_name = resolve_table_index_header(frame, options.index_label.as_deref());
2576        if !index_name.is_empty() {
2577            let mut index_name_row = Vec::with_capacity(table_width);
2578            index_name_row.push(index_name);
2579            index_name_row.extend(std::iter::repeat_n(String::new(), headers.len()));
2580            push_latex_row(&mut out, &index_name_row, options.escape);
2581        }
2582    }
2583
2584    out.push_str("\\midrule\n");
2585
2586    for row_idx in 0..frame.index().len() {
2587        let mut row = Vec::with_capacity(table_width);
2588        if options.include_index {
2589            row.push(index_label_string(frame, row_idx)?);
2590        }
2591        row.extend(headers.iter().map(|name| {
2592            let value = frame.column(name).and_then(|column| column.value(row_idx));
2593            match value {
2594                Some(scalar) => scalar_to_latex_cell(scalar, &options.na_rep),
2595                None => options.na_rep.clone(),
2596            }
2597        }));
2598        push_latex_row(&mut out, &row, options.escape);
2599    }
2600
2601    out.push_str("\\bottomrule\n\\end{tabular}\n");
2602    Ok(out)
2603}
2604
2605/// Serialize a DataFrame to an HTML table string.
2606pub fn write_html_string_with_options(
2607    frame: &DataFrame,
2608    options: &HtmlWriteOptions,
2609) -> Result<String, IoError> {
2610    if options.include_index && frame.row_multiindex().is_some() {
2611        let materialized = materialize_named_row_multiindex_columns(frame)?;
2612        let nested_options = HtmlWriteOptions {
2613            include_index: false,
2614            ..options.clone()
2615        };
2616        return write_html_string_with_options(&materialized, &nested_options);
2617    }
2618
2619    write_html_table_string(frame, options)
2620}
2621
2622fn write_html_table_string(
2623    frame: &DataFrame,
2624    options: &HtmlWriteOptions,
2625) -> Result<String, IoError> {
2626    let column_names = frame.column_names();
2627    let columns = column_names
2628        .iter()
2629        .map(|name| frame.column(name))
2630        .collect::<Vec<_>>();
2631    let mut out = String::new();
2632    push_html_table_open(&mut out, options);
2633    out.push_str("  <thead>\n    <tr style=\"text-align: ");
2634    out.push_str(&escape_html_attr(
2635        options.justify.as_deref().unwrap_or("right"),
2636    ));
2637    out.push_str(";\">\n");
2638
2639    if options.include_index {
2640        out.push_str("      <th></th>\n");
2641    }
2642    for name in &column_names {
2643        out.push_str("      <th>");
2644        out.push_str(&html_text(name, options.escape));
2645        out.push_str("</th>\n");
2646    }
2647    out.push_str("    </tr>\n  </thead>\n  <tbody>\n");
2648
2649    for row_idx in 0..frame.index().len() {
2650        out.push_str("    <tr>\n");
2651        if options.include_index {
2652            out.push_str("      <th>");
2653            out.push_str(&html_index_label_string(frame, row_idx, options.escape)?);
2654            out.push_str("</th>\n");
2655        }
2656        for column in &columns {
2657            let value = (*column).and_then(|column| column.value(row_idx));
2658            out.push_str("      <td>");
2659            match value {
2660                Some(scalar) => out.push_str(&html_scalar_string(scalar, options)),
2661                None => out.push_str(&html_text(&options.na_rep, options.escape)),
2662            }
2663            out.push_str("</td>\n");
2664        }
2665        out.push_str("    </tr>\n");
2666    }
2667
2668    out.push_str("  </tbody>\n</table>");
2669    Ok(out)
2670}
2671
2672fn push_html_table_open(out: &mut String, options: &HtmlWriteOptions) {
2673    out.push_str("<table");
2674    if let Some(border) = options.border.filter(|border| *border > 0) {
2675        out.push_str(" border=\"");
2676        out.push_str(&border.to_string());
2677        out.push('"');
2678    }
2679    out.push_str(" class=\"");
2680    out.push_str(&html_class_attr(&options.classes));
2681    out.push('"');
2682    if let Some(table_id) = options
2683        .table_id
2684        .as_deref()
2685        .map(str::trim)
2686        .filter(|table_id| !table_id.is_empty())
2687    {
2688        out.push_str(" id=\"");
2689        out.push_str(&escape_html_attr(table_id));
2690        out.push('"');
2691    }
2692    out.push_str(">\n");
2693}
2694
2695fn html_class_attr(classes: &[String]) -> String {
2696    std::iter::once("dataframe".to_owned())
2697        .chain(
2698            classes
2699                .iter()
2700                .flat_map(|class| class.split_whitespace())
2701                .filter(|class| !class.is_empty())
2702                .map(escape_html_attr),
2703        )
2704        .collect::<Vec<_>>()
2705        .join(" ")
2706}
2707
2708fn html_index_label_string(
2709    frame: &DataFrame,
2710    row_idx: usize,
2711    escape: bool,
2712) -> Result<String, IoError> {
2713    let label = frame
2714        .index()
2715        .labels()
2716        .get(row_idx)
2717        .ok_or_else(|| IoError::Html(format!("missing index label at row {row_idx}")))?;
2718    let raw = match label {
2719        IndexLabel::Int64(v) => v.to_string(),
2720        IndexLabel::Utf8(s) => s.clone(),
2721        IndexLabel::Timedelta64(ns) => Timedelta::format(*ns),
2722        IndexLabel::Datetime64(ns) => format_datetime_ns(*ns),
2723        f @ (IndexLabel::Float64(_) | IndexLabel::Bool(_)) => f.to_string(),
2724        IndexLabel::Null(_) => label.to_string(),
2725    };
2726    Ok(html_text(&raw, escape))
2727}
2728
2729fn html_scalar_string(scalar: &Scalar, options: &HtmlWriteOptions) -> String {
2730    match scalar {
2731        Scalar::Null(_) => html_text(&options.na_rep, options.escape),
2732        Scalar::Bool(value) => html_text(if *value { "True" } else { "False" }, options.escape),
2733        Scalar::Int64(value) => value.to_string(),
2734        Scalar::Float64(value) => {
2735            if value.is_nan() {
2736                html_text(&options.na_rep, options.escape)
2737            } else if value.fract() == 0.0 {
2738                format!("{value:.1}")
2739            } else {
2740                value.to_string()
2741            }
2742        }
2743        Scalar::Utf8(value) => {
2744            if options.render_links && is_html_renderable_link(value) {
2745                let label = html_text(value, options.escape);
2746                format!(
2747                    "<a href=\"{}\" target=\"_blank\">{label}</a>",
2748                    escape_html_attr(value)
2749                )
2750            } else {
2751                html_text(value, options.escape)
2752            }
2753        }
2754        // pandas to_html renders a temporal NaT as the literal "NaT" (na_rep
2755        // overrides only float NaN); verified vs pandas 2.2.3. (tblnat)
2756        Scalar::Timedelta64(value) => {
2757            if *value == Timedelta::NAT {
2758                html_text("NaT", options.escape)
2759            } else {
2760                html_text(&Timedelta::format(*value), options.escape)
2761            }
2762        }
2763        Scalar::Datetime64(value) => {
2764            if *value == Timestamp::NAT {
2765                html_text("NaT", options.escape)
2766            } else {
2767                html_text(&format_datetime_ns(*value), options.escape)
2768            }
2769        }
2770        Scalar::Period(value) => {
2771            if value.ordinal == i64::MIN {
2772                html_text("NaT", options.escape)
2773            } else {
2774                html_text(&value.calendar_string(), options.escape)
2775            }
2776        }
2777        Scalar::Interval(iv) => html_text(&format!("{iv}"), options.escape),
2778    }
2779}
2780
2781fn html_text(value: &str, escape: bool) -> String {
2782    if escape {
2783        escape_html_text(value)
2784    } else {
2785        value.to_owned()
2786    }
2787}
2788
2789fn is_html_renderable_link(value: &str) -> bool {
2790    value.starts_with("http://") || value.starts_with("https://") || value.starts_with("ftp://")
2791}
2792
2793fn escape_html_text(value: &str) -> String {
2794    let mut escaped = String::with_capacity(value.len());
2795    for ch in value.chars() {
2796        match ch {
2797            '&' => escaped.push_str("&amp;"),
2798            '<' => escaped.push_str("&lt;"),
2799            '>' => escaped.push_str("&gt;"),
2800            _ => escaped.push(ch),
2801        }
2802    }
2803    escaped
2804}
2805
2806fn escape_html_attr(value: &str) -> String {
2807    let mut escaped = String::with_capacity(value.len());
2808    for ch in value.chars() {
2809        match ch {
2810            '&' => escaped.push_str("&amp;"),
2811            '"' => escaped.push_str("&quot;"),
2812            '<' => escaped.push_str("&lt;"),
2813            '>' => escaped.push_str("&gt;"),
2814            _ => escaped.push(ch),
2815        }
2816    }
2817    escaped
2818}
2819
2820/// Parse a DataFrame from the first HTML table in a document string.
2821///
2822/// This is the local, table-oriented subset of pandas `read_html`: it parses
2823/// static HTML with an HTML5 parser, uses the first `<thead><tr>` as headers
2824/// when present, otherwise uses the first row with header cells, and fills
2825/// short body rows with nulls.
2826pub fn read_html_str(input: &str) -> Result<DataFrame, IoError> {
2827    read_html_str_with_options(input, &HtmlReadOptions::default())
2828}
2829
2830/// Parse a DataFrame from an HTML document string with options.
2831pub fn read_html_str_with_options(
2832    input: &str,
2833    options: &HtmlReadOptions,
2834) -> Result<DataFrame, IoError> {
2835    let document = Html::parse_document(input);
2836    let table_selector = html_selector("table")?;
2837    let row_selector = html_selector("tr")?;
2838    let thead_row_selector = html_selector("thead tr")?;
2839    let tbody_row_selector = html_selector("tbody tr")?;
2840    let cell_selector = html_selector("th, td")?;
2841    let th_selector = html_selector("th")?;
2842
2843    let table = document
2844        .select(&table_selector)
2845        .nth(options.table_index)
2846        .ok_or_else(|| {
2847            IoError::Html(format!(
2848                "html input contains no table at index {}",
2849                options.table_index
2850            ))
2851        })?;
2852
2853    let header_rows = table
2854        .select(&thead_row_selector)
2855        .map(|row| html_row_cells(row, &cell_selector))
2856        .filter(|cells| !cells.is_empty())
2857        .collect::<Vec<_>>();
2858    let body_rows = table
2859        .select(&tbody_row_selector)
2860        .map(|row| html_row_cells(row, &cell_selector))
2861        .filter(|cells| !cells.is_empty())
2862        .collect::<Vec<_>>();
2863
2864    if let Some(header_cells) = header_rows.first() {
2865        let headers = normalize_html_headers(header_cells)?;
2866        return html_rows_to_frame(headers, body_rows);
2867    }
2868
2869    let all_rows = table
2870        .select(&row_selector)
2871        .map(|row| {
2872            let has_header_cell = row.select(&th_selector).next().is_some();
2873            (has_header_cell, html_row_cells(row, &cell_selector))
2874        })
2875        .filter(|(_, cells)| !cells.is_empty())
2876        .collect::<Vec<_>>();
2877    if all_rows.is_empty() {
2878        return Err(IoError::Html(
2879            "html table contains no rows with cells".to_owned(),
2880        ));
2881    }
2882
2883    let mut all_rows = all_rows.into_iter();
2884    let (first_has_header, first_cells) = all_rows
2885        .next()
2886        .ok_or_else(|| IoError::Html("html table contains no rows with cells".to_owned()))?;
2887
2888    if first_has_header {
2889        let headers = normalize_html_headers(&first_cells)?;
2890        let data_rows = all_rows.map(|(_, cells)| cells).collect::<Vec<_>>();
2891        html_rows_to_frame(headers, data_rows)
2892    } else {
2893        let mut data_rows = vec![first_cells];
2894        data_rows.extend(all_rows.map(|(_, cells)| cells));
2895        let width = data_rows.iter().map(Vec::len).max().unwrap_or(0);
2896        if width == 0 {
2897            return Err(IoError::Html("html table contains no cells".to_owned()));
2898        }
2899        let headers = (0..width).map(|idx| idx.to_string()).collect::<Vec<_>>();
2900        html_rows_to_frame(headers, data_rows)
2901    }
2902}
2903
2904const PICKLE_FORMAT_KEY: &str = "__frankenpandas_pickle_format";
2905const PICKLE_FORMAT_VERSION: &str = "frankenpandas.dataframe.v1";
2906const PICKLE_ORIENT_KEY: &str = "orient";
2907const PICKLE_PAYLOAD_KEY: &str = "payload";
2908
2909/// Serialize a DataFrame to Pickle bytes.
2910///
2911/// This emits a fail-closed FrankenPandas envelope containing the existing
2912/// split-orient DataFrame representation. It is intentionally narrower than
2913/// pandas' arbitrary Python-object pickle support.
2914pub fn write_pickle_bytes_with_options(
2915    frame: &DataFrame,
2916    options: &PickleWriteOptions,
2917) -> Result<Vec<u8>, IoError> {
2918    let split_json = write_json_string(frame, JsonOrient::Split)?;
2919    let split_value = serde_json::from_str::<serde_json::Value>(&split_json)?;
2920    let mut envelope = serde_json::Map::new();
2921    envelope.insert(
2922        PICKLE_FORMAT_KEY.to_owned(),
2923        serde_json::Value::String(PICKLE_FORMAT_VERSION.to_owned()),
2924    );
2925    envelope.insert(
2926        PICKLE_ORIENT_KEY.to_owned(),
2927        serde_json::Value::String("split".to_owned()),
2928    );
2929    envelope.insert(PICKLE_PAYLOAD_KEY.to_owned(), split_value);
2930
2931    serde_pickle::to_vec(
2932        &serde_json::Value::Object(envelope),
2933        pickle_ser_options(options),
2934    )
2935    .map_err(|err| IoError::Pickle(err.to_string()))
2936}
2937
2938/// Deserialize a DataFrame from Pickle bytes.
2939pub fn read_pickle_bytes(input: &[u8]) -> Result<DataFrame, IoError> {
2940    read_pickle_bytes_with_options(input, &PickleReadOptions::default())
2941}
2942
2943/// Deserialize a DataFrame from Pickle bytes with options.
2944///
2945/// Only the versioned FrankenPandas envelope is accepted. Foreign Python
2946/// pickles fail closed with [`IoError::Pickle`].
2947pub fn read_pickle_bytes_with_options(
2948    input: &[u8],
2949    options: &PickleReadOptions,
2950) -> Result<DataFrame, IoError> {
2951    let value = serde_pickle::from_slice::<serde_json::Value>(input, pickle_de_options(options))
2952        .map_err(|err| IoError::Pickle(err.to_string()))?;
2953    let envelope = value
2954        .as_object()
2955        .ok_or_else(|| IoError::Pickle("pickle payload must be an object".to_owned()))?;
2956
2957    match envelope
2958        .get(PICKLE_FORMAT_KEY)
2959        .and_then(|value| value.as_str())
2960    {
2961        Some(PICKLE_FORMAT_VERSION) => {}
2962        Some(other) => {
2963            return Err(IoError::Pickle(format!(
2964                "unsupported FrankenPandas pickle format '{other}'"
2965            )));
2966        }
2967        None => {
2968            return Err(IoError::Pickle(
2969                "pickle payload is missing FrankenPandas format marker".to_owned(),
2970            ));
2971        }
2972    }
2973
2974    match envelope
2975        .get(PICKLE_ORIENT_KEY)
2976        .and_then(|value| value.as_str())
2977    {
2978        Some("split") => {}
2979        Some(other) => {
2980            return Err(IoError::Pickle(format!(
2981                "unsupported FrankenPandas pickle orient '{other}'"
2982            )));
2983        }
2984        None => {
2985            return Err(IoError::Pickle(
2986                "pickle payload is missing orient".to_owned(),
2987            ));
2988        }
2989    }
2990
2991    let payload = envelope
2992        .get(PICKLE_PAYLOAD_KEY)
2993        .ok_or_else(|| IoError::Pickle("pickle payload is missing data".to_owned()))?;
2994    let payload_json = serde_json::to_string(payload)?;
2995    read_json_str(&payload_json, JsonOrient::Split)
2996}
2997
2998fn pickle_ser_options(options: &PickleWriteOptions) -> serde_pickle::SerOptions {
2999    match options.protocol {
3000        PickleProtocol::V2 => serde_pickle::SerOptions::new().proto_v2(),
3001        PickleProtocol::V3 => serde_pickle::SerOptions::new(),
3002    }
3003}
3004
3005fn pickle_de_options(options: &PickleReadOptions) -> serde_pickle::DeOptions {
3006    let de_options = serde_pickle::DeOptions::new();
3007    if options.decode_legacy_strings {
3008        de_options.decode_strings()
3009    } else {
3010        de_options
3011    }
3012}
3013
3014#[derive(Debug, Clone)]
3015struct StataField {
3016    variable_name: String,
3017    source: StataFieldSource,
3018    variable_type: VariableType,
3019}
3020
3021#[derive(Debug, Clone)]
3022enum StataFieldSource {
3023    Index,
3024    Column(String),
3025}
3026
3027/// Serialize a DataFrame to Stata DTA bytes.
3028///
3029/// This first slice targets DTA release 118 and a DataFrame-oriented subset:
3030/// integer/bool, float, fixed string, and missing values.
3031pub fn write_stata_bytes_with_options(
3032    frame: &DataFrame,
3033    options: &StataWriteOptions,
3034) -> Result<Vec<u8>, IoError> {
3035    let fields = stata_fields_for_frame(frame, options)?;
3036    let header = Header::builder(Release::V118, ByteOrder::LittleEndian).build();
3037    let mut schema = StataSchema::builder();
3038    for field in &fields {
3039        let format = stata_format_for_type(field.variable_type);
3040        schema = schema.add_variable(
3041            Variable::builder(field.variable_type, &field.variable_name).format(format),
3042        );
3043    }
3044    let schema = schema.build().map_err(stata_error)?;
3045
3046    let mut record_writer = DtaWriter::new()
3047        .from_writer(Cursor::new(Vec::<u8>::new()))
3048        .write_header(header)
3049        .map_err(stata_error)?
3050        .write_schema(schema)
3051        .map_err(stata_error)?
3052        .into_record_writer()
3053        .map_err(stata_error)?;
3054
3055    for row_idx in 0..frame.index().len() {
3056        let mut record = Vec::with_capacity(fields.len());
3057        for field in &fields {
3058            record.push(stata_value_for_field(frame, row_idx, field)?);
3059        }
3060        record_writer.write_record(&record).map_err(stata_error)?;
3061    }
3062
3063    Ok(record_writer
3064        .into_long_string_writer()
3065        .map_err(stata_error)?
3066        .into_value_label_writer()
3067        .map_err(stata_error)?
3068        .finish()
3069        .map_err(stata_error)?
3070        .into_inner())
3071}
3072
3073/// Read a DataFrame from Stata DTA bytes.
3074pub fn read_stata_bytes(input: &[u8]) -> Result<DataFrame, IoError> {
3075    let mut characteristic_reader = DtaReader::new()
3076        .from_reader(Cursor::new(input))
3077        .read_header()
3078        .map_err(stata_error)?
3079        .read_schema()
3080        .map_err(stata_error)?;
3081    characteristic_reader.skip_to_end().map_err(stata_error)?;
3082
3083    let mut record_reader = characteristic_reader
3084        .into_record_reader()
3085        .map_err(stata_error)?;
3086    let column_order = record_reader
3087        .schema()
3088        .variables()
3089        .iter()
3090        .map(|variable| variable.name().to_owned())
3091        .collect::<Vec<_>>();
3092    reject_duplicate_headers(&column_order)?;
3093
3094    let mut columns = column_order
3095        .iter()
3096        .cloned()
3097        .map(|name| (name, Vec::new()))
3098        .collect::<BTreeMap<_, _>>();
3099    let mut row_count: i64 = 0;
3100    while let Some(record) = record_reader.read_record().map_err(stata_error)? {
3101        for (name, value) in column_order.iter().zip(record.values()) {
3102            columns
3103                .get_mut(name)
3104                .ok_or_else(|| IoError::Stata(format!("missing Stata column '{name}'")))?
3105                .push(stata_value_to_scalar(value)?);
3106        }
3107        row_count = row_count
3108            .checked_add(1)
3109            .ok_or_else(|| IoError::Stata("Stata row count exceeded i64 range".to_owned()))?;
3110    }
3111
3112    let mut out = BTreeMap::new();
3113    for name in &column_order {
3114        let values = columns
3115            .remove(name)
3116            .ok_or_else(|| IoError::Stata(format!("missing Stata column '{name}'")))?;
3117        out.insert(name.clone(), Column::from_values(values)?);
3118    }
3119    Ok(DataFrame::new_with_column_order(
3120        Index::from_i64((0..row_count).collect()),
3121        out,
3122        column_order,
3123    )?)
3124}
3125
3126fn stata_fields_for_frame(
3127    frame: &DataFrame,
3128    options: &StataWriteOptions,
3129) -> Result<Vec<StataField>, IoError> {
3130    let mut fields = Vec::new();
3131    if options.include_index {
3132        let name = options
3133            .index_label
3134            .clone()
3135            .unwrap_or_else(|| "index".to_owned());
3136        validate_stata_variable_name(&name)?;
3137        fields.push(StataField {
3138            variable_name: name,
3139            source: StataFieldSource::Index,
3140            variable_type: stata_index_variable_type(frame)?,
3141        });
3142    }
3143
3144    for name in frame.column_names() {
3145        validate_stata_variable_name(name)?;
3146        let column = frame
3147            .column(name)
3148            .ok_or_else(|| IoError::Stata(format!("missing DataFrame column '{name}'")))?;
3149        fields.push(StataField {
3150            variable_name: name.clone(),
3151            source: StataFieldSource::Column(name.clone()),
3152            variable_type: infer_stata_variable_type(column, name)?,
3153        });
3154    }
3155
3156    let mut seen = BTreeSet::new();
3157    for field in &fields {
3158        if !seen.insert(field.variable_name.clone()) {
3159            return Err(IoError::DuplicateColumnName(field.variable_name.clone()));
3160        }
3161    }
3162    Ok(fields)
3163}
3164
3165fn validate_stata_variable_name(name: &str) -> Result<(), IoError> {
3166    if name.is_empty() {
3167        return Err(IoError::Stata(
3168            "Stata variable name cannot be empty".to_owned(),
3169        ));
3170    }
3171    if name.len() > 32 {
3172        return Err(IoError::Stata(format!(
3173            "Stata variable name '{name}' exceeds 32 bytes"
3174        )));
3175    }
3176    let mut chars = name.chars();
3177    let first = chars
3178        .next()
3179        .ok_or_else(|| IoError::Stata("Stata variable name cannot be empty".to_owned()))?;
3180    if !(first == '_' || first.is_ascii_alphabetic()) {
3181        return Err(IoError::Stata(format!(
3182            "invalid Stata variable name '{name}': first character must be ASCII letter or '_'"
3183        )));
3184    }
3185    if !chars.all(|ch| ch == '_' || ch.is_ascii_alphanumeric()) {
3186        return Err(IoError::Stata(format!(
3187            "invalid Stata variable name '{name}': only ASCII letters, digits, and '_' are supported"
3188        )));
3189    }
3190    Ok(())
3191}
3192
3193fn stata_index_variable_type(frame: &DataFrame) -> Result<VariableType, IoError> {
3194    let max_len = frame
3195        .index()
3196        .labels()
3197        .iter()
3198        .map(|label| label.to_string().len())
3199        .max()
3200        .unwrap_or(1)
3201        .max(1);
3202    stata_fixed_string_type(max_len, "index")
3203}
3204
3205fn infer_stata_variable_type(column: &Column, name: &str) -> Result<VariableType, IoError> {
3206    let mut saw_numeric = false;
3207    let mut saw_float = false;
3208    let mut saw_string = false;
3209    let mut max_string_len = 1usize;
3210
3211    for value in column.values() {
3212        match value {
3213            Scalar::Null(_) => {}
3214            Scalar::Bool(_) => {
3215                saw_numeric = true;
3216            }
3217            Scalar::Int64(v) => {
3218                saw_numeric = true;
3219                if i32::try_from(*v).is_err() {
3220                    return Err(IoError::Stata(format!(
3221                        "Stata long column '{name}' cannot encode i64 value {v}"
3222                    )));
3223                }
3224            }
3225            Scalar::Float64(v) => {
3226                if !v.is_nan() {
3227                    saw_numeric = true;
3228                    saw_float = true;
3229                }
3230            }
3231            Scalar::Utf8(text) => {
3232                saw_string = true;
3233                max_string_len = max_string_len.max(text.len());
3234            }
3235            other => {
3236                saw_string = true;
3237                max_string_len = max_string_len.max(scalar_to_table_with_na(other, "").len());
3238            }
3239        }
3240    }
3241
3242    if saw_string {
3243        stata_fixed_string_type(max_string_len, name)
3244    } else if saw_numeric && !saw_float {
3245        Ok(VariableType::Long)
3246    } else {
3247        Ok(VariableType::Double)
3248    }
3249}
3250
3251fn stata_fixed_string_type(len: usize, name: &str) -> Result<VariableType, IoError> {
3252    let width = len.max(1);
3253    let width = u16::try_from(width).map_err(|_| {
3254        IoError::Stata(format!(
3255            "Stata string column '{name}' exceeds fixed string capacity"
3256        ))
3257    })?;
3258    if width > 2045 {
3259        return Err(IoError::Stata(format!(
3260            "Stata string column '{name}' requires strL; this slice supports fixed strings only"
3261        )));
3262    }
3263    Ok(VariableType::FixedString(width))
3264}
3265
3266fn stata_format_for_type(variable_type: VariableType) -> &'static str {
3267    match variable_type {
3268        VariableType::Byte | VariableType::Int | VariableType::Long => "%12.0g",
3269        VariableType::Float | VariableType::Double => "%10.0g",
3270        VariableType::FixedString(_) | VariableType::LongString => "%9s",
3271    }
3272}
3273
3274fn stata_value_for_field(
3275    frame: &DataFrame,
3276    row_idx: usize,
3277    field: &StataField,
3278) -> Result<StataValue<'static>, IoError> {
3279    match field.source {
3280        StataFieldSource::Index => Ok(StataValue::String(std::borrow::Cow::Owned(
3281            index_label_string(frame, row_idx)?,
3282        ))),
3283        StataFieldSource::Column(ref name) => {
3284            let value = frame.column(name).and_then(|column| column.value(row_idx));
3285            scalar_to_stata_value(value, field.variable_type, name)
3286        }
3287    }
3288}
3289
3290fn scalar_to_stata_value(
3291    value: Option<&Scalar>,
3292    variable_type: VariableType,
3293    name: &str,
3294) -> Result<StataValue<'static>, IoError> {
3295    match variable_type {
3296        VariableType::Long => match value {
3297            Some(Scalar::Bool(v)) => Ok(StataValue::Long(StataLong::Present(i32::from(*v)))),
3298            Some(Scalar::Int64(v)) => Ok(StataValue::Long(StataLong::Present(
3299                i32::try_from(*v).map_err(|_| {
3300                    IoError::Stata(format!("Stata long column '{name}' cannot encode {v}"))
3301                })?,
3302            ))),
3303            Some(Scalar::Null(_)) | None => {
3304                Ok(StataValue::Long(StataLong::Missing(MissingValue::System)))
3305            }
3306            Some(other) => Err(IoError::Stata(format!(
3307                "Stata long column '{name}' cannot encode {other:?}"
3308            ))),
3309        },
3310        VariableType::Double => match value {
3311            Some(Scalar::Bool(v)) => Ok(StataValue::Double(StataDouble::Present(if *v {
3312                1.0
3313            } else {
3314                0.0
3315            }))),
3316            Some(Scalar::Int64(v)) => Ok(StataValue::Double(StataDouble::Present(*v as f64))),
3317            Some(Scalar::Float64(v)) if v.is_nan() => Ok(StataValue::Double(StataDouble::Missing(
3318                MissingValue::System,
3319            ))),
3320            Some(Scalar::Float64(v)) => Ok(StataValue::Double(StataDouble::Present(*v))),
3321            Some(Scalar::Null(_)) | None => Ok(StataValue::Double(StataDouble::Missing(
3322                MissingValue::System,
3323            ))),
3324            Some(other) => Err(IoError::Stata(format!(
3325                "Stata double column '{name}' cannot encode {other:?}"
3326            ))),
3327        },
3328        VariableType::FixedString(_) => {
3329            let text = match value {
3330                Some(Scalar::Null(_)) | None => String::new(),
3331                Some(scalar) => scalar_to_table_with_na(scalar, ""),
3332            };
3333            Ok(StataValue::String(std::borrow::Cow::Owned(text)))
3334        }
3335        VariableType::Byte | VariableType::Int | VariableType::Float | VariableType::LongString => {
3336            Err(IoError::Stata(format!(
3337                "unsupported Stata variable type for column '{name}': {variable_type:?}"
3338            )))
3339        }
3340    }
3341}
3342
3343fn stata_value_to_scalar(value: &StataValue<'_>) -> Result<Scalar, IoError> {
3344    match value {
3345        StataValue::Byte(v) => Ok(v
3346            .present()
3347            .map(|value| Scalar::Int64(i64::from(value)))
3348            .unwrap_or(Scalar::Null(NullKind::NaN))),
3349        StataValue::Int(v) => Ok(v
3350            .present()
3351            .map(|value| Scalar::Int64(i64::from(value)))
3352            .unwrap_or(Scalar::Null(NullKind::NaN))),
3353        StataValue::Long(v) => Ok(v
3354            .present()
3355            .map(|value| Scalar::Int64(i64::from(value)))
3356            .unwrap_or(Scalar::Null(NullKind::NaN))),
3357        StataValue::Float(v) => Ok(v
3358            .present()
3359            .map(|value| Scalar::Float64(f64::from(value)))
3360            .unwrap_or(Scalar::Null(NullKind::NaN))),
3361        StataValue::Double(v) => Ok(v
3362            .present()
3363            .map(Scalar::Float64)
3364            .unwrap_or(Scalar::Null(NullKind::NaN))),
3365        StataValue::String(text) => Ok(Scalar::Utf8(text.to_string())),
3366        StataValue::LongStringRef(_) => Err(IoError::Stata(
3367            "Stata strL values are not supported by this reader slice".to_owned(),
3368        )),
3369    }
3370}
3371
3372fn stata_error<E: std::fmt::Display>(err: E) -> IoError {
3373    IoError::Stata(err.to_string())
3374}
3375
3376/// Parse a DataFrame from a row-oriented XML document string.
3377///
3378/// Matches the writer-oriented subset accepted by `pd.read_xml(...,
3379/// parser="etree")`: each row is an element named by
3380/// [`XmlReadOptions::row_name`], and each direct child element becomes a
3381/// DataFrame column. Attributes, XPath, namespaces, and nested field elements
3382/// are intentionally out of scope for this slice.
3383pub fn read_xml_str(input: &str) -> Result<DataFrame, IoError> {
3384    read_xml_str_with_options(input, &XmlReadOptions::default())
3385}
3386
3387/// Parse a DataFrame from a row-oriented XML document string with options.
3388pub fn read_xml_str_with_options(
3389    input: &str,
3390    options: &XmlReadOptions,
3391) -> Result<DataFrame, IoError> {
3392    validate_xml_element_name(&options.row_name)?;
3393
3394    let mut reader = XmlReader::from_str(input);
3395    reader.config_mut().trim_text(false);
3396    let mut buf = Vec::new();
3397    let mut rows: Vec<BTreeMap<String, Scalar>> = Vec::new();
3398    let mut column_order = Vec::new();
3399    let mut seen_columns = HashSet::new();
3400    let mut current_row: Option<BTreeMap<String, Scalar>> = None;
3401    let mut current_field: Option<String> = None;
3402    let mut field_text = String::new();
3403    let mut xml_version = XmlVersion::Implicit1_0;
3404
3405    loop {
3406        match reader
3407            .read_event_into(&mut buf)
3408            .map_err(|err| IoError::Xml(err.to_string()))?
3409        {
3410            Event::Start(event) => {
3411                let name = xml_event_name(event.name())?;
3412                if current_row.is_none() {
3413                    if name == options.row_name {
3414                        current_row = Some(BTreeMap::new());
3415                    }
3416                } else if let Some(field_name) = &current_field {
3417                    return Err(IoError::Xml(format!(
3418                        "nested xml element '{name}' inside field '{field_name}' is unsupported"
3419                    )));
3420                } else {
3421                    current_field = Some(name);
3422                    field_text.clear();
3423                }
3424            }
3425            Event::Empty(event) => {
3426                let name = xml_event_name(event.name())?;
3427                if let Some(field_name) = &current_field {
3428                    return Err(IoError::Xml(format!(
3429                        "nested xml element '{name}' inside field '{field_name}' is unsupported"
3430                    )));
3431                }
3432                if let Some(row) = current_row.as_mut() {
3433                    insert_xml_field(
3434                        row,
3435                        &mut column_order,
3436                        &mut seen_columns,
3437                        name,
3438                        Scalar::Null(NullKind::Null),
3439                    )?;
3440                } else if name == options.row_name {
3441                    rows.push(BTreeMap::new());
3442                }
3443            }
3444            Event::Text(event) => {
3445                if current_field.is_some() {
3446                    let decoded = event
3447                        .xml_content(xml_version)
3448                        .map_err(|err| IoError::Xml(err.to_string()))?;
3449                    field_text.push_str(&decoded);
3450                }
3451            }
3452            Event::CData(event) => {
3453                if current_field.is_some() {
3454                    let decoded = event
3455                        .xml_content(xml_version)
3456                        .map_err(|err| IoError::Xml(err.to_string()))?;
3457                    field_text.push_str(&decoded);
3458                }
3459            }
3460            Event::End(event) => {
3461                let name = xml_event_name(event.name())?;
3462                if let Some(field_name) = current_field.as_ref() {
3463                    if name != *field_name {
3464                        return Err(IoError::Xml(format!(
3465                            "xml field '{field_name}' closed by mismatched element '{name}'"
3466                        )));
3467                    }
3468                    let field_name = current_field.take().expect("field checked");
3469                    let value = parse_scalar(&field_text);
3470                    field_text.clear();
3471                    let row = current_row
3472                        .as_mut()
3473                        .ok_or_else(|| IoError::Xml("xml field outside row".to_owned()))?;
3474                    insert_xml_field(row, &mut column_order, &mut seen_columns, field_name, value)?;
3475                } else if name == options.row_name {
3476                    let row = current_row.take().ok_or_else(|| {
3477                        IoError::Xml("xml row closed before it opened".to_owned())
3478                    })?;
3479                    rows.push(row);
3480                }
3481            }
3482            Event::GeneralRef(reference) => {
3483                if current_field.is_some() {
3484                    field_text.push_str(&decode_xml_general_ref(reference)?);
3485                }
3486            }
3487            Event::Eof => break,
3488            Event::Decl(decl) => {
3489                if let Ok(v) = decl.version() {
3490                    xml_version = match v.as_ref() {
3491                        b"1.0" => XmlVersion::Explicit1_0,
3492                        b"1.1" => XmlVersion::Explicit1_1,
3493                        _ => xml_version,
3494                    };
3495                }
3496            }
3497            Event::PI(_) | Event::DocType(_) | Event::Comment(_) => {}
3498        }
3499        buf.clear();
3500    }
3501
3502    if current_field.is_some() || current_row.is_some() {
3503        return Err(IoError::Xml(
3504            "xml document ended inside an open row or field".to_owned(),
3505        ));
3506    }
3507    if rows.is_empty() {
3508        return Err(IoError::Xml(
3509            "xml input contains no row elements".to_owned(),
3510        ));
3511    }
3512
3513    let mut out_columns = BTreeMap::new();
3514    for name in &column_order {
3515        let values = rows
3516            .iter()
3517            .map(|row| {
3518                row.get(name)
3519                    .cloned()
3520                    .unwrap_or(Scalar::Null(NullKind::Null))
3521            })
3522            .collect::<Vec<_>>();
3523        out_columns.insert(name.clone(), Column::from_values(values)?);
3524    }
3525    let index = Index::from_i64((0..rows.len() as i64).collect());
3526    Ok(DataFrame::new_with_column_order(
3527        index,
3528        out_columns,
3529        column_order,
3530    )?)
3531}
3532
3533/// Serialize a DataFrame to an XML document string.
3534pub fn write_xml_string_with_options(
3535    frame: &DataFrame,
3536    options: &XmlWriteOptions,
3537) -> Result<String, IoError> {
3538    if options.include_index && frame.row_multiindex().is_some() {
3539        let materialized = materialize_named_row_multiindex_columns(frame)?;
3540        let mut nested_options = options.clone();
3541        nested_options.include_index = false;
3542        nested_options.index_label = None;
3543        return write_xml_string_with_options(&materialized, &nested_options);
3544    }
3545
3546    validate_xml_element_name(&options.root_name)?;
3547    validate_xml_element_name(&options.row_name)?;
3548
3549    let headers = frame
3550        .column_names()
3551        .into_iter()
3552        .cloned()
3553        .collect::<Vec<_>>();
3554    for name in &headers {
3555        validate_xml_element_name(name)?;
3556    }
3557
3558    let index_label = options
3559        .index_label
3560        .clone()
3561        .or_else(|| frame.index().name().map(ToOwned::to_owned))
3562        .unwrap_or_else(|| "index".to_owned());
3563    if options.include_index {
3564        validate_xml_element_name(&index_label)?;
3565    }
3566
3567    let mut out = String::new();
3568    out.push_str("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
3569    out.push('<');
3570    out.push_str(&options.root_name);
3571    out.push_str(">\n");
3572
3573    for row_idx in 0..frame.index().len() {
3574        out.push_str("  <");
3575        out.push_str(&options.row_name);
3576        out.push_str(">\n");
3577
3578        if options.include_index {
3579            let value = index_label_string(frame, row_idx)?;
3580            push_xml_field(&mut out, &index_label, Some(&value));
3581        }
3582
3583        for name in &headers {
3584            let value = frame
3585                .column(name)
3586                .and_then(|column| column.value(row_idx))
3587                .and_then(scalar_to_xml_value);
3588            push_xml_field(&mut out, name, value.as_deref());
3589        }
3590
3591        out.push_str("  </");
3592        out.push_str(&options.row_name);
3593        out.push_str(">\n");
3594    }
3595
3596    out.push_str("</");
3597    out.push_str(&options.root_name);
3598    out.push_str(">\n");
3599    Ok(out)
3600}
3601
3602fn xml_event_name(name: quick_xml::name::QName<'_>) -> Result<String, IoError> {
3603    std::str::from_utf8(name.as_ref())
3604        .map(ToOwned::to_owned)
3605        .map_err(|err| IoError::Xml(format!("invalid utf-8 xml element name: {err}")))
3606}
3607
3608fn decode_xml_general_ref(reference: quick_xml::events::BytesRef<'_>) -> Result<String, IoError> {
3609    let raw = std::str::from_utf8(reference.as_ref())
3610        .map_err(|err| IoError::Xml(format!("invalid utf-8 xml entity reference: {err}")))?;
3611    match raw {
3612        "amp" => Ok("&".to_owned()),
3613        "lt" => Ok("<".to_owned()),
3614        "gt" => Ok(">".to_owned()),
3615        "quot" => Ok("\"".to_owned()),
3616        "apos" => Ok("'".to_owned()),
3617        _ if raw.starts_with("#x") => {
3618            let value = u32::from_str_radix(&raw[2..], 16)
3619                .map_err(|err| IoError::Xml(format!("invalid hex xml entity '&{raw};': {err}")))?;
3620            char::from_u32(value)
3621                .map(|ch| ch.to_string())
3622                .ok_or_else(|| IoError::Xml(format!("invalid unicode xml entity '&{raw};'")))
3623        }
3624        _ if raw.starts_with('#') => {
3625            let value = raw[1..].parse::<u32>().map_err(|err| {
3626                IoError::Xml(format!("invalid decimal xml entity '&{raw};': {err}"))
3627            })?;
3628            char::from_u32(value)
3629                .map(|ch| ch.to_string())
3630                .ok_or_else(|| IoError::Xml(format!("invalid unicode xml entity '&{raw};'")))
3631        }
3632        _ => Err(IoError::Xml(format!(
3633            "unsupported xml entity reference '&{raw};'"
3634        ))),
3635    }
3636}
3637
3638fn insert_xml_field(
3639    row: &mut BTreeMap<String, Scalar>,
3640    column_order: &mut Vec<String>,
3641    seen_columns: &mut HashSet<String>,
3642    name: String,
3643    value: Scalar,
3644) -> Result<(), IoError> {
3645    if row.insert(name.clone(), value).is_some() {
3646        return Err(IoError::Xml(format!("duplicate xml field '{name}' in row")));
3647    }
3648    if seen_columns.insert(name.clone()) {
3649        column_order.push(name);
3650    }
3651    Ok(())
3652}
3653
3654fn validate_xml_element_name(name: &str) -> Result<(), IoError> {
3655    let mut chars = name.chars();
3656    let Some(first) = chars.next() else {
3657        return Err(IoError::Xml(
3658            "xml element name must be non-empty".to_owned(),
3659        ));
3660    };
3661    let valid_first = first == '_' || first.is_ascii_alphabetic();
3662    let valid_rest =
3663        chars.all(|ch| ch == '_' || ch == '-' || ch == '.' || ch.is_ascii_alphanumeric());
3664    if valid_first && valid_rest {
3665        Ok(())
3666    } else {
3667        Err(IoError::Xml(format!("invalid xml element name '{name}'")))
3668    }
3669}
3670
3671fn push_xml_field(out: &mut String, name: &str, value: Option<&str>) {
3672    out.push_str("    <");
3673    out.push_str(name);
3674    match value {
3675        Some(value) => {
3676            out.push('>');
3677            out.push_str(&escape_xml_text(value));
3678            out.push_str("</");
3679            out.push_str(name);
3680            out.push_str(">\n");
3681        }
3682        None => out.push_str("/>\n"),
3683    }
3684}
3685
3686fn escape_xml_text(value: &str) -> String {
3687    let mut escaped = String::with_capacity(value.len());
3688    let mut chars = value.chars().peekable();
3689    while let Some(ch) = chars.next() {
3690        match ch {
3691            '&' => escaped.push_str("&amp;"),
3692            '<' => escaped.push_str("&lt;"),
3693            '>' => escaped.push_str("&gt;"),
3694            '\r' => {
3695                escaped.push('\n');
3696                if chars.peek() == Some(&'\n') {
3697                    chars.next();
3698                }
3699            }
3700            _ => escaped.push(ch),
3701        }
3702    }
3703    escaped
3704}
3705
3706fn scalar_to_xml_value(scalar: &Scalar) -> Option<String> {
3707    match scalar {
3708        Scalar::Null(_) => None,
3709        Scalar::Bool(value) => Some(if *value { "True" } else { "False" }.to_owned()),
3710        Scalar::Int64(value) => Some(value.to_string()),
3711        Scalar::Float64(value) => {
3712            if value.is_nan() {
3713                None
3714            } else if value.is_finite() && *value == value.round() && value.abs() < 1e15 {
3715                Some(format!("{value:.1}"))
3716            } else {
3717                Some(value.to_string())
3718            }
3719        }
3720        Scalar::Utf8(value) => Some(value.clone()),
3721        Scalar::Timedelta64(value) => {
3722            if *value == Timedelta::NAT {
3723                None
3724            } else {
3725                Some(Timedelta::format(*value))
3726            }
3727        }
3728        Scalar::Datetime64(value) => {
3729            if *value == Timestamp::NAT {
3730                None
3731            } else {
3732                Some(format_datetime_ns(*value))
3733            }
3734        }
3735        Scalar::Period(value) => {
3736            if value.ordinal == i64::MIN {
3737                None
3738            } else {
3739                Some(value.calendar_string())
3740            }
3741        }
3742        Scalar::Interval(iv) => Some(format!("{iv}")),
3743    }
3744}
3745
3746fn html_selector(pattern: &str) -> Result<Selector, IoError> {
3747    Selector::parse(pattern).map_err(|err| {
3748        IoError::Html(format!(
3749            "invalid built-in html selector {pattern:?}: {err:?}"
3750        ))
3751    })
3752}
3753
3754fn html_row_cells(row: ElementRef<'_>, cell_selector: &Selector) -> Vec<String> {
3755    row.select(cell_selector)
3756        .map(|cell| cell.text().collect::<String>().trim().to_owned())
3757        .collect()
3758}
3759
3760fn normalize_html_headers(raw_headers: &[String]) -> Result<Vec<String>, IoError> {
3761    if raw_headers.is_empty() {
3762        return Err(IoError::Html(
3763            "html table header row contains no cells".to_owned(),
3764        ));
3765    }
3766
3767    let mut seen = HashSet::new();
3768    let mut headers = Vec::with_capacity(raw_headers.len());
3769    for (idx, raw) in raw_headers.iter().enumerate() {
3770        let name = if raw.trim().is_empty() {
3771            format!("Unnamed: {idx}")
3772        } else {
3773            raw.trim().to_owned()
3774        };
3775        if !seen.insert(name.clone()) {
3776            return Err(IoError::DuplicateColumnName(name));
3777        }
3778        headers.push(name);
3779    }
3780    Ok(headers)
3781}
3782
3783fn html_rows_to_frame(
3784    column_order: Vec<String>,
3785    rows: Vec<Vec<String>>,
3786) -> Result<DataFrame, IoError> {
3787    let width = column_order.len();
3788    if width == 0 {
3789        return Err(IoError::Html(
3790            "html table must contain at least one column".to_owned(),
3791        ));
3792    }
3793
3794    let mut values_by_column = column_order
3795        .iter()
3796        .map(|name| (name.clone(), Vec::with_capacity(rows.len())))
3797        .collect::<BTreeMap<_, _>>();
3798    for (row_idx, row) in rows.iter().enumerate() {
3799        if row.len() > width {
3800            return Err(IoError::Html(format!(
3801                "html row {row_idx} has {} cells but header has {width}",
3802                row.len()
3803            )));
3804        }
3805        for (col_idx, name) in column_order.iter().enumerate() {
3806            let value = row
3807                .get(col_idx)
3808                .map_or(Scalar::Null(NullKind::Null), |cell| parse_scalar(cell));
3809            let column_values = values_by_column.get_mut(name).ok_or_else(|| {
3810                IoError::Html(format!("html column '{name}' was not initialized"))
3811            })?;
3812            column_values.push(value);
3813        }
3814    }
3815
3816    let mut columns = BTreeMap::new();
3817    for name in &column_order {
3818        let values = values_by_column
3819            .remove(name)
3820            .ok_or_else(|| IoError::Html(format!("html column '{name}' has no values")))?;
3821        columns.insert(name.clone(), Column::from_values(values)?);
3822    }
3823    let row_count = i64::try_from(rows.len()).map_err(|_| {
3824        IoError::Html(format!(
3825            "html table row count {} exceeds supported i64 index range",
3826            rows.len()
3827        ))
3828    })?;
3829    Ok(DataFrame::new_with_column_order(
3830        Index::from_i64((0..row_count).collect()),
3831        columns,
3832        column_order,
3833    )?)
3834}
3835
3836fn resolve_csv_index_header(frame: &DataFrame, options: &CsvWriteOptions) -> String {
3837    options
3838        .index_label
3839        .clone()
3840        .or_else(|| frame.index().name().map(ToOwned::to_owned))
3841        .unwrap_or_default()
3842}
3843
3844fn resolve_table_index_header(frame: &DataFrame, index_label: Option<&str>) -> String {
3845    index_label
3846        .map(ToOwned::to_owned)
3847        .or_else(|| frame.index().name().map(ToOwned::to_owned))
3848        .unwrap_or_default()
3849}
3850
3851fn index_label_string(frame: &DataFrame, row_idx: usize) -> Result<String, IoError> {
3852    frame
3853        .index()
3854        .labels()
3855        .get(row_idx)
3856        .map(ToString::to_string)
3857        .ok_or_else(|| {
3858            IoError::Frame(FrameError::CompatibilityRejected(format!(
3859                "index position {row_idx} out of bounds for index length {}",
3860                frame.index().len()
3861            )))
3862        })
3863}
3864
3865/// Derive the column-uniform `to_csv` datetime spec for a DatetimeIndex.
3866///
3867/// Returns `None` unless every label is `Datetime64` (a homogeneous datetime
3868/// index), so non-datetime / mixed indexes keep their default rendering.
3869fn index_datetime_csv_format(frame: &DataFrame) -> Option<DatetimeCsvFormat> {
3870    let labels = frame.index().labels();
3871    let mut any_datetime = false;
3872    let mut date_only = true;
3873    let mut subsec_digits = 0u8;
3874    for label in labels {
3875        let IndexLabel::Datetime64(ns) = label else {
3876            return None;
3877        };
3878        any_datetime = true;
3879        if *ns == i64::MIN {
3880            continue; // NaT
3881        }
3882        let subsec = (ns.rem_euclid(1_000_000_000)) as u32;
3883        if ns.div_euclid(1_000_000_000).rem_euclid(86_400) != 0 || subsec != 0 {
3884            date_only = false;
3885        }
3886        if subsec != 0 {
3887            let digits = if !subsec.is_multiple_of(1_000) {
3888                9
3889            } else if !subsec.is_multiple_of(1_000_000) {
3890                6
3891            } else {
3892                3
3893            };
3894            subsec_digits = subsec_digits.max(digits);
3895        }
3896    }
3897    any_datetime.then_some(DatetimeCsvFormat {
3898        date_only,
3899        subsec_digits,
3900    })
3901}
3902
3903/// CSV index-cell formatter: applies a DatetimeIndex's column-uniform spec when
3904/// present, otherwise identical to `index_label_string`.
3905fn index_label_csv_string(
3906    frame: &DataFrame,
3907    row_idx: usize,
3908    dt_format: Option<DatetimeCsvFormat>,
3909) -> Result<String, IoError> {
3910    if let Some(fmt) = dt_format
3911        && let Some(IndexLabel::Datetime64(ns)) = frame.index().labels().get(row_idx)
3912        && *ns != i64::MIN
3913    {
3914        return Ok(format_datetime_csv(*ns, fmt));
3915    }
3916    index_label_string(frame, row_idx)
3917}
3918
3919/// Column-uniform datetime rendering spec for `to_csv`, mirroring pandas.
3920///
3921/// pandas chooses one format for the whole datetime column: a date-only
3922/// `YYYY-MM-DD` when every value falls exactly on midnight, otherwise
3923/// `YYYY-MM-DD HH:MM:SS` with a fractional-seconds suffix whose width is the
3924/// column's finest sub-second resolution (3 = ms, 6 = µs, 9 = ns; 0 = none).
3925#[derive(Clone, Copy)]
3926struct DatetimeCsvFormat {
3927    date_only: bool,
3928    subsec_digits: u8,
3929}
3930
3931/// Scan a Datetime64 column and derive its column-uniform `to_csv` format.
3932fn datetime_csv_format(column: &Column) -> DatetimeCsvFormat {
3933    if let Some(nanos) = column.as_datetime64_slice() {
3934        return datetime_csv_format_from_nanos(nanos.iter().copied());
3935    }
3936
3937    datetime_csv_format_from_nanos(column.values().iter().filter_map(|value| {
3938        let Scalar::Datetime64(nanos) = value else {
3939            return None;
3940        };
3941        Some(*nanos)
3942    }))
3943}
3944
3945fn datetime_csv_format_from_nanos(nanos: impl Iterator<Item = i64>) -> DatetimeCsvFormat {
3946    let mut date_only = true;
3947    let mut subsec_digits = 0u8;
3948    for ns in nanos {
3949        if ns == Timestamp::NAT {
3950            continue;
3951        }
3952        let subsec = (ns.rem_euclid(1_000_000_000)) as u32;
3953        // Any non-midnight time-of-day OR any sub-second component forces the
3954        // full timestamp form for the entire column.
3955        if ns.div_euclid(1_000_000_000).rem_euclid(86_400) != 0 || subsec != 0 {
3956            date_only = false;
3957        }
3958        if subsec != 0 {
3959            let digits = if !subsec.is_multiple_of(1_000) {
3960                9
3961            } else if !subsec.is_multiple_of(1_000_000) {
3962                6
3963            } else {
3964                3
3965            };
3966            subsec_digits = subsec_digits.max(digits);
3967        }
3968    }
3969    DatetimeCsvFormat {
3970        date_only,
3971        subsec_digits,
3972    }
3973}
3974
3975/// Format one datetime (ns since epoch) under a column's `to_csv` spec.
3976fn format_datetime_csv(nanos: i64, fmt: DatetimeCsvFormat) -> String {
3977    // `format_datetime_ns` now CARRIES sub-second precision (trailing-zero
3978    // trimmed, e.g. ".5"); to_csv instead wants a COLUMN-UNIFORM fixed-width
3979    // fraction (e.g. ".500"), so work from the fixed 19-char
3980    // "YYYY-MM-DD HH:MM:SS" stem (year is always 4 digits across the i64-ns
3981    // range) and apply the column's resolution here. (br-frankenpandas-dt64fmt)
3982    let base = format_datetime_ns(nanos);
3983    if fmt.date_only {
3984        return base[..10].to_owned();
3985    }
3986    let stem = &base[..19];
3987    if fmt.subsec_digits == 0 {
3988        return stem.to_owned();
3989    }
3990    let subsec = (nanos.rem_euclid(1_000_000_000)) as u32;
3991    let frac = subsec / 10u32.pow(9 - u32::from(fmt.subsec_digits));
3992    format!(
3993        "{stem}.{frac:0>width$}",
3994        width = usize::from(fmt.subsec_digits)
3995    )
3996}
3997
3998fn scalar_to_csv_with_na(scalar: &Scalar, na_rep: &str) -> String {
3999    match scalar {
4000        Scalar::Null(_) => na_rep.to_owned(),
4001        Scalar::Float64(v) if v.is_nan() => na_rep.to_owned(),
4002        // pandas to_csv renders floats via Python str(float): whole numbers keep
4003        // ".0" ("1.0", not "1") and extreme magnitudes use signed two-digit
4004        // scientific notation. The table writers (latex/markdown/html) use the
4005        // separate scalar_to_table_with_na path and keep their own formatting.
4006        Scalar::Float64(v) => format_pandas_float(*v),
4007        Scalar::Timedelta64(v) if *v == Timedelta::NAT => na_rep.to_owned(),
4008        other => scalar_to_csv(other),
4009    }
4010}
4011
4012/// CSV cell formatter that applies a column's datetime spec when present;
4013/// otherwise identical to `scalar_to_csv_with_na`.
4014fn scalar_to_csv_cell(
4015    scalar: &Scalar,
4016    na_rep: &str,
4017    dt_format: Option<DatetimeCsvFormat>,
4018) -> String {
4019    if let (Scalar::Datetime64(ns), Some(fmt)) = (scalar, dt_format) {
4020        if *ns == Timestamp::NAT {
4021            return na_rep.to_owned();
4022        }
4023        return format_datetime_csv(*ns, fmt);
4024    }
4025    scalar_to_csv_with_na(scalar, na_rep)
4026}
4027
4028fn scalar_to_table_with_na(scalar: &Scalar, na_rep: &str) -> String {
4029    match scalar {
4030        Scalar::Null(_) => na_rep.to_owned(),
4031        Scalar::Float64(v) if v.is_nan() => na_rep.to_owned(),
4032        // pandas to_string / to_markdown / to_html render a TEMPORAL NaT as the
4033        // literal "NaT": na_rep overrides only float NaN, NOT NaT. Verified vs
4034        // pandas 2.2.3 — `df.to_html(na_rep='X')` keeps "NaT" for datetime/
4035        // timedelta but shows "X" for NaN. (Datetime64/Period NaT previously
4036        // fell through to scalar_to_csv -> "" blank cells; an earlier fix wrongly
4037        // routed all temporal NaT to na_rep.) to_latex DIFFERS (collapses NaT to
4038        // na_rep) and is corrected in scalar_to_latex_cell. (br-frankenpandas-tblnat)
4039        Scalar::Timedelta64(v) if *v == Timedelta::NAT => "NaT".to_owned(),
4040        Scalar::Datetime64(v) if *v == Timestamp::NAT => "NaT".to_owned(),
4041        Scalar::Period(p) if p.ordinal == i64::MIN => "NaT".to_owned(),
4042        other => scalar_to_csv(other),
4043    }
4044}
4045
4046/// LaTeX cell formatter. pandas `to_latex` renders floats with its default
4047/// `float_format` of six decimal places (`1.0` -> "1.000000", `0.1234567` ->
4048/// "0.123457"), unlike the str(float) form used by to_csv/to_html. Integers and
4049/// other scalars keep the shared table formatting. Verified vs pandas 2.2.3.
4050fn scalar_to_latex_cell(scalar: &Scalar, na_rep: &str) -> String {
4051    match scalar {
4052        Scalar::Float64(v) if v.is_nan() => na_rep.to_owned(),
4053        // pandas to_latex collapses ALL missing — float NaN AND temporal NaT —
4054        // to na_rep (default "NaN"), unlike to_string/to_html which keep "NaT".
4055        // Verified vs pandas 2.2.3. Override here before delegating, since
4056        // scalar_to_table_with_na now renders temporal NaT as "NaT" for the
4057        // markdown/string family. (br-frankenpandas-tblnat)
4058        Scalar::Timedelta64(v) if *v == Timedelta::NAT => na_rep.to_owned(),
4059        Scalar::Datetime64(v) if *v == Timestamp::NAT => na_rep.to_owned(),
4060        Scalar::Period(p) if p.ordinal == i64::MIN => na_rep.to_owned(),
4061        // Rust `{:.6}` matches Python `%.6f` (round-half-to-even) and renders
4062        // infinities as "inf"/"-inf", exactly as pandas to_latex does.
4063        Scalar::Float64(v) => format!("{v:.6}"),
4064        other => scalar_to_table_with_na(other, na_rep),
4065    }
4066}
4067
4068fn push_markdown_row(out: &mut String, cells: &[String]) {
4069    out.push('|');
4070    for cell in cells {
4071        out.push(' ');
4072        push_escaped_markdown_table_cell(out, cell);
4073        out.push_str(" |");
4074    }
4075    out.push('\n');
4076}
4077
4078fn push_escaped_markdown_table_cell(out: &mut String, value: &str) {
4079    for ch in value.chars() {
4080        match ch {
4081            '\\' => out.push_str("\\\\"),
4082            '|' => out.push_str("\\|"),
4083            '\n' | '\r' => out.push(' '),
4084            _ => out.push(ch),
4085        }
4086    }
4087}
4088
4089fn push_latex_row(out: &mut String, cells: &[String], escape: bool) {
4090    for (idx, cell) in cells.iter().enumerate() {
4091        if idx > 0 {
4092            out.push_str(" & ");
4093        }
4094        if escape {
4095            out.push_str(&escape_latex_table_cell(cell));
4096        } else {
4097            out.push_str(cell);
4098        }
4099    }
4100    out.push_str(" \\\\\n");
4101}
4102
4103fn escape_latex_table_cell(value: &str) -> String {
4104    let mut escaped = String::with_capacity(value.len());
4105    for ch in value.chars() {
4106        match ch {
4107            '&' => escaped.push_str("\\&"),
4108            '%' => escaped.push_str("\\%"),
4109            '$' => escaped.push_str("\\$"),
4110            '#' => escaped.push_str("\\#"),
4111            '_' => escaped.push_str("\\_"),
4112            '{' => escaped.push_str("\\{"),
4113            '}' => escaped.push_str("\\}"),
4114            '~' => escaped.push_str("\\textasciitilde{}"),
4115            '^' => escaped.push_str("\\textasciicircum{}"),
4116            '\\' => escaped.push_str("\\textbackslash{}"),
4117            '\n' | '\r' => escaped.push(' '),
4118            _ => escaped.push(ch),
4119        }
4120    }
4121    escaped
4122}
4123
4124fn is_pandas_default_na(s: &str) -> bool {
4125    // Default NA values recognized by pandas read_csv.
4126    // See: <https://pandas.pydata.org/docs/reference/api/pandas.read_csv.html>
4127    matches!(
4128        s,
4129        "" | "#N/A"
4130            | "#N/A N/A"
4131            | "#NA"
4132            | "-1.#IND"
4133            | "-1.#QNAN"
4134            | "-NaN"
4135            | "-nan"
4136            | "1.#IND"
4137            | "1.#QNAN"
4138            | "<NA>"
4139            | "N/A"
4140            | "NA"
4141            | "NULL"
4142            | "NaN"
4143            | "None"
4144            | "n/a"
4145            | "nan"
4146            | "null"
4147    )
4148}
4149
4150fn parse_scalar(field: &str) -> Scalar {
4151    // pandas read_csv tolerates surrounding whitespace ONLY for numeric
4152    // inference. NA markers and booleans must match the field EXACTLY (a
4153    // padded " NA " or "true " is NOT null/bool), and plain strings keep their
4154    // original whitespace. Verified vs live pandas 2.2.3: " abc " stays
4155    // " abc "; "true " / " NA " stay strings; but " 1 " parses to Int64(1).
4156    if is_pandas_default_na(field) {
4157        return Scalar::Null(NullKind::Null);
4158    }
4159
4160    let trimmed = field.trim();
4161    if let Ok(value) = trimmed.parse::<i64>() {
4162        return Scalar::Int64(value);
4163    }
4164    if let Ok(value) = trimmed.parse::<f64>() {
4165        return Scalar::Float64(value);
4166    }
4167    if field.eq_ignore_ascii_case("true") {
4168        return Scalar::Bool(true);
4169    }
4170    if field.eq_ignore_ascii_case("false") {
4171        return Scalar::Bool(false);
4172    }
4173
4174    Scalar::Utf8(field.to_owned())
4175}
4176
4177/// Format an f64 the way pandas `to_csv` does (Python `str(float)`): keep a
4178/// trailing ".0" on whole numbers ("1.0", not Rust Display's "1"), shortest
4179/// round-trip for decimals, and signed two-digit scientific notation
4180/// ("1e+16" / "1e-05") for very large / small magnitudes. Verified vs live
4181/// pandas 2.2.3. NaN must be handled by the caller (it becomes na_rep).
4182fn format_pandas_float(v: f64) -> String {
4183    let mut out = String::new();
4184    write_pandas_float(&mut out, v);
4185    out
4186}
4187
4188/// Append the pandas `str(float)` rendering of `v` directly to `out`, without
4189/// the per-call `String` allocation `format_pandas_float` makes — the hot path
4190/// for the all-numeric CSV writer (br-frankenpandas-qk2i9).
4191///
4192/// Finite values first try `ryu::Buffer` to bypass Rust's generic formatting
4193/// machinery. Boundary spellings where `ryu` and Python choose different fixed
4194/// vs scientific notation deopt to the Debug-based fallback below.
4195fn write_pandas_float(out: &mut String, v: f64) {
4196    if v.is_finite() {
4197        let mut buffer = ryu::Buffer::new();
4198        let rendered = buffer.format_finite(v);
4199        let has_exponent = rendered.contains('e');
4200        let is_zero = v.to_bits() << 1 == 0;
4201        if has_exponent || is_zero || v.abs() >= 1e-4 {
4202            append_pandas_normalized_float(out, rendered);
4203            return;
4204        }
4205    }
4206
4207    write_pandas_float_debug_fallback(out, v);
4208}
4209
4210fn append_pandas_normalized_float(out: &mut String, rendered: &str) {
4211    let Some(e) = rendered.find('e') else {
4212        out.push_str(rendered);
4213        if !rendered.contains('.') {
4214            out.push_str(".0");
4215        }
4216        return;
4217    };
4218
4219    out.push_str(&rendered[..=e]);
4220    let exp = &rendered[e + 1..];
4221    let (sign, digits) = match exp.strip_prefix('-') {
4222        Some(d) => ('-', d),
4223        None => ('+', exp.strip_prefix('+').unwrap_or(exp)),
4224    };
4225    out.push(sign);
4226    if digits.len() < 2 {
4227        out.push('0');
4228    }
4229    out.push_str(digits);
4230}
4231
4232/// Rust's Debug formatter gives the shortest round-trip representation and,
4233/// unlike Display, keeps ".0" on whole numbers and switches to scientific
4234/// notation at Python's repr boundaries. Only the exponent spelling differs
4235/// (Rust "1e16"/"1e-5" vs Python "1e+16"/"1e-05"), so the rare sci-notation case
4236/// is normalized in place.
4237fn write_pandas_float_debug_fallback(out: &mut String, v: f64) {
4238    use std::fmt::Write as _;
4239    let start = out.len();
4240    let _ = write!(out, "{v:?}");
4241    // Common case (no scientific notation): `{v:?}` is already the pandas form.
4242    let Some(rel_e) = out[start..].find('e') else {
4243        return;
4244    };
4245    // Sci notation: normalize the exponent to Python's signed, >=2-digit form.
4246    let e = start + rel_e;
4247    let exp = out.split_off(e + 1); // everything after 'e'; `out` keeps "<mantissa>e"
4248    let (sign, digits) = match exp.strip_prefix('-') {
4249        Some(d) => ('-', d),
4250        None => ('+', exp.strip_prefix('+').unwrap_or(&exp)),
4251    };
4252    out.push(sign);
4253    if digits.len() < 2 {
4254        out.push('0');
4255    }
4256    out.push_str(digits);
4257}
4258
4259fn scalar_to_csv(scalar: &Scalar) -> String {
4260    match scalar {
4261        Scalar::Null(_) => String::new(),
4262        // pandas to_csv writes capitalized True/False (matches fp-frame::to_csv).
4263        Scalar::Bool(v) => if *v { "True" } else { "False" }.to_string(),
4264        Scalar::Int64(v) => v.to_string(),
4265        Scalar::Float64(v) => {
4266            if v.is_nan() {
4267                String::new()
4268            } else {
4269                v.to_string()
4270            }
4271        }
4272        Scalar::Utf8(v) => v.clone(),
4273        Scalar::Timedelta64(v) => {
4274            if *v == Timedelta::NAT {
4275                String::new()
4276            } else {
4277                Timedelta::format(*v)
4278            }
4279        }
4280        Scalar::Datetime64(v) => {
4281            if *v == Timestamp::NAT {
4282                String::new()
4283            } else {
4284                format_datetime_ns(*v)
4285            }
4286        }
4287        Scalar::Period(p) => {
4288            if p.ordinal == i64::MIN {
4289                String::new()
4290            } else {
4291                p.calendar_string()
4292            }
4293        }
4294        Scalar::Interval(iv) => format!("{iv}"),
4295    }
4296}
4297
4298/// Parse a field with NA value handling respecting pandas options.
4299///
4300/// - `na_filter`: If false, skip NA detection entirely for performance
4301/// - `keep_default_na`: If true, use pandas default NA values
4302/// - `na_set` / `true_set` / `false_set`: Pre-built HashSets for O(1)
4303///   membership lookup. Per br-frankenpandas-b67a3 (sister to br-fcf5d),
4304///   these were previously `&[String]` slices scanned linearly per cell;
4305///   now built once at the parent CSV reader and passed in.
4306#[allow(clippy::too_many_arguments)]
4307fn parse_scalar_with_options(
4308    field: &str,
4309    na_filter: bool,
4310    keep_default_na: bool,
4311    na_set: &HashSet<&str>,
4312    true_set: &HashSet<&str>,
4313    false_set: &HashSet<&str>,
4314    decimal: u8,
4315    thousands: Option<u8>,
4316) -> Scalar {
4317    // pandas only tolerates surrounding whitespace for NUMERIC inference; NA
4318    // markers, booleans, and plain strings match/keep the field EXACTLY (a
4319    // padded " NA " or "true " stays a string). See parse_scalar.
4320    let trimmed = field.trim();
4321
4322    // Check NA values only if na_filter is enabled
4323    if na_filter {
4324        let is_default_na = keep_default_na && is_pandas_default_na(field);
4325        let is_custom_na = na_set.contains(field);
4326        if is_default_na || is_custom_na {
4327            return Scalar::Null(NullKind::Null);
4328        }
4329    }
4330
4331    // `thousands` is silently ignored if it equals the decimal separator,
4332    // matching pandas semantics.
4333    let thousands_effective = thousands.filter(|t| *t != decimal);
4334    let numeric_candidate: Cow<'_, str> = if let Some(t) = thousands_effective {
4335        let ch = char::from(t);
4336        if trimmed.contains(ch) {
4337            Cow::Owned(trimmed.replace(ch, ""))
4338        } else {
4339            Cow::Borrowed(trimmed)
4340        }
4341    } else {
4342        Cow::Borrowed(trimmed)
4343    };
4344
4345    if let Ok(value) = numeric_candidate.as_ref().parse::<i64>() {
4346        return Scalar::Int64(value);
4347    }
4348
4349    let decimal_ch = char::from(decimal);
4350    let float_candidate: Cow<'_, str> = if decimal == b'.' {
4351        Cow::Borrowed(numeric_candidate.as_ref())
4352    } else if numeric_candidate.contains(decimal_ch) {
4353        Cow::Owned(numeric_candidate.replace(decimal_ch, "."))
4354    } else {
4355        Cow::Borrowed(numeric_candidate.as_ref())
4356    };
4357    if let Ok(value) = float_candidate.as_ref().parse::<f64>() {
4358        return Scalar::Float64(value);
4359    }
4360
4361    if true_set.contains(field) {
4362        return Scalar::Bool(true);
4363    }
4364    if false_set.contains(field) {
4365        return Scalar::Bool(false);
4366    }
4367
4368    if field.eq_ignore_ascii_case("true") {
4369        return Scalar::Bool(true);
4370    }
4371    if field.eq_ignore_ascii_case("false") {
4372        return Scalar::Bool(false);
4373    }
4374    Scalar::Utf8(field.to_owned())
4375}
4376
4377fn reject_duplicate_headers(headers: &[String]) -> Result<(), IoError> {
4378    let mut used = BTreeSet::new();
4379    for name in headers {
4380        if !used.insert(name.clone()) {
4381            return Err(IoError::DuplicateColumnName(name.clone()));
4382        }
4383    }
4384    Ok(())
4385}
4386
4387fn validate_usecols(headers: &[String], usecols: &[String]) -> Result<(), IoError> {
4388    let header_set: std::collections::BTreeSet<&String> = headers.iter().collect();
4389    let mut missing = Vec::new();
4390    for name in usecols {
4391        if !header_set.contains(name) {
4392            missing.push(name.clone());
4393        }
4394    }
4395    if missing.is_empty() {
4396        Ok(())
4397    } else {
4398        Err(IoError::MissingUsecols(missing))
4399    }
4400}
4401
4402fn validate_parse_dates(headers: &[String], parse_dates: &[String]) -> Result<(), IoError> {
4403    let header_set: std::collections::BTreeSet<&String> = headers.iter().collect();
4404    let mut missing = Vec::new();
4405    for name in parse_dates {
4406        if !header_set.contains(name) {
4407            missing.push(name.clone());
4408        }
4409    }
4410    if missing.is_empty() {
4411        Ok(())
4412    } else {
4413        Err(IoError::MissingParseDateColumns(missing))
4414    }
4415}
4416
4417fn validate_parse_date_combinations(
4418    headers: &[String],
4419    parse_date_combinations: &[Vec<String>],
4420) -> Result<(), IoError> {
4421    let header_set: std::collections::BTreeSet<&String> = headers.iter().collect();
4422    let mut missing = BTreeSet::new();
4423    for combo in parse_date_combinations {
4424        for name in combo {
4425            if !header_set.contains(name) {
4426                missing.insert(name.clone());
4427            }
4428        }
4429    }
4430    if missing.is_empty() {
4431        Ok(())
4432    } else {
4433        Err(IoError::MissingParseDateColumns(
4434            missing.into_iter().collect(),
4435        ))
4436    }
4437}
4438
4439fn apply_parse_dates_to_scalar_columns(
4440    headers: &[String],
4441    columns: &mut [Vec<Scalar>],
4442    parse_dates: &[String],
4443) -> Result<(), IoError> {
4444    if parse_dates.is_empty() {
4445        return Ok(());
4446    }
4447
4448    validate_parse_dates(headers, parse_dates)?;
4449
4450    for column_name in parse_dates {
4451        let Some(column_idx) = headers.iter().position(|header| header == column_name) else {
4452            continue;
4453        };
4454
4455        if let Some(parsed) = parse_csv_datetime_values(&columns[column_idx])? {
4456            columns[column_idx] = parsed;
4457        }
4458    }
4459
4460    Ok(())
4461}
4462
4463#[allow(clippy::too_many_arguments)]
4464fn apply_csv_parse_dates(
4465    headers: &[String],
4466    columns: &mut [Vec<Scalar>],
4467    raw_columns: &[Vec<String>],
4468    deferred_parse_date_columns: &[bool],
4469    parse_dates: &[String],
4470    options: &CsvReadOptions,
4471    na_set: &HashSet<&str>,
4472    true_set: &HashSet<&str>,
4473    false_set: &HashSet<&str>,
4474) -> Result<(), IoError> {
4475    if parse_dates.is_empty() {
4476        return Ok(());
4477    }
4478
4479    validate_parse_dates(headers, parse_dates)?;
4480
4481    for column_name in parse_dates {
4482        let Some(column_idx) = headers.iter().position(|header| header == column_name) else {
4483            continue;
4484        };
4485
4486        let parsed = if deferred_parse_date_columns
4487            .get(column_idx)
4488            .copied()
4489            .unwrap_or(false)
4490        {
4491            if let Some(parsed) = parse_csv_fixed_naive_datetime_fields(
4492                &raw_columns[column_idx],
4493                options.na_filter,
4494                options.keep_default_na,
4495                na_set,
4496            ) {
4497                Some(parsed)
4498            } else {
4499                columns[column_idx] = parse_csv_scalar_fields_with_options(
4500                    &raw_columns[column_idx],
4501                    options,
4502                    na_set,
4503                    true_set,
4504                    false_set,
4505                );
4506                parse_csv_datetime_values(&columns[column_idx])?
4507            }
4508        } else {
4509            parse_csv_datetime_values(&columns[column_idx])?
4510        };
4511
4512        if let Some(parsed) = parsed {
4513            columns[column_idx] = parsed;
4514        }
4515    }
4516
4517    Ok(())
4518}
4519
4520fn deferred_parse_date_column_mask(headers: &[String], options: &CsvReadOptions) -> Vec<bool> {
4521    let Some(parse_dates) = options.parse_dates.as_deref() else {
4522        return vec![false; headers.len()];
4523    };
4524    if parse_dates.is_empty()
4525        || options.parse_date_combinations.is_some()
4526        || options.parse_date_combinations_named.is_some()
4527    {
4528        return vec![false; headers.len()];
4529    }
4530
4531    headers
4532        .iter()
4533        .map(|header| parse_dates.iter().any(|name| name == header))
4534        .collect()
4535}
4536
4537fn parse_csv_fixed_naive_datetime_fields(
4538    fields: &[String],
4539    na_filter: bool,
4540    keep_default_na: bool,
4541    na_set: &HashSet<&str>,
4542) -> Option<Vec<Scalar>> {
4543    let mut parsed = Vec::with_capacity(fields.len());
4544    let mut saw_datetime = false;
4545
4546    for field in fields {
4547        if na_filter
4548            && ((keep_default_na && is_pandas_default_na(field)) || na_set.contains(field.as_str()))
4549        {
4550            parsed.push(Scalar::Datetime64(Timestamp::NAT));
4551            continue;
4552        }
4553
4554        parsed.push(Scalar::Datetime64(parse_fixed_naive_csv_datetime_nanos(
4555            field,
4556        )?));
4557        saw_datetime = true;
4558    }
4559
4560    saw_datetime.then_some(parsed)
4561}
4562
4563fn parse_csv_scalar_fields_with_options(
4564    fields: &[String],
4565    options: &CsvReadOptions,
4566    na_set: &HashSet<&str>,
4567    true_set: &HashSet<&str>,
4568    false_set: &HashSet<&str>,
4569) -> Vec<Scalar> {
4570    fields
4571        .iter()
4572        .map(|field| {
4573            parse_scalar_with_options(
4574                field,
4575                options.na_filter,
4576                options.keep_default_na,
4577                na_set,
4578                true_set,
4579                false_set,
4580                options.decimal,
4581                options.thousands,
4582            )
4583        })
4584        .collect()
4585}
4586
4587fn parse_sql_float_text(text: &str) -> Option<f64> {
4588    let trimmed = text.trim();
4589    if trimmed.is_empty() {
4590        return None;
4591    }
4592
4593    let mut normalized = String::with_capacity(trimmed.len());
4594    for ch in trimmed.chars() {
4595        match ch {
4596            ',' => {}
4597            '$' if normalized.is_empty() || normalized == "+" || normalized == "-" => {}
4598            _ => normalized.push(ch),
4599        }
4600    }
4601
4602    if matches!(normalized.as_str(), "" | "+" | "-" | ".") {
4603        return None;
4604    }
4605
4606    let value = normalized.parse::<f64>().ok()?;
4607    value.is_finite().then_some(value)
4608}
4609
4610fn apply_sql_coerce_float(columns: &mut [Vec<Scalar>]) {
4611    for column in columns {
4612        let mut saw_text_float = false;
4613        let mut parsed_values = Vec::with_capacity(column.len());
4614
4615        for value in column.iter() {
4616            match value {
4617                Scalar::Utf8(text) => {
4618                    let Some(parsed) = parse_sql_float_text(text) else {
4619                        saw_text_float = false;
4620                        parsed_values.clear();
4621                        break;
4622                    };
4623                    saw_text_float = true;
4624                    parsed_values.push(Some(parsed));
4625                }
4626                Scalar::Null(_) | Scalar::Int64(_) | Scalar::Float64(_) => {
4627                    parsed_values.push(None);
4628                }
4629                Scalar::Bool(_)
4630                | Scalar::Timedelta64(_)
4631                | Scalar::Datetime64(_)
4632                | Scalar::Period(_)
4633                | Scalar::Interval(_) => {
4634                    saw_text_float = false;
4635                    parsed_values.clear();
4636                    break;
4637                }
4638            }
4639        }
4640
4641        if !saw_text_float {
4642            continue;
4643        }
4644
4645        for (value, parsed) in column.iter_mut().zip(parsed_values) {
4646            if let Some(parsed) = parsed {
4647                *value = Scalar::Float64(parsed);
4648            } else if value.is_missing() {
4649                *value = Scalar::Null(NullKind::NaN);
4650            }
4651        }
4652    }
4653}
4654
4655fn combine_parse_date_values(column_group: &[Vec<Scalar>]) -> Vec<Scalar> {
4656    let len = column_group.first().map_or(0, Vec::len);
4657    let mut combined = Vec::with_capacity(len);
4658
4659    for row in 0..len {
4660        if column_group
4661            .iter()
4662            .any(|column| matches!(column[row], Scalar::Null(_)))
4663        {
4664            combined.push(Scalar::Null(NullKind::NaT));
4665            continue;
4666        }
4667
4668        let joined = column_group
4669            .iter()
4670            .map(|column| match &column[row] {
4671                Scalar::Utf8(value) => value.clone(),
4672                other => other.to_string(),
4673            })
4674            .collect::<Vec<_>>()
4675            .join(" ");
4676        combined.push(Scalar::Utf8(joined));
4677    }
4678
4679    combined
4680}
4681
4682fn apply_one_parse_date_combination(
4683    headers: &mut Vec<String>,
4684    columns: &mut Vec<Vec<Scalar>>,
4685    combined_name: String,
4686    sources: &[String],
4687) -> Result<(), IoError> {
4688    let mut positions = sources
4689        .iter()
4690        .map(|name| {
4691            headers
4692                .iter()
4693                .position(|header| header == name)
4694                .ok_or_else(|| IoError::MissingParseDateColumns(vec![name.clone()]))
4695        })
4696        .collect::<Result<Vec<_>, _>>()?;
4697    positions.sort_unstable();
4698
4699    let combined_values = combine_parse_date_values(
4700        &positions
4701            .iter()
4702            .map(|&idx| columns[idx].clone())
4703            .collect::<Vec<_>>(),
4704    );
4705    let parsed_values = match parse_csv_datetime_values(&combined_values)? {
4706        Some(parsed) => parsed,
4707        None => combined_values,
4708    };
4709
4710    for idx in positions.iter().rev() {
4711        headers.remove(*idx);
4712        columns.remove(*idx);
4713    }
4714    headers.insert(positions[0], combined_name);
4715    columns.insert(positions[0], parsed_values);
4716    Ok(())
4717}
4718
4719fn parse_csv_datetime_values(values: &[Scalar]) -> Result<Option<Vec<Scalar>>, IoError> {
4720    if let Some(parsed) = parse_csv_fixed_naive_datetime_values(values) {
4721        return Ok(Some(parsed));
4722    }
4723
4724    // pandas pd.read_csv(parse_dates=[col]) parses each value on its own —
4725    // a column with mixed naive ("2024-01-15 10:30:00") and aware
4726    // ("2024-01-15T10:30:00Z") entries normalizes each value
4727    // independently. The ToDatetimeOptions default `infer_mixed_timezone:
4728    // true` locks the column to the FIRST inferred pattern and rejects
4729    // any value that doesn't match it, which causes parse_failed=true and
4730    // leaves the column as raw strings even though every individual value
4731    // is parseable. Set it explicitly to false so each value goes through
4732    // parse_datetime_string, which already handles both naive and aware.
4733    let parsed = to_datetime_values_with_options(
4734        values,
4735        ToDatetimeOptions {
4736            infer_mixed_timezone: false,
4737            // pandas keeps a mixed naive+tz-aware parse_dates column as object
4738            // rather than datetime64 (br-frankenpandas-unz0t).
4739            mixed_tz_as_object: true,
4740            ..ToDatetimeOptions::default()
4741        },
4742    )?;
4743    let parse_failed = values
4744        .iter()
4745        .zip(parsed.iter())
4746        .any(|(original, parsed)| !original.is_missing() && parsed.is_missing());
4747
4748    if parse_failed {
4749        Ok(None)
4750    } else {
4751        Ok(Some(parsed))
4752    }
4753}
4754
4755fn parse_csv_fixed_naive_datetime_values(values: &[Scalar]) -> Option<Vec<Scalar>> {
4756    let mut parsed = Vec::with_capacity(values.len());
4757    let mut saw_datetime = false;
4758
4759    for value in values {
4760        match value {
4761            Scalar::Utf8(text) => {
4762                parsed.push(Scalar::Datetime64(parse_fixed_naive_csv_datetime_nanos(
4763                    text,
4764                )?));
4765                saw_datetime = true;
4766            }
4767            Scalar::Null(_) => parsed.push(Scalar::Datetime64(Timestamp::NAT)),
4768            _ => return None,
4769        }
4770    }
4771
4772    saw_datetime.then_some(parsed)
4773}
4774
4775fn parse_fixed_naive_csv_datetime_nanos(value: &str) -> Option<i64> {
4776    let bytes = value.trim().as_bytes();
4777    let (year, month, day, hour, minute, second) = match bytes.len() {
4778        10 => (
4779            parse_4_digits(bytes, 0)?,
4780            parse_2_digits(bytes, 5)?,
4781            parse_2_digits(bytes, 8)?,
4782            0,
4783            0,
4784            0,
4785        ),
4786        19 => (
4787            parse_4_digits(bytes, 0)?,
4788            parse_2_digits(bytes, 5)?,
4789            parse_2_digits(bytes, 8)?,
4790            parse_2_digits(bytes, 11)?,
4791            parse_2_digits(bytes, 14)?,
4792            parse_2_digits(bytes, 17)?,
4793        ),
4794        _ => return None,
4795    };
4796
4797    if bytes.get(4) != Some(&b'-')
4798        || bytes.get(7) != Some(&b'-')
4799        || (bytes.len() == 19
4800            && (bytes.get(10) != Some(&b' ')
4801                || bytes.get(13) != Some(&b':')
4802                || bytes.get(16) != Some(&b':')))
4803        || !valid_ymd(year, month, day)
4804        || hour > 23
4805        || minute > 59
4806        || second > 59
4807    {
4808        return None;
4809    }
4810
4811    let days = days_from_ymd(year, month, day);
4812    days.checked_mul(Timedelta::NANOS_PER_DAY)?
4813        .checked_add(hour.checked_mul(Timedelta::NANOS_PER_HOUR)?)?
4814        .checked_add(minute.checked_mul(Timedelta::NANOS_PER_MIN)?)?
4815        .checked_add(second.checked_mul(Timedelta::NANOS_PER_SEC)?)
4816}
4817
4818fn parse_2_digits(bytes: &[u8], offset: usize) -> Option<i64> {
4819    let hi = *bytes.get(offset)?;
4820    let lo = *bytes.get(offset + 1)?;
4821    if !hi.is_ascii_digit() || !lo.is_ascii_digit() {
4822        return None;
4823    }
4824    Some((i64::from(hi - b'0') * 10) + i64::from(lo - b'0'))
4825}
4826
4827fn parse_4_digits(bytes: &[u8], offset: usize) -> Option<i64> {
4828    let hi = parse_2_digits(bytes, offset)?;
4829    let lo = parse_2_digits(bytes, offset + 2)?;
4830    Some((hi * 100) + lo)
4831}
4832
4833fn valid_ymd(year: i64, month: i64, day: i64) -> bool {
4834    if !(1..=9999).contains(&year) || !(1..=12).contains(&month) {
4835        return false;
4836    }
4837    let max_day = match month {
4838        1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
4839        4 | 6 | 9 | 11 => 30,
4840        2 if is_leap_year(year) => 29,
4841        2 => 28,
4842        _ => return false,
4843    };
4844    (1..=max_day).contains(&day)
4845}
4846
4847fn is_leap_year(year: i64) -> bool {
4848    (year % 4 == 0 && year % 100 != 0) || year % 400 == 0
4849}
4850
4851fn days_from_ymd(year: i64, month: i64, day: i64) -> i64 {
4852    let y = if month <= 2 { year - 1 } else { year };
4853    let era = if y >= 0 { y } else { y - 399 } / 400;
4854    let yoe = y - (era * 400);
4855    let doy = (153 * (if month > 2 { month - 3 } else { month + 9 }) + 2) / 5 + day - 1;
4856    let doe = (yoe * 365) + (yoe / 4) - (yoe / 100) + doy;
4857    (era * 146_097) + doe - 719_468
4858}
4859
4860fn pandas_csv_numeric_column_requires_float(values: &[Scalar]) -> bool {
4861    // DISC-011: Nullable extension Int64 dtype parity.
4862    // Previously: Int64 columns with nulls promoted to Float64 for CSV output.
4863    // Now: Int64 columns preserve integer encoding; only promote when the
4864    // column actually contains Float64 values (mixed Int64/Float64 → Float64).
4865    let mut saw_int = false;
4866    let mut saw_float = false;
4867
4868    for value in values {
4869        match value {
4870            Scalar::Int64(_) => saw_int = true,
4871            Scalar::Float64(_) => saw_float = true,
4872            Scalar::Null(_) => {}
4873            Scalar::Bool(_)
4874            | Scalar::Utf8(_)
4875            | Scalar::Timedelta64(_)
4876            | Scalar::Datetime64(_)
4877            | Scalar::Period(_)
4878            | Scalar::Interval(_) => {
4879                return false;
4880            }
4881        }
4882    }
4883
4884    saw_int && saw_float
4885}
4886
4887fn apply_pandas_csv_numeric_promotions(columns: &mut [Vec<Scalar>]) {
4888    for column in columns {
4889        if !pandas_csv_numeric_column_requires_float(column) {
4890            continue;
4891        }
4892
4893        for value in column {
4894            if let Scalar::Int64(v) = value {
4895                *value = Scalar::Float64(*v as f64);
4896            }
4897        }
4898    }
4899}
4900
4901fn apply_parse_date_combinations(
4902    headers: &mut Vec<String>,
4903    columns: &mut Vec<Vec<Scalar>>,
4904    parse_date_combinations: &[Vec<String>],
4905) -> Result<(), IoError> {
4906    if parse_date_combinations.is_empty() {
4907        return Ok(());
4908    }
4909
4910    validate_parse_date_combinations(headers, parse_date_combinations)?;
4911
4912    for combination in parse_date_combinations {
4913        if combination.is_empty() {
4914            continue;
4915        }
4916        let combined_name = combination.join("_");
4917        apply_one_parse_date_combination(headers, columns, combined_name, combination)?;
4918    }
4919
4920    Ok(())
4921}
4922
4923fn apply_parse_date_combinations_named(
4924    headers: &mut Vec<String>,
4925    columns: &mut Vec<Vec<Scalar>>,
4926    parse_date_combinations_named: &[(String, Vec<String>)],
4927) -> Result<(), IoError> {
4928    if parse_date_combinations_named.is_empty() {
4929        return Ok(());
4930    }
4931
4932    let mut assigned_names: std::collections::HashSet<String> = std::collections::HashSet::new();
4933    for (new_name, _) in parse_date_combinations_named {
4934        if !assigned_names.insert(new_name.clone()) {
4935            return Err(IoError::DuplicateColumnName(new_name.clone()));
4936        }
4937    }
4938
4939    let combos_only: Vec<Vec<String>> = parse_date_combinations_named
4940        .iter()
4941        .map(|(_, sources)| sources.clone())
4942        .collect();
4943    validate_parse_date_combinations(headers, &combos_only)?;
4944
4945    for (new_name, sources) in parse_date_combinations_named {
4946        if sources.is_empty() {
4947            continue;
4948        }
4949        apply_one_parse_date_combination(headers, columns, new_name.clone(), sources)?;
4950    }
4951
4952    Ok(())
4953}
4954
4955#[allow(clippy::too_many_arguments)]
4956fn append_csv_record(
4957    columns: &mut [Vec<Scalar>],
4958    raw_columns: &mut [Vec<String>],
4959    record: &StringRecord,
4960    options: &CsvReadOptions,
4961    na_set: &HashSet<&str>,
4962    true_set: &HashSet<&str>,
4963    false_set: &HashSet<&str>,
4964    deferred_parse_date_columns: &[bool],
4965) {
4966    for (idx, col) in columns.iter_mut().enumerate() {
4967        let field = record.get(idx).unwrap_or_default();
4968        if deferred_parse_date_columns
4969            .get(idx)
4970            .copied()
4971            .unwrap_or(false)
4972        {
4973            col.push(Scalar::Null(NullKind::Null));
4974        } else {
4975            col.push(parse_scalar_with_options(
4976                field,
4977                options.na_filter,
4978                options.keep_default_na,
4979                na_set,
4980                true_set,
4981                false_set,
4982                options.decimal,
4983                options.thousands,
4984            ));
4985        }
4986        // Keep the verbatim field so an object-fallback column can preserve the
4987        // original literal like pandas (see build_csv_object_aware_column).
4988        raw_columns[idx].push(field.to_owned());
4989    }
4990}
4991
4992fn should_skip_bad_csv_record(
4993    record: &StringRecord,
4994    expected_fields: usize,
4995    on_bad_lines: CsvOnBadLines,
4996) -> bool {
4997    if record.len() <= expected_fields {
4998        return false;
4999    }
5000
5001    match on_bad_lines {
5002        CsvOnBadLines::Error => false,
5003        CsvOnBadLines::Warn => {
5004            eprintln!(
5005                "Skipping bad CSV line: expected {expected_fields} fields, found {}",
5006                record.len()
5007            );
5008            true
5009        }
5010        CsvOnBadLines::Skip => true,
5011    }
5012}
5013
5014// ── CSV with options ───────────────────────────────────────────────────
5015
5016/// Strip ASCII spaces (0x20) at each unquoted field start for `skipinitialspace`
5017/// (br-frankenpandas-i4h5g). A field starts at line start and immediately after a
5018/// delimiter; spaces there are dropped until the first non-space byte. Quote
5019/// state is tracked so spaces inside quoted fields (and delimiters/terminators
5020/// inside quotes) are preserved, and a `   "x,y"` field becomes the quoted value.
5021/// `doublequote` (a doubled quotechar = literal quote, stay in quote) and
5022/// `escapechar` (next byte is literal) are honored. Only ASCII 0x20 is stripped
5023/// (tabs are kept, matching pandas); trailing spaces are preserved. Every byte
5024/// other than the stripped leading spaces is copied verbatim, so the output is
5025/// valid UTF-8 and the downstream parse is byte-identical except for the removed
5026/// leading spaces.
5027fn apply_skipinitialspace(
5028    input: &str,
5029    delimiter: u8,
5030    quotechar: u8,
5031    doublequote: bool,
5032    escapechar: Option<u8>,
5033    lineterminator: Option<u8>,
5034) -> String {
5035    let bytes = input.as_bytes();
5036    let mut out: Vec<u8> = Vec::with_capacity(bytes.len());
5037    let is_terminator = |b: u8| match lineterminator {
5038        Some(t) => b == t,
5039        None => b == b'\n' || b == b'\r',
5040    };
5041    let mut in_quote = false;
5042    let mut at_field_start = true;
5043    let mut i = 0;
5044    while i < bytes.len() {
5045        let b = bytes[i];
5046        if in_quote {
5047            out.push(b);
5048            if let Some(esc) = escapechar
5049                && b == esc
5050                && i + 1 < bytes.len()
5051            {
5052                out.push(bytes[i + 1]);
5053                i += 2;
5054                continue;
5055            }
5056            if b == quotechar {
5057                if doublequote && i + 1 < bytes.len() && bytes[i + 1] == quotechar {
5058                    out.push(quotechar);
5059                    i += 2;
5060                    continue;
5061                }
5062                in_quote = false;
5063            }
5064            i += 1;
5065            continue;
5066        }
5067        if at_field_start && b == b' ' {
5068            i += 1;
5069            continue;
5070        }
5071        out.push(b);
5072        if at_field_start && b == quotechar {
5073            in_quote = true;
5074            at_field_start = false;
5075        } else {
5076            at_field_start = b == delimiter || is_terminator(b);
5077        }
5078        i += 1;
5079    }
5080    String::from_utf8(out).unwrap_or_else(|_| input.to_string())
5081}
5082
5083pub fn read_csv_with_options(input: &str, options: &CsvReadOptions) -> Result<DataFrame, IoError> {
5084    // br-frankenpandas-i4h5g: pandas `skipinitialspace` strips leading ASCII
5085    // spaces at each field start BEFORE quote handling, so it cannot be expressed
5086    // as a post-parse field trim. Rewrite the raw input once (quote/escape-aware)
5087    // and re-enter with the flag cleared, so the existing fast paths still apply
5088    // to the stripped text.
5089    if options.skipinitialspace {
5090        let processed = apply_skipinitialspace(
5091            input,
5092            options.delimiter,
5093            options.quotechar,
5094            options.doublequote,
5095            options.escapechar,
5096            options.lineterminator,
5097        );
5098        let mut opts = options.clone();
5099        opts.skipinitialspace = false;
5100        return read_csv_with_options(&processed, &opts);
5101    }
5102    if csv_read_options_match_default_fast_path(options) {
5103        return read_csv_str(input);
5104    }
5105
5106    if csv_read_options_match_no_na_numeric_fast_path(options) {
5107        if let Some(frame) = csv_parse_cache_lookup(CsvParseCacheMode::NoNaNumeric, input) {
5108            return Ok(frame);
5109        }
5110
5111        if let Some(frame) = try_read_csv_with_options_no_na_numeric_fast_path(input)? {
5112            csv_parse_cache_store(CsvParseCacheMode::NoNaNumeric, input, &frame);
5113            return Ok(frame);
5114        }
5115    }
5116
5117    let mut builder = ReaderBuilder::new();
5118    builder
5119        .has_headers(false)
5120        .delimiter(options.delimiter)
5121        .quote(options.quotechar)
5122        .double_quote(options.doublequote)
5123        .escape(options.escapechar);
5124    if options.on_bad_lines != CsvOnBadLines::Error {
5125        builder.flexible(true);
5126    }
5127    if let Some(c) = options.comment {
5128        builder.comment(Some(c));
5129    }
5130    if let Some(term) = options.lineterminator {
5131        builder.terminator(csv::Terminator::Any(term));
5132    }
5133    let mut reader = builder.from_reader(input.as_bytes());
5134
5135    let max_rows = options.nrows.unwrap_or(usize::MAX);
5136    let skip = options.skiprows;
5137
5138    let mut records = reader.records();
5139    for _ in 0..skip {
5140        if records.next().transpose()?.is_none() {
5141            return Err(IoError::MissingHeaders);
5142        }
5143    }
5144
5145    // Per br-frankenpandas-b67a3: pre-build NA / true / false sets once,
5146    // then thread through the per-record loop. Was Vec::iter().any()
5147    // per cell.
5148    let na_set: HashSet<&str> = options.na_values.iter().map(String::as_str).collect();
5149    let true_set: HashSet<&str> = options.true_values.iter().map(String::as_str).collect();
5150    let false_set: HashSet<&str> = options.false_values.iter().map(String::as_str).collect();
5151
5152    let mut row_count: i64 = 0;
5153    // raw_columns shadows columns with each cell's verbatim text so an
5154    // object-fallback column can preserve original literals (see the final
5155    // build step and build_csv_object_aware_column).
5156    let (headers, mut columns, mut raw_columns, deferred_parse_date_columns) =
5157        if options.has_headers {
5158            let headers_record = records.next().transpose()?.ok_or(IoError::MissingHeaders)?;
5159            if headers_record.is_empty() {
5160                return Err(IoError::MissingHeaders);
5161            }
5162
5163            let header_count = headers_record.len();
5164            let row_hint = input.len() / (header_count * 8).max(1);
5165            let headers = headers_record
5166                .iter()
5167                .map(ToOwned::to_owned)
5168                .collect::<Vec<_>>();
5169            let columns: Vec<Vec<Scalar>> = (0..header_count)
5170                .map(|_| Vec::with_capacity(row_hint))
5171                .collect();
5172            let raw_columns: Vec<Vec<String>> = (0..header_count)
5173                .map(|_| Vec::with_capacity(row_hint))
5174                .collect();
5175            let deferred_parse_date_columns = deferred_parse_date_column_mask(&headers, options);
5176
5177            (headers, columns, raw_columns, deferred_parse_date_columns)
5178        } else {
5179            let first_record = records.next().transpose()?.ok_or(IoError::MissingHeaders)?;
5180            if first_record.is_empty() {
5181                return Err(IoError::MissingHeaders);
5182            }
5183
5184            let header_count = first_record.len();
5185            let row_hint = input.len() / (header_count * 8).max(1);
5186            let headers = (0..header_count)
5187                .map(|idx| format!("column_{idx}"))
5188                .collect::<Vec<_>>();
5189            let mut columns: Vec<Vec<Scalar>> = (0..header_count)
5190                .map(|_| Vec::with_capacity(row_hint))
5191                .collect();
5192            let mut raw_columns: Vec<Vec<String>> = (0..header_count)
5193                .map(|_| Vec::with_capacity(row_hint))
5194                .collect();
5195            let deferred_parse_date_columns = deferred_parse_date_column_mask(&headers, options);
5196
5197            if (row_count as usize) < max_rows {
5198                append_csv_record(
5199                    &mut columns,
5200                    &mut raw_columns,
5201                    &first_record,
5202                    options,
5203                    &na_set,
5204                    &true_set,
5205                    &false_set,
5206                    &deferred_parse_date_columns,
5207                );
5208                row_count += 1;
5209            }
5210
5211            (headers, columns, raw_columns, deferred_parse_date_columns)
5212        };
5213
5214    for row in records {
5215        if (row_count as usize) >= max_rows {
5216            break;
5217        }
5218        let record = row?;
5219        if should_skip_bad_csv_record(&record, columns.len(), options.on_bad_lines) {
5220            continue;
5221        }
5222        append_csv_record(
5223            &mut columns,
5224            &mut raw_columns,
5225            &record,
5226            options,
5227            &na_set,
5228            &true_set,
5229            &false_set,
5230            &deferred_parse_date_columns,
5231        );
5232        row_count += 1;
5233    }
5234
5235    // Drop the last `skipfooter` data rows. Matches pandas semantics:
5236    // footer rows are dropped *after* header parsing and nrows limit.
5237    if options.skipfooter > 0 && (row_count as usize) > 0 {
5238        let drop = options.skipfooter.min(row_count as usize);
5239        for col in columns.iter_mut() {
5240            let new_len = col.len().saturating_sub(drop);
5241            col.truncate(new_len);
5242        }
5243        for col in raw_columns.iter_mut() {
5244            let new_len = col.len().saturating_sub(drop);
5245            col.truncate(new_len);
5246        }
5247        row_count -= drop as i64;
5248    }
5249    reject_duplicate_headers(&headers)?;
5250    if let Some(ref usecols) = options.usecols {
5251        validate_usecols(&headers, usecols)?;
5252    }
5253
5254    // Apply usecols filter: keep only selected columns.
5255    let (mut headers, mut columns, raw_columns, deferred_parse_date_columns) =
5256        if let Some(ref usecols) = options.usecols {
5257            let mut fh = Vec::new();
5258            let mut fc = Vec::new();
5259            let mut fr = Vec::new();
5260            let mut fd = Vec::new();
5261            for (((h, c), r), d) in headers
5262                .into_iter()
5263                .zip(columns)
5264                .zip(raw_columns)
5265                .zip(deferred_parse_date_columns)
5266            {
5267                if usecols.contains(&h) {
5268                    fh.push(h);
5269                    fc.push(c);
5270                    fr.push(r);
5271                    fd.push(d);
5272                }
5273            }
5274            (fh, fc, fr, fd)
5275        } else {
5276            (headers, columns, raw_columns, deferred_parse_date_columns)
5277        };
5278
5279    if let Some(ref parse_date_combinations) = options.parse_date_combinations {
5280        apply_parse_date_combinations(&mut headers, &mut columns, parse_date_combinations)?;
5281    }
5282
5283    if let Some(ref named) = options.parse_date_combinations_named {
5284        apply_parse_date_combinations_named(&mut headers, &mut columns, named)?;
5285    }
5286
5287    if let Some(ref parse_dates) = options.parse_dates {
5288        apply_csv_parse_dates(
5289            &headers,
5290            &mut columns,
5291            &raw_columns,
5292            &deferred_parse_date_columns,
5293            parse_dates,
5294            options,
5295            &na_set,
5296            &true_set,
5297            &false_set,
5298        )?;
5299    }
5300
5301    apply_pandas_csv_numeric_promotions(&mut columns);
5302
5303    // Apply dtype coercion if specified.
5304    if let Some(ref dtype_map) = options.dtype {
5305        for (i, name) in headers.iter().enumerate() {
5306            if let Some(&target_dt) = dtype_map.get(name) {
5307                let coerced = columns[i]
5308                    .iter()
5309                    .map(|v| fp_types::cast_scalar(v, target_dt))
5310                    .collect::<Result<Vec<_>, _>>()
5311                    .map_err(|err| IoError::Column(ColumnError::from(err)))?;
5312                columns[i] = coerced;
5313            }
5314        }
5315    }
5316
5317    let header_count = headers.len();
5318
5319    // Object-fallback columns should keep verbatim source text (pandas parity,
5320    // see build_csv_object_aware_column). Only safe when no parse-date transform
5321    // rewrote/added columns (which would desync raw_columns from columns); a
5322    // per-column dtype override is also excluded so explicit astype wins.
5323    let preserve_object_text = options.parse_dates.is_none()
5324        && options.parse_date_combinations.is_none()
5325        && options.parse_date_combinations_named.is_none();
5326    let dtype_forced = |name: &str| -> bool {
5327        options
5328            .dtype
5329            .as_ref()
5330            .is_some_and(|map| map.contains_key(name))
5331    };
5332
5333    // If index_col is set, extract that column as the index
5334    if let Some(ref idx_col_name) = options.index_col {
5335        let idx_pos = headers
5336            .iter()
5337            .position(|h| h == idx_col_name)
5338            .ok_or_else(|| IoError::MissingIndexColumn(idx_col_name.clone()))?;
5339
5340        let index_values = columns.remove(idx_pos);
5341        let index_labels: Vec<fp_index::IndexLabel> = index_values
5342            .into_iter()
5343            .map(|s| match s {
5344                Scalar::Int64(v) => fp_index::IndexLabel::Int64(v),
5345                Scalar::Utf8(v) => fp_index::IndexLabel::Utf8(v),
5346                Scalar::Float64(v) => fp_index::IndexLabel::Utf8(v.to_string()),
5347                Scalar::Bool(v) => {
5348                    fp_index::IndexLabel::Utf8(if v { "True" } else { "False" }.to_string())
5349                }
5350                // Typed null label (br-frankenpandas-8m6ay): pandas
5351                // read_csv(index_col=...) keeps a real nan index entry for an
5352                // empty cell. Kind-preserving bijection.
5353                Scalar::Null(kind) => fp_index::IndexLabel::Null(kind),
5354                Scalar::Timedelta64(v) => {
5355                    if v == Timedelta::NAT {
5356                        fp_index::IndexLabel::Utf8("<NaT>".to_owned())
5357                    } else {
5358                        fp_index::IndexLabel::Utf8(Timedelta::format(v))
5359                    }
5360                }
5361                Scalar::Datetime64(v) => {
5362                    if v == Timestamp::NAT {
5363                        fp_index::IndexLabel::Utf8("<NaT>".to_owned())
5364                    } else {
5365                        fp_index::IndexLabel::Utf8(format_datetime_ns(v))
5366                    }
5367                }
5368                Scalar::Period(v) => {
5369                    if v.ordinal == i64::MIN {
5370                        fp_index::IndexLabel::Utf8("<NaT>".to_owned())
5371                    } else {
5372                        fp_index::IndexLabel::Utf8(v.calendar_string())
5373                    }
5374                }
5375                Scalar::Interval(iv) => fp_index::IndexLabel::Utf8(format!("{iv}")),
5376            })
5377            .collect();
5378        // Per br-frankenpandas-l0vbr: pandas pd.read_csv(index_col='col')
5379        // sets result.index.name = 'col'.
5380        let index = Index::new(index_labels).set_name(idx_col_name);
5381
5382        let mut out_columns = BTreeMap::new();
5383        let mut column_order = Vec::with_capacity(headers.len() - 1);
5384        let mut col_idx = 0;
5385        for (orig_idx, _) in headers.iter().enumerate() {
5386            if orig_idx == idx_pos {
5387                continue;
5388            }
5389            let name = headers.get(orig_idx).cloned().unwrap_or_default();
5390            let column = if preserve_object_text && !dtype_forced(&name) {
5391                let (rb, ro) = strings_to_contiguous_raw(&raw_columns[orig_idx]);
5392                build_csv_object_aware_column(columns[col_idx].clone(), &rb, &ro)?
5393            } else {
5394                Column::from_values(columns[col_idx].clone())?
5395            };
5396            out_columns.insert(name.clone(), column);
5397            column_order.push(name);
5398            col_idx += 1;
5399        }
5400        Ok(DataFrame::new_with_column_order(
5401            index,
5402            out_columns,
5403            column_order,
5404        )?)
5405    } else {
5406        let mut out_columns = BTreeMap::new();
5407        let mut column_order = Vec::with_capacity(header_count);
5408        for (idx, values) in columns.into_iter().enumerate() {
5409            let name = headers.get(idx).cloned().unwrap_or_default();
5410            let column = if preserve_object_text && !dtype_forced(&name) {
5411                let (rb, ro) = strings_to_contiguous_raw(&raw_columns[idx]);
5412                build_csv_object_aware_column(values, &rb, &ro)?
5413            } else {
5414                Column::from_values(values)?
5415            };
5416            out_columns.insert(name.clone(), column);
5417            column_order.push(name);
5418        }
5419        let index = csv_default_unit_range_index(row_count);
5420        Ok(DataFrame::new_with_column_order(
5421            index,
5422            out_columns,
5423            column_order,
5424        )?)
5425    }
5426}
5427
5428/// Read CSV and promote the named columns into a row index / row MultiIndex.
5429///
5430/// For multiple names this mirrors pandas `index_col=[...]`.
5431pub fn read_csv_with_index_cols(
5432    input: &str,
5433    options: &CsvReadOptions,
5434    index_cols: &[&str],
5435) -> Result<DataFrame, IoError> {
5436    let frame = read_csv_with_options(input, options)?;
5437    promote_frame_index_columns(&frame, index_cols)
5438}
5439
5440// ── File-based CSV ─────────────────────────────────────────────────────
5441
5442pub fn read_csv(path: &Path) -> Result<DataFrame, IoError> {
5443    read_csv_with_options_path(path, &CsvReadOptions::default())
5444}
5445
5446pub fn read_csv_with_options_path(
5447    path: &Path,
5448    options: &CsvReadOptions,
5449) -> Result<DataFrame, IoError> {
5450    let content = std::fs::read_to_string(path)?;
5451    read_csv_with_options(&content, options)
5452}
5453
5454pub fn read_csv_with_index_cols_path(
5455    path: &Path,
5456    options: &CsvReadOptions,
5457    index_cols: &[&str],
5458) -> Result<DataFrame, IoError> {
5459    let content = std::fs::read_to_string(path)?;
5460    read_csv_with_index_cols(&content, options, index_cols)
5461}
5462
5463pub fn write_csv(frame: &DataFrame, path: &Path) -> Result<(), IoError> {
5464    let content = write_csv_string(frame)?;
5465    std::fs::write(path, content)?;
5466    Ok(())
5467}
5468
5469// ── read_table (tab-separated thin wrapper) ────────────────────────────
5470
5471/// Parse a tab-separated string, matching `pd.read_table(io.StringIO(s))`.
5472///
5473/// Equivalent to [`read_csv_str`] with `delimiter=b'\t'`. Other defaults
5474/// match pandas `read_table`: `header='infer'`, default NA values, no
5475/// index column promotion. Use [`read_table_with_options`] for full
5476/// option control.
5477pub fn read_table_str(input: &str) -> Result<DataFrame, IoError> {
5478    let opts = CsvReadOptions {
5479        delimiter: b'\t',
5480        ..CsvReadOptions::default()
5481    };
5482    read_csv_with_options(input, &opts)
5483}
5484
5485/// Parse a tab-separated string with explicit options. The caller-supplied
5486/// `options.delimiter` is preserved when it differs from the comma default
5487/// to allow override; otherwise it is forced to `b'\t'` so that the
5488/// pandas `read_table` semantics survive `CsvReadOptions::default()`.
5489pub fn read_table_with_options(
5490    input: &str,
5491    options: &CsvReadOptions,
5492) -> Result<DataFrame, IoError> {
5493    let mut effective = options.clone();
5494    if effective.delimiter == b',' {
5495        effective.delimiter = b'\t';
5496    }
5497    read_csv_with_options(input, &effective)
5498}
5499
5500/// Read a tab-separated file from disk, matching `pd.read_table(path)`.
5501pub fn read_table(path: &Path) -> Result<DataFrame, IoError> {
5502    let opts = CsvReadOptions {
5503        delimiter: b'\t',
5504        ..CsvReadOptions::default()
5505    };
5506    read_csv_with_options_path(path, &opts)
5507}
5508
5509/// Read a tab-separated file from disk with explicit options. The
5510/// caller-supplied delimiter is honored when it has been overridden from
5511/// the comma default; otherwise it is forced to `b'\t'`.
5512pub fn read_table_with_options_path(
5513    path: &Path,
5514    options: &CsvReadOptions,
5515) -> Result<DataFrame, IoError> {
5516    let mut effective = options.clone();
5517    if effective.delimiter == b',' {
5518        effective.delimiter = b'\t';
5519    }
5520    read_csv_with_options_path(path, &effective)
5521}
5522
5523// ── read_fwf (fixed-width file reader) ─────────────────────────────────
5524
5525/// Read a fixed-width file from disk, matching `pd.read_fwf(path, ...)`.
5526///
5527/// See [`read_fwf_str`] for the option semantics. When neither explicit
5528/// `colspecs` nor `widths` are supplied, column ranges are inferred from
5529/// non-whitespace runs.
5530pub fn read_fwf(path: &Path, options: &FwfReadOptions) -> Result<DataFrame, IoError> {
5531    let content = std::fs::read_to_string(path)?;
5532    read_fwf_str(&content, options)
5533}
5534
5535// ── Deferred reader surfaces ───────────────────────────────────────────
5536//
5537// pandas exposes pd.read_gbq / pd.read_sas / pd.read_spss (read_clipboard is
5538// implemented above via an OS subprocess backend). Each remaining one is out of
5539// scope for FrankenPandas's local file-format charter:
5540//
5541//   * read_gbq calls Google BigQuery (external service, GCP credentials).
5542//   * read_sas / read_spss are proprietary statistical-software formats with
5543//     no first-party Rust reader at parity (pandas calls into pyreadstat /
5544//     sas7bdat).
5545//
5546// Following the deferral precedent in fp-frame for plotting (see
5547// `plotting_deferred`), expose typed reject-closed entry points so callers
5548// can program against the surface and fall through to a clean error rather
5549// than a missing symbol.
5550
5551fn deferred_reader_error(method: &str, reason: &str) -> IoError {
5552    IoError::Deferred(format!(
5553        "{method}: in scope but deferred; {reason}. Use the pandas surface in the meantime."
5554    ))
5555}
5556
5557fn deferred_writer_error(method: &str, reason: &str) -> IoError {
5558    IoError::Deferred(format!(
5559        "{method}: in scope but deferred; {reason}. Use the pandas surface in the meantime."
5560    ))
5561}
5562
5563// ── Clipboard I/O (br-frankenpandas-261) ───────────────────────────────
5564//
5565// pandas `read_clipboard` / `to_clipboard` shell out to an OS clipboard helper
5566// (pyperclip → xclip/xsel/wl-clipboard/pbcopy). FrankenPandas mirrors that with
5567// a zero-dependency subprocess backend: no `arboard`/X11 dep tree is pulled in,
5568// and the pure TSV transform (`read_clipboard_str` / the `to_clipboard` writer)
5569// is fully testable without a live clipboard. When no backend binary is
5570// installed (e.g. a headless CI box) the call returns a clear `Clipboard`
5571// error, exactly as pandas raises `PyperclipException`.
5572
5573/// Backends tried in order for READING the clipboard: `(binary, args)`.
5574const CLIPBOARD_READ_BACKENDS: &[(&str, &[&str])] = &[
5575    ("wl-paste", &["-n"]),
5576    ("xclip", &["-selection", "clipboard", "-o"]),
5577    ("xsel", &["-b", "-o"]),
5578    ("pbpaste", &[]),
5579];
5580
5581/// Backends tried in order for WRITING the clipboard: `(binary, args)`.
5582const CLIPBOARD_WRITE_BACKENDS: &[(&str, &[&str])] = &[
5583    ("wl-copy", &[]),
5584    ("xclip", &["-selection", "clipboard"]),
5585    ("xsel", &["-b", "-i"]),
5586    ("pbcopy", &[]),
5587];
5588
5589fn clipboard_get() -> Result<String, IoError> {
5590    let mut last =
5591        String::from("no clipboard backend found (tried wl-paste, xclip, xsel, pbpaste)");
5592    for (cmd, args) in CLIPBOARD_READ_BACKENDS {
5593        match std::process::Command::new(cmd).args(*args).output() {
5594            Ok(out) if out.status.success() => {
5595                return String::from_utf8(out.stdout)
5596                    .map_err(|e| IoError::Clipboard(format!("clipboard text is not UTF-8: {e}")));
5597            }
5598            Ok(_) => last = format!("{cmd}: exited non-zero"),
5599            Err(_) => {} // binary not installed — try the next backend
5600        }
5601    }
5602    Err(IoError::Clipboard(last))
5603}
5604
5605fn clipboard_set(text: &str) -> Result<(), IoError> {
5606    use std::io::Write as _;
5607    let mut last = String::from("no clipboard backend found (tried wl-copy, xclip, xsel, pbcopy)");
5608    for (cmd, args) in CLIPBOARD_WRITE_BACKENDS {
5609        let spawned = std::process::Command::new(cmd)
5610            .args(*args)
5611            .stdin(std::process::Stdio::piped())
5612            .stdout(std::process::Stdio::null())
5613            .stderr(std::process::Stdio::null())
5614            .spawn();
5615        let mut child = match spawned {
5616            Ok(child) => child,
5617            Err(_) => continue, // binary not installed — try the next backend
5618        };
5619        if let Some(mut stdin) = child.stdin.take()
5620            && stdin.write_all(text.as_bytes()).is_err()
5621        {
5622            last = format!("{cmd}: writing to stdin failed");
5623            continue;
5624        }
5625        match child.wait() {
5626            Ok(status) if status.success() => return Ok(()),
5627            Ok(_) => last = format!("{cmd}: exited non-zero"),
5628            Err(e) => last = format!("{cmd}: {e}"),
5629        }
5630    }
5631    Err(IoError::Clipboard(last))
5632}
5633
5634/// Parse clipboard text into a `DataFrame` — the pure, backend-free core of
5635/// [`read_clipboard`]. Tab-separated, matching the bytes `to_clipboard` writes
5636/// (pandas `excel=True`).
5637pub fn read_clipboard_str(text: &str) -> Result<DataFrame, IoError> {
5638    let options = CsvReadOptions {
5639        delimiter: b'\t',
5640        ..CsvReadOptions::default()
5641    };
5642    read_csv_with_options(text, &options)
5643}
5644
5645/// Read the system clipboard, matching `pd.read_clipboard()`. The clipboard is
5646/// fetched via the first available OS backend (`wl-paste`/`xclip`/`xsel`/
5647/// `pbpaste`) and parsed as TSV (the format [`DataFrameIoExt::to_clipboard`]
5648/// writes). Returns a `Clipboard` error when no backend is installed.
5649pub fn read_clipboard() -> Result<DataFrame, IoError> {
5650    read_clipboard_str(&clipboard_get()?)
5651}
5652
5653/// Serialize a frame to the tab-separated bytes `to_clipboard` puts on the
5654/// clipboard (pandas `excel=True`, index included). Pure/testable.
5655fn clipboard_tsv(frame: &DataFrame) -> Result<String, IoError> {
5656    let options = CsvWriteOptions {
5657        delimiter: b'\t',
5658        include_index: true,
5659        ..CsvWriteOptions::default()
5660    };
5661    write_csv_string_with_options(frame, &options)
5662}
5663
5664/// Reject-closed BigQuery reader, matching `pd.read_gbq(query, project_id)`.
5665pub fn read_gbq(_query: &str, _project_id: Option<&str>) -> Result<DataFrame, IoError> {
5666    Err(deferred_reader_error(
5667        "read_gbq",
5668        "Google BigQuery integration is outside FrankenPandas's local file-format scope",
5669    ))
5670}
5671
5672/// Reject-closed SAS reader, matching `pd.read_sas(path)`.
5673pub fn read_sas(_path: &Path) -> Result<DataFrame, IoError> {
5674    Err(deferred_reader_error(
5675        "read_sas",
5676        "no first-party Rust SAS sas7bdat/xport reader exists at pandas-parity yet",
5677    ))
5678}
5679
5680/// Reject-closed SPSS reader, matching `pd.read_spss(path)`.
5681pub fn read_spss(_path: &Path) -> Result<DataFrame, IoError> {
5682    Err(deferred_reader_error(
5683        "read_spss",
5684        "no first-party Rust SPSS .sav reader exists at pandas-parity yet",
5685    ))
5686}
5687
5688// ── File-based Markdown / LaTeX ────────────────────────────────────────
5689
5690/// Write a DataFrame to a Markdown table file.
5691pub fn write_markdown(frame: &DataFrame, path: &Path) -> Result<(), IoError> {
5692    write_markdown_with_options(frame, path, &MarkdownWriteOptions::default())
5693}
5694
5695/// Write a DataFrame to a Markdown table file with explicit options.
5696pub fn write_markdown_with_options(
5697    frame: &DataFrame,
5698    path: &Path,
5699    options: &MarkdownWriteOptions,
5700) -> Result<(), IoError> {
5701    let content = write_markdown_string_with_options(frame, options)?;
5702    std::fs::write(path, content)?;
5703    Ok(())
5704}
5705
5706/// Write a DataFrame to a LaTeX tabular file.
5707pub fn write_latex(frame: &DataFrame, path: &Path) -> Result<(), IoError> {
5708    write_latex_with_options(frame, path, &LatexWriteOptions::default())
5709}
5710
5711/// Write a DataFrame to a LaTeX tabular file with explicit options.
5712pub fn write_latex_with_options(
5713    frame: &DataFrame,
5714    path: &Path,
5715    options: &LatexWriteOptions,
5716) -> Result<(), IoError> {
5717    let content = write_latex_string_with_options(frame, options)?;
5718    std::fs::write(path, content)?;
5719    Ok(())
5720}
5721
5722// ── File-based HTML ────────────────────────────────────────────────────
5723
5724pub fn read_html(path: &Path) -> Result<DataFrame, IoError> {
5725    read_html_with_options(path, &HtmlReadOptions::default())
5726}
5727
5728pub fn read_html_with_options(
5729    path: &Path,
5730    options: &HtmlReadOptions,
5731) -> Result<DataFrame, IoError> {
5732    let content = std::fs::read_to_string(path)?;
5733    read_html_str_with_options(&content, options)
5734}
5735
5736pub fn write_html(frame: &DataFrame, path: &Path) -> Result<(), IoError> {
5737    write_html_with_options(frame, path, &HtmlWriteOptions::default())
5738}
5739
5740pub fn write_html_with_options(
5741    frame: &DataFrame,
5742    path: &Path,
5743    options: &HtmlWriteOptions,
5744) -> Result<(), IoError> {
5745    let content = write_html_string_with_options(frame, options)?;
5746    std::fs::write(path, content)?;
5747    Ok(())
5748}
5749
5750// ── File-based XML ─────────────────────────────────────────────────────
5751
5752pub fn write_xml(frame: &DataFrame, path: &Path) -> Result<(), IoError> {
5753    write_xml_with_options(frame, path, &XmlWriteOptions::default())
5754}
5755
5756pub fn write_xml_with_options(
5757    frame: &DataFrame,
5758    path: &Path,
5759    options: &XmlWriteOptions,
5760) -> Result<(), IoError> {
5761    let content = write_xml_string_with_options(frame, options)?;
5762    std::fs::write(path, content)?;
5763    Ok(())
5764}
5765
5766// ── File-based XML readers ─────────────────────────────────────────────
5767
5768pub fn read_xml(path: &Path) -> Result<DataFrame, IoError> {
5769    read_xml_with_options(path, &XmlReadOptions::default())
5770}
5771
5772pub fn read_xml_with_options(path: &Path, options: &XmlReadOptions) -> Result<DataFrame, IoError> {
5773    let content = std::fs::read_to_string(path)?;
5774    read_xml_str_with_options(&content, options)
5775}
5776
5777// ── JSON IO ────────────────────────────────────────────────────────────
5778
5779fn json_value_to_scalar(val: &serde_json::Value) -> Scalar {
5780    match val {
5781        serde_json::Value::Null => Scalar::Null(NullKind::Null),
5782        serde_json::Value::Bool(b) => Scalar::Bool(*b),
5783        serde_json::Value::Number(n) => {
5784            if let Some(i) = n.as_i64() {
5785                Scalar::Int64(i)
5786            } else if let Some(f) = n.as_f64() {
5787                Scalar::Float64(f)
5788            } else {
5789                Scalar::Utf8(n.to_string())
5790            }
5791        }
5792        serde_json::Value::String(s) => Scalar::Utf8(s.clone()),
5793        other => Scalar::Utf8(other.to_string()),
5794    }
5795}
5796
5797fn parse_json_value_allowing_pandas_nan(input: &str) -> Result<serde_json::Value, IoError> {
5798    match serde_json::from_str(input) {
5799        Ok(value) => Ok(value),
5800        Err(original) => {
5801            let normalized = normalize_bare_json_nan_tokens(input);
5802            if normalized == input {
5803                return Err(original.into());
5804            }
5805            serde_json::from_str(&normalized).map_err(IoError::from)
5806        }
5807    }
5808}
5809
5810fn normalize_bare_json_nan_tokens(input: &str) -> String {
5811    let mut output = String::with_capacity(input.len());
5812    let mut index = 0;
5813    let mut in_string = false;
5814    let mut escaped = false;
5815
5816    while index < input.len() {
5817        let rest = &input[index..];
5818        let Some(ch) = rest.chars().next() else {
5819            break;
5820        };
5821
5822        if in_string {
5823            output.push(ch);
5824            index += ch.len_utf8();
5825            if escaped {
5826                escaped = false;
5827            } else if ch == '\\' {
5828                escaped = true;
5829            } else if ch == '"' {
5830                in_string = false;
5831            }
5832            continue;
5833        }
5834
5835        if ch == '"' {
5836            in_string = true;
5837            output.push(ch);
5838            index += ch.len_utf8();
5839            continue;
5840        }
5841
5842        if rest.starts_with("NaN")
5843            && is_json_value_start_boundary(input, index)
5844            && is_json_value_end_boundary(input, index + 3)
5845        {
5846            output.push_str("null");
5847            index += 3;
5848            continue;
5849        }
5850
5851        output.push(ch);
5852        index += ch.len_utf8();
5853    }
5854
5855    output
5856}
5857
5858fn is_json_value_start_boundary(input: &str, index: usize) -> bool {
5859    input[..index]
5860        .chars()
5861        .rev()
5862        .find(|ch| !ch.is_whitespace())
5863        .is_none_or(|ch| matches!(ch, ':' | '[' | ','))
5864}
5865
5866fn is_json_value_end_boundary(input: &str, index: usize) -> bool {
5867    input[index..]
5868        .chars()
5869        .find(|ch| !ch.is_whitespace())
5870        .is_none_or(|ch| matches!(ch, ',' | ']' | '}'))
5871}
5872
5873fn column_from_json_values(values: Vec<Scalar>) -> Result<Column, IoError> {
5874    let saw_utf8 = values.iter().any(|value| matches!(value, Scalar::Utf8(_)));
5875    let saw_missing = values.iter().any(Scalar::is_missing);
5876    let saw_numeric_like = values.iter().any(|value| {
5877        matches!(
5878            value,
5879            Scalar::Int64(_) | Scalar::Float64(_) | Scalar::Bool(_)
5880        )
5881    });
5882
5883    if !saw_utf8 && saw_missing && (saw_numeric_like || values.iter().all(Scalar::is_missing)) {
5884        let promoted = values
5885            .into_iter()
5886            .map(|value| match value {
5887                Scalar::Int64(value) => Scalar::Float64(value as f64),
5888                Scalar::Bool(value) => Scalar::Float64(if value { 1.0 } else { 0.0 }),
5889                Scalar::Null(_) => Scalar::Null(NullKind::NaN),
5890                other => other,
5891            })
5892            .collect();
5893        return Column::new(DType::Float64, promoted).map_err(IoError::from);
5894    }
5895
5896    Column::from_values(values).map_err(IoError::from)
5897}
5898
5899fn scalar_to_json(scalar: &Scalar) -> serde_json::Value {
5900    match scalar {
5901        Scalar::Null(_) => serde_json::Value::Null,
5902        Scalar::Bool(b) => serde_json::Value::Bool(*b),
5903        Scalar::Int64(i) => serde_json::json!(*i),
5904        Scalar::Float64(f) => {
5905            if f.is_nan() || f.is_infinite() {
5906                serde_json::Value::Null
5907            } else {
5908                serde_json::json!(*f)
5909            }
5910        }
5911        Scalar::Utf8(s) => serde_json::Value::String(s.clone()),
5912        // pandas to_json (default date_format='epoch', date_unit='ms') serializes
5913        // datetime64 and timedelta64 as epoch-MILLISECOND integers, not strings.
5914        // (br-frankenpandas-lb0iu)
5915        Scalar::Timedelta64(v) => {
5916            if *v == Timedelta::NAT {
5917                serde_json::Value::Null
5918            } else {
5919                serde_json::json!(*v / 1_000_000)
5920            }
5921        }
5922        Scalar::Datetime64(v) => {
5923            if *v == Timestamp::NAT {
5924                serde_json::Value::Null
5925            } else {
5926                serde_json::json!(*v / 1_000_000)
5927            }
5928        }
5929        Scalar::Period(p) => {
5930            if p.ordinal == i64::MIN {
5931                serde_json::Value::Null
5932            } else {
5933                serde_json::Value::String(p.calendar_string())
5934            }
5935        }
5936        Scalar::Interval(iv) => serde_json::Value::String(format!("{iv}")),
5937    }
5938}
5939
5940fn column_promotes_int_json_values_to_float(_values: &[Scalar]) -> bool {
5941    // DISC-011: Nullable extension Int64 dtype parity.
5942    // Pandas (since v0.24) preserves Int64 via a separate validity mask when
5943    // null values are present. We now match: Int64 values serialize as integers,
5944    // Null values serialize as null, no Float64 promotion.
5945    false
5946}
5947
5948fn scalar_to_json_with_column_promotion(
5949    scalar: &Scalar,
5950    promote_int_to_float: bool,
5951) -> serde_json::Value {
5952    if promote_int_to_float && let Scalar::Int64(v) = scalar {
5953        return serde_json::json!(*v as f64);
5954    }
5955    scalar_to_json(scalar)
5956}
5957
5958fn json_value_to_index_label(value: &serde_json::Value) -> IndexLabel {
5959    match value {
5960        serde_json::Value::Number(n) => n
5961            .as_i64()
5962            .map(IndexLabel::Int64)
5963            .unwrap_or_else(|| IndexLabel::Utf8(n.to_string())),
5964        serde_json::Value::String(s) => IndexLabel::Utf8(s.clone()),
5965        serde_json::Value::Bool(b) => IndexLabel::Utf8(b.to_string()),
5966        serde_json::Value::Null => IndexLabel::Utf8("null".to_owned()),
5967        other => IndexLabel::Utf8(other.to_string()),
5968    }
5969}
5970
5971fn json_value_to_column_name(value: &serde_json::Value) -> String {
5972    match value {
5973        serde_json::Value::String(s) => s.clone(),
5974        serde_json::Value::Number(n) => n.to_string(),
5975        serde_json::Value::Bool(b) => b.to_string(),
5976        serde_json::Value::Null => "null".to_owned(),
5977        other => other.to_string(),
5978    }
5979}
5980
5981fn json_key_to_index_label(value: &str) -> IndexLabel {
5982    value
5983        .parse::<i64>()
5984        .map(IndexLabel::Int64)
5985        .unwrap_or_else(|_| IndexLabel::Utf8(value.to_owned()))
5986}
5987
5988fn index_label_to_json(label: &IndexLabel) -> serde_json::Value {
5989    match label {
5990        IndexLabel::Int64(v) => serde_json::json!(*v),
5991        IndexLabel::Float64(v) => serde_json::json!(v.0),
5992        IndexLabel::Bool(b) => serde_json::json!(*b),
5993        IndexLabel::Utf8(v) => serde_json::Value::String(v.clone()),
5994        // Epoch-millisecond ints, matching pandas to_json (date_unit='ms') and
5995        // the value path above — previously emitted raw nanoseconds, which
5996        // matched neither pandas nor FP's own value serialization.
5997        // (br-frankenpandas-lb0iu)
5998        //
5999        // A NaT label (the i64::MIN sentinel) must serialize as JSON null, NOT
6000        // `i64::MIN / 1e6` (-9223372036854775) — the latter is neither pandas nor
6001        // FP's own value path (`scalar_to_json_value`), which already null-checks
6002        // `Timestamp::NAT`/`Timedelta::NAT`. (br-frankenpandas-natjson)
6003        IndexLabel::Timedelta64(ns) => {
6004            if *ns == fp_types::Timedelta::NAT {
6005                serde_json::Value::Null
6006            } else {
6007                serde_json::json!(*ns / 1_000_000)
6008            }
6009        }
6010        IndexLabel::Datetime64(ns) => {
6011            if *ns == fp_types::Timestamp::NAT {
6012                serde_json::Value::Null
6013            } else {
6014                serde_json::json!(*ns / 1_000_000)
6015            }
6016        }
6017        // pandas to_json renders a missing label as JSON null.
6018        IndexLabel::Null(_) => serde_json::Value::Null,
6019    }
6020}
6021
6022/// Stringified index label for use as a JSON object key (columns/index orients).
6023/// Temporal labels become epoch-millisecond strings, matching pandas to_json
6024/// (e.g. a 2020-01-01 index key is "1577836800000", not "2020-01-01 00:00:00").
6025/// (br-frankenpandas-lb0iu)
6026fn index_label_json_key(label: &IndexLabel) -> String {
6027    match label {
6028        // NaT (i64::MIN) as an object key renders as "null" rather than the
6029        // sentinel's epoch garbage (-9223372036854775), matching the JSON-null
6030        // the value path emits for a missing temporal label.
6031        // (br-frankenpandas-natjson)
6032        IndexLabel::Datetime64(ns) if *ns == fp_types::Timestamp::NAT => "null".to_owned(),
6033        IndexLabel::Timedelta64(ns) if *ns == fp_types::Timedelta::NAT => "null".to_owned(),
6034        IndexLabel::Datetime64(ns) | IndexLabel::Timedelta64(ns) => (*ns / 1_000_000).to_string(),
6035        other => other.to_string(),
6036    }
6037}
6038
6039const SYNTHETIC_ROW_MULTIINDEX_PREFIX: &str = "__index_level_";
6040
6041fn index_label_to_scalar_value(label: &IndexLabel) -> Scalar {
6042    match label {
6043        IndexLabel::Int64(v) => Scalar::Int64(*v),
6044        IndexLabel::Float64(v) => Scalar::Float64(v.0),
6045        IndexLabel::Bool(b) => Scalar::Bool(*b),
6046        IndexLabel::Utf8(v) => Scalar::Utf8(v.clone()),
6047        IndexLabel::Timedelta64(v) => Scalar::Timedelta64(*v),
6048        // Keep the TYPED Datetime64 scalar, like the Timedelta64 arm above —
6049        // materializing a MultiIndex level into a column must preserve its dtype
6050        // (pandas reset_index keeps a datetime level as datetime64, not object).
6051        // The old `Scalar::Utf8(format_datetime_ns(..))` downgrade made datetime
6052        // levels render as ISO strings in to_json (inconsistent with a single
6053        // DatetimeIndex's epoch-ms ints) and bypassed to_csv's column-uniform
6054        // datetime format. (br-frankenpandas-mdt64)
6055        IndexLabel::Datetime64(v) => Scalar::Datetime64(*v),
6056        // Typed-null label round-trips to the same-kind missing scalar.
6057        IndexLabel::Null(kind) => Scalar::Null(*kind),
6058    }
6059}
6060
6061fn synthetic_row_multiindex_names(nlevels: usize) -> Vec<String> {
6062    (0..nlevels)
6063        .map(|level| format!("{SYNTHETIC_ROW_MULTIINDEX_PREFIX}{level}__"))
6064        .collect()
6065}
6066
6067fn materialize_row_multiindex_columns(
6068    frame: &DataFrame,
6069    names: &[String],
6070) -> Result<DataFrame, IoError> {
6071    let Some(row_multiindex) = frame.row_multiindex() else {
6072        return Ok(frame.clone());
6073    };
6074
6075    let mut columns = BTreeMap::new();
6076    let mut column_order = Vec::with_capacity(names.len() + frame.column_names().len());
6077    for (level, name) in names.iter().enumerate() {
6078        let level_index = row_multiindex.get_level_values(level)?;
6079        let values = level_index
6080            .labels()
6081            .iter()
6082            .map(index_label_to_scalar_value)
6083            .collect::<Vec<_>>();
6084        columns.insert(name.clone(), Column::from_values(values)?);
6085        column_order.push(name.clone());
6086    }
6087
6088    for name in frame.column_names() {
6089        let column = frame
6090            .column(name)
6091            .ok_or_else(|| {
6092                IoError::Frame(FrameError::CompatibilityRejected(format!(
6093                    "column not found: '{name}'"
6094                )))
6095            })?
6096            .clone();
6097        columns.insert(name.clone(), column);
6098        column_order.push(name.clone());
6099    }
6100
6101    let index = Index::from_i64((0..frame.len() as i64).collect());
6102    DataFrame::new_with_column_order(index, columns, column_order).map_err(IoError::from)
6103}
6104
6105fn materialize_named_row_multiindex_columns(frame: &DataFrame) -> Result<DataFrame, IoError> {
6106    if frame.row_multiindex().is_some() {
6107        frame.reset_index(false).map_err(IoError::from)
6108    } else {
6109        Ok(frame.clone())
6110    }
6111}
6112
6113fn materialize_synthetic_row_multiindex_columns(frame: &DataFrame) -> Result<DataFrame, IoError> {
6114    let Some(row_multiindex) = frame.row_multiindex() else {
6115        return Ok(frame.clone());
6116    };
6117    let names = synthetic_row_multiindex_names(row_multiindex.nlevels());
6118    materialize_row_multiindex_columns(frame, &names)
6119}
6120
6121fn promote_frame_index_columns(
6122    frame: &DataFrame,
6123    index_cols: &[&str],
6124) -> Result<DataFrame, IoError> {
6125    if index_cols.is_empty() {
6126        return Ok(frame.clone());
6127    }
6128    if index_cols.len() == 1 {
6129        frame.set_index(index_cols[0], true).map_err(IoError::from)
6130    } else {
6131        frame
6132            .set_index_multi(index_cols, true, "|")
6133            .map_err(IoError::from)
6134    }
6135}
6136
6137fn detect_synthetic_row_multiindex_columns(frame: &DataFrame) -> Vec<String> {
6138    let mut out = Vec::new();
6139    for (level, name) in frame.column_names().iter().enumerate() {
6140        let expected = format!("{SYNTHETIC_ROW_MULTIINDEX_PREFIX}{level}__");
6141        if **name == expected {
6142            out.push(expected);
6143        } else {
6144            break;
6145        }
6146    }
6147    out
6148}
6149
6150fn promote_synthetic_row_multiindex_if_present(frame: &DataFrame) -> Result<DataFrame, IoError> {
6151    let synthetic_cols = detect_synthetic_row_multiindex_columns(frame);
6152    if synthetic_cols.len() < 2 {
6153        return Ok(frame.clone());
6154    }
6155    let refs = synthetic_cols
6156        .iter()
6157        .map(String::as_str)
6158        .collect::<Vec<_>>();
6159    promote_frame_index_columns(frame, &refs)
6160}
6161
6162/// Fast path for `read_json_str(JsonOrient::Records)`: scan a FLAT records array
6163/// (`[{...}, ...]` whose values are only number / string / bool / null) directly into
6164/// per-column `Vec<Scalar>` builders, skipping the `serde_json::Value` tree + the
6165/// per-record map allocation. Returns `Ok(None)` to defer to the generic Value-tree
6166/// path on ANY deviation (nested value, escaped string/key, `NaN`/`Infinity` token,
6167/// trailing garbage, malformed structure), so the produced frame is BIT-IDENTICAL to
6168/// the generic path for every input it accepts:
6169/// - each `Scalar` is built exactly as `json_value_to_scalar` would (number tokens are
6170///   parsed by `serde_json`, so `as_i64`/`as_f64` classification is identical);
6171/// - column order is first-seen (same as the generic path's first-seen collection);
6172/// - a key missing from a record backfills `Null`, a duplicate key keeps the last value
6173///   (matching `serde_json`'s `preserve_order` map);
6174/// - the frame is assembled with the same `column_from_json_values` +
6175///   `promote_synthetic_row_multiindex_if_present` tail.
6176///
6177/// Depth- and string-aware scan of a records array `[ {...}, {...}, … ]`: returns the
6178/// body byte range `[body_start, body_end)` (just inside `[` … `]`) and the byte offset
6179/// of every DEPTH-1 (record-separating) comma. `None` unless the input is a non-empty
6180/// top-level array. Used to split a records JSON into whole-record byte ranges for
6181/// parallel parsing; correctness is verified by the flat scanner re-parsing each range.
6182fn scan_json_record_boundaries(s: &[u8]) -> Option<(usize, usize, Vec<usize>)> {
6183    let n = s.len();
6184    let mut i = 0;
6185    while i < n && matches!(s[i], b' ' | b'\t' | b'\n' | b'\r') {
6186        i += 1;
6187    }
6188    if i >= n || s[i] != b'[' {
6189        return None;
6190    }
6191    let body_start = i + 1;
6192    let mut depth = 0i32;
6193    let mut in_str = false;
6194    let mut esc = false;
6195    let mut commas: Vec<usize> = Vec::new();
6196    let mut body_end = None;
6197    let mut j = i;
6198    while j < n {
6199        let c = s[j];
6200        if in_str {
6201            if esc {
6202                esc = false;
6203            } else if c == b'\\' {
6204                esc = true;
6205            } else if c == b'"' {
6206                in_str = false;
6207            }
6208        } else {
6209            match c {
6210                b'"' => in_str = true,
6211                b'{' | b'[' => depth += 1,
6212                b'}' | b']' => {
6213                    depth -= 1;
6214                    if depth == 0 {
6215                        body_end = Some(j);
6216                        break;
6217                    }
6218                }
6219                b',' if depth == 1 => commas.push(j),
6220                _ => {}
6221            }
6222        }
6223        j += 1;
6224    }
6225    let body_end = body_end?;
6226    // Trailing content after the closing `]` must be whitespace only.
6227    let mut t = body_end + 1;
6228    while t < n && matches!(s[t], b' ' | b'\t' | b'\n' | b'\r') {
6229        t += 1;
6230    }
6231    if t != n {
6232        return None;
6233    }
6234    if body_start >= body_end {
6235        return None; // empty array -> generic path
6236    }
6237    Some((body_start, body_end, commas))
6238}
6239
6240/// Parse a flat records SEQUENCE `{...},{...},…` occupying `s[lo..hi]` (no surrounding
6241/// `[` `]`; `hi` is a record boundary or the closing `]` position) into per-column
6242/// `Vec<Scalar>` with first-seen column order and `Null` backfill for absent keys —
6243/// the exact same value handling as [`try_read_json_records_flat`] (numbers via
6244/// `serde_json::from_str::<Number>`), factored out so parallel workers can each parse a
6245/// byte range. Returns `None` on anything the flat scanner bails on. `rec` = row count.
6246fn parse_json_records_range(
6247    s: &[u8],
6248    lo: usize,
6249    hi: usize,
6250) -> Option<(Vec<String>, Vec<Vec<Scalar>>, usize)> {
6251    let mut i = lo;
6252    macro_rules! ws {
6253        () => {
6254            while i < hi && matches!(s[i], b' ' | b'\t' | b'\n' | b'\r') {
6255                i += 1;
6256            }
6257        };
6258    }
6259    let mut col_names: Vec<String> = Vec::new();
6260    let mut cols: Vec<Vec<Scalar>> = Vec::new();
6261    let mut last_seen: Vec<usize> = Vec::new();
6262    let mut name_to_idx: std::collections::HashMap<Vec<u8>, usize> =
6263        std::collections::HashMap::new();
6264    let mut rec: usize = 0;
6265    loop {
6266        ws!();
6267        if i >= hi {
6268            break;
6269        }
6270        if s[i] != b'{' {
6271            return None;
6272        }
6273        i += 1;
6274        loop {
6275            ws!();
6276            if i < hi && s[i] == b'}' {
6277                i += 1;
6278                break;
6279            }
6280            if i >= hi || s[i] != b'"' {
6281                return None;
6282            }
6283            i += 1;
6284            let kstart = i;
6285            while i < hi && s[i] != b'"' {
6286                if s[i] == b'\\' {
6287                    return None;
6288                }
6289                i += 1;
6290            }
6291            if i >= hi {
6292                return None;
6293            }
6294            let key = &s[kstart..i];
6295            i += 1;
6296            ws!();
6297            if i >= hi || s[i] != b':' {
6298                return None;
6299            }
6300            i += 1;
6301            ws!();
6302            if i >= hi {
6303                return None;
6304            }
6305            let scalar = match s[i] {
6306                b'-' | b'0'..=b'9' => {
6307                    let vstart = i;
6308                    if s[i] == b'-' {
6309                        i += 1;
6310                    }
6311                    let mut any = false;
6312                    while i < hi && matches!(s[i], b'0'..=b'9' | b'.' | b'e' | b'E' | b'+' | b'-') {
6313                        any = true;
6314                        i += 1;
6315                    }
6316                    if !any {
6317                        return None;
6318                    }
6319                    let Ok(numstr) = std::str::from_utf8(&s[vstart..i]) else {
6320                        return None;
6321                    };
6322                    match serde_json::from_str::<serde_json::Number>(numstr) {
6323                        Ok(num) => {
6324                            if let Some(v) = num.as_i64() {
6325                                Scalar::Int64(v)
6326                            } else if let Some(v) = num.as_f64() {
6327                                Scalar::Float64(v)
6328                            } else {
6329                                Scalar::Utf8(num.to_string())
6330                            }
6331                        }
6332                        Err(_) => return None,
6333                    }
6334                }
6335                b'"' => {
6336                    i += 1;
6337                    let vstart = i;
6338                    while i < hi && s[i] != b'"' {
6339                        if s[i] == b'\\' {
6340                            return None;
6341                        }
6342                        i += 1;
6343                    }
6344                    if i >= hi {
6345                        return None;
6346                    }
6347                    let raw = &s[vstart..i];
6348                    i += 1;
6349                    match std::str::from_utf8(raw) {
6350                        Ok(st) => Scalar::Utf8(st.to_owned()),
6351                        Err(_) => return None,
6352                    }
6353                }
6354                b't' if s[i..hi].starts_with(b"true") => {
6355                    i += 4;
6356                    Scalar::Bool(true)
6357                }
6358                b'f' if s[i..hi].starts_with(b"false") => {
6359                    i += 5;
6360                    Scalar::Bool(false)
6361                }
6362                b'n' if s[i..hi].starts_with(b"null") => {
6363                    i += 4;
6364                    Scalar::Null(NullKind::Null)
6365                }
6366                _ => return None,
6367            };
6368            let ci = match name_to_idx.get(key) {
6369                Some(&c) => c,
6370                None => {
6371                    let c = cols.len();
6372                    name_to_idx.insert(key.to_vec(), c);
6373                    col_names.push(String::from_utf8_lossy(key).into_owned());
6374                    let mut v: Vec<Scalar> = Vec::new();
6375                    v.resize(rec, Scalar::Null(NullKind::Null));
6376                    cols.push(v);
6377                    last_seen.push(usize::MAX);
6378                    c
6379                }
6380            };
6381            if last_seen[ci] == rec {
6382                *cols[ci].last_mut().expect("seen this record => non-empty") = scalar;
6383            } else {
6384                cols[ci].push(scalar);
6385                last_seen[ci] = rec;
6386            }
6387            ws!();
6388            if i < hi && s[i] == b',' {
6389                i += 1;
6390                continue;
6391            }
6392        }
6393        for c in 0..cols.len() {
6394            if last_seen[c] != rec {
6395                cols[c].push(Scalar::Null(NullKind::Null));
6396            }
6397        }
6398        rec += 1;
6399        ws!();
6400        if i < hi && s[i] == b',' {
6401            i += 1;
6402            continue;
6403        }
6404        if i >= hi {
6405            break;
6406        }
6407        return None;
6408    }
6409    Some((col_names, cols, rec))
6410}
6411
6412/// Parallel records fast path: split the array at record boundaries, parse the chunks
6413/// concurrently (each a `parse_json_records_range`), and merge. Returns `None` (defer to
6414/// the serial scanner / Value path) unless it is a large FULLY-HOMOGENEOUS records array
6415/// — every chunk must report the IDENTICAL first-seen `col_names`, which guarantees the
6416/// merged columns equal the serial scanner's output (concatenation preserves record
6417/// order; the serial first-seen order equals the shared per-chunk order). Bit-identical:
6418/// same per-value parsing, same column order, same `column_from_json_values` +
6419/// `promote_synthetic_row_multiindex_if_present` assembly.
6420fn try_read_json_records_flat_parallel(input: &str) -> Result<Option<DataFrame>, IoError> {
6421    let s = input.as_bytes();
6422    let Some((body_start, body_end, commas)) = scan_json_record_boundaries(s) else {
6423        return Ok(None);
6424    };
6425    let nrec = commas.len() + 1;
6426    const PAR_MIN_RECORDS: usize = 50_000;
6427    const PAR_MIN_RECORDS_PER_WORKER: usize = 16_384;
6428    if nrec < PAR_MIN_RECORDS {
6429        return Ok(None);
6430    }
6431    let workers = std::thread::available_parallelism()
6432        .map_or(1, std::num::NonZeroUsize::get)
6433        .min(16)
6434        .min(nrec / PAR_MIN_RECORDS_PER_WORKER)
6435        .max(1);
6436    if workers < 2 {
6437        return Ok(None);
6438    }
6439    let per = nrec.div_ceil(workers);
6440    let mut ranges: Vec<(usize, usize)> = Vec::with_capacity(workers);
6441    let mut rstart = 0;
6442    while rstart < nrec {
6443        let rend = (rstart + per).min(nrec);
6444        let lo = if rstart == 0 {
6445            body_start
6446        } else {
6447            commas[rstart - 1] + 1
6448        };
6449        let hi = if rend == nrec {
6450            body_end
6451        } else {
6452            commas[rend - 1]
6453        };
6454        ranges.push((lo, hi));
6455        rstart = rend;
6456    }
6457    #[allow(clippy::type_complexity)]
6458    let parsed: Vec<Option<(Vec<String>, Vec<Vec<Scalar>>, usize)>> = std::thread::scope(|scope| {
6459        ranges
6460            .iter()
6461            .map(|&(lo, hi)| scope.spawn(move || parse_json_records_range(s, lo, hi)))
6462            .collect::<Vec<_>>()
6463            .into_iter()
6464            .map(|h| h.join().expect("json parse thread"))
6465            .collect()
6466    });
6467    let Some(parts) = parsed.into_iter().collect::<Option<Vec<_>>>() else {
6468        return Ok(None);
6469    };
6470    // Homogeneity gate: every chunk must share the FIRST chunk's exact column order.
6471    if parts[0].0.is_empty() {
6472        return Ok(None);
6473    }
6474    let names: Vec<String> = parts[0].0.clone();
6475    if parts.iter().any(|p| p.0 != names) {
6476        return Ok(None);
6477    }
6478    let k = names.len();
6479    let total_rows: usize = parts.iter().map(|p| p.2).sum();
6480    // Merge per column (chunk c's cols[j] IS column names[j] since orders match),
6481    // then build the typed columns in parallel (columns are independent).
6482    let mut merged: Vec<Vec<Scalar>> = (0..k).map(|_| Vec::with_capacity(total_rows)).collect();
6483    let mut parts = parts;
6484    for p in &mut parts {
6485        for (j, col) in p.1.iter_mut().enumerate() {
6486            merged[j].append(col);
6487        }
6488    }
6489    let built: Vec<Result<Column, IoError>> = std::thread::scope(|scope| {
6490        merged
6491            .into_iter()
6492            .map(|vals| scope.spawn(move || column_from_json_values(vals)))
6493            .collect::<Vec<_>>()
6494            .into_iter()
6495            .map(|h| h.join().expect("json column-build thread"))
6496            .collect()
6497    });
6498    let mut out = BTreeMap::new();
6499    for (name, col) in names.iter().zip(built) {
6500        out.insert(name.clone(), col?);
6501    }
6502    let index = Index::from_i64((0..total_rows as i64).collect());
6503    let frame = DataFrame::new_with_column_order(index, out, names)?;
6504    Ok(Some(promote_synthetic_row_multiindex_if_present(&frame)?))
6505}
6506
6507fn try_read_json_records_flat(input: &str) -> Result<Option<DataFrame>, IoError> {
6508    let s = input.as_bytes();
6509    let n = s.len();
6510    let mut i = 0usize;
6511    macro_rules! ws {
6512        () => {
6513            while i < n && matches!(s[i], b' ' | b'\t' | b'\n' | b'\r') {
6514                i += 1;
6515            }
6516        };
6517    }
6518    ws!();
6519    if i >= n || s[i] != b'[' {
6520        return Ok(None);
6521    }
6522    i += 1;
6523    ws!();
6524    if i < n && s[i] == b']' {
6525        // Empty array: defer to the generic path's canonical empty-frame handling.
6526        return Ok(None);
6527    }
6528
6529    let mut col_names: Vec<String> = Vec::new();
6530    let mut cols: Vec<Vec<Scalar>> = Vec::new();
6531    // `last_seen[c]` = the last record index that pushed a value for column c, so a
6532    // duplicate key in the same record overwrites and an absent key backfills Null.
6533    let mut last_seen: Vec<usize> = Vec::new();
6534    let mut name_to_idx: std::collections::HashMap<Vec<u8>, usize> =
6535        std::collections::HashMap::new();
6536    let mut rec: usize = 0;
6537
6538    loop {
6539        ws!();
6540        if i >= n || s[i] != b'{' {
6541            return Ok(None);
6542        }
6543        i += 1;
6544        loop {
6545            ws!();
6546            if i < n && s[i] == b'}' {
6547                i += 1;
6548                break;
6549            }
6550            // key: a plain (unescaped) JSON string
6551            if i >= n || s[i] != b'"' {
6552                return Ok(None);
6553            }
6554            i += 1;
6555            let kstart = i;
6556            while i < n && s[i] != b'"' {
6557                if s[i] == b'\\' {
6558                    return Ok(None);
6559                }
6560                i += 1;
6561            }
6562            if i >= n {
6563                return Ok(None);
6564            }
6565            let key = &s[kstart..i];
6566            i += 1;
6567            ws!();
6568            if i >= n || s[i] != b':' {
6569                return Ok(None);
6570            }
6571            i += 1;
6572            ws!();
6573            if i >= n {
6574                return Ok(None);
6575            }
6576            // value: number | string | true | false | null (else bail)
6577            let scalar = match s[i] {
6578                b'-' | b'0'..=b'9' => {
6579                    let vstart = i;
6580                    if s[i] == b'-' {
6581                        i += 1;
6582                    }
6583                    let mut any = false;
6584                    while i < n && matches!(s[i], b'0'..=b'9' | b'.' | b'e' | b'E' | b'+' | b'-') {
6585                        any = true;
6586                        i += 1;
6587                    }
6588                    if !any {
6589                        return Ok(None);
6590                    }
6591                    let Ok(numstr) = std::str::from_utf8(&s[vstart..i]) else {
6592                        return Ok(None);
6593                    };
6594                    // Parse via serde_json so as_i64/as_f64 classification is identical
6595                    // to the Value path (bit-identical, incl. the non-round-trip f64).
6596                    match serde_json::from_str::<serde_json::Number>(numstr) {
6597                        Ok(num) => {
6598                            if let Some(v) = num.as_i64() {
6599                                Scalar::Int64(v)
6600                            } else if let Some(v) = num.as_f64() {
6601                                Scalar::Float64(v)
6602                            } else {
6603                                Scalar::Utf8(num.to_string())
6604                            }
6605                        }
6606                        Err(_) => return Ok(None),
6607                    }
6608                }
6609                b'"' => {
6610                    i += 1;
6611                    let vstart = i;
6612                    while i < n && s[i] != b'"' {
6613                        if s[i] == b'\\' {
6614                            return Ok(None); // escaped string -> generic path
6615                        }
6616                        i += 1;
6617                    }
6618                    if i >= n {
6619                        return Ok(None);
6620                    }
6621                    let raw = &s[vstart..i];
6622                    i += 1;
6623                    match std::str::from_utf8(raw) {
6624                        Ok(st) => Scalar::Utf8(st.to_owned()),
6625                        Err(_) => return Ok(None),
6626                    }
6627                }
6628                b't' if s[i..].starts_with(b"true") => {
6629                    i += 4;
6630                    Scalar::Bool(true)
6631                }
6632                b'f' if s[i..].starts_with(b"false") => {
6633                    i += 5;
6634                    Scalar::Bool(false)
6635                }
6636                b'n' if s[i..].starts_with(b"null") => {
6637                    i += 4;
6638                    Scalar::Null(NullKind::Null)
6639                }
6640                _ => return Ok(None),
6641            };
6642            let ci = match name_to_idx.get(key) {
6643                Some(&c) => c,
6644                None => {
6645                    let c = cols.len();
6646                    name_to_idx.insert(key.to_vec(), c);
6647                    col_names.push(String::from_utf8_lossy(key).into_owned());
6648                    let mut v: Vec<Scalar> = Vec::new();
6649                    v.resize(rec, Scalar::Null(NullKind::Null)); // backfill prior records
6650                    cols.push(v);
6651                    last_seen.push(usize::MAX);
6652                    c
6653                }
6654            };
6655            if last_seen[ci] == rec {
6656                *cols[ci].last_mut().expect("seen this record => non-empty") = scalar;
6657            } else {
6658                cols[ci].push(scalar);
6659                last_seen[ci] = rec;
6660            }
6661            ws!();
6662            if i < n && s[i] == b',' {
6663                i += 1;
6664                continue;
6665            }
6666        }
6667        // Pad every column not present in this record with Null.
6668        for c in 0..cols.len() {
6669            if last_seen[c] != rec {
6670                cols[c].push(Scalar::Null(NullKind::Null));
6671            }
6672        }
6673        rec += 1;
6674        ws!();
6675        if i < n && s[i] == b',' {
6676            i += 1;
6677            continue;
6678        }
6679        if i < n && s[i] == b']' {
6680            i += 1;
6681            break;
6682        }
6683        return Ok(None);
6684    }
6685    ws!();
6686    if i != n {
6687        return Ok(None); // trailing garbage -> generic path
6688    }
6689
6690    let row_count = rec as i64;
6691    let mut out = BTreeMap::new();
6692    for (name, vals) in col_names.iter().zip(cols) {
6693        out.insert(name.clone(), column_from_json_values(vals)?);
6694    }
6695    let index = Index::from_i64((0..row_count).collect());
6696    let frame = DataFrame::new_with_column_order(index, out, col_names)?;
6697    Ok(Some(promote_synthetic_row_multiindex_if_present(&frame)?))
6698}
6699
6700pub fn read_json_str(input: &str, orient: JsonOrient) -> Result<DataFrame, IoError> {
6701    // Records fast path (must precede the Value-tree parse): scan a FLAT records
6702    // array directly into per-column Scalar builders, skipping the serde_json::Value
6703    // tree + per-record map allocation that dominates a large records JSON (a 260 MB
6704    // input is ~3.2s via the tree). `try_read_json_records_flat` returns `None` to
6705    // defer to the generic path below on any non-flat input, so the frame is
6706    // bit-identical for every input.
6707    if matches!(orient, JsonOrient::Records) {
6708        // Parallel records fast path first (large homogeneous arrays), then the serial
6709        // flat scanner, then the generic Value-tree path. All produce bit-identical frames.
6710        if let Some(frame) = try_read_json_records_flat_parallel(input)? {
6711            return Ok(frame);
6712        }
6713        if let Some(frame) = try_read_json_records_flat(input)? {
6714            return Ok(frame);
6715        }
6716    }
6717    let parsed = parse_json_value_allowing_pandas_nan(input)?;
6718
6719    match orient {
6720        JsonOrient::Records => {
6721            let arr = parsed
6722                .as_array()
6723                .ok_or_else(|| IoError::JsonFormat("expected array for records orient".into()))?;
6724            if arr.is_empty() {
6725                return Ok(DataFrame::new(Index::new(Vec::new()), BTreeMap::new())?);
6726            }
6727
6728            // Collect column names from all records to handle heterogeneous keys
6729            let mut col_names_set = std::collections::BTreeSet::new();
6730            let mut col_names = Vec::new();
6731            for record in arr {
6732                let obj = record
6733                    .as_object()
6734                    .ok_or_else(|| IoError::JsonFormat("each record must be an object".into()))?;
6735                for key in obj.keys() {
6736                    if col_names_set.insert(key.clone()) {
6737                        col_names.push(key.clone());
6738                    }
6739                }
6740            }
6741
6742            let mut columns: BTreeMap<String, Vec<Scalar>> = BTreeMap::new();
6743            for name in &col_names {
6744                columns.insert(name.clone(), Vec::with_capacity(arr.len()));
6745            }
6746
6747            for record in arr {
6748                let obj = record
6749                    .as_object()
6750                    .ok_or_else(|| IoError::JsonFormat("each record must be an object".into()))?;
6751                for name in &col_names {
6752                    let val = obj.get(name).unwrap_or(&serde_json::Value::Null);
6753                    columns
6754                        .get_mut(name)
6755                        .ok_or_else(|| {
6756                            IoError::JsonFormat(format!(
6757                                "records orient missing column accumulator for '{name}'"
6758                            ))
6759                        })?
6760                        .push(json_value_to_scalar(val));
6761                }
6762            }
6763
6764            let row_count = arr.len() as i64;
6765            let mut out = BTreeMap::new();
6766            for (name, vals) in columns {
6767                out.insert(name, column_from_json_values(vals)?);
6768            }
6769            let index = Index::from_i64((0..row_count).collect());
6770            let frame = DataFrame::new_with_column_order(index, out, col_names)?;
6771            promote_synthetic_row_multiindex_if_present(&frame)
6772        }
6773        JsonOrient::Columns => {
6774            let obj = parsed
6775                .as_object()
6776                .ok_or_else(|| IoError::JsonFormat("expected object for columns orient".into()))?;
6777
6778            if obj.is_empty() {
6779                return Ok(DataFrame::new(Index::new(Vec::new()), BTreeMap::new())?);
6780            }
6781
6782            let mut raw_columns: BTreeMap<String, Vec<Scalar>> = BTreeMap::new();
6783            let mut column_order = Vec::with_capacity(obj.len());
6784            let mut index_labels = Vec::new();
6785            let mut index_lookup = BTreeMap::new();
6786            for (col_name, col_data) in obj {
6787                let col_obj = col_data.as_object().ok_or_else(|| {
6788                    IoError::JsonFormat("column data must be {index: val}".into())
6789                })?;
6790                let mut values = vec![Scalar::Null(NullKind::Null); index_labels.len()];
6791                for (label_key, val) in col_obj {
6792                    let label = json_key_to_index_label(label_key);
6793                    let row_idx = if let Some(&existing_idx) = index_lookup.get(&label) {
6794                        existing_idx
6795                    } else {
6796                        let next_idx = index_labels.len();
6797                        index_labels.push(label.clone());
6798                        index_lookup.insert(label, next_idx);
6799                        for existing_values in raw_columns.values_mut() {
6800                            existing_values.push(Scalar::Null(NullKind::Null));
6801                        }
6802                        values.push(Scalar::Null(NullKind::Null));
6803                        next_idx
6804                    };
6805                    if row_idx >= values.len() {
6806                        values.resize(index_labels.len(), Scalar::Null(NullKind::Null));
6807                    }
6808                    values[row_idx] = json_value_to_scalar(val);
6809                }
6810                if values.len() < index_labels.len() {
6811                    values.resize(index_labels.len(), Scalar::Null(NullKind::Null));
6812                }
6813                raw_columns.insert(col_name.clone(), values);
6814                column_order.push(col_name.clone());
6815            }
6816
6817            let mut out = BTreeMap::new();
6818            for (name, vals) in raw_columns {
6819                out.insert(name, column_from_json_values(vals)?);
6820            }
6821
6822            let frame =
6823                DataFrame::new_with_column_order(Index::new(index_labels), out, column_order)?;
6824            promote_synthetic_row_multiindex_if_present(&frame)
6825        }
6826        JsonOrient::Index => {
6827            let obj = parsed
6828                .as_object()
6829                .ok_or_else(|| IoError::JsonFormat("expected object for index orient".into()))?;
6830
6831            if obj.is_empty() {
6832                return Ok(DataFrame::new(Index::new(Vec::new()), BTreeMap::new())?);
6833            }
6834
6835            let mut index_labels = Vec::with_capacity(obj.len());
6836            let mut columns: BTreeMap<String, Vec<Scalar>> = BTreeMap::new();
6837            let mut column_order = Vec::new();
6838            let mut seen_columns = std::collections::HashSet::new();
6839
6840            for (row_label, row_data) in obj {
6841                let row_obj = row_data.as_object().ok_or_else(|| {
6842                    IoError::JsonFormat("index orient rows must be objects".into())
6843                })?;
6844
6845                let row_idx = index_labels.len();
6846
6847                // Pre-fill this row as null for all known columns, then overwrite present cells.
6848                for values in columns.values_mut() {
6849                    values.push(Scalar::Null(NullKind::Null));
6850                }
6851
6852                let parsed_label = row_label
6853                    .parse::<i64>()
6854                    .map(IndexLabel::Int64)
6855                    .unwrap_or_else(|_| IndexLabel::Utf8(row_label.clone()));
6856                index_labels.push(parsed_label);
6857
6858                for (col_name, value) in row_obj {
6859                    if seen_columns.insert(col_name.clone()) {
6860                        column_order.push(col_name.clone());
6861                    }
6862                    let scalar = json_value_to_scalar(value);
6863                    if let Some(values) = columns.get_mut(col_name) {
6864                        values[row_idx] = scalar;
6865                    } else {
6866                        let mut values = vec![Scalar::Null(NullKind::Null); row_idx + 1];
6867                        values[row_idx] = scalar;
6868                        columns.insert(col_name.clone(), values);
6869                    }
6870                }
6871            }
6872
6873            let mut out = BTreeMap::new();
6874            for (name, vals) in columns {
6875                out.insert(name, column_from_json_values(vals)?);
6876            }
6877            let frame =
6878                DataFrame::new_with_column_order(Index::new(index_labels), out, column_order)?;
6879            promote_synthetic_row_multiindex_if_present(&frame)
6880        }
6881        JsonOrient::Split => {
6882            let obj = parsed
6883                .as_object()
6884                .ok_or_else(|| IoError::JsonFormat("expected object for split orient".into()))?;
6885
6886            let col_names: Vec<String> = obj
6887                .get("columns")
6888                .and_then(|v| v.as_array())
6889                .ok_or_else(|| IoError::JsonFormat("split orient needs 'columns' array".into()))?
6890                .iter()
6891                .map(json_value_to_column_name)
6892                .collect();
6893            reject_duplicate_headers(&col_names)?;
6894
6895            let data = obj
6896                .get("data")
6897                .and_then(|v| v.as_array())
6898                .ok_or_else(|| IoError::JsonFormat("split orient needs 'data' array".into()))?;
6899
6900            let explicit_index = obj
6901                .get("index")
6902                .map(|v| {
6903                    v.as_array()
6904                        .ok_or_else(|| {
6905                            IoError::JsonFormat("split orient 'index' must be an array".into())
6906                        })
6907                        .map(|arr| {
6908                            arr.iter()
6909                                .map(json_value_to_index_label)
6910                                .collect::<Vec<_>>()
6911                        })
6912                })
6913                .transpose()?;
6914
6915            let mut columns: BTreeMap<String, Vec<Scalar>> = BTreeMap::new();
6916            for name in &col_names {
6917                columns.insert(name.clone(), Vec::with_capacity(data.len()));
6918            }
6919
6920            for (row_idx, row) in data.iter().enumerate() {
6921                let arr = row
6922                    .as_array()
6923                    .ok_or_else(|| IoError::JsonFormat("each data row must be an array".into()))?;
6924                if arr.len() != col_names.len() {
6925                    return Err(IoError::JsonFormat(format!(
6926                        "split orient row {row_idx} length ({}) does not match columns length ({})",
6927                        arr.len(),
6928                        col_names.len()
6929                    )));
6930                }
6931                for (i, name) in col_names.iter().enumerate() {
6932                    let val = arr.get(i).unwrap_or(&serde_json::Value::Null);
6933                    columns
6934                        .get_mut(name)
6935                        .ok_or_else(|| {
6936                            IoError::JsonFormat(format!(
6937                                "split orient missing column accumulator for '{name}'"
6938                            ))
6939                        })?
6940                        .push(json_value_to_scalar(val));
6941                }
6942            }
6943
6944            let row_count = data.len() as i64;
6945            let mut out = BTreeMap::new();
6946            for (name, vals) in columns {
6947                out.insert(name, column_from_json_values(vals)?);
6948            }
6949            let index = match explicit_index {
6950                Some(labels) => {
6951                    if labels.len() != row_count as usize {
6952                        return Err(IoError::JsonFormat(format!(
6953                            "split orient index length ({}) must match data row count ({row_count})",
6954                            labels.len()
6955                        )));
6956                    }
6957                    Index::new(labels)
6958                }
6959                None => Index::from_i64((0..row_count).collect()),
6960            };
6961            let frame = DataFrame::new_with_column_order(index, out, col_names)?;
6962            promote_synthetic_row_multiindex_if_present(&frame)
6963        }
6964        JsonOrient::Values => {
6965            let rows = parsed
6966                .as_array()
6967                .ok_or_else(|| IoError::JsonFormat("expected array for values orient".into()))?;
6968
6969            if rows.is_empty() {
6970                return Ok(DataFrame::new(Index::new(Vec::new()), BTreeMap::new())?);
6971            }
6972
6973            let mut width = 0usize;
6974            for row in rows {
6975                let arr = row.as_array().ok_or_else(|| {
6976                    IoError::JsonFormat("each values row must be an array".into())
6977                })?;
6978                width = width.max(arr.len());
6979            }
6980
6981            let column_order: Vec<String> = (0..width).map(|idx| idx.to_string()).collect();
6982            let mut columns: BTreeMap<String, Vec<Scalar>> = column_order
6983                .iter()
6984                .cloned()
6985                .map(|name| (name, Vec::with_capacity(rows.len())))
6986                .collect();
6987
6988            for row in rows {
6989                let arr = row.as_array().ok_or_else(|| {
6990                    IoError::JsonFormat("each values row must be an array".into())
6991                })?;
6992                for (col_idx, name) in column_order.iter().enumerate() {
6993                    let val = arr.get(col_idx).unwrap_or(&serde_json::Value::Null);
6994                    columns
6995                        .get_mut(name)
6996                        .ok_or_else(|| {
6997                            IoError::JsonFormat(format!(
6998                                "values orient missing column accumulator for '{name}'"
6999                            ))
7000                        })?
7001                        .push(json_value_to_scalar(val));
7002                }
7003            }
7004
7005            let mut out = BTreeMap::new();
7006            for (name, vals) in columns {
7007                out.insert(name, column_from_json_values(vals)?);
7008            }
7009            let index = Index::from_i64((0..rows.len() as i64).collect());
7010            let frame = DataFrame::new_with_column_order(index, out, column_order)?;
7011            promote_synthetic_row_multiindex_if_present(&frame)
7012        }
7013    }
7014}
7015
7016/// Serde-tree implementation of `to_json(orient="records")` — the bit-exact
7017/// reference the typed fast path below must match. Kept as a named fn so the
7018/// differential test can compare the two directly.
7019fn write_json_records_serde(
7020    frame: &DataFrame,
7021    headers: &[String],
7022    column_float_promotions: &[bool],
7023) -> Result<String, IoError> {
7024    let row_count = frame.index().len();
7025    let mut records = Vec::with_capacity(row_count);
7026    for row_idx in 0..row_count {
7027        let mut obj = serde_json::Map::new();
7028        for (name, promote_int_to_float) in headers.iter().zip(column_float_promotions.iter()) {
7029            let val = frame
7030                .column(name)
7031                .and_then(|c| c.value(row_idx))
7032                .map(|value| scalar_to_json_with_column_promotion(value, *promote_int_to_float))
7033                .unwrap_or(serde_json::Value::Null);
7034            obj.insert(name.clone(), val);
7035        }
7036        records.push(serde_json::Value::Object(obj));
7037    }
7038    Ok(serde_json::to_string(&records)?)
7039}
7040
7041/// Streaming typed fast path for `to_json(orient="records")` over an all-valid
7042/// numeric/bool frame: writes JSON bytes straight into one `String` with no
7043/// per-row `serde_json::Map`, no per-cell `Scalar`/`Value` materialization, and
7044/// no per-row key re-allocation (the materialized serde tree is ~0.69x pandas;
7045/// this restores the win). Returns `None` — caller falls back to the serde
7046/// tree — for any column that is not all-valid `Int64` / all-valid `Float64` /
7047/// `Bool`, or that would take the int→float promotion branch.
7048///
7049/// Bit-identical to `write_json_records_serde`:
7050///   * keys are pre-serialized with `serde_json::to_string` (same escaping) and
7051///     emitted in column order (the `preserve_order` Map preserves insertion),
7052///   * `i64` via `append_i64_decimal` (the same decimal spelling itoa serde's
7053///     integer formatter produces),
7054///   * finite `f64` via serde's own `CompactFormatter::write_f64` (exact
7055///     exponent spelling, e.g. `1e+20`); non-finite `f64` emits `null`,
7056///     matching `scalar_to_json`'s NaN/Inf → `Value::Null` arm.
7057///
7058/// With `as_jsonl = true` the row objects are joined by `\n` with no enclosing
7059/// `[ ]` (the JSON Lines spelling `write_jsonl_string` produces); otherwise they
7060/// are wrapped as a `[..]` array (the `records` orient).
7061/// A typed all-valid value column view for the streaming JSON writers.
7062enum JCol<'a> {
7063    I(&'a [i64]),
7064    F(&'a [f64]),
7065    B(&'a [bool]),
7066    /// Datetime64 ns: serialized as epoch-MILLISECOND integers (`v / 1_000_000`),
7067    /// `NaT` (i64::MIN) → `null` — matching `scalar_to_json`.
7068    DtMs(&'a [i64]),
7069    /// All-valid contiguous Utf8: `(bytes, offsets)`, row r =
7070    /// `bytes[offsets[r]..offsets[r+1]]`, serialized as a JSON string.
7071    U(&'a [u8], &'a [usize]),
7072    /// NULLABLE contiguous Utf8: `(bytes, offsets, validity)`. A present row
7073    /// (validity.get(r)) serializes its span as a JSON string; a missing row
7074    /// serializes as `null` — so a string column WITH nulls no longer forces the
7075    /// whole frame onto the serde tree.
7076    UN(&'a [u8], &'a [usize], &'a fp_columnar::ValidityMask),
7077    /// NULLABLE Float64: `(data, validity)`. A present, finite row serializes via
7078    /// serde's `write_f64`; a missing row (validity-clear) OR a non-finite datum
7079    /// (NaN/±inf) serializes as `null` — matching `scalar_to_json` and the F arm.
7080    FN(&'a [f64], &'a fp_columnar::ValidityMask),
7081    /// NULLABLE Int64: `(data, validity)`. Present → decimal; missing → `null`.
7082    IN(&'a [i64], &'a fp_columnar::ValidityMask),
7083    /// NULLABLE Bool: `(data, validity)`. Present → `true`/`false`; missing → `null`.
7084    BN(&'a [bool], &'a fp_columnar::ValidityMask),
7085}
7086
7087/// Append `s` as a JSON string literal, byte-identical to `serde_json` (which
7088/// escapes only `"`, `\`, and the control bytes 0x00–0x1F; everything else,
7089/// including multi-byte UTF-8, passes through verbatim). The overwhelmingly
7090/// common no-escape case is a single `"` + raw + `"`; only a string that
7091/// actually contains an escape-worthy byte deopts to `serde_json::to_string`.
7092#[inline]
7093fn append_json_string(out: &mut String, s: &str) {
7094    if s.bytes().all(|b| b >= 0x20 && b != b'"' && b != b'\\') {
7095        out.push('"');
7096        out.push_str(s);
7097        out.push('"');
7098    } else {
7099        match serde_json::to_string(s) {
7100            Ok(escaped) => out.push_str(&escaped),
7101            Err(_) => out.push_str("\"\""),
7102        }
7103    }
7104}
7105
7106/// Extract every column as an all-valid typed slice plus its pre-serialized,
7107/// escaped, colon-terminated JSON key (column order = `preserve_order`
7108/// insertion order). Returns `None` — caller falls back to the serde tree — on
7109/// any column that is not all-valid `Int64`/`Float64`/`Bool`/`Datetime64`,
7110/// would take the int→float promotion branch, or on a row-multiindex frame.
7111fn extract_typed_value_columns(frame: &DataFrame) -> Option<(Vec<JCol<'_>>, Vec<String>)> {
7112    if frame.row_multiindex().is_some() {
7113        return None;
7114    }
7115    let headers: Vec<&String> = frame.column_names();
7116    let n = frame.index().len();
7117    let mut cols: Vec<JCol<'_>> = Vec::with_capacity(headers.len());
7118    let mut keys: Vec<String> = Vec::with_capacity(headers.len());
7119    for name in &headers {
7120        let column = frame.column(name.as_str())?;
7121        if column_promotes_int_json_values_to_float(column.values()) {
7122            return None;
7123        }
7124        let jc = if let Some(s) = column.as_i64_slice() {
7125            (s.len() == n).then_some(JCol::I(s))?
7126        } else if let Some(s) = column.as_f64_slice() {
7127            (s.len() == n).then_some(JCol::F(s))?
7128        } else if let Some(s) = column.as_bool_slice() {
7129            (s.len() == n).then_some(JCol::B(s))?
7130        } else if let Some(s) = column.as_datetime64_slice() {
7131            // The slice exposes the raw ns including any NaT sentinel; a
7132            // validity-mask null (data slot ≠ NaT) would diverge from
7133            // `value()`'s `Scalar::Null`, so require no mask-nulls. An all-valid
7134            // `from_datetime64_values` backing keeps NaT AS DATA (validity stays
7135            // all-valid), and `append_typed_json_value` maps that sentinel → null
7136            // exactly like `scalar_to_json(Datetime64(NaT))`.
7137            if column.has_nulls() {
7138                return None;
7139            }
7140            (s.len() == n).then_some(JCol::DtMs(s))?
7141        } else if let Some((bytes, offsets)) = column.as_utf8_contiguous() {
7142            // as_utf8_contiguous already requires validity.all(), so every row
7143            // is a present `Scalar::Utf8` → JSON string (never null).
7144            (offsets.len() == n + 1).then_some(JCol::U(bytes, offsets))?
7145        } else if let Some((bytes, offsets)) = column.as_nullable_utf8_contiguous() {
7146            // Nullable contiguous Utf8: present rows serialize their span, missing
7147            // rows serialize as `null` — so one null-bearing string column no longer
7148            // forces the whole frame onto the serde tree.
7149            (offsets.len() == n + 1).then_some(JCol::UN(bytes, offsets, column.validity()))?
7150        } else if let Some((s, validity)) = column.as_f64_slice_with_validity() {
7151            // Nullable Float64: present+finite → number, missing/non-finite → null.
7152            (s.len() == n).then_some(JCol::FN(s, validity))?
7153        } else if let Some((s, validity)) = column.as_i64_slice_with_validity() {
7154            // Nullable Int64: present → integer, missing → null.
7155            (s.len() == n).then_some(JCol::IN(s, validity))?
7156        } else if let Some((s, validity)) = column.as_nullable_bool_slice() {
7157            // Nullable Bool: present → true/false, missing → null.
7158            (s.len() == n).then_some(JCol::BN(s, validity))?
7159        } else {
7160            return None;
7161        };
7162        cols.push(jc);
7163        let mut key = serde_json::to_string(name.as_str()).ok()?;
7164        key.push(':');
7165        keys.push(key);
7166    }
7167    Some((cols, keys))
7168}
7169
7170/// Append cell `(col, r)` as a JSON value, byte-identical to serde:
7171/// `i64` via `append_i64_decimal`, finite `f64` via serde's own
7172/// `CompactFormatter::write_f64` (exact exponent spelling, e.g. `1e+20`),
7173/// non-finite `f64` as `null` (matching `scalar_to_json`), `bool` as
7174/// `true`/`false`. `fbytes` is a reusable scratch to avoid a per-cell alloc.
7175#[inline]
7176fn append_typed_json_value(out: &mut String, col: &JCol<'_>, r: usize, fbytes: &mut Vec<u8>) {
7177    use serde_json::ser::{CompactFormatter, Formatter};
7178    match col {
7179        JCol::I(s) => append_i64_decimal(out, s[r]),
7180        JCol::F(s) => {
7181            let v = s[r];
7182            if v.is_finite() {
7183                fbytes.clear();
7184                // Writing into a Vec<u8> is infallible.
7185                let _ = CompactFormatter.write_f64(fbytes, v);
7186                out.push_str(std::str::from_utf8(fbytes).unwrap_or("null"));
7187            } else {
7188                out.push_str("null");
7189            }
7190        }
7191        JCol::B(s) => out.push_str(if s[r] { "true" } else { "false" }),
7192        JCol::DtMs(s) => {
7193            let v = s[r];
7194            // i64::MIN is the Datetime64 NaT sentinel.
7195            if v == i64::MIN {
7196                out.push_str("null");
7197            } else {
7198                append_i64_decimal(out, v / 1_000_000);
7199            }
7200        }
7201        JCol::U(bytes, offsets) => {
7202            let field = &bytes[offsets[r]..offsets[r + 1]];
7203            // SAFETY-FREE: contiguous Utf8 backing is valid UTF-8.
7204            append_json_string(out, std::str::from_utf8(field).unwrap_or(""));
7205        }
7206        // Nullable Utf8: a present row renders its span like JCol::U; a missing row
7207        // renders `null` — matching the serde-tree fallback's `Scalar::Null` → null.
7208        JCol::UN(bytes, offsets, validity) => {
7209            if validity.get(r) {
7210                let field = &bytes[offsets[r]..offsets[r + 1]];
7211                append_json_string(out, std::str::from_utf8(field).unwrap_or(""));
7212            } else {
7213                out.push_str("null");
7214            }
7215        }
7216        // Nullable Float64: a present finite row renders like JCol::F (serde's
7217        // write_f64); a missing row (validity-clear) OR a non-finite datum
7218        // (NaN/±inf — no JSON representation, matching scalar_to_json) renders `null`.
7219        JCol::FN(s, validity) => {
7220            let v = s[r];
7221            if validity.get(r) && v.is_finite() {
7222                fbytes.clear();
7223                let _ = CompactFormatter.write_f64(fbytes, v);
7224                out.push_str(std::str::from_utf8(fbytes).unwrap_or("null"));
7225            } else {
7226                out.push_str("null");
7227            }
7228        }
7229        // Nullable Int64: present ⇒ decimal (== JCol::I); missing ⇒ `null`.
7230        JCol::IN(s, validity) => {
7231            if validity.get(r) {
7232                append_i64_decimal(out, s[r]);
7233            } else {
7234                out.push_str("null");
7235            }
7236        }
7237        // Nullable Bool: present ⇒ true/false (== JCol::B); missing ⇒ `null`.
7238        JCol::BN(s, validity) => {
7239            if validity.get(r) {
7240                out.push_str(if s[r] { "true" } else { "false" });
7241            } else {
7242                out.push_str("null");
7243            }
7244        }
7245    }
7246}
7247
7248fn try_write_json_records_typed(frame: &DataFrame, as_jsonl: bool) -> Option<String> {
7249    let (cols, keys) = extract_typed_value_columns(frame)?;
7250    let n = frame.index().len();
7251    let mut out = String::with_capacity(
7252        n.saturating_mul(cols.len().max(1))
7253            .saturating_mul(12)
7254            .saturating_add(16),
7255    );
7256    if !as_jsonl {
7257        out.push('[');
7258    }
7259    let mut fbytes: Vec<u8> = Vec::with_capacity(32);
7260    for r in 0..n {
7261        if r > 0 {
7262            out.push(if as_jsonl { '\n' } else { ',' });
7263        }
7264        out.push('{');
7265        for (c, col) in cols.iter().enumerate() {
7266            if c > 0 {
7267                out.push(',');
7268            }
7269            out.push_str(&keys[c]);
7270            append_typed_json_value(&mut out, col, r, &mut fbytes);
7271        }
7272        out.push('}');
7273    }
7274    if !as_jsonl {
7275        out.push(']');
7276    }
7277    Some(out)
7278}
7279
7280/// Streaming typed fast path for `to_json(orient="columns")` — `{col: {idx:
7281/// val}}`. The serde tree re-stringifies the index-label key for EVERY cell of
7282/// EVERY column (n×k) and builds a nested Map per column; this is ~0.39x pandas.
7283/// Here the n index-label keys are pre-serialized ONCE and reused across every
7284/// column. Returns `None` (serde fallback) unless the index is unique (so no
7285/// inner key collides — the serde path errors on a duplicate index key, which
7286/// this fast path must not silently swallow) and every column is typed.
7287///
7288/// Bit-identical to the serde `Columns` arm: outer keys in column order, inner
7289/// keys in index-label order (both `preserve_order`), inner keys spelled by
7290/// `index_label_json_key` then serde-quoted, values via `append_typed_json_value`.
7291/// Pre-serialize the n index-label JSON object keys ONCE into a single
7292/// contiguous buffer (+ offsets), each carrying its quotes and trailing `:`.
7293/// For an all-Int64 unique index the keys are hand-rolled `"` + itoa + `":`
7294/// straight off `int64_label_values()` — no `labels()` IndexLabel
7295/// materialization and no per-key `String` alloc. Returns `None` (caller falls
7296/// back to the serde tree) if any serialized key collides (the serde path
7297/// errors on a duplicate index-label key, which the fast path must not swallow).
7298/// Shared by the `columns` and `index` orients (the index keys are the
7299/// repeated-per-column / repeated-per-row keys respectively).
7300fn build_json_index_key_buffer(frame: &DataFrame) -> Option<(String, Vec<usize>)> {
7301    let n = frame.index().len();
7302    let mut keybuf = String::with_capacity(n.saturating_mul(10).saturating_add(8));
7303    let mut keyoff: Vec<usize> = Vec::with_capacity(n + 1);
7304    keyoff.push(0);
7305    let mut keys_known_unique = false;
7306    if frame.index().is_unique()
7307        && let Some(vals) = frame.index().int64_label_values()
7308        && vals.len() == n
7309    {
7310        // Distinct i64 → distinct decimal keys, and
7311        // `serde_json::to_string(v.to_string())` is exactly `"<decimal>"`, so the
7312        // hand-rolled spelling is byte-identical and needs no dedup.
7313        for &v in vals.iter() {
7314            keybuf.push('"');
7315            append_i64_decimal(&mut keybuf, v);
7316            keybuf.push_str("\":");
7317            keyoff.push(keybuf.len());
7318        }
7319        keys_known_unique = true;
7320    } else {
7321        for label in frame.index().labels() {
7322            let k = serde_json::to_string(&index_label_json_key(label)).ok()?;
7323            keybuf.push_str(&k);
7324            keybuf.push(':');
7325            keyoff.push(keybuf.len());
7326        }
7327    }
7328    if !keys_known_unique {
7329        let mut seen = std::collections::HashSet::with_capacity(n);
7330        for r in 0..n {
7331            if !seen.insert(&keybuf[keyoff[r]..keyoff[r + 1]]) {
7332                return None;
7333            }
7334        }
7335    }
7336    Some((keybuf, keyoff))
7337}
7338
7339fn try_write_json_columns_typed(frame: &DataFrame) -> Option<String> {
7340    let (cols, colkeys) = extract_typed_value_columns(frame)?;
7341    let n = frame.index().len();
7342    // The n inner index-label keys, pre-serialized once, reused across every
7343    // column — vs the serde path's n×k re-stringification.
7344    let (keybuf, keyoff) = build_json_index_key_buffer(frame)?;
7345
7346    let mut out = String::with_capacity(
7347        n.saturating_mul(cols.len().max(1))
7348            .saturating_mul(16)
7349            .saturating_add(16),
7350    );
7351    out.push('{');
7352    let mut fbytes: Vec<u8> = Vec::with_capacity(32);
7353    for (c, col) in cols.iter().enumerate() {
7354        if c > 0 {
7355            out.push(',');
7356        }
7357        out.push_str(&colkeys[c]);
7358        out.push('{');
7359        for r in 0..n {
7360            if r > 0 {
7361                out.push(',');
7362            }
7363            out.push_str(&keybuf[keyoff[r]..keyoff[r + 1]]);
7364            append_typed_json_value(&mut out, col, r, &mut fbytes);
7365        }
7366        out.push('}');
7367    }
7368    out.push('}');
7369    Some(out)
7370}
7371
7372/// Streaming typed fast path for `to_json(orient="index")` — `{idx: {col:
7373/// val}}`, the transpose of `columns`. The serde tree builds a `serde_json::Map`
7374/// per ROW plus an index-label outer key per row (~0.63x pandas). Here the n
7375/// outer index-label keys are pre-serialized once (contiguous buffer) and the k
7376/// inner column keys are reused every row. Bit-identical to the serde `Index`
7377/// arm: outer keys in row order, inner keys in column order (both
7378/// `preserve_order`), same key spellings and value formatting; bails (→ serde
7379/// path, which errors) on a duplicate index-label key or any non-typed column.
7380fn try_write_json_index_typed(frame: &DataFrame) -> Option<String> {
7381    let (cols, colkeys) = extract_typed_value_columns(frame)?;
7382    let n = frame.index().len();
7383    // The n outer index-label keys, pre-serialized once.
7384    let (keybuf, keyoff) = build_json_index_key_buffer(frame)?;
7385
7386    let mut out = String::with_capacity(
7387        n.saturating_mul(cols.len().max(1))
7388            .saturating_mul(16)
7389            .saturating_add(16),
7390    );
7391    out.push('{');
7392    let mut fbytes: Vec<u8> = Vec::with_capacity(32);
7393    for r in 0..n {
7394        if r > 0 {
7395            out.push(',');
7396        }
7397        out.push_str(&keybuf[keyoff[r]..keyoff[r + 1]]);
7398        out.push('{');
7399        for (c, col) in cols.iter().enumerate() {
7400            if c > 0 {
7401                out.push(',');
7402            }
7403            out.push_str(&colkeys[c]);
7404            append_typed_json_value(&mut out, col, r, &mut fbytes);
7405        }
7406        out.push('}');
7407    }
7408    out.push('}');
7409    Some(out)
7410}
7411
7412/// Append the row-major `[[v, v], ...]` array of all cells (column order per
7413/// row) to `out` — the shared body of the `values` orient and the `data`
7414/// section of the `split` orient.
7415fn append_json_row_arrays(out: &mut String, cols: &[JCol<'_>], n: usize) {
7416    out.push('[');
7417    let mut fbytes: Vec<u8> = Vec::with_capacity(32);
7418    for r in 0..n {
7419        if r > 0 {
7420            out.push(',');
7421        }
7422        out.push('[');
7423        for (c, col) in cols.iter().enumerate() {
7424            if c > 0 {
7425                out.push(',');
7426            }
7427            append_typed_json_value(out, col, r, &mut fbytes);
7428        }
7429        out.push(']');
7430    }
7431    out.push(']');
7432}
7433
7434/// Streaming typed fast path for `to_json(orient="values")` — `[[v, v], ...]`,
7435/// row-major arrays with no keys (the simplest orient). Bit-identical to the
7436/// serde `Values` arm. Bails (→ serde) on any non-typed column.
7437fn try_write_json_values_typed(frame: &DataFrame) -> Option<String> {
7438    let (cols, _keys) = extract_typed_value_columns(frame)?;
7439    let n = frame.index().len();
7440    let mut out = String::with_capacity(
7441        n.saturating_mul(cols.len().max(1))
7442            .saturating_mul(12)
7443            .saturating_add(16),
7444    );
7445    append_json_row_arrays(&mut out, &cols, n);
7446    Some(out)
7447}
7448
7449/// Streaming typed fast path for `to_json(orient="split")` —
7450/// `{"columns":[...],"index":[...],"data":[[...]]}`. The `data` section is the
7451/// same row-major shape as `values` (the bulk); the `columns`/`index` header
7452/// arrays are tiny. Bit-identical to the serde `Split` arm: `columns` is the
7453/// header strings, `index` is each label via `index_label_to_json` (bare ints
7454/// for an Int64 index, hand-rolled here), `data` via `append_json_row_arrays`,
7455/// and the object keys are in insertion order (columns, index, data) under
7456/// `preserve_order`. Bails (→ serde) on any non-typed column.
7457fn try_write_json_split_typed(frame: &DataFrame) -> Option<String> {
7458    let (cols, _keys) = extract_typed_value_columns(frame)?;
7459    let n = frame.index().len();
7460    let headers = frame.column_names();
7461    // columns array: serde over the (few) header strings — same escaping as the
7462    // serde path's `Vec<Value::String>`.
7463    let cols_json = serde_json::to_string(&headers).ok()?;
7464    // index array: bare JSON values (NOT object keys), `index_label_to_json` per
7465    // label — hand-rolled itoa for the common all-Int64 index, serde otherwise.
7466    let mut idx_json = String::with_capacity(n.saturating_mul(8).saturating_add(2));
7467    idx_json.push('[');
7468    if let Some(vals) = frame.index().int64_label_values()
7469        && vals.len() == n
7470    {
7471        for (i, &v) in vals.iter().enumerate() {
7472            if i > 0 {
7473                idx_json.push(',');
7474            }
7475            append_i64_decimal(&mut idx_json, v);
7476        }
7477    } else {
7478        for (i, label) in frame.index().labels().iter().enumerate() {
7479            if i > 0 {
7480                idx_json.push(',');
7481            }
7482            idx_json.push_str(&serde_json::to_string(&index_label_to_json(label)).ok()?);
7483        }
7484    }
7485    idx_json.push(']');
7486
7487    let mut out = String::with_capacity(
7488        n.saturating_mul(cols.len().max(1))
7489            .saturating_mul(12)
7490            .saturating_add(idx_json.len() + cols_json.len() + 48),
7491    );
7492    out.push_str("{\"columns\":");
7493    out.push_str(&cols_json);
7494    out.push_str(",\"index\":");
7495    out.push_str(&idx_json);
7496    out.push_str(",\"data\":");
7497    append_json_row_arrays(&mut out, &cols, n);
7498    out.push('}');
7499    Some(out)
7500}
7501
7502pub fn write_json_string(frame: &DataFrame, orient: JsonOrient) -> Result<String, IoError> {
7503    if frame.row_multiindex().is_some() && orient != JsonOrient::Values {
7504        let materialized = materialize_synthetic_row_multiindex_columns(frame)?;
7505        return write_json_string(&materialized, orient);
7506    }
7507
7508    let headers: Vec<String> = frame.column_names().into_iter().cloned().collect();
7509    let row_count = frame.index().len();
7510    let column_float_promotions = headers
7511        .iter()
7512        .map(|name| {
7513            frame
7514                .column(name)
7515                .is_some_and(|column| column_promotes_int_json_values_to_float(column.values()))
7516        })
7517        .collect::<Vec<_>>();
7518
7519    match orient {
7520        JsonOrient::Records => {
7521            // Typed streaming fast path for all-valid numeric/bool frames; falls
7522            // back to the serde tree below on anything it can't handle.
7523            if let Some(s) = try_write_json_records_typed(frame, false) {
7524                return Ok(s);
7525            }
7526            write_json_records_serde(frame, &headers, &column_float_promotions)
7527        }
7528        JsonOrient::Columns => {
7529            // Typed streaming fast path; falls back to the serde tree below.
7530            if let Some(s) = try_write_json_columns_typed(frame) {
7531                return Ok(s);
7532            }
7533            let mut outer = serde_json::Map::new();
7534            for (name, promote_int_to_float) in headers.iter().zip(column_float_promotions.iter()) {
7535                let mut col_obj = serde_json::Map::new();
7536                if let Some(col) = frame.column(name) {
7537                    for (label, val) in frame.index().labels().iter().zip(col.values()) {
7538                        let key = index_label_json_key(label);
7539                        if col_obj
7540                            .insert(
7541                                key.clone(),
7542                                scalar_to_json_with_column_promotion(val, *promote_int_to_float),
7543                            )
7544                            .is_some()
7545                        {
7546                            return Err(IoError::JsonFormat(format!(
7547                                "columns orient cannot encode duplicate index label key: {key}"
7548                            )));
7549                        }
7550                    }
7551                }
7552                outer.insert(name.clone(), serde_json::Value::Object(col_obj));
7553            }
7554            Ok(serde_json::to_string(&serde_json::Value::Object(outer))?)
7555        }
7556        JsonOrient::Index => {
7557            // Typed streaming fast path; falls back to the serde tree below.
7558            if let Some(s) = try_write_json_index_typed(frame) {
7559                return Ok(s);
7560            }
7561            let mut outer = serde_json::Map::new();
7562            for row_idx in 0..row_count {
7563                let mut row_obj = serde_json::Map::new();
7564                for (name, promote_int_to_float) in
7565                    headers.iter().zip(column_float_promotions.iter())
7566                {
7567                    let val = frame
7568                        .column(name)
7569                        .and_then(|c| c.value(row_idx))
7570                        .map(|value| {
7571                            scalar_to_json_with_column_promotion(value, *promote_int_to_float)
7572                        })
7573                        .unwrap_or(serde_json::Value::Null);
7574                    row_obj.insert(name.clone(), val);
7575                }
7576
7577                let row_label = index_label_json_key(&frame.index().labels()[row_idx]);
7578                if outer
7579                    .insert(row_label.clone(), serde_json::Value::Object(row_obj))
7580                    .is_some()
7581                {
7582                    return Err(IoError::JsonFormat(format!(
7583                        "index orient cannot encode duplicate index label key: {row_label}"
7584                    )));
7585                }
7586            }
7587            Ok(serde_json::to_string(&serde_json::Value::Object(outer))?)
7588        }
7589        JsonOrient::Split => {
7590            // Typed streaming fast path; falls back to the serde tree below.
7591            if let Some(s) = try_write_json_split_typed(frame) {
7592                return Ok(s);
7593            }
7594            let col_array: Vec<serde_json::Value> = headers
7595                .iter()
7596                .map(|h| serde_json::Value::String(h.clone()))
7597                .collect();
7598            let index_array: Vec<serde_json::Value> = frame
7599                .index()
7600                .labels()
7601                .iter()
7602                .map(index_label_to_json)
7603                .collect();
7604
7605            let mut data = Vec::with_capacity(row_count);
7606            for row_idx in 0..row_count {
7607                let row: Vec<serde_json::Value> = headers
7608                    .iter()
7609                    .zip(column_float_promotions.iter())
7610                    .map(|(name, promote_int_to_float)| {
7611                        frame
7612                            .column(name)
7613                            .and_then(|c| c.value(row_idx))
7614                            .map(|value| {
7615                                scalar_to_json_with_column_promotion(value, *promote_int_to_float)
7616                            })
7617                            .unwrap_or(serde_json::Value::Null)
7618                    })
7619                    .collect();
7620                data.push(serde_json::Value::Array(row));
7621            }
7622
7623            let mut obj = serde_json::Map::new();
7624            obj.insert("columns".into(), serde_json::Value::Array(col_array));
7625            obj.insert("index".into(), serde_json::Value::Array(index_array));
7626            obj.insert("data".into(), serde_json::Value::Array(data));
7627            Ok(serde_json::to_string(&serde_json::Value::Object(obj))?)
7628        }
7629        JsonOrient::Values => {
7630            // Typed streaming fast path; falls back to the serde tree below.
7631            if let Some(s) = try_write_json_values_typed(frame) {
7632                return Ok(s);
7633            }
7634            let mut data = Vec::with_capacity(row_count);
7635            for row_idx in 0..row_count {
7636                let row: Vec<serde_json::Value> = headers
7637                    .iter()
7638                    .zip(column_float_promotions.iter())
7639                    .map(|(name, promote_int_to_float)| {
7640                        frame
7641                            .column(name)
7642                            .and_then(|c| c.value(row_idx))
7643                            .map(|value| {
7644                                scalar_to_json_with_column_promotion(value, *promote_int_to_float)
7645                            })
7646                            .unwrap_or(serde_json::Value::Null)
7647                    })
7648                    .collect();
7649                data.push(serde_json::Value::Array(row));
7650            }
7651            Ok(serde_json::to_string(&serde_json::Value::Array(data))?)
7652        }
7653    }
7654}
7655
7656// ── File-based JSON ────────────────────────────────────────────────────
7657
7658pub fn read_json(path: &Path, orient: JsonOrient) -> Result<DataFrame, IoError> {
7659    let content = std::fs::read_to_string(path)?;
7660    read_json_str(&content, orient)
7661}
7662
7663pub fn write_json(frame: &DataFrame, path: &Path, orient: JsonOrient) -> Result<(), IoError> {
7664    let content = write_json_string(frame, orient)?;
7665    std::fs::write(path, content)?;
7666    Ok(())
7667}
7668
7669// ── File-based Pickle ──────────────────────────────────────────────────
7670
7671/// Read a DataFrame from a Pickle file.
7672pub fn read_pickle(path: &Path) -> Result<DataFrame, IoError> {
7673    read_pickle_with_options(path, &PickleReadOptions::default())
7674}
7675
7676/// Read a DataFrame from a Pickle file with options.
7677pub fn read_pickle_with_options(
7678    path: &Path,
7679    options: &PickleReadOptions,
7680) -> Result<DataFrame, IoError> {
7681    let content = std::fs::read(path)?;
7682    read_pickle_bytes_with_options(&content, options)
7683}
7684
7685/// Write a DataFrame to a Pickle file.
7686pub fn write_pickle(frame: &DataFrame, path: &Path) -> Result<(), IoError> {
7687    write_pickle_with_options(frame, path, &PickleWriteOptions::default())
7688}
7689
7690/// Write a DataFrame to a Pickle file with options.
7691pub fn write_pickle_with_options(
7692    frame: &DataFrame,
7693    path: &Path,
7694    options: &PickleWriteOptions,
7695) -> Result<(), IoError> {
7696    let content = write_pickle_bytes_with_options(frame, options)?;
7697    std::fs::write(path, content)?;
7698    Ok(())
7699}
7700
7701// ── File-based HDF5 ────────────────────────────────────────────────────
7702
7703/// Read a DataFrame from the default HDF5 key.
7704pub fn read_hdf(path: &Path) -> Result<DataFrame, IoError> {
7705    read_hdf_with_options(path, &HdfReadOptions::default())
7706}
7707
7708/// Read a DataFrame from an explicit HDF5 key.
7709pub fn read_hdf_key(path: &Path, key: &str) -> Result<DataFrame, IoError> {
7710    read_hdf_with_options(
7711        path,
7712        &HdfReadOptions {
7713            key: key.to_owned(),
7714        },
7715    )
7716}
7717
7718/// Read a DataFrame from an HDF5 file with options.
7719#[cfg(feature = "hdf5")]
7720pub fn read_hdf_with_options(path: &Path, options: &HdfReadOptions) -> Result<DataFrame, IoError> {
7721    let key = normalize_hdf5_key(&options.key)?;
7722    let dataset_path = hdf5_payload_path(&key);
7723    let file = Hdf5File::open(path).map_err(hdf5_error)?;
7724    let dataset = file.dataset(&dataset_path).map_err(|err| {
7725        IoError::Hdf5(format!(
7726            "missing FrankenPandas payload dataset '{dataset_path}': {err}"
7727        ))
7728    })?;
7729    let payload = dataset.read_raw::<u8>().map_err(hdf5_error)?;
7730    read_pickle_bytes(&payload).map_err(|err| {
7731        IoError::Hdf5(format!(
7732            "invalid FrankenPandas payload at key '{key}': {err}"
7733        ))
7734    })
7735}
7736
7737/// Read a DataFrame from an HDF5 file with options.
7738#[cfg(not(feature = "hdf5"))]
7739pub fn read_hdf_with_options(
7740    _path: &Path,
7741    _options: &HdfReadOptions,
7742) -> Result<DataFrame, IoError> {
7743    hdf5_feature_disabled()
7744}
7745
7746/// Write a DataFrame to the default HDF5 key.
7747pub fn write_hdf(frame: &DataFrame, path: &Path) -> Result<(), IoError> {
7748    write_hdf_with_options(frame, path, &HdfWriteOptions::default())
7749}
7750
7751/// Write a Series to the default HDF5 key.
7752///
7753/// Converts the Series to a single-column DataFrame and writes it.
7754pub fn write_hdf_series(series: &Series, path: &Path) -> Result<(), IoError> {
7755    let frame = series
7756        .to_frame(Some(series.name()))
7757        .map_err(|e| IoError::Hdf5(format!("Series to DataFrame conversion: {e}")))?;
7758    write_hdf(&frame, path)
7759}
7760
7761/// Write a Series to an explicit HDF5 key.
7762pub fn write_hdf_series_key(series: &Series, path: &Path, key: &str) -> Result<(), IoError> {
7763    let frame = series
7764        .to_frame(Some(series.name()))
7765        .map_err(|e| IoError::Hdf5(format!("Series to DataFrame conversion: {e}")))?;
7766    write_hdf_key(&frame, path, key)
7767}
7768
7769/// Write a DataFrame to an explicit HDF5 key.
7770pub fn write_hdf_key(frame: &DataFrame, path: &Path, key: &str) -> Result<(), IoError> {
7771    write_hdf_with_options(
7772        frame,
7773        path,
7774        &HdfWriteOptions {
7775            key: key.to_owned(),
7776        },
7777    )
7778}
7779
7780/// Write a DataFrame to an HDF5 file with options.
7781#[cfg(feature = "hdf5")]
7782pub fn write_hdf_with_options(
7783    frame: &DataFrame,
7784    path: &Path,
7785    options: &HdfWriteOptions,
7786) -> Result<(), IoError> {
7787    let key = normalize_hdf5_key(&options.key)?;
7788    let payload = write_pickle_bytes(frame)?;
7789    let file = Hdf5File::create(path).map_err(hdf5_error)?;
7790    let group = file.create_group(&key).map_err(hdf5_error)?;
7791    group
7792        .new_dataset_builder()
7793        .with_data(payload.as_slice())
7794        .create(HDF5_PAYLOAD_DATASET)
7795        .map_err(hdf5_error)?;
7796    file.flush().map_err(hdf5_error)?;
7797    Ok(())
7798}
7799
7800/// Write a DataFrame to an HDF5 file with options.
7801#[cfg(not(feature = "hdf5"))]
7802pub fn write_hdf_with_options(
7803    _frame: &DataFrame,
7804    _path: &Path,
7805    _options: &HdfWriteOptions,
7806) -> Result<(), IoError> {
7807    hdf5_feature_disabled()
7808}
7809
7810#[cfg(feature = "hdf5")]
7811fn normalize_hdf5_key(key: &str) -> Result<String, IoError> {
7812    let trimmed = key.trim_matches('/');
7813    if trimmed.is_empty() {
7814        return Err(IoError::Hdf5(
7815            "hdf5 key must name a non-root group".to_owned(),
7816        ));
7817    }
7818
7819    for part in trimmed.split('/') {
7820        if part.is_empty() || part == "." || part == ".." {
7821            return Err(IoError::Hdf5(format!("invalid hdf5 key '{key}'")));
7822        }
7823        if part == HDF5_PAYLOAD_DATASET {
7824            return Err(IoError::Hdf5(format!(
7825                "hdf5 key '{key}' uses reserved FrankenPandas dataset name"
7826            )));
7827        }
7828    }
7829
7830    Ok(trimmed.to_owned())
7831}
7832
7833#[cfg(feature = "hdf5")]
7834fn hdf5_payload_path(key: &str) -> String {
7835    format!("{key}/{HDF5_PAYLOAD_DATASET}")
7836}
7837
7838#[cfg(feature = "hdf5")]
7839fn hdf5_error(err: hdf5::Error) -> IoError {
7840    IoError::Hdf5(err.to_string())
7841}
7842
7843#[cfg(not(feature = "hdf5"))]
7844fn hdf5_feature_disabled<T>() -> Result<T, IoError> {
7845    Err(IoError::Hdf5(
7846        "hdf5 support is disabled; enable the fp-io `hdf5` feature".to_owned(),
7847    ))
7848}
7849
7850// ── File-based Stata ───────────────────────────────────────────────────
7851
7852/// Read a DataFrame from a Stata DTA file.
7853pub fn read_stata(path: &Path) -> Result<DataFrame, IoError> {
7854    let content = std::fs::read(path)?;
7855    read_stata_bytes(&content)
7856}
7857
7858/// Write a DataFrame to a Stata DTA file.
7859pub fn write_stata(frame: &DataFrame, path: &Path) -> Result<(), IoError> {
7860    write_stata_with_options(frame, path, &StataWriteOptions::default())
7861}
7862
7863/// Write a DataFrame to a Stata DTA file with explicit options.
7864pub fn write_stata_with_options(
7865    frame: &DataFrame,
7866    path: &Path,
7867    options: &StataWriteOptions,
7868) -> Result<(), IoError> {
7869    let content = write_stata_bytes_with_options(frame, options)?;
7870    std::fs::write(path, content)?;
7871    Ok(())
7872}
7873
7874// ── JSONL (JSON Lines) I/O ──────────────────────────────────────────────
7875
7876/// Write a DataFrame to JSONL (JSON Lines) format.
7877///
7878/// Matches `pd.DataFrame.to_json(orient='records', lines=True)`.
7879/// Each row is written as a separate JSON object on its own line,
7880/// with no enclosing array. This format is standard for streaming
7881/// data pipelines and log processing.
7882pub fn write_jsonl_string(frame: &DataFrame) -> Result<String, IoError> {
7883    // Typed streaming fast path (\n-joined row objects, no enclosing array);
7884    // falls back to the serde tree below on anything it can't handle.
7885    if let Some(s) = try_write_json_records_typed(frame, true) {
7886        return Ok(s);
7887    }
7888    let headers: Vec<String> = frame.column_names().into_iter().cloned().collect();
7889    let row_count = frame.index().len();
7890    let column_float_promotions = headers
7891        .iter()
7892        .map(|name| {
7893            frame
7894                .column(name)
7895                .is_some_and(|column| column_promotes_int_json_values_to_float(column.values()))
7896        })
7897        .collect::<Vec<_>>();
7898
7899    let mut lines = Vec::with_capacity(row_count);
7900    for row_idx in 0..row_count {
7901        let mut obj = serde_json::Map::new();
7902        for (name, promote_int_to_float) in headers.iter().zip(column_float_promotions.iter()) {
7903            let val = frame
7904                .column(name)
7905                .and_then(|c| c.value(row_idx))
7906                .map(|value| scalar_to_json_with_column_promotion(value, *promote_int_to_float))
7907                .unwrap_or(serde_json::Value::Null);
7908            obj.insert(name.clone(), val);
7909        }
7910        lines.push(serde_json::to_string(&serde_json::Value::Object(obj))?);
7911    }
7912
7913    Ok(lines.join("\n"))
7914}
7915
7916/// Read a DataFrame from JSONL (JSON Lines) format.
7917///
7918/// Matches `pd.read_json(input, lines=True)`.
7919/// Each line must be a valid JSON object with the same keys.
7920/// Per br-frankenpandas-9l8gd: row cap to prevent DoS via hostile input.
7921/// Hostile JSONL with billions of lines would otherwise grow `all_rows`
7922/// unbounded before the column-build allocation.
7923const READ_JSONL_MAX_ROWS: usize = 100_000_000;
7924
7925pub fn read_jsonl_str(input: &str) -> Result<DataFrame, IoError> {
7926    let mut all_rows: Vec<serde_json::Map<String, serde_json::Value>> = Vec::new();
7927
7928    for line in input.lines() {
7929        let trimmed = line.trim();
7930        if trimmed.is_empty() {
7931            continue;
7932        }
7933        // Per br-frankenpandas-9l8gd: reject hostile inputs that would
7934        // exhaust memory before the column-build allocation step.
7935        if all_rows.len() >= READ_JSONL_MAX_ROWS {
7936            return Err(IoError::JsonFormat(format!(
7937                "JSONL input exceeds maximum of {READ_JSONL_MAX_ROWS} rows"
7938            )));
7939        }
7940        // Move the parsed object out of the per-line `Value` instead of cloning
7941        // it — avoids a deep copy (every key String + value) of each row's Map.
7942        match parse_json_value_allowing_pandas_nan(trimmed)? {
7943            serde_json::Value::Object(map) => all_rows.push(map),
7944            _ => {
7945                return Err(IoError::JsonFormat(
7946                    "JSONL: each line must be a JSON object".into(),
7947                ));
7948            }
7949        }
7950    }
7951
7952    if all_rows.is_empty() {
7953        return DataFrame::new(Index::new(Vec::new()), BTreeMap::new()).map_err(IoError::Frame);
7954    }
7955
7956    // Collect column names as the UNION of all keys across all rows.
7957    // This matches pandas behavior: missing keys in a row become null.
7958    let mut col_name_set = std::collections::BTreeSet::new();
7959    let mut col_names_ordered: Vec<String> = Vec::new();
7960    for row in &all_rows {
7961        for key in row.keys() {
7962            // Only clone a key the first time it is seen (uniform JSONL — every
7963            // line sharing the same keys — clones each key exactly once total,
7964            // not once per row).
7965            if !col_name_set.contains(key.as_str()) {
7966                col_name_set.insert(key.clone());
7967                col_names_ordered.push(key.clone());
7968            }
7969        }
7970    }
7971    let col_names = col_names_ordered;
7972    let mut columns: Vec<Vec<Scalar>> = col_names
7973        .iter()
7974        .map(|_| Vec::with_capacity(all_rows.len()))
7975        .collect();
7976
7977    for row in &all_rows {
7978        for (col_idx, name) in col_names.iter().enumerate() {
7979            let val = row.get(name).unwrap_or(&serde_json::Value::Null);
7980            columns[col_idx].push(json_value_to_scalar(val));
7981        }
7982    }
7983
7984    let mut out_columns = BTreeMap::new();
7985    let mut column_order = Vec::new();
7986    for (name, values) in col_names.into_iter().zip(columns) {
7987        out_columns.insert(name.clone(), column_from_json_values(values)?);
7988        column_order.push(name);
7989    }
7990
7991    let index = Index::from_i64((0..all_rows.len() as i64).collect());
7992    Ok(DataFrame::new_with_column_order(
7993        index,
7994        out_columns,
7995        column_order,
7996    )?)
7997}
7998
7999/// Write a DataFrame to a JSONL file.
8000pub fn write_jsonl(frame: &DataFrame, path: &Path) -> Result<(), IoError> {
8001    let content = write_jsonl_string(frame)?;
8002    std::fs::write(path, content)?;
8003    Ok(())
8004}
8005
8006/// Read a DataFrame from a JSONL file.
8007pub fn read_jsonl(path: &Path) -> Result<DataFrame, IoError> {
8008    let content = std::fs::read_to_string(path)?;
8009    read_jsonl_str(&content)
8010}
8011
8012// ── Parquet I/O ─────────────────────────────────────────────────────────────
8013
8014/// Convert an fp-types DType to an Arrow DataType.
8015fn dtype_to_arrow(dtype: DType) -> ArrowDataType {
8016    match dtype {
8017        DType::Int64 | DType::Int64Nullable => ArrowDataType::Int64,
8018        DType::Float64 => ArrowDataType::Float64,
8019        DType::Utf8 => ArrowDataType::Utf8,
8020        DType::Categorical => ArrowDataType::Utf8,
8021        DType::Bool | DType::BoolNullable => ArrowDataType::Boolean,
8022        DType::Null => ArrowDataType::Utf8, // fallback: null-only columns as string
8023        DType::Timedelta64 => ArrowDataType::Int64, // store as nanoseconds
8024        DType::Datetime64 => ArrowDataType::Int64, // store as nanoseconds
8025        DType::Period => ArrowDataType::Int64, // store as ordinal
8026        DType::Interval => ArrowDataType::Utf8, // store as string until arrow interval lands
8027        DType::Sparse => ArrowDataType::Utf8, // marker fallback until sparse arrays land
8028    }
8029}
8030
8031fn column_to_arrow_array(column: &Column) -> Result<Arc<dyn Array>, IoError> {
8032    let arr: Arc<dyn Array> = match column.dtype() {
8033        DType::Int64 | DType::Int64Nullable => {
8034            let mut builder = Int64Builder::with_capacity(column.len());
8035            for value in column.values() {
8036                match value {
8037                    Scalar::Int64(n) => builder.append_value(*n),
8038                    _ if value.is_missing() => builder.append_null(),
8039                    _ => builder.append_null(),
8040                }
8041            }
8042            Arc::new(builder.finish())
8043        }
8044        DType::Float64 => {
8045            let mut builder = Float64Builder::with_capacity(column.len());
8046            for value in column.values() {
8047                match value {
8048                    Scalar::Float64(n) => {
8049                        if n.is_nan() {
8050                            builder.append_null();
8051                        } else {
8052                            builder.append_value(*n);
8053                        }
8054                    }
8055                    _ if value.is_missing() => builder.append_null(),
8056                    _ => builder.append_null(),
8057                }
8058            }
8059            Arc::new(builder.finish())
8060        }
8061        DType::Bool | DType::BoolNullable => {
8062            let mut builder = BooleanBuilder::with_capacity(column.len());
8063            for value in column.values() {
8064                match value {
8065                    Scalar::Bool(flag) => builder.append_value(*flag),
8066                    _ if value.is_missing() => builder.append_null(),
8067                    _ => builder.append_null(),
8068                }
8069            }
8070            Arc::new(builder.finish())
8071        }
8072        DType::Utf8 | DType::Categorical | DType::Null | DType::Sparse => {
8073            let mut builder = StringBuilder::with_capacity(column.len(), column.len() * 8);
8074            for value in column.values() {
8075                match value {
8076                    Scalar::Utf8(text) => builder.append_value(text),
8077                    _ if value.is_missing() => builder.append_null(),
8078                    _ => builder.append_value(format!("{value:?}")),
8079                }
8080            }
8081            Arc::new(builder.finish())
8082        }
8083        DType::Timedelta64 => {
8084            let mut builder = Int64Builder::with_capacity(column.len());
8085            for value in column.values() {
8086                match value {
8087                    Scalar::Timedelta64(nanos) => {
8088                        if *nanos == Timedelta::NAT {
8089                            builder.append_null();
8090                        } else {
8091                            builder.append_value(*nanos);
8092                        }
8093                    }
8094                    _ if value.is_missing() => builder.append_null(),
8095                    _ => builder.append_null(),
8096                }
8097            }
8098            Arc::new(builder.finish())
8099        }
8100        DType::Datetime64 => {
8101            let mut builder = Int64Builder::with_capacity(column.len());
8102            for value in column.values() {
8103                match value {
8104                    Scalar::Datetime64(nanos) => {
8105                        if *nanos == Timestamp::NAT {
8106                            builder.append_null();
8107                        } else {
8108                            builder.append_value(*nanos);
8109                        }
8110                    }
8111                    _ if value.is_missing() => builder.append_null(),
8112                    _ => builder.append_null(),
8113                }
8114            }
8115            Arc::new(builder.finish())
8116        }
8117        DType::Period => {
8118            let mut builder = Int64Builder::with_capacity(column.len());
8119            for value in column.values() {
8120                match value {
8121                    Scalar::Period(p) => {
8122                        if p.ordinal == i64::MIN {
8123                            builder.append_null();
8124                        } else {
8125                            builder.append_value(p.ordinal);
8126                        }
8127                    }
8128                    _ if value.is_missing() => builder.append_null(),
8129                    _ => builder.append_null(),
8130                }
8131            }
8132            Arc::new(builder.finish())
8133        }
8134        DType::Interval => {
8135            let mut builder = StringBuilder::with_capacity(column.len(), column.len() * 32);
8136            for value in column.values() {
8137                match value {
8138                    Scalar::Interval(iv) => builder.append_value(format!("{iv}")),
8139                    _ if value.is_missing() => builder.append_null(),
8140                    _ => builder.append_null(),
8141                }
8142            }
8143            Arc::new(builder.finish())
8144        }
8145    };
8146
8147    Ok(arr)
8148}
8149
8150/// Convert a Series to its Arrow data type plus backing array.
8151///
8152/// This is the Arrow-level building block under Feather / IPC round-trips and
8153/// preserves nullable Int64 columns as Arrow null-bitmaps rather than coercing
8154/// through Float64.
8155pub fn series_to_arrow_array(series: &Series) -> Result<(ArrowDataType, Arc<dyn Array>), IoError> {
8156    let dt = dtype_to_arrow(series.column().dtype());
8157    Ok((dt, column_to_arrow_array(series.column())?))
8158}
8159
8160/// Rebuild a Series from an Arrow array and explicit dtype metadata.
8161pub fn series_from_arrow_array(
8162    name: impl Into<String>,
8163    index_labels: Vec<IndexLabel>,
8164    arr: &dyn Array,
8165    dt: &ArrowDataType,
8166) -> Result<Series, IoError> {
8167    let values = arrow_array_to_scalars(arr, dt)?;
8168    Series::from_values(name, index_labels, values).map_err(IoError::from)
8169}
8170
8171/// Build an Arrow RecordBatch from a DataFrame.
8172fn dataframe_to_record_batch(frame: &DataFrame) -> Result<RecordBatch, IoError> {
8173    let materialized = if frame.row_multiindex().is_some() {
8174        Some(materialize_synthetic_row_multiindex_columns(frame)?)
8175    } else {
8176        None
8177    };
8178    let frame = materialized.as_ref().unwrap_or(frame);
8179
8180    let col_names: Vec<String> = frame.column_names().into_iter().cloned().collect();
8181    let mut fields = Vec::with_capacity(col_names.len());
8182    let mut arrays: Vec<Arc<dyn Array>> = Vec::with_capacity(col_names.len());
8183
8184    for name in &col_names {
8185        let col = frame
8186            .column(name)
8187            .ok_or_else(|| IoError::Parquet(format!("missing column: {name}")))?;
8188        let dt = col.dtype();
8189        fields.push(Field::new(name.as_str(), dtype_to_arrow(dt), true));
8190        let arr = column_to_arrow_array(col)?;
8191        arrays.push(arr);
8192    }
8193
8194    let schema = Arc::new(Schema::new(fields));
8195    RecordBatch::try_new(schema, arrays).map_err(|e| IoError::Parquet(e.to_string()))
8196}
8197
8198/// Convert an Arrow RecordBatch back into a DataFrame.
8199fn record_batch_to_dataframe(batch: &RecordBatch) -> Result<DataFrame, IoError> {
8200    let n_rows = batch.num_rows();
8201    let schema = batch.schema();
8202    let mut columns = BTreeMap::new();
8203    let mut col_order = Vec::new();
8204
8205    for (i, field) in schema.fields().iter().enumerate() {
8206        let name = field.name().clone();
8207        let arr = batch.column(i);
8208        // Typed fast path: convert the Arrow buffer DIRECTLY to a typed fp column
8209        // (Int64/Float64/Bool/all-valid-Utf8), skipping the per-cell Vec<Scalar>
8210        // materialization (~32 B/elem boxing) + Column::new re-scan that made
8211        // read_parquet ~0.21x pandas/pyarrow. Bails (→ Scalar path) for
8212        // Date/Timestamp (need chrono formatting) and nullable-Utf8 (no typed
8213        // contiguous-nullable constructor). Bit-identical to the Scalar path's
8214        // per-type null-kind conventions (Int/Bool/Utf8 → Null(Null); Float →
8215        // Null(NaN)); validity constructors reproduce those exactly (verified).
8216        let col = match arrow_array_to_column_typed(arr.as_ref(), field.data_type()) {
8217            Some(c) => c,
8218            None => {
8219                let values = arrow_array_to_scalars(arr.as_ref(), field.data_type())?;
8220                let dtype = fp_dtype_for_arrow_data_type(field.data_type());
8221                Column::new(dtype, values)?
8222            }
8223        };
8224        columns.insert(name.clone(), col);
8225        col_order.push(name);
8226    }
8227
8228    // A parquet batch gets the default 0..n RangeIndex. Use the LAZY unit-range
8229    // index instead of materializing a Vec<IndexLabel> of n_rows + Index::new
8230    // (which was ~110ms of a 137ms 1M-row read — the real read_parquet bottleneck,
8231    // NOT the ~27ms decode). Bit-identical: same integer labels 0..n_rows.
8232    let index = Index::new_known_unique_int64_unit_range(0, n_rows);
8233
8234    let frame = DataFrame::new_with_column_order(index, columns, col_order)?;
8235    promote_synthetic_row_multiindex_if_present(&frame)
8236}
8237
8238fn fp_dtype_for_arrow_data_type(dt: &ArrowDataType) -> DType {
8239    match dt {
8240        ArrowDataType::Int8
8241        | ArrowDataType::Int16
8242        | ArrowDataType::Int32
8243        | ArrowDataType::Int64
8244        | ArrowDataType::UInt8
8245        | ArrowDataType::UInt16
8246        | ArrowDataType::UInt32
8247        | ArrowDataType::UInt64 => DType::Int64,
8248        ArrowDataType::Float16 | ArrowDataType::Float32 | ArrowDataType::Float64 => DType::Float64,
8249        ArrowDataType::Boolean => DType::Bool,
8250        ArrowDataType::Utf8
8251        | ArrowDataType::LargeUtf8
8252        | ArrowDataType::Date32
8253        | ArrowDataType::Date64
8254        | ArrowDataType::Timestamp(_, _) => DType::Utf8,
8255        _ => DType::Utf8,
8256    }
8257}
8258
8259/// Build an fp `ValidityMask` from an Arrow array's null buffer, or `None` when
8260/// the array has no nulls (caller uses the all-valid constructor).
8261fn arrow_validity_mask(arr: &dyn Array) -> Option<fp_columnar::ValidityMask> {
8262    if arr.null_count() == 0 {
8263        return None;
8264    }
8265    let len = arr.len();
8266    let mut mask = fp_columnar::ValidityMask::all_valid(len);
8267    for i in 0..len {
8268        if arr.is_null(i) {
8269            mask.set(i, false);
8270        }
8271    }
8272    Some(mask)
8273}
8274
8275/// Typed Arrow-array → fp `Column` conversion (br-frankenpandas parquet-typed):
8276/// reads the Arrow buffer directly into a typed fp column, bypassing the per-cell
8277/// `Vec<Scalar>` boxing + `Column::new` re-scan of `arrow_array_to_scalars`.
8278/// Returns `None` for types that need the Scalar path (Date/Timestamp string
8279/// coercion, nullable Utf8, and any uncovered dtype). Bit-identical to that path.
8280fn arrow_array_to_column_typed(arr: &dyn Array, dt: &ArrowDataType) -> Option<Column> {
8281    use arrow::array::{
8282        Float32Array, Float64Array, Int8Array, Int16Array, Int32Array, Int64Array, UInt8Array,
8283        UInt16Array, UInt32Array, UInt64Array,
8284    };
8285    macro_rules! i64_col {
8286        ($ty:ty) => {{
8287            let t = arr.as_any().downcast_ref::<$ty>()?;
8288            let data: Vec<i64> = t.values().iter().map(|&v| v as i64).collect();
8289            Some(match arrow_validity_mask(arr) {
8290                Some(m) => Column::from_i64_values_with_validity(data, m),
8291                // MOVE the gathered Vec into the backing (one Arc::new) rather than
8292                // from_i64_values' Arc::from(Vec) alloc+memcpy (~28ms/5M) — a second
8293                // copy on top of the Arrow-buffer gather. All-valid, so _owned fits.
8294                None => Column::from_i64_values_owned(data),
8295            })
8296        }};
8297    }
8298    macro_rules! f64_col {
8299        ($ty:ty) => {{
8300            let t = arr.as_any().downcast_ref::<$ty>()?;
8301            let data: Vec<f64> = t.values().iter().map(|&v| v as f64).collect();
8302            Some(match arrow_validity_mask(arr) {
8303                Some(m) => Column::from_f64_values_with_validity(data, m),
8304                None => Column::from_f64_values_owned(data),
8305            })
8306        }};
8307    }
8308    match dt {
8309        ArrowDataType::Int64 => i64_col!(Int64Array),
8310        ArrowDataType::Int32 => i64_col!(Int32Array),
8311        ArrowDataType::Int16 => i64_col!(Int16Array),
8312        ArrowDataType::Int8 => i64_col!(Int8Array),
8313        // UInt64 as i64: matches the Scalar path's `Scalar::Int64(value as ...)`
8314        // reinterpretation for the width; large u64 wrap identically both ways.
8315        ArrowDataType::UInt64 => i64_col!(UInt64Array),
8316        ArrowDataType::UInt32 => i64_col!(UInt32Array),
8317        ArrowDataType::UInt16 => i64_col!(UInt16Array),
8318        ArrowDataType::UInt8 => i64_col!(UInt8Array),
8319        ArrowDataType::Float64 => f64_col!(Float64Array),
8320        ArrowDataType::Float32 => f64_col!(Float32Array),
8321        ArrowDataType::Boolean => {
8322            let t = arr.as_any().downcast_ref::<BooleanArray>()?;
8323            let data: Vec<bool> = (0..t.len()).map(|i| t.value(i)).collect();
8324            Some(match arrow_validity_mask(arr) {
8325                Some(m) => Column::from_bool_values_with_validity(data, m),
8326                None => Column::from_bool_values(data),
8327            })
8328        }
8329        // Only the all-valid case: there is no typed contiguous-nullable-Utf8
8330        // constructor, so a StringArray with nulls falls to the Scalar path.
8331        ArrowDataType::Utf8 if arr.null_count() == 0 => {
8332            let t = arr.as_any().downcast_ref::<StringArray>()?;
8333            let offs = t.value_offsets();
8334            let len = t.len();
8335            let start = offs[0] as usize;
8336            let end = offs[len] as usize;
8337            let bytes = t.value_data()[start..end].to_vec();
8338            let offsets: Vec<usize> = offs.iter().map(|&o| o as usize - start).collect();
8339            Some(Column::from_utf8_contiguous(bytes, offsets))
8340        }
8341        ArrowDataType::LargeUtf8 if arr.null_count() == 0 => {
8342            let t = arr
8343                .as_any()
8344                .downcast_ref::<arrow::array::LargeStringArray>()?;
8345            let offs = t.value_offsets();
8346            let len = t.len();
8347            let start = offs[0] as usize;
8348            let end = offs[len] as usize;
8349            let bytes = t.value_data()[start..end].to_vec();
8350            let offsets: Vec<usize> = offs.iter().map(|&o| o as usize - start).collect();
8351            Some(Column::from_utf8_contiguous(bytes, offsets))
8352        }
8353        _ => None,
8354    }
8355}
8356
8357/// Convert an Arrow array + data type to a Vec of Scalars.
8358fn arrow_array_to_scalars(arr: &dyn Array, dt: &ArrowDataType) -> Result<Vec<Scalar>, IoError> {
8359    let len = arr.len();
8360    let mut scalars = Vec::with_capacity(len);
8361
8362    match dt {
8363        ArrowDataType::Int64 => {
8364            let typed = arr
8365                .as_any()
8366                .downcast_ref::<Int64Array>()
8367                .ok_or_else(|| IoError::Parquet("expected Int64Array".into()))?;
8368            for i in 0..len {
8369                if typed.is_null(i) {
8370                    scalars.push(Scalar::Null(NullKind::Null));
8371                } else {
8372                    scalars.push(Scalar::Int64(typed.value(i)));
8373                }
8374            }
8375        }
8376        ArrowDataType::Int32 => {
8377            let typed = arr
8378                .as_any()
8379                .downcast_ref::<arrow::array::Int32Array>()
8380                .ok_or_else(|| IoError::Parquet("expected Int32Array".into()))?;
8381            for i in 0..len {
8382                if typed.is_null(i) {
8383                    scalars.push(Scalar::Null(NullKind::Null));
8384                } else {
8385                    scalars.push(Scalar::Int64(i64::from(typed.value(i))));
8386                }
8387            }
8388        }
8389        ArrowDataType::Float64 => {
8390            let typed = arr
8391                .as_any()
8392                .downcast_ref::<Float64Array>()
8393                .ok_or_else(|| IoError::Parquet("expected Float64Array".into()))?;
8394            for i in 0..len {
8395                if typed.is_null(i) {
8396                    scalars.push(Scalar::Null(NullKind::NaN));
8397                } else {
8398                    scalars.push(Scalar::Float64(typed.value(i)));
8399                }
8400            }
8401        }
8402        ArrowDataType::Float32 => {
8403            let typed = arr
8404                .as_any()
8405                .downcast_ref::<arrow::array::Float32Array>()
8406                .ok_or_else(|| IoError::Parquet("expected Float32Array".into()))?;
8407            for i in 0..len {
8408                if typed.is_null(i) {
8409                    scalars.push(Scalar::Null(NullKind::NaN));
8410                } else {
8411                    scalars.push(Scalar::Float64(f64::from(typed.value(i))));
8412                }
8413            }
8414        }
8415        ArrowDataType::Boolean => {
8416            let typed = arr
8417                .as_any()
8418                .downcast_ref::<BooleanArray>()
8419                .ok_or_else(|| IoError::Parquet("expected BooleanArray".into()))?;
8420            for i in 0..len {
8421                if typed.is_null(i) {
8422                    scalars.push(Scalar::Null(NullKind::Null));
8423                } else {
8424                    scalars.push(Scalar::Bool(typed.value(i)));
8425                }
8426            }
8427        }
8428        ArrowDataType::Utf8 => {
8429            let typed = arr
8430                .as_any()
8431                .downcast_ref::<StringArray>()
8432                .ok_or_else(|| IoError::Parquet("expected StringArray".into()))?;
8433            for i in 0..len {
8434                if typed.is_null(i) {
8435                    scalars.push(Scalar::Null(NullKind::Null));
8436                } else {
8437                    scalars.push(Scalar::Utf8(typed.value(i).to_owned()));
8438                }
8439            }
8440        }
8441        ArrowDataType::LargeUtf8 => {
8442            let typed = arr
8443                .as_any()
8444                .downcast_ref::<arrow::array::LargeStringArray>()
8445                .ok_or_else(|| IoError::Parquet("expected LargeStringArray".into()))?;
8446            for i in 0..len {
8447                if typed.is_null(i) {
8448                    scalars.push(Scalar::Null(NullKind::Null));
8449                } else {
8450                    scalars.push(Scalar::Utf8(typed.value(i).to_owned()));
8451                }
8452            }
8453        }
8454        ArrowDataType::Date32 => {
8455            let typed = arr
8456                .as_any()
8457                .downcast_ref::<Date32Array>()
8458                .ok_or_else(|| IoError::Parquet("expected Date32Array".into()))?;
8459            for i in 0..len {
8460                if typed.is_null(i) {
8461                    scalars.push(Scalar::Null(NullKind::NaT));
8462                } else {
8463                    if let Some(date) = arrow::temporal_conversions::as_date::<
8464                        arrow::datatypes::Date32Type,
8465                    >(typed.value(i).into())
8466                    {
8467                        scalars.push(Scalar::Utf8(date.format("%Y-%m-%d").to_string()));
8468                    } else {
8469                        scalars.push(Scalar::Null(NullKind::NaT));
8470                    }
8471                }
8472            }
8473        }
8474        ArrowDataType::Date64 => {
8475            let typed = arr
8476                .as_any()
8477                .downcast_ref::<Date64Array>()
8478                .ok_or_else(|| IoError::Parquet("expected Date64Array".into()))?;
8479            for i in 0..len {
8480                if typed.is_null(i) {
8481                    scalars.push(Scalar::Null(NullKind::NaT));
8482                } else {
8483                    if let Some(dt) = arrow::temporal_conversions::as_datetime::<
8484                        arrow::datatypes::Date64Type,
8485                    >(typed.value(i))
8486                    {
8487                        scalars.push(Scalar::Utf8(dt.format("%Y-%m-%d").to_string()));
8488                    } else {
8489                        scalars.push(Scalar::Null(NullKind::NaT));
8490                    }
8491                }
8492            }
8493        }
8494        ArrowDataType::Timestamp(unit, _tz) => match unit {
8495            TimeUnit::Second => {
8496                let typed = arr
8497                    .as_any()
8498                    .downcast_ref::<TimestampSecondArray>()
8499                    .ok_or_else(|| IoError::Parquet("expected TimestampSecondArray".into()))?;
8500                for i in 0..len {
8501                    if typed.is_null(i) {
8502                        scalars.push(Scalar::Null(NullKind::NaT));
8503                    } else {
8504                        if let Some(dt) = arrow::temporal_conversions::as_datetime::<
8505                            arrow::datatypes::TimestampSecondType,
8506                        >(typed.value(i))
8507                        {
8508                            scalars.push(Scalar::Utf8(dt.format("%Y-%m-%d %H:%M:%S").to_string()));
8509                        } else {
8510                            scalars.push(Scalar::Null(NullKind::NaT));
8511                        }
8512                    }
8513                }
8514            }
8515            TimeUnit::Millisecond => {
8516                let typed = arr
8517                    .as_any()
8518                    .downcast_ref::<TimestampMillisecondArray>()
8519                    .ok_or_else(|| IoError::Parquet("expected TimestampMillisecondArray".into()))?;
8520                for i in 0..len {
8521                    if typed.is_null(i) {
8522                        scalars.push(Scalar::Null(NullKind::NaT));
8523                    } else {
8524                        if let Some(dt) = arrow::temporal_conversions::as_datetime::<
8525                            arrow::datatypes::TimestampMillisecondType,
8526                        >(typed.value(i))
8527                        {
8528                            scalars.push(Scalar::Utf8(dt.format("%Y-%m-%d %H:%M:%S").to_string()));
8529                        } else {
8530                            scalars.push(Scalar::Null(NullKind::NaT));
8531                        }
8532                    }
8533                }
8534            }
8535            TimeUnit::Microsecond => {
8536                let typed = arr
8537                    .as_any()
8538                    .downcast_ref::<TimestampMicrosecondArray>()
8539                    .ok_or_else(|| IoError::Parquet("expected TimestampMicrosecondArray".into()))?;
8540                for i in 0..len {
8541                    if typed.is_null(i) {
8542                        scalars.push(Scalar::Null(NullKind::NaT));
8543                    } else {
8544                        if let Some(dt) = arrow::temporal_conversions::as_datetime::<
8545                            arrow::datatypes::TimestampMicrosecondType,
8546                        >(typed.value(i))
8547                        {
8548                            scalars
8549                                .push(Scalar::Utf8(dt.format("%Y-%m-%d %H:%M:%S%.6f").to_string()));
8550                        } else {
8551                            scalars.push(Scalar::Null(NullKind::NaT));
8552                        }
8553                    }
8554                }
8555            }
8556            TimeUnit::Nanosecond => {
8557                let typed = arr
8558                    .as_any()
8559                    .downcast_ref::<TimestampNanosecondArray>()
8560                    .ok_or_else(|| IoError::Parquet("expected TimestampNanosecondArray".into()))?;
8561                for i in 0..len {
8562                    if typed.is_null(i) {
8563                        scalars.push(Scalar::Null(NullKind::NaT));
8564                    } else {
8565                        if let Some(dt) = arrow::temporal_conversions::as_datetime::<
8566                            arrow::datatypes::TimestampNanosecondType,
8567                        >(typed.value(i))
8568                        {
8569                            scalars
8570                                .push(Scalar::Utf8(dt.format("%Y-%m-%d %H:%M:%S%.9f").to_string()));
8571                        } else {
8572                            scalars.push(Scalar::Null(NullKind::NaT));
8573                        }
8574                    }
8575                }
8576            }
8577        },
8578        other => {
8579            return Err(IoError::Parquet(format!(
8580                "unsupported Arrow data type: {other:?}"
8581            )));
8582        }
8583    }
8584
8585    Ok(scalars)
8586}
8587
8588/// Write a DataFrame to an in-memory Parquet buffer.
8589pub fn write_parquet_bytes(frame: &DataFrame) -> Result<Vec<u8>, IoError> {
8590    let batch = dataframe_to_record_batch(frame)?;
8591    let mut buf = Vec::new();
8592    let mut writer = ArrowWriter::try_new(&mut buf, batch.schema(), None)
8593        .map_err(|e| IoError::Parquet(e.to_string()))?;
8594    writer
8595        .write(&batch)
8596        .map_err(|e| IoError::Parquet(e.to_string()))?;
8597    writer
8598        .close()
8599        .map_err(|e| IoError::Parquet(e.to_string()))?;
8600    Ok(buf)
8601}
8602
8603/// Read a DataFrame from in-memory Parquet bytes.
8604pub fn read_parquet_bytes(data: &[u8]) -> Result<DataFrame, IoError> {
8605    let b = bytes::Bytes::from(data.to_vec());
8606    let builder =
8607        ParquetRecordBatchReaderBuilder::try_new(b).map_err(|e| IoError::Parquet(e.to_string()))?;
8608    // Read the whole file as ONE record batch instead of the default 1024-row
8609    // batches: a 1M-row file otherwise yields ~1000 tiny batches, each turned into
8610    // a DataFrame and then concatenated — the many-batch + concat overhead (not
8611    // the decode) dominated read_parquet (~0.21x pandas). Sizing the batch to the
8612    // row count collapses that to a single typed conversion, no concat. Clamp so a
8613    // pathological row count can't request an absurd allocation up front.
8614    let total_rows = builder.metadata().file_metadata().num_rows().max(0) as usize;
8615    let batch_size = total_rows.clamp(1, 16 * 1024 * 1024);
8616    let reader = builder
8617        .with_batch_size(batch_size)
8618        .build()
8619        .map_err(|e| IoError::Parquet(e.to_string()))?;
8620
8621    let mut all_frames: Vec<DataFrame> = Vec::new();
8622    for batch_result in reader {
8623        let batch: RecordBatch =
8624            batch_result.map_err(|e: arrow::error::ArrowError| IoError::Parquet(e.to_string()))?;
8625        all_frames.push(record_batch_to_dataframe(&batch)?);
8626    }
8627
8628    if all_frames.is_empty() {
8629        // Return empty DataFrame
8630        return Ok(DataFrame::new_with_column_order(
8631            Index::new(vec![]),
8632            BTreeMap::new(),
8633            vec![],
8634        )?);
8635    }
8636
8637    // For a single batch (common case), return directly
8638    if all_frames.len() == 1 {
8639        if let Some(frame) = all_frames.into_iter().next() {
8640            return Ok(frame);
8641        }
8642        return Err(IoError::Parquet(
8643            "parquet reader produced zero record batches".to_owned(),
8644        ));
8645    }
8646
8647    // Multiple batches: concatenate via fp_frame::concat_dataframes
8648    let refs: Vec<&DataFrame> = all_frames.iter().collect();
8649    fp_frame::concat_dataframes(&refs).map_err(IoError::from)
8650}
8651
8652/// Write a DataFrame to a Parquet file.
8653pub fn write_parquet(frame: &DataFrame, path: &Path) -> Result<(), IoError> {
8654    let bytes = write_parquet_bytes(frame)?;
8655    std::fs::write(path, bytes)?;
8656    Ok(())
8657}
8658
8659/// Read a DataFrame from a Parquet file.
8660pub fn read_parquet(path: &Path) -> Result<DataFrame, IoError> {
8661    let data = std::fs::read(path)?;
8662    read_parquet_bytes(&data)
8663}
8664
8665// ── ORC I/O ────────────────────────────────────────────────────────────────
8666
8667/// Write a DataFrame to an in-memory ORC buffer.
8668///
8669/// This fails closed under the workspace no-Tokio policy. The previous
8670/// implementation delegated to `orc-rust`, which unconditionally pulled Tokio
8671/// into `fp-io` and therefore into the umbrella `frankenpandas` crate.
8672pub fn write_orc_bytes(_frame: &DataFrame) -> Result<Vec<u8>, IoError> {
8673    Err(orc_no_tokio_error())
8674}
8675
8676/// Read a DataFrame from in-memory ORC bytes.
8677pub fn read_orc_bytes(_data: &[u8]) -> Result<DataFrame, IoError> {
8678    Err(orc_no_tokio_error())
8679}
8680
8681/// Write a DataFrame to an ORC file.
8682pub fn write_orc(_frame: &DataFrame, _path: &Path) -> Result<(), IoError> {
8683    Err(orc_no_tokio_error())
8684}
8685
8686/// Read a DataFrame from an ORC file.
8687pub fn read_orc(_path: &Path) -> Result<DataFrame, IoError> {
8688    Err(orc_no_tokio_error())
8689}
8690
8691// ── Excel (xlsx) I/O ────────────────────────────────────────────────────
8692
8693/// Options for reading Excel files.
8694#[derive(Debug, Clone)]
8695pub struct ExcelReadOptions {
8696    /// Sheet name to read. If `None`, reads the first sheet.
8697    pub sheet_name: Option<String>,
8698    /// Whether the first row contains column headers.
8699    pub has_headers: bool,
8700    /// Read only these columns (by name). `None` means read all.
8701    /// Matches pandas `usecols` parameter for label-based selection.
8702    pub usecols: Option<Vec<String>>,
8703    /// Explicit column names to use instead of worksheet headers or
8704    /// auto-generated `column_N` names. Matches pandas `names=...`.
8705    pub names: Option<Vec<String>>,
8706    /// Optional column to use as the DataFrame index.
8707    pub index_col: Option<String>,
8708    /// Number of initial rows to skip before reading headers/data.
8709    pub skip_rows: usize,
8710}
8711
8712impl Default for ExcelReadOptions {
8713    fn default() -> Self {
8714        Self {
8715            sheet_name: None,
8716            has_headers: true,
8717            usecols: None,
8718            names: None,
8719            index_col: None,
8720            skip_rows: 0,
8721        }
8722    }
8723}
8724
8725/// Convert a calamine `Data` cell value to a `Scalar`.
8726fn excel_cell_to_scalar(cell: &calamine::Data) -> Scalar {
8727    match cell {
8728        calamine::Data::Int(v) => Scalar::Int64(*v),
8729        calamine::Data::Float(v) => {
8730            if v.is_nan() {
8731                Scalar::Null(NullKind::NaN)
8732            } else if v.fract() == 0.0 && *v >= i64::MIN as f64 && *v <= i64::MAX as f64 {
8733                // Excel stores integers as floats; recover Int64 for whole numbers.
8734                Scalar::Int64(*v as i64)
8735            } else {
8736                Scalar::Float64(*v)
8737            }
8738        }
8739        calamine::Data::String(s) => {
8740            if s.is_empty() {
8741                Scalar::Null(NullKind::Null)
8742            } else {
8743                Scalar::Utf8(s.clone())
8744            }
8745        }
8746        calamine::Data::Bool(b) => Scalar::Bool(*b),
8747        calamine::Data::Empty => Scalar::Null(NullKind::Null),
8748        calamine::Data::DateTime(dt) => {
8749            // Convert ExcelDateTime to string representation for now.
8750            Scalar::Utf8(format!("{dt}"))
8751        }
8752        calamine::Data::DateTimeIso(s) => Scalar::Utf8(s.clone()),
8753        calamine::Data::DurationIso(s) => Scalar::Utf8(s.clone()),
8754        calamine::Data::Error(e) => Scalar::Utf8(format!("#ERROR:{e:?}")),
8755    }
8756}
8757
8758/// Convert a Scalar to an IndexLabel, handling float precision correctly.
8759fn scalar_to_index_label(scalar: Scalar) -> IndexLabel {
8760    match scalar {
8761        Scalar::Int64(v) => IndexLabel::Int64(v),
8762        Scalar::Utf8(s) => IndexLabel::Utf8(s),
8763        Scalar::Float64(v) if v.fract() == 0.0 && v >= i64::MIN as f64 && v <= i64::MAX as f64 => {
8764            IndexLabel::Int64(v as i64)
8765        }
8766        Scalar::Float64(v) => IndexLabel::Utf8(v.to_string()),
8767        Scalar::Bool(b) => IndexLabel::Utf8(if b { "True" } else { "False" }.to_string()),
8768        _ => IndexLabel::Utf8(String::new()),
8769    }
8770}
8771
8772fn infer_writer_emitted_default_excel_index_col(
8773    headers: &[String],
8774    header_generated: &[bool],
8775    columns: &[Vec<Scalar>],
8776    options: &ExcelReadOptions,
8777) -> Option<usize> {
8778    if !options.has_headers
8779        || options.index_col.is_some()
8780        || options.usecols.is_some()
8781        || options.names.is_some()
8782    {
8783        return None;
8784    }
8785
8786    if headers.first()?.as_str() != "column_0"
8787        || !header_generated.first().copied().unwrap_or(false)
8788    {
8789        return None;
8790    }
8791
8792    let first_col = columns.first()?;
8793    if first_col
8794        .iter()
8795        .enumerate()
8796        .all(|(idx, scalar)| matches!(scalar, Scalar::Int64(value) if *value == idx as i64))
8797    {
8798        Some(0)
8799    } else {
8800        None
8801    }
8802}
8803
8804/// Shared parsing logic for Excel data after extracting rows from a workbook.
8805fn parse_excel_rows(
8806    rows: Vec<Vec<calamine::Data>>,
8807    options: &ExcelReadOptions,
8808) -> Result<DataFrame, IoError> {
8809    if rows.is_empty() {
8810        return DataFrame::new(Index::new(Vec::new()), BTreeMap::new()).map_err(IoError::Frame);
8811    }
8812
8813    let resolve_names = |width: usize| -> Result<Option<Vec<String>>, IoError> {
8814        options.names.as_ref().map_or(Ok(None), |names| {
8815            if names.len() == width {
8816                Ok(Some(names.clone()))
8817            } else {
8818                Err(IoError::Excel(format!(
8819                    "expected {width} column names, got {}",
8820                    names.len()
8821                )))
8822            }
8823        })
8824    };
8825
8826    // Extract headers.
8827    let (headers, header_generated, data_rows) = if options.has_headers {
8828        let header_row = &rows[0];
8829        let header_width = header_row.len();
8830        let provided_names = resolve_names(header_width)?;
8831        let (headers, header_generated): (Vec<_>, Vec<_>) = if let Some(names) = provided_names {
8832            (names, vec![false; header_width])
8833        } else {
8834            let header_pairs: Vec<(String, bool)> = header_row
8835                .iter()
8836                .enumerate()
8837                .map(|(i, cell)| match cell {
8838                    calamine::Data::String(s) if !s.is_empty() => (s.clone(), false),
8839                    _ => (format!("column_{i}"), true),
8840                })
8841                .collect();
8842            header_pairs.into_iter().unzip()
8843        };
8844        (headers, header_generated, &rows[1..])
8845    } else {
8846        let ncols = rows.iter().map(Vec::len).max().unwrap_or(0);
8847        let provided_names = resolve_names(ncols)?;
8848        let (headers, header_generated) = if let Some(names) = provided_names {
8849            (names, vec![false; ncols])
8850        } else {
8851            let headers: Vec<String> = (0..ncols).map(|i| format!("column_{i}")).collect();
8852            let header_generated = vec![true; ncols];
8853            (headers, header_generated)
8854        };
8855        (headers, header_generated, rows.as_slice())
8856    };
8857    reject_duplicate_headers(&headers)?;
8858
8859    if let Some(ref usecols) = options.usecols {
8860        validate_usecols(&headers, usecols)?;
8861    }
8862
8863    let ncols = headers.len();
8864
8865    // Accumulate columns.
8866    let mut columns: Vec<Vec<Scalar>> = (0..ncols)
8867        .map(|_| Vec::with_capacity(data_rows.len()))
8868        .collect();
8869
8870    for row in data_rows {
8871        for (col_idx, col_vec) in columns.iter_mut().enumerate() {
8872            let cell = row.get(col_idx).unwrap_or(&calamine::Data::Empty);
8873            col_vec.push(excel_cell_to_scalar(cell));
8874        }
8875    }
8876
8877    let (headers, header_generated, columns) = if let Some(ref usecols) = options.usecols {
8878        let mut filtered_headers = Vec::new();
8879        let mut filtered_generated = Vec::new();
8880        let mut filtered_columns = Vec::new();
8881        for ((name, generated), values) in headers.into_iter().zip(header_generated).zip(columns) {
8882            if usecols.contains(&name) {
8883                filtered_headers.push(name);
8884                filtered_generated.push(generated);
8885                filtered_columns.push(values);
8886            }
8887        }
8888        (filtered_headers, filtered_generated, filtered_columns)
8889    } else {
8890        (headers, header_generated, columns)
8891    };
8892
8893    // Handle index_col if specified.
8894    let index_col_idx = if let Some(ref idx_name) = options.index_col {
8895        let pos = headers.iter().position(|h| h == idx_name);
8896        if pos.is_none() {
8897            return Err(IoError::MissingIndexColumn(idx_name.clone()));
8898        }
8899        pos
8900    } else {
8901        infer_writer_emitted_default_excel_index_col(&headers, &header_generated, &columns, options)
8902    };
8903
8904    let index_name = index_col_idx.and_then(|idx_pos| {
8905        if !header_generated[idx_pos] {
8906            Some(headers[idx_pos].clone())
8907        } else {
8908            None
8909        }
8910    });
8911
8912    let mut out_columns = BTreeMap::new();
8913    let mut column_order = Vec::new();
8914
8915    for (idx, (name, values)) in headers.into_iter().zip(columns).enumerate() {
8916        if Some(idx) == index_col_idx {
8917            continue; // skip index column from data columns
8918        }
8919        out_columns.insert(name.clone(), Column::from_values(values)?);
8920        column_order.push(name);
8921    }
8922
8923    let index = if let Some(idx_pos) = index_col_idx {
8924        let idx_labels: Vec<IndexLabel> = data_rows
8925            .iter()
8926            .map(|row| {
8927                let cell = row.get(idx_pos).unwrap_or(&calamine::Data::Empty);
8928                scalar_to_index_label(excel_cell_to_scalar(cell))
8929            })
8930            .collect();
8931        Index::new(idx_labels).set_names(index_name.as_deref())
8932    } else {
8933        Index::from_i64((0..data_rows.len() as i64).collect())
8934    };
8935
8936    Ok(DataFrame::new_with_column_order(
8937        index,
8938        out_columns,
8939        column_order,
8940    )?)
8941}
8942
8943/// Read an Excel (.xlsx/.xls/.xlsb/.ods) file into a DataFrame.
8944///
8945/// Matches `pd.read_excel(path)` for basic usage.
8946pub fn read_excel(path: &Path, options: &ExcelReadOptions) -> Result<DataFrame, IoError> {
8947    use calamine::{Reader, open_workbook_auto};
8948
8949    let mut workbook = open_workbook_auto(path)
8950        .map_err(|e| IoError::Excel(format!("cannot open workbook: {e}")))?;
8951
8952    let sheet_name = if let Some(ref name) = options.sheet_name {
8953        name.clone()
8954    } else {
8955        let names = workbook.sheet_names();
8956        if names.is_empty() {
8957            return Err(IoError::Excel("workbook contains no sheets".into()));
8958        }
8959        names[0].clone()
8960    };
8961
8962    let range = workbook
8963        .worksheet_range(&sheet_name)
8964        .map_err(|e| IoError::Excel(format!("cannot read sheet '{sheet_name}': {e}")))?;
8965
8966    let rows: Vec<Vec<calamine::Data>> = range
8967        .rows()
8968        .skip(options.skip_rows)
8969        .map(|r| r.to_vec())
8970        .collect();
8971
8972    parse_excel_rows(rows, options)
8973}
8974
8975pub fn read_excel_with_index_cols(
8976    path: &Path,
8977    options: &ExcelReadOptions,
8978    index_cols: &[&str],
8979) -> Result<DataFrame, IoError> {
8980    let frame = read_excel(path, options)?;
8981    promote_frame_index_columns(&frame, index_cols)
8982}
8983
8984/// Read Excel from in-memory bytes.
8985pub fn read_excel_bytes(data: &[u8], options: &ExcelReadOptions) -> Result<DataFrame, IoError> {
8986    use calamine::{Reader, open_workbook_auto_from_rs};
8987
8988    let cursor = std::io::Cursor::new(data);
8989    let mut workbook = open_workbook_auto_from_rs(cursor)
8990        .map_err(|e| IoError::Excel(format!("cannot open workbook from bytes: {e}")))?;
8991
8992    let sheet_name = if let Some(ref name) = options.sheet_name {
8993        name.clone()
8994    } else {
8995        let names = workbook.sheet_names();
8996        if names.is_empty() {
8997            return Err(IoError::Excel("workbook contains no sheets".into()));
8998        }
8999        names[0].clone()
9000    };
9001
9002    let range = workbook
9003        .worksheet_range(&sheet_name)
9004        .map_err(|e| IoError::Excel(format!("cannot read sheet '{sheet_name}': {e}")))?;
9005
9006    let rows: Vec<Vec<calamine::Data>> = range
9007        .rows()
9008        .skip(options.skip_rows)
9009        .map(|r| r.to_vec())
9010        .collect();
9011
9012    parse_excel_rows(rows, options)
9013}
9014
9015pub fn read_excel_bytes_with_index_cols(
9016    data: &[u8],
9017    options: &ExcelReadOptions,
9018    index_cols: &[&str],
9019) -> Result<DataFrame, IoError> {
9020    let frame = read_excel_bytes(data, options)?;
9021    promote_frame_index_columns(&frame, index_cols)
9022}
9023
9024/// Read multiple sheets from an Excel file.
9025///
9026/// Matches `pd.read_excel(path, sheet_name=[...])` when `sheet_name`
9027/// is a list of sheet names — pandas returns a dict
9028/// `{name: DataFrame}`. Pass `sheet_names=None` to read every sheet
9029/// in the workbook (pandas `sheet_name=None`).
9030///
9031/// The outer Excel reader options (`has_headers`, `index_col`,
9032/// `skip_rows`) are applied uniformly to each selected sheet. The
9033/// per-sheet `sheet_name` option on `options` is ignored here
9034/// because the explicit `sheet_names` argument drives selection.
9035/// Read multiple sheets preserving workbook iteration order.
9036///
9037/// Matches `pd.read_excel(sheet_name=None)` exactly — pandas returns
9038/// a `dict` and, since Python 3.7, dict iteration order matches
9039/// insertion order, which in turn matches workbook sheet position.
9040/// `BTreeMap` (used by `read_excel_sheets`) would alphabetize, so
9041/// this sibling returns `Vec<(String, DataFrame)>` to preserve order.
9042pub fn read_excel_sheets_ordered(
9043    path: &Path,
9044    sheet_names: Option<&[String]>,
9045    options: &ExcelReadOptions,
9046) -> Result<Vec<(String, DataFrame)>, IoError> {
9047    use calamine::{Reader, open_workbook_auto};
9048
9049    let mut workbook = open_workbook_auto(path)
9050        .map_err(|e| IoError::Excel(format!("cannot open workbook: {e}")))?;
9051    let available: Vec<String> = workbook.sheet_names();
9052    // Per br-frankenpandas-c9cb4: HashSet<&str> for O(1) membership;
9053    // was O(m × n) Vec::iter().any() per requested name.
9054    let available_set: HashSet<&str> = available.iter().map(String::as_str).collect();
9055    let selected: Vec<String> = match sheet_names {
9056        Some(names) => {
9057            for name in names {
9058                if !available_set.contains(name.as_str()) {
9059                    return Err(IoError::Excel(format!(
9060                        "workbook does not contain sheet {name:?}"
9061                    )));
9062                }
9063            }
9064            names.to_vec()
9065        }
9066        None => available.clone(),
9067    };
9068    if selected.is_empty() {
9069        return Err(IoError::Excel("no sheets selected".to_owned()));
9070    }
9071    let mut out = Vec::with_capacity(selected.len());
9072    for sheet in &selected {
9073        let range = workbook
9074            .worksheet_range(sheet)
9075            .map_err(|e| IoError::Excel(format!("cannot read sheet {sheet:?}: {e}")))?;
9076        let rows: Vec<Vec<calamine::Data>> = range
9077            .rows()
9078            .skip(options.skip_rows)
9079            .map(|r| r.to_vec())
9080            .collect();
9081        let frame = parse_excel_rows(rows, options)?;
9082        out.push((sheet.clone(), frame));
9083    }
9084    Ok(out)
9085}
9086
9087/// Byte-based counterpart to `read_excel_sheets_ordered`.
9088pub fn read_excel_sheets_ordered_bytes(
9089    data: &[u8],
9090    sheet_names: Option<&[String]>,
9091    options: &ExcelReadOptions,
9092) -> Result<Vec<(String, DataFrame)>, IoError> {
9093    use calamine::{Reader, open_workbook_auto_from_rs};
9094
9095    let cursor = std::io::Cursor::new(data);
9096    let mut workbook = open_workbook_auto_from_rs(cursor)
9097        .map_err(|e| IoError::Excel(format!("cannot open workbook from bytes: {e}")))?;
9098    let available: Vec<String> = workbook.sheet_names();
9099    // Per br-frankenpandas-c9cb4: HashSet<&str> for O(1) membership;
9100    // was O(m × n) Vec::iter().any() per requested name.
9101    let available_set: HashSet<&str> = available.iter().map(String::as_str).collect();
9102    let selected: Vec<String> = match sheet_names {
9103        Some(names) => {
9104            for name in names {
9105                if !available_set.contains(name.as_str()) {
9106                    return Err(IoError::Excel(format!(
9107                        "workbook does not contain sheet {name:?}"
9108                    )));
9109                }
9110            }
9111            names.to_vec()
9112        }
9113        None => available.clone(),
9114    };
9115    if selected.is_empty() {
9116        return Err(IoError::Excel("no sheets selected".to_owned()));
9117    }
9118    let mut out = Vec::with_capacity(selected.len());
9119    for sheet in &selected {
9120        let range = workbook
9121            .worksheet_range(sheet)
9122            .map_err(|e| IoError::Excel(format!("cannot read sheet {sheet:?}: {e}")))?;
9123        let rows: Vec<Vec<calamine::Data>> = range
9124            .rows()
9125            .skip(options.skip_rows)
9126            .map(|r| r.to_vec())
9127            .collect();
9128        let frame = parse_excel_rows(rows, options)?;
9129        out.push((sheet.clone(), frame));
9130    }
9131    Ok(out)
9132}
9133
9134pub fn read_excel_sheets(
9135    path: &Path,
9136    sheet_names: Option<&[String]>,
9137    options: &ExcelReadOptions,
9138) -> Result<BTreeMap<String, DataFrame>, IoError> {
9139    use calamine::{Reader, open_workbook_auto};
9140
9141    let mut workbook = open_workbook_auto(path)
9142        .map_err(|e| IoError::Excel(format!("cannot open workbook: {e}")))?;
9143    let available: Vec<String> = workbook.sheet_names();
9144    // Per br-frankenpandas-c9cb4: HashSet<&str> for O(1) membership;
9145    // was O(m × n) Vec::iter().any() per requested name.
9146    let available_set: HashSet<&str> = available.iter().map(String::as_str).collect();
9147    let selected: Vec<String> = match sheet_names {
9148        Some(names) => {
9149            for name in names {
9150                if !available_set.contains(name.as_str()) {
9151                    return Err(IoError::Excel(format!(
9152                        "workbook does not contain sheet {name:?}"
9153                    )));
9154                }
9155            }
9156            names.to_vec()
9157        }
9158        None => available.clone(),
9159    };
9160    if selected.is_empty() {
9161        return Err(IoError::Excel("no sheets selected".to_owned()));
9162    }
9163
9164    let mut out = BTreeMap::new();
9165    for sheet in &selected {
9166        let range = workbook
9167            .worksheet_range(sheet)
9168            .map_err(|e| IoError::Excel(format!("cannot read sheet {sheet:?}: {e}")))?;
9169        let rows: Vec<Vec<calamine::Data>> = range
9170            .rows()
9171            .skip(options.skip_rows)
9172            .map(|r| r.to_vec())
9173            .collect();
9174        let frame = parse_excel_rows(rows, options)?;
9175        out.insert(sheet.clone(), frame);
9176    }
9177    Ok(out)
9178}
9179
9180/// Read multiple sheets from Excel bytes.
9181///
9182/// Byte-based counterpart to `read_excel_sheets`.
9183pub fn read_excel_sheets_bytes(
9184    data: &[u8],
9185    sheet_names: Option<&[String]>,
9186    options: &ExcelReadOptions,
9187) -> Result<BTreeMap<String, DataFrame>, IoError> {
9188    use calamine::{Reader, open_workbook_auto_from_rs};
9189
9190    let cursor = std::io::Cursor::new(data);
9191    let mut workbook = open_workbook_auto_from_rs(cursor)
9192        .map_err(|e| IoError::Excel(format!("cannot open workbook from bytes: {e}")))?;
9193    let available: Vec<String> = workbook.sheet_names();
9194    // Per br-frankenpandas-c9cb4: HashSet<&str> for O(1) membership;
9195    // was O(m × n) Vec::iter().any() per requested name.
9196    let available_set: HashSet<&str> = available.iter().map(String::as_str).collect();
9197    let selected: Vec<String> = match sheet_names {
9198        Some(names) => {
9199            for name in names {
9200                if !available_set.contains(name.as_str()) {
9201                    return Err(IoError::Excel(format!(
9202                        "workbook does not contain sheet {name:?}"
9203                    )));
9204                }
9205            }
9206            names.to_vec()
9207        }
9208        None => available.clone(),
9209    };
9210    if selected.is_empty() {
9211        return Err(IoError::Excel("no sheets selected".to_owned()));
9212    }
9213
9214    let mut out = BTreeMap::new();
9215    for sheet in &selected {
9216        let range = workbook
9217            .worksheet_range(sheet)
9218            .map_err(|e| IoError::Excel(format!("cannot read sheet {sheet:?}: {e}")))?;
9219        let rows: Vec<Vec<calamine::Data>> = range
9220            .rows()
9221            .skip(options.skip_rows)
9222            .map(|r| r.to_vec())
9223            .collect();
9224        let frame = parse_excel_rows(rows, options)?;
9225        out.insert(sheet.clone(), frame);
9226    }
9227    Ok(out)
9228}
9229
9230/// Write a DataFrame to an Excel (.xlsx) file.
9231///
9232/// Matches `pd.DataFrame.to_excel(path)`.
9233pub fn write_excel(frame: &DataFrame, path: &Path) -> Result<(), IoError> {
9234    let bytes = write_excel_bytes(frame)?;
9235    std::fs::write(path, bytes)?;
9236    Ok(())
9237}
9238
9239fn write_excel_index_label(
9240    worksheet: &mut rust_xlsxwriter::Worksheet,
9241    excel_row: u32,
9242    excel_col: u16,
9243    label: &IndexLabel,
9244) -> Result<(), IoError> {
9245    match label {
9246        IndexLabel::Int64(v) => {
9247            worksheet
9248                .write_number(excel_row, excel_col, *v as f64)
9249                .map_err(|e| IoError::Excel(format!("write index int: {e}")))?;
9250        }
9251        IndexLabel::Utf8(s) => {
9252            worksheet
9253                .write_string(excel_row, excel_col, s.as_str())
9254                .map_err(|e| IoError::Excel(format!("write index string: {e}")))?;
9255        }
9256        IndexLabel::Timedelta64(v) => {
9257            if *v != Timedelta::NAT {
9258                worksheet
9259                    .write_string(excel_row, excel_col, Timedelta::format(*v))
9260                    .map_err(|e| IoError::Excel(format!("write index timedelta: {e}")))?;
9261            }
9262        }
9263        IndexLabel::Datetime64(v) => {
9264            if *v != i64::MIN {
9265                worksheet
9266                    .write_string(excel_row, excel_col, label.to_string())
9267                    .map_err(|e| IoError::Excel(format!("write index datetime: {e}")))?;
9268            }
9269        }
9270        // Missing labels leave the cell blank, like NAT timedelta/datetime
9271        // above (pandas writes an empty cell for a NaN index label).
9272        IndexLabel::Float64(v) => {
9273            worksheet
9274                .write_number(excel_row, excel_col, v.0)
9275                .map_err(|e| IoError::Excel(format!("write index float: {e}")))?;
9276        }
9277        IndexLabel::Bool(b) => {
9278            worksheet
9279                .write_boolean(excel_row, excel_col, *b)
9280                .map_err(|e| IoError::Excel(format!("write index bool: {e}")))?;
9281        }
9282        IndexLabel::Null(_) => {}
9283    }
9284    Ok(())
9285}
9286
9287fn write_excel_scalar(
9288    worksheet: &mut rust_xlsxwriter::Worksheet,
9289    excel_row: u32,
9290    excel_col: u16,
9291    scalar: &Scalar,
9292) -> Result<(), IoError> {
9293    match scalar {
9294        Scalar::Int64(v) => {
9295            worksheet
9296                .write_number(excel_row, excel_col, *v as f64)
9297                .map_err(|e| IoError::Excel(format!("write int: {e}")))?;
9298        }
9299        Scalar::Float64(v) if !v.is_nan() => {
9300            worksheet
9301                .write_number(excel_row, excel_col, *v)
9302                .map_err(|e| IoError::Excel(format!("write float: {e}")))?;
9303        }
9304        Scalar::Bool(b) => {
9305            worksheet
9306                .write_boolean(excel_row, excel_col, *b)
9307                .map_err(|e| IoError::Excel(format!("write bool: {e}")))?;
9308        }
9309        Scalar::Utf8(s) => {
9310            worksheet
9311                .write_string(excel_row, excel_col, s.as_str())
9312                .map_err(|e| IoError::Excel(format!("write string: {e}")))?;
9313        }
9314        Scalar::Timedelta64(v) => {
9315            if *v != Timedelta::NAT {
9316                worksheet
9317                    .write_string(excel_row, excel_col, Timedelta::format(*v))
9318                    .map_err(|e| IoError::Excel(format!("write timedelta: {e}")))?;
9319            }
9320        }
9321        Scalar::Datetime64(v) => {
9322            if *v != Timestamp::NAT {
9323                worksheet
9324                    .write_string(excel_row, excel_col, format_datetime_ns(*v))
9325                    .map_err(|e| IoError::Excel(format!("write datetime: {e}")))?;
9326            }
9327        }
9328        Scalar::Period(p) => {
9329            if p.ordinal != i64::MIN {
9330                worksheet
9331                    .write_string(excel_row, excel_col, p.calendar_string())
9332                    .map_err(|e| IoError::Excel(format!("write period: {e}")))?;
9333            }
9334        }
9335        Scalar::Interval(iv) => {
9336            worksheet
9337                .write_string(excel_row, excel_col, format!("{iv}"))
9338                .map_err(|e| IoError::Excel(format!("write interval: {e}")))?;
9339        }
9340        Scalar::Float64(_) | Scalar::Null(_) => {}
9341    }
9342    Ok(())
9343}
9344
9345/// Write a DataFrame to Excel (.xlsx) bytes in memory.
9346///
9347/// Matches pandas `DataFrame.to_excel()` default index behavior by emitting
9348/// the index as the first worksheet column.
9349pub fn write_excel_bytes(frame: &DataFrame) -> Result<Vec<u8>, IoError> {
9350    write_excel_bytes_with_options(frame, &ExcelWriteOptions::default())
9351}
9352
9353/// Options for serializing a DataFrame to Excel.
9354///
9355/// Mirrors the subset of `pd.DataFrame.to_excel` parameters that
9356/// don't depend on the workbook writer itself.
9357#[derive(Debug, Clone)]
9358pub struct ExcelWriteOptions {
9359    /// Target sheet name. Default: `"Sheet1"` (rust_xlsxwriter default).
9360    pub sheet_name: String,
9361    /// Whether to write the row index as a leading column. Matches
9362    /// pandas `index=True|False`. Default: true.
9363    pub index: bool,
9364    /// Header label for the index column when `index=true`. When
9365    /// `None`, the frame's index name is used (falling back to an
9366    /// empty string). Matches pandas `index_label=...`.
9367    pub index_label: Option<String>,
9368    /// Whether to emit the column-name header row. Matches pandas
9369    /// `header=True|False`. Default: true.
9370    pub header: bool,
9371}
9372
9373impl Default for ExcelWriteOptions {
9374    fn default() -> Self {
9375        Self {
9376            sheet_name: "Sheet1".to_string(),
9377            index: true,
9378            index_label: None,
9379            header: true,
9380        }
9381    }
9382}
9383
9384/// Serialize a DataFrame to Excel bytes with explicit options.
9385///
9386/// Matches `pd.DataFrame.to_excel(sheet_name, index, index_label,
9387/// header)` for the in-memory byte form. The default `ExcelWriteOptions`
9388/// reproduces the existing `write_excel_bytes` behavior (index=true,
9389/// sheet_name="Sheet1").
9390pub fn write_excel_bytes_with_options(
9391    frame: &DataFrame,
9392    options: &ExcelWriteOptions,
9393) -> Result<Vec<u8>, IoError> {
9394    if options.index && frame.row_multiindex().is_some() {
9395        let materialized = materialize_named_row_multiindex_columns(frame)?;
9396        let mut nested_options = options.clone();
9397        nested_options.index = false;
9398        nested_options.index_label = None;
9399        return write_excel_bytes_with_options(&materialized, &nested_options);
9400    }
9401
9402    use rust_xlsxwriter::Workbook;
9403
9404    let mut workbook = Workbook::new();
9405    let worksheet = workbook.add_worksheet();
9406    worksheet
9407        .set_name(options.sheet_name.as_str())
9408        .map_err(|e| IoError::Excel(format!("set sheet name: {e}")))?;
9409
9410    let col_names: Vec<String> = frame.column_names().into_iter().cloned().collect();
9411    let data_col_offset: u16 = if options.index { 1 } else { 0 };
9412
9413    // Header row (optional).
9414    if options.header {
9415        if options.index {
9416            let idx_header = options
9417                .index_label
9418                .as_deref()
9419                .unwrap_or_else(|| frame.index().name().unwrap_or(""));
9420            worksheet
9421                .write_string(0, 0, idx_header)
9422                .map_err(|e| IoError::Excel(format!("write index header: {e}")))?;
9423        }
9424        for (col_idx, name) in col_names.iter().enumerate() {
9425            worksheet
9426                .write_string(0, data_col_offset + col_idx as u16, name.as_str())
9427                .map_err(|e| IoError::Excel(format!("write header: {e}")))?;
9428        }
9429    }
9430
9431    // Data rows — when header=true the first data row lands at excel
9432    // row 1; when header=false data starts at row 0.
9433    let header_rows: u32 = if options.header { 1 } else { 0 };
9434    let nrows = frame.index().len();
9435    for row_idx in 0..nrows {
9436        let excel_row = row_idx as u32 + header_rows;
9437        if options.index
9438            && let Some(label) = frame.index().labels().get(row_idx)
9439        {
9440            write_excel_index_label(worksheet, excel_row, 0, label)?;
9441        }
9442        for (col_idx, name) in col_names.iter().enumerate() {
9443            if let Some(col) = frame.column(name)
9444                && let Some(scalar) = col.value(row_idx)
9445            {
9446                write_excel_scalar(
9447                    worksheet,
9448                    excel_row,
9449                    data_col_offset + col_idx as u16,
9450                    scalar,
9451                )?;
9452            }
9453        }
9454    }
9455
9456    let buf = workbook
9457        .save_to_buffer()
9458        .map_err(|e| IoError::Excel(format!("save workbook: {e}")))?;
9459
9460    Ok(buf)
9461}
9462
9463/// File-based counterpart to `write_excel_bytes_with_options`.
9464pub fn write_excel_with_options(
9465    frame: &DataFrame,
9466    path: &Path,
9467    options: &ExcelWriteOptions,
9468) -> Result<(), IoError> {
9469    let bytes = write_excel_bytes_with_options(frame, options)?;
9470    std::fs::write(path, bytes)?;
9471    Ok(())
9472}
9473
9474// ── Arrow IPC / Feather I/O ──────────────────────────────────────────────
9475
9476/// Write a DataFrame to Arrow IPC (Feather v2) bytes in memory.
9477///
9478/// Matches `pd.DataFrame.to_feather()`. Feather v2 is the Arrow IPC file format
9479/// — the fastest columnar interchange format, recommended by pandas over HDF5.
9480pub fn write_feather_bytes(frame: &DataFrame) -> Result<Vec<u8>, IoError> {
9481    use arrow::ipc::writer::FileWriter;
9482
9483    let batch = dataframe_to_record_batch(frame)?;
9484    let schema = batch.schema();
9485
9486    let mut buf = Vec::new();
9487    let mut writer =
9488        FileWriter::try_new(&mut buf, &schema).map_err(|e| IoError::Arrow(e.to_string()))?;
9489    writer
9490        .write(&batch)
9491        .map_err(|e| IoError::Arrow(e.to_string()))?;
9492    writer.finish().map_err(|e| IoError::Arrow(e.to_string()))?;
9493    Ok(buf)
9494}
9495
9496/// Read a DataFrame from Arrow IPC (Feather v2) bytes in memory.
9497///
9498/// Matches `pd.read_feather()`.
9499pub fn read_feather_bytes(data: &[u8]) -> Result<DataFrame, IoError> {
9500    use arrow::ipc::reader::FileReader;
9501
9502    let cursor = std::io::Cursor::new(data);
9503    let reader = FileReader::try_new(cursor, None).map_err(|e| IoError::Arrow(e.to_string()))?;
9504
9505    let mut all_frames: Vec<DataFrame> = Vec::new();
9506    for batch_result in reader {
9507        let batch = batch_result.map_err(|e| IoError::Arrow(e.to_string()))?;
9508        all_frames.push(record_batch_to_dataframe(&batch)?);
9509    }
9510
9511    if all_frames.is_empty() {
9512        return Ok(DataFrame::new_with_column_order(
9513            Index::new(vec![]),
9514            BTreeMap::new(),
9515            vec![],
9516        )?);
9517    }
9518
9519    if all_frames.len() == 1 {
9520        if let Some(frame) = all_frames.into_iter().next() {
9521            return Ok(frame);
9522        }
9523        return Err(IoError::Arrow(
9524            "feather reader produced zero record batches".to_owned(),
9525        ));
9526    }
9527
9528    let refs: Vec<&DataFrame> = all_frames.iter().collect();
9529    fp_frame::concat_dataframes(&refs).map_err(IoError::from)
9530}
9531
9532/// Write a DataFrame to an Arrow IPC (Feather v2) file.
9533///
9534/// Matches `pd.DataFrame.to_feather(path)`.
9535pub fn write_feather(frame: &DataFrame, path: &Path) -> Result<(), IoError> {
9536    let bytes = write_feather_bytes(frame)?;
9537    std::fs::write(path, bytes)?;
9538    Ok(())
9539}
9540
9541/// Read a DataFrame from an Arrow IPC (Feather v2) file.
9542///
9543/// Matches `pd.read_feather(path)`.
9544pub fn read_feather(path: &Path) -> Result<DataFrame, IoError> {
9545    let data = std::fs::read(path)?;
9546    read_feather_bytes(&data)
9547}
9548
9549/// Write a DataFrame to Arrow IPC stream bytes (streaming format, no random access).
9550///
9551/// Unlike Feather (file format), the stream format has no footer and supports
9552/// streaming reads without seeking. Used for inter-process communication.
9553pub fn write_ipc_stream_bytes(frame: &DataFrame) -> Result<Vec<u8>, IoError> {
9554    use arrow::ipc::writer::StreamWriter;
9555
9556    let batch = dataframe_to_record_batch(frame)?;
9557    let schema = batch.schema();
9558
9559    let mut buf = Vec::new();
9560    let mut writer =
9561        StreamWriter::try_new(&mut buf, &schema).map_err(|e| IoError::Arrow(e.to_string()))?;
9562    writer
9563        .write(&batch)
9564        .map_err(|e| IoError::Arrow(e.to_string()))?;
9565    writer.finish().map_err(|e| IoError::Arrow(e.to_string()))?;
9566    Ok(buf)
9567}
9568
9569/// Read a DataFrame from Arrow IPC stream bytes (streaming format).
9570pub fn read_ipc_stream_bytes(data: &[u8]) -> Result<DataFrame, IoError> {
9571    use arrow::ipc::reader::StreamReader;
9572
9573    let cursor = std::io::Cursor::new(data);
9574    let reader = StreamReader::try_new(cursor, None).map_err(|e| IoError::Arrow(e.to_string()))?;
9575
9576    let mut all_frames: Vec<DataFrame> = Vec::new();
9577    for batch_result in reader {
9578        let batch = batch_result.map_err(|e| IoError::Arrow(e.to_string()))?;
9579        all_frames.push(record_batch_to_dataframe(&batch)?);
9580    }
9581
9582    if all_frames.is_empty() {
9583        return Ok(DataFrame::new_with_column_order(
9584            Index::new(vec![]),
9585            BTreeMap::new(),
9586            vec![],
9587        )?);
9588    }
9589
9590    if all_frames.len() == 1 {
9591        if let Some(frame) = all_frames.into_iter().next() {
9592            return Ok(frame);
9593        }
9594        return Err(IoError::Arrow(
9595            "ipc stream reader produced zero record batches".to_owned(),
9596        ));
9597    }
9598
9599    let refs: Vec<&DataFrame> = all_frames.iter().collect();
9600    fp_frame::concat_dataframes(&refs).map_err(IoError::from)
9601}
9602
9603// ── SQL I/O ─────────────────────────────────────────────────────────────
9604
9605/// Options for writing a DataFrame to SQL.
9606#[derive(Debug, Clone, Copy, PartialEq, Eq)]
9607pub enum SqlIfExists {
9608    /// Raise an error if the table already exists.
9609    Fail,
9610    /// Drop the table and recreate it.
9611    Replace,
9612    /// Insert new rows into the existing table.
9613    Append,
9614}
9615
9616/// Strategy for emitting INSERT statements during `write_sql`.
9617///
9618/// Matches `pd.DataFrame.to_sql(.., method=...)` shape:
9619/// `Single` (default) emits one `INSERT INTO t VALUES (?, ...)` per row,
9620/// reusing a prepared statement under a transaction. `Multi` builds a
9621/// single multi-row `INSERT INTO t VALUES (...), (...), ...` statement
9622/// per chunk, where chunk size is `max_param_count() / num_cols` (or
9623/// the whole frame when the backend reports no max). `Multi` typically
9624/// wins on backends with high per-statement overhead (PostgreSQL,
9625/// MySQL); SQLite is already fast under prepared-statement reuse so the
9626/// gap there is small.
9627///
9628/// Per br-frankenpandas-i0ml (fd90.19).
9629#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
9630pub enum SqlInsertMethod {
9631    /// One INSERT per row, prepared once and re-bound per row.
9632    #[default]
9633    Single,
9634    /// Multi-row INSERT, chunked by the backend's parameter limit.
9635    Multi,
9636}
9637
9638/// Options for reading SQL query results into a DataFrame.
9639#[derive(Debug, Clone)]
9640pub struct SqlReadOptions {
9641    /// Positional parameters to bind to `?` placeholders in the SQL query.
9642    pub params: Option<Vec<Scalar>>,
9643    /// Column names to coerce via pandas-style parse_dates handling.
9644    /// Currently supports explicit column-name selection.
9645    pub parse_dates: Option<Vec<String>>,
9646    /// Promote decimal-like SQL text result columns to Float64.
9647    ///
9648    /// This is an opt-in form of pandas' `coerce_float` behavior for
9649    /// backends that expose NUMERIC/DECIMAL/MONEY values through text.
9650    /// Columns containing any non-numeric strings are left unchanged.
9651    pub coerce_float: bool,
9652    /// Per-column dtype override applied after row materialization.
9653    ///
9654    /// Matches `pd.read_sql(.., dtype={'col': 'float64'})`. Each entry casts
9655    /// the named column to the declared dtype using `fp_types::cast_scalar_owned`.
9656    /// Map entries for columns not present in the result are silently
9657    /// ignored (matches pandas). Columns also listed in `parse_dates` are
9658    /// skipped to avoid double-cast errors — parse_dates wins.
9659    ///
9660    /// Per br-frankenpandas-l9pt (fd90.11).
9661    pub dtype: Option<BTreeMap<String, DType>>,
9662    /// Optional schema namespace for `read_sql_table` lookups.
9663    ///
9664    /// Matches `pd.read_sql_table(table, con, schema=...)`. When the
9665    /// backend reports `supports_schemas() == true` (PostgreSQL, MySQL,
9666    /// MSSQL, etc.) and `schema` is `Some(s)`, the SELECT references
9667    /// `s.table` with each part quoted by `conn.quote_identifier(...)`.
9668    /// When the backend reports `supports_schemas() == false` (SQLite),
9669    /// any `Some(s)` here is rejected before query execution. Pandas /
9670    /// SQLAlchemy raises `NotImplementedError` on that surface; failing
9671    /// closed avoids silently reading an unqualified table from the wrong
9672    /// namespace.
9673    ///
9674    /// Per br-frankenpandas-u6zn (fd90.14).
9675    pub schema: Option<String>,
9676    /// Optional projection list for `read_sql_table` reads.
9677    ///
9678    /// Matches `pd.read_sql_table(table, con, columns=[...])`. When
9679    /// `Some(list)`, the emitted SELECT projects only those columns
9680    /// (and in that order) instead of `SELECT *`. `None` preserves
9681    /// `SELECT *`. An empty Vec is rejected with `IoError::Sql` —
9682    /// pandas raises ValueError there. Each entry is validated via
9683    /// the standard alphanumeric+underscore policy.
9684    ///
9685    /// Note: `read_sql` / `read_sql_query` ignore this field — it
9686    /// only takes effect on `read_sql_table*` paths, where
9687    /// frankenpandas builds the SELECT itself.
9688    ///
9689    /// Per br-frankenpandas-d3e9 (fd90.34).
9690    pub columns: Option<Vec<String>>,
9691    /// Optional column name to promote to the DataFrame index.
9692    ///
9693    /// Matches `pd.read_sql(.., index_col=...)` and
9694    /// `pd.read_sql_table(table, con, index_col=...)`. When
9695    /// `Some(name)`, after row materialization the named column is
9696    /// removed from the result and used as the DataFrame index. The
9697    /// column must exist in the read result (or in the projection
9698    /// when `columns` is also set). `None` preserves the default
9699    /// RangeIndex.
9700    ///
9701    /// Empty string is rejected with `IoError::Sql` to match
9702    /// pandas' ValueError. List-of-strings (for MultiIndex) is out
9703    /// of scope for this slice — single index only.
9704    ///
9705    /// Per br-frankenpandas-c1h9 (fd90.36).
9706    pub index_col: Option<String>,
9707}
9708
9709impl Default for SqlReadOptions {
9710    /// Per br-frankenpandas-o0x6 (fd90.41): pandas defaults
9711    /// `coerce_float=True` for `read_sql` / `read_sql_query` /
9712    /// `read_sql_table` so we follow suit. Other defaults are the
9713    /// natural empty / None values.
9714    fn default() -> Self {
9715        Self {
9716            params: None,
9717            parse_dates: None,
9718            coerce_float: true,
9719            dtype: None,
9720            schema: None,
9721            columns: None,
9722            index_col: None,
9723        }
9724    }
9725}
9726
9727/// Options for writing a DataFrame to SQL.
9728#[derive(Debug, Clone, PartialEq, Eq)]
9729pub struct SqlWriteOptions {
9730    /// Behavior when the target table already exists.
9731    pub if_exists: SqlIfExists,
9732    /// Whether to materialize the DataFrame index as the leading SQL column.
9733    pub index: bool,
9734    /// Optional override for the emitted index column name.
9735    pub index_label: Option<String>,
9736    /// Optional schema namespace for CREATE TABLE / INSERT routing.
9737    ///
9738    /// Matches `pd.DataFrame.to_sql(table, con, schema=...)`. When the
9739    /// backend reports `supports_schemas() == true` and `schema` is
9740    /// `Some(s)`, generated CREATE TABLE / INSERT statements target
9741    /// `\"s\".\"table\"`. On backends that report `false` (SQLite),
9742    /// `Some(s)` is silently ignored — preserves SQLite users' existing
9743    /// option structs.
9744    ///
9745    /// Per br-frankenpandas-udn6 (fd90.15).
9746    pub schema: Option<String>,
9747    /// Per-column SQL-type override applied during CREATE TABLE.
9748    ///
9749    /// Matches `pd.DataFrame.to_sql(.., dtype={'amount': 'NUMERIC(10,2)'})`.
9750    /// Each entry's value is the literal SQL type string emitted in the
9751    /// column definition for that column. Map entries for columns not
9752    /// in the frame are silently ignored (matches pandas). Falls back
9753    /// to `conn.dtype_sql(DType)` when no override is present.
9754    ///
9755    /// Per br-frankenpandas-ev2s (fd90.18).
9756    pub dtype: Option<BTreeMap<String, String>>,
9757    /// INSERT-emission strategy.
9758    ///
9759    /// Default `Single` matches pandas' default: one INSERT per row,
9760    /// re-binding a prepared statement under a transaction. `Multi`
9761    /// switches to multi-row VALUES batched by `conn.max_param_count()`,
9762    /// matching `pd.to_sql(.., method='multi')`.
9763    ///
9764    /// Per br-frankenpandas-i0ml (fd90.19).
9765    pub method: SqlInsertMethod,
9766    /// Maximum rows per transaction-bounded INSERT chunk.
9767    ///
9768    /// Matches `pd.DataFrame.to_sql(.., chunksize=...)`. When `Some(n)`,
9769    /// the row emit loop batches into chunks of `n` rows, each routed
9770    /// through its own `insert_rows` call (which on transactional
9771    /// backends commits a fresh transaction per chunk). This caps WAL /
9772    /// journal size for huge frames where the default `Single`
9773    /// single-transaction mode would balloon. For `Multi` mode the
9774    /// effective per-chunk row count is `min(chunksize,
9775    /// max_param_count / num_cols)`. `None` preserves existing
9776    /// single-transaction semantics.
9777    ///
9778    /// `Some(0)` is rejected — pandas raises ValueError there too.
9779    ///
9780    /// Per br-frankenpandas-ls9z (fd90.33).
9781    pub chunksize: Option<usize>,
9782}
9783
9784/// Backend-agnostic in-memory representation of a SQL query result.
9785#[derive(Debug, Clone, PartialEq)]
9786pub struct SqlQueryResult {
9787    pub columns: Vec<String>,
9788    pub rows: Vec<Vec<Scalar>>,
9789}
9790
9791type SqlColumnDtypeHints = Vec<Option<DType>>;
9792type SqlMaterializedColumns = (Vec<String>, Vec<Vec<Scalar>>, SqlColumnDtypeHints);
9793
9794/// Backend-neutral SQL column metadata.
9795#[derive(Debug, Clone, PartialEq, Eq)]
9796pub struct SqlColumnSchema {
9797    pub name: String,
9798    pub declared_type: Option<String>,
9799    pub nullable: bool,
9800    pub default_value: Option<String>,
9801    pub primary_key_ordinal: Option<usize>,
9802    /// Column-level comment text, when the backend exposes one.
9803    ///
9804    /// Per br-frankenpandas-cfld (fd90.35). SQLite has no column-comment
9805    /// storage so the rusqlite override always emits `None`. PostgreSQL
9806    /// impls populate from `pg_catalog.pg_description.col_description`;
9807    /// MySQL uses `information_schema.columns.column_comment`; MSSQL
9808    /// reads from `sys.extended_properties`. Companion to the
9809    /// table-level `table_comment` (fd90.32) — together they round
9810    /// out SQLAlchemy.Inspector.get_columns() parity (its dict shape
9811    /// includes a `'comment'` key).
9812    pub comment: Option<String>,
9813    /// Whether the column is auto-incrementing.
9814    ///
9815    /// Per br-frankenpandas-bkl2 (fd90.37). Completes
9816    /// SQLAlchemy.Inspector.get_columns() parity (the dict shape
9817    /// includes an `'autoincrement'` key).
9818    ///
9819    /// SQLite detection rule (in the rusqlite `table_schema`
9820    /// override): true when `declared_type` is `INTEGER`
9821    /// (case-insensitive) AND the column is the sole primary key
9822    /// (`primary_key_ordinal == Some(0)`) — SQLite makes
9823    /// `INTEGER PRIMARY KEY` an alias for the auto-increment
9824    /// `rowid`. The optional `AUTOINCREMENT` keyword affects
9825    /// whether IDs are reused after delete but does not change the
9826    /// "is auto-incrementing" property pandas cares about.
9827    ///
9828    /// Other backends: PG SERIAL/BIGSERIAL/IDENTITY columns
9829    /// `true`; MySQL `AUTO_INCREMENT` modifier `true`; otherwise
9830    /// `false`.
9831    pub autoincrement: bool,
9832}
9833
9834/// Backend-neutral SQL table metadata.
9835#[derive(Debug, Clone, PartialEq, Eq)]
9836pub struct SqlTableSchema {
9837    pub table_name: String,
9838    pub columns: Vec<SqlColumnSchema>,
9839}
9840
9841impl SqlTableSchema {
9842    pub fn column(&self, name: &str) -> Option<&SqlColumnSchema> {
9843        self.columns.iter().find(|column| column.name == name)
9844    }
9845}
9846
9847/// Backend-neutral SQL index metadata.
9848///
9849/// Per br-frankenpandas-bgv9 (fd90.28). Used by `list_indexes` /
9850/// `list_sql_indexes` to surface user-defined indexes so callers can
9851/// align with `SQLAlchemy.Inspector.get_indexes()` shape.
9852#[derive(Debug, Clone, PartialEq, Eq)]
9853pub struct SqlIndexSchema {
9854    pub name: String,
9855    pub columns: Vec<String>,
9856    pub unique: bool,
9857}
9858
9859/// Backend-neutral SQL unique-constraint metadata.
9860///
9861/// Per br-frankenpandas-sh4v (fd90.31). Surfaces inline `UNIQUE`
9862/// declarations and `UNIQUE (...)` table constraints separately from
9863/// user-created `CREATE UNIQUE INDEX` (those land in
9864/// `SqlIndexSchema` via `list_indexes`). `name` may be backend-
9865/// generated (SQLite reports `sqlite_autoindex_<table>_<n>`) when
9866/// the constraint was declared inline without an explicit name —
9867/// we surface the backend's name verbatim rather than fabricating.
9868#[derive(Debug, Clone, PartialEq, Eq)]
9869pub struct SqlUniqueConstraintSchema {
9870    pub name: String,
9871    pub columns: Vec<String>,
9872}
9873
9874/// Bundle of all introspection metadata for a single SQL table.
9875///
9876/// Per br-frankenpandas-76mw (fd90.40). Returned by
9877/// `SqlInspector::reflect_table` to give callers the full picture of
9878/// a table in one call instead of 5 separate trait dispatches.
9879/// Mirrors the bundled view that `SQLAlchemy.MetaData.reflect_table`
9880/// builds internally.
9881#[derive(Debug, Clone, PartialEq, Eq)]
9882pub struct SqlReflectedTable {
9883    pub table_name: String,
9884    pub columns: Vec<SqlColumnSchema>,
9885    pub primary_key_columns: Vec<String>,
9886    pub indexes: Vec<SqlIndexSchema>,
9887    pub foreign_keys: Vec<SqlForeignKeySchema>,
9888    pub unique_constraints: Vec<SqlUniqueConstraintSchema>,
9889    pub comment: Option<String>,
9890}
9891
9892impl SqlReflectedTable {
9893    /// Look up a column by name. Mirrors `SqlTableSchema::column`.
9894    ///
9895    /// Per br-frankenpandas-63ac (fd90.51).
9896    #[must_use]
9897    pub fn column(&self, name: &str) -> Option<&SqlColumnSchema> {
9898        self.columns.iter().find(|c| c.name == name)
9899    }
9900
9901    /// Look up an index by name.
9902    ///
9903    /// Per br-frankenpandas-63ac (fd90.51).
9904    #[must_use]
9905    pub fn index(&self, name: &str) -> Option<&SqlIndexSchema> {
9906        self.indexes.iter().find(|i| i.name == name)
9907    }
9908
9909    /// Look up a unique constraint by name (backend-generated names
9910    /// like `sqlite_autoindex_*` count too — match what
9911    /// `list_unique_constraints` surfaced).
9912    ///
9913    /// Per br-frankenpandas-63ac (fd90.51).
9914    #[must_use]
9915    pub fn unique_constraint(&self, name: &str) -> Option<&SqlUniqueConstraintSchema> {
9916        self.unique_constraints.iter().find(|u| u.name == name)
9917    }
9918
9919    /// Find every foreign key whose `columns` slice contains `column_name`.
9920    ///
9921    /// A given column may participate in multiple FK constraints (e.g.
9922    /// the same column referenced by separate FKs to different parents
9923    /// — rare but valid SQL). Returns the matching FKs in their
9924    /// declaration order from PRAGMA foreign_key_list.
9925    ///
9926    /// Per br-frankenpandas-63ac (fd90.51).
9927    #[must_use]
9928    pub fn foreign_keys_for_column(&self, column_name: &str) -> Vec<&SqlForeignKeySchema> {
9929        self.foreign_keys
9930            .iter()
9931            .filter(|fk| fk.columns.iter().any(|c| c == column_name))
9932            .collect()
9933    }
9934
9935    /// Find every index whose `columns` slice contains `column_name`.
9936    ///
9937    /// Matches multi-column indexes where the column appears at any
9938    /// position (first, middle, last) — useful for answering "is this
9939    /// column indexed" rather than the more restrictive "is this
9940    /// column the leading entry of an index" question.
9941    ///
9942    /// Per br-frankenpandas-37uy (fd90.52).
9943    #[must_use]
9944    pub fn indexes_for_column(&self, column_name: &str) -> Vec<&SqlIndexSchema> {
9945        self.indexes
9946            .iter()
9947            .filter(|i| i.columns.iter().any(|c| c == column_name))
9948            .collect()
9949    }
9950
9951    /// Find every UNIQUE constraint whose `columns` slice contains
9952    /// `column_name`.
9953    ///
9954    /// Same any-position match semantics as `indexes_for_column` and
9955    /// `foreign_keys_for_column`.
9956    ///
9957    /// Per br-frankenpandas-37uy (fd90.52).
9958    #[must_use]
9959    pub fn unique_constraints_for_column(
9960        &self,
9961        column_name: &str,
9962    ) -> Vec<&SqlUniqueConstraintSchema> {
9963        self.unique_constraints
9964            .iter()
9965            .filter(|u| u.columns.iter().any(|c| c == column_name))
9966            .collect()
9967    }
9968}
9969
9970/// Backend-neutral SQL foreign-key constraint metadata.
9971///
9972/// Per br-frankenpandas-uht8 (fd90.29). Aligns with
9973/// `SQLAlchemy.Inspector.get_foreign_keys()` shape: a single FK
9974/// constraint may span multiple columns (composite FK), and
9975/// `columns[i]` references `referenced_columns[i]` on
9976/// `referenced_table`. `constraint_name` is `None` for SQLite
9977/// inline FKs declared without an explicit CONSTRAINT name (PRAGMA
9978/// foreign_key_list does not surface a name, so we return None
9979/// there rather than fabricating one).
9980#[derive(Debug, Clone, PartialEq, Eq)]
9981pub struct SqlForeignKeySchema {
9982    pub constraint_name: Option<String>,
9983    pub columns: Vec<String>,
9984    pub referenced_table: String,
9985    pub referenced_columns: Vec<String>,
9986}
9987
9988/// Iterator over DataFrame chunks produced by a SQL query.
9989pub struct SqlChunkIterator<'conn> {
9990    state: SqlChunkIteratorState<'conn>,
9991}
9992
9993enum SqlChunkIteratorState<'conn> {
9994    Materialized {
9995        headers: Vec<String>,
9996        columns: Vec<Vec<Scalar>>,
9997        dtype_hints: SqlColumnDtypeHints,
9998        chunk_size: usize,
9999        next_row: usize,
10000    },
10001    Paged {
10002        conn: &'conn dyn SqlConnection,
10003        query: String,
10004        options: SqlReadOptions,
10005        headers: Vec<String>,
10006        chunk_size: usize,
10007        next_offset: usize,
10008        finished: bool,
10009    },
10010}
10011
10012impl std::fmt::Debug for SqlChunkIterator<'_> {
10013    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
10014        match &self.state {
10015            SqlChunkIteratorState::Materialized {
10016                headers,
10017                columns,
10018                dtype_hints: _,
10019                chunk_size,
10020                next_row,
10021            } => f
10022                .debug_struct("SqlChunkIterator")
10023                .field("mode", &"materialized")
10024                .field("headers", headers)
10025                .field("row_count", &columns.first().map_or(0, Vec::len))
10026                .field("chunk_size", chunk_size)
10027                .field("next_row", next_row)
10028                .finish(),
10029            SqlChunkIteratorState::Paged {
10030                query,
10031                headers,
10032                chunk_size,
10033                next_offset,
10034                finished,
10035                ..
10036            } => f
10037                .debug_struct("SqlChunkIterator")
10038                .field("mode", &"paged")
10039                .field("query", query)
10040                .field("headers", headers)
10041                .field("chunk_size", chunk_size)
10042                .field("next_offset", next_offset)
10043                .field("finished", finished)
10044                .finish(),
10045        }
10046    }
10047}
10048
10049impl<'conn> SqlChunkIterator<'conn> {
10050    fn materialized(
10051        headers: Vec<String>,
10052        columns: Vec<Vec<Scalar>>,
10053        dtype_hints: SqlColumnDtypeHints,
10054        chunk_size: usize,
10055    ) -> Self {
10056        Self {
10057            state: SqlChunkIteratorState::Materialized {
10058                headers,
10059                columns,
10060                dtype_hints,
10061                chunk_size,
10062                next_row: 0,
10063            },
10064        }
10065    }
10066
10067    fn paged<C: SqlConnection + 'conn>(
10068        conn: &'conn C,
10069        query: &str,
10070        options: &SqlReadOptions,
10071        chunk_size: usize,
10072    ) -> Result<Self, IoError> {
10073        let headers = sql_paged_query_headers(conn, query, options)?;
10074        Ok(Self {
10075            state: SqlChunkIteratorState::Paged {
10076                conn,
10077                query: sql_trim_chunk_source(query)?.to_owned(),
10078                options: options.clone(),
10079                headers,
10080                chunk_size,
10081                next_offset: 0,
10082                finished: false,
10083            },
10084        })
10085    }
10086
10087    fn headers(&self) -> &[String] {
10088        match &self.state {
10089            SqlChunkIteratorState::Materialized { headers, .. }
10090            | SqlChunkIteratorState::Paged { headers, .. } => headers,
10091        }
10092    }
10093}
10094
10095impl Iterator for SqlChunkIterator<'_> {
10096    type Item = Result<DataFrame, IoError>;
10097
10098    fn next(&mut self) -> Option<Self::Item> {
10099        match &mut self.state {
10100            SqlChunkIteratorState::Materialized {
10101                headers,
10102                columns,
10103                dtype_hints,
10104                chunk_size,
10105                next_row,
10106            } => {
10107                let row_count = columns.first().map_or(0, Vec::len);
10108                if *next_row >= row_count {
10109                    return None;
10110                }
10111
10112                let start = *next_row;
10113                let end = start.saturating_add(*chunk_size).min(row_count);
10114                *next_row = end;
10115
10116                let chunk_columns = columns
10117                    .iter()
10118                    .map(|column| column[start..end].to_vec())
10119                    .collect();
10120                Some(dataframe_from_sql_columns(
10121                    headers.clone(),
10122                    chunk_columns,
10123                    dtype_hints.clone(),
10124                ))
10125            }
10126            SqlChunkIteratorState::Paged {
10127                conn,
10128                query,
10129                options,
10130                chunk_size,
10131                next_offset,
10132                finished,
10133                ..
10134            } => {
10135                if *finished {
10136                    return None;
10137                }
10138
10139                let page =
10140                    sql_query_to_columns_paged(*conn, query, options, *chunk_size, *next_offset);
10141                Some(match page {
10142                    Ok((headers, columns, dtype_hints)) => {
10143                        let row_count = columns.first().map_or(0, Vec::len);
10144                        if row_count == 0 {
10145                            *finished = true;
10146                            return None;
10147                        }
10148                        if row_count < *chunk_size {
10149                            *finished = true;
10150                        }
10151                        *next_offset = next_offset.saturating_add(row_count);
10152                        dataframe_from_sql_columns(headers, columns, dtype_hints)
10153                    }
10154                    Err(err) => {
10155                        *finished = true;
10156                        Err(err)
10157                    }
10158                })
10159            }
10160        }
10161    }
10162}
10163
10164/// Iterator over SQL DataFrame chunks with optional per-chunk index promotion.
10165pub struct SqlIndexedChunkIterator<'conn> {
10166    inner: SqlChunkIterator<'conn>,
10167    index_col: Option<String>,
10168}
10169
10170impl std::fmt::Debug for SqlIndexedChunkIterator<'_> {
10171    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
10172        f.debug_struct("SqlIndexedChunkIterator")
10173            .field("inner", &self.inner)
10174            .field("index_col", &self.index_col)
10175            .finish()
10176    }
10177}
10178
10179impl Iterator for SqlIndexedChunkIterator<'_> {
10180    type Item = Result<DataFrame, IoError>;
10181
10182    fn next(&mut self) -> Option<Self::Item> {
10183        let chunk = self.inner.next()?;
10184        Some(match (chunk, self.index_col.as_deref()) {
10185            (Ok(frame), Some(index_col)) => apply_sql_index_col(frame, Some(index_col)),
10186            (Ok(frame), None) => Ok(frame),
10187            (Err(err), _) => Err(err),
10188        })
10189    }
10190}
10191
10192fn sql_indexed_chunks<'conn>(
10193    inner: SqlChunkIterator<'conn>,
10194    index_col: Option<&str>,
10195) -> Result<SqlIndexedChunkIterator<'conn>, IoError> {
10196    if let Some(col_name) = index_col {
10197        if col_name.is_empty() {
10198            return Err(IoError::Sql(
10199                "index_col: empty string is not a valid column name".to_owned(),
10200            ));
10201        }
10202        if !inner.headers().iter().any(|header| header == col_name) {
10203            return Err(IoError::Sql(format!(
10204                "index_col {col_name:?} not present in result columns"
10205            )));
10206        }
10207    }
10208    Ok(SqlIndexedChunkIterator {
10209        inner,
10210        index_col: index_col.map(str::to_owned),
10211    })
10212}
10213
10214/// Minimal SQL connection surface needed by FrankenPandas SQL IO.
10215pub trait SqlConnection {
10216    fn query(&self, query: &str, params: &[Scalar]) -> Result<SqlQueryResult, IoError>;
10217
10218    /// Return optional dtype hints for each result column in `query`.
10219    ///
10220    /// Backends that expose declared result-column types should override this
10221    /// so empty/all-null SQL results keep their table schema instead of
10222    /// falling back to `DType::Null`.
10223    fn query_column_dtypes(
10224        &self,
10225        _query: &str,
10226        _params: &[Scalar],
10227    ) -> Result<Vec<Option<DType>>, IoError> {
10228        Ok(Vec::new())
10229    }
10230
10231    /// Whether `read_sql_chunks*` may page this backend with a bounded
10232    /// `LIMIT`/`OFFSET` wrapper instead of materializing the whole result
10233    /// before the first chunk. Defaults to `false` so lightweight test
10234    /// doubles and custom backends keep the legacy behavior until they opt in.
10235    fn supports_paged_sql_chunks(&self) -> bool {
10236        false
10237    }
10238
10239    fn execute_batch(&self, sql: &str) -> Result<(), IoError>;
10240
10241    fn table_exists(&self, table_name: &str) -> Result<bool, IoError>;
10242
10243    fn insert_rows(&self, insert_sql: &str, rows: &[Vec<Scalar>]) -> Result<(), IoError>;
10244
10245    fn dtype_sql(&self, dtype: DType) -> &'static str;
10246
10247    fn index_dtype_sql(&self, index: &Index) -> &'static str;
10248
10249    /// Return the bind marker for the one-based parameter ordinal.
10250    ///
10251    /// SQLite and MySQL accept `?`; PostgreSQL-style backends use `$1`,
10252    /// `$2`, ... . Keeping marker generation on the backend trait lets
10253    /// write_sql stay generic without leaking backend dialect branches.
10254    fn parameter_marker(&self, _ordinal: usize) -> String {
10255        "?".to_owned()
10256    }
10257
10258    // ── Backend-capability + dialect probes (br-frankenpandas-6dtf) ─────
10259    //
10260    // Default impls return conservative values so existing implementations
10261    // stay backwards-compatible; concrete backends override per their
10262    // engine. Phase 2 wires these probes into the read_sql / read_sql_table
10263    // dispatch path so per-backend SQL quirks (RETURNING, max param count,
10264    // transaction semantics) can fan out without leaking concrete types.
10265
10266    /// Short identifier for this backend's SQL dialect.
10267    ///
10268    /// Used by diagnostics + DISCREPANCIES.md routing. Backends should
10269    /// override with the canonical pandas/SQLAlchemy dialect name:
10270    /// `"sqlite"`, `"postgresql"`, `"mysql"`, `"mariadb"`, `"oracle"`, etc.
10271    /// Default `"unknown"` flags un-customized impls during reviews.
10272    fn dialect_name(&self) -> &'static str {
10273        "unknown"
10274    }
10275
10276    /// Whether this backend honors `INSERT ... RETURNING ...` natively.
10277    ///
10278    /// Drives the write_sql path's choice between RETURNING-based row
10279    /// retrieval and a follow-up SELECT. Default `false` is the
10280    /// conservative choice (forces follow-up SELECT path) until each
10281    /// backend opts in.
10282    fn supports_returning(&self) -> bool {
10283        false
10284    }
10285
10286    /// Hard upper bound on bound-parameter count per statement, if known.
10287    ///
10288    /// SQLite (3.32+): 32766. PostgreSQL: 65535. MySQL: 65535. Backends
10289    /// that don't surface a meaningful cap return `None`. The bulk-insert
10290    /// path uses this to chunk multi-row INSERTs so a single executemany
10291    /// stays under the backend's parameter ceiling.
10292    fn max_param_count(&self) -> Option<usize> {
10293        None
10294    }
10295
10296    /// Maximum identifier length supported by the backend, or `None`
10297    /// when no documented limit exists (or the limit is irrelevant for
10298    /// the deployment).
10299    ///
10300    /// Per br-frankenpandas-cs81 (fd90.26). Defaults to `None`. Known
10301    /// caps: PostgreSQL = 63, MySQL = 64, MSSQL = 128, Oracle = 30
10302    /// (pre-12.2) or 128 (12.2+), SQLite = no documented limit.
10303    /// Useful for to_sql validation when emitting auto-generated
10304    /// index/constraint/column names that could otherwise exceed
10305    /// backend limits and produce truncated or rejected DDL.
10306    fn max_identifier_length(&self) -> Option<usize> {
10307        None
10308    }
10309
10310    /// Run `f` inside a transaction. The default impl runs `f` without
10311    /// BEGIN/COMMIT — backends that support transactions should override
10312    /// to wrap in their native transaction primitive (rusqlite `BEGIN`,
10313    /// PostgreSQL `BEGIN`, MySQL `START TRANSACTION`, ...). On `Err`
10314    /// from `f`, transactional backends roll back; on `Ok` they commit.
10315    ///
10316    /// The default impl is intentionally a no-op so non-transactional
10317    /// connection wrappers (e.g. test doubles) compile without
10318    /// implementation effort. Production backends MUST override.
10319    fn with_transaction<T, F>(&self, f: F) -> Result<T, IoError>
10320    where
10321        F: FnOnce(&Self) -> Result<T, IoError>,
10322        Self: Sized,
10323    {
10324        f(self)
10325    }
10326
10327    /// Quote a SQL identifier (table name, column name, schema name) for
10328    /// safe inclusion in a generated statement.
10329    ///
10330    /// Default impl: ANSI `"..."` form with embedded `"` doubled (matches
10331    /// SQLite + PostgreSQL). MySQL/MariaDB backends must override to
10332    /// produce `\`...\`` (backtick). MSSQL backends use `[...]`. Per
10333    /// br-frankenpandas-2y7w (fd90.10).
10334    ///
10335    /// NUL bytes in the identifier are rejected (security: prevents
10336    /// statement-injection via embedded null terminators in C-string
10337    /// driver layers).
10338    fn quote_identifier(&self, ident: &str) -> Result<String, IoError> {
10339        if ident.contains('\0') {
10340            return Err(IoError::Sql("invalid SQL identifier: NUL byte".to_owned()));
10341        }
10342        Ok(format!("\"{}\"", ident.replace('"', "\"\"")))
10343    }
10344
10345    /// Whether this backend exposes multi-schema namespacing.
10346    ///
10347    /// PostgreSQL / MySQL / MariaDB / MSSQL / Oracle: true. SQLite (one
10348    /// schema per file connection — though ATTACH adds named schemas as
10349    /// a special case): false. Drives the `pd.read_sql_table(.., schema=X)`
10350    /// path's choice between qualifying the table reference (`schema.table`)
10351    /// and a connection-level pre-SET. Per br-frankenpandas-6dk9 (fd90.13).
10352    fn supports_schemas(&self) -> bool {
10353        false
10354    }
10355
10356    /// Default schema for unqualified table references, if the backend
10357    /// has one.
10358    ///
10359    /// PostgreSQL: `'public'` (or whatever the connection's `search_path`
10360    /// resolves to first). MySQL: the database name passed to the
10361    /// connection URL. SQLite: `None` (single namespace). The `read_sql_table`
10362    /// dispatch uses this when the user passes `schema=None` to choose
10363    /// between a bare `SELECT * FROM \"table\"` and a schema-qualified form.
10364    /// Default `None` keeps behavior identical to today's SQLite-only path.
10365    fn default_schema(&self) -> Option<String> {
10366        None
10367    }
10368
10369    /// Schema-aware table-existence check.
10370    ///
10371    /// Per br-frankenpandas-70d1 (fd90.17). Default impl delegates to
10372    /// `table_exists(table)` and ignores the schema argument — matches
10373    /// single-namespace embedded backends like SQLite. Multi-schema
10374    /// backends (PostgreSQL, MySQL, MSSQL) override to scope the check
10375    /// to the requested schema, so write_sql's `Fail` branch correctly
10376    /// distinguishes `analytics.users` from `audit.users`. The schema
10377    /// arg passes through unchanged — backends MAY consult
10378    /// `default_schema()` for their own fallback logic when `schema`
10379    /// is `None` (per fd90.57: this fallback is NOT applied by the
10380    /// default impl or the SQLite override).
10381    fn table_exists_in_schema(
10382        &self,
10383        table_name: &str,
10384        _schema: Option<&str>,
10385    ) -> Result<bool, IoError> {
10386        self.table_exists(table_name)
10387    }
10388
10389    /// List user-visible table names, optionally scoped to `schema`.
10390    ///
10391    /// Per br-frankenpandas-vhq2 (fd90.20). Default impl returns an empty
10392    /// vector — backends that cannot introspect (or that haven't yet
10393    /// implemented this method) report "no tables visible" rather than
10394    /// raising. Multi-schema backends (PostgreSQL, MySQL, MSSQL) override
10395    /// to query their information_schema; embedded backends (SQLite)
10396    /// override to query their internal catalog and ignore `schema`.
10397    fn list_tables(&self, _schema: Option<&str>) -> Result<Vec<String>, IoError> {
10398        Ok(Vec::new())
10399    }
10400
10401    /// Introspect a table's column metadata, optionally schema-scoped.
10402    ///
10403    /// Per br-frankenpandas-w43q (fd90.21). Returns `Ok(None)` if the
10404    /// table does not exist. Default impl returns `Ok(None)` for
10405    /// backends that cannot introspect; rusqlite overrides to use
10406    /// `PRAGMA table_info`. Multi-schema backends override to query
10407    /// `information_schema.columns` filtered by `schema`. Schema arg is
10408    /// silently ignored when `supports_schemas() == false`.
10409    fn table_schema(
10410        &self,
10411        _table_name: &str,
10412        _schema: Option<&str>,
10413    ) -> Result<Option<SqlTableSchema>, IoError> {
10414        Ok(None)
10415    }
10416
10417    /// List user-visible schemas (PostgreSQL "schemas", MySQL "databases").
10418    ///
10419    /// Per br-frankenpandas-lxhi (fd90.22). Default impl returns an empty
10420    /// vector. Single-namespace backends (SQLite) return empty as well —
10421    /// they have no meaningful schema concept. Multi-schema backends
10422    /// (PostgreSQL, MySQL, MSSQL) override to query their catalog and
10423    /// filter out internal/system schemas (`pg_*`, `information_schema`,
10424    /// `mysql`, `performance_schema`, etc.) so user-visible schemas
10425    /// surface cleanly.
10426    fn list_schemas(&self) -> Result<Vec<String>, IoError> {
10427        Ok(Vec::new())
10428    }
10429
10430    /// Probe the backend server's version string.
10431    ///
10432    /// Per br-frankenpandas-e23k (fd90.24). Useful for dialect-version
10433    /// gating (INSERT ... RETURNING needs PG 8.2+ / SQLite 3.35.0+,
10434    /// JSON operators need MySQL 5.7.8+, etc.) and for diagnostics.
10435    /// Default impl returns `Ok(None)` so backends that can't probe
10436    /// (or that haven't yet implemented this) report "unknown" rather
10437    /// than raising. rusqlite override returns the SQLite library
10438    /// version. PostgreSQL/MySQL impls should override with
10439    /// `SHOW server_version` / `SELECT VERSION()`.
10440    fn server_version(&self) -> Result<Option<String>, IoError> {
10441        Ok(None)
10442    }
10443
10444    /// List user-visible view names, optionally scoped to `schema`.
10445    ///
10446    /// Per br-frankenpandas-gm3r (fd90.30). Default impl returns an
10447    /// empty vector. rusqlite override queries `sqlite_master WHERE
10448    /// type='view'`, excluding internal `sqlite_*` views. Multi-schema
10449    /// backends override with `information_schema.views` filtered by
10450    /// the schema arg. Schema is silently ignored when
10451    /// `supports_schemas() == false`. Companion to `list_tables` —
10452    /// pandas/SQLAlchemy keep tables and views in distinct buckets so
10453    /// `pd.read_sql_table` can distinguish them.
10454    fn list_views(&self, _schema: Option<&str>) -> Result<Vec<String>, IoError> {
10455        Ok(Vec::new())
10456    }
10457
10458    /// List indexes defined on a table, optionally schema-scoped.
10459    ///
10460    /// Per br-frankenpandas-bgv9 (fd90.28). Default impl returns
10461    /// `Ok(Vec::new())` for backends that can't introspect. rusqlite
10462    /// override uses `PRAGMA index_list(table)` + `PRAGMA index_info`
10463    /// per index, surfacing only user-created indexes (the auto-created
10464    /// indexes for PRIMARY KEY constraints are filtered out to match
10465    /// SQLAlchemy.Inspector.get_indexes() semantics). Multi-schema
10466    /// backends override with information_schema queries.
10467    fn list_indexes(
10468        &self,
10469        _table_name: &str,
10470        _schema: Option<&str>,
10471    ) -> Result<Vec<SqlIndexSchema>, IoError> {
10472        Ok(Vec::new())
10473    }
10474
10475    /// List UNIQUE constraints declared on a table (inline or table-level),
10476    /// excluding `CREATE UNIQUE INDEX` indexes (those land in `list_indexes`).
10477    ///
10478    /// Per br-frankenpandas-sh4v (fd90.31). Default impl returns
10479    /// `Ok(Vec::new())`. rusqlite override uses
10480    /// `PRAGMA index_list(table)` filtered by `origin == 'u'` (the
10481    /// auto-created indexes that back declared UNIQUE constraints)
10482    /// then `PRAGMA index_info` per match. Multi-schema backends
10483    /// override with information_schema queries.
10484    fn list_unique_constraints(
10485        &self,
10486        _table_name: &str,
10487        _schema: Option<&str>,
10488    ) -> Result<Vec<SqlUniqueConstraintSchema>, IoError> {
10489        Ok(Vec::new())
10490    }
10491
10492    /// Probe the table-level comment, optionally schema-scoped.
10493    ///
10494    /// Per br-frankenpandas-yu3w (fd90.32). Default impl returns
10495    /// `Ok(None)` — SQLite has no native table-comment storage so it
10496    /// inherits the default. PostgreSQL impls should override using
10497    /// `pg_catalog.obj_description(...)` or
10498    /// `pg_catalog.pg_class.relkind` joined to `pg_description`;
10499    /// MySQL uses `information_schema.tables.table_comment`; MSSQL
10500    /// reads from `sys.extended_properties`. Aligns with
10501    /// `SQLAlchemy.Inspector.get_table_comment()` shape (returns
10502    /// `{'text': comment_or_none}`).
10503    fn table_comment(
10504        &self,
10505        _table_name: &str,
10506        _schema: Option<&str>,
10507    ) -> Result<Option<String>, IoError> {
10508        Ok(None)
10509    }
10510
10511    /// List foreign-key constraints declared on a table, optionally
10512    /// schema-scoped.
10513    ///
10514    /// Per br-frankenpandas-uht8 (fd90.29). Default impl returns
10515    /// `Ok(Vec::new())`. rusqlite override uses
10516    /// `PRAGMA foreign_key_list(table)`, grouping rows by their `id`
10517    /// column (each id is a single FK constraint that may span multiple
10518    /// columns) and ordering paired columns by `seq`. Multi-schema
10519    /// backends override with `information_schema.referential_constraints`
10520    /// + `key_column_usage` joined queries.
10521    fn list_foreign_keys(
10522        &self,
10523        _table_name: &str,
10524        _schema: Option<&str>,
10525    ) -> Result<Vec<SqlForeignKeySchema>, IoError> {
10526        Ok(Vec::new())
10527    }
10528
10529    /// Return the primary-key column names for a table, ordered by
10530    /// the `primary_key_ordinal` reported by `table_schema`.
10531    ///
10532    /// Per br-frankenpandas-uw3y (fd90.25). Default impl delegates to
10533    /// `table_schema(table, schema)` and pulls out columns whose
10534    /// `primary_key_ordinal` is `Some(_)`, sorted ascending. Returns
10535    /// an empty vector when:
10536    /// - the table doesn't exist (`table_schema` returns `Ok(None)`),
10537    /// - the table has no primary key,
10538    /// - the backend can't introspect (default `table_schema`).
10539    ///
10540    /// Useful for upsert conflict-target generation, `index_label`
10541    /// defaulting, and schema validation. Backends can override to
10542    /// query their catalog directly when `table_schema` is too heavy.
10543    fn primary_key_columns(
10544        &self,
10545        table_name: &str,
10546        schema: Option<&str>,
10547    ) -> Result<Vec<String>, IoError> {
10548        // Per fd90.47: defer to the shared primary_keys_from_schema
10549        // helper so the filter+sort logic lives in exactly one place
10550        // (the helper is also used by SqlInspector::reflect_table).
10551        let Some(meta) = self.table_schema(table_name, schema)? else {
10552            return Ok(Vec::new());
10553        };
10554        Ok(primary_keys_from_schema(&meta))
10555    }
10556
10557    /// Reset a table to empty without dropping its definition.
10558    ///
10559    /// Per br-frankenpandas-phum (fd90.23). Default impl emits
10560    /// `DELETE FROM <table>` — universal SQL that every backend
10561    /// supports, but slower than TRUNCATE on large tables because the
10562    /// row deletes are logged in the transaction journal. PostgreSQL
10563    /// and MySQL backends should override with `TRUNCATE TABLE`,
10564    /// which is dramatically faster (DDL-style fast-path) and resets
10565    /// auto-increment sequences. The schema arg routes through
10566    /// `quote_identifier` and is silently ignored when
10567    /// `supports_schemas() == false`.
10568    fn truncate_table(&self, table_name: &str, schema: Option<&str>) -> Result<(), IoError> {
10569        validate_sql_table_name(table_name)?;
10570        validate_sql_table_ref_identifier_lengths(self, table_name, schema)?;
10571        let qualified = match schema {
10572            Some(s) if self.supports_schemas() => {
10573                validate_sql_schema_name(s)?;
10574                format!(
10575                    "{}.{}",
10576                    self.quote_identifier(s)?,
10577                    self.quote_identifier(table_name)?
10578                )
10579            }
10580            _ => self.quote_identifier(table_name)?,
10581        };
10582        self.execute_batch(&format!("DELETE FROM {qualified}"))
10583    }
10584}
10585
10586/// Map an fp-types DType to an SQLite column type declaration.
10587#[cfg(feature = "sql-sqlite")]
10588fn dtype_to_sql(dtype: DType) -> &'static str {
10589    match dtype {
10590        DType::Int64 | DType::Int64Nullable => "INTEGER",
10591        DType::Float64 => "REAL",
10592        DType::Utf8 => "TEXT",
10593        DType::Categorical => "TEXT",
10594        DType::Bool | DType::BoolNullable => "INTEGER",
10595        DType::Null => "TEXT",
10596        DType::Timedelta64 => "INTEGER", // store as nanoseconds
10597        DType::Datetime64 => "INTEGER",  // store as nanoseconds
10598        DType::Period => "INTEGER",      // store as ordinal
10599        DType::Interval => "TEXT",       // store as string
10600        DType::Sparse => "TEXT",
10601    }
10602}
10603
10604#[cfg(feature = "sql-sqlite")]
10605fn sqlite_decl_type_to_dtype(decl_type: &str) -> Option<DType> {
10606    let upper = decl_type.trim().to_ascii_uppercase();
10607    if upper.contains("INT") {
10608        Some(DType::Int64)
10609    } else if upper.contains("REAL") || upper.contains("FLOA") || upper.contains("DOUB") {
10610        Some(DType::Float64)
10611    } else if upper.contains("CHAR") || upper.contains("CLOB") || upper.contains("TEXT") {
10612        Some(DType::Utf8)
10613    } else {
10614        None
10615    }
10616}
10617
10618/// Convert an SQLite column value to a Scalar.
10619#[cfg(feature = "sql-sqlite")]
10620fn sql_value_to_scalar(value: &rusqlite::types::Value) -> Scalar {
10621    match value {
10622        rusqlite::types::Value::Null => Scalar::Null(NullKind::Null),
10623        rusqlite::types::Value::Integer(v) => Scalar::Int64(*v),
10624        rusqlite::types::Value::Real(v) => Scalar::Float64(*v),
10625        rusqlite::types::Value::Text(s) => Scalar::Utf8(s.clone()),
10626        rusqlite::types::Value::Blob(b) => Scalar::Utf8(format!("<blob:{} bytes>", b.len())),
10627    }
10628}
10629
10630#[cfg(feature = "sql-sqlite")]
10631fn sql_value_from_scalar(scalar: &Scalar) -> rusqlite::types::Value {
10632    match scalar {
10633        Scalar::Int64(v) => rusqlite::types::Value::Integer(*v),
10634        Scalar::Float64(v) => {
10635            if v.is_nan() {
10636                rusqlite::types::Value::Null
10637            } else {
10638                rusqlite::types::Value::Real(*v)
10639            }
10640        }
10641        Scalar::Bool(b) => rusqlite::types::Value::Integer(if *b { 1 } else { 0 }),
10642        Scalar::Utf8(s) => rusqlite::types::Value::Text(s.clone()),
10643        Scalar::Null(_) => rusqlite::types::Value::Null,
10644        Scalar::Timedelta64(v) => {
10645            if *v == Timedelta::NAT {
10646                rusqlite::types::Value::Null
10647            } else {
10648                rusqlite::types::Value::Integer(*v)
10649            }
10650        }
10651        Scalar::Datetime64(v) => {
10652            if *v == Timestamp::NAT {
10653                rusqlite::types::Value::Null
10654            } else {
10655                rusqlite::types::Value::Integer(*v)
10656            }
10657        }
10658        Scalar::Period(p) => {
10659            if p.ordinal == i64::MIN {
10660                rusqlite::types::Value::Null
10661            } else {
10662                rusqlite::types::Value::Integer(p.ordinal)
10663            }
10664        }
10665        Scalar::Interval(iv) => rusqlite::types::Value::Text(format!("{iv}")),
10666    }
10667}
10668
10669fn scalar_from_index_label(label: &IndexLabel) -> Scalar {
10670    match label {
10671        IndexLabel::Int64(v) => Scalar::Int64(*v),
10672        IndexLabel::Float64(v) => Scalar::Float64(v.0),
10673        IndexLabel::Bool(b) => Scalar::Bool(*b),
10674        IndexLabel::Utf8(s) => Scalar::Utf8(s.clone()),
10675        // Typed-null label round-trips to the same-kind missing scalar.
10676        IndexLabel::Null(kind) => Scalar::Null(*kind),
10677        IndexLabel::Timedelta64(v) => {
10678            if *v == Timedelta::NAT {
10679                Scalar::Null(NullKind::Null)
10680            } else {
10681                Scalar::Timedelta64(*v)
10682            }
10683        }
10684        IndexLabel::Datetime64(v) => {
10685            if *v == i64::MIN {
10686                Scalar::Null(NullKind::Null)
10687            } else {
10688                Scalar::Utf8(format_datetime_ns(*v))
10689            }
10690        }
10691    }
10692}
10693
10694#[cfg(feature = "sql-sqlite")]
10695impl SqlConnection for rusqlite::Connection {
10696    fn query(&self, query: &str, params: &[Scalar]) -> Result<SqlQueryResult, IoError> {
10697        let mut stmt = self
10698            .prepare(query)
10699            .map_err(|e| IoError::Sql(format!("prepare failed: {e}")))?;
10700
10701        let col_count = stmt.column_count();
10702        let columns: Vec<String> = (0..col_count)
10703            .map(|i| stmt.column_name(i).unwrap_or("?").to_owned())
10704            .collect();
10705
10706        let sql_params = params.iter().map(sql_value_from_scalar).collect::<Vec<_>>();
10707        let mut rows = stmt
10708            .query(rusqlite::params_from_iter(sql_params.iter()))
10709            .map_err(|e| IoError::Sql(format!("query failed: {e}")))?;
10710
10711        let mut out_rows = Vec::new();
10712        while let Some(row) = rows
10713            .next()
10714            .map_err(|e| IoError::Sql(format!("row fetch failed: {e}")))?
10715        {
10716            let mut values = Vec::with_capacity(col_count);
10717            for col_idx in 0..col_count {
10718                let value: rusqlite::types::Value = row
10719                    .get(col_idx)
10720                    .map_err(|e| IoError::Sql(format!("cell read failed: {e}")))?;
10721                values.push(sql_value_to_scalar(&value));
10722            }
10723            out_rows.push(values);
10724        }
10725
10726        Ok(SqlQueryResult {
10727            columns,
10728            rows: out_rows,
10729        })
10730    }
10731
10732    fn query_column_dtypes(
10733        &self,
10734        query: &str,
10735        _params: &[Scalar],
10736    ) -> Result<Vec<Option<DType>>, IoError> {
10737        let stmt = self
10738            .prepare(query)
10739            .map_err(|e| IoError::Sql(format!("prepare failed: {e}")))?;
10740        Ok(stmt
10741            .columns()
10742            .into_iter()
10743            .map(|column| column.decl_type().and_then(sqlite_decl_type_to_dtype))
10744            .collect())
10745    }
10746
10747    fn supports_paged_sql_chunks(&self) -> bool {
10748        true
10749    }
10750
10751    fn execute_batch(&self, sql: &str) -> Result<(), IoError> {
10752        rusqlite::Connection::execute_batch(self, sql)
10753            .map_err(|e| IoError::Sql(format!("execute_batch failed: {e}")))
10754    }
10755
10756    fn table_exists(&self, table_name: &str) -> Result<bool, IoError> {
10757        self.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name=?1")
10758            .and_then(|mut stmt| stmt.exists(rusqlite::params![table_name]))
10759            .map_err(|e| IoError::Sql(format!("existence check failed: {e}")))
10760    }
10761
10762    fn insert_rows(&self, insert_sql: &str, rows: &[Vec<Scalar>]) -> Result<(), IoError> {
10763        let tx = self
10764            .unchecked_transaction()
10765            .map_err(|e| IoError::Sql(format!("begin transaction failed: {e}")))?;
10766
10767        {
10768            let mut stmt = tx
10769                .prepare_cached(insert_sql)
10770                .map_err(|e| IoError::Sql(format!("prepare insert failed: {e}")))?;
10771
10772            for (row_idx, row_values) in rows.iter().enumerate() {
10773                let params = row_values
10774                    .iter()
10775                    .map(sql_value_from_scalar)
10776                    .collect::<Vec<_>>();
10777                stmt.execute(rusqlite::params_from_iter(params.iter()))
10778                    .map_err(|e| IoError::Sql(format!("insert row {row_idx} failed: {e}")))?;
10779            }
10780        }
10781
10782        tx.commit()
10783            .map_err(|e| IoError::Sql(format!("commit failed: {e}")))?;
10784        Ok(())
10785    }
10786
10787    fn dtype_sql(&self, dtype: DType) -> &'static str {
10788        dtype_to_sql(dtype)
10789    }
10790
10791    fn index_dtype_sql(&self, index: &Index) -> &'static str {
10792        sql_dtype_from_index(index)
10793    }
10794
10795    // br-frankenpandas-6dtf: backend-capability + dialect probes.
10796    fn dialect_name(&self) -> &'static str {
10797        "sqlite"
10798    }
10799
10800    fn supports_returning(&self) -> bool {
10801        // SQLite 3.35.0+ (released March 2021) supports INSERT ... RETURNING.
10802        // rusqlite ships with bundled SQLite >= 3.45 by default, so we can
10803        // unconditionally claim support here.
10804        true
10805    }
10806
10807    fn max_param_count(&self) -> Option<usize> {
10808        // SQLite default SQLITE_MAX_VARIABLE_NUMBER is 32766 since 3.32.0.
10809        // (Older builds capped at 999.) rusqlite bundled SQLite is current,
10810        // so this matches.
10811        Some(32766)
10812    }
10813
10814    fn with_transaction<T, F>(&self, f: F) -> Result<T, IoError>
10815    where
10816        F: FnOnce(&Self) -> Result<T, IoError>,
10817        Self: Sized,
10818    {
10819        struct RollbackOnDrop<'conn> {
10820            conn: &'conn rusqlite::Connection,
10821            active: bool,
10822        }
10823
10824        impl Drop for RollbackOnDrop<'_> {
10825            fn drop(&mut self) {
10826                if self.active {
10827                    let _ = rusqlite::Connection::execute_batch(self.conn, "ROLLBACK");
10828                }
10829            }
10830        }
10831
10832        // rusqlite's pure-trait `Self: Sized` constraint means we operate on
10833        // `&rusqlite::Connection` directly without taking the `&mut` that
10834        // `Connection::transaction()` requires. We emulate the same
10835        // BEGIN/COMMIT semantics with explicit pragmas. The guard keeps the
10836        // connection from retaining a write transaction if the callback
10837        // panics before we reach the explicit rollback/commit paths.
10838        self.execute_batch("BEGIN")
10839            .map_err(|e| IoError::Sql(format!("begin transaction failed: {e}")))?;
10840        let mut rollback = RollbackOnDrop {
10841            conn: self,
10842            active: true,
10843        };
10844        match f(self) {
10845            Ok(result) => {
10846                self.execute_batch("COMMIT")
10847                    .map_err(|e| IoError::Sql(format!("commit transaction failed: {e}")))?;
10848                rollback.active = false;
10849                Ok(result)
10850            }
10851            Err(err) => {
10852                // Best-effort rollback; surface the original error if rollback
10853                // also fails (rollback failure is logged via the Sql error
10854                // variant for diagnostics but the user wants the closure
10855                // error preserved as the primary signal).
10856                if self.execute_batch("ROLLBACK").is_ok() {
10857                    rollback.active = false;
10858                }
10859                Err(err)
10860            }
10861        }
10862    }
10863
10864    fn quote_identifier(&self, ident: &str) -> Result<String, IoError> {
10865        // SQLite accepts ANSI double-quotes for identifiers (it ALSO accepts
10866        // backticks for MySQL compat, but ANSI is the recommended form per
10867        // SQLite docs). Delegate to the existing free-fn helper to keep the
10868        // exact escaping policy in one place.
10869        quote_sql_ident(ident)
10870    }
10871
10872    fn list_tables(&self, _schema: Option<&str>) -> Result<Vec<String>, IoError> {
10873        // SQLite has a single namespace; the schema arg is silently
10874        // ignored to match `supports_schemas() == false`. We exclude
10875        // SQLite's internal `sqlite_*` book-keeping tables to match
10876        // pandas' SQLAlchemy dialect, which never surfaces them as
10877        // user tables.
10878        // Per fd90.50: ESCAPE '\' makes the `_` in 'sqlite\_%' a literal
10879        // underscore instead of a SQL LIKE single-char wildcard. Without
10880        // the escape, a user table named e.g. `sqliteX` would be
10881        // incorrectly excluded because the `_` matches any single char.
10882        let mut stmt = self
10883            .prepare(
10884                r"SELECT name FROM sqlite_master
10885                 WHERE type='table' AND name NOT LIKE 'sqlite\_%' ESCAPE '\'
10886                 ORDER BY name",
10887            )
10888            .map_err(|e| IoError::Sql(format!("list_tables prepare failed: {e}")))?;
10889        let names = stmt
10890            .query_map([], |row| row.get::<_, String>(0))
10891            .map_err(|e| IoError::Sql(format!("list_tables query failed: {e}")))?
10892            .collect::<Result<Vec<_>, _>>()
10893            .map_err(|e| IoError::Sql(format!("list_tables row read failed: {e}")))?;
10894        Ok(names)
10895    }
10896
10897    fn list_views(&self, _schema: Option<&str>) -> Result<Vec<String>, IoError> {
10898        // Same single-namespace policy as list_tables; type='view'
10899        // distinguishes the two buckets in sqlite_master.
10900        // Per fd90.50: same ESCAPE '\' fix as list_tables to treat
10901        // the underscore in 'sqlite_' as a literal.
10902        let mut stmt = self
10903            .prepare(
10904                r"SELECT name FROM sqlite_master
10905                 WHERE type='view' AND name NOT LIKE 'sqlite\_%' ESCAPE '\'
10906                 ORDER BY name",
10907            )
10908            .map_err(|e| IoError::Sql(format!("list_views prepare failed: {e}")))?;
10909        let names = stmt
10910            .query_map([], |row| row.get::<_, String>(0))
10911            .map_err(|e| IoError::Sql(format!("list_views query failed: {e}")))?
10912            .collect::<Result<Vec<_>, _>>()
10913            .map_err(|e| IoError::Sql(format!("list_views row read failed: {e}")))?;
10914        Ok(names)
10915    }
10916
10917    fn table_schema(
10918        &self,
10919        table_name: &str,
10920        _schema: Option<&str>,
10921    ) -> Result<Option<SqlTableSchema>, IoError> {
10922        // Validate the table name first — PRAGMA table_info doesn't
10923        // accept parameter binding, so we must reject anything that
10924        // could break out of the identifier slot.
10925        validate_sql_table_name(table_name)?;
10926        // PRAGMA table_info returns: cid, name, type, notnull, dflt_value, pk.
10927        let pragma = format!("PRAGMA table_info(\"{}\")", table_name.replace('"', "\"\""));
10928        let mut stmt = self
10929            .prepare(&pragma)
10930            .map_err(|e| IoError::Sql(format!("table_schema prepare failed: {e}")))?;
10931        // PRAGMA table_info row tuple: (name, type, notnull, dflt_value, pk).
10932        // Type alias keeps clippy::type_complexity happy on the
10933        // intermediate Vec used for the two-pass autoincrement detection.
10934        type ColumnInfoRow = (String, Option<String>, i64, Option<String>, i64);
10935        let raw_rows: Vec<ColumnInfoRow> = stmt
10936            .query_map([], |row| {
10937                Ok((
10938                    row.get::<_, String>(1)?,
10939                    row.get::<_, Option<String>>(2)?,
10940                    row.get::<_, i64>(3)?,
10941                    row.get::<_, Option<String>>(4)?,
10942                    row.get::<_, i64>(5)?,
10943                ))
10944            })
10945            .map_err(|e| IoError::Sql(format!("table_schema query failed: {e}")))?
10946            .collect::<Result<Vec<_>, _>>()
10947            .map_err(|e| IoError::Sql(format!("table_schema row read failed: {e}")))?;
10948
10949        // Per fd90.42 (refines fd90.37): SQLite's rowid-alias rule
10950        // requires the column to be the SOLE primary key — i.e. exactly
10951        // one row in PRAGMA table_info has pk > 0. Composite PKs (where
10952        // multiple columns have pk > 0) never qualify, even if the
10953        // first column is INTEGER. So we count single-PK status across
10954        // the table before deciding any column's autoincrement bit.
10955        let pk_count = raw_rows.iter().filter(|(_, _, _, _, pk)| *pk > 0).count();
10956        let single_pk = pk_count == 1;
10957
10958        let mut columns: Vec<SqlColumnSchema> = Vec::with_capacity(raw_rows.len());
10959        for (name, declared, notnull, dflt, pk) in raw_rows {
10960            let cleaned_type = declared.filter(|s| !s.is_empty());
10961            let autoincrement = single_pk
10962                && pk == 1
10963                && cleaned_type
10964                    .as_deref()
10965                    .map(|t| t.eq_ignore_ascii_case("INTEGER"))
10966                    .unwrap_or(false);
10967            columns.push(SqlColumnSchema {
10968                name,
10969                declared_type: cleaned_type,
10970                nullable: notnull == 0,
10971                default_value: dflt,
10972                primary_key_ordinal: if pk > 0 {
10973                    Some(usize::try_from(pk - 1).unwrap_or(0))
10974                } else {
10975                    None
10976                },
10977                comment: None,
10978                autoincrement,
10979            });
10980        }
10981        if columns.is_empty() {
10982            // PRAGMA table_info on a non-existent table returns 0 rows
10983            // without erroring; map that to None so callers can
10984            // distinguish missing tables from empty ones.
10985            Ok(None)
10986        } else {
10987            Ok(Some(SqlTableSchema {
10988                table_name: table_name.to_owned(),
10989                columns,
10990            }))
10991        }
10992    }
10993
10994    fn server_version(&self) -> Result<Option<String>, IoError> {
10995        // sqlite_version() is a built-in scalar that returns the
10996        // SQLite library version string (e.g. "3.45.1").
10997        let version: String = self
10998            .query_row("SELECT sqlite_version()", [], |row| row.get(0))
10999            .map_err(|e| IoError::Sql(format!("server_version query failed: {e}")))?;
11000        Ok(Some(version))
11001    }
11002
11003    fn list_indexes(
11004        &self,
11005        table_name: &str,
11006        _schema: Option<&str>,
11007    ) -> Result<Vec<SqlIndexSchema>, IoError> {
11008        validate_sql_table_name(table_name)?;
11009        // PRAGMA index_list(table) returns: seq, name, unique, origin, partial.
11010        // origin is 'c' for CREATE INDEX (user), 'pk' for PRIMARY KEY auto,
11011        // 'u' for UNIQUE constraint auto. SQLAlchemy.Inspector surfaces
11012        // only the user-created ones, so we filter out 'pk' to match.
11013        let pragma_list = format!("PRAGMA index_list(\"{}\")", table_name.replace('"', "\"\""));
11014        let mut list_stmt = self
11015            .prepare(&pragma_list)
11016            .map_err(|e| IoError::Sql(format!("list_indexes prepare failed: {e}")))?;
11017        let index_meta = list_stmt
11018            .query_map([], |row| {
11019                Ok((
11020                    row.get::<_, String>(1)?, // name
11021                    row.get::<_, i64>(2)?,    // unique flag
11022                    row.get::<_, String>(3)?, // origin
11023                ))
11024            })
11025            .map_err(|e| IoError::Sql(format!("list_indexes query failed: {e}")))?
11026            .collect::<Result<Vec<_>, _>>()
11027            .map_err(|e| IoError::Sql(format!("list_indexes row read failed: {e}")))?;
11028
11029        let mut indexes = Vec::new();
11030        for (name, uniq, origin) in index_meta {
11031            if origin == "pk" {
11032                // Auto-created PK index — pandas/SQLAlchemy hide it.
11033                continue;
11034            }
11035            if origin == "u" {
11036                // Auto-created index backing a declared UNIQUE
11037                // constraint — surfaced via list_unique_constraints
11038                // (fd90.31), not here, to match SQLAlchemy disjoint
11039                // bucketing between get_indexes and
11040                // get_unique_constraints.
11041                continue;
11042            }
11043            // PRAGMA index_info(idx) returns: seqno, cid, column_name (col2 may
11044            // be NULL for expression-based indexes — skip those rather than
11045            // surfacing partial column lists).
11046            let pragma_info = format!("PRAGMA index_info(\"{}\")", name.replace('"', "\"\""));
11047            let mut info_stmt = self
11048                .prepare(&pragma_info)
11049                .map_err(|e| IoError::Sql(format!("index_info prepare failed: {e}")))?;
11050            let cols = info_stmt
11051                .query_map([], |row| {
11052                    Ok((row.get::<_, i64>(0)?, row.get::<_, Option<String>>(2)?))
11053                })
11054                .map_err(|e| IoError::Sql(format!("index_info query failed: {e}")))?
11055                .collect::<Result<Vec<_>, _>>()
11056                .map_err(|e| IoError::Sql(format!("index_info row read failed: {e}")))?;
11057            // Skip expression-based indexes (any column_name is NULL).
11058            if cols.iter().any(|(_, c)| c.is_none()) {
11059                continue;
11060            }
11061            let mut sorted: Vec<(i64, String)> = cols
11062                .into_iter()
11063                .map(|(seq, c)| (seq, c.unwrap_or_default()))
11064                .collect();
11065            sorted.sort_by_key(|(seq, _)| *seq);
11066            indexes.push(SqlIndexSchema {
11067                name,
11068                columns: sorted.into_iter().map(|(_, c)| c).collect(),
11069                unique: uniq != 0,
11070            });
11071        }
11072        Ok(indexes)
11073    }
11074
11075    fn list_unique_constraints(
11076        &self,
11077        table_name: &str,
11078        _schema: Option<&str>,
11079    ) -> Result<Vec<SqlUniqueConstraintSchema>, IoError> {
11080        validate_sql_table_name(table_name)?;
11081        // PRAGMA index_list(table) origin column:
11082        //   'c' = CREATE INDEX (user) — surfaces via list_indexes
11083        //   'u' = UNIQUE constraint   — surfaces here
11084        //   'pk' = PRIMARY KEY auto   — surfaces via primary_key_columns
11085        let pragma_list = format!("PRAGMA index_list(\"{}\")", table_name.replace('"', "\"\""));
11086        let mut list_stmt = self
11087            .prepare(&pragma_list)
11088            .map_err(|e| IoError::Sql(format!("list_unique_constraints prepare failed: {e}")))?;
11089        let candidates = list_stmt
11090            .query_map([], |row| {
11091                Ok((
11092                    row.get::<_, String>(1)?, // index name
11093                    row.get::<_, String>(3)?, // origin
11094                ))
11095            })
11096            .map_err(|e| IoError::Sql(format!("list_unique_constraints query failed: {e}")))?
11097            .collect::<Result<Vec<_>, _>>()
11098            .map_err(|e| IoError::Sql(format!("list_unique_constraints row read failed: {e}")))?;
11099
11100        let mut constraints = Vec::new();
11101        for (name, origin) in candidates {
11102            if origin != "u" {
11103                continue;
11104            }
11105            let pragma_info = format!("PRAGMA index_info(\"{}\")", name.replace('"', "\"\""));
11106            let mut info_stmt = self
11107                .prepare(&pragma_info)
11108                .map_err(|e| IoError::Sql(format!("uq index_info prepare failed: {e}")))?;
11109            let cols = info_stmt
11110                .query_map([], |row| {
11111                    Ok((row.get::<_, i64>(0)?, row.get::<_, Option<String>>(2)?))
11112                })
11113                .map_err(|e| IoError::Sql(format!("uq index_info query failed: {e}")))?
11114                .collect::<Result<Vec<_>, _>>()
11115                .map_err(|e| IoError::Sql(format!("uq index_info row read failed: {e}")))?;
11116            // Skip expression-based unique constraints (column NULL).
11117            if cols.iter().any(|(_, c)| c.is_none()) {
11118                continue;
11119            }
11120            let mut sorted: Vec<(i64, String)> = cols
11121                .into_iter()
11122                .map(|(seq, c)| (seq, c.unwrap_or_default()))
11123                .collect();
11124            sorted.sort_by_key(|(seq, _)| *seq);
11125            constraints.push(SqlUniqueConstraintSchema {
11126                name,
11127                columns: sorted.into_iter().map(|(_, c)| c).collect(),
11128            });
11129        }
11130        Ok(constraints)
11131    }
11132
11133    fn list_foreign_keys(
11134        &self,
11135        table_name: &str,
11136        _schema: Option<&str>,
11137    ) -> Result<Vec<SqlForeignKeySchema>, IoError> {
11138        // PRAGMA foreign_key_list rows: (seq, referenced_table, from_col, to_col).
11139        // The constraint id is the BTreeMap key; we don't repeat it inside the
11140        // value tuple. Type alias keeps clippy::type_complexity happy and
11141        // the grouping logic readable.
11142        type FkRow = (i64, String, String, Option<String>);
11143
11144        validate_sql_table_name(table_name)?;
11145        // PRAGMA foreign_key_list(table) returns: id, seq, table, from, to,
11146        // on_update, on_delete, match. Each `id` is one FK constraint;
11147        // multiple rows with the same id describe a composite FK.
11148        let pragma = format!(
11149            "PRAGMA foreign_key_list(\"{}\")",
11150            table_name.replace('"', "\"\"")
11151        );
11152        let mut stmt = self
11153            .prepare(&pragma)
11154            .map_err(|e| IoError::Sql(format!("list_foreign_keys prepare failed: {e}")))?;
11155        let rows: Vec<(i64, FkRow)> = stmt
11156            .query_map([], |row| {
11157                Ok((
11158                    row.get::<_, i64>(0)?, // id
11159                    (
11160                        row.get::<_, i64>(1)?,            // seq
11161                        row.get::<_, String>(2)?,         // referenced table
11162                        row.get::<_, String>(3)?,         // from column
11163                        row.get::<_, Option<String>>(4)?, // to column (nullable)
11164                    ),
11165                ))
11166            })
11167            .map_err(|e| IoError::Sql(format!("list_foreign_keys query failed: {e}")))?
11168            .collect::<Result<Vec<_>, _>>()
11169            .map_err(|e| IoError::Sql(format!("list_foreign_keys row read failed: {e}")))?;
11170
11171        // Group by id; preserve discovery order across distinct ids.
11172        let mut order: Vec<i64> = Vec::new();
11173        let mut grouped: std::collections::BTreeMap<i64, Vec<FkRow>> =
11174            std::collections::BTreeMap::new();
11175        for (id, fk_row) in rows {
11176            let (seq, ref_table, from_col, to_col) = fk_row;
11177            if !grouped.contains_key(&id) {
11178                order.push(id);
11179            }
11180            grouped
11181                .entry(id)
11182                .or_default()
11183                .push((seq, ref_table, from_col, to_col));
11184        }
11185
11186        let mut fks = Vec::with_capacity(order.len());
11187        for id in order {
11188            let mut group = grouped.remove(&id).unwrap_or_default();
11189            group.sort_by_key(|(seq, _, _, _)| *seq);
11190            let ref_table = group
11191                .first()
11192                .map(|(_, t, _, _)| t.clone())
11193                .unwrap_or_default();
11194            let mut columns = Vec::with_capacity(group.len());
11195            let mut referenced_columns: Vec<Option<String>> = Vec::with_capacity(group.len());
11196            for (_, _, from_col, to_col) in group {
11197                columns.push(from_col);
11198                referenced_columns.push(to_col);
11199            }
11200            // Per fd90.44: when ALL `to` columns are NULL, the user
11201            // declared `FOREIGN KEY (cols) REFERENCES parent` (implicit
11202            // reference to parent's PK). Resolve by looking up the
11203            // parent's primary key columns. SQLAlchemy.Inspector
11204            // surfaces these as resolved-to-PK references; matching
11205            // that behavior keeps callers from missing real FKs.
11206            let resolved_columns: Vec<String> = if referenced_columns.iter().all(Option::is_none) {
11207                // Implicit-PK reference: look up parent's PK.
11208                let pk = self.primary_key_columns(&ref_table, None)?;
11209                if pk.len() == columns.len() {
11210                    pk
11211                } else {
11212                    // Parent PK shape doesn't match FK column count
11213                    // (parent has no PK, or composite mismatch). Skip
11214                    // — fabricating columns would mislead callers
11215                    // worse than hiding the FK.
11216                    continue;
11217                }
11218            } else if referenced_columns.iter().all(Option::is_some) {
11219                // Fully explicit: every column has a resolved 'to'.
11220                referenced_columns.into_iter().flatten().collect()
11221            } else {
11222                // Mixed Some/None: SQLite shouldn't produce this for
11223                // a single FK group, but if it ever does, skip rather
11224                // than mispair.
11225                continue;
11226            };
11227            fks.push(SqlForeignKeySchema {
11228                // SQLite PRAGMA foreign_key_list does not surface a
11229                // CONSTRAINT name; pandas/SQLAlchemy report None there too.
11230                constraint_name: None,
11231                columns,
11232                referenced_table: ref_table,
11233                referenced_columns: resolved_columns,
11234            });
11235        }
11236        Ok(fks)
11237    }
11238}
11239
11240#[cfg(feature = "sql-sqlite")]
11241fn sql_dtype_from_index(index: &Index) -> &'static str {
11242    for label in index.labels() {
11243        match label {
11244            IndexLabel::Int64(_) => return "INTEGER",
11245            IndexLabel::Utf8(_) => return "TEXT",
11246            IndexLabel::Timedelta64(v) if *v != Timedelta::NAT => return "INTEGER",
11247            IndexLabel::Datetime64(v) if *v != i64::MIN => return "TEXT",
11248            _ => {}
11249        }
11250    }
11251    "TEXT"
11252}
11253
11254fn resolve_sql_index_label(
11255    frame: &DataFrame,
11256    options: &SqlWriteOptions,
11257) -> Result<Option<String>, IoError> {
11258    if !options.index {
11259        return Ok(None);
11260    }
11261
11262    let label = options
11263        .index_label
11264        .clone()
11265        .or_else(|| frame.index().name().map(str::to_owned))
11266        .unwrap_or_else(|| "index".to_owned());
11267
11268    if frame.column(&label).is_some() {
11269        return Err(IoError::DuplicateColumnName(label));
11270    }
11271
11272    Ok(Some(label))
11273}
11274
11275// Per br-frankenpandas-ld8h (fd90.45): these helpers are only called
11276// from the rusqlite SqlConnection impl, which is gated behind
11277// `feature = "sql-sqlite"`. Mirroring the gate here keeps
11278// --no-default-features builds clean of dead-code warnings.
11279#[cfg(feature = "sql-sqlite")]
11280fn escape_sql_ident(name: &str) -> Result<String, IoError> {
11281    if name.contains('\0') {
11282        return Err(IoError::Sql("invalid SQL identifier: NUL byte".to_owned()));
11283    }
11284    Ok(name.replace('"', "\"\""))
11285}
11286
11287#[cfg(feature = "sql-sqlite")]
11288fn quote_sql_ident(name: &str) -> Result<String, IoError> {
11289    Ok(format!("\"{}\"", escape_sql_ident(name)?))
11290}
11291
11292/// Per br-frankenpandas-4l7a (fd90.55): shared identifier-shape
11293/// validator used by `validate_sql_table_name` and
11294/// `validate_sql_column_name`. `kind` is the user-facing label
11295/// inserted into the error message ("table", "column", ...). The
11296/// rule is the same for both: non-empty, ASCII-alphanumeric or
11297/// underscore only — defense in depth alongside `quote_identifier`
11298/// (which handles embedded quotes but doesn't reject other shapes).
11299fn validate_sql_ident(name: &str, kind: &str) -> Result<(), IoError> {
11300    if name.is_empty() || !name.chars().all(|c| c.is_alphanumeric() || c == '_') {
11301        return Err(IoError::Sql(format!(
11302            "invalid {kind} name: '{name}' (must be non-empty, only alphanumeric and underscore allowed)"
11303        )));
11304    }
11305    Ok(())
11306}
11307
11308fn validate_sql_table_name(table_name: &str) -> Result<(), IoError> {
11309    validate_sql_ident(table_name, "table")
11310}
11311
11312/// Per br-frankenpandas-597l (fd90.56): dedicated schema-name
11313/// validator so error messages correctly identify the invalid
11314/// identifier as a schema rather than a table. Same alphanumeric+
11315/// underscore rule as table/column names.
11316fn validate_sql_schema_name(schema: &str) -> Result<(), IoError> {
11317    validate_sql_ident(schema, "schema")
11318}
11319
11320/// Validate `name` against the backend's identifier-length cap.
11321///
11322/// Per br-frankenpandas-9ynk (fd90.27). When `max` is `Some(n)`, errors
11323/// out when `name.len() > n`. When `max` is `None`, accepts any length
11324/// (e.g. SQLite, where the engine has no documented limit). `kind` is
11325/// the user-facing label used in the error message ("table", "column",
11326/// "index label", ...) so misuse points cleanly back to the offending
11327/// identifier without callers having to format the message.
11328fn validate_sql_identifier_length(
11329    name: &str,
11330    max: Option<usize>,
11331    kind: &str,
11332) -> Result<(), IoError> {
11333    if let Some(limit) = max
11334        && name.len() > limit
11335    {
11336        return Err(IoError::Sql(format!(
11337            "invalid {kind} name '{name}': length {len} exceeds backend identifier limit ({limit})",
11338            len = name.len()
11339        )));
11340    }
11341    Ok(())
11342}
11343
11344fn validate_sql_table_ref_identifier_lengths<C: SqlConnection + ?Sized>(
11345    conn: &C,
11346    table_name: &str,
11347    schema: Option<&str>,
11348) -> Result<(), IoError> {
11349    let max = conn.max_identifier_length();
11350    validate_sql_identifier_length(table_name, max, "table")?;
11351    if let Some(s) = schema {
11352        validate_sql_identifier_length(s, max, "schema")?;
11353    }
11354    Ok(())
11355}
11356
11357fn validate_sql_column_identifier_lengths<C, I, S>(conn: &C, names: I) -> Result<(), IoError>
11358where
11359    C: SqlConnection + ?Sized,
11360    I: IntoIterator<Item = S>,
11361    S: AsRef<str>,
11362{
11363    let max = conn.max_identifier_length();
11364    for name in names {
11365        validate_sql_identifier_length(name.as_ref(), max, "column")?;
11366    }
11367    Ok(())
11368}
11369
11370fn sql_select_all_query<C: SqlConnection>(conn: &C, table_name: &str) -> Result<String, IoError> {
11371    sql_select_all_query_in_schema(conn, table_name, None)
11372}
11373
11374/// Build a `SELECT * FROM ...` statement, optionally schema-qualified.
11375///
11376/// Per br-frankenpandas-u6zn (fd90.14). When `schema` is `Some(s)` AND
11377/// `conn.supports_schemas()`, the FROM clause becomes `\"schema\".\"table\"`.
11378/// When `supports_schemas` returns false, any `Some(s)` is rejected before
11379/// query generation so `read_sql_table(schema=...)` matches pandas' fail-closed
11380/// SQLite behavior.
11381fn sql_select_all_query_in_schema<C: SqlConnection>(
11382    conn: &C,
11383    table_name: &str,
11384    schema: Option<&str>,
11385) -> Result<String, IoError> {
11386    validate_sql_table_name(table_name)?;
11387    validate_sql_table_ref_identifier_lengths(conn, table_name, schema)?;
11388    let qualified = match schema {
11389        Some(s) => {
11390            validate_sql_schema_name(s)?;
11391            if !conn.supports_schemas() {
11392                return Err(IoError::Sql(format!(
11393                    "read_sql_table: schema is not supported by {} backend",
11394                    conn.dialect_name()
11395                )));
11396            }
11397            format!(
11398                "{}.{}",
11399                conn.quote_identifier(s)?,
11400                conn.quote_identifier(table_name)?
11401            )
11402        }
11403        _ => conn.quote_identifier(table_name)?,
11404    };
11405    Ok(format!("SELECT * FROM {qualified}"))
11406}
11407
11408fn validate_sql_column_name(column_name: &str) -> Result<(), IoError> {
11409    validate_sql_ident(column_name, "column")
11410}
11411
11412fn sql_select_columns_query<C: SqlConnection>(
11413    conn: &C,
11414    table_name: &str,
11415    columns: &[&str],
11416) -> Result<String, IoError> {
11417    sql_select_columns_query_in_schema(conn, table_name, None, columns)
11418}
11419
11420/// Build a `SELECT col1, col2, ... FROM ...` statement, optionally
11421/// schema-qualified.
11422///
11423/// Per br-frankenpandas-d3e9 (fd90.34). Companion to
11424/// `sql_select_all_query_in_schema`. Same schema rules: when
11425/// `schema` is `Some(s)` AND `conn.supports_schemas()`, the FROM
11426/// clause becomes `\"schema\".\"table\"`; when `supports_schemas()`
11427/// returns false, the request is rejected before query generation.
11428fn sql_select_columns_query_in_schema<C: SqlConnection>(
11429    conn: &C,
11430    table_name: &str,
11431    schema: Option<&str>,
11432    columns: &[&str],
11433) -> Result<String, IoError> {
11434    validate_sql_table_name(table_name)?;
11435    if columns.is_empty() {
11436        return Err(IoError::Sql(
11437            "read_sql_table_columns: columns must be non-empty".to_owned(),
11438        ));
11439    }
11440    for name in columns {
11441        validate_sql_column_name(name)?;
11442    }
11443    validate_sql_table_ref_identifier_lengths(conn, table_name, schema)?;
11444    validate_sql_column_identifier_lengths(conn, columns)?;
11445
11446    let qualified = match schema {
11447        Some(s) => {
11448            validate_sql_schema_name(s)?;
11449            if !conn.supports_schemas() {
11450                return Err(IoError::Sql(format!(
11451                    "read_sql_table: schema is not supported by {} backend",
11452                    conn.dialect_name()
11453                )));
11454            }
11455            format!(
11456                "{}.{}",
11457                conn.quote_identifier(s)?,
11458                conn.quote_identifier(table_name)?
11459            )
11460        }
11461        _ => conn.quote_identifier(table_name)?,
11462    };
11463    let projection: Vec<String> = columns
11464        .iter()
11465        .map(|name| conn.quote_identifier(name))
11466        .collect::<Result<_, _>>()?;
11467    Ok(format!(
11468        "SELECT {} FROM {}",
11469        projection.join(", "),
11470        qualified
11471    ))
11472}
11473
11474fn sql_column_definition<C: SqlConnection>(
11475    conn: &C,
11476    column_name: &str,
11477    sql_type: &str,
11478) -> Result<String, IoError> {
11479    Ok(format!(
11480        "{} {sql_type}",
11481        conn.quote_identifier(column_name)?
11482    ))
11483}
11484
11485// ============================================================================
11486// PostgreSQL SqlConnection placeholder (feature = "sql-postgresql")
11487// ============================================================================
11488
11489#[cfg(feature = "sql-mysql")]
11490use std::cell::RefCell;
11491
11492// The `sql-postgresql` feature is intentionally a placeholder under the
11493// workspace no-Tokio policy. The removed concrete adapter used the `postgres`
11494// crate, which is built on tokio-postgres and pulled Tokio into all-features
11495// builds even when users did not need PostgreSQL.
11496
11497// ============================================================================
11498// MySQL SqlConnection Implementation (feature = "sql-mysql")
11499// ============================================================================
11500
11501/// Wrapper around `mysql::Conn` providing interior mutability for the
11502/// `SqlConnection` trait (which requires `&self`).
11503#[cfg(feature = "sql-mysql")]
11504pub struct MysqlConnection {
11505    conn: RefCell<mysql::Conn>,
11506}
11507
11508#[cfg(feature = "sql-mysql")]
11509impl MysqlConnection {
11510    pub fn new(conn: mysql::Conn) -> Self {
11511        Self {
11512            conn: RefCell::new(conn),
11513        }
11514    }
11515}
11516
11517#[cfg(feature = "sql-mysql")]
11518impl SqlConnection for MysqlConnection {
11519    fn query(&self, query_str: &str, params: &[Scalar]) -> Result<SqlQueryResult, IoError> {
11520        use mysql::prelude::*;
11521
11522        let mysql_params: Vec<mysql::Value> = params.iter().map(scalar_to_mysql_value).collect();
11523        let result: Vec<mysql::Row> = self
11524            .conn
11525            .borrow_mut()
11526            .exec(query_str, mysql_params)
11527            .map_err(|e| IoError::Sql(format!("MySQL query failed: {e}")))?;
11528
11529        if result.is_empty() {
11530            return Ok(SqlQueryResult {
11531                columns: Vec::new(),
11532                rows: Vec::new(),
11533            });
11534        }
11535
11536        let columns: Vec<String> = result[0]
11537            .columns_ref()
11538            .iter()
11539            .map(|c| c.name_str().to_string())
11540            .collect();
11541
11542        let mut out_rows = Vec::new();
11543        for row in &result {
11544            let mut values = Vec::new();
11545            for idx in 0..row.len() {
11546                let value = mysql_value_to_scalar(row.get(idx));
11547                values.push(value);
11548            }
11549            out_rows.push(values);
11550        }
11551
11552        Ok(SqlQueryResult {
11553            columns,
11554            rows: out_rows,
11555        })
11556    }
11557
11558    fn execute_batch(&self, sql: &str) -> Result<(), IoError> {
11559        use mysql::prelude::*;
11560        let mut conn = self.conn.borrow_mut();
11561        for statement in sql.split(';').filter(|s| !s.trim().is_empty()) {
11562            conn.query_drop(statement)
11563                .map_err(|e| IoError::Sql(format!("MySQL execute failed: {e}")))?;
11564        }
11565        Ok(())
11566    }
11567
11568    fn table_exists(&self, table_name: &str) -> Result<bool, IoError> {
11569        use mysql::prelude::*;
11570        let result: Option<(i32,)> = self
11571            .conn
11572            .borrow_mut()
11573            .exec_first(
11574                "SELECT 1 FROM information_schema.tables WHERE table_name = ? LIMIT 1",
11575                (table_name,),
11576            )
11577            .map_err(|e| IoError::Sql(format!("MySQL table_exists failed: {e}")))?;
11578        Ok(result.is_some())
11579    }
11580
11581    fn insert_rows(&self, insert_sql: &str, rows: &[Vec<Scalar>]) -> Result<(), IoError> {
11582        use mysql::prelude::*;
11583        let mut conn = self.conn.borrow_mut();
11584        for row in rows {
11585            let params: Vec<mysql::Value> = row.iter().map(scalar_to_mysql_value).collect();
11586            conn.exec_drop(insert_sql, params)
11587                .map_err(|e| IoError::Sql(format!("MySQL insert failed: {e}")))?;
11588        }
11589        Ok(())
11590    }
11591
11592    fn dtype_sql(&self, dtype: DType) -> &'static str {
11593        match dtype {
11594            DType::Bool | DType::BoolNullable => "TINYINT(1)",
11595            DType::Int64 | DType::Int64Nullable => "BIGINT",
11596            DType::Float64 => "DOUBLE",
11597            DType::Utf8 => "TEXT",
11598            DType::Datetime64 => "DATETIME",
11599            DType::Timedelta64 => "TIME",
11600            _ => "TEXT",
11601        }
11602    }
11603
11604    fn index_dtype_sql(&self, index: &Index) -> &'static str {
11605        mysql_sql_dtype_from_index(index)
11606    }
11607
11608    fn dialect_name(&self) -> &'static str {
11609        "mysql"
11610    }
11611
11612    fn parameter_marker(&self, _ordinal: usize) -> String {
11613        "?".to_owned()
11614    }
11615
11616    fn supports_returning(&self) -> bool {
11617        false
11618    }
11619
11620    fn max_param_count(&self) -> Option<usize> {
11621        Some(65535)
11622    }
11623
11624    fn max_identifier_length(&self) -> Option<usize> {
11625        Some(64)
11626    }
11627
11628    fn quote_identifier(&self, ident: &str) -> Result<String, IoError> {
11629        if ident.contains('\0') {
11630            return Err(IoError::Sql("invalid identifier: NUL byte".to_owned()));
11631        }
11632        Ok(format!("`{}`", ident.replace('`', "``")))
11633    }
11634
11635    fn list_tables(&self, _schema: Option<&str>) -> Result<Vec<String>, IoError> {
11636        use mysql::prelude::*;
11637        let rows: Vec<(String,)> = self
11638            .conn
11639            .borrow_mut()
11640            .query("SHOW TABLES")
11641            .map_err(|e| IoError::Sql(format!("MySQL list_tables failed: {e}")))?;
11642        Ok(rows.into_iter().map(|(name,)| name).collect())
11643    }
11644}
11645
11646#[cfg(feature = "sql-mysql")]
11647fn mysql_sql_dtype_from_index(index: &Index) -> &'static str {
11648    for label in index.labels() {
11649        match label {
11650            IndexLabel::Int64(_) => return "BIGINT",
11651            IndexLabel::Utf8(_) => return "VARCHAR(255)",
11652            IndexLabel::Timedelta64(v) if *v != Timedelta::NAT => return "TIME",
11653            IndexLabel::Datetime64(v) if *v != i64::MIN => return "DATETIME",
11654            _ => {}
11655        }
11656    }
11657    "VARCHAR(255)"
11658}
11659
11660#[cfg(feature = "sql-mysql")]
11661fn scalar_to_mysql_value(s: &Scalar) -> mysql::Value {
11662    match s {
11663        Scalar::Null(_) => mysql::Value::NULL,
11664        Scalar::Bool(b) => mysql::Value::from(*b),
11665        Scalar::Int64(i) => mysql::Value::from(*i),
11666        Scalar::Float64(f) => mysql::Value::from(*f),
11667        Scalar::Utf8(s) => mysql::Value::from(s.as_str()),
11668        _ => mysql::Value::NULL,
11669    }
11670}
11671
11672#[cfg(feature = "sql-mysql")]
11673fn mysql_value_to_scalar(v: Option<mysql::Value>) -> Scalar {
11674    match v {
11675        None | Some(mysql::Value::NULL) => Scalar::Null(crate::NullKind::Null),
11676        Some(mysql::Value::Bytes(b)) => Scalar::Utf8(String::from_utf8_lossy(&b).into_owned()),
11677        Some(mysql::Value::Int(i)) => Scalar::Int64(i),
11678        Some(mysql::Value::UInt(u)) => Scalar::Int64(u as i64),
11679        Some(mysql::Value::Float(f)) => Scalar::Float64(f as f64),
11680        Some(mysql::Value::Double(d)) => Scalar::Float64(d),
11681        _ => Scalar::Null(crate::NullKind::Null),
11682    }
11683}
11684
11685#[cfg(test)]
11686fn sql_create_table_query<C: SqlConnection>(
11687    conn: &C,
11688    table_name: &str,
11689    column_defs: &[String],
11690) -> Result<String, IoError> {
11691    sql_create_table_query_in_schema(conn, table_name, None, column_defs)
11692}
11693
11694/// Build a `CREATE TABLE IF NOT EXISTS ...` statement, optionally
11695/// schema-qualified.
11696///
11697/// Per br-frankenpandas-udn6 (fd90.15). When `schema` is `Some(s)` AND
11698/// `conn.supports_schemas()`, the target becomes `"schema"."table"`. On
11699/// backends that report false, any `Some(s)` is silently ignored.
11700fn sql_create_table_query_in_schema<C: SqlConnection>(
11701    conn: &C,
11702    table_name: &str,
11703    schema: Option<&str>,
11704    column_defs: &[String],
11705) -> Result<String, IoError> {
11706    validate_sql_table_name(table_name)?;
11707    validate_sql_table_ref_identifier_lengths(conn, table_name, schema)?;
11708    let qualified = match schema {
11709        Some(s) if conn.supports_schemas() => {
11710            validate_sql_schema_name(s)?;
11711            format!(
11712                "{}.{}",
11713                conn.quote_identifier(s)?,
11714                conn.quote_identifier(table_name)?
11715            )
11716        }
11717        _ => conn.quote_identifier(table_name)?,
11718    };
11719    Ok(format!(
11720        "CREATE TABLE IF NOT EXISTS {qualified} ({})",
11721        column_defs.join(", ")
11722    ))
11723}
11724
11725#[cfg(test)]
11726fn sql_insert_rows_query<C: SqlConnection>(
11727    conn: &C,
11728    table_name: &str,
11729    column_names: &[String],
11730) -> Result<String, IoError> {
11731    sql_insert_rows_query_in_schema(conn, table_name, None, column_names)
11732}
11733
11734/// Build an `INSERT INTO ... VALUES (...)` statement, optionally
11735/// schema-qualified.
11736///
11737/// Per br-frankenpandas-udn6 (fd90.15). Same schema rules as the CREATE
11738/// TABLE counterpart.
11739fn sql_insert_rows_query_in_schema<C: SqlConnection>(
11740    conn: &C,
11741    table_name: &str,
11742    schema: Option<&str>,
11743    column_names: &[String],
11744) -> Result<String, IoError> {
11745    validate_sql_table_name(table_name)?;
11746    validate_sql_table_ref_identifier_lengths(conn, table_name, schema)?;
11747    validate_sql_column_identifier_lengths(conn, column_names.iter())?;
11748    let qualified = match schema {
11749        Some(s) if conn.supports_schemas() => {
11750            validate_sql_schema_name(s)?;
11751            format!(
11752                "{}.{}",
11753                conn.quote_identifier(s)?,
11754                conn.quote_identifier(table_name)?
11755            )
11756        }
11757        _ => conn.quote_identifier(table_name)?,
11758    };
11759    let quoted_columns = column_names
11760        .iter()
11761        .map(|name| conn.quote_identifier(name))
11762        .collect::<Result<Vec<_>, _>>()?
11763        .join(", ");
11764    let placeholders = (1..=column_names.len())
11765        .map(|ordinal| conn.parameter_marker(ordinal))
11766        .collect::<Vec<_>>()
11767        .join(", ");
11768    Ok(format!(
11769        "INSERT INTO {qualified} ({quoted_columns}) VALUES ({placeholders})"
11770    ))
11771}
11772
11773/// Build a multi-row `INSERT INTO ... VALUES (...), (...), ...`
11774/// statement, optionally schema-qualified.
11775///
11776/// Placeholder ordinals span 1..=`num_rows` * `column_names.len()` so
11777/// PostgreSQL-style `$N` markers stay unique across the whole statement.
11778/// SQLite's `?N` and the bare `?` default also work because positional
11779/// binding consumes ordinals in left-to-right order.
11780///
11781/// Per br-frankenpandas-i0ml (fd90.19).
11782fn sql_multi_row_insert_query_in_schema<C: SqlConnection>(
11783    conn: &C,
11784    table_name: &str,
11785    schema: Option<&str>,
11786    column_names: &[String],
11787    num_rows: usize,
11788) -> Result<String, IoError> {
11789    validate_sql_table_name(table_name)?;
11790    if num_rows == 0 || column_names.is_empty() {
11791        return Err(IoError::Sql(
11792            "multi-row insert requires at least one row and one column".to_owned(),
11793        ));
11794    }
11795    validate_sql_table_ref_identifier_lengths(conn, table_name, schema)?;
11796    validate_sql_column_identifier_lengths(conn, column_names.iter())?;
11797    let qualified = match schema {
11798        Some(s) if conn.supports_schemas() => {
11799            validate_sql_schema_name(s)?;
11800            format!(
11801                "{}.{}",
11802                conn.quote_identifier(s)?,
11803                conn.quote_identifier(table_name)?
11804            )
11805        }
11806        _ => conn.quote_identifier(table_name)?,
11807    };
11808    let quoted_columns = column_names
11809        .iter()
11810        .map(|name| conn.quote_identifier(name))
11811        .collect::<Result<Vec<_>, _>>()?
11812        .join(", ");
11813    let cols = column_names.len();
11814    let mut tuples = Vec::with_capacity(num_rows);
11815    let mut next_ord = 1usize;
11816    for _ in 0..num_rows {
11817        let row_placeholders = (0..cols)
11818            .map(|_| {
11819                let marker = conn.parameter_marker(next_ord);
11820                next_ord += 1;
11821                marker
11822            })
11823            .collect::<Vec<_>>()
11824            .join(", ");
11825        tuples.push(format!("({row_placeholders})"));
11826    }
11827    Ok(format!(
11828        "INSERT INTO {qualified} ({quoted_columns}) VALUES {}",
11829        tuples.join(", ")
11830    ))
11831}
11832
11833/// Build a `DROP TABLE IF EXISTS ...` statement, optionally
11834/// schema-qualified.
11835///
11836/// Per br-frankenpandas-hxob (fd90.16). Companion to
11837/// `sql_create_table_query_in_schema`. Same schema rules: when
11838/// `schema` is `Some(s)` AND `conn.supports_schemas()`, the target
11839/// becomes `\"schema\".\"table\"`; otherwise the bare table name is
11840/// used. Routes through `conn.quote_identifier` so backend dialect
11841/// overrides (MySQL backticks etc.) take effect on the drop path.
11842fn sql_drop_table_query_in_schema<C: SqlConnection>(
11843    conn: &C,
11844    table_name: &str,
11845    schema: Option<&str>,
11846) -> Result<String, IoError> {
11847    validate_sql_table_name(table_name)?;
11848    validate_sql_table_ref_identifier_lengths(conn, table_name, schema)?;
11849    let qualified = match schema {
11850        Some(s) if conn.supports_schemas() => {
11851            validate_sql_schema_name(s)?;
11852            format!(
11853                "{}.{}",
11854                conn.quote_identifier(s)?,
11855                conn.quote_identifier(table_name)?
11856            )
11857        }
11858        _ => conn.quote_identifier(table_name)?,
11859    };
11860    Ok(format!("DROP TABLE IF EXISTS {qualified}"))
11861}
11862
11863/// Read the result of a SQL query into a DataFrame.
11864///
11865/// Matches `pd.read_sql(sql, con)`.
11866pub fn read_sql<C: SqlConnection>(conn: &C, query: &str) -> Result<DataFrame, IoError> {
11867    read_sql_with_options(conn, query, &SqlReadOptions::default())
11868}
11869
11870/// Read the result of a SQL query into a DataFrame with read-time options.
11871///
11872/// Matches the supported subset of `pd.read_sql(sql, con, params=[...], parse_dates=...)`.
11873pub fn read_sql_with_options<C: SqlConnection>(
11874    conn: &C,
11875    query: &str,
11876    options: &SqlReadOptions,
11877) -> Result<DataFrame, IoError> {
11878    // Per br-frankenpandas-t1777: query readers take a raw SELECT written
11879    // by the caller, so options.columns has no effect. Silently ignoring
11880    // diverged from the table-reader sibling. Reject to surface the
11881    // mismatch — callers should embed the column list in the SELECT, or
11882    // use read_sql_table_with_options to generate the projection.
11883    if options.columns.is_some() {
11884        return Err(IoError::Sql(
11885            "options.columns is meaningful only for table readers; embed the column list in \
11886             the SELECT or use read_sql_table_with_options to generate the projection from a \
11887             table name"
11888                .to_owned(),
11889        ));
11890    }
11891    let (headers, columns, dtype_hints) = sql_query_to_columns(conn, query, options)?;
11892    let frame = dataframe_from_sql_columns(headers, columns, dtype_hints)?;
11893    apply_sql_index_col(frame, options.index_col.as_deref())
11894}
11895
11896/// Per br-frankenpandas-c1h9 (fd90.36): promote `options.index_col`
11897/// to the DataFrame index when set, with empty-string rejection.
11898fn apply_sql_index_col(frame: DataFrame, index_col: Option<&str>) -> Result<DataFrame, IoError> {
11899    let Some(name) = index_col else {
11900        return Ok(frame);
11901    };
11902    if name.is_empty() {
11903        return Err(IoError::Sql(
11904            "index_col: empty string is not a valid column name".to_owned(),
11905        ));
11906    }
11907    promote_column_to_index(&frame, name)
11908}
11909
11910/// Read the result of a SQL query into a DataFrame.
11911///
11912/// Matches `pd.read_sql_query(sql, con)`. This is the query-only spelling of
11913/// `read_sql`; table-name dispatch stays on `read_sql_table`.
11914pub fn read_sql_query<C: SqlConnection>(conn: &C, query: &str) -> Result<DataFrame, IoError> {
11915    read_sql(conn, query)
11916}
11917
11918/// Read the result of a SQL query into a DataFrame with read-time options.
11919///
11920/// Matches the supported subset of
11921/// `pd.read_sql_query(sql, con, params=[...], parse_dates=..., coerce_float=...)`.
11922pub fn read_sql_query_with_options<C: SqlConnection>(
11923    conn: &C,
11924    query: &str,
11925    options: &SqlReadOptions,
11926) -> Result<DataFrame, IoError> {
11927    read_sql_with_options(conn, query, options)
11928}
11929
11930/// Read a SQL query result with read-time options and optional index promotion.
11931///
11932/// Matches the supported subset of
11933/// `pd.read_sql_query(sql, con, params=[...], parse_dates=..., coerce_float=..., index_col=...)`.
11934pub fn read_sql_query_with_options_and_index_col<C: SqlConnection>(
11935    conn: &C,
11936    query: &str,
11937    options: &SqlReadOptions,
11938    index_col: Option<&str>,
11939) -> Result<DataFrame, IoError> {
11940    if let Some(col_name) = index_col {
11941        let cleared = SqlReadOptions {
11942            index_col: None,
11943            ..options.clone()
11944        };
11945        let frame = read_sql_query_with_options(conn, query, &cleared)?;
11946        return apply_sql_index_col(frame, Some(col_name));
11947    }
11948    read_sql_query_with_options(conn, query, options)
11949}
11950
11951/// Read the result of a SQL query as an iterator of DataFrame chunks.
11952///
11953/// Matches the supported subset of `pd.read_sql_query(sql, con, chunksize=...)`.
11954pub fn read_sql_query_chunks<'conn, C: SqlConnection + 'conn>(
11955    conn: &'conn C,
11956    query: &str,
11957    chunk_size: usize,
11958) -> Result<SqlChunkIterator<'conn>, IoError> {
11959    read_sql_chunks(conn, query, chunk_size)
11960}
11961
11962/// Read a SQL query result as chunks with one column promoted to each chunk's index.
11963///
11964/// Matches the supported subset of
11965/// `pd.read_sql_query(sql, con, index_col=..., chunksize=...)`.
11966pub fn read_sql_query_chunks_with_index_col<'conn, C: SqlConnection + 'conn>(
11967    conn: &'conn C,
11968    query: &str,
11969    index_col: Option<&str>,
11970    chunk_size: usize,
11971) -> Result<SqlIndexedChunkIterator<'conn>, IoError> {
11972    read_sql_chunks_with_index_col(conn, query, index_col, chunk_size)
11973}
11974
11975/// Read the result of a SQL query as chunks with read-time options.
11976///
11977/// Matches the supported subset of
11978/// `pd.read_sql_query(sql, con, params=[...], parse_dates=..., coerce_float=..., chunksize=...)`.
11979pub fn read_sql_query_chunks_with_options<'conn, C: SqlConnection + 'conn>(
11980    conn: &'conn C,
11981    query: &str,
11982    options: &SqlReadOptions,
11983    chunk_size: usize,
11984) -> Result<SqlChunkIterator<'conn>, IoError> {
11985    if options.index_col.is_some() {
11986        return Err(IoError::Sql(
11987            "options.index_col is set but this entrypoint returns SqlChunkIterator without \
11988             index promotion; use read_sql_query_chunks_with_options_and_index_col to honor \
11989             index_col"
11990                .to_owned(),
11991        ));
11992    }
11993    read_sql_chunks_with_options(conn, query, options, chunk_size)
11994}
11995
11996/// Read a SQL query result as chunks with read-time options and index promotion.
11997///
11998/// Matches the supported subset of
11999/// `pd.read_sql_query(sql, con, params=[...], parse_dates=..., coerce_float=..., index_col=..., chunksize=...)`.
12000pub fn read_sql_query_chunks_with_options_and_index_col<'conn, C: SqlConnection + 'conn>(
12001    conn: &'conn C,
12002    query: &str,
12003    options: &SqlReadOptions,
12004    index_col: Option<&str>,
12005    chunk_size: usize,
12006) -> Result<SqlIndexedChunkIterator<'conn>, IoError> {
12007    read_sql_chunks_with_options_and_index_col(conn, query, options, index_col, chunk_size)
12008}
12009
12010/// Read a SQL query result with one column promoted to the index.
12011///
12012/// Matches `pd.read_sql_query(sql, con, index_col=...)`.
12013pub fn read_sql_query_with_index_col<C: SqlConnection>(
12014    conn: &C,
12015    query: &str,
12016    index_col: Option<&str>,
12017) -> Result<DataFrame, IoError> {
12018    read_sql_with_index_col(conn, query, index_col)
12019}
12020
12021fn sql_trim_chunk_source(query: &str) -> Result<&str, IoError> {
12022    let trimmed = query.trim().trim_end_matches(';').trim();
12023    if trimmed.is_empty() {
12024        Err(IoError::Sql("read_sql query must be non-empty".to_owned()))
12025    } else {
12026        Ok(trimmed)
12027    }
12028}
12029
12030fn sql_paged_query<C: SqlConnection + ?Sized>(
12031    conn: &C,
12032    query: &str,
12033    base_param_count: usize,
12034) -> Result<String, IoError> {
12035    let source = sql_trim_chunk_source(query)?;
12036    let limit_marker = conn.parameter_marker(base_param_count + 1);
12037    let offset_marker = conn.parameter_marker(base_param_count + 2);
12038    Ok(format!(
12039        "SELECT * FROM ({source}) AS frankenpandas_sql_chunk_source \
12040         LIMIT {limit_marker} OFFSET {offset_marker}"
12041    ))
12042}
12043
12044fn sql_paged_options(
12045    options: &SqlReadOptions,
12046    limit: usize,
12047    offset: usize,
12048) -> Result<SqlReadOptions, IoError> {
12049    let limit = i64::try_from(limit)
12050        .map_err(|_| IoError::Sql("read_sql chunksize exceeds i64 range".to_owned()))?;
12051    let offset = i64::try_from(offset)
12052        .map_err(|_| IoError::Sql("read_sql chunk offset exceeds i64 range".to_owned()))?;
12053    let mut params = options.params.clone().unwrap_or_default();
12054    params.push(Scalar::Int64(limit));
12055    params.push(Scalar::Int64(offset));
12056    Ok(SqlReadOptions {
12057        params: Some(params),
12058        ..options.clone()
12059    })
12060}
12061
12062fn sql_paged_query_headers<C: SqlConnection + ?Sized>(
12063    conn: &C,
12064    query: &str,
12065    options: &SqlReadOptions,
12066) -> Result<Vec<String>, IoError> {
12067    let base_param_count = options.params.as_ref().map_or(0, Vec::len);
12068    let paged_query = sql_paged_query(conn, query, base_param_count)?;
12069    let paged_options = sql_paged_options(options, 0, 0)?;
12070    let result = conn.query(&paged_query, paged_options.params.as_deref().unwrap_or(&[]))?;
12071    reject_duplicate_headers(&result.columns)?;
12072    Ok(result.columns)
12073}
12074
12075fn sql_query_to_columns_paged<C: SqlConnection + ?Sized>(
12076    conn: &C,
12077    query: &str,
12078    options: &SqlReadOptions,
12079    chunk_size: usize,
12080    offset: usize,
12081) -> Result<SqlMaterializedColumns, IoError> {
12082    let base_param_count = options.params.as_ref().map_or(0, Vec::len);
12083    let paged_query = sql_paged_query(conn, query, base_param_count)?;
12084    let paged_options = sql_paged_options(options, chunk_size, offset)?;
12085    sql_query_to_columns(conn, &paged_query, &paged_options)
12086}
12087
12088fn sql_query_to_columns<C: SqlConnection + ?Sized>(
12089    conn: &C,
12090    query: &str,
12091    options: &SqlReadOptions,
12092) -> Result<SqlMaterializedColumns, IoError> {
12093    let params = options.params.as_deref().unwrap_or(&[]);
12094    let SqlQueryResult {
12095        columns: headers,
12096        rows,
12097    } = conn.query(query, params)?;
12098    reject_duplicate_headers(&headers)?;
12099    let mut dtype_hints = conn.query_column_dtypes(query, params)?;
12100    dtype_hints.resize(headers.len(), None);
12101    let mut columns: Vec<Vec<Scalar>> = (0..headers.len()).map(|_| Vec::new()).collect();
12102
12103    for row in rows {
12104        for (col_idx, value) in row.into_iter().enumerate() {
12105            if let Some(col_vec) = columns.get_mut(col_idx) {
12106                col_vec.push(value);
12107            }
12108        }
12109    }
12110
12111    if let Some(ref parse_dates) = options.parse_dates {
12112        apply_parse_dates_to_scalar_columns(&headers, &mut columns, parse_dates)?;
12113    }
12114    if options.coerce_float {
12115        apply_sql_coerce_float(&mut columns);
12116    }
12117    if let Some(ref dtype_map) = options.dtype {
12118        apply_sql_dtype_overrides(
12119            &headers,
12120            &mut columns,
12121            dtype_map,
12122            options.parse_dates.as_deref().unwrap_or(&[]),
12123        )?;
12124        for (idx, header) in headers.iter().enumerate() {
12125            if let Some(dtype) = dtype_map.get(header)
12126                && !options
12127                    .parse_dates
12128                    .as_deref()
12129                    .unwrap_or(&[])
12130                    .iter()
12131                    .any(|d| d == header)
12132            {
12133                dtype_hints[idx] = Some(*dtype);
12134            }
12135        }
12136    }
12137
12138    Ok((headers, columns, dtype_hints))
12139}
12140
12141/// Apply pandas-style `dtype={'col': dtype}` overrides to materialized
12142/// SQL result columns. Skips columns also listed in `parse_dates` to
12143/// avoid double-cast errors. Per br-frankenpandas-l9pt (fd90.11).
12144fn apply_sql_dtype_overrides(
12145    headers: &[String],
12146    columns: &mut [Vec<Scalar>],
12147    dtype_map: &BTreeMap<String, DType>,
12148    parse_dates: &[String],
12149) -> Result<(), IoError> {
12150    for (idx, header) in headers.iter().enumerate() {
12151        let Some(target_dtype) = dtype_map.get(header) else {
12152            continue;
12153        };
12154        if parse_dates.iter().any(|d| d == header) {
12155            // parse_dates wins; skip dtype override for this column.
12156            continue;
12157        }
12158        let Some(col) = columns.get_mut(idx) else {
12159            continue;
12160        };
12161        for value in col.iter_mut() {
12162            // Take ownership of the scalar, cast, and write back. NaT/Null
12163            // pass through cast_scalar_owned unchanged so missingness is
12164            // preserved across the override.
12165            let taken = std::mem::replace(value, Scalar::Null(NullKind::Null));
12166            *value = cast_scalar_owned(taken, *target_dtype).map_err(|e| {
12167                IoError::Sql(format!(
12168                    "dtype override on column '{header}' to {target_dtype:?} failed: {e}"
12169                ))
12170            })?;
12171        }
12172    }
12173    Ok(())
12174}
12175
12176fn dataframe_from_sql_columns(
12177    headers: Vec<String>,
12178    columns: Vec<Vec<Scalar>>,
12179    dtype_hints: SqlColumnDtypeHints,
12180) -> Result<DataFrame, IoError> {
12181    let row_count = columns.first().map_or(0, Vec::len);
12182    let mut out_columns = BTreeMap::new();
12183    let mut column_order = Vec::new();
12184
12185    for (idx, (name, values)) in headers.into_iter().zip(columns).enumerate() {
12186        let dtype_hint = dtype_hints.get(idx).copied().flatten();
12187        let has_observed_value = values.iter().any(|value| !matches!(value, Scalar::Null(_)));
12188        let column = match (has_observed_value, dtype_hint) {
12189            (false, Some(dtype)) => Column::new(dtype, values)?,
12190            _ => Column::from_values(values)?,
12191        };
12192        out_columns.insert(name.clone(), column);
12193        column_order.push(name);
12194    }
12195
12196    let index = Index::from_i64((0..row_count as i64).collect());
12197    Ok(DataFrame::new_with_column_order(
12198        index,
12199        out_columns,
12200        column_order,
12201    )?)
12202}
12203
12204/// Read a SQL query result as an iterator of DataFrame chunks.
12205///
12206/// Matches the supported subset of `pd.read_sql(sql, con, chunksize=...)`.
12207/// Each chunk receives a fresh zero-based RangeIndex, matching pandas'
12208/// SQLite chunk iterator behavior.
12209pub fn read_sql_chunks<'conn, C: SqlConnection + 'conn>(
12210    conn: &'conn C,
12211    query: &str,
12212    chunk_size: usize,
12213) -> Result<SqlChunkIterator<'conn>, IoError> {
12214    read_sql_chunks_with_options(conn, query, &SqlReadOptions::default(), chunk_size)
12215}
12216
12217/// Read a SQL query result as DataFrame chunks with read-time options.
12218///
12219/// Backends that opt into `supports_paged_sql_chunks` are queried one bounded
12220/// page at a time through a `LIMIT`/`OFFSET` wrapper so the iterator does not
12221/// hold the full result set in memory. Other backends keep the legacy
12222/// materialized fallback until they provide a native chunk strategy. `params`,
12223/// `parse_dates`, `coerce_float`, and `dtype` are applied to each yielded page.
12224pub fn read_sql_chunks_with_options<'conn, C: SqlConnection + 'conn>(
12225    conn: &'conn C,
12226    query: &str,
12227    options: &SqlReadOptions,
12228    chunk_size: usize,
12229) -> Result<SqlChunkIterator<'conn>, IoError> {
12230    if chunk_size == 0 {
12231        return Err(IoError::Sql(
12232            "read_sql chunksize must be greater than zero".to_owned(),
12233        ));
12234    }
12235    // Per br-frankenpandas-i8kja: this entrypoint returns SqlChunkIterator
12236    // with no index promotion. Honoring options.index_col would silently
12237    // diverge from the full-frame read_sql_with_options sibling (which
12238    // does promote). Reject to surface the mismatch — callers should use
12239    // read_sql_chunks_with_options_and_index_col when index_col is set.
12240    if options.index_col.is_some() {
12241        return Err(IoError::Sql(
12242            "options.index_col is set but this entrypoint returns SqlChunkIterator without \
12243             index promotion; use read_sql_chunks_with_options_and_index_col to honor index_col"
12244                .to_owned(),
12245        ));
12246    }
12247    // Per br-frankenpandas-t1777: query readers take a raw SELECT written
12248    // by the caller, so options.columns has no effect (the projection is
12249    // already in the query string). Silently ignoring would diverge from
12250    // the table-reader sibling (which honors columns to build the SELECT).
12251    // Reject to surface the mismatch — callers should embed the column
12252    // list in the SELECT, or use read_sql_table_chunks_with_options when
12253    // generating the SELECT from a table name.
12254    if options.columns.is_some() {
12255        return Err(IoError::Sql(
12256            "options.columns is meaningful only for table readers; embed the column list in \
12257             the SELECT or use read_sql_table_chunks_with_options to generate the projection \
12258             from a table name"
12259                .to_owned(),
12260        ));
12261    }
12262
12263    if conn.supports_paged_sql_chunks() {
12264        return SqlChunkIterator::paged(conn, query, options, chunk_size);
12265    }
12266
12267    let (headers, columns, dtype_hints) = sql_query_to_columns(conn, query, options)?;
12268    Ok(SqlChunkIterator::materialized(
12269        headers,
12270        columns,
12271        dtype_hints,
12272        chunk_size,
12273    ))
12274}
12275
12276/// Read a SQL query result as DataFrame chunks with read-time options and optional index promotion.
12277///
12278/// `params`, `parse_dates`, `coerce_float`, and `dtype` are applied to each
12279/// yielded page before optional index promotion.
12280pub fn read_sql_chunks_with_options_and_index_col<'conn, C: SqlConnection + 'conn>(
12281    conn: &'conn C,
12282    query: &str,
12283    options: &SqlReadOptions,
12284    index_col: Option<&str>,
12285    chunk_size: usize,
12286) -> Result<SqlIndexedChunkIterator<'conn>, IoError> {
12287    // Per br-frankenpandas-t1777: query readers can't apply options.columns
12288    // (caller writes the SELECT). Reject for consistency with the plain
12289    // chunk reader's rejection — the indexed sibling shouldn't be a
12290    // backdoor.
12291    if options.columns.is_some() {
12292        return Err(IoError::Sql(
12293            "options.columns is meaningful only for table readers; embed the column list in \
12294             the SELECT or use read_sql_table_chunks_with_options_and_index_col to generate \
12295             the projection from a table name"
12296                .to_owned(),
12297        ));
12298    }
12299    // The plain chunk reader rejects options.index_col (see i8kja); clear
12300    // it before delegating so the indexed sibling is the canonical
12301    // honor-index_col entrypoint regardless of which slot the caller used.
12302    let cleared = SqlReadOptions {
12303        index_col: None,
12304        ..options.clone()
12305    };
12306    let inner = read_sql_chunks_with_options(conn, query, &cleared, chunk_size)?;
12307    sql_indexed_chunks(inner, index_col.or(options.index_col.as_deref()))
12308}
12309
12310/// Read a SQL query result as DataFrame chunks with optional index promotion.
12311///
12312/// Matches the supported subset of `pd.read_sql(sql, con, index_col=..., chunksize=...)`.
12313pub fn read_sql_chunks_with_index_col<'conn, C: SqlConnection + 'conn>(
12314    conn: &'conn C,
12315    query: &str,
12316    index_col: Option<&str>,
12317    chunk_size: usize,
12318) -> Result<SqlIndexedChunkIterator<'conn>, IoError> {
12319    let inner = read_sql_chunks(conn, query, chunk_size)?;
12320    sql_indexed_chunks(inner, index_col)
12321}
12322
12323/// Read a SQL query result with one column promoted to the index.
12324///
12325/// Matches `pd.read_sql(sql, con, index_col=...)`. When
12326/// `index_col=Some(name)` the named column is removed from the data
12327/// columns and its values become the DataFrame's row index. Returns
12328/// `IoError::Sql` if the named column is absent from the result set.
12329pub fn read_sql_with_index_col<C: SqlConnection>(
12330    conn: &C,
12331    query: &str,
12332    index_col: Option<&str>,
12333) -> Result<DataFrame, IoError> {
12334    let frame = read_sql(conn, query)?;
12335    apply_sql_index_col(frame, index_col)
12336}
12337
12338/// Read an entire SQL table with one column promoted to the index.
12339///
12340/// Matches `pd.read_sql_table(table, con, index_col=...)`.
12341pub fn read_sql_table_with_index_col<C: SqlConnection>(
12342    conn: &C,
12343    table_name: &str,
12344    index_col: Option<&str>,
12345) -> Result<DataFrame, IoError> {
12346    let frame = read_sql_table(conn, table_name)?;
12347    apply_sql_index_col(frame, index_col)
12348}
12349
12350fn promote_column_to_index(frame: &DataFrame, col_name: &str) -> Result<DataFrame, IoError> {
12351    let column = frame.column(col_name).ok_or_else(|| {
12352        IoError::Sql(format!(
12353            "index_col {col_name:?} not present in result columns"
12354        ))
12355    })?;
12356    let labels: Vec<IndexLabel> = column
12357        .values()
12358        .iter()
12359        .map(|v| match v {
12360            Scalar::Int64(i) => IndexLabel::Int64(*i),
12361            Scalar::Utf8(s) => IndexLabel::Utf8(s.clone()),
12362            Scalar::Float64(f) if !f.is_nan() => IndexLabel::Utf8(f.to_string()),
12363            Scalar::Bool(b) => IndexLabel::Utf8(if *b { "True" } else { "False" }.to_string()),
12364            Scalar::Timedelta64(ns) => IndexLabel::Timedelta64(*ns),
12365            // A parse_dates column promoted to index becomes a DatetimeIndex
12366            // (typed Datetime64[ns], br-frankenpandas-0ezw7) — not a "NaN" string.
12367            Scalar::Datetime64(ns) => IndexLabel::Datetime64(*ns),
12368            _ => IndexLabel::Utf8("NaN".to_owned()),
12369        })
12370        .collect();
12371    let new_index = Index::new(labels).set_name(col_name);
12372
12373    let mut new_columns = std::collections::BTreeMap::new();
12374    let mut new_order = Vec::new();
12375    for name in frame.column_names() {
12376        if name == col_name {
12377            continue;
12378        }
12379        if let Some(col) = frame.column(name) {
12380            new_columns.insert(name.clone(), col.clone());
12381            new_order.push(name.clone());
12382        }
12383    }
12384
12385    Ok(DataFrame::new_with_column_order(
12386        new_index,
12387        new_columns,
12388        new_order,
12389    )?)
12390}
12391
12392/// Read an entire SQL table into a DataFrame.
12393///
12394/// Matches `pd.read_sql_table(table_name, con)`.
12395pub fn read_sql_table<C: SqlConnection>(conn: &C, table_name: &str) -> Result<DataFrame, IoError> {
12396    read_sql(conn, &sql_select_all_query(conn, table_name)?)
12397}
12398
12399/// List user-visible table names known to the SQL backend.
12400///
12401/// Matches the supported subset of
12402/// `pd.io.sql.SQLDatabase.list_tables(schema=...)`. When the backend
12403/// reports `supports_schemas() == false` (SQLite), `schema` is ignored
12404/// and all tables in the single namespace are returned. When the
12405/// backend supports schemas (PostgreSQL, MySQL, MSSQL), `Some(s)`
12406/// scopes the listing. `None` passes through to the backend
12407/// unchanged — backends MAY consult `default_schema()` for their own
12408/// fallback logic if desired (per fd90.57: this wrapper does NOT
12409/// apply the fallback automatically).
12410///
12411/// Per br-frankenpandas-vhq2 (fd90.20).
12412pub fn list_sql_tables<C: SqlConnection>(
12413    conn: &C,
12414    schema: Option<&str>,
12415) -> Result<Vec<String>, IoError> {
12416    conn.list_tables(schema)
12417}
12418
12419/// Introspect a SQL table's column metadata, optionally schema-scoped.
12420///
12421/// Matches the supported subset of
12422/// `pd.io.sql.SQLDatabase.has_table` + `SQLAlchemy.MetaData.reflect`
12423/// for column-level details. Returns `Ok(None)` when the table does
12424/// not exist. Schema arg is silently ignored when the backend reports
12425/// `supports_schemas() == false` (SQLite).
12426///
12427/// Per br-frankenpandas-w43q (fd90.21).
12428pub fn sql_table_schema<C: SqlConnection>(
12429    conn: &C,
12430    table_name: &str,
12431    schema: Option<&str>,
12432) -> Result<Option<SqlTableSchema>, IoError> {
12433    conn.table_schema(table_name, schema)
12434}
12435
12436/// List user-visible schemas exposed by the SQL backend.
12437///
12438/// Matches `SQLAlchemy.Inspector.get_schema_names()` shape. Single
12439/// namespace backends (SQLite) return an empty vector. Multi-schema
12440/// backends return the schemas the connection's role can see, with
12441/// internal/system schemas filtered out.
12442///
12443/// Per br-frankenpandas-lxhi (fd90.22).
12444pub fn list_sql_schemas<C: SqlConnection>(conn: &C) -> Result<Vec<String>, IoError> {
12445    conn.list_schemas()
12446}
12447
12448/// Reset a SQL table to empty without dropping its definition.
12449///
12450/// On backends that override the default (PostgreSQL, MySQL), this
12451/// uses `TRUNCATE TABLE` for a DDL-style fast-path reset. On backends
12452/// that inherit the default (SQLite), this emits `DELETE FROM <table>`,
12453/// which is universal but slower on large tables. Schema arg is
12454/// silently ignored when `supports_schemas() == false`.
12455///
12456/// Per br-frankenpandas-phum (fd90.23).
12457pub fn truncate_sql_table<C: SqlConnection>(
12458    conn: &C,
12459    table_name: &str,
12460    schema: Option<&str>,
12461) -> Result<(), IoError> {
12462    conn.truncate_table(table_name, schema)
12463}
12464
12465/// Probe the SQL backend's server version string.
12466///
12467/// Returns `Ok(None)` for backends that can't (or don't) introspect
12468/// their version. SQLite returns `Some("3.x.y")`. PostgreSQL/MySQL
12469/// impls return their respective `SHOW server_version` /
12470/// `SELECT VERSION()` payloads. Useful for dialect-version gating
12471/// (RETURNING, JSON ops, generated columns) and diagnostics.
12472///
12473/// Per br-frankenpandas-e23k (fd90.24).
12474pub fn sql_server_version<C: SqlConnection>(conn: &C) -> Result<Option<String>, IoError> {
12475    conn.server_version()
12476}
12477
12478/// Return the primary-key column names for a SQL table, ordered by
12479/// the table's primary-key ordinal.
12480///
12481/// Returns an empty vector when the table doesn't exist, has no
12482/// primary key, or the backend can't introspect column metadata.
12483/// Useful for upsert conflict-target generation and `index_label`
12484/// defaulting.
12485///
12486/// Per br-frankenpandas-uw3y (fd90.25).
12487pub fn sql_primary_key_columns<C: SqlConnection>(
12488    conn: &C,
12489    table_name: &str,
12490    schema: Option<&str>,
12491) -> Result<Vec<String>, IoError> {
12492    conn.primary_key_columns(table_name, schema)
12493}
12494
12495/// List user-defined indexes on a SQL table, optionally schema-scoped.
12496///
12497/// Matches `SQLAlchemy.Inspector.get_indexes()` shape. Returns an
12498/// empty vector when the table doesn't exist, has no user-created
12499/// indexes, or the backend can't introspect. Auto-created PRIMARY-KEY
12500/// indexes are filtered out (they're surfaced via primary_key_columns
12501/// instead).
12502///
12503/// Per br-frankenpandas-bgv9 (fd90.28).
12504pub fn list_sql_indexes<C: SqlConnection>(
12505    conn: &C,
12506    table_name: &str,
12507    schema: Option<&str>,
12508) -> Result<Vec<SqlIndexSchema>, IoError> {
12509    conn.list_indexes(table_name, schema)
12510}
12511
12512/// List user-visible view names known to the SQL backend.
12513///
12514/// Matches `SQLAlchemy.Inspector.get_view_names()` shape. Companion
12515/// to `list_sql_tables` — pandas/SQLAlchemy keep tables and views in
12516/// distinct buckets so `pd.read_sql_table` can distinguish them.
12517/// Schema arg is silently ignored when `supports_schemas() == false`.
12518///
12519/// Per br-frankenpandas-gm3r (fd90.30).
12520pub fn list_sql_views<C: SqlConnection>(
12521    conn: &C,
12522    schema: Option<&str>,
12523) -> Result<Vec<String>, IoError> {
12524    conn.list_views(schema)
12525}
12526
12527/// List foreign-key constraints declared on a SQL table, optionally
12528/// schema-scoped.
12529///
12530/// Matches `SQLAlchemy.Inspector.get_foreign_keys()` shape. Returns
12531/// an empty vector when the table has no FKs or the backend can't
12532/// introspect. Composite FKs are returned as a single entry with
12533/// paired `columns` / `referenced_columns` ordered by declaration
12534/// position. SQLite does not expose constraint names via PRAGMA, so
12535/// `constraint_name` is `None` there.
12536///
12537/// Per br-frankenpandas-uht8 (fd90.29).
12538pub fn list_sql_foreign_keys<C: SqlConnection>(
12539    conn: &C,
12540    table_name: &str,
12541    schema: Option<&str>,
12542) -> Result<Vec<SqlForeignKeySchema>, IoError> {
12543    conn.list_foreign_keys(table_name, schema)
12544}
12545
12546/// Probe the table-level comment for a SQL table, optionally
12547/// schema-scoped.
12548///
12549/// Matches `SQLAlchemy.Inspector.get_table_comment()` shape — returns
12550/// `Ok(Some(text))` when a comment exists, `Ok(None)` otherwise.
12551/// SQLite has no native table-comment storage and returns `None`.
12552/// PostgreSQL/MySQL/MSSQL impls override with their respective
12553/// catalog queries.
12554///
12555/// Per br-frankenpandas-yu3w (fd90.32).
12556pub fn sql_table_comment<C: SqlConnection>(
12557    conn: &C,
12558    table_name: &str,
12559    schema: Option<&str>,
12560) -> Result<Option<String>, IoError> {
12561    conn.table_comment(table_name, schema)
12562}
12563
12564/// List UNIQUE constraints declared on a SQL table.
12565///
12566/// Matches `SQLAlchemy.Inspector.get_unique_constraints()` shape.
12567/// Surfaces only inline `UNIQUE` declarations and `UNIQUE (...)`
12568/// table constraints. User-created `CREATE UNIQUE INDEX` indexes
12569/// remain in `list_sql_indexes` (with `unique == true`). The two
12570/// listings are intentionally disjoint to match SQLAlchemy.
12571///
12572/// Per br-frankenpandas-sh4v (fd90.31).
12573pub fn list_sql_unique_constraints<C: SqlConnection>(
12574    conn: &C,
12575    table_name: &str,
12576    schema: Option<&str>,
12577) -> Result<Vec<SqlUniqueConstraintSchema>, IoError> {
12578    conn.list_unique_constraints(table_name, schema)
12579}
12580
12581/// Maximum identifier length supported by the SQL backend, or `None`
12582/// when no documented limit exists.
12583///
12584/// Useful for to_sql validation: backends that override this report
12585/// their cap (PostgreSQL=63, MySQL=64, MSSQL=128) so auto-generated
12586/// index / constraint / column names can be truncated or rejected
12587/// before round-tripping through DDL that would silently truncate.
12588///
12589/// Per br-frankenpandas-cs81 (fd90.26).
12590pub fn sql_max_identifier_length<C: SqlConnection>(conn: &C) -> Option<usize> {
12591    conn.max_identifier_length()
12592}
12593
12594/// Backend capability summary exposed through `SqlInspector`.
12595///
12596/// The per-field values come from `SqlConnection` probes so concrete
12597/// backends can report their native ceilings without forcing callers to
12598/// branch on the connection type.
12599#[derive(Debug, Clone, PartialEq, Eq)]
12600pub struct SqlBackendCaps {
12601    pub dialect_name: &'static str,
12602    pub server_version: Option<String>,
12603    pub supports_returning: bool,
12604    pub supports_schemas: bool,
12605    pub max_param_count: Option<usize>,
12606    pub max_identifier_length: Option<usize>,
12607}
12608
12609impl SqlBackendCaps {
12610    /// Maximum rows in one parameter-bound INSERT for `column_count`.
12611    ///
12612    /// Returns `None` when the backend has no known parameter ceiling, or
12613    /// when `column_count` is zero and therefore no parameter-derived row
12614    /// ceiling can be computed.
12615    #[must_use]
12616    pub fn max_insert_rows(&self, column_count: usize) -> Option<usize> {
12617        sql_max_insert_rows_for_columns(self.max_param_count, column_count)
12618    }
12619}
12620
12621/// Maximum bound parameters supported by the SQL backend, if known.
12622#[must_use]
12623pub fn sql_max_param_count<C: SqlConnection>(conn: &C) -> Option<usize> {
12624    conn.max_param_count()
12625}
12626
12627/// Whether the SQL backend supports native `INSERT ... RETURNING`.
12628#[must_use]
12629pub fn sql_supports_returning<C: SqlConnection>(conn: &C) -> bool {
12630    conn.supports_returning()
12631}
12632
12633/// Whether the SQL backend exposes schema-qualified namespaces.
12634#[must_use]
12635pub fn sql_supports_schemas<C: SqlConnection>(conn: &C) -> bool {
12636    conn.supports_schemas()
12637}
12638
12639/// Maximum INSERT rows for `column_count`, derived from the backend's
12640/// bound-parameter ceiling.
12641///
12642/// A return value of `Some(0)` means the requested column count exceeds
12643/// the backend's total bind-parameter cap.
12644#[must_use]
12645pub fn sql_max_insert_rows<C: SqlConnection>(conn: &C, column_count: usize) -> Option<usize> {
12646    sql_max_insert_rows_for_columns(conn.max_param_count(), column_count)
12647}
12648
12649fn sql_max_insert_rows_for_columns(
12650    max_param_count: Option<usize>,
12651    column_count: usize,
12652) -> Option<usize> {
12653    if column_count == 0 {
12654        return None;
12655    }
12656    max_param_count.map(|max| max / column_count)
12657}
12658
12659/// Gather the backend capability probes into one typed bundle.
12660pub fn sql_backend_caps<C: SqlConnection>(conn: &C) -> Result<SqlBackendCaps, IoError> {
12661    Ok(SqlBackendCaps {
12662        dialect_name: conn.dialect_name(),
12663        server_version: conn.server_version()?,
12664        supports_returning: conn.supports_returning(),
12665        supports_schemas: conn.supports_schemas(),
12666        max_param_count: conn.max_param_count(),
12667        max_identifier_length: conn.max_identifier_length(),
12668    })
12669}
12670
12671/// Backend-agnostic introspection facade matching the
12672/// `SQLAlchemy.Inspector` shape.
12673///
12674/// Per br-frankenpandas-szs9 (fd90.38). Wraps a `&C: SqlConnection`
12675/// and exposes the full fd90.20-37 introspection surface as methods
12676/// on a single bundle so callers don't have to remember which
12677/// `list_sql_*` / `sql_*` free-fn to use. Pure delegation — no new
12678/// behavior, just API ergonomics.
12679///
12680/// ```rust,ignore
12681/// use frankenpandas::SqlInspector;
12682/// let inspector = SqlInspector::new(&conn);
12683/// for table in inspector.tables(None)? {
12684///     for col in inspector.columns(&table, None)?
12685///         .map(|s| s.columns)
12686///         .unwrap_or_default()
12687///     {
12688///         println!("{}: {:?}", col.name, col.declared_type);
12689///     }
12690/// }
12691/// ```
12692#[derive(Debug)]
12693pub struct SqlInspector<'a, C: SqlConnection> {
12694    conn: &'a C,
12695}
12696
12697impl<'a, C: SqlConnection> SqlInspector<'a, C> {
12698    /// Create a new inspector bound to the given connection.
12699    #[must_use]
12700    pub fn new(conn: &'a C) -> Self {
12701        Self { conn }
12702    }
12703
12704    /// List user-visible table names. See `list_sql_tables`.
12705    pub fn tables(&self, schema: Option<&str>) -> Result<Vec<String>, IoError> {
12706        self.conn.list_tables(schema)
12707    }
12708
12709    /// List user-visible view names. See `list_sql_views`.
12710    pub fn views(&self, schema: Option<&str>) -> Result<Vec<String>, IoError> {
12711        self.conn.list_views(schema)
12712    }
12713
12714    /// List user-visible schemas. See `list_sql_schemas`.
12715    pub fn schemas(&self) -> Result<Vec<String>, IoError> {
12716        self.conn.list_schemas()
12717    }
12718
12719    /// Introspect a table's columns. See `sql_table_schema`.
12720    pub fn columns(
12721        &self,
12722        table_name: &str,
12723        schema: Option<&str>,
12724    ) -> Result<Option<SqlTableSchema>, IoError> {
12725        self.conn.table_schema(table_name, schema)
12726    }
12727
12728    /// List user-defined indexes. See `list_sql_indexes`.
12729    pub fn indexes(
12730        &self,
12731        table_name: &str,
12732        schema: Option<&str>,
12733    ) -> Result<Vec<SqlIndexSchema>, IoError> {
12734        self.conn.list_indexes(table_name, schema)
12735    }
12736
12737    /// List foreign-key constraints. See `list_sql_foreign_keys`.
12738    pub fn foreign_keys(
12739        &self,
12740        table_name: &str,
12741        schema: Option<&str>,
12742    ) -> Result<Vec<SqlForeignKeySchema>, IoError> {
12743        self.conn.list_foreign_keys(table_name, schema)
12744    }
12745
12746    /// List UNIQUE constraints. See `list_sql_unique_constraints`.
12747    pub fn unique_constraints(
12748        &self,
12749        table_name: &str,
12750        schema: Option<&str>,
12751    ) -> Result<Vec<SqlUniqueConstraintSchema>, IoError> {
12752        self.conn.list_unique_constraints(table_name, schema)
12753    }
12754
12755    /// Return primary-key columns sorted by ordinal.
12756    /// See `sql_primary_key_columns`.
12757    pub fn primary_key_columns(
12758        &self,
12759        table_name: &str,
12760        schema: Option<&str>,
12761    ) -> Result<Vec<String>, IoError> {
12762        self.conn.primary_key_columns(table_name, schema)
12763    }
12764
12765    /// Probe the table-level comment. See `sql_table_comment`.
12766    pub fn table_comment(
12767        &self,
12768        table_name: &str,
12769        schema: Option<&str>,
12770    ) -> Result<Option<String>, IoError> {
12771        self.conn.table_comment(table_name, schema)
12772    }
12773
12774    /// Schema-aware existence check. Routes to
12775    /// `SqlConnection::table_exists_in_schema`.
12776    pub fn table_exists(&self, table_name: &str, schema: Option<&str>) -> Result<bool, IoError> {
12777        self.conn.table_exists_in_schema(table_name, schema)
12778    }
12779
12780    /// Probe the backend server version. See `sql_server_version`.
12781    pub fn server_version(&self) -> Result<Option<String>, IoError> {
12782        self.conn.server_version()
12783    }
12784
12785    /// Maximum identifier length, when the backend exposes one.
12786    /// See `sql_max_identifier_length`.
12787    #[must_use]
12788    pub fn max_identifier_length(&self) -> Option<usize> {
12789        self.conn.max_identifier_length()
12790    }
12791
12792    /// Maximum bound parameters supported by this backend, if known.
12793    #[must_use]
12794    pub fn max_param_count(&self) -> Option<usize> {
12795        self.conn.max_param_count()
12796    }
12797
12798    /// Maximum INSERT rows for `column_count`, derived from the backend's
12799    /// bound-parameter ceiling.
12800    #[must_use]
12801    pub fn max_insert_rows(&self, column_count: usize) -> Option<usize> {
12802        sql_max_insert_rows_for_columns(self.conn.max_param_count(), column_count)
12803    }
12804
12805    /// Whether this backend supports native `INSERT ... RETURNING`.
12806    #[must_use]
12807    pub fn supports_returning(&self) -> bool {
12808        self.conn.supports_returning()
12809    }
12810
12811    /// Whether this backend exposes schema-qualified namespaces.
12812    #[must_use]
12813    pub fn supports_schemas(&self) -> bool {
12814        self.conn.supports_schemas()
12815    }
12816
12817    /// Gather backend capability probes into one typed bundle.
12818    pub fn backend_caps(&self) -> Result<SqlBackendCaps, IoError> {
12819        sql_backend_caps(self.conn)
12820    }
12821
12822    /// Backend dialect name (`"sqlite"`, `"postgresql"`, etc.).
12823    #[must_use]
12824    pub fn dialect_name(&self) -> &'static str {
12825        self.conn.dialect_name()
12826    }
12827
12828    /// Check whether a specific column exists on a table.
12829    ///
12830    /// Per br-frankenpandas-ppry (fd90.39). Returns `Ok(false)` when
12831    /// the table doesn't exist (i.e. `columns` returns `None`), or
12832    /// when the table exists but has no column matching `column_name`.
12833    /// Returns `Ok(true)` only when the named column is present.
12834    /// Mirrors `SQLAlchemy.Inspector.has_column()` semantics.
12835    pub fn has_column(
12836        &self,
12837        table_name: &str,
12838        column_name: &str,
12839        schema: Option<&str>,
12840    ) -> Result<bool, IoError> {
12841        let Some(meta) = self.conn.table_schema(table_name, schema)? else {
12842            return Ok(false);
12843        };
12844        Ok(meta.column(column_name).is_some())
12845    }
12846
12847    /// Look up the metadata bundle for a single column.
12848    ///
12849    /// Per br-frankenpandas-ppry (fd90.39). Returns `Ok(None)` when the
12850    /// table doesn't exist or the column isn't present. The returned
12851    /// `SqlColumnSchema` carries the full set of fields populated by
12852    /// the underlying `table_schema` impl (declared_type, nullable,
12853    /// default_value, primary_key_ordinal, comment, autoincrement).
12854    pub fn column(
12855        &self,
12856        table_name: &str,
12857        column_name: &str,
12858        schema: Option<&str>,
12859    ) -> Result<Option<SqlColumnSchema>, IoError> {
12860        let Some(meta) = self.conn.table_schema(table_name, schema)? else {
12861            return Ok(None);
12862        };
12863        Ok(meta.column(column_name).cloned())
12864    }
12865
12866    /// Reflect a full table's metadata in one call: columns, primary
12867    /// key, indexes, foreign keys, unique constraints, and comment.
12868    ///
12869    /// Per br-frankenpandas-76mw (fd90.40). Mirrors
12870    /// `SQLAlchemy.MetaData.reflect_table` shape — gives callers a
12871    /// single bundle instead of 5 separate fetches. Returns `Ok(None)`
12872    /// when the table doesn't exist (matched via `table_schema`
12873    /// returning `None`); otherwise all derived calls run and any
12874    /// missing pieces (e.g. SQLite's always-None `table_comment`)
12875    /// are simply preserved as their natural empty values.
12876    ///
12877    /// Per br-frankenpandas-2kzv (fd90.43): primary-key columns are
12878    /// derived directly from the `SqlTableSchema` we already fetched
12879    /// rather than dispatching `primary_key_columns()` again — that
12880    /// trait method's default impl calls `table_schema()` internally,
12881    /// which would double the round-trip count for backends where
12882    /// each call is a real network hop.
12883    pub fn reflect_table(
12884        &self,
12885        table_name: &str,
12886        schema: Option<&str>,
12887    ) -> Result<Option<SqlReflectedTable>, IoError> {
12888        let Some(meta) = self.conn.table_schema(table_name, schema)? else {
12889            return Ok(None);
12890        };
12891        let primary_key_columns = primary_keys_from_schema(&meta);
12892        let indexes = self.conn.list_indexes(table_name, schema)?;
12893        let foreign_keys = self.conn.list_foreign_keys(table_name, schema)?;
12894        let unique_constraints = self.conn.list_unique_constraints(table_name, schema)?;
12895        let comment = self.conn.table_comment(table_name, schema)?;
12896        Ok(Some(SqlReflectedTable {
12897            table_name: meta.table_name,
12898            columns: meta.columns,
12899            primary_key_columns,
12900            indexes,
12901            foreign_keys,
12902            unique_constraints,
12903            comment,
12904        }))
12905    }
12906
12907    /// Reflect every user-visible table in `schema` into a vector of
12908    /// bundles, one per table.
12909    ///
12910    /// Per br-frankenpandas-jmmo (fd90.53). Iterates `tables(schema)`
12911    /// then calls `reflect_table` on each. Skips any table that
12912    /// `reflect_table` returns `Ok(None)` for — covers the race
12913    /// condition where a table existed at list time but not at
12914    /// reflect time (e.g. concurrent DROP). Useful for whole-database
12915    /// introspection in one call.
12916    pub fn reflect_all_tables(
12917        &self,
12918        schema: Option<&str>,
12919    ) -> Result<Vec<SqlReflectedTable>, IoError> {
12920        let table_names = self.conn.list_tables(schema)?;
12921        let mut bundles = Vec::with_capacity(table_names.len());
12922        for name in table_names {
12923            if let Some(bundle) = self.reflect_table(&name, schema)? {
12924                bundles.push(bundle);
12925            }
12926        }
12927        Ok(bundles)
12928    }
12929
12930    /// Reflect every user-visible view in `schema` into a vector of
12931    /// bundles, one per view.
12932    ///
12933    /// Per br-frankenpandas-zuqt (fd90.54). View-side parity with
12934    /// `reflect_all_tables`: iterates `views(schema)` then calls
12935    /// `reflect_table` on each (PRAGMA table_info works on views too,
12936    /// returning the view's column shape). PK/FK/UC/index lists in
12937    /// the bundle will typically be empty for views since views don't
12938    /// carry constraints — only the column metadata + comment are
12939    /// meaningful. Same disappearing-entity skip semantics as
12940    /// `reflect_all_tables`.
12941    pub fn reflect_all_views(
12942        &self,
12943        schema: Option<&str>,
12944    ) -> Result<Vec<SqlReflectedTable>, IoError> {
12945        let view_names = self.conn.list_views(schema)?;
12946        let mut bundles = Vec::with_capacity(view_names.len());
12947        for name in view_names {
12948            if let Some(bundle) = self.reflect_table(&name, schema)? {
12949                bundles.push(bundle);
12950            }
12951        }
12952        Ok(bundles)
12953    }
12954}
12955
12956/// Derive the primary-key column names from an already-fetched
12957/// `SqlTableSchema`, sorted ascending by `primary_key_ordinal`.
12958///
12959/// Per br-frankenpandas-2kzv (fd90.43) / fd90.47: this is the
12960/// canonical filter+sort impl shared by both
12961/// `SqlConnection::primary_key_columns` (the trait default) and
12962/// `SqlInspector::reflect_table` (which uses already-fetched
12963/// metadata to avoid a redundant `table_schema()` round-trip).
12964fn primary_keys_from_schema(meta: &SqlTableSchema) -> Vec<String> {
12965    let mut pk: Vec<(usize, String)> = meta
12966        .columns
12967        .iter()
12968        .filter_map(|c| c.primary_key_ordinal.map(|ord| (ord, c.name.clone())))
12969        .collect();
12970    pk.sort_by_key(|(ord, _)| *ord);
12971    pk.into_iter().map(|(_, name)| name).collect()
12972}
12973
12974/// Convenience constructor for `SqlInspector`.
12975///
12976/// `let inspector = inspect(&conn);` reads more naturally than
12977/// `SqlInspector::new(&conn)` for one-shot uses. Per br-frankenpandas-szs9 (fd90.38).
12978#[must_use]
12979pub fn inspect<C: SqlConnection>(conn: &C) -> SqlInspector<'_, C> {
12980    SqlInspector::new(conn)
12981}
12982
12983/// Read an entire SQL table into a DataFrame with read-time options.
12984///
12985/// Matches the supported subset of
12986/// `pd.read_sql_table(table_name, con, parse_dates=..., coerce_float=...)`.
12987pub fn read_sql_table_with_options<C: SqlConnection>(
12988    conn: &C,
12989    table_name: &str,
12990    options: &SqlReadOptions,
12991) -> Result<DataFrame, IoError> {
12992    let query =
12993        sql_table_read_query_for_options(conn, table_name, options, options.index_col.as_deref())?;
12994    // Per br-frankenpandas-t1777: the query reader rejects options.columns
12995    // (the SELECT is already projected here). Clear before delegating so
12996    // the table reader stays the canonical honor-columns entrypoint
12997    // regardless of which slot the caller used.
12998    let cleared = SqlReadOptions {
12999        columns: None,
13000        ..options.clone()
13001    };
13002    read_sql_with_options(conn, &query, &cleared)
13003}
13004
13005fn sql_table_read_query_for_options<C: SqlConnection>(
13006    conn: &C,
13007    table_name: &str,
13008    options: &SqlReadOptions,
13009    required_projection_col: Option<&str>,
13010) -> Result<String, IoError> {
13011    // Per br-frankenpandas-d3e9 (fd90.34): when options.columns is
13012    // Some(list), project only those columns instead of SELECT *.
13013    // Per br-frankenpandas-fd90.76: if an index_col will be promoted
13014    // after materialization, include it in the generated projection even
13015    // when the user did not list it in columns. pandas SQLTable.read does
13016    // this before set_index so columns=[...] and index_col=... compose.
13017    match options.columns.as_deref() {
13018        Some(cols) => {
13019            let mut refs: Vec<&str> = Vec::with_capacity(cols.len() + 1);
13020            if let Some(index_col) = required_projection_col
13021                && !cols.iter().any(|name| name == index_col)
13022            {
13023                refs.push(index_col);
13024            }
13025            refs.extend(cols.iter().map(String::as_str));
13026            sql_select_columns_query_in_schema(conn, table_name, options.schema.as_deref(), &refs)
13027        }
13028        None => sql_select_all_query_in_schema(conn, table_name, options.schema.as_deref()),
13029    }
13030}
13031
13032/// Read an entire SQL table with read-time options and optional index promotion.
13033///
13034/// Matches the supported subset of
13035/// `pd.read_sql_table(table_name, con, parse_dates=..., coerce_float=..., index_col=...)`.
13036pub fn read_sql_table_with_options_and_index_col<C: SqlConnection>(
13037    conn: &C,
13038    table_name: &str,
13039    options: &SqlReadOptions,
13040    index_col: Option<&str>,
13041) -> Result<DataFrame, IoError> {
13042    // Per br-frankenpandas-c1h9 (fd90.36): explicit `index_col` arg
13043    // always wins over `options.index_col`. Avoid double-promotion by
13044    // clearing the option-struct copy when the explicit arg is set.
13045    if let Some(col_name) = index_col {
13046        // Build the SELECT projection from the ORIGINAL options (so
13047        // options.columns is honored when present). Per br-frankenpandas-t1777,
13048        // also strip options.columns before passing to the query reader
13049        // (which now rejects the field; the SELECT already projects the
13050        // columns we wanted).
13051        let query = sql_table_read_query_for_options(conn, table_name, options, Some(col_name))?;
13052        let cleared = SqlReadOptions {
13053            index_col: None,
13054            columns: None,
13055            ..options.clone()
13056        };
13057        let frame = read_sql_with_options(conn, &query, &cleared)?;
13058        return apply_sql_index_col(frame, Some(col_name));
13059    }
13060    read_sql_table_with_options(conn, table_name, options)
13061}
13062
13063/// Read an entire SQL table as an iterator of DataFrame chunks.
13064///
13065/// Matches the supported subset of `pd.read_sql_table(table_name, con, chunksize=...)`.
13066pub fn read_sql_table_chunks<'conn, C: SqlConnection + 'conn>(
13067    conn: &'conn C,
13068    table_name: &str,
13069    chunk_size: usize,
13070) -> Result<SqlChunkIterator<'conn>, IoError> {
13071    read_sql_chunks(conn, &sql_select_all_query(conn, table_name)?, chunk_size)
13072}
13073
13074/// Read an entire SQL table as DataFrame chunks with read-time options.
13075///
13076/// Matches the supported subset of
13077/// `pd.read_sql_table(table_name, con, parse_dates=..., coerce_float=..., chunksize=...)`.
13078pub fn read_sql_table_chunks_with_options<'conn, C: SqlConnection + 'conn>(
13079    conn: &'conn C,
13080    table_name: &str,
13081    options: &SqlReadOptions,
13082    chunk_size: usize,
13083) -> Result<SqlChunkIterator<'conn>, IoError> {
13084    // Per br-frankenpandas-i8kja: this entrypoint returns the
13085    // un-indexed SqlChunkIterator. Honoring options.index_col would
13086    // silently diverge from the full-frame read_sql_table_with_options
13087    // sibling (which does promote). Reject to surface the mismatch —
13088    // callers should use read_sql_table_chunks_with_options_and_index_col
13089    // when index_col is set.
13090    if options.index_col.is_some() {
13091        return Err(IoError::Sql(
13092            "options.index_col is set but this entrypoint returns SqlChunkIterator without \
13093             index promotion; use read_sql_table_chunks_with_options_and_index_col to honor \
13094             index_col"
13095                .to_owned(),
13096        ));
13097    }
13098    let query = match options.columns.as_deref() {
13099        Some(cols) => {
13100            let refs: Vec<&str> = cols.iter().map(String::as_str).collect();
13101            sql_select_columns_query_in_schema(conn, table_name, options.schema.as_deref(), &refs)?
13102        }
13103        None => sql_select_all_query_in_schema(conn, table_name, options.schema.as_deref())?,
13104    };
13105    // Per br-frankenpandas-t1777: query reader rejects options.columns
13106    // (the SELECT is already projected here). Clear before delegating.
13107    let cleared = SqlReadOptions {
13108        columns: None,
13109        ..options.clone()
13110    };
13111    read_sql_chunks_with_options(conn, &query, &cleared, chunk_size)
13112}
13113
13114/// Read an entire SQL table as chunks with read-time options and optional index promotion.
13115///
13116/// Matches the supported subset of
13117/// `pd.read_sql_table(table_name, con, parse_dates=..., coerce_float=..., index_col=..., chunksize=...)`.
13118pub fn read_sql_table_chunks_with_options_and_index_col<'conn, C: SqlConnection + 'conn>(
13119    conn: &'conn C,
13120    table_name: &str,
13121    options: &SqlReadOptions,
13122    index_col: Option<&str>,
13123    chunk_size: usize,
13124) -> Result<SqlIndexedChunkIterator<'conn>, IoError> {
13125    let effective_index_col = index_col.or(options.index_col.as_deref());
13126    let query = sql_table_read_query_for_options(conn, table_name, options, effective_index_col)?;
13127    // The plain chunk reader rejects options.index_col (see i8kja) and
13128    // options.columns (see t1777); clear both before delegating so
13129    // chunked-with-options remains a sibling of the full-frame path
13130    // regardless of which slots the caller populated.
13131    let cleared = SqlReadOptions {
13132        index_col: None,
13133        columns: None,
13134        ..options.clone()
13135    };
13136    let inner = read_sql_chunks_with_options(conn, &query, &cleared, chunk_size)?;
13137    sql_indexed_chunks(inner, effective_index_col)
13138}
13139
13140/// Read an entire SQL table as chunks with one column promoted to each chunk's index.
13141///
13142/// Matches the supported subset of
13143/// `pd.read_sql_table(table_name, con, index_col=..., chunksize=...)`.
13144pub fn read_sql_table_chunks_with_index_col<'conn, C: SqlConnection + 'conn>(
13145    conn: &'conn C,
13146    table_name: &str,
13147    index_col: Option<&str>,
13148    chunk_size: usize,
13149) -> Result<SqlIndexedChunkIterator<'conn>, IoError> {
13150    let inner = read_sql_table_chunks(conn, table_name, chunk_size)?;
13151    sql_indexed_chunks(inner, index_col)
13152}
13153
13154/// Read a subset of columns from a SQL table.
13155///
13156/// Matches `pd.read_sql_table(table, con, columns=[...])`. The named
13157/// columns are emitted in the requested order. Each column name must
13158/// satisfy the same alphanumeric+underscore rule as `table_name` to
13159/// keep the projection injection-safe; mismatched names return
13160/// `IoError::Sql`. Empty `columns` is rejected (pandas raises in
13161/// the same case rather than producing an empty SELECT).
13162pub fn read_sql_table_columns<C: SqlConnection>(
13163    conn: &C,
13164    table_name: &str,
13165    columns: &[&str],
13166) -> Result<DataFrame, IoError> {
13167    read_sql(conn, &sql_select_columns_query(conn, table_name, columns)?)
13168}
13169
13170/// Read a subset of columns from a SQL table with optional index promotion.
13171///
13172/// Matches the supported subset of
13173/// `pd.read_sql_table(table, con, columns=[...], index_col=...)`. When
13174/// `index_col` is set and is not already in `columns`, it is auto-projected
13175/// into the underlying SELECT (matching pandas SQLTable.read which does the
13176/// same before set_index). The promoted column is removed from the data
13177/// columns after projection. Per br-frankenpandas-6n0uz.
13178pub fn read_sql_table_columns_with_index_col<C: SqlConnection>(
13179    conn: &C,
13180    table_name: &str,
13181    columns: &[&str],
13182    index_col: Option<&str>,
13183) -> Result<DataFrame, IoError> {
13184    let projection = projection_with_index_col(columns, index_col)?;
13185    let frame = read_sql_table_columns(conn, table_name, &projection)?;
13186    apply_sql_index_col(frame, index_col)
13187}
13188
13189/// Read a subset of columns from a SQL table as DataFrame chunks.
13190///
13191/// Matches the supported subset of
13192/// `pd.read_sql_table(table, con, columns=[...], chunksize=...)`. The named
13193/// columns are emitted in the requested order and each chunk receives a fresh
13194/// zero-based RangeIndex.
13195pub fn read_sql_table_columns_chunks<'conn, C: SqlConnection + 'conn>(
13196    conn: &'conn C,
13197    table_name: &str,
13198    columns: &[&str],
13199    chunk_size: usize,
13200) -> Result<SqlChunkIterator<'conn>, IoError> {
13201    read_sql_chunks(
13202        conn,
13203        &sql_select_columns_query(conn, table_name, columns)?,
13204        chunk_size,
13205    )
13206}
13207
13208/// Read a subset of columns from a SQL table as chunks with optional index promotion.
13209///
13210/// Matches the supported subset of
13211/// `pd.read_sql_table(table, con, columns=[...], index_col=..., chunksize=...)`.
13212/// When `index_col` is set and is not already in `columns`, it is auto-projected
13213/// into the underlying SELECT (matching pandas SQLTable.read). The promoted
13214/// column is removed from each chunk after projection. Per br-frankenpandas-6n0uz.
13215pub fn read_sql_table_columns_chunks_with_index_col<'conn, C: SqlConnection + 'conn>(
13216    conn: &'conn C,
13217    table_name: &str,
13218    columns: &[&str],
13219    index_col: Option<&str>,
13220    chunk_size: usize,
13221) -> Result<SqlIndexedChunkIterator<'conn>, IoError> {
13222    let projection = projection_with_index_col(columns, index_col)?;
13223    let inner = read_sql_table_columns_chunks(conn, table_name, &projection, chunk_size)?;
13224    sql_indexed_chunks(inner, index_col)
13225}
13226
13227/// Per br-frankenpandas-6n0uz: helper that prepends `index_col` to a
13228/// `columns` projection list if it isn't already present. Mirrors the
13229/// inline logic in `sql_table_read_query_for_options` (fd90.76) so the
13230/// columns-list and options-based read paths agree on the auto-include
13231/// rule while preserving the public `index_col=""` and empty-projection
13232/// error contracts.
13233fn projection_with_index_col<'a>(
13234    columns: &'a [&'a str],
13235    index_col: Option<&'a str>,
13236) -> Result<Vec<&'a str>, IoError> {
13237    match index_col {
13238        Some("") => Err(IoError::Sql(
13239            "index_col: empty string is not a valid column name".to_owned(),
13240        )),
13241        Some(name) if !columns.is_empty() && !columns.contains(&name) => {
13242            let mut out = Vec::with_capacity(columns.len() + 1);
13243            out.push(name);
13244            out.extend_from_slice(columns);
13245            Ok(out)
13246        }
13247        _ => Ok(columns.to_vec()),
13248    }
13249}
13250
13251/// Write a DataFrame to a SQL table.
13252///
13253/// Matches `pd.DataFrame.to_sql(name, con)`.
13254pub fn write_sql<C: SqlConnection>(
13255    frame: &DataFrame,
13256    conn: &C,
13257    table_name: &str,
13258    if_exists: SqlIfExists,
13259) -> Result<(), IoError> {
13260    write_sql_with_options(
13261        frame,
13262        conn,
13263        table_name,
13264        &SqlWriteOptions {
13265            if_exists,
13266            index: false,
13267            index_label: None,
13268            schema: None,
13269            dtype: None,
13270            method: SqlInsertMethod::Single,
13271            chunksize: None,
13272        },
13273    )
13274}
13275
13276/// Write a DataFrame to a SQLite table with pandas-style index options.
13277///
13278/// Matches the supported subset of
13279/// `pd.DataFrame.to_sql(name, con, index=..., index_label=...)`.
13280pub fn write_sql_with_options<C: SqlConnection>(
13281    frame: &DataFrame,
13282    conn: &C,
13283    table_name: &str,
13284    options: &SqlWriteOptions,
13285) -> Result<(), IoError> {
13286    // Validate table name to prevent SQL injection (only allow alphanumeric + underscore, non-empty).
13287    if table_name.is_empty() || !table_name.chars().all(|c| c.is_alphanumeric() || c == '_') {
13288        return Err(IoError::Sql(format!(
13289            "invalid table name: '{table_name}' (must be non-empty, only alphanumeric and underscore allowed)"
13290        )));
13291    }
13292
13293    let col_names: Vec<String> = frame.column_names().into_iter().cloned().collect();
13294    let index_label = resolve_sql_index_label(frame, options)?;
13295    let mut sql_col_names =
13296        Vec::with_capacity(col_names.len() + usize::from(index_label.is_some()));
13297    if let Some(ref label) = index_label {
13298        sql_col_names.push(label.clone());
13299    }
13300    sql_col_names.extend(col_names.iter().cloned());
13301
13302    // Per fd90.27: when the backend reports an identifier-length cap
13303    // (PG=63, MySQL=64, MSSQL=128), reject any identifier that exceeds
13304    // it before emitting DDL. SQLite (None) is unaffected.
13305    let max_ident = conn.max_identifier_length();
13306    validate_sql_identifier_length(table_name, max_ident, "table")?;
13307    if let Some(ref label) = index_label {
13308        validate_sql_identifier_length(label, max_ident, "index label")?;
13309    }
13310    for name in &col_names {
13311        validate_sql_identifier_length(name, max_ident, "column")?;
13312    }
13313    if let Some(s) = options.schema.as_deref() {
13314        validate_sql_identifier_length(s, max_ident, "schema")?;
13315    }
13316
13317    // Handle if_exists policy.
13318    let schema = options.schema.as_deref();
13319    match options.if_exists {
13320        SqlIfExists::Fail => {
13321            let exists = conn.table_exists_in_schema(table_name, schema)?;
13322            if exists {
13323                return Err(IoError::Sql(format!("table '{table_name}' already exists")));
13324            }
13325        }
13326        SqlIfExists::Replace => {
13327            let drop_sql = sql_drop_table_query_in_schema(conn, table_name, schema)?;
13328            conn.execute_batch(&drop_sql)?;
13329        }
13330        SqlIfExists::Append => {
13331            // Table may or may not exist; CREATE TABLE IF NOT EXISTS handles both.
13332        }
13333    }
13334
13335    // Build CREATE TABLE statement.
13336    let mut col_defs = Vec::with_capacity(sql_col_names.len());
13337    if let Some(ref label) = index_label {
13338        col_defs.push(sql_column_definition(
13339            conn,
13340            label,
13341            conn.index_dtype_sql(frame.index()),
13342        )?);
13343    }
13344    let dtype_overrides = options.dtype.as_ref();
13345    col_defs.extend(
13346        col_names
13347            .iter()
13348            .map(|name| {
13349                // Per br-frankenpandas-ev2s (fd90.18): explicit per-column
13350                // SQL-type override wins over the inferred conn.dtype_sql.
13351                let override_sql = dtype_overrides
13352                    .and_then(|m| m.get(name))
13353                    .map(|s| s.as_str());
13354                let sql_type = match override_sql {
13355                    Some(s) => s,
13356                    None => {
13357                        let dt = frame.column(name).map_or(DType::Utf8, |c| c.dtype());
13358                        conn.dtype_sql(dt)
13359                    }
13360                };
13361                sql_column_definition(conn, name, sql_type)
13362            })
13363            .collect::<Result<Vec<_>, IoError>>()?,
13364    );
13365
13366    let create_sql = sql_create_table_query_in_schema(conn, table_name, schema, &col_defs)?;
13367    conn.execute_batch(&create_sql)?;
13368
13369    let nrows = frame.index().len();
13370    let ncols = sql_col_names.len();
13371    let mut rows = Vec::with_capacity(nrows);
13372    for row_idx in 0..nrows {
13373        let mut row = Vec::with_capacity(ncols);
13374        if options.index {
13375            row.push(scalar_from_index_label(&frame.index().labels()[row_idx]));
13376        }
13377        row.extend(col_names.iter().map(|name| {
13378            frame
13379                .column(name)
13380                .and_then(|col| col.value(row_idx))
13381                .cloned()
13382                .unwrap_or(Scalar::Null(NullKind::Null))
13383        }));
13384        rows.push(row);
13385    }
13386
13387    if rows.is_empty() {
13388        // Empty frame: still emit CREATE TABLE (already done) but skip INSERT.
13389        return Ok(());
13390    }
13391
13392    // Per fd90.33: pandas-style chunksize. None preserves prior
13393    // single-transaction semantics; Some(0) is rejected (matches pandas).
13394    if let Some(0) = options.chunksize {
13395        return Err(IoError::Sql(
13396            "invalid chunksize: 0 (must be > 0 if Some)".to_owned(),
13397        ));
13398    }
13399
13400    match options.method {
13401        SqlInsertMethod::Single => {
13402            let insert_sql =
13403                sql_insert_rows_query_in_schema(conn, table_name, schema, &sql_col_names)?;
13404            match options.chunksize {
13405                None => {
13406                    conn.insert_rows(&insert_sql, &rows)?;
13407                }
13408                Some(n) => {
13409                    for chunk in rows.chunks(n) {
13410                        conn.insert_rows(&insert_sql, chunk)?;
13411                    }
13412                }
13413            }
13414        }
13415        SqlInsertMethod::Multi => {
13416            // Per fd90.19: chunk rows to fit `max_param_count`. When the
13417            // backend reports None, send the whole frame in one statement.
13418            // Per fd90.33: when chunksize is also Some(n), the effective
13419            // chunk row count is min(n, max_param_count / num_cols).
13420            let param_chunk = match conn.max_param_count() {
13421                Some(max) if ncols > 0 => {
13422                    let per_chunk = max / ncols;
13423                    if per_chunk == 0 {
13424                        return Err(IoError::Sql(format!(
13425                            "multi-row insert: ncols={ncols} exceeds backend max_param_count={max}"
13426                        )));
13427                    }
13428                    per_chunk
13429                }
13430                _ => rows.len(),
13431            };
13432            let chunk_rows = options
13433                .chunksize
13434                .map(|cs| cs.min(param_chunk))
13435                .unwrap_or(param_chunk);
13436            for chunk in rows.chunks(chunk_rows) {
13437                let chunk_sql = sql_multi_row_insert_query_in_schema(
13438                    conn,
13439                    table_name,
13440                    schema,
13441                    &sql_col_names,
13442                    chunk.len(),
13443                )?;
13444                let mut flat = Vec::with_capacity(chunk.len() * ncols);
13445                for row in chunk {
13446                    flat.extend(row.iter().cloned());
13447                }
13448                conn.insert_rows(&chunk_sql, &[flat])?;
13449            }
13450        }
13451    }
13452
13453    Ok(())
13454}
13455
13456// ── Extension trait for DataFrame IO convenience methods ─────────────
13457
13458/// Extension trait that adds IO convenience methods to `DataFrame`.
13459///
13460/// Import this trait to call `df.to_parquet(path)`, `df.to_orc(path)`,
13461/// `df.to_hdf(path)`, `df.to_parquet_bytes()`, etc. directly on DataFrame
13462/// values.
13463pub trait DataFrameIoExt {
13464    /// Write this DataFrame to a Parquet file.
13465    ///
13466    /// Matches `pd.DataFrame.to_parquet(path)`.
13467    fn to_parquet(&self, path: &Path) -> Result<(), IoError>;
13468
13469    /// Serialize this DataFrame to Parquet bytes in memory.
13470    ///
13471    /// Matches `pd.DataFrame.to_parquet()` with no path (returns bytes).
13472    fn to_parquet_bytes(&self) -> Result<Vec<u8>, IoError>;
13473
13474    /// Write this DataFrame to an ORC file.
13475    ///
13476    /// Matches the scoped `DataFrame.to_orc(path)` compatibility surface.
13477    fn to_orc(&self, path: &Path) -> Result<(), IoError>;
13478
13479    /// Write this DataFrame to an ORC file.
13480    ///
13481    /// Explicit file-suffixed form of [`DataFrameIoExt::to_orc`].
13482    fn to_orc_file(&self, path: &Path) -> Result<(), IoError>;
13483
13484    /// Serialize this DataFrame to ORC bytes in memory.
13485    fn to_orc_bytes(&self) -> Result<Vec<u8>, IoError>;
13486
13487    /// Write this DataFrame to an HDF5 file at the default key.
13488    ///
13489    /// Matches the scoped `DataFrame.to_hdf(path)` compatibility surface.
13490    fn to_hdf(&self, path: &Path) -> Result<(), IoError>;
13491
13492    /// Write this DataFrame to an HDF5 file at the default key.
13493    ///
13494    /// Explicit file-suffixed form of [`DataFrameIoExt::to_hdf`].
13495    fn to_hdf_file(&self, path: &Path) -> Result<(), IoError>;
13496
13497    /// Write this DataFrame to an HDF5 file at an explicit key.
13498    fn to_hdf_key(&self, path: &Path, key: &str) -> Result<(), IoError>;
13499
13500    /// Write this DataFrame to an HDF5 file with explicit options.
13501    fn to_hdf_with_options(&self, path: &Path, options: &HdfWriteOptions) -> Result<(), IoError>;
13502
13503    /// Write this DataFrame to a CSV file.
13504    ///
13505    /// Matches `pd.DataFrame.to_csv(path)`.
13506    fn to_csv_file(&self, path: &Path) -> Result<(), IoError>;
13507
13508    /// Serialize this DataFrame to a CSV string.
13509    ///
13510    /// Matches `pd.DataFrame.to_csv()` with no path.
13511    fn to_csv_string(&self) -> Result<String, IoError>;
13512
13513    /// Serialize this DataFrame to a CSV string with explicit write options.
13514    ///
13515    /// Matches `pd.DataFrame.to_csv(sep, na_rep, header, index, index_label)`.
13516    fn to_csv_string_with_options(&self, options: &CsvWriteOptions) -> Result<String, IoError>;
13517
13518    /// Serialize this DataFrame to a Markdown table string.
13519    ///
13520    /// Matches `pd.DataFrame.to_markdown()` with no buffer.
13521    fn to_markdown_string(&self) -> Result<String, IoError>;
13522
13523    /// Serialize this DataFrame to a Markdown table string with explicit options.
13524    fn to_markdown_string_with_options(
13525        &self,
13526        options: &MarkdownWriteOptions,
13527    ) -> Result<String, IoError>;
13528
13529    /// Write this DataFrame to a Markdown table file.
13530    ///
13531    /// Uses a file-suffixed name to avoid colliding with
13532    /// `DataFrame::to_markdown(include_index, tablefmt)`.
13533    fn to_markdown_file(&self, path: &Path) -> Result<(), IoError>;
13534
13535    /// Write this DataFrame to a Markdown table file with explicit options.
13536    fn to_markdown_file_with_options(
13537        &self,
13538        path: &Path,
13539        options: &MarkdownWriteOptions,
13540    ) -> Result<(), IoError>;
13541
13542    /// Serialize this DataFrame to a LaTeX tabular string.
13543    ///
13544    /// Matches `pd.DataFrame.to_latex()` with no buffer.
13545    fn to_latex_string(&self) -> Result<String, IoError>;
13546
13547    /// Serialize this DataFrame to a LaTeX tabular string with explicit options.
13548    fn to_latex_string_with_options(&self, options: &LatexWriteOptions) -> Result<String, IoError>;
13549
13550    /// Write this DataFrame to a LaTeX tabular file.
13551    ///
13552    /// Uses a file-suffixed name to avoid colliding with
13553    /// `DataFrame::to_latex(include_index)`.
13554    fn to_latex_file(&self, path: &Path) -> Result<(), IoError>;
13555
13556    /// Write this DataFrame to a LaTeX tabular file with explicit options.
13557    fn to_latex_file_with_options(
13558        &self,
13559        path: &Path,
13560        options: &LatexWriteOptions,
13561    ) -> Result<(), IoError>;
13562
13563    /// Serialize this DataFrame to an HTML table string.
13564    ///
13565    /// Matches `pd.DataFrame.to_html()` with no buffer.
13566    fn to_html_string(&self) -> Result<String, IoError>;
13567
13568    /// Serialize this DataFrame to an HTML table string with explicit options.
13569    fn to_html_string_with_options(&self, options: &HtmlWriteOptions) -> Result<String, IoError>;
13570
13571    /// Write this DataFrame to an HTML file.
13572    ///
13573    /// Matches `pd.DataFrame.to_html(path)`.
13574    fn to_html_file(&self, path: &Path) -> Result<(), IoError>;
13575
13576    /// Write this DataFrame to an HTML file with explicit options.
13577    fn to_html_file_with_options(
13578        &self,
13579        path: &Path,
13580        options: &HtmlWriteOptions,
13581    ) -> Result<(), IoError>;
13582
13583    /// Serialize this DataFrame to an XML document string.
13584    ///
13585    /// Matches `pd.DataFrame.to_xml()` with no buffer for the writer-only subset.
13586    fn to_xml_string(&self) -> Result<String, IoError>;
13587
13588    /// Serialize this DataFrame to an XML document string with explicit options.
13589    fn to_xml_string_with_options(&self, options: &XmlWriteOptions) -> Result<String, IoError>;
13590
13591    /// Write this DataFrame to an XML file.
13592    ///
13593    /// Matches `pd.DataFrame.to_xml(path)`.
13594    fn to_xml(&self, path: &Path) -> Result<(), IoError>;
13595
13596    /// Write this DataFrame to an XML file.
13597    ///
13598    /// Matches `pd.DataFrame.to_xml(path)`.
13599    fn to_xml_file(&self, path: &Path) -> Result<(), IoError>;
13600
13601    /// Write this DataFrame to an XML file with explicit options.
13602    fn to_xml_file_with_options(
13603        &self,
13604        path: &Path,
13605        options: &XmlWriteOptions,
13606    ) -> Result<(), IoError>;
13607
13608    /// Write this DataFrame to a JSON file.
13609    ///
13610    /// Matches `pd.DataFrame.to_json(path)`.
13611    fn to_json_file(&self, path: &Path, orient: JsonOrient) -> Result<(), IoError>;
13612
13613    /// Serialize this DataFrame to a JSON string.
13614    ///
13615    /// Matches `pd.DataFrame.to_json()` with no path.
13616    fn to_json_string(&self, orient: JsonOrient) -> Result<String, IoError>;
13617
13618    /// Write this DataFrame to a Pickle file.
13619    ///
13620    /// Matches `pd.DataFrame.to_pickle(path)` for the supported envelope.
13621    fn to_pickle(&self, path: &Path) -> Result<(), IoError>;
13622
13623    /// Write this DataFrame to a Pickle file.
13624    ///
13625    /// Explicit file-suffixed form of [`DataFrameIoExt::to_pickle`].
13626    fn to_pickle_file(&self, path: &Path) -> Result<(), IoError>;
13627
13628    /// Write this DataFrame to a Pickle file with explicit options.
13629    fn to_pickle_with_options(
13630        &self,
13631        path: &Path,
13632        options: &PickleWriteOptions,
13633    ) -> Result<(), IoError>;
13634
13635    /// Serialize this DataFrame to Pickle bytes.
13636    fn to_pickle_bytes(&self) -> Result<Vec<u8>, IoError>;
13637
13638    /// Serialize this DataFrame to Pickle bytes with explicit options.
13639    fn to_pickle_bytes_with_options(
13640        &self,
13641        options: &PickleWriteOptions,
13642    ) -> Result<Vec<u8>, IoError>;
13643
13644    /// Write this DataFrame to a Stata DTA file.
13645    ///
13646    /// Matches `pd.DataFrame.to_stata(path)` for the supported subset.
13647    fn to_stata(&self, path: &Path) -> Result<(), IoError>;
13648
13649    /// Write this DataFrame to a Stata DTA file.
13650    ///
13651    /// Explicit file-suffixed form of [`DataFrameIoExt::to_stata`].
13652    fn to_stata_file(&self, path: &Path) -> Result<(), IoError>;
13653
13654    /// Write this DataFrame to a Stata DTA file with explicit options.
13655    fn to_stata_with_options(
13656        &self,
13657        path: &Path,
13658        options: &StataWriteOptions,
13659    ) -> Result<(), IoError>;
13660
13661    /// Serialize this DataFrame to Stata DTA bytes.
13662    fn to_stata_bytes(&self) -> Result<Vec<u8>, IoError>;
13663
13664    /// Serialize this DataFrame to Stata DTA bytes with explicit options.
13665    fn to_stata_bytes_with_options(&self, options: &StataWriteOptions) -> Result<Vec<u8>, IoError>;
13666
13667    /// Write this DataFrame to an Excel (.xlsx) file.
13668    ///
13669    /// Matches `pd.DataFrame.to_excel(path)`.
13670    fn to_excel(&self, path: &Path) -> Result<(), IoError>;
13671
13672    /// Write this DataFrame to an Excel (.xlsx) file.
13673    ///
13674    /// Explicit file-suffixed form of [`DataFrameIoExt::to_excel`].
13675    fn to_excel_file(&self, path: &Path) -> Result<(), IoError>;
13676
13677    /// Write this DataFrame to an Excel (.xlsx) file with explicit write options.
13678    fn to_excel_with_options(
13679        &self,
13680        path: &Path,
13681        options: &ExcelWriteOptions,
13682    ) -> Result<(), IoError>;
13683
13684    /// Serialize this DataFrame to Excel (.xlsx) bytes in memory.
13685    fn to_excel_bytes(&self) -> Result<Vec<u8>, IoError>;
13686
13687    /// Serialize this DataFrame to Excel (.xlsx) bytes with explicit write options.
13688    fn to_excel_bytes_with_options(&self, options: &ExcelWriteOptions) -> Result<Vec<u8>, IoError>;
13689
13690    /// Write this DataFrame to a JSONL file (one JSON object per line).
13691    ///
13692    /// Matches `pd.DataFrame.to_json(path, orient='records', lines=True)`.
13693    fn to_jsonl_file(&self, path: &Path) -> Result<(), IoError>;
13694
13695    /// Serialize this DataFrame to newline-delimited JSON.
13696    ///
13697    /// Matches `pd.DataFrame.to_json(orient='records', lines=True)`.
13698    fn to_jsonl_string(&self) -> Result<String, IoError>;
13699
13700    /// Write this DataFrame to an Arrow IPC (Feather v2) file.
13701    ///
13702    /// Matches `pd.DataFrame.to_feather(path)`.
13703    fn to_feather(&self, path: &Path) -> Result<(), IoError>;
13704
13705    /// Write this DataFrame to an Arrow IPC (Feather v2) file.
13706    ///
13707    /// Explicit file-suffixed form of [`DataFrameIoExt::to_feather`].
13708    fn to_feather_file(&self, path: &Path) -> Result<(), IoError>;
13709
13710    /// Serialize this DataFrame to Arrow IPC (Feather v2) bytes.
13711    fn to_feather_bytes(&self) -> Result<Vec<u8>, IoError>;
13712
13713    /// Write this DataFrame to a SQL table.
13714    ///
13715    /// Matches `pd.DataFrame.to_sql(name, con)`.
13716    fn to_sql<C: SqlConnection>(
13717        &self,
13718        conn: &C,
13719        table_name: &str,
13720        if_exists: SqlIfExists,
13721    ) -> Result<(), IoError>;
13722
13723    /// Write this DataFrame to a SQL table with pandas-style SQL write options.
13724    fn to_sql_with_options<C: SqlConnection>(
13725        &self,
13726        conn: &C,
13727        table_name: &str,
13728        options: &SqlWriteOptions,
13729    ) -> Result<(), IoError>;
13730
13731    /// Clipboard writer (TSV via an OS backend), matching `pd.DataFrame.to_clipboard()`.
13732    fn to_clipboard(&self) -> Result<(), IoError>;
13733
13734    /// Reject-closed BigQuery writer, matching `pd.DataFrame.to_gbq(destination_table, project_id)`.
13735    fn to_gbq(&self, destination_table: &str, project_id: Option<&str>) -> Result<(), IoError>;
13736}
13737
13738impl DataFrameIoExt for DataFrame {
13739    fn to_parquet(&self, path: &Path) -> Result<(), IoError> {
13740        write_parquet(self, path)
13741    }
13742
13743    fn to_parquet_bytes(&self) -> Result<Vec<u8>, IoError> {
13744        write_parquet_bytes(self)
13745    }
13746
13747    fn to_orc(&self, path: &Path) -> Result<(), IoError> {
13748        write_orc(self, path)
13749    }
13750
13751    fn to_orc_file(&self, path: &Path) -> Result<(), IoError> {
13752        self.to_orc(path)
13753    }
13754
13755    fn to_orc_bytes(&self) -> Result<Vec<u8>, IoError> {
13756        write_orc_bytes(self)
13757    }
13758
13759    fn to_hdf(&self, path: &Path) -> Result<(), IoError> {
13760        write_hdf(self, path)
13761    }
13762
13763    fn to_hdf_file(&self, path: &Path) -> Result<(), IoError> {
13764        self.to_hdf(path)
13765    }
13766
13767    fn to_hdf_key(&self, path: &Path, key: &str) -> Result<(), IoError> {
13768        write_hdf_key(self, path, key)
13769    }
13770
13771    fn to_hdf_with_options(&self, path: &Path, options: &HdfWriteOptions) -> Result<(), IoError> {
13772        write_hdf_with_options(self, path, options)
13773    }
13774
13775    fn to_csv_file(&self, path: &Path) -> Result<(), IoError> {
13776        write_csv(self, path)
13777    }
13778
13779    fn to_csv_string(&self) -> Result<String, IoError> {
13780        write_csv_string(self)
13781    }
13782
13783    fn to_csv_string_with_options(&self, options: &CsvWriteOptions) -> Result<String, IoError> {
13784        write_csv_string_with_options(self, options)
13785    }
13786
13787    fn to_markdown_string(&self) -> Result<String, IoError> {
13788        write_markdown_string(self)
13789    }
13790
13791    fn to_markdown_string_with_options(
13792        &self,
13793        options: &MarkdownWriteOptions,
13794    ) -> Result<String, IoError> {
13795        write_markdown_string_with_options(self, options)
13796    }
13797
13798    fn to_markdown_file(&self, path: &Path) -> Result<(), IoError> {
13799        write_markdown(self, path)
13800    }
13801
13802    fn to_markdown_file_with_options(
13803        &self,
13804        path: &Path,
13805        options: &MarkdownWriteOptions,
13806    ) -> Result<(), IoError> {
13807        write_markdown_with_options(self, path, options)
13808    }
13809
13810    fn to_latex_string(&self) -> Result<String, IoError> {
13811        write_latex_string(self)
13812    }
13813
13814    fn to_latex_string_with_options(&self, options: &LatexWriteOptions) -> Result<String, IoError> {
13815        write_latex_string_with_options(self, options)
13816    }
13817
13818    fn to_latex_file(&self, path: &Path) -> Result<(), IoError> {
13819        write_latex(self, path)
13820    }
13821
13822    fn to_latex_file_with_options(
13823        &self,
13824        path: &Path,
13825        options: &LatexWriteOptions,
13826    ) -> Result<(), IoError> {
13827        write_latex_with_options(self, path, options)
13828    }
13829
13830    fn to_html_string(&self) -> Result<String, IoError> {
13831        write_html_string(self)
13832    }
13833
13834    fn to_html_string_with_options(&self, options: &HtmlWriteOptions) -> Result<String, IoError> {
13835        write_html_string_with_options(self, options)
13836    }
13837
13838    fn to_html_file(&self, path: &Path) -> Result<(), IoError> {
13839        write_html(self, path)
13840    }
13841
13842    fn to_html_file_with_options(
13843        &self,
13844        path: &Path,
13845        options: &HtmlWriteOptions,
13846    ) -> Result<(), IoError> {
13847        write_html_with_options(self, path, options)
13848    }
13849
13850    fn to_xml_string(&self) -> Result<String, IoError> {
13851        write_xml_string(self)
13852    }
13853
13854    fn to_xml_string_with_options(&self, options: &XmlWriteOptions) -> Result<String, IoError> {
13855        write_xml_string_with_options(self, options)
13856    }
13857
13858    fn to_xml(&self, path: &Path) -> Result<(), IoError> {
13859        write_xml(self, path)
13860    }
13861
13862    fn to_xml_file(&self, path: &Path) -> Result<(), IoError> {
13863        self.to_xml(path)
13864    }
13865
13866    fn to_xml_file_with_options(
13867        &self,
13868        path: &Path,
13869        options: &XmlWriteOptions,
13870    ) -> Result<(), IoError> {
13871        write_xml_with_options(self, path, options)
13872    }
13873
13874    fn to_json_file(&self, path: &Path, orient: JsonOrient) -> Result<(), IoError> {
13875        write_json(self, path, orient)
13876    }
13877
13878    fn to_json_string(&self, orient: JsonOrient) -> Result<String, IoError> {
13879        write_json_string(self, orient)
13880    }
13881
13882    fn to_pickle(&self, path: &Path) -> Result<(), IoError> {
13883        write_pickle(self, path)
13884    }
13885
13886    fn to_pickle_file(&self, path: &Path) -> Result<(), IoError> {
13887        self.to_pickle(path)
13888    }
13889
13890    fn to_pickle_with_options(
13891        &self,
13892        path: &Path,
13893        options: &PickleWriteOptions,
13894    ) -> Result<(), IoError> {
13895        write_pickle_with_options(self, path, options)
13896    }
13897
13898    fn to_pickle_bytes(&self) -> Result<Vec<u8>, IoError> {
13899        write_pickle_bytes(self)
13900    }
13901
13902    fn to_pickle_bytes_with_options(
13903        &self,
13904        options: &PickleWriteOptions,
13905    ) -> Result<Vec<u8>, IoError> {
13906        write_pickle_bytes_with_options(self, options)
13907    }
13908
13909    fn to_stata(&self, path: &Path) -> Result<(), IoError> {
13910        write_stata(self, path)
13911    }
13912
13913    fn to_stata_file(&self, path: &Path) -> Result<(), IoError> {
13914        self.to_stata(path)
13915    }
13916
13917    fn to_stata_with_options(
13918        &self,
13919        path: &Path,
13920        options: &StataWriteOptions,
13921    ) -> Result<(), IoError> {
13922        write_stata_with_options(self, path, options)
13923    }
13924
13925    fn to_stata_bytes(&self) -> Result<Vec<u8>, IoError> {
13926        write_stata_bytes(self)
13927    }
13928
13929    fn to_stata_bytes_with_options(&self, options: &StataWriteOptions) -> Result<Vec<u8>, IoError> {
13930        write_stata_bytes_with_options(self, options)
13931    }
13932
13933    fn to_excel(&self, path: &Path) -> Result<(), IoError> {
13934        write_excel(self, path)
13935    }
13936
13937    fn to_excel_file(&self, path: &Path) -> Result<(), IoError> {
13938        self.to_excel(path)
13939    }
13940
13941    fn to_excel_with_options(
13942        &self,
13943        path: &Path,
13944        options: &ExcelWriteOptions,
13945    ) -> Result<(), IoError> {
13946        write_excel_with_options(self, path, options)
13947    }
13948
13949    fn to_excel_bytes(&self) -> Result<Vec<u8>, IoError> {
13950        write_excel_bytes(self)
13951    }
13952
13953    fn to_excel_bytes_with_options(&self, options: &ExcelWriteOptions) -> Result<Vec<u8>, IoError> {
13954        write_excel_bytes_with_options(self, options)
13955    }
13956
13957    fn to_jsonl_file(&self, path: &Path) -> Result<(), IoError> {
13958        write_jsonl(self, path)
13959    }
13960
13961    fn to_jsonl_string(&self) -> Result<String, IoError> {
13962        write_jsonl_string(self)
13963    }
13964
13965    fn to_feather(&self, path: &Path) -> Result<(), IoError> {
13966        write_feather(self, path)
13967    }
13968
13969    fn to_feather_file(&self, path: &Path) -> Result<(), IoError> {
13970        self.to_feather(path)
13971    }
13972
13973    fn to_feather_bytes(&self) -> Result<Vec<u8>, IoError> {
13974        write_feather_bytes(self)
13975    }
13976
13977    fn to_sql<C: SqlConnection>(
13978        &self,
13979        conn: &C,
13980        table_name: &str,
13981        if_exists: SqlIfExists,
13982    ) -> Result<(), IoError> {
13983        write_sql(self, conn, table_name, if_exists)
13984    }
13985
13986    fn to_sql_with_options<C: SqlConnection>(
13987        &self,
13988        conn: &C,
13989        table_name: &str,
13990        options: &SqlWriteOptions,
13991    ) -> Result<(), IoError> {
13992        write_sql_with_options(self, conn, table_name, options)
13993    }
13994
13995    fn to_clipboard(&self) -> Result<(), IoError> {
13996        clipboard_set(&clipboard_tsv(self)?)
13997    }
13998
13999    fn to_gbq(&self, _destination_table: &str, _project_id: Option<&str>) -> Result<(), IoError> {
14000        let _ = self;
14001        Err(deferred_writer_error(
14002            "to_gbq",
14003            "Google BigQuery integration is outside FrankenPandas's local file-format scope",
14004        ))
14005    }
14006}
14007
14008// ── Extension trait for Series IO convenience methods ─────────────────
14009
14010/// Extension trait that adds IO convenience methods to `Series`.
14011///
14012/// Import this trait to call `series.to_pickle(path)`,
14013/// `series.to_pickle_bytes()`, `series.to_hdf(path)`,
14014/// `series.to_csv_string()`, `series.to_markdown_string()`,
14015/// `series.to_latex_string()`, `series.to_json_string("records")`,
14016/// `series.to_hdf(path)`, `series.to_excel(path)`,
14017/// `series.to_sql(conn, table, if_exists)`, or `series.to_clipboard()`
14018/// directly on Series values.
14019pub trait SeriesIoExt {
14020    /// Write this Series to a Pickle file.
14021    ///
14022    /// Matches `pd.Series.to_pickle(path)` for the supported
14023    /// FrankenPandas pickle envelope.
14024    fn to_pickle(&self, path: &Path) -> Result<(), IoError>;
14025
14026    /// Write this Series to a Pickle file.
14027    ///
14028    /// Explicit file-suffixed form of [`SeriesIoExt::to_pickle`].
14029    fn to_pickle_file(&self, path: &Path) -> Result<(), IoError>;
14030
14031    /// Write this Series to a Pickle file with explicit options.
14032    fn to_pickle_with_options(
14033        &self,
14034        path: &Path,
14035        options: &PickleWriteOptions,
14036    ) -> Result<(), IoError>;
14037
14038    /// Serialize this Series to Pickle bytes.
14039    fn to_pickle_bytes(&self) -> Result<Vec<u8>, IoError>;
14040
14041    /// Serialize this Series to Pickle bytes with explicit options.
14042    fn to_pickle_bytes_with_options(
14043        &self,
14044        options: &PickleWriteOptions,
14045    ) -> Result<Vec<u8>, IoError>;
14046
14047    /// Write this Series to a CSV file.
14048    ///
14049    /// Matches `pd.Series.to_csv(path)` for the supported CSV writer surface,
14050    /// including pandas' default index materialization.
14051    fn to_csv_file(&self, path: &Path) -> Result<(), IoError>;
14052
14053    /// Write this Series to a CSV file with explicit write options.
14054    fn to_csv_file_with_options(
14055        &self,
14056        path: &Path,
14057        options: &CsvWriteOptions,
14058    ) -> Result<(), IoError>;
14059
14060    /// Serialize this Series to a CSV string.
14061    ///
14062    /// Matches `pd.Series.to_csv()` with no path for the supported writer
14063    /// surface.
14064    fn to_csv_string(&self) -> Result<String, IoError>;
14065
14066    /// Serialize this Series to a CSV string with explicit write options.
14067    fn to_csv_string_with_options(&self, options: &CsvWriteOptions) -> Result<String, IoError>;
14068
14069    /// Serialize this Series to a Markdown table string.
14070    ///
14071    /// Matches `pd.Series.to_markdown()` with no buffer for the supported
14072    /// table formatter surface.
14073    fn to_markdown_string(&self) -> Result<String, IoError>;
14074
14075    /// Serialize this Series to a Markdown table string with explicit options.
14076    fn to_markdown_string_with_options(
14077        &self,
14078        options: &MarkdownWriteOptions,
14079    ) -> Result<String, IoError>;
14080
14081    /// Write this Series to a Markdown table file.
14082    ///
14083    /// Uses a file-suffixed name to avoid colliding with
14084    /// `Series::to_markdown(include_index, tablefmt)`.
14085    fn to_markdown_file(&self, path: &Path) -> Result<(), IoError>;
14086
14087    /// Write this Series to a Markdown table file with explicit options.
14088    fn to_markdown_file_with_options(
14089        &self,
14090        path: &Path,
14091        options: &MarkdownWriteOptions,
14092    ) -> Result<(), IoError>;
14093
14094    /// Serialize this Series to a LaTeX tabular string.
14095    ///
14096    /// Matches `pd.Series.to_latex()` with no buffer for the supported table
14097    /// formatter surface.
14098    fn to_latex_string(&self) -> Result<String, IoError>;
14099
14100    /// Serialize this Series to a LaTeX tabular string with explicit options.
14101    fn to_latex_string_with_options(&self, options: &LatexWriteOptions) -> Result<String, IoError>;
14102
14103    /// Write this Series to a LaTeX tabular file.
14104    ///
14105    /// Uses a file-suffixed name to avoid colliding with
14106    /// `Series::to_latex(include_index)`.
14107    fn to_latex_file(&self, path: &Path) -> Result<(), IoError>;
14108
14109    /// Write this Series to a LaTeX tabular file with explicit options.
14110    fn to_latex_file_with_options(
14111        &self,
14112        path: &Path,
14113        options: &LatexWriteOptions,
14114    ) -> Result<(), IoError>;
14115
14116    /// Write this Series to a JSON file.
14117    ///
14118    /// Matches `pd.Series.to_json(path, orient=...)` for the supported Series
14119    /// JSON orientations.
14120    fn to_json_file(&self, path: &Path, orient: &str) -> Result<(), IoError>;
14121
14122    /// Serialize this Series to a JSON string.
14123    ///
14124    /// Matches `pd.Series.to_json(orient=...)` for the supported Series JSON
14125    /// orientations.
14126    fn to_json_string(&self, orient: &str) -> Result<String, IoError>;
14127
14128    /// Write this Series to an HDF5 file at the default key.
14129    ///
14130    /// Matches `pd.Series.to_hdf(path)` for the supported HDF5 snapshot
14131    /// surface.
14132    fn to_hdf(&self, path: &Path) -> Result<(), IoError>;
14133
14134    /// Write this Series to an HDF5 file at the default key.
14135    ///
14136    /// Explicit file-suffixed form of [`SeriesIoExt::to_hdf`].
14137    fn to_hdf_file(&self, path: &Path) -> Result<(), IoError>;
14138
14139    /// Write this Series to an HDF5 file at an explicit key.
14140    fn to_hdf_key(&self, path: &Path, key: &str) -> Result<(), IoError>;
14141
14142    /// Write this Series to an HDF5 file with explicit options.
14143    fn to_hdf_with_options(&self, path: &Path, options: &HdfWriteOptions) -> Result<(), IoError>;
14144
14145    /// Write this Series to an Excel file.
14146    ///
14147    /// Matches `pd.Series.to_excel(path)` for the supported xlsx writer
14148    /// surface.
14149    fn to_excel(&self, path: &Path) -> Result<(), IoError>;
14150
14151    /// Write this Series to an Excel file.
14152    ///
14153    /// Explicit file-suffixed form of [`SeriesIoExt::to_excel`].
14154    fn to_excel_file(&self, path: &Path) -> Result<(), IoError>;
14155
14156    /// Write this Series to an Excel file with explicit options.
14157    fn to_excel_with_options(
14158        &self,
14159        path: &Path,
14160        options: &ExcelWriteOptions,
14161    ) -> Result<(), IoError>;
14162
14163    /// Serialize this Series to xlsx bytes.
14164    fn to_excel_bytes(&self) -> Result<Vec<u8>, IoError>;
14165
14166    /// Serialize this Series to xlsx bytes with explicit options.
14167    fn to_excel_bytes_with_options(&self, options: &ExcelWriteOptions) -> Result<Vec<u8>, IoError>;
14168
14169    /// Write this Series to a SQL table.
14170    ///
14171    /// Matches `pd.Series.to_sql(name, con)` for the supported SQL writer
14172    /// surface, including pandas' default index materialization.
14173    fn to_sql<C: SqlConnection>(
14174        &self,
14175        conn: &C,
14176        table_name: &str,
14177        if_exists: SqlIfExists,
14178    ) -> Result<(), IoError>;
14179
14180    /// Write this Series to a SQL table with pandas-style SQL write options.
14181    fn to_sql_with_options<C: SqlConnection>(
14182        &self,
14183        conn: &C,
14184        table_name: &str,
14185        options: &SqlWriteOptions,
14186    ) -> Result<(), IoError>;
14187
14188    /// Clipboard writer (TSV via an OS backend), matching `pd.Series.to_clipboard()`.
14189    fn to_clipboard(&self) -> Result<(), IoError>;
14190}
14191
14192impl SeriesIoExt for Series {
14193    fn to_pickle(&self, path: &Path) -> Result<(), IoError> {
14194        write_pickle(&self.to_frame(None)?, path)
14195    }
14196
14197    fn to_pickle_file(&self, path: &Path) -> Result<(), IoError> {
14198        self.to_pickle(path)
14199    }
14200
14201    fn to_pickle_with_options(
14202        &self,
14203        path: &Path,
14204        options: &PickleWriteOptions,
14205    ) -> Result<(), IoError> {
14206        write_pickle_with_options(&self.to_frame(None)?, path, options)
14207    }
14208
14209    fn to_pickle_bytes(&self) -> Result<Vec<u8>, IoError> {
14210        write_pickle_bytes(&self.to_frame(None)?)
14211    }
14212
14213    fn to_pickle_bytes_with_options(
14214        &self,
14215        options: &PickleWriteOptions,
14216    ) -> Result<Vec<u8>, IoError> {
14217        write_pickle_bytes_with_options(&self.to_frame(None)?, options)
14218    }
14219
14220    fn to_csv_file(&self, path: &Path) -> Result<(), IoError> {
14221        self.to_csv_file_with_options(
14222            path,
14223            &CsvWriteOptions {
14224                include_index: true,
14225                ..CsvWriteOptions::default()
14226            },
14227        )
14228    }
14229
14230    fn to_csv_file_with_options(
14231        &self,
14232        path: &Path,
14233        options: &CsvWriteOptions,
14234    ) -> Result<(), IoError> {
14235        std::fs::write(path, self.to_csv_string_with_options(options)?)?;
14236        Ok(())
14237    }
14238
14239    fn to_csv_string(&self) -> Result<String, IoError> {
14240        self.to_csv_string_with_options(&CsvWriteOptions {
14241            include_index: true,
14242            ..CsvWriteOptions::default()
14243        })
14244    }
14245
14246    fn to_csv_string_with_options(&self, options: &CsvWriteOptions) -> Result<String, IoError> {
14247        write_csv_string_with_options(&self.to_frame(None)?, options)
14248    }
14249
14250    fn to_markdown_string(&self) -> Result<String, IoError> {
14251        self.to_markdown_string_with_options(&MarkdownWriteOptions::default())
14252    }
14253
14254    fn to_markdown_string_with_options(
14255        &self,
14256        options: &MarkdownWriteOptions,
14257    ) -> Result<String, IoError> {
14258        write_markdown_string_with_options(&self.to_frame(None)?, options)
14259    }
14260
14261    fn to_markdown_file(&self, path: &Path) -> Result<(), IoError> {
14262        self.to_markdown_file_with_options(path, &MarkdownWriteOptions::default())
14263    }
14264
14265    fn to_markdown_file_with_options(
14266        &self,
14267        path: &Path,
14268        options: &MarkdownWriteOptions,
14269    ) -> Result<(), IoError> {
14270        write_markdown_with_options(&self.to_frame(None)?, path, options)
14271    }
14272
14273    fn to_latex_string(&self) -> Result<String, IoError> {
14274        self.to_latex_string_with_options(&LatexWriteOptions::default())
14275    }
14276
14277    fn to_latex_string_with_options(&self, options: &LatexWriteOptions) -> Result<String, IoError> {
14278        write_latex_string_with_options(&self.to_frame(None)?, options)
14279    }
14280
14281    fn to_latex_file(&self, path: &Path) -> Result<(), IoError> {
14282        self.to_latex_file_with_options(path, &LatexWriteOptions::default())
14283    }
14284
14285    fn to_latex_file_with_options(
14286        &self,
14287        path: &Path,
14288        options: &LatexWriteOptions,
14289    ) -> Result<(), IoError> {
14290        write_latex_with_options(&self.to_frame(None)?, path, options)
14291    }
14292
14293    fn to_json_file(&self, path: &Path, orient: &str) -> Result<(), IoError> {
14294        std::fs::write(path, self.to_json_string(orient)?)?;
14295        Ok(())
14296    }
14297
14298    fn to_json_string(&self, orient: &str) -> Result<String, IoError> {
14299        Ok(Series::to_json(self, orient)?)
14300    }
14301
14302    fn to_hdf(&self, path: &Path) -> Result<(), IoError> {
14303        write_hdf(&self.to_frame(None)?, path)
14304    }
14305
14306    fn to_hdf_file(&self, path: &Path) -> Result<(), IoError> {
14307        self.to_hdf(path)
14308    }
14309
14310    fn to_hdf_key(&self, path: &Path, key: &str) -> Result<(), IoError> {
14311        write_hdf_key(&self.to_frame(None)?, path, key)
14312    }
14313
14314    fn to_hdf_with_options(&self, path: &Path, options: &HdfWriteOptions) -> Result<(), IoError> {
14315        write_hdf_with_options(&self.to_frame(None)?, path, options)
14316    }
14317
14318    fn to_excel(&self, path: &Path) -> Result<(), IoError> {
14319        write_excel(&self.to_frame(None)?, path)
14320    }
14321
14322    fn to_excel_file(&self, path: &Path) -> Result<(), IoError> {
14323        self.to_excel(path)
14324    }
14325
14326    fn to_excel_with_options(
14327        &self,
14328        path: &Path,
14329        options: &ExcelWriteOptions,
14330    ) -> Result<(), IoError> {
14331        write_excel_with_options(&self.to_frame(None)?, path, options)
14332    }
14333
14334    fn to_excel_bytes(&self) -> Result<Vec<u8>, IoError> {
14335        write_excel_bytes(&self.to_frame(None)?)
14336    }
14337
14338    fn to_excel_bytes_with_options(&self, options: &ExcelWriteOptions) -> Result<Vec<u8>, IoError> {
14339        write_excel_bytes_with_options(&self.to_frame(None)?, options)
14340    }
14341
14342    fn to_sql<C: SqlConnection>(
14343        &self,
14344        conn: &C,
14345        table_name: &str,
14346        if_exists: SqlIfExists,
14347    ) -> Result<(), IoError> {
14348        write_sql_with_options(
14349            &self.to_frame(None)?,
14350            conn,
14351            table_name,
14352            &SqlWriteOptions {
14353                if_exists,
14354                index: true,
14355                index_label: None,
14356                schema: None,
14357                dtype: None,
14358                method: SqlInsertMethod::Single,
14359                chunksize: None,
14360            },
14361        )
14362    }
14363
14364    fn to_sql_with_options<C: SqlConnection>(
14365        &self,
14366        conn: &C,
14367        table_name: &str,
14368        options: &SqlWriteOptions,
14369    ) -> Result<(), IoError> {
14370        write_sql_with_options(&self.to_frame(None)?, conn, table_name, options)
14371    }
14372
14373    fn to_clipboard(&self) -> Result<(), IoError> {
14374        clipboard_set(&clipboard_tsv(&self.to_frame(None)?)?)
14375    }
14376}
14377
14378#[cfg(test)]
14379mod tests {
14380    use std::collections::BTreeMap;
14381
14382    use arrow::{
14383        array::{Array, Int64Array},
14384        datatypes::DataType as ArrowDataType,
14385    };
14386    use fp_columnar::Column;
14387    use fp_frame::{DataFrame, Series};
14388    use fp_index::{Index, IndexLabel};
14389    use fp_types::{DType, NullKind, Scalar, Timestamp};
14390
14391    use super::{
14392        CsvWriteOptions, ExcelReadOptions, ExcelWriteOptions, Float64QuarterAffineCsvPlan,
14393        HtmlReadOptions, HtmlWriteOptions, IoError, JsonOrient, LatexWriteOptions,
14394        MarkdownWriteOptions, PickleProtocol, PickleWriteOptions, StataWriteOptions,
14395        XmlReadOptions, XmlWriteOptions, format_pandas_float, read_csv_str,
14396        read_csv_with_index_cols, read_excel_bytes, read_feather_bytes, read_html, read_html_str,
14397        read_html_str_with_options, read_json_str, read_orc, read_orc_bytes, read_parquet_bytes,
14398        read_pickle, read_pickle_bytes, read_stata, read_stata_bytes, read_xml, read_xml_str,
14399        read_xml_str_with_options, write_csv_string, write_csv_string_with_options,
14400        write_excel_bytes, write_html, write_html_string, write_html_string_with_options,
14401        write_json_string, write_jsonl_string, write_latex, write_latex_string,
14402        write_latex_string_with_options, write_latex_with_options, write_markdown,
14403        write_markdown_string, write_markdown_string_with_options, write_markdown_with_options,
14404        write_orc, write_orc_bytes, write_pickle, write_pickle_bytes, write_stata,
14405        write_stata_bytes, write_stata_bytes_with_options, write_xml, write_xml_string,
14406        write_xml_string_with_options,
14407    };
14408    #[cfg(feature = "hdf5")]
14409    use super::{
14410        HdfReadOptions, HdfWriteOptions, read_hdf, read_hdf_key, read_hdf_with_options, write_hdf,
14411        write_hdf_key, write_hdf_with_options,
14412    };
14413
14414    fn assert_orc_disabled(err: IoError) {
14415        assert!(
14416            matches!(
14417                err,
14418                IoError::Orc(ref message)
14419                    if message.contains("Tokio-free native ORC backend")
14420            ),
14421            "expected ORC no-Tokio policy error, got {err:?}"
14422        );
14423    }
14424
14425    #[test]
14426    fn csv_quoting_round_trip_special_chars_1h8ar() {
14427        // RFC4180 escaping (br-frankenpandas-1h8ar): quoted fields parse to their
14428        // unescaped value, and write->read round-trips them (write must re-quote).
14429        // (csv_field_as_written, expected_parsed_value)
14430        let cases: [(&str, &str); 4] = [
14431            ("\"x,y\"", "x,y"),     // comma requires quoting
14432            ("\"a\"\"b\"", "a\"b"), // embedded quote -> doubled
14433            ("plain", "plain"),     // no quoting needed
14434            ("\" sp \"", " sp "),   // preserved leading/trailing spaces
14435        ];
14436        for (field, expected) in cases {
14437            let input = format!("col\n{field}\n");
14438            let f1 = read_csv_str(&input).expect("read1");
14439            assert_eq!(
14440                f1.column("col").expect("col").values()[0],
14441                Scalar::Utf8(expected.to_string()),
14442                "parse field={field:?}"
14443            );
14444            // write then re-read must preserve the value (correct re-quoting).
14445            let s2 = write_csv_string(&f1).expect("write");
14446            let f2 = read_csv_str(&s2).expect("read2");
14447            assert_eq!(
14448                f2.column("col").expect("col2").values()[0],
14449                Scalar::Utf8(expected.to_string()),
14450                "round-trip field={field:?} written={s2:?}"
14451            );
14452        }
14453    }
14454
14455    #[test]
14456    fn csv_write_header_line_order_g9rxa() {
14457        // br-frankenpandas-g9rxa: write_csv_string's first line == column names in
14458        // column order joined by comma.
14459        let idx = vec![0_i64.into(), 1_i64.into()];
14460        let col = |name: &str, v: [i64; 2]| {
14461            Series::from_values(
14462                name,
14463                idx.clone(),
14464                vec![Scalar::Int64(v[0]), Scalar::Int64(v[1])],
14465            )
14466            .unwrap()
14467        };
14468        let df = DataFrame::from_series(vec![
14469            col("alpha", [1, 2]),
14470            col("beta", [3, 4]),
14471            col("gamma", [5, 6]),
14472        ])
14473        .unwrap();
14474        let csv = write_csv_string(&df).expect("write");
14475        let header = csv.lines().next().expect("header line");
14476        assert_eq!(header, "alpha,beta,gamma", "header order; csv={csv:?}");
14477    }
14478
14479    // Deterministic n-row frame whose row `i` depends ONLY on `i`, using the typed
14480    // constructors so try_write_csv_typed's fast path applies. Exercises every
14481    // FastCol arm: an AFFINE Float64 (quarter_plan), a non-affine Float64 (ryu),
14482    // Int64, Bool, and contiguous Utf8 with embedded commas (QUOTE_MINIMAL).
14483    fn csv_bitident_frame_ironquail(n: usize) -> DataFrame {
14484        let idx = Index::from_range(0, n as i64, 1);
14485        let aff: Vec<f64> = (0..n).map(|i| i as f64).collect();
14486        let flt: Vec<f64> = (0..n)
14487            .map(|i| {
14488                ((i as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15) >> 11) as f64 / (1u64 << 53) as f64
14489                    * 1e6
14490            })
14491            .collect();
14492        let int: Vec<i64> = (0..n as i64).collect();
14493        let boo: Vec<bool> = (0..n).map(|i| i % 3 == 0).collect();
14494        let mut sbytes: Vec<u8> = Vec::new();
14495        let mut soff: Vec<usize> = vec![0];
14496        for i in 0..n {
14497            let s = if i % 7 == 0 {
14498                format!("a,b{i}")
14499            } else {
14500                format!("x{i}")
14501            };
14502            sbytes.extend_from_slice(s.as_bytes());
14503            soff.push(sbytes.len());
14504        }
14505        let mut cols = BTreeMap::new();
14506        cols.insert("aff".to_string(), Column::from_f64_values(aff));
14507        cols.insert("flt".to_string(), Column::from_f64_values(flt));
14508        cols.insert("int".to_string(), Column::from_i64_values(int));
14509        cols.insert("boo".to_string(), Column::from_bool_values(boo));
14510        cols.insert(
14511            "str".to_string(),
14512            Column::from_utf8_contiguous(sbytes, soff),
14513        );
14514        DataFrame::new_with_column_order(
14515            idx,
14516            cols,
14517            vec![
14518                "aff".to_string(),
14519                "flt".to_string(),
14520                "int".to_string(),
14521                "boo".to_string(),
14522                "str".to_string(),
14523            ],
14524        )
14525        .unwrap()
14526    }
14527
14528    #[test]
14529    fn csv_parallel_path_matches_serial_prefix_ironquail() {
14530        // The 49k frame writes via the SERIAL path (< CSV_PAR_MIN_ROWS); the 51k frame
14531        // writes via the CHUNKED-PARALLEL path (>= CSV_PAR_MIN_ROWS). Row `i` depends
14532        // only on `i`, so rows 0..49000 are identical between the frames — hence the
14533        // 51k CSV must have the 49k CSV as a BYTE-EXACT prefix, proving the parallel
14534        // writer is byte-identical to the serial writer across chunk boundaries.
14535        let small = csv_bitident_frame_ironquail(49_000);
14536        let large = csv_bitident_frame_ironquail(51_000);
14537        let csv_small = write_csv_string(&small).expect("serial write");
14538        let csv_large = write_csv_string(&large).expect("parallel write");
14539        assert!(csv_large.len() > csv_small.len(), "large must be longer");
14540        assert!(
14541            csv_large.as_bytes().starts_with(csv_small.as_bytes()),
14542            "parallel CSV diverges from serial on the shared 0..49000 rows"
14543        );
14544    }
14545
14546    #[test]
14547    fn json_read_parallel_matches_serial_ironquail() {
14548        // 60k >= PAR_MIN_RECORDS so records read via the PARALLEL boundary-split path;
14549        // compare it directly to the SERIAL flat scanner on the same input. The Utf8
14550        // column carries embedded commas, so this also exercises the string-aware
14551        // boundary scan (a comma inside a string must NOT be a record boundary).
14552        let frame = csv_bitident_frame_ironquail(60_000);
14553        let json = write_json_string(&frame, JsonOrient::Records).expect("write records json");
14554        let par = super::try_read_json_records_flat_parallel(&json)
14555            .expect("parallel ok")
14556            .expect("parallel took its path (>=50k homogeneous)");
14557        let ser = super::try_read_json_records_flat(&json)
14558            .expect("serial ok")
14559            .expect("serial took its path");
14560        assert_eq!(par.len(), 60_000);
14561        assert!(
14562            par.equals(&ser),
14563            "parallel json read diverges from the serial flat scanner"
14564        );
14565    }
14566
14567    #[test]
14568    fn csv_per_column_dtype_inference_me2x3() {
14569        // br-frankenpandas-me2x3: read_csv infers Int64 for all-int, Float64 for a
14570        // column containing a decimal, Utf8 for text.
14571        let df = read_csv_str("a,b,c\n1,1.5,x\n2,2.5,y\n3,3.5,z\n").expect("read");
14572        assert_eq!(
14573            df.column("a").expect("a").dtype(),
14574            DType::Int64,
14575            "all-int -> Int64"
14576        );
14577        assert_eq!(
14578            df.column("b").expect("b").dtype(),
14579            DType::Float64,
14580            "decimal -> Float64"
14581        );
14582        assert_eq!(
14583            df.column("c").expect("c").dtype(),
14584            DType::Utf8,
14585            "text -> Utf8"
14586        );
14587        assert_eq!(df.len(), 3, "row count");
14588    }
14589
14590    #[test]
14591    fn csv_header_only_zero_rows_yqfw0() {
14592        // br-frankenpandas-yqfw0: a header-only CSV parses to a 0-row frame that still
14593        // exposes the header columns.
14594        let df = read_csv_str("a,b\n").expect("read header-only");
14595        assert_eq!(df.len(), 0, "no data rows; df={df:?}");
14596        assert!(df.column("a").is_some(), "column a present");
14597        assert!(df.column("b").is_some(), "column b present");
14598        assert_eq!(df.column("a").unwrap().values().len(), 0, "column a empty");
14599    }
14600
14601    #[test]
14602    fn csv_embedded_comma_in_quoted_field_rtpo7() {
14603        // br-frankenpandas-rtpo7: a quoted field containing the delimiter parses as ONE
14604        // field, not two columns (RFC4180). Companion to ftqon (embedded newline).
14605        let df = read_csv_str("col,n\n\"a,b\",1\n").expect("read");
14606        assert_eq!(df.len(), 1, "one row");
14607        assert!(
14608            df.column("col").is_some() && df.column("n").is_some(),
14609            "two columns only"
14610        );
14611        assert_eq!(
14612            df.column("col").unwrap().values()[0],
14613            Scalar::Utf8("a,b".to_owned()),
14614            "embedded comma kept"
14615        );
14616    }
14617
14618    #[test]
14619    fn csv_embedded_newline_in_quoted_field_ftqon() {
14620        // br-frankenpandas-ftqon: a quoted field containing a newline parses as ONE
14621        // multiline value (RFC4180), not two rows; and round-trips.
14622        let input = "col\n\"line1\nline2\"\n";
14623        let df = read_csv_str(input).expect("read");
14624        assert_eq!(df.len(), 1, "embedded newline stays one row; df={df:?}");
14625        let col = df.column("col").expect("col");
14626        assert_eq!(
14627            col.values()[0],
14628            Scalar::Utf8("line1\nline2".to_owned()),
14629            "multiline value intact"
14630        );
14631        // Round-trip: writing then reading preserves the multiline value.
14632        let csv = write_csv_string(&df).expect("write");
14633        let back = read_csv_str(&csv).expect("reread");
14634        assert_eq!(back.len(), 1, "round-trip row count");
14635        assert_eq!(
14636            back.column("col").expect("col").values()[0],
14637            Scalar::Utf8("line1\nline2".to_owned()),
14638            "round-trip value"
14639        );
14640    }
14641
14642    #[test]
14643    fn csv_bool_column_round_trip_w3dja() {
14644        // br-frankenpandas-w3dja: Bool column survives write_csv_string -> read_csv_str
14645        // (True/False spelling on write + case-insensitive bool inference on read).
14646        let bools = [true, false, true, false, true];
14647        let df = DataFrame::from_series(vec![
14648            Series::from_values(
14649                "flag",
14650                (0..bools.len() as i64).map(Into::into).collect::<Vec<_>>(),
14651                bools.iter().map(|&b| Scalar::Bool(b)).collect::<Vec<_>>(),
14652            )
14653            .unwrap(),
14654        ])
14655        .unwrap();
14656
14657        let csv = write_csv_string(&df).expect("write");
14658        let back = read_csv_str(&csv).expect("read");
14659        let col = back.column("flag").expect("flag");
14660        assert_eq!(
14661            col.dtype(),
14662            DType::Bool,
14663            "round-trip keeps Bool; csv={csv:?}"
14664        );
14665        assert_eq!(
14666            col.values(),
14667            &bools.iter().map(|&b| Scalar::Bool(b)).collect::<Vec<_>>()[..],
14668            "bool values preserved"
14669        );
14670    }
14671
14672    #[test]
14673    fn csv_read_write_read_idempotent_5gfjz() {
14674        // Round-trip fixed point (br-frankenpandas-5gfjz): read -> write -> read
14675        // yields an identical frame. Simple cells (ints + single letters, no
14676        // special chars) avoid quoting/precision edges. Seeded LCG, no mocks.
14677        let mut st: u64 = 0xc5f0_1d2e_3a4b_5c6d;
14678        let mut next = || {
14679            st = st
14680                .wrapping_mul(6_364_136_223_846_793_005)
14681                .wrapping_add(1_442_695_040_888_963_407);
14682            (st >> 33) as u32
14683        };
14684        for iter in 0..400u32 {
14685            let rows = (next() % 6) as usize + 1;
14686            let mut csv = String::from("a,b,c\n");
14687            for _ in 0..rows {
14688                let x = (next() % 100) as i64;
14689                let y = (next() % 1000) as i64;
14690                let letter = (b'a' + (next() % 5) as u8) as char;
14691                csv.push_str(&format!("{x},{y},{letter}\n"));
14692            }
14693            let f1 = read_csv_str(&csv).expect("read1");
14694            let s2 = write_csv_string(&f1).expect("write");
14695            let f2 = read_csv_str(&s2).expect("read2");
14696            assert_eq!(f1.len(), f2.len(), "row count iter={iter} csv={csv:?}");
14697            for name in ["a", "b", "c"] {
14698                assert_eq!(
14699                    f1.column(name).expect("c1").values(),
14700                    f2.column(name).expect("c2").values(),
14701                    "col {name} iter={iter} csv={csv:?}"
14702                );
14703            }
14704        }
14705    }
14706
14707    #[test]
14708    fn csv_round_trip_preserves_null_and_numeric_shape() {
14709        let input = "id,value\n1,10\n2,\n3,3.5\n";
14710        let frame = read_csv_str(input).expect("read");
14711        let value_col = frame.column("value").expect("value");
14712
14713        assert_eq!(value_col.values()[1], Scalar::Null(NullKind::NaN));
14714
14715        let out = write_csv_string(&frame).expect("write");
14716        assert!(out.contains("id,value"));
14717        assert!(out.contains("3,3.5"));
14718    }
14719
14720    #[test]
14721    fn csv_numeric_fast_path_preserves_default_dtypes_and_values() {
14722        let input = "i,f\n1,0.5\n2,3\n";
14723        let frame = read_csv_str(input).expect("read");
14724
14725        let int_col = frame.column("i").expect("i");
14726        assert_eq!(int_col.dtype(), DType::Int64);
14727        assert_eq!(int_col.values(), &[Scalar::Int64(1), Scalar::Int64(2)]);
14728
14729        let float_col = frame.column("f").expect("f");
14730        assert_eq!(float_col.dtype(), DType::Float64);
14731        assert_eq!(
14732            float_col.values(),
14733            &[Scalar::Float64(0.5), Scalar::Float64(3.0)]
14734        );
14735    }
14736
14737    #[test]
14738    fn csv_numeric_probe_falls_back_to_preserve_object_raw_text() {
14739        let input = "x\n 1 \nabc\n";
14740        let frame = read_csv_str(input).expect("read");
14741        let column = frame.column("x").expect("x");
14742
14743        assert_eq!(column.dtype(), DType::Utf8);
14744        assert_eq!(
14745            column.values(),
14746            &[
14747                Scalar::Utf8(" 1 ".to_owned()),
14748                Scalar::Utf8("abc".to_owned())
14749            ]
14750        );
14751    }
14752
14753    #[test]
14754    fn csv_parses_boolean_true_false_case_insensitive() {
14755        let input = "flag\nTrue\nFALSE\ntrue\nfalse\n";
14756        let frame = read_csv_str(input).expect("read");
14757        let flag_col = frame.column("flag").expect("flag");
14758        assert_eq!(flag_col.values()[0], Scalar::Bool(true));
14759        assert_eq!(flag_col.values()[1], Scalar::Bool(false));
14760        assert_eq!(flag_col.values()[2], Scalar::Bool(true));
14761        assert_eq!(flag_col.values()[3], Scalar::Bool(false));
14762    }
14763
14764    #[test]
14765    fn csv_duplicate_headers_error() {
14766        let input = "a,a\n1,2\n";
14767        let err = read_csv_str(input).expect_err("duplicate header");
14768        assert!(matches!(err, IoError::DuplicateColumnName(name) if name == "a"));
14769    }
14770
14771    #[test]
14772    fn csv_ragged_row_returns_error_4hpid() {
14773        // Per br-frankenpandas-4hpid: confirm pandas-faithful rejection on
14774        // ragged rows. The underlying csv crate raises UnequalLengths
14775        // (surfaced as IoError::Csv) — record.get(idx).unwrap_or_default()
14776        // inside the loop is dead code because the `row?` upstream errors
14777        // first. This locks in the rejection contract.
14778        let short_row = "a,b,c\n1,2,3\n4,5\n7,8,9\n";
14779        let err = read_csv_str(short_row).expect_err("short row must reject");
14780        assert!(
14781            matches!(err, IoError::Csv(_)),
14782            "expected IoError::Csv (UnequalLengths from csv crate), got {err:?}"
14783        );
14784    }
14785
14786    fn make_table_format_dataframe() -> DataFrame {
14787        let mut columns = BTreeMap::new();
14788        columns.insert(
14789            "name".to_owned(),
14790            Column::from_values(vec![
14791                Scalar::Utf8("A|B".to_owned()),
14792                Scalar::Utf8("under_score".to_owned()),
14793            ])
14794            .expect("name column"),
14795        );
14796        columns.insert(
14797            "value".to_owned(),
14798            Column::from_values(vec![Scalar::Float64(f64::NAN), Scalar::Int64(2)])
14799                .expect("value column"),
14800        );
14801
14802        let index = Index::new(vec![
14803            IndexLabel::Utf8("r&1".to_owned()),
14804            IndexLabel::Utf8("r_2".to_owned()),
14805        ])
14806        .set_name("row");
14807        DataFrame::new_with_column_order(
14808            index,
14809            columns,
14810            vec!["name".to_owned(), "value".to_owned()],
14811        )
14812        .expect("table format frame")
14813    }
14814
14815    #[test]
14816    fn markdown_table_writer_includes_index_missing_values_and_escaping() {
14817        let frame = make_table_format_dataframe();
14818
14819        let out = write_markdown_string(&frame).expect("markdown");
14820
14821        assert_eq!(
14822            out,
14823            concat!(
14824                "| row | name | value |\n",
14825                "| --- | --- | --- |\n",
14826                "| r&1 | A\\|B | NaN |\n",
14827                "| r_2 | under_score | 2 |\n",
14828            )
14829        );
14830    }
14831
14832    #[test]
14833    fn markdown_table_writer_options_can_omit_index_and_override_na() {
14834        let frame = make_table_format_dataframe();
14835
14836        let out = write_markdown_string_with_options(
14837            &frame,
14838            &MarkdownWriteOptions {
14839                include_index: false,
14840                na_rep: "<missing>".to_owned(),
14841                index_label: Some("ignored".to_owned()),
14842            },
14843        )
14844        .expect("markdown");
14845
14846        assert_eq!(
14847            out,
14848            concat!(
14849                "| name | value |\n",
14850                "| --- | --- |\n",
14851                "| A\\|B | <missing> |\n",
14852                "| under_score | 2 |\n",
14853            )
14854        );
14855    }
14856
14857    #[test]
14858    fn latex_table_writer_emits_booktabs_and_supports_escaping() {
14859        let frame = make_table_format_dataframe();
14860
14861        let out = write_latex_string_with_options(
14862            &frame,
14863            &LatexWriteOptions {
14864                include_index: true,
14865                na_rep: "NA".to_owned(),
14866                index_label: Some("row_id".to_owned()),
14867                escape: true,
14868            },
14869        )
14870        .expect("latex");
14871
14872        assert_eq!(
14873            out,
14874            concat!(
14875                "\\begin{tabular}{lll}\n",
14876                "\\toprule\n",
14877                " & name & value \\\\\n",
14878                "row\\_id &  &  \\\\\n",
14879                "\\midrule\n",
14880                "r\\&1 & A|B & NA \\\\\n",
14881                "r\\_2 & under\\_score & 2.000000 \\\\\n",
14882                "\\bottomrule\n",
14883                "\\end{tabular}\n",
14884            )
14885        );
14886    }
14887
14888    #[test]
14889    fn to_latex_floats_use_six_decimal_places_like_pandas() {
14890        // pandas to_latex default float_format is %.6f. Verified vs pandas 2.2.3:
14891        // 1.0->"1.000000", -2.5->"-2.500000", 0.1234567->"0.123457" (rounded),
14892        // inf->"inf". Other writers (csv/html) keep str(float).
14893        let values = vec![
14894            Scalar::Float64(1.0),
14895            Scalar::Float64(-2.5),
14896            Scalar::Float64(0.1234567),
14897            Scalar::Float64(f64::INFINITY),
14898        ];
14899        let col = Column::new(DType::Float64, values).expect("col");
14900        let mut cols = BTreeMap::new();
14901        cols.insert("a".to_string(), col);
14902        let index = Index::from_i64((0..4).collect());
14903        let frame =
14904            DataFrame::new_with_column_order(index, cols, vec!["a".to_string()]).expect("frame");
14905
14906        let out = write_latex_string_with_options(
14907            &frame,
14908            &LatexWriteOptions {
14909                include_index: false,
14910                na_rep: "NaN".to_owned(),
14911                index_label: None,
14912                escape: true,
14913            },
14914        )
14915        .expect("latex");
14916        assert!(out.contains("1.000000 \\\\"), "got: {out}");
14917        assert!(out.contains("-2.500000 \\\\"), "got: {out}");
14918        assert!(out.contains("0.123457 \\\\"), "got: {out}");
14919        assert!(out.contains("inf \\\\"), "got: {out}");
14920    }
14921
14922    #[test]
14923    fn markdown_latex_file_writers_match_string_outputs() {
14924        let frame = make_table_format_dataframe();
14925        let markdown_path = std::env::temp_dir().join(format!(
14926            "fp_io_markdown_writer_{}_{}.md",
14927            std::process::id(),
14928            line!()
14929        ));
14930        let latex_path = std::env::temp_dir().join(format!(
14931            "fp_io_latex_writer_{}_{}.tex",
14932            std::process::id(),
14933            line!()
14934        ));
14935
14936        write_markdown(&frame, &markdown_path).expect("write markdown path");
14937        write_latex(&frame, &latex_path).expect("write latex path");
14938
14939        assert_eq!(
14940            std::fs::read_to_string(&markdown_path).expect("read markdown path"),
14941            write_markdown_string(&frame).expect("markdown string")
14942        );
14943        assert_eq!(
14944            std::fs::read_to_string(&latex_path).expect("read latex path"),
14945            write_latex_string(&frame).expect("latex string")
14946        );
14947    }
14948
14949    #[test]
14950    fn markdown_latex_trait_aliases_forward_options() {
14951        use super::DataFrameIoExt;
14952
14953        let frame = make_table_format_dataframe();
14954        let markdown_options = MarkdownWriteOptions {
14955            include_index: false,
14956            na_rep: "NA".to_owned(),
14957            index_label: Some("ignored".to_owned()),
14958        };
14959        let latex_options = LatexWriteOptions {
14960            include_index: false,
14961            na_rep: "NA".to_owned(),
14962            index_label: Some("ignored".to_owned()),
14963            escape: true,
14964        };
14965        let markdown_path = std::env::temp_dir().join(format!(
14966            "fp_io_markdown_trait_{}_{}.md",
14967            std::process::id(),
14968            line!()
14969        ));
14970        let latex_path = std::env::temp_dir().join(format!(
14971            "fp_io_latex_trait_{}_{}.tex",
14972            std::process::id(),
14973            line!()
14974        ));
14975
14976        frame
14977            .to_markdown_file_with_options(&markdown_path, &markdown_options)
14978            .expect("trait markdown file");
14979        frame
14980            .to_latex_file_with_options(&latex_path, &latex_options)
14981            .expect("trait latex file");
14982
14983        assert_eq!(
14984            frame
14985                .to_markdown_string_with_options(&markdown_options)
14986                .expect("trait markdown options"),
14987            std::fs::read_to_string(&markdown_path).expect("read markdown trait path")
14988        );
14989        assert_eq!(
14990            frame
14991                .to_latex_string_with_options(&latex_options)
14992                .expect("trait latex options"),
14993            std::fs::read_to_string(&latex_path).expect("read latex trait path")
14994        );
14995
14996        let default_markdown_path = std::env::temp_dir().join(format!(
14997            "fp_io_markdown_trait_default_{}_{}.md",
14998            std::process::id(),
14999            line!()
15000        ));
15001        let default_latex_path = std::env::temp_dir().join(format!(
15002            "fp_io_latex_trait_default_{}_{}.tex",
15003            std::process::id(),
15004            line!()
15005        ));
15006        frame
15007            .to_markdown_file(&default_markdown_path)
15008            .expect("trait markdown default file");
15009        frame
15010            .to_latex_file(&default_latex_path)
15011            .expect("trait latex default file");
15012
15013        assert_eq!(
15014            std::fs::read_to_string(&default_markdown_path).expect("read markdown default"),
15015            write_markdown_string(&frame).expect("markdown default")
15016        );
15017        assert_eq!(
15018            std::fs::read_to_string(&default_latex_path).expect("read latex default"),
15019            write_latex_string(&frame).expect("latex default")
15020        );
15021
15022        let free_markdown_path = std::env::temp_dir().join(format!(
15023            "fp_io_markdown_free_options_{}_{}.md",
15024            std::process::id(),
15025            line!()
15026        ));
15027        let free_latex_path = std::env::temp_dir().join(format!(
15028            "fp_io_latex_free_options_{}_{}.tex",
15029            std::process::id(),
15030            line!()
15031        ));
15032        write_markdown_with_options(&frame, &free_markdown_path, &markdown_options)
15033            .expect("free markdown options file");
15034        write_latex_with_options(&frame, &free_latex_path, &latex_options)
15035            .expect("free latex options file");
15036        assert_eq!(
15037            std::fs::read_to_string(&free_markdown_path).expect("read free markdown options"),
15038            write_markdown_string_with_options(&frame, &markdown_options)
15039                .expect("free markdown options string")
15040        );
15041        assert_eq!(
15042            std::fs::read_to_string(&free_latex_path).expect("read free latex options"),
15043            write_latex_string_with_options(&frame, &latex_options)
15044                .expect("free latex options string")
15045        );
15046    }
15047
15048    #[test]
15049    #[ignore = "foreground release attribution harness"]
15050    fn html_table_writer_ordered_column_hoist_profile_z8gge() {
15051        const ROWS: usize = 256;
15052        const COLUMNS: usize = 24;
15053        const BATCH: usize = 8;
15054        const BLOCKS: usize = 9;
15055
15056        fn former(frame: &DataFrame, options: &HtmlWriteOptions) -> Result<String, IoError> {
15057            let mut out = String::new();
15058            super::push_html_table_open(&mut out, options);
15059            out.push_str("  <thead>\n    <tr style=\"text-align: ");
15060            out.push_str(&super::escape_html_attr(
15061                options.justify.as_deref().unwrap_or("right"),
15062            ));
15063            out.push_str(";\">\n");
15064
15065            if options.include_index {
15066                out.push_str("      <th></th>\n");
15067            }
15068            for name in frame.column_names() {
15069                out.push_str("      <th>");
15070                out.push_str(&super::html_text(name, options.escape));
15071                out.push_str("</th>\n");
15072            }
15073            out.push_str("    </tr>\n  </thead>\n  <tbody>\n");
15074
15075            for row_idx in 0..frame.index().len() {
15076                out.push_str("    <tr>\n");
15077                if options.include_index {
15078                    out.push_str("      <th>");
15079                    out.push_str(&super::html_index_label_string(
15080                        frame,
15081                        row_idx,
15082                        options.escape,
15083                    )?);
15084                    out.push_str("</th>\n");
15085                }
15086                for name in frame.column_names() {
15087                    let value = frame.column(name).and_then(|column| column.value(row_idx));
15088                    out.push_str("      <td>");
15089                    match value {
15090                        Some(scalar) => {
15091                            out.push_str(&super::html_scalar_string(scalar, options));
15092                        }
15093                        None => {
15094                            out.push_str(&super::html_text(&options.na_rep, options.escape));
15095                        }
15096                    }
15097                    out.push_str("</td>\n");
15098                }
15099                out.push_str("    </tr>\n");
15100            }
15101
15102            out.push_str("  </tbody>\n</table>");
15103            Ok(out)
15104        }
15105
15106        fn prototype(frame: &DataFrame, options: &HtmlWriteOptions) -> Result<String, IoError> {
15107            super::write_html_table_string(frame, options)
15108        }
15109
15110        fn elapsed_ns(frame: &DataFrame, options: &HtmlWriteOptions, use_prototype: bool) -> u128 {
15111            let started = std::time::Instant::now();
15112            for _ in 0..BATCH {
15113                let output = if use_prototype {
15114                    prototype(frame, options)
15115                } else {
15116                    former(frame, options)
15117                }
15118                .expect("HTML render");
15119                std::hint::black_box(output.as_bytes().last());
15120            }
15121            started.elapsed().as_nanos()
15122        }
15123
15124        fn median(mut samples: Vec<u128>) -> u128 {
15125            samples.sort_unstable();
15126            samples[samples.len() / 2]
15127        }
15128
15129        let mut columns = BTreeMap::new();
15130        let mut column_order = Vec::with_capacity(COLUMNS);
15131        for column_idx in 0..COLUMNS {
15132            let name = format!("column_{column_idx:02}");
15133            let values = (0..ROWS)
15134                .map(|row_idx| (column_idx * ROWS + row_idx) as i64)
15135                .collect();
15136            columns.insert(name.clone(), Column::from_i64_values(values));
15137            column_order.push(name);
15138        }
15139        column_order.reverse();
15140        let frame = DataFrame::new_with_column_order(
15141            Index::from_range(0, ROWS as i64, 1),
15142            columns,
15143            column_order,
15144        )
15145        .expect("profile frame");
15146        let options = HtmlWriteOptions {
15147            include_index: false,
15148            ..HtmlWriteOptions::default()
15149        };
15150
15151        let expected = former(&frame, &options).expect("former HTML");
15152        let actual = prototype(&frame, &options).expect("prototype HTML");
15153        assert_eq!(actual, expected, "prototype must be byte-identical");
15154
15155        std::hint::black_box(former(&frame, &options).expect("former warm-up"));
15156        std::hint::black_box(prototype(&frame, &options).expect("prototype warm-up"));
15157
15158        let mut former_samples = Vec::with_capacity(BLOCKS * 2);
15159        let mut prototype_samples = Vec::with_capacity(BLOCKS * 2);
15160        for block in 0..BLOCKS {
15161            let order = if block % 2 == 0 {
15162                [false, true, true, false]
15163            } else {
15164                [true, false, false, true]
15165            };
15166            for use_prototype in order {
15167                let elapsed = elapsed_ns(&frame, &options, use_prototype);
15168                if use_prototype {
15169                    prototype_samples.push(elapsed);
15170                } else {
15171                    former_samples.push(elapsed);
15172                }
15173            }
15174        }
15175
15176        let former_ns = median(former_samples) / BATCH as u128;
15177        let prototype_ns = median(prototype_samples) / BATCH as u128;
15178        println!(
15179            "HTML_COLUMN_HOIST_PROFILE rows={ROWS} columns={COLUMNS} former_ns={former_ns} prototype_ns={prototype_ns} speedup={:.6}",
15180            former_ns as f64 / prototype_ns as f64
15181        );
15182    }
15183
15184    #[test]
15185    fn html_table_writer_defaults_to_index_and_reuses_dataframe_formatter() {
15186        let frame = make_table_format_dataframe();
15187
15188        let out = write_html_string(&frame).expect("html");
15189
15190        assert_eq!(out, frame.to_html(true));
15191        assert!(out.contains("<th>r&amp;1</th>"));
15192        assert!(out.contains("<td>A|B</td>"));
15193        assert!(out.contains("<td>NaN</td>"));
15194    }
15195
15196    #[test]
15197    fn html_table_writer_options_can_omit_index() {
15198        let frame = make_table_format_dataframe();
15199
15200        let out = write_html_string_with_options(
15201            &frame,
15202            &HtmlWriteOptions {
15203                include_index: false,
15204                ..HtmlWriteOptions::default()
15205            },
15206        )
15207        .expect("html");
15208
15209        assert_eq!(out, frame.to_html(false));
15210        assert!(!out.contains("<th>r&amp;1</th>"));
15211        assert!(out.contains("<td>A|B</td>"));
15212    }
15213
15214    #[test]
15215    fn html_table_writer_supports_pandas_pure_string_options_u892h() {
15216        let mut columns = BTreeMap::new();
15217        columns.insert(
15218            "url&col".to_owned(),
15219            Column::from_values(vec![
15220                Scalar::Utf8("https://example.test/a?x=1&y=2".to_owned()),
15221                Scalar::Utf8("<b>".to_owned()),
15222            ])
15223            .expect("url column"),
15224        );
15225        columns.insert(
15226            "value".to_owned(),
15227            Column::from_values(vec![Scalar::Null(NullKind::NaN), Scalar::Float64(2.0)])
15228                .expect("value column"),
15229        );
15230        let frame = DataFrame::new_with_column_order(
15231            Index::new(vec![
15232                IndexLabel::Utf8("r&1".to_owned()),
15233                IndexLabel::Utf8("r2".to_owned()),
15234            ]),
15235            columns,
15236            vec!["url&col".to_owned(), "value".to_owned()],
15237        )
15238        .expect("html options frame");
15239
15240        let out = write_html_string_with_options(
15241            &frame,
15242            &HtmlWriteOptions {
15243                include_index: true,
15244                na_rep: "<NA>".to_owned(),
15245                classes: vec!["table table-sm".to_owned(), "fp".to_owned()],
15246                table_id: Some("report&1".to_owned()),
15247                border: Some(0),
15248                justify: Some("left".to_owned()),
15249                escape: true,
15250                render_links: true,
15251            },
15252        )
15253        .expect("html options");
15254
15255        assert!(
15256            out.starts_with("<table class=\"dataframe table table-sm fp\" id=\"report&amp;1\">")
15257        );
15258        assert!(!out.contains("border=\""));
15259        assert!(out.contains("<tr style=\"text-align: left;\">"));
15260        assert!(out.contains("<th>url&amp;col</th>"));
15261        assert!(out.contains("<th>r&amp;1</th>"));
15262        assert!(out.contains("<td>&lt;NA&gt;</td>"));
15263        assert!(out.contains(
15264            "<a href=\"https://example.test/a?x=1&amp;y=2\" target=\"_blank\">https://example.test/a?x=1&amp;y=2</a>"
15265        ));
15266        assert!(out.contains("<td>&lt;b&gt;</td>"));
15267    }
15268
15269    #[test]
15270    fn html_table_writer_can_disable_escaping_u892h() {
15271        let mut columns = BTreeMap::new();
15272        columns.insert(
15273            "raw<th>".to_owned(),
15274            Column::from_values(vec![
15275                Scalar::Utf8("<b>".to_owned()),
15276                Scalar::Null(NullKind::NaN),
15277            ])
15278            .expect("raw column"),
15279        );
15280        let frame = DataFrame::new_with_column_order(
15281            Index::new(vec![
15282                IndexLabel::Utf8("r&1".to_owned()),
15283                IndexLabel::Int64(2),
15284            ]),
15285            columns,
15286            vec!["raw<th>".to_owned()],
15287        )
15288        .expect("raw html frame");
15289
15290        let out = write_html_string_with_options(
15291            &frame,
15292            &HtmlWriteOptions {
15293                na_rep: "<NA>".to_owned(),
15294                escape: false,
15295                ..HtmlWriteOptions::default()
15296            },
15297        )
15298        .expect("raw html options");
15299
15300        assert!(out.contains("<th>raw<th></th>"));
15301        assert!(out.contains("<th>r&1</th>"));
15302        assert!(out.contains("<td><b></td>"));
15303        assert!(out.contains("<td><NA></td>"));
15304    }
15305
15306    #[test]
15307    fn html_table_writer_file_output_matches_string_output() {
15308        use super::DataFrameIoExt;
15309
15310        let frame = make_table_format_dataframe();
15311        let path = std::env::temp_dir().join(format!(
15312            "fp_io_html_writer_{}_{}.html",
15313            std::process::id(),
15314            line!()
15315        ));
15316
15317        write_html(&frame, &path).expect("write html");
15318        let file_out = std::fs::read_to_string(&path).expect("read html");
15319
15320        assert_eq!(file_out, write_html_string(&frame).expect("html string"));
15321        assert_eq!(
15322            frame.to_html_string().expect("trait html string"),
15323            write_html_string(&frame).expect("free html string")
15324        );
15325
15326        let no_index_path = std::env::temp_dir().join(format!(
15327            "fp_io_html_writer_no_index_{}_{}.html",
15328            std::process::id(),
15329            line!()
15330        ));
15331        let no_index_options = HtmlWriteOptions {
15332            include_index: false,
15333            ..HtmlWriteOptions::default()
15334        };
15335        frame
15336            .to_html_file_with_options(&no_index_path, &no_index_options)
15337            .expect("trait html file");
15338        assert_eq!(
15339            std::fs::read_to_string(&no_index_path).expect("read trait html"),
15340            write_html_string_with_options(&frame, &no_index_options).expect("free html options")
15341        );
15342    }
15343
15344    #[test]
15345    fn html_reader_parses_first_table_headers_and_missing_cells() {
15346        let html = concat!(
15347            "<html><body>",
15348            "<table><tr><td>ignored</td></tr></table>",
15349            "<table>",
15350            "<thead><tr><th>name</th><th>value</th><th>flag</th></tr></thead>",
15351            "<tbody>",
15352            "<tr><td>A&amp;B</td><td>1</td><td>True</td></tr>",
15353            "<tr><td>missing</td><td></td></tr>",
15354            "</tbody>",
15355            "</table>",
15356            "</body></html>",
15357        );
15358
15359        let frame = read_html_str_with_options(html, &HtmlReadOptions { table_index: 1 })
15360            .expect("read second table");
15361
15362        assert_eq!(
15363            frame
15364                .column_names()
15365                .into_iter()
15366                .map(String::as_str)
15367                .collect::<Vec<_>>(),
15368            vec!["name", "value", "flag"]
15369        );
15370        assert_eq!(
15371            frame.column("name").expect("name").values()[0],
15372            Scalar::Utf8("A&B".to_owned())
15373        );
15374        assert_eq!(
15375            frame.column("value").expect("value").values()[0],
15376            Scalar::Int64(1)
15377        );
15378        assert!(frame.column("value").expect("value").values()[1].is_missing());
15379        assert_eq!(
15380            frame.column("flag").expect("flag").values()[0],
15381            Scalar::Bool(true)
15382        );
15383        assert!(matches!(
15384            frame.column("flag").expect("flag").values()[1],
15385            Scalar::Null(NullKind::Null)
15386        ));
15387    }
15388
15389    #[test]
15390    fn html_reader_roundtrips_writer_output_as_columns() {
15391        let source = make_table_format_dataframe();
15392        let html = write_html_string(&source).expect("write html");
15393
15394        let frame = read_html_str(&html).expect("read writer html");
15395
15396        assert_eq!(
15397            frame
15398                .column_names()
15399                .into_iter()
15400                .map(String::as_str)
15401                .collect::<Vec<_>>(),
15402            vec!["Unnamed: 0", "name", "value"]
15403        );
15404        assert_eq!(
15405            frame.column("Unnamed: 0").expect("index column").values()[0],
15406            Scalar::Utf8("r&1".to_owned())
15407        );
15408        assert_eq!(
15409            frame.column("name").expect("name").values()[0],
15410            Scalar::Utf8("A|B".to_owned())
15411        );
15412        assert!(frame.column("value").expect("value").values()[0].is_missing());
15413        assert_eq!(
15414            frame.column("value").expect("value").values()[1],
15415            Scalar::Float64(2.0)
15416        );
15417    }
15418
15419    #[test]
15420    fn html_reader_path_reader_matches_string_reader() {
15421        use std::io::Write;
15422
15423        let html = "<table><tr><th>name</th></tr><tr><td>A</td></tr></table>\n";
15424        let path = std::env::temp_dir().join(format!(
15425            "fp_io_html_reader_{}_{}.html",
15426            std::process::id(),
15427            line!()
15428        ));
15429        let mut file = std::fs::OpenOptions::new()
15430            .write(true)
15431            .create_new(true)
15432            .open(&path)
15433            .expect("create html fixture");
15434        file.write_all(html.as_bytes()).expect("write html fixture");
15435
15436        let via_path = read_html(&path).expect("read path html");
15437        let via_str = read_html_str(html).expect("read string html");
15438
15439        assert_eq!(via_path.column_names(), via_str.column_names());
15440        assert_eq!(
15441            via_path.column("name").expect("path name").values(),
15442            via_str.column("name").expect("str name").values()
15443        );
15444    }
15445
15446    #[test]
15447    fn html_reader_rejects_no_table_duplicate_headers_and_wide_rows() {
15448        let err = read_html_str("<p>no table</p>").expect_err("missing table");
15449        assert!(matches!(err, IoError::Html(message) if message.contains("no table")));
15450
15451        let duplicate = "<table><tr><th>a</th><th>a</th></tr><tr><td>1</td><td>2</td></tr></table>";
15452        assert!(matches!(
15453            read_html_str(duplicate),
15454            Err(IoError::DuplicateColumnName(name)) if name == "a"
15455        ));
15456
15457        let wide = "<table><tr><th>a</th></tr><tr><td>1</td><td>2</td></tr></table>";
15458        let err = read_html_str(wide).expect_err("wide row");
15459        assert!(matches!(err, IoError::Html(message) if message.contains("row 0")));
15460    }
15461
15462    #[test]
15463    fn pickle_bytes_roundtrip_preserves_split_frame_shape() {
15464        let source = read_json_str(
15465            r#"{"columns":["name","value","flag"],"index":["r1","r2"],"data":[["alice",1,true],[null,2.5,false]]}"#,
15466            JsonOrient::Split,
15467        )
15468        .expect("source frame");
15469
15470        let bytes = write_pickle_bytes(&source).expect("write pickle bytes");
15471        assert!(!bytes.is_empty());
15472        let roundtrip = read_pickle_bytes(&bytes).expect("read pickle bytes");
15473
15474        assert_eq!(
15475            write_json_string(&roundtrip, JsonOrient::Split).expect("roundtrip json"),
15476            write_json_string(&source, JsonOrient::Split).expect("source json")
15477        );
15478    }
15479
15480    #[test]
15481    fn pickle_path_reader_matches_bytes_reader() {
15482        let source = make_table_format_dataframe();
15483        let path = std::env::temp_dir().join(format!(
15484            "fp_io_pickle_reader_{}_{}.pkl",
15485            std::process::id(),
15486            line!()
15487        ));
15488
15489        write_pickle(&source, &path).expect("write pickle path");
15490
15491        let via_path = read_pickle(&path).expect("read pickle path");
15492        let via_bytes =
15493            read_pickle_bytes(&std::fs::read(&path).expect("read pickle bytes from path"))
15494                .expect("read pickle bytes");
15495
15496        assert_eq!(
15497            write_json_string(&via_path, JsonOrient::Split).expect("path json"),
15498            write_json_string(&via_bytes, JsonOrient::Split).expect("bytes json")
15499        );
15500    }
15501
15502    #[test]
15503    fn pickle_protocol_v2_and_extension_aliases_roundtrip() {
15504        use super::DataFrameIoExt;
15505
15506        let source = make_table_format_dataframe();
15507        let options = PickleWriteOptions {
15508            protocol: PickleProtocol::V2,
15509        };
15510        let bytes = source
15511            .to_pickle_bytes_with_options(&options)
15512            .expect("trait pickle protocol v2");
15513        let roundtrip = read_pickle_bytes(&bytes).expect("read protocol v2");
15514
15515        assert_eq!(
15516            write_json_string(&roundtrip, JsonOrient::Split).expect("roundtrip json"),
15517            write_json_string(&source, JsonOrient::Split).expect("source json")
15518        );
15519        assert_eq!(
15520            source.to_pickle_bytes().expect("trait pickle bytes"),
15521            write_pickle_bytes(&source).expect("free pickle bytes")
15522        );
15523    }
15524
15525    #[test]
15526    fn series_pickle_extension_aliases_roundtrip_to_single_column_frame() {
15527        use super::SeriesIoExt;
15528
15529        let source = Series::from_values(
15530            "sales",
15531            vec!["r1".into(), "r2".into()],
15532            vec![Scalar::Int64(10), Scalar::Int64(12)],
15533        )
15534        .expect("source series");
15535
15536        let bytes = source.to_pickle_bytes().expect("series pickle bytes");
15537        let roundtrip = read_pickle_bytes(&bytes).expect("read series pickle frame");
15538        let names = roundtrip
15539            .column_names()
15540            .into_iter()
15541            .map(String::as_str)
15542            .collect::<Vec<_>>();
15543        assert_eq!(names, vec!["sales"]);
15544        assert_eq!(roundtrip.index().labels(), source.index().labels());
15545        assert_eq!(
15546            roundtrip.column("sales").expect("sales column").values(),
15547            source.values()
15548        );
15549
15550        let frame = source.to_frame(None).expect("series frame");
15551        assert_eq!(
15552            source.to_pickle_bytes().expect("trait pickle bytes"),
15553            write_pickle_bytes(&frame).expect("frame pickle bytes")
15554        );
15555
15556        let options = PickleWriteOptions {
15557            protocol: PickleProtocol::V2,
15558        };
15559        assert!(
15560            !source
15561                .to_pickle_bytes_with_options(&options)
15562                .expect("series pickle protocol v2")
15563                .is_empty()
15564        );
15565    }
15566
15567    #[test]
15568    fn series_csv_extension_aliases_preserve_default_index() {
15569        use super::SeriesIoExt;
15570
15571        let source = Series::from_values(
15572            "sales",
15573            vec!["r1".into(), "r2".into()],
15574            vec![Scalar::Int64(10), Scalar::Int64(12)],
15575        )
15576        .expect("source series");
15577
15578        let csv = source.to_csv_string().expect("series csv string");
15579        assert_eq!(csv, ",sales\nr1,10\nr2,12\n");
15580
15581        let no_index = source
15582            .to_csv_string_with_options(&CsvWriteOptions {
15583                include_index: false,
15584                ..CsvWriteOptions::default()
15585            })
15586            .expect("series csv without index");
15587        assert_eq!(no_index, "sales\n10\n12\n");
15588
15589        let path = std::env::temp_dir().join(format!(
15590            "fp_io_series_csv_{}_{}.csv",
15591            std::process::id(),
15592            line!()
15593        ));
15594        source.to_csv_file(&path).expect("series csv file");
15595        assert_eq!(
15596            std::fs::read_to_string(&path).expect("read series csv file"),
15597            csv
15598        );
15599    }
15600
15601    #[test]
15602    fn series_json_extension_aliases_use_series_orients() {
15603        use super::SeriesIoExt;
15604
15605        let source = Series::from_values(
15606            "sales",
15607            vec!["r1".into(), "r2".into()],
15608            vec![Scalar::Int64(10), Scalar::Int64(12)],
15609        )
15610        .expect("source series");
15611
15612        assert_eq!(
15613            source
15614                .to_json_string("records")
15615                .expect("series records json"),
15616            "[10,12]"
15617        );
15618
15619        let split: serde_json::Value =
15620            serde_json::from_str(&source.to_json_string("split").expect("series split json"))
15621                .expect("parse split json");
15622        assert_eq!(split["name"], "sales");
15623        assert_eq!(split["index"], serde_json::json!(["r1", "r2"]));
15624        assert_eq!(split["data"], serde_json::json!([10, 12]));
15625
15626        let path = std::env::temp_dir().join(format!(
15627            "fp_io_series_json_{}_{}.json",
15628            std::process::id(),
15629            line!()
15630        ));
15631        source
15632            .to_json_file(&path, "index")
15633            .expect("series json file");
15634        assert_eq!(
15635            std::fs::read_to_string(&path).expect("read series json file"),
15636            source.to_json("index").expect("series index json")
15637        );
15638    }
15639
15640    #[test]
15641    fn series_markdown_extension_aliases_forward_options() {
15642        use super::SeriesIoExt;
15643
15644        let source = Series::from_values(
15645            "sales",
15646            vec!["r1".into(), "r2".into()],
15647            vec![Scalar::Int64(10), Scalar::Null(NullKind::NaN)],
15648        )
15649        .expect("source series");
15650        let options = MarkdownWriteOptions {
15651            include_index: false,
15652            na_rep: "NA".to_owned(),
15653            index_label: Some("ignored".to_owned()),
15654        };
15655
15656        assert_eq!(
15657            source.to_markdown_string().expect("series markdown string"),
15658            write_markdown_string(&source.to_frame(None).expect("series frame"))
15659                .expect("frame markdown string")
15660        );
15661        assert_eq!(
15662            source
15663                .to_markdown_string_with_options(&options)
15664                .expect("series markdown options"),
15665            write_markdown_string_with_options(
15666                &source.to_frame(None).expect("series options frame"),
15667                &options,
15668            )
15669            .expect("frame markdown options")
15670        );
15671
15672        let path = std::env::temp_dir().join(format!(
15673            "fp_io_series_markdown_{}_{}.md",
15674            std::process::id(),
15675            line!()
15676        ));
15677        source
15678            .to_markdown_file_with_options(&path, &options)
15679            .expect("series markdown file");
15680        assert_eq!(
15681            std::fs::read_to_string(&path).expect("read series markdown file"),
15682            source
15683                .to_markdown_string_with_options(&options)
15684                .expect("series markdown options string")
15685        );
15686    }
15687
15688    #[test]
15689    fn series_latex_extension_aliases_forward_options() {
15690        use super::SeriesIoExt;
15691
15692        let source = Series::from_values(
15693            "sales&tax",
15694            vec!["r1".into(), "r2".into()],
15695            vec![Scalar::Utf8("a&b".into()), Scalar::Null(NullKind::NaN)],
15696        )
15697        .expect("source series");
15698        let options = LatexWriteOptions {
15699            include_index: false,
15700            na_rep: "NA".to_owned(),
15701            index_label: Some("ignored".to_owned()),
15702            escape: true,
15703        };
15704
15705        assert_eq!(
15706            source.to_latex_string().expect("series latex string"),
15707            write_latex_string(&source.to_frame(None).expect("series frame"))
15708                .expect("frame latex string")
15709        );
15710        assert_eq!(
15711            source
15712                .to_latex_string_with_options(&options)
15713                .expect("series latex options"),
15714            write_latex_string_with_options(
15715                &source.to_frame(None).expect("series options frame"),
15716                &options,
15717            )
15718            .expect("frame latex options")
15719        );
15720
15721        let path = std::env::temp_dir().join(format!(
15722            "fp_io_series_latex_{}_{}.tex",
15723            std::process::id(),
15724            line!()
15725        ));
15726        source
15727            .to_latex_file_with_options(&path, &options)
15728            .expect("series latex file");
15729        assert_eq!(
15730            std::fs::read_to_string(&path).expect("read series latex file"),
15731            source
15732                .to_latex_string_with_options(&options)
15733                .expect("series latex options string")
15734        );
15735    }
15736
15737    #[cfg(feature = "hdf5")]
15738    #[test]
15739    fn series_hdf5_extension_aliases_roundtrip_to_single_column_frame() {
15740        use super::SeriesIoExt;
15741
15742        let source = Series::from_values(
15743            "sales",
15744            vec!["r1".into(), "r2".into()],
15745            vec![Scalar::Int64(10), Scalar::Int64(12)],
15746        )
15747        .expect("source series");
15748        let expected = source.to_frame(None).expect("series frame");
15749
15750        let key_path = std::env::temp_dir().join(format!(
15751            "fp_io_series_hdf5_key_{}_{}.h5",
15752            std::process::id(),
15753            line!()
15754        ));
15755        source
15756            .to_hdf_key(&key_path, "series/data")
15757            .expect("series hdf key");
15758        assert!(
15759            read_hdf_key(&key_path, "series/data")
15760                .expect("read series hdf key")
15761                .equals(&expected)
15762        );
15763
15764        let default_path = std::env::temp_dir().join(format!(
15765            "fp_io_series_hdf5_default_{}_{}.h5",
15766            std::process::id(),
15767            line!()
15768        ));
15769        source
15770            .to_hdf_file(&default_path)
15771            .expect("series hdf default key");
15772        assert!(
15773            read_hdf(&default_path)
15774                .expect("read series hdf default")
15775                .equals(&expected)
15776        );
15777
15778        let options_path = std::env::temp_dir().join(format!(
15779            "fp_io_series_hdf5_options_{}_{}.h5",
15780            std::process::id(),
15781            line!()
15782        ));
15783        source
15784            .to_hdf_with_options(
15785                &options_path,
15786                &HdfWriteOptions {
15787                    key: "series/options".to_owned(),
15788                },
15789            )
15790            .expect("series hdf options");
15791        assert!(
15792            read_hdf_key(&options_path, "series/options")
15793                .expect("read series hdf options")
15794                .equals(&expected)
15795        );
15796    }
15797
15798    #[test]
15799    fn series_excel_extension_aliases_roundtrip_to_single_column_frame() {
15800        use super::SeriesIoExt;
15801
15802        let source = Series::from_values(
15803            "sales",
15804            vec!["r1".into(), "r2".into()],
15805            vec![Scalar::Int64(10), Scalar::Int64(12)],
15806        )
15807        .expect("source series");
15808
15809        let bytes = source.to_excel_bytes().expect("series excel bytes");
15810        let roundtrip =
15811            read_excel_bytes(&bytes, &ExcelReadOptions::default()).expect("read series excel");
15812        let names = roundtrip
15813            .column_names()
15814            .into_iter()
15815            .map(String::as_str)
15816            .collect::<Vec<_>>();
15817        assert_eq!(names, vec!["column_0", "sales"]);
15818        assert_eq!(
15819            roundtrip.column("column_0").expect("index column").values(),
15820            &[Scalar::Utf8("r1".into()), Scalar::Utf8("r2".into())]
15821        );
15822        assert_eq!(
15823            roundtrip.column("sales").expect("sales column").values(),
15824            source.values()
15825        );
15826
15827        let frame = source.to_frame(None).expect("series frame");
15828        assert_eq!(
15829            source.to_excel_bytes().expect("trait excel bytes"),
15830            write_excel_bytes(&frame).expect("frame excel bytes")
15831        );
15832
15833        let options = ExcelWriteOptions {
15834            index: false,
15835            ..ExcelWriteOptions::default()
15836        };
15837        let no_index_bytes = source
15838            .to_excel_bytes_with_options(&options)
15839            .expect("series excel index false");
15840        let no_index = read_excel_bytes(&no_index_bytes, &ExcelReadOptions::default())
15841            .expect("read no-index series excel");
15842        assert_eq!(no_index.column_names(), vec!["sales"]);
15843        assert_eq!(no_index.index().len(), source.index().len());
15844    }
15845
15846    #[test]
15847    fn pickle_reader_rejects_malformed_and_foreign_payloads() {
15848        let err = read_pickle_bytes(b"not a pickle").expect_err("malformed pickle");
15849        assert!(matches!(err, IoError::Pickle(_)));
15850
15851        let foreign = serde_pickle::to_vec(
15852            &serde_json::json!({"payload": {"columns": [], "index": [], "data": []}}),
15853            serde_pickle::SerOptions::new(),
15854        )
15855        .expect("foreign pickle");
15856        let err = read_pickle_bytes(&foreign).expect_err("foreign pickle");
15857        assert!(matches!(
15858            err,
15859            IoError::Pickle(message) if message.contains("format marker")
15860        ));
15861    }
15862
15863    #[cfg(feature = "hdf5")]
15864    #[test]
15865    fn hdf5_path_roundtrip_preserves_snapshot_frame() {
15866        let source = make_table_format_dataframe();
15867        let path = std::env::temp_dir().join(format!(
15868            "fp_io_hdf5_default_{}_{}.h5",
15869            std::process::id(),
15870            line!()
15871        ));
15872
15873        write_hdf(&source, &path).expect("write hdf default key");
15874        let roundtrip = read_hdf(&path).expect("read hdf default key");
15875
15876        assert_eq!(
15877            write_json_string(&roundtrip, JsonOrient::Split).expect("roundtrip json"),
15878            write_json_string(&source, JsonOrient::Split).expect("source json")
15879        );
15880    }
15881
15882    #[cfg(feature = "hdf5")]
15883    #[test]
15884    fn hdf5_custom_key_and_extension_aliases_roundtrip() {
15885        use super::DataFrameIoExt;
15886
15887        let source = make_test_dataframe();
15888        let free_path = std::env::temp_dir().join(format!(
15889            "fp_io_hdf5_custom_free_{}_{}.h5",
15890            std::process::id(),
15891            line!()
15892        ));
15893        let trait_path = std::env::temp_dir().join(format!(
15894            "fp_io_hdf5_custom_trait_{}_{}.h5",
15895            std::process::id(),
15896            line!()
15897        ));
15898        let default_path = std::env::temp_dir().join(format!(
15899            "fp_io_hdf5_custom_default_{}_{}.h5",
15900            std::process::id(),
15901            line!()
15902        ));
15903        let write_options = HdfWriteOptions {
15904            key: "tables/snapshot".to_owned(),
15905        };
15906
15907        write_hdf_with_options(&source, &free_path, &write_options).expect("write custom key");
15908        let roundtrip = read_hdf_with_options(
15909            &free_path,
15910            &HdfReadOptions {
15911                key: "/tables/snapshot/".to_owned(),
15912            },
15913        )
15914        .expect("read custom key with slash aliases");
15915        assert!(roundtrip.equals(&source));
15916
15917        source
15918            .to_hdf_key(&trait_path, "nested/frame")
15919            .expect("trait hdf key");
15920        assert!(
15921            read_hdf_key(&trait_path, "nested/frame")
15922                .expect("read trait hdf key")
15923                .equals(&source)
15924        );
15925
15926        source
15927            .to_hdf_file(&default_path)
15928            .expect("trait hdf default key");
15929        assert!(
15930            read_hdf(&default_path)
15931                .expect("read trait hdf default")
15932                .equals(&source)
15933        );
15934    }
15935
15936    #[cfg(feature = "hdf5")]
15937    #[test]
15938    fn hdf5_row_multiindex_roundtrip_restores_logical_row_axis() {
15939        let frame = make_row_multiindex_test_dataframe();
15940        let path = std::env::temp_dir().join(format!(
15941            "fp_io_hdf5_multiindex_{}_{}.h5",
15942            std::process::id(),
15943            line!()
15944        ));
15945
15946        write_hdf_key(&frame, &path, "axes/frame").expect("write hdf multiindex");
15947        let roundtrip = read_hdf_key(&path, "axes/frame").expect("read hdf multiindex");
15948
15949        assert!(roundtrip.equals(&frame));
15950        assert!(roundtrip.column("__index_level_0__").is_none());
15951        assert_eq!(
15952            roundtrip
15953                .row_multiindex()
15954                .expect("row multiindex should be restored")
15955                .get_level_values(0)
15956                .unwrap()
15957                .labels(),
15958            frame
15959                .row_multiindex()
15960                .expect("source row multiindex")
15961                .get_level_values(0)
15962                .unwrap()
15963                .labels()
15964        );
15965    }
15966
15967    #[cfg(feature = "hdf5")]
15968    #[test]
15969    fn hdf5_reader_rejects_invalid_keys_and_missing_payloads() {
15970        let frame = make_test_dataframe();
15971        let path = std::env::temp_dir().join(format!(
15972            "fp_io_hdf5_missing_payload_{}_{}.h5",
15973            std::process::id(),
15974            line!()
15975        ));
15976
15977        let file = hdf5::File::create(&path).expect("create hdf shell");
15978        file.create_group("frame")
15979            .expect("create empty frame group");
15980        file.flush().expect("flush hdf shell");
15981        drop(file);
15982
15983        let err = read_hdf(&path).expect_err("missing payload should fail");
15984        assert!(matches!(
15985            err,
15986            IoError::Hdf5(message) if message.contains("missing FrankenPandas payload dataset")
15987        ));
15988
15989        let err = write_hdf_key(&frame, &path, "../bad").expect_err("invalid key should fail");
15990        assert!(matches!(
15991            err,
15992            IoError::Hdf5(message) if message.contains("invalid hdf5 key")
15993        ));
15994    }
15995
15996    fn make_stata_dataframe() -> DataFrame {
15997        let mut columns = BTreeMap::new();
15998        columns.insert(
15999            "id".to_owned(),
16000            Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)])
16001                .expect("id column"),
16002        );
16003        columns.insert(
16004            "score".to_owned(),
16005            Column::from_values(vec![
16006                Scalar::Float64(1.5),
16007                Scalar::Null(NullKind::NaN),
16008                Scalar::Float64(3.25),
16009            ])
16010            .expect("score column"),
16011        );
16012        columns.insert(
16013            "flag".to_owned(),
16014            Column::from_values(vec![
16015                Scalar::Bool(true),
16016                Scalar::Bool(false),
16017                Scalar::Bool(true),
16018            ])
16019            .expect("flag column"),
16020        );
16021        columns.insert(
16022            "label".to_owned(),
16023            Column::from_values(vec![
16024                Scalar::Utf8("alpha".to_owned()),
16025                Scalar::Utf8("beta".to_owned()),
16026                Scalar::Utf8("gamma".to_owned()),
16027            ])
16028            .expect("label column"),
16029        );
16030
16031        DataFrame::new_with_column_order(
16032            Index::new(vec![
16033                IndexLabel::Utf8("row_a".to_owned()),
16034                IndexLabel::Utf8("row_b".to_owned()),
16035                IndexLabel::Utf8("row_c".to_owned()),
16036            ]),
16037            columns,
16038            vec![
16039                "id".to_owned(),
16040                "score".to_owned(),
16041                "flag".to_owned(),
16042                "label".to_owned(),
16043            ],
16044        )
16045        .expect("stata frame")
16046    }
16047
16048    #[test]
16049    fn stata_bytes_roundtrip_preserves_supported_columns() {
16050        let source = make_stata_dataframe();
16051        let bytes = write_stata_bytes(&source).expect("write stata bytes");
16052        assert!(!bytes.is_empty());
16053
16054        let roundtrip = read_stata_bytes(&bytes).expect("read stata bytes");
16055
16056        assert_eq!(
16057            roundtrip
16058                .column_names()
16059                .into_iter()
16060                .map(String::as_str)
16061                .collect::<Vec<_>>(),
16062            vec!["index", "id", "score", "flag", "label"]
16063        );
16064        assert_eq!(
16065            roundtrip.column("index").expect("index").values(),
16066            &[
16067                Scalar::Utf8("row_a".to_owned()),
16068                Scalar::Utf8("row_b".to_owned()),
16069                Scalar::Utf8("row_c".to_owned())
16070            ]
16071        );
16072        assert_eq!(
16073            roundtrip.column("id").expect("id").values(),
16074            &[Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)]
16075        );
16076        assert_eq!(
16077            roundtrip.column("score").expect("score").values(),
16078            &[
16079                Scalar::Float64(1.5),
16080                Scalar::Null(NullKind::NaN),
16081                Scalar::Float64(3.25)
16082            ]
16083        );
16084        assert_eq!(
16085            roundtrip.column("flag").expect("flag").values(),
16086            &[Scalar::Int64(1), Scalar::Int64(0), Scalar::Int64(1)]
16087        );
16088        assert_eq!(
16089            roundtrip.column("label").expect("label").values(),
16090            &[
16091                Scalar::Utf8("alpha".to_owned()),
16092                Scalar::Utf8("beta".to_owned()),
16093                Scalar::Utf8("gamma".to_owned())
16094            ]
16095        );
16096    }
16097
16098    #[test]
16099    fn stata_path_reader_matches_bytes_reader() {
16100        let source = make_stata_dataframe();
16101        let path = std::env::temp_dir().join(format!(
16102            "fp_io_stata_reader_{}_{}.dta",
16103            std::process::id(),
16104            line!()
16105        ));
16106
16107        write_stata(&source, &path).expect("write stata path");
16108
16109        let via_path = read_stata(&path).expect("read stata path");
16110        let via_bytes =
16111            read_stata_bytes(&std::fs::read(&path).expect("read stata bytes from path"))
16112                .expect("read stata bytes");
16113
16114        assert_eq!(via_path.column_names(), via_bytes.column_names());
16115        for name in via_path.column_names() {
16116            assert_eq!(
16117                via_path.column(name).expect("path column").values(),
16118                via_bytes.column(name).expect("bytes column").values()
16119            );
16120        }
16121    }
16122
16123    #[test]
16124    fn stata_extension_aliases_and_no_index_option_roundtrip() {
16125        use super::DataFrameIoExt;
16126
16127        let source = make_stata_dataframe();
16128        let options = StataWriteOptions {
16129            include_index: false,
16130            index_label: Some("ignored".to_owned()),
16131        };
16132        let bytes = source
16133            .to_stata_bytes_with_options(&options)
16134            .expect("trait stata bytes without index");
16135        let roundtrip = read_stata_bytes(&bytes).expect("read no-index stata");
16136
16137        assert_eq!(
16138            roundtrip
16139                .column_names()
16140                .into_iter()
16141                .map(String::as_str)
16142                .collect::<Vec<_>>(),
16143            vec!["id", "score", "flag", "label"]
16144        );
16145
16146        let path = std::env::temp_dir().join(format!(
16147            "fp_io_stata_trait_{}_{}.dta",
16148            std::process::id(),
16149            line!()
16150        ));
16151        source
16152            .to_stata_with_options(&path, &options)
16153            .expect("trait stata path without index");
16154        let via_path = read_stata(&path).expect("read trait stata path");
16155        assert_eq!(via_path.column_names(), roundtrip.column_names());
16156
16157        assert_eq!(
16158            source.to_stata_bytes().expect("trait stata bytes"),
16159            write_stata_bytes(&source).expect("free stata bytes")
16160        );
16161    }
16162
16163    #[test]
16164    fn stata_writer_rejects_invalid_variable_names_and_malformed_input() {
16165        let mut columns = BTreeMap::new();
16166        columns.insert(
16167            "bad-name".to_owned(),
16168            Column::from_values(vec![Scalar::Int64(1)]).expect("bad column"),
16169        );
16170        let frame = DataFrame::new_with_column_order(
16171            Index::from_i64(vec![0]),
16172            columns,
16173            vec!["bad-name".to_owned()],
16174        )
16175        .expect("frame with invalid stata column");
16176
16177        let err = write_stata_bytes(&frame).expect_err("invalid stata variable name");
16178        assert!(matches!(
16179            err,
16180            IoError::Stata(message) if message.contains("invalid Stata variable name")
16181        ));
16182
16183        let source = make_stata_dataframe();
16184        let err = write_stata_bytes_with_options(
16185            &source,
16186            &StataWriteOptions {
16187                include_index: true,
16188                index_label: Some("1bad".to_owned()),
16189            },
16190        )
16191        .expect_err("invalid index variable name");
16192        assert!(matches!(
16193            err,
16194            IoError::Stata(message) if message.contains("first character")
16195        ));
16196
16197        let err = read_stata_bytes(b"not a dta").expect_err("malformed stata");
16198        assert!(matches!(err, IoError::Stata(_)));
16199    }
16200
16201    #[test]
16202    fn xml_writer_defaults_to_index_and_escapes_values() {
16203        let frame = make_table_format_dataframe();
16204
16205        let out = write_xml_string(&frame).expect("xml");
16206
16207        assert_eq!(
16208            out,
16209            concat!(
16210                "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n",
16211                "<data>\n",
16212                "  <row>\n",
16213                "    <row>r&amp;1</row>\n",
16214                "    <name>A|B</name>\n",
16215                "    <value/>\n",
16216                "  </row>\n",
16217                "  <row>\n",
16218                "    <row>r_2</row>\n",
16219                "    <name>under_score</name>\n",
16220                "    <value>2.0</value>\n",
16221                "  </row>\n",
16222                "</data>\n",
16223            )
16224        );
16225    }
16226
16227    #[test]
16228    fn xml_writer_options_can_omit_index_and_reject_bad_names() {
16229        let frame = make_table_format_dataframe();
16230
16231        let out = write_xml_string_with_options(
16232            &frame,
16233            &XmlWriteOptions {
16234                include_index: false,
16235                root_name: "records".to_owned(),
16236                row_name: "entry".to_owned(),
16237                index_label: Some("ignored".to_owned()),
16238            },
16239        )
16240        .expect("xml");
16241
16242        assert_eq!(
16243            out,
16244            concat!(
16245                "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n",
16246                "<records>\n",
16247                "  <entry>\n",
16248                "    <name>A|B</name>\n",
16249                "    <value/>\n",
16250                "  </entry>\n",
16251                "  <entry>\n",
16252                "    <name>under_score</name>\n",
16253                "    <value>2.0</value>\n",
16254                "  </entry>\n",
16255                "</records>\n",
16256            )
16257        );
16258
16259        let err = write_xml_string_with_options(
16260            &frame,
16261            &XmlWriteOptions {
16262                root_name: "bad name".to_owned(),
16263                ..Default::default()
16264            },
16265        )
16266        .expect_err("invalid xml name");
16267        assert!(matches!(err, IoError::Xml(message) if message.contains("bad name")));
16268    }
16269
16270    #[test]
16271    fn xml_writer_escapes_text_like_pandas_etree() {
16272        let mut columns = BTreeMap::new();
16273        columns.insert(
16274            "name".to_owned(),
16275            Column::from_values(vec![Scalar::Utf8(
16276                "A&B <tag> \"quote\" it's\r\nnext".to_owned(),
16277            )])
16278            .expect("name column"),
16279        );
16280        let frame = DataFrame::new_with_column_order(
16281            Index::new(vec![IndexLabel::Utf8("idx".to_owned())]),
16282            columns,
16283            vec!["name".to_owned()],
16284        )
16285        .expect("xml escape frame");
16286
16287        assert_eq!(
16288            write_xml_string_with_options(
16289                &frame,
16290                &XmlWriteOptions {
16291                    include_index: false,
16292                    ..Default::default()
16293                },
16294            )
16295            .expect("xml"),
16296            concat!(
16297                "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n",
16298                "<data>\n",
16299                "  <row>\n",
16300                "    <name>A&amp;B &lt;tag&gt; \"quote\" it's\n",
16301                "next</name>\n",
16302                "  </row>\n",
16303                "</data>\n",
16304            )
16305        );
16306    }
16307
16308    #[test]
16309    fn xml_writer_file_output_and_extension_aliases_match_free_functions() {
16310        use super::DataFrameIoExt;
16311
16312        let frame = make_table_format_dataframe();
16313        let path = std::env::temp_dir().join(format!(
16314            "fp_io_xml_writer_{}_{}.xml",
16315            std::process::id(),
16316            line!()
16317        ));
16318
16319        write_xml(&frame, &path).expect("write xml");
16320        assert_eq!(
16321            std::fs::read_to_string(&path).expect("read xml"),
16322            write_xml_string(&frame).expect("xml string")
16323        );
16324        assert_eq!(
16325            frame.to_xml_string().expect("trait xml string"),
16326            write_xml_string(&frame).expect("free xml string")
16327        );
16328
16329        let trait_path = std::env::temp_dir().join(format!(
16330            "fp_io_xml_writer_trait_alias_{}_{}.xml",
16331            std::process::id(),
16332            line!()
16333        ));
16334        frame.to_xml(&trait_path).expect("trait xml alias");
16335        assert_eq!(
16336            std::fs::read_to_string(&trait_path).expect("read trait xml alias"),
16337            write_xml_string(&frame).expect("free xml string")
16338        );
16339
16340        let no_index_options = XmlWriteOptions {
16341            include_index: false,
16342            ..Default::default()
16343        };
16344        let no_index_path = std::env::temp_dir().join(format!(
16345            "fp_io_xml_writer_no_index_{}_{}.xml",
16346            std::process::id(),
16347            line!()
16348        ));
16349        frame
16350            .to_xml_file_with_options(&no_index_path, &no_index_options)
16351            .expect("trait xml file");
16352        assert_eq!(
16353            std::fs::read_to_string(&no_index_path).expect("read trait xml"),
16354            write_xml_string_with_options(&frame, &no_index_options).expect("free xml options")
16355        );
16356    }
16357
16358    #[test]
16359    fn xml_reader_parses_pandas_row_shape_and_empty_values() {
16360        let xml = concat!(
16361            "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n",
16362            "<data>\n",
16363            "  <row>\n",
16364            "    <index>0</index>\n",
16365            "    <a>1</a>\n",
16366            "    <b/>\n",
16367            "  </row>\n",
16368            "  <row>\n",
16369            "    <index>1</index>\n",
16370            "    <a>2.5</a>\n",
16371            "    <b>x</b>\n",
16372            "  </row>\n",
16373            "</data>\n",
16374        );
16375
16376        let frame = read_xml_str(xml).expect("read xml");
16377
16378        assert_eq!(
16379            frame
16380                .column_names()
16381                .into_iter()
16382                .map(String::as_str)
16383                .collect::<Vec<_>>(),
16384            vec!["index", "a", "b"]
16385        );
16386        assert_eq!(
16387            frame.index().labels(),
16388            &[IndexLabel::Int64(0), IndexLabel::Int64(1)]
16389        );
16390        assert_eq!(
16391            frame.column("index").expect("index").values()[0],
16392            Scalar::Int64(0)
16393        );
16394        assert_eq!(
16395            frame.column("a").expect("a").values()[1],
16396            Scalar::Float64(2.5)
16397        );
16398        assert!(matches!(
16399            frame.column("b").expect("b").values()[0],
16400            Scalar::Null(NullKind::Null)
16401        ));
16402        assert_eq!(
16403            frame.column("b").expect("b").values()[1],
16404            Scalar::Utf8("x".to_owned())
16405        );
16406    }
16407
16408    #[test]
16409    fn xml_reader_roundtrips_writer_output_as_columns() {
16410        let source = make_table_format_dataframe();
16411        let xml = write_xml_string(&source).expect("write xml");
16412
16413        let frame = read_xml_str(&xml).expect("read writer xml");
16414
16415        assert_eq!(
16416            frame
16417                .column_names()
16418                .into_iter()
16419                .map(String::as_str)
16420                .collect::<Vec<_>>(),
16421            vec!["row", "name", "value"]
16422        );
16423        assert_eq!(
16424            frame.column("row").expect("row").values()[0],
16425            Scalar::Utf8("r&1".to_owned())
16426        );
16427        assert_eq!(
16428            frame.column("name").expect("name").values()[0],
16429            Scalar::Utf8("A|B".to_owned())
16430        );
16431        assert!(frame.column("value").expect("value").values()[0].is_missing());
16432        assert_eq!(
16433            frame.column("value").expect("value").values()[1],
16434            Scalar::Float64(2.0)
16435        );
16436    }
16437
16438    #[test]
16439    fn xml_reader_unescapes_text_and_supports_custom_row_names() {
16440        let xml = concat!(
16441            "<records>\n",
16442            "  <entry><name>A&amp;B &lt;tag&gt; \"quote\" it's</name><flag>True</flag></entry>\n",
16443            "  <entry><name>line\n",
16444            "next</name><flag>false</flag></entry>\n",
16445            "</records>\n",
16446        );
16447
16448        let frame = read_xml_str_with_options(
16449            xml,
16450            &XmlReadOptions {
16451                row_name: "entry".to_owned(),
16452            },
16453        )
16454        .expect("read custom xml");
16455
16456        assert_eq!(
16457            frame.column("name").expect("name").values()[0],
16458            Scalar::Utf8("A&B <tag> \"quote\" it's".to_owned())
16459        );
16460        assert_eq!(
16461            frame.column("name").expect("name").values()[1],
16462            Scalar::Utf8("line\nnext".to_owned())
16463        );
16464        assert_eq!(
16465            frame.column("flag").expect("flag").values()[0],
16466            Scalar::Bool(true)
16467        );
16468        assert_eq!(
16469            frame.column("flag").expect("flag").values()[1],
16470            Scalar::Bool(false)
16471        );
16472    }
16473
16474    #[test]
16475    fn xml_reader_path_reader_matches_string_reader() {
16476        use std::io::Write;
16477
16478        let xml = "<data><row><name>A</name></row></data>\n";
16479        let path = std::env::temp_dir().join(format!(
16480            "fp_io_xml_reader_{}_{}.xml",
16481            std::process::id(),
16482            line!()
16483        ));
16484        let mut file = std::fs::OpenOptions::new()
16485            .write(true)
16486            .create_new(true)
16487            .open(&path)
16488            .expect("create xml fixture");
16489        file.write_all(xml.as_bytes()).expect("write xml fixture");
16490
16491        let via_path = read_xml(&path).expect("read path xml");
16492        let via_str = read_xml_str(xml).expect("read string xml");
16493
16494        assert_eq!(via_path.column_names(), via_str.column_names());
16495        assert_eq!(
16496            via_path.column("name").expect("path name").values(),
16497            via_str.column("name").expect("str name").values()
16498        );
16499    }
16500
16501    #[test]
16502    fn xml_reader_rejects_malformed_nested_and_duplicate_fields() {
16503        let malformed = "<data><row><name>A</row></data>";
16504        assert!(matches!(read_xml_str(malformed), Err(IoError::Xml(_))));
16505
16506        let nested = "<data><row><name><inner>A</inner></name></row></data>";
16507        let err = read_xml_str(nested).expect_err("nested field error");
16508        assert!(matches!(err, IoError::Xml(message) if message.contains("nested xml element")));
16509
16510        let duplicate = "<data><row><name>A</name><name>B</name></row></data>";
16511        let err = read_xml_str(duplicate).expect_err("duplicate field error");
16512        assert!(matches!(err, IoError::Xml(message) if message.contains("duplicate xml field")));
16513    }
16514
16515    // === AG-07-T: CSV Parser Optimization Tests ===
16516
16517    #[test]
16518    fn test_csv_vec_based_column_order() {
16519        // Verify Vec-based parser preserves header-to-data mapping exactly.
16520        // BTreeMap sorts alphabetically, so we use alpha-ordered headers.
16521        let input = "alpha,bravo,charlie\n1,2,3\n4,5,6\n";
16522        let frame = read_csv_str(input).expect("parse");
16523        let keys: Vec<&String> = frame.columns().keys().collect();
16524        assert_eq!(keys, &["alpha", "bravo", "charlie"]);
16525        assert_eq!(frame.column("alpha").unwrap().values()[0], Scalar::Int64(1));
16526        assert_eq!(frame.column("bravo").unwrap().values()[0], Scalar::Int64(2));
16527        assert_eq!(
16528            frame.column("charlie").unwrap().values()[1],
16529            Scalar::Int64(6)
16530        );
16531        eprintln!("[TEST] test_csv_vec_based_column_order | rows=2 cols=3 parse_ok=true | PASS");
16532    }
16533
16534    #[test]
16535    fn read_csv_object_fallback_preserves_original_text() {
16536        // pandas does column-level inference: when a column falls back to object
16537        // dtype, every non-NA cell keeps its VERBATIM source text. A bool-like
16538        // token in non-canonical case ("true") or a zero-padded number ("01")
16539        // must survive unchanged once the column is object. Verified vs live
16540        // pandas 2.2.3: read_csv('c\ntrue\nfalse\nmaybe\n')['c'] is
16541        // ['true','false','maybe'] (object), and '01'/'02' stay '01'/'02'.
16542        let cases: &[(&str, &str)] = &[
16543            // Uniform native columns are unaffected.
16544            ("c\n1\n2\n3\n", "c\n1\n2\n3\n"),
16545            ("c\ntrue\nfalse\n", "c\nTrue\nFalse\n"), // pure bool -> bool dtype
16546            // Object fallbacks keep original literals.
16547            ("c\n1\n2\nabc\n", "c\n1\n2\nabc\n"),
16548            ("c\ntrue\nfalse\nmaybe\n", "c\ntrue\nfalse\nmaybe\n"),
16549            ("c\nTrue\nFalse\nmaybe\n", "c\nTrue\nFalse\nmaybe\n"),
16550            ("c\n01\n02\nabc\n", "c\n01\n02\nabc\n"),
16551        ];
16552        for (input, expected_csv) in cases {
16553            let frame = read_csv_str(input).expect("read");
16554            let out = write_csv_string(&frame).expect("write");
16555            assert_eq!(
16556                &out, expected_csv,
16557                "round-trip mismatch for input {input:?}"
16558            );
16559        }
16560    }
16561
16562    #[test]
16563    fn read_csv_typed_numeric_fast_path_promotes_in_one_pass() {
16564        let input = "i,f\n1,0\n2,0.5\n3,1.25\n";
16565        let headers = vec!["i".to_owned(), "f".to_owned()];
16566
16567        let fast = super::try_read_csv_str_typed_numeric(input, &headers)
16568            .expect("typed parse")
16569            .expect("numeric fast path");
16570        assert_eq!(fast.column("i").expect("i").dtype(), DType::Int64);
16571        assert_eq!(fast.column("f").expect("f").dtype(), DType::Float64);
16572        assert_eq!(fast.column("i").expect("i").values()[2], Scalar::Int64(3));
16573        assert_eq!(
16574            fast.column("f").expect("f").values()[2],
16575            Scalar::Float64(1.25)
16576        );
16577
16578        let object_input = "c\n01\nabc\n";
16579        let object_headers = vec!["c".to_owned()];
16580        assert!(
16581            super::try_read_csv_str_typed_numeric(object_input, &object_headers)
16582                .expect("object probe")
16583                .is_none()
16584        );
16585        let object_frame = read_csv_str(object_input).expect("fallback read");
16586        assert_eq!(object_frame.index().int64_unit_range_labels(), Some((0, 2)));
16587        assert_eq!(
16588            write_csv_string(&object_frame).expect("fallback write"),
16589            object_input
16590        );
16591    }
16592
16593    #[test]
16594    fn read_csv_simple_typed_numeric_fast_path_builds_typed_columns() {
16595        let input = "i,f\n1,0\n2,0.5\n3,1.25\n";
16596        let headers = vec!["i".to_owned(), "f".to_owned()];
16597
16598        let fast = super::try_read_csv_str_simple_typed_numeric(input, &headers)
16599            .expect("simple typed parse")
16600            .expect("simple numeric fast path");
16601
16602        assert_eq!(fast.column("i").expect("i").dtype(), DType::Int64);
16603        assert_eq!(fast.column("f").expect("f").dtype(), DType::Float64);
16604        assert_eq!(fast.index().int64_unit_range_labels(), Some((0, 3)));
16605        assert_eq!(fast.index().labels()[2], IndexLabel::Int64(2));
16606        assert_eq!(fast.column("i").expect("i").values()[2], Scalar::Int64(3));
16607        assert_eq!(
16608            fast.column("f").expect("f").values()[2],
16609            Scalar::Float64(1.25)
16610        );
16611    }
16612
16613    #[test]
16614    fn read_csv_mixed_quoted_unquoted_numeric_infers_numeric_3gen4() {
16615        // br-frankenpandas-3gen4: quoting is per-field CSV syntax stripped before
16616        // type inference, so a column mixing quoted + unquoted numbers still
16617        // infers a numeric dtype (pandas parity).
16618        let int_col = read_csv_str("x\n1\n\"2\"\n3\n").expect("read int");
16619        let xi = int_col.column("x").expect("x");
16620        assert_eq!(
16621            xi.dtype(),
16622            DType::Int64,
16623            "mixed quoted/unquoted ints -> Int64"
16624        );
16625        assert_eq!(
16626            xi.values(),
16627            &[Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)]
16628        );
16629
16630        // Mixed int + quoted float -> Float64 (one float promotes the column).
16631        let float_col = read_csv_str("y\n1\n\"2.5\"\n3\n").expect("read float");
16632        let yf = float_col.column("y").expect("y");
16633        assert_eq!(
16634            yf.dtype(),
16635            DType::Float64,
16636            "mixed int + quoted float -> Float64"
16637        );
16638        assert_eq!(
16639            yf.values(),
16640            &[
16641                Scalar::Float64(1.0),
16642                Scalar::Float64(2.5),
16643                Scalar::Float64(3.0)
16644            ]
16645        );
16646    }
16647
16648    #[test]
16649    fn read_csv_simple_typed_numeric_fast_path_rejects_quoted_fields() {
16650        let input = "x\n\"1.5\"\n";
16651        let headers = vec!["x".to_owned()];
16652
16653        assert!(
16654            super::try_read_csv_str_simple_typed_numeric(input, &headers)
16655                .expect("simple probe")
16656                .is_none()
16657        );
16658
16659        let frame = read_csv_str(input).expect("fallback read");
16660        assert_eq!(frame.column("x").expect("x").dtype(), DType::Float64);
16661        assert_eq!(
16662            frame.column("x").expect("x").values(),
16663            &[Scalar::Float64(1.5)]
16664        );
16665    }
16666
16667    #[test]
16668    fn read_csv_simple_typed_numeric_fast_path_accepts_crlf_rows() {
16669        let input = "i,f\n1,0\r\n2,0.5\r\n";
16670        let headers = vec!["i".to_owned(), "f".to_owned()];
16671
16672        let fast = super::try_read_csv_str_simple_typed_numeric(input, &headers)
16673            .expect("simple typed parse")
16674            .expect("simple numeric fast path");
16675
16676        assert_eq!(fast.len(), 2);
16677        assert_eq!(fast.column("i").expect("i").values()[1], Scalar::Int64(2));
16678        assert_eq!(
16679            fast.column("f").expect("f").values()[1],
16680            Scalar::Float64(0.5)
16681        );
16682    }
16683
16684    #[test]
16685    fn read_csv_simple_parallel_chunks_preserve_order_and_promotion() {
16686        use std::fmt::Write as _;
16687
16688        let headers = vec!["i".to_owned(), "f".to_owned()];
16689        let mut data = String::new();
16690        for row in 0..32 {
16691            let float_value = row as f64 * 0.25;
16692            writeln!(data, "{row},{float_value}").expect("write row");
16693        }
16694
16695        let (columns, row_count) =
16696            super::parse_simple_numeric_csv_parallel_chunks(data.as_bytes(), headers.len(), 3)
16697                .expect("parallel chunk parse");
16698        let frame = super::build_typed_numeric_csv_frame(&headers, columns, row_count)
16699            .expect("frame build");
16700
16701        assert_eq!(frame.len(), 32);
16702        assert_eq!(frame.column("i").expect("i").dtype(), DType::Int64);
16703        assert_eq!(frame.column("f").expect("f").dtype(), DType::Float64);
16704        assert_eq!(frame.column("i").expect("i").values()[0], Scalar::Int64(0));
16705        assert_eq!(
16706            frame.column("i").expect("i").values()[31],
16707            Scalar::Int64(31)
16708        );
16709        assert_eq!(
16710            frame.column("f").expect("f").values()[31],
16711            Scalar::Float64(7.75)
16712        );
16713    }
16714
16715    #[test]
16716    fn read_csv_typed_numeric_fast_path_rejects_non_all_valid_numeric_semantics() {
16717        let headers = vec!["x".to_owned()];
16718        for input in [
16719            "x\nNaN\n1.0\n",
16720            "x\nNAN\n1.0\n",
16721            "x\n+NaN\n1.0\n",
16722            "x\n NaN \n1.0\n",
16723            "x\n\"NAN\"\n1.0\n",
16724            "x\ntrue\nfalse\n",
16725            "x\n \n1\n",
16726        ] {
16727            assert!(
16728                super::try_read_csv_str_typed_numeric(input, &headers)
16729                    .expect("probe")
16730                    .is_none(),
16731                "fast path must reject {input:?}"
16732            );
16733        }
16734
16735        let nan_frame = read_csv_str("x\nNaN\n1.0\n").expect("fallback nan");
16736        assert_eq!(
16737            nan_frame.column("x").expect("x").values(),
16738            &[Scalar::Null(NullKind::NaN), Scalar::Float64(1.0)]
16739        );
16740
16741        let bool_frame = read_csv_str("x\ntrue\nfalse\n").expect("fallback bool");
16742        assert_eq!(
16743            bool_frame.column("x").expect("x").values(),
16744            &[Scalar::Bool(true), Scalar::Bool(false)]
16745        );
16746
16747        let padded_nan_frame = read_csv_str("x\n NaN \n1.0\n").expect("fallback padded nan");
16748        let padded_nan_column = padded_nan_frame.column("x").expect("x");
16749        assert!(padded_nan_column.has_nulls());
16750        assert!(!padded_nan_column.validity().get(0));
16751        assert!(padded_nan_column.values()[0].is_missing());
16752    }
16753
16754    #[test]
16755    fn read_csv_typed_numeric_fast_path_keeps_all_valid_float_edges() {
16756        let input = "x\n-0.0\ninf\n-inf\n1\n";
16757        let headers = vec!["x".to_owned()];
16758        let frame = super::try_read_csv_str_typed_numeric(input, &headers)
16759            .expect("typed parse")
16760            .expect("numeric fast path");
16761        let column = frame.column("x").expect("x");
16762
16763        assert_eq!(column.dtype(), DType::Float64);
16764        assert!(!column.has_nulls());
16765        assert!(column.validity().all());
16766        let values = column.values();
16767        assert_eq!(
16768            values,
16769            &[
16770                Scalar::Float64(-0.0),
16771                Scalar::Float64(f64::INFINITY),
16772                Scalar::Float64(f64::NEG_INFINITY),
16773                Scalar::Float64(1.0)
16774            ]
16775        );
16776        let negative_zero_bits = match values[0] {
16777            Scalar::Float64(value) => Some(value.to_bits()),
16778            _ => None,
16779        };
16780        assert_eq!(negative_zero_bits, Some((-0.0f64).to_bits()));
16781    }
16782
16783    #[test]
16784    fn read_csv_typed_numeric_fast_path_preserves_ragged_row_errors() {
16785        let long_row = "a,b\n1,2,3\n";
16786        let err = read_csv_str(long_row).expect_err("long row must reject");
16787        assert!(matches!(err, IoError::Csv(_)), "got {err:?}");
16788    }
16789
16790    #[test]
16791    fn to_csv_datetime_is_column_uniform_like_pandas() {
16792        // pandas to_csv renders a datetime column with ONE format: date-only
16793        // when all values are midnight, else YYYY-MM-DD HH:MM:SS with a
16794        // sub-second suffix sized to the column's finest resolution. Verified
16795        // vs live pandas 2.2.3. (Previously format_datetime_ns dropped the
16796        // sub-second component and always wrote 00:00:00.)
16797        fn dt_frame(nanos: &[i64]) -> DataFrame {
16798            let values: Vec<Scalar> = nanos.iter().map(|&n| Scalar::Datetime64(n)).collect();
16799            let col = Column::new(DType::Datetime64, values).expect("col");
16800            let mut cols = BTreeMap::new();
16801            cols.insert("d".to_string(), col);
16802            let index = Index::from_i64((0..nanos.len() as i64).collect());
16803            DataFrame::new_with_column_order(index, cols, vec!["d".to_string()]).expect("frame")
16804        }
16805        const MIDNIGHT_JAN1: i64 = 1_577_836_800_000_000_000; // 2020-01-01 00:00:00Z
16806        const MIDNIGHT_JAN2: i64 = 1_577_923_200_000_000_000; // 2020-01-02 00:00:00Z
16807        const JAN2_0300: i64 = 1_577_934_000_000_000_000; // 2020-01-02 03:00:00Z
16808        const JAN1_HALF: i64 = 1_577_836_800_500_000_000; // 2020-01-01 00:00:00.5Z
16809
16810        // All midnight -> date only.
16811        assert_eq!(
16812            write_csv_string(&dt_frame(&[MIDNIGHT_JAN1, MIDNIGHT_JAN2])).expect("w"),
16813            "d\n2020-01-01\n2020-01-02\n"
16814        );
16815        // Sub-second present -> whole column gets .fff (millis), incl. .000.
16816        assert_eq!(
16817            write_csv_string(&dt_frame(&[JAN1_HALF, MIDNIGHT_JAN1])).expect("w"),
16818            "d\n2020-01-01 00:00:00.500\n2020-01-01 00:00:00.000\n"
16819        );
16820        // Time present, no sub-second -> HH:MM:SS for all (midnight -> 00:00:00).
16821        assert_eq!(
16822            write_csv_string(&dt_frame(&[JAN2_0300, MIDNIGHT_JAN1])).expect("w"),
16823            "d\n2020-01-02 03:00:00\n2020-01-01 00:00:00\n"
16824        );
16825        // NaT in an otherwise date-only column -> date only, NaT -> quoted "".
16826        assert_eq!(
16827            write_csv_string(&dt_frame(&[MIDNIGHT_JAN1, i64::MIN])).expect("w"),
16828            "d\n2020-01-01\n\"\"\n"
16829        );
16830    }
16831
16832    #[test]
16833    #[ignore = "foreground release A/B harness"]
16834    fn datetime_csv_format_raw_nanos_ab_vrflh() {
16835        const ROWS: usize = 131_072;
16836        const BLOCKS: usize = 5;
16837        const BASE: i64 = 1_577_836_800_000_000_000;
16838
16839        fn former(column: &Column) -> super::DatetimeCsvFormat {
16840            super::datetime_csv_format_from_nanos(column.values().iter().filter_map(|value| {
16841                let Scalar::Datetime64(nanos) = value else {
16842                    return None;
16843                };
16844                Some(*nanos)
16845            }))
16846        }
16847
16848        fn elapsed(nanos: &[i64], use_candidate: bool) -> (u128, super::DatetimeCsvFormat) {
16849            let column = Column::from_datetime64_values(nanos.to_vec());
16850            let started = std::time::Instant::now();
16851            let format = if use_candidate {
16852                super::datetime_csv_format(&column)
16853            } else {
16854                former(&column)
16855            };
16856            let elapsed = started.elapsed().as_nanos();
16857            std::hint::black_box((format.date_only, format.subsec_digits));
16858            (elapsed, format)
16859        }
16860
16861        fn median(mut samples: Vec<u128>) -> u128 {
16862            samples.sort_unstable();
16863            samples[samples.len() / 2]
16864        }
16865
16866        let mut nanos = (0..ROWS)
16867            .map(|row| BASE + row as i64 * 37_000_000_000)
16868            .collect::<Vec<_>>();
16869        nanos[ROWS / 3] += 500_000_000;
16870        nanos[ROWS - 1] = Timestamp::NAT;
16871
16872        let (_, former_format) = elapsed(&nanos, false);
16873        let (_, candidate_format) = elapsed(&nanos, true);
16874        assert_eq!(candidate_format.date_only, former_format.date_only);
16875        assert_eq!(candidate_format.subsec_digits, former_format.subsec_digits);
16876
16877        let mut former_samples = Vec::with_capacity(BLOCKS * 2);
16878        let mut candidate_samples = Vec::with_capacity(BLOCKS * 2);
16879        for block in 0..BLOCKS {
16880            let order = if block % 2 == 0 {
16881                [false, true, true, false]
16882            } else {
16883                [true, false, false, true]
16884            };
16885            for use_candidate in order {
16886                let (elapsed_ns, format) = elapsed(&nanos, use_candidate);
16887                assert_eq!(format.date_only, former_format.date_only);
16888                assert_eq!(format.subsec_digits, former_format.subsec_digits);
16889                if use_candidate {
16890                    candidate_samples.push(elapsed_ns);
16891                } else {
16892                    former_samples.push(elapsed_ns);
16893                }
16894            }
16895        }
16896
16897        let former_ns = median(former_samples);
16898        let candidate_ns = median(candidate_samples);
16899        println!(
16900            "DATETIME_CSV_FORMAT_SCAN_AB rows={ROWS} former_ns={former_ns} candidate_ns={candidate_ns} speedup={:.6}",
16901            former_ns as f64 / candidate_ns as f64
16902        );
16903    }
16904
16905    #[test]
16906    fn to_csv_datetime_index_is_column_uniform_like_pandas() {
16907        use super::{CsvWriteOptions, write_csv_string_with_options};
16908        // A DatetimeIndex written with index=True follows the same column-
16909        // uniform rule as a datetime column. Verified vs live pandas 2.2.3.
16910        fn dt_index_frame(nanos: &[i64]) -> DataFrame {
16911            let labels: Vec<IndexLabel> =
16912                nanos.iter().map(|&n| IndexLabel::Datetime64(n)).collect();
16913            let index = Index::new(labels);
16914            let values: Vec<Scalar> = (0..nanos.len() as i64).map(Scalar::Int64).collect();
16915            let col = Column::new(DType::Int64, values).expect("col");
16916            let mut cols = BTreeMap::new();
16917            cols.insert("v".to_string(), col);
16918            DataFrame::new_with_column_order(index, cols, vec!["v".to_string()]).expect("frame")
16919        }
16920        let opts = CsvWriteOptions {
16921            include_index: true,
16922            ..Default::default()
16923        };
16924        // All midnight -> date only.
16925        assert_eq!(
16926            write_csv_string_with_options(
16927                &dt_index_frame(&[1_577_836_800_000_000_000, 1_577_923_200_000_000_000]),
16928                &opts
16929            )
16930            .expect("w"),
16931            ",v\n2020-01-01,0\n2020-01-02,1\n"
16932        );
16933        // Sub-second (ms) -> .fff on every label.
16934        assert_eq!(
16935            write_csv_string_with_options(
16936                &dt_index_frame(&[1_577_836_800_500_000_000, 1_577_836_800_250_000_000]),
16937                &opts
16938            )
16939            .expect("w"),
16940            ",v\n2020-01-01 00:00:00.500,0\n2020-01-01 00:00:00.250,1\n"
16941        );
16942    }
16943
16944    #[test]
16945    fn to_json_nat_index_label_is_null_not_sentinel_epoch_natjson() {
16946        use super::{JsonOrient, write_json_string};
16947        // A DatetimeIndex containing NaT (the i64::MIN sentinel): the index label
16948        // must serialize as JSON null, NOT i64::MIN/1e6 (-9223372036854775).
16949        let labels = vec![
16950            IndexLabel::Datetime64(1_577_836_800_000_000_000), // 2020-01-01
16951            IndexLabel::Datetime64(i64::MIN),                  // NaT
16952        ];
16953        let index = Index::new(labels);
16954        let col = Column::new(DType::Int64, vec![Scalar::Int64(7), Scalar::Int64(9)]).expect("col");
16955        let mut cols = BTreeMap::new();
16956        cols.insert("v".to_string(), col);
16957        let frame =
16958            DataFrame::new_with_column_order(index, cols, vec!["v".to_string()]).expect("frame");
16959
16960        // The garbage sentinel epoch must never appear in any orient.
16961        for orient in [
16962            JsonOrient::Split,
16963            JsonOrient::Records,
16964            JsonOrient::Columns,
16965            JsonOrient::Index,
16966        ] {
16967            let out = write_json_string(&frame, orient).expect("json");
16968            assert!(
16969                !out.contains("-9223372036854775"),
16970                "orient {orient:?} leaked the NaT sentinel epoch: {out}"
16971            );
16972        }
16973        // Split orient lists the index as values -> NaT becomes literal null.
16974        let split = write_json_string(&frame, JsonOrient::Split).expect("json");
16975        assert!(
16976            split.contains("null"),
16977            "NaT index label should be null in split orient: {split}"
16978        );
16979    }
16980
16981    #[test]
16982    fn index_label_to_scalar_value_preserves_temporal_dtype_mdt64() {
16983        // Materializing a MultiIndex level into a column must keep the level's
16984        // dtype: a Datetime64 label stays a typed Datetime64 scalar (like the
16985        // Timedelta64 arm), NOT a downgraded Utf8 string — otherwise a datetime
16986        // level becomes an object column (pandas keeps datetime64) and serializes
16987        // inconsistently with a single DatetimeIndex.
16988        assert_eq!(
16989            super::index_label_to_scalar_value(&IndexLabel::Datetime64(1_577_836_800_000_000_000)),
16990            Scalar::Datetime64(1_577_836_800_000_000_000)
16991        );
16992        assert_eq!(
16993            super::index_label_to_scalar_value(&IndexLabel::Timedelta64(86_400_000_000_000)),
16994            Scalar::Timedelta64(86_400_000_000_000)
16995        );
16996        // NaT sentinel stays the typed Datetime64 NaT (downstream writers map it
16997        // to na_rep / null), not the "NaT" literal a Utf8 downgrade produced.
16998        assert_eq!(
16999            super::index_label_to_scalar_value(&IndexLabel::Datetime64(i64::MIN)),
17000            Scalar::Datetime64(i64::MIN)
17001        );
17002    }
17003
17004    #[test]
17005    fn table_writers_render_temporal_nat_dtype_aware_tblnat() {
17006        // Verified vs pandas 2.2.3:
17007        //   to_string/to_markdown/to_html: temporal NaT -> "NaT", float NaN -> na_rep.
17008        //   to_latex:                       temporal NaT -> na_rep, float NaN -> na_rep.
17009        let na = "NaN";
17010        // markdown/string family (scalar_to_table_with_na): NaT literal, NaN -> na_rep.
17011        assert_eq!(
17012            super::scalar_to_table_with_na(&Scalar::Float64(f64::NAN), na),
17013            na
17014        );
17015        assert_eq!(
17016            super::scalar_to_table_with_na(&Scalar::Timedelta64(i64::MIN), na),
17017            "NaT"
17018        );
17019        assert_eq!(
17020            super::scalar_to_table_with_na(&Scalar::Datetime64(i64::MIN), na),
17021            "NaT"
17022        );
17023        assert_eq!(
17024            super::scalar_to_table_with_na(
17025                &Scalar::Period(fp_types::Period::new(i64::MIN, fp_types::PeriodFreq::Daily)),
17026                na
17027            ),
17028            "NaT"
17029        );
17030        // latex (scalar_to_latex_cell): ALL missing collapse to na_rep.
17031        assert_eq!(
17032            super::scalar_to_latex_cell(&Scalar::Float64(f64::NAN), na),
17033            na
17034        );
17035        assert_eq!(
17036            super::scalar_to_latex_cell(&Scalar::Timedelta64(i64::MIN), na),
17037            na
17038        );
17039        assert_eq!(
17040            super::scalar_to_latex_cell(&Scalar::Datetime64(i64::MIN), na),
17041            na
17042        );
17043        assert_eq!(
17044            super::scalar_to_latex_cell(
17045                &Scalar::Period(fp_types::Period::new(i64::MIN, fp_types::PeriodFreq::Daily)),
17046                na
17047            ),
17048            na
17049        );
17050        // A non-NaT datetime still renders normally (sanity).
17051        assert_eq!(
17052            super::scalar_to_table_with_na(&Scalar::Datetime64(1_577_836_800_000_000_000), na),
17053            "2020-01-01 00:00:00"
17054        );
17055    }
17056
17057    #[test]
17058    fn format_pandas_float_matches_python_str_float_at_boundaries() {
17059        // to_csv float cells use Python str(float): fixed notation for decimal
17060        // exponents in [-4, 16), scientific (signed 2-digit exp) outside. Each
17061        // expectation verified vs live pandas 2.2.3 `DataFrame({'v':[x]}).to_csv`.
17062        let cases: &[(f64, &str)] = &[
17063            (0.1, "0.1"),
17064            (1.0 / 3.0, "0.3333333333333333"),
17065            (1e16, "1e+16"),
17066            (1e-5, "1e-05"),
17067            (1e-4, "0.0001"),
17068            (123_456_789_012_345.6, "123456789012345.6"),
17069            (1e21, "1e+21"),
17070            (1e-7, "1e-07"),
17071            (-0.0, "-0.0"),
17072            // 9999999999999999.0 rounds to 1e16 in f64.
17073            (9_999_999_999_999_999.0, "1e+16"),
17074            (2.5e-8, "2.5e-08"),
17075            (1e17, "1e+17"),
17076            (0.00012345, "0.00012345"),
17077        ];
17078        for &(v, expected) in cases {
17079            assert_eq!(
17080                super::format_pandas_float(v),
17081                expected,
17082                "format_pandas_float({v:?})"
17083            );
17084        }
17085    }
17086
17087    #[test]
17088    fn skipinitialspace_preprocessor_strips_leading_field_spaces_i4h5g() {
17089        let f = |s: &str| super::apply_skipinitialspace(s, b',', b'"', true, None, None);
17090        // Leading spaces at every field start (first field + header + after
17091        // delimiter) stripped; trailing spaces kept; verified vs pandas 2.2.3.
17092        assert_eq!(f(" a,  b\n  x,  y  \n"), "a,b\nx,y  \n");
17093        // Space before a quoted field is stripped, the quote is then honored, and
17094        // spaces INSIDE the quotes are preserved.
17095        assert_eq!(f("a,b\nx,  \"  q,q  \"\n"), "a,b\nx,\"  q,q  \"\n");
17096        // Tabs are not stripped (only ASCII 0x20).
17097        assert_eq!(f("a,b\nx,\t y\n"), "a,b\nx,\t y\n");
17098        // An all-space field collapses to empty.
17099        assert_eq!(f("a,   ,b\n"), "a,,b\n");
17100        // Doubled quotes inside a quoted field stay intact.
17101        assert_eq!(f("a\n  \"x\"\"y\"\n"), "a\n\"x\"\"y\"\n");
17102    }
17103
17104    #[test]
17105    fn read_csv_skipinitialspace_strips_field_leading_spaces_i4h5g() {
17106        use super::{CsvReadOptions, read_csv_with_options, write_csv_string};
17107        let opts = CsvReadOptions {
17108            skipinitialspace: true,
17109            ..Default::default()
17110        };
17111        // Object columns: leading spaces at each field start are dropped.
17112        let frame = read_csv_with_options("k,v\n  aa,bb\n cc,  dd\n", &opts).expect("read");
17113        assert_eq!(
17114            write_csv_string(&frame).expect("write"),
17115            "k,v\naa,bb\ncc,dd\n"
17116        );
17117        // Default (skipinitialspace=false) keeps the leading spaces.
17118        let frame_def =
17119            read_csv_with_options("k,v\n  aa,bb\n", &CsvReadOptions::default()).expect("read");
17120        assert_eq!(
17121            write_csv_string(&frame_def).expect("write"),
17122            "k,v\n  aa,bb\n"
17123        );
17124    }
17125
17126    #[test]
17127    fn read_csv_with_options_object_fallback_preserves_text() {
17128        use super::{CsvReadOptions, read_csv_with_options};
17129        // Same pandas object-fallback rule on the options reader (custom
17130        // delimiter / na_values etc.): non-canonical bool casing and zero-padded
17131        // numbers survive once the column is object. Verified vs pandas 2.2.3.
17132        let tsv = CsvReadOptions {
17133            delimiter: b'\t',
17134            ..Default::default()
17135        };
17136        let frame = read_csv_with_options("c\ntrue\nfalse\nmaybe\n", &tsv).expect("read");
17137        assert_eq!(frame.index().int64_unit_range_labels(), Some((0, 3)));
17138        let out = write_csv_string(&frame).expect("write");
17139        assert_eq!(out, "c\ntrue\nfalse\nmaybe\n");
17140
17141        let frame2 = read_csv_with_options("c\n01\n02\nabc\n", &tsv).expect("read");
17142        let out2 = write_csv_string(&frame2).expect("write");
17143        assert_eq!(out2, "c\n01\n02\nabc\n");
17144
17145        // Pure-bool column still infers bool dtype (writes True/False).
17146        let frame3 = read_csv_with_options("c\ntrue\nfalse\n", &tsv).expect("read");
17147        let out3 = write_csv_string(&frame3).expect("write");
17148        assert_eq!(out3, "c\nTrue\nFalse\n");
17149
17150        // Custom na_values: an NA cell in an object column stays missing while
17151        // the surrounding original literals are preserved.
17152        let na_opts = CsvReadOptions {
17153            delimiter: b'\t',
17154            na_values: vec!["MISSING".to_string()],
17155            ..Default::default()
17156        };
17157        let frame4 = read_csv_with_options("c\ntrue\nMISSING\nmaybe\n", &na_opts).expect("read");
17158        let out4 = write_csv_string(&frame4).expect("write");
17159        // The lone empty NaN field in a single-column object frame is quoted "".
17160        assert_eq!(out4, "c\ntrue\n\"\"\nmaybe\n");
17161    }
17162
17163    #[test]
17164    fn to_csv_float_format_matches_pandas_str() {
17165        // pandas to_csv writes floats via Python str(float): whole numbers keep
17166        // ".0", decimals use the shortest round-trip, and extreme magnitudes use
17167        // signed two-digit scientific notation. Verified vs live pandas 2.2.3.
17168        let cases: &[(f64, &str)] = &[
17169            (0.0, "0.0"),
17170            (-0.0, "-0.0"),
17171            (1.0, "1.0"),
17172            (100.0, "100.0"),
17173            (0.1, "0.1"),
17174            (1.0 / 3.0, "0.3333333333333333"),
17175            (9999999999999999.0, "1e+16"),
17176            (1e16, "1e+16"),
17177            (1e20, "1e+20"),
17178            (0.0001, "0.0001"),
17179            (1e-5, "1e-05"),
17180            (1e-7, "1e-07"),
17181            (f64::MIN_POSITIVE / 2.0, "1.1125369292536007e-308"),
17182            (f64::INFINITY, "inf"),
17183            (f64::NEG_INFINITY, "-inf"),
17184        ];
17185        for (v, expected) in cases {
17186            assert_eq!(
17187                &format_pandas_float(*v),
17188                expected,
17189                "format_pandas_float({v})"
17190            );
17191        }
17192
17193        let col = Column::from_f64_values(vec![1.0, f64::NAN, 3.0]);
17194        let mut cols = BTreeMap::new();
17195        cols.insert("x".to_owned(), col);
17196        let frame = DataFrame::new_with_column_order(
17197            Index::from_i64((0..3).collect()),
17198            cols,
17199            vec!["x".to_owned()],
17200        )
17201        .expect("frame");
17202        let out = write_csv_string_with_options(
17203            &frame,
17204            &CsvWriteOptions {
17205                include_index: false,
17206                na_rep: "NA".to_owned(),
17207                ..Default::default()
17208            },
17209        )
17210        .expect("write");
17211        assert_eq!(out, "x\n1.0\nNA\n3.0\n");
17212    }
17213
17214    #[test]
17215    fn to_csv_quarter_affine_float_plan_matches_pandas_str_uza0481() {
17216        let values = (0..128)
17217            .map(|row| (row as f64 * 1.25) + 2.0)
17218            .collect::<Vec<_>>();
17219        let plan = Float64QuarterAffineCsvPlan::for_slice(&values).expect("quarter plan");
17220        let expected_cells = values
17221            .iter()
17222            .copied()
17223            .map(format_pandas_float)
17224            .collect::<Vec<_>>();
17225        let mut fast_cells = Vec::with_capacity(values.len());
17226        for row in 0..values.len() {
17227            let mut out = String::new();
17228            assert!(plan.append_row(&mut out, row));
17229            fast_cells.push(out);
17230        }
17231        assert_eq!(fast_cells, expected_cells);
17232
17233        let col = Column::from_f64_values(values);
17234        let mut cols = BTreeMap::new();
17235        cols.insert("x".to_owned(), col);
17236        let frame = DataFrame::new_with_column_order(
17237            Index::from_i64((0..128).collect()),
17238            cols,
17239            vec!["x".to_owned()],
17240        )
17241        .expect("frame");
17242        let out = write_csv_string_with_options(
17243            &frame,
17244            &CsvWriteOptions {
17245                include_index: false,
17246                ..Default::default()
17247            },
17248        )
17249        .expect("write");
17250        let mut expected = String::from("x\n");
17251        for cell in expected_cells {
17252            expected.push_str(&cell);
17253            expected.push('\n');
17254        }
17255        assert_eq!(out, expected);
17256    }
17257
17258    #[test]
17259    fn quarter_affine_float_plan_rejects_fallback_boundaries_uza0481() {
17260        let rejected: &[&[f64]] = &[
17261            &[-0.0, 1.25, 2.5],
17262            &[-1.25, 0.0, 1.25],
17263            &[0.0, f64::NAN, 2.5],
17264            &[0.0, f64::INFINITY, 2.5],
17265            &[0.1, 1.35, 2.6],
17266            &[0.0, 1.25, 2.75],
17267            &[1e16, 1e16 + 1.25],
17268        ];
17269        for values in rejected {
17270            assert!(
17271                Float64QuarterAffineCsvPlan::for_slice(values).is_none(),
17272                "unexpected quarter plan for {values:?}"
17273            );
17274        }
17275    }
17276
17277    #[test]
17278    fn to_csv_single_column_nan_quotes_empty_and_keeps_float_repr() {
17279        // The lone empty NaN field is already quoted as "" by the csv writer so
17280        // read_csv doesn't drop it (NOT a blank line). The real fix here is the
17281        // float repr: 1.0/3.0 must stay "1.0"/"3.0", not collapse to "1"/"3".
17282        let frame = read_csv_str("x\n1.0\nNaN\n3.0\n").expect("read");
17283        assert!(frame.column("x").unwrap().values()[1].is_missing());
17284        let out = write_csv_string(&frame).expect("write");
17285        assert_eq!(out, "x\n1.0\n\"\"\n3.0\n");
17286    }
17287
17288    #[test]
17289    fn to_csv_typed_single_empty_string_field_is_quoted_like_pandas() {
17290        // Oracle pandas 2.2.3 (csv QUOTE_MINIMAL): a SOLE empty field per record is
17291        // quoted "" so read_csv round-trips '' instead of a blank line -> NaN. An
17292        // all-valid contiguous Utf8 single column takes the typed fast path
17293        // (try_write_csv_typed), which previously emitted the empty cell bare.
17294        // DataFrame({'a':['','x','y']}).to_csv(index=False) -> 'a\n""\nx\ny\n'
17295        let col = Column::from_utf8_contiguous(b"xy".to_vec(), vec![0, 0, 1, 2]);
17296        // Sanity: this column is the all-valid contiguous Utf8 the typed path needs.
17297        assert!(col.as_utf8_contiguous().is_some());
17298        assert_eq!(col.value(0), Some(&Scalar::Utf8(String::new())));
17299        let mut columns = BTreeMap::new();
17300        columns.insert("a".to_string(), col);
17301        let frame = DataFrame::new_with_column_order(
17302            Index::new(vec![
17303                IndexLabel::Int64(0),
17304                IndexLabel::Int64(1),
17305                IndexLabel::Int64(2),
17306            ]),
17307            columns,
17308            vec!["a".to_string()],
17309        )
17310        .unwrap();
17311        assert_eq!(write_csv_string(&frame).expect("write"), "a\n\"\"\nx\ny\n");
17312
17313        // Empty header for a sole column is quoted too (DataFrame({'':['a','b']})).
17314        let named = frame.rename_columns(&[("a", "")]).expect("rename");
17315        assert_eq!(
17316            write_csv_string(&named).expect("write2"),
17317            "\"\"\n\"\"\nx\ny\n"
17318        );
17319    }
17320
17321    #[test]
17322    fn to_csv_typed_multi_column_empty_string_stays_bare_like_pandas() {
17323        // With >1 field per record an empty field is NOT quoted (no blank-line
17324        // ambiguity): DataFrame({'a':['','x'],'b':['y','']}).to_csv(index=False)
17325        // -> 'a,b\n,y\nx,\n'.
17326        let mut columns = BTreeMap::new();
17327        columns.insert(
17328            "a".to_string(),
17329            Column::from_utf8_contiguous(b"x".to_vec(), vec![0, 0, 1]),
17330        );
17331        columns.insert(
17332            "b".to_string(),
17333            Column::from_utf8_contiguous(b"y".to_vec(), vec![0, 1, 1]),
17334        );
17335        let frame = DataFrame::new_with_column_order(
17336            Index::new(vec![IndexLabel::Int64(0), IndexLabel::Int64(1)]),
17337            columns,
17338            vec!["a".to_string(), "b".to_string()],
17339        )
17340        .unwrap();
17341        assert_eq!(write_csv_string(&frame).expect("write"), "a,b\n,y\nx,\n");
17342    }
17343
17344    #[test]
17345    fn to_csv_typed_mixed_columns_quote_alt_delimiter_property_7q396() {
17346        // Code-first property guard (br-frankenpandas-fp-io-csv-typed-writer-quote-property-7q396):
17347        // all-valid typed Int64/Float64 plus contiguous Utf8 must stay byte-exact
17348        // under QUOTE_MINIMAL when the delimiter changes and Utf8 cells contain
17349        // delimiter, quote, and newline characters.
17350        let mut columns = BTreeMap::new();
17351        columns.insert("i".to_string(), Column::from_i64_values(vec![-1, 0, 42, 7]));
17352        columns.insert(
17353            "f".to_string(),
17354            Column::from_f64_values(vec![1.0, 2.5, -0.0, 3.25]),
17355        );
17356
17357        let text = b"plainsemi;colonquote\"meline\nbreak".to_vec();
17358        let offsets = vec![0, 5, 15, 23, 33];
17359        let utf8 = Column::from_utf8_contiguous(text, offsets);
17360        assert!(utf8.as_utf8_contiguous().is_some());
17361        columns.insert("s".to_string(), utf8);
17362
17363        let frame = DataFrame::new_with_column_order(
17364            Index::new((0..4).map(IndexLabel::Int64).collect()),
17365            columns,
17366            vec!["i".to_string(), "f".to_string(), "s".to_string()],
17367        )
17368        .unwrap();
17369        let out = write_csv_string_with_options(
17370            &frame,
17371            &CsvWriteOptions {
17372                delimiter: b';',
17373                include_index: false,
17374                ..CsvWriteOptions::default()
17375            },
17376        )
17377        .expect("typed csv write");
17378
17379        assert_eq!(
17380            out,
17381            "i;f;s\n-1;1.0;plain\n0;2.5;\"semi;colon\"\n42;-0.0;\"quote\"\"me\"\n7;3.25;\"line\nbreak\"\n"
17382        );
17383    }
17384
17385    #[test]
17386    fn to_csv_typed_headerless_keeps_fast_path_for_quoted_column_name_up3yf() {
17387        // br-frankenpandas-fp-io-csv-headerless-quoted-name-typed-fast-pat-up3yf:
17388        // a quoted column name is unobservable when header=false, so it must not
17389        // force the all-valid typed writer off the fast path.
17390        let mut columns = BTreeMap::new();
17391        columns.insert(
17392            "needs,quote".to_string(),
17393            Column::from_i64_values(vec![1, 2]),
17394        );
17395        let frame = DataFrame::new_with_column_order(
17396            Index::new(vec![IndexLabel::Int64(0), IndexLabel::Int64(1)]),
17397            columns,
17398            vec!["needs,quote".to_string()],
17399        )
17400        .unwrap();
17401        let options = CsvWriteOptions {
17402            header: false,
17403            include_index: false,
17404            ..CsvWriteOptions::default()
17405        };
17406
17407        assert_eq!(
17408            super::try_write_csv_typed(&frame, &options).as_deref(),
17409            Some("1\n2\n")
17410        );
17411        assert_eq!(
17412            write_csv_string_with_options(&frame, &options).expect("write"),
17413            "1\n2\n"
17414        );
17415    }
17416
17417    #[test]
17418    fn to_csv_typed_quotes_header_names_without_fallback_ay42b() {
17419        // br-frankenpandas-fp-io-csv-typed-quoted-header-fast-path-4d9vn-ay42b:
17420        // emitted headers use the same QUOTE_MINIMAL rules as data cells, so
17421        // typed columns with quoted names can still bypass the generic writer.
17422        let mut columns = BTreeMap::new();
17423        columns.insert(
17424            "comma,name".to_string(),
17425            Column::from_i64_values(vec![1, 2]),
17426        );
17427        columns.insert(
17428            "quote\"name".to_string(),
17429            Column::from_f64_values(vec![1.0, 2.5]),
17430        );
17431        columns.insert(
17432            "line\nname".to_string(),
17433            Column::from_utf8_contiguous(b"xy".to_vec(), vec![0, 1, 2]),
17434        );
17435        let frame = DataFrame::new_with_column_order(
17436            Index::new(vec![IndexLabel::Int64(0), IndexLabel::Int64(1)]),
17437            columns,
17438            vec![
17439                "comma,name".to_string(),
17440                "quote\"name".to_string(),
17441                "line\nname".to_string(),
17442            ],
17443        )
17444        .unwrap();
17445        let expected = "\"comma,name\",\"quote\"\"name\",\"line\nname\"\n1,1.0,x\n2,2.5,y\n";
17446
17447        assert_eq!(
17448            super::try_write_csv_typed(&frame, &CsvWriteOptions::default()).as_deref(),
17449            Some(expected)
17450        );
17451        assert_eq!(write_csv_string(&frame).expect("write"), expected);
17452    }
17453
17454    #[test]
17455    fn to_csv_typed_handles_datetime_column_without_fallback_dtcsv() {
17456        // A Datetime64 column must stay on the typed fast path (previously any
17457        // datetime forced the whole frame to the generic writer). NaT renders as
17458        // na_rep; the column-uniform full-timestamp form is used because one
17459        // value is non-midnight.
17460        let v0 = 946_684_800_000_000_000i64; // 2000-01-01 00:00:00
17461        let v1 = v0 + 3_661_000_000_000; // 2000-01-01 01:01:01
17462        let mut columns = BTreeMap::new();
17463        columns.insert("a".to_string(), Column::from_i64_values(vec![10, 20, 30]));
17464        columns.insert(
17465            "b".to_string(),
17466            Column::from_f64_values(vec![1.5, 2.0, 3.5]),
17467        );
17468        columns.insert(
17469            "t".to_string(),
17470            Column::from_datetime64_values(vec![v0, v1, Timestamp::NAT]),
17471        );
17472        let frame = DataFrame::new_with_column_order(
17473            Index::new(vec![
17474                IndexLabel::Int64(0),
17475                IndexLabel::Int64(1),
17476                IndexLabel::Int64(2),
17477            ]),
17478            columns,
17479            vec!["a".to_string(), "b".to_string(), "t".to_string()],
17480        )
17481        .unwrap();
17482        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";
17483        // Typed fast path fires (no datetime fallback) and is byte-identical to
17484        // the public writer (which routes through it).
17485        assert_eq!(
17486            super::try_write_csv_typed(&frame, &CsvWriteOptions::default()).as_deref(),
17487            Some(expected),
17488        );
17489        assert_eq!(write_csv_string(&frame).expect("write"), expected);
17490    }
17491
17492    #[test]
17493    fn to_csv_typed_emits_int64_index_without_fallback_a2uli() {
17494        // br-frankenpandas-fp-io-csv-typed-int64-index-fast-path-8m6qd-a2uli:
17495        // a simple Int64 index can be emitted directly without forcing typed
17496        // columns through per-cell Scalar materialization.
17497        let mut columns = BTreeMap::new();
17498        columns.insert("a".to_string(), Column::from_i64_values(vec![1, 2]));
17499        columns.insert("b".to_string(), Column::from_f64_values(vec![1.0, 2.5]));
17500        let frame = DataFrame::new_with_column_order(
17501            Index::from_i64(vec![10, 20]).set_name("row,id"),
17502            columns,
17503            vec!["a".to_string(), "b".to_string()],
17504        )
17505        .unwrap();
17506        let options = CsvWriteOptions {
17507            include_index: true,
17508            ..CsvWriteOptions::default()
17509        };
17510        let expected = "\"row,id\",a,b\n10,1,1.0\n20,2,2.5\n";
17511
17512        assert_eq!(
17513            super::try_write_csv_typed(&frame, &options).as_deref(),
17514            Some(expected)
17515        );
17516        assert_eq!(
17517            write_csv_string_with_options(&frame, &options).expect("write"),
17518            expected
17519        );
17520    }
17521
17522    #[test]
17523    fn to_csv_typed_int64_manual_decimal_boundaries_cnw1j() {
17524        // br-frankenpandas-fp-io-csv-int64-manual-decimal-emitter-5p8kx-cnw1j:
17525        // the stack decimal emitter must preserve Display bytes for every i64,
17526        // including the unsigned_abs corner at i64::MIN.
17527        let mut columns = BTreeMap::new();
17528        columns.insert(
17529            "v".to_string(),
17530            Column::from_i64_values(vec![i64::MIN, 0, i64::MAX]),
17531        );
17532        let frame = DataFrame::new_with_column_order(
17533            Index::from_i64(vec![-1, 0, 1]),
17534            columns,
17535            vec!["v".to_string()],
17536        )
17537        .unwrap();
17538        let options = CsvWriteOptions {
17539            include_index: true,
17540            index_label: Some("i".to_string()),
17541            ..CsvWriteOptions::default()
17542        };
17543        let expected = "i,v\n-1,-9223372036854775808\n0,0\n1,9223372036854775807\n";
17544
17545        assert_eq!(
17546            super::try_write_csv_typed(&frame, &options).as_deref(),
17547            Some(expected)
17548        );
17549        assert_eq!(
17550            write_csv_string_with_options(&frame, &options).expect("write"),
17551            expected
17552        );
17553    }
17554
17555    #[test]
17556    fn to_csv_typed_bool_column_stays_on_fast_path_48fwr() {
17557        // br-frankenpandas-fp-io-csv-typed-bool-column-fast-path-2k7hm-48fwr:
17558        // all-valid Bool columns have a typed backing and should emit pandas
17559        // True/False spelling without Scalar materialization.
17560        let mut columns = BTreeMap::new();
17561        columns.insert(
17562            "flag".to_string(),
17563            Column::from_bool_values(vec![true, false, true]),
17564        );
17565        columns.insert("value".to_string(), Column::from_i64_values(vec![7, 8, 9]));
17566        let frame = DataFrame::new_with_column_order(
17567            Index::from_i64(vec![100, 101, 102]),
17568            columns,
17569            vec!["flag".to_string(), "value".to_string()],
17570        )
17571        .unwrap();
17572        let options = CsvWriteOptions {
17573            include_index: true,
17574            index_label: Some("row".to_string()),
17575            ..CsvWriteOptions::default()
17576        };
17577        let expected = "row,flag,value\n100,True,7\n101,False,8\n102,True,9\n";
17578
17579        assert_eq!(
17580            super::try_write_csv_typed(&frame, &options).as_deref(),
17581            Some(expected)
17582        );
17583        assert_eq!(
17584            write_csv_string_with_options(&frame, &options).expect("write"),
17585            expected
17586        );
17587    }
17588
17589    #[test]
17590    fn test_csv_capacity_hint_reasonable() {
17591        // Generate a ~1MB CSV and verify it parses correctly.
17592        // The capacity hint (input.len / (cols*8)) should avoid excessive reallocs.
17593        let mut csv = String::with_capacity(1_100_000);
17594        csv.push_str("a,b,c,d,e\n");
17595        let target_rows = 50_000; // ~20 bytes/row * 50k ≈ 1MB
17596        for i in 0..target_rows {
17597            csv.push_str(&format!("{},{},{},{},{}\n", i, i * 2, i * 3, i * 4, i * 5));
17598        }
17599        assert!(csv.len() > 500_000, "CSV should be large");
17600
17601        let frame = read_csv_str(&csv).expect("parse large CSV");
17602        assert_eq!(frame.index().len(), target_rows);
17603        assert_eq!(frame.columns().len(), 5);
17604        // Spot-check last row
17605        assert_eq!(
17606            frame.column("a").unwrap().values()[target_rows - 1],
17607            Scalar::Int64((target_rows - 1) as i64)
17608        );
17609        eprintln!(
17610            "[TEST] test_csv_capacity_hint_reasonable | rows={target_rows} cols=5 parse_ok=true | PASS"
17611        );
17612    }
17613
17614    #[test]
17615    fn test_csv_empty_columns() {
17616        // CSV with headers but no data rows -> empty DataFrame with correct column names.
17617        let input = "x,y,z\n";
17618        let frame = read_csv_str(input).expect("parse");
17619        assert_eq!(frame.index().len(), 0);
17620        let keys: Vec<&String> = frame.columns().keys().collect();
17621        assert_eq!(keys, &["x", "y", "z"]);
17622        for col in frame.columns().values() {
17623            assert!(col.is_empty());
17624        }
17625        eprintln!("[TEST] test_csv_empty_columns | rows=0 cols=3 parse_ok=true | PASS");
17626    }
17627
17628    #[test]
17629    fn test_csv_comment_skips_lines() {
17630        let input = "# header comment\nname,age\n# inline comment\nalice,30\nbob,25\n";
17631        let options = CsvReadOptions {
17632            comment: Some(b'#'),
17633            ..CsvReadOptions::default()
17634        };
17635        let frame = read_csv_with_options(input, &options).expect("parse");
17636        assert_eq!(frame.index().len(), 2);
17637        let names: Vec<&String> = frame.column_names().into_iter().collect();
17638        assert_eq!(names, vec!["name", "age"]);
17639        assert_eq!(
17640            frame.column("name").unwrap().values()[0],
17641            Scalar::Utf8("alice".to_string())
17642        );
17643        assert_eq!(frame.column("age").unwrap().values()[1], Scalar::Int64(25));
17644    }
17645
17646    #[test]
17647    fn test_csv_comment_none_preserves_comment_lines() {
17648        // Without comment set, a leading "#"-line should become part of parsing
17649        // (and fail as duplicate/missing-headers or be treated as data).
17650        let input = "name,age\nalice,30\n";
17651        let frame = read_csv_with_options(input, &CsvReadOptions::default()).expect("parse");
17652        assert_eq!(frame.index().len(), 1);
17653    }
17654
17655    #[test]
17656    fn read_csv_with_default_options_matches_read_csv_str() {
17657        for input in [
17658            "i,f,s\n1,2.5,abc\n3,4.0,def\n",
17659            "flag\ntrue\nfalse\nmaybe\n",
17660        ] {
17661            let expected = read_csv_str(input).expect("default read");
17662            let actual =
17663                read_csv_with_options(input, &CsvReadOptions::default()).expect("options read");
17664
17665            assert_eq!(actual.index().len(), expected.index().len());
17666            assert_eq!(actual.column_names(), expected.column_names());
17667            for name in expected.column_names() {
17668                let expected_col = expected.column(name).expect("expected column");
17669                let actual_col = actual.column(name).expect("actual column");
17670                assert_eq!(actual_col.dtype(), expected_col.dtype());
17671                assert_eq!(actual_col.values(), expected_col.values());
17672            }
17673        }
17674    }
17675
17676    #[test]
17677    fn read_csv_str_cache_reuses_exact_successful_input() {
17678        let input = "x,y\n1,2.5\n3,4.5\n";
17679
17680        let first = read_csv_str(input).expect("first parse");
17681        let second = read_csv_str(input).expect("cached parse");
17682
17683        assert_eq!(second.index().len(), first.index().len());
17684        assert_eq!(second.column_names(), first.column_names());
17685        for name in first.column_names() {
17686            let first_col = first.column(name).expect("first column");
17687            let second_col = second.column(name).expect("second column");
17688            assert_eq!(second_col.dtype(), first_col.dtype());
17689            assert_eq!(second_col.values(), first_col.values());
17690        }
17691    }
17692
17693    #[test]
17694    fn read_csv_str_cache_is_content_addressed() {
17695        let mut input = String::from("x\n1\n2\n");
17696        let first = read_csv_str(&input).expect("first parse");
17697        assert_eq!(first.column("x").unwrap().values()[0], Scalar::Int64(1));
17698
17699        input.clear();
17700        input.push_str("x\n9\n10\n");
17701        let second = read_csv_str(&input).expect("changed-content parse");
17702
17703        assert_eq!(second.index().len(), 2);
17704        assert_eq!(second.column("x").unwrap().values()[0], Scalar::Int64(9));
17705        assert_eq!(second.column("x").unwrap().values()[1], Scalar::Int64(10));
17706    }
17707
17708    #[test]
17709    fn read_csv_no_na_cache_reuses_exact_successful_input() {
17710        let options = CsvReadOptions {
17711            na_filter: false,
17712            ..CsvReadOptions::default()
17713        };
17714        let input = "x,y\n1,2.5\n3,4.5\n";
17715
17716        let first = read_csv_with_options(input, &options).expect("first no-na parse");
17717        let second = read_csv_with_options(input, &options).expect("cached no-na parse");
17718
17719        assert_eq!(second.index().len(), first.index().len());
17720        assert_eq!(second.column_names(), first.column_names());
17721        for name in first.column_names() {
17722            let first_col = first.column(name).expect("first column");
17723            let second_col = second.column(name).expect("second column");
17724            assert_eq!(second_col.dtype(), first_col.dtype());
17725            assert_eq!(second_col.values(), first_col.values());
17726        }
17727    }
17728
17729    #[test]
17730    fn csv_parse_cache_keeps_default_and_no_na_modes_separate() {
17731        let input = "mode_sep_a,mode_sep_b\n11,12.5\n13,14.5\n";
17732        let no_na_options = CsvReadOptions {
17733            na_filter: false,
17734            ..CsvReadOptions::default()
17735        };
17736
17737        // This test asserts KEY SEPARATION, not cache retention, and the two need
17738        // different strengths of assertion.
17739        //
17740        // CSV_PARSE_CACHE is one global VecDeque holding CSV_PARSE_CACHE_MAX_ENTRIES
17741        // (2) entries, and 117 tests in this module parse CSVs. Under the default
17742        // parallel harness any of them can evict this test's entries between a store
17743        // and the matching lookup, so `.expect("... cache entry")` on a retention
17744        // lookup fails intermittently — it did, on the no-na entry, once a second
17745        // parse pushed the deque past two. That is the harness racing, not the cache
17746        // misbehaving: the whole file passes under `--test-threads=1`.
17747        //
17748        // So: assertions that can only fail because of a real bug stay strict, and
17749        // assertions that a concurrent eviction can legitimately defeat are guarded
17750        // on presence. Nothing real is given up. `input` is unique to this test, so
17751        // a hit under the wrong mode can only mean the two modes share a key, which
17752        // is exactly the defect this test exists to catch.
17753        let no_na_frame = read_csv_with_options(input, &no_na_options).expect("no-na parse");
17754
17755        // STRICT: a no-na parse must never satisfy a Default lookup for this input.
17756        // Eviction can only turn a Some into a None here, never a None into a Some,
17757        // so a failure is unambiguously a key collision.
17758        assert!(
17759            super::csv_parse_cache_lookup(super::CsvParseCacheMode::Default, input).is_none(),
17760            "a no-na parse populated the Default cache key: the two modes are not separated"
17761        );
17762
17763        let default_frame = read_csv_str(input).expect("default parse");
17764
17765        // STRICT, and the mirror of the above: a default parse must never satisfy a
17766        // no-na lookup with default-parsed content.
17767        assert!(
17768            super::csv_parse_cache_lookup(super::CsvParseCacheMode::NoNaNumeric, input)
17769                .is_none_or(|cached| cached.column("mode_sep_b").unwrap().values()
17770                    == no_na_frame.column("mode_sep_b").unwrap().values()),
17771            "the NoNaNumeric key returned default-parsed content: the modes are not separated"
17772        );
17773
17774        // GUARDED: whether an entry survived is a property of the eviction policy and
17775        // of what else is running. What must hold is that a surviving entry matches a
17776        // fresh parse in the same mode.
17777        if let Some(default_cached) =
17778            super::csv_parse_cache_lookup(super::CsvParseCacheMode::Default, input)
17779        {
17780            assert_eq!(default_cached.column_names(), default_frame.column_names());
17781            assert_eq!(
17782                default_cached.column("mode_sep_b").unwrap().values(),
17783                default_frame.column("mode_sep_b").unwrap().values()
17784            );
17785        }
17786        if let Some(no_na_cached) =
17787            super::csv_parse_cache_lookup(super::CsvParseCacheMode::NoNaNumeric, input)
17788        {
17789            assert_eq!(no_na_cached.column_names(), no_na_frame.column_names());
17790            assert_eq!(
17791                no_na_cached.column("mode_sep_b").unwrap().values(),
17792                no_na_frame.column("mode_sep_b").unwrap().values()
17793            );
17794        }
17795    }
17796
17797    #[test]
17798    fn csv_default_options_fast_path_excludes_behavioral_options() {
17799        assert!(super::csv_read_options_match_default_fast_path(
17800            &CsvReadOptions::default()
17801        ));
17802
17803        for options in [
17804            CsvReadOptions {
17805                delimiter: b'\t',
17806                ..CsvReadOptions::default()
17807            },
17808            CsvReadOptions {
17809                na_filter: false,
17810                ..CsvReadOptions::default()
17811            },
17812            CsvReadOptions {
17813                nrows: Some(1),
17814                ..CsvReadOptions::default()
17815            },
17816            CsvReadOptions {
17817                comment: Some(b'#'),
17818                ..CsvReadOptions::default()
17819            },
17820            CsvReadOptions {
17821                thousands: Some(b','),
17822                ..CsvReadOptions::default()
17823            },
17824        ] {
17825            assert!(!super::csv_read_options_match_default_fast_path(&options));
17826        }
17827    }
17828
17829    #[test]
17830    fn read_csv_no_na_filter_numeric_fast_path_preserves_numeric_columns() {
17831        let options = CsvReadOptions {
17832            na_filter: false,
17833            ..CsvReadOptions::default()
17834        };
17835        assert!(super::csv_read_options_match_no_na_numeric_fast_path(
17836            &options
17837        ));
17838
17839        let frame = read_csv_with_options("i,f\n1,2.5\n3,4\n", &options).expect("parse");
17840        assert_eq!(frame.len(), 2);
17841        assert_eq!(frame.column("i").expect("i").dtype(), DType::Int64);
17842        assert_eq!(frame.column("f").expect("f").dtype(), DType::Float64);
17843        assert_eq!(frame.column("i").expect("i").values()[1], Scalar::Int64(3));
17844        assert_eq!(
17845            frame.column("f").expect("f").values()[0],
17846            Scalar::Float64(2.5)
17847        );
17848    }
17849
17850    #[test]
17851    fn read_csv_no_na_filter_fast_path_falls_back_for_empty_field() {
17852        let options = CsvReadOptions {
17853            na_filter: false,
17854            ..CsvReadOptions::default()
17855        };
17856        let frame = read_csv_with_options("x,y\n1,\n2,3\n", &options).expect("parse");
17857        let y = frame.column("y").expect("y");
17858
17859        assert_eq!(y.dtype(), DType::Utf8);
17860        assert_eq!(y.values()[0], Scalar::Utf8(String::new()));
17861        assert_eq!(y.values()[1], Scalar::Utf8("3".to_owned()));
17862    }
17863
17864    #[test]
17865    fn test_csv_comment_custom_char() {
17866        let input = "% this is ignored\nname,age\nalice,30\n";
17867        let options = CsvReadOptions {
17868            comment: Some(b'%'),
17869            ..CsvReadOptions::default()
17870        };
17871        let frame = read_csv_with_options(input, &options).expect("parse");
17872        assert_eq!(frame.index().len(), 1);
17873        assert_eq!(
17874            frame.column("name").unwrap().values()[0],
17875            Scalar::Utf8("alice".to_string())
17876        );
17877    }
17878
17879    #[test]
17880    fn test_csv_thousands_strips_int_separator() {
17881        let input = "amount\n\"1,234,567\"\n\"42\"\n";
17882        let options = CsvReadOptions {
17883            thousands: Some(b','),
17884            ..CsvReadOptions::default()
17885        };
17886        let frame = read_csv_with_options(input, &options).expect("parse");
17887        assert_eq!(
17888            frame.column("amount").unwrap().values()[0],
17889            Scalar::Int64(1234567)
17890        );
17891        assert_eq!(
17892            frame.column("amount").unwrap().values()[1],
17893            Scalar::Int64(42)
17894        );
17895    }
17896
17897    #[test]
17898    fn test_csv_thousands_strips_float_with_custom_decimal() {
17899        // European convention: '.' as thousands, ',' as decimal.
17900        let input = "price\n\"1.234,56\"\n";
17901        let options = CsvReadOptions {
17902            thousands: Some(b'.'),
17903            decimal: b',',
17904            ..CsvReadOptions::default()
17905        };
17906        let frame = read_csv_with_options(input, &options).expect("parse");
17907        let v = frame.column("price").unwrap().values()[0].clone();
17908        assert!(matches!(v, Scalar::Float64(_)), "expected Float64");
17909        let Scalar::Float64(f) = v else { return };
17910        assert!((f - 1234.56).abs() < 1e-9);
17911    }
17912
17913    #[test]
17914    fn test_csv_thousands_none_keeps_separator_as_string() {
17915        // Without thousands set, "1,234" in a single field stays Utf8.
17916        let input = "amount\n\"1,234\"\n";
17917        let frame = read_csv_with_options(input, &CsvReadOptions::default()).expect("parse");
17918        assert_eq!(
17919            frame.column("amount").unwrap().values()[0],
17920            Scalar::Utf8("1,234".to_string())
17921        );
17922    }
17923
17924    #[test]
17925    fn test_csv_thousands_equal_to_decimal_is_ignored() {
17926        // pandas silently ignores thousands if it equals decimal.
17927        let input = "v\n\"1.234\"\n";
17928        let options = CsvReadOptions {
17929            thousands: Some(b'.'),
17930            decimal: b'.',
17931            ..CsvReadOptions::default()
17932        };
17933        let frame = read_csv_with_options(input, &options).expect("parse");
17934        let v = frame.column("v").unwrap().values()[0].clone();
17935        // thousands ignored → "1.234" parses as float 1.234
17936        assert!(matches!(v, Scalar::Float64(_)), "expected Float64");
17937        let Scalar::Float64(f) = v else { return };
17938        assert!((f - 1.234).abs() < 1e-9);
17939    }
17940
17941    #[test]
17942    fn test_csv_thousands_does_not_affect_non_numeric() {
17943        let input = "name\n\"a,b\"\n";
17944        let options = CsvReadOptions {
17945            thousands: Some(b','),
17946            ..CsvReadOptions::default()
17947        };
17948        let frame = read_csv_with_options(input, &options).expect("parse");
17949        assert_eq!(
17950            frame.column("name").unwrap().values()[0],
17951            Scalar::Utf8("a,b".to_string())
17952        );
17953    }
17954
17955    #[test]
17956    fn test_csv_quotechar_custom_single_quote() {
17957        let input = "name,remark\n'alice','loves, cats'\n";
17958        let options = CsvReadOptions {
17959            quotechar: b'\'',
17960            ..CsvReadOptions::default()
17961        };
17962        let frame = read_csv_with_options(input, &options).expect("parse");
17963        assert_eq!(
17964            frame.column("name").unwrap().values()[0],
17965            Scalar::Utf8("alice".to_string())
17966        );
17967        assert_eq!(
17968            frame.column("remark").unwrap().values()[0],
17969            Scalar::Utf8("loves, cats".to_string())
17970        );
17971    }
17972
17973    #[test]
17974    fn test_csv_doublequote_true_collapses_doubled_quotes() {
17975        // The field is `she said ""hi""` with doubled inner quotes.
17976        let input = "text\n\"she said \"\"hi\"\"\"\n";
17977        let frame = read_csv_with_options(input, &CsvReadOptions::default()).expect("parse");
17978        assert_eq!(
17979            frame.column("text").unwrap().values()[0],
17980            Scalar::Utf8("she said \"hi\"".to_string())
17981        );
17982    }
17983
17984    #[test]
17985    fn test_csv_doublequote_false_requires_escapechar() {
17986        // With doublequote=false and escapechar=\, \" escapes the quote.
17987        let input = "text\n\"hi\\\"there\"\n";
17988        let options = CsvReadOptions {
17989            doublequote: false,
17990            escapechar: Some(b'\\'),
17991            ..CsvReadOptions::default()
17992        };
17993        let frame = read_csv_with_options(input, &options).expect("parse");
17994        assert_eq!(
17995            frame.column("text").unwrap().values()[0],
17996            Scalar::Utf8("hi\"there".to_string())
17997        );
17998    }
17999
18000    #[test]
18001    fn test_csv_lineterminator_semicolon() {
18002        // Single-byte record separator '|'. No newlines in the data.
18003        let input = "a,b|1,x|2,y|3,z";
18004        let options = CsvReadOptions {
18005            lineterminator: Some(b'|'),
18006            ..CsvReadOptions::default()
18007        };
18008        let frame = read_csv_with_options(input, &options).expect("parse");
18009        assert_eq!(frame.index().len(), 3);
18010        assert_eq!(frame.column_names(), vec!["a", "b"]);
18011        assert_eq!(frame.column("a").unwrap().values()[2], Scalar::Int64(3));
18012    }
18013
18014    #[test]
18015    fn test_csv_lineterminator_default_none_accepts_crlf() {
18016        let input = "a,b\r\n1,x\r\n2,y\r\n";
18017        let frame = read_csv_with_options(input, &CsvReadOptions::default()).expect("parse");
18018        assert_eq!(frame.index().len(), 2);
18019    }
18020
18021    #[test]
18022    fn test_csv_lineterminator_interacts_with_skipfooter() {
18023        let input = "a|1|2|3|4|FOOTER";
18024        let options = CsvReadOptions {
18025            lineterminator: Some(b'|'),
18026            skipfooter: 1,
18027            ..CsvReadOptions::default()
18028        };
18029        let frame = read_csv_with_options(input, &options).expect("parse");
18030        // 5 data rows after header, footer drops 1 → 4 rows.
18031        assert_eq!(frame.index().len(), 4);
18032    }
18033
18034    #[test]
18035    fn test_csv_skipfooter_drops_trailing_rows() {
18036        let input = "a,b\n1,x\n2,y\n3,z\nTOTAL,summary\n";
18037        let options = CsvReadOptions {
18038            skipfooter: 1,
18039            ..CsvReadOptions::default()
18040        };
18041        let frame = read_csv_with_options(input, &options).expect("parse");
18042        assert_eq!(frame.index().len(), 3);
18043        assert_eq!(frame.column("a").unwrap().values()[2], Scalar::Int64(3));
18044    }
18045
18046    #[test]
18047    fn test_csv_skipfooter_zero_is_noop() {
18048        let input = "a,b\n1,x\n2,y\n";
18049        let frame_default =
18050            read_csv_with_options(input, &CsvReadOptions::default()).expect("parse");
18051        let options = CsvReadOptions {
18052            skipfooter: 0,
18053            ..CsvReadOptions::default()
18054        };
18055        let frame_zero = read_csv_with_options(input, &options).expect("parse");
18056        assert_eq!(frame_default.index().len(), frame_zero.index().len());
18057    }
18058
18059    #[test]
18060    fn test_csv_skipfooter_larger_than_data_clears_rows() {
18061        let input = "a,b\n1,x\n2,y\n";
18062        let options = CsvReadOptions {
18063            skipfooter: 10,
18064            ..CsvReadOptions::default()
18065        };
18066        let frame = read_csv_with_options(input, &options).expect("parse");
18067        assert_eq!(frame.index().len(), 0);
18068        // Columns and headers are still preserved.
18069        assert_eq!(frame.column_names().len(), 2);
18070    }
18071
18072    #[test]
18073    fn test_csv_skipfooter_with_nrows() {
18074        // nrows caps read to 4, then skipfooter drops last 1 → 3 rows.
18075        let input = "a\n1\n2\n3\n4\n5\n";
18076        let options = CsvReadOptions {
18077            nrows: Some(4),
18078            skipfooter: 1,
18079            ..CsvReadOptions::default()
18080        };
18081        let frame = read_csv_with_options(input, &options).expect("parse");
18082        assert_eq!(frame.index().len(), 3);
18083    }
18084
18085    #[test]
18086    fn test_csv_escapechar_none_default_keeps_backslash_literal() {
18087        // Without escapechar set, backslash is just a normal character.
18088        let input = "text\n\"foo\\bar\"\n";
18089        let frame = read_csv_with_options(input, &CsvReadOptions::default()).expect("parse");
18090        assert_eq!(
18091            frame.column("text").unwrap().values()[0],
18092            Scalar::Utf8("foo\\bar".to_string())
18093        );
18094    }
18095
18096    #[test]
18097    fn test_csv_single_column() {
18098        // CSV with one column, many rows -> correct parsing.
18099        let mut csv = String::from("value\n");
18100        for i in 0..500 {
18101            csv.push_str(&format!("{}\n", i));
18102        }
18103        let frame = read_csv_str(&csv).expect("parse");
18104        assert_eq!(frame.index().len(), 500);
18105        assert_eq!(frame.columns().len(), 1);
18106        assert_eq!(
18107            frame.column("value").unwrap().values()[499],
18108            Scalar::Int64(499)
18109        );
18110        eprintln!("[TEST] test_csv_single_column | rows=500 cols=1 parse_ok=true | PASS");
18111    }
18112
18113    #[test]
18114    fn test_csv_many_columns() {
18115        // CSV with 100+ columns -> all columns present, correct values.
18116        let col_count = 120;
18117        let headers: Vec<String> = (0..col_count).map(|i| format!("c{i:03}")).collect();
18118        let mut csv = headers.join(",");
18119        csv.push('\n');
18120        // 3 data rows
18121        for row in 0..3 {
18122            let vals: Vec<String> = (0..col_count)
18123                .map(|c| format!("{}", row * 1000 + c))
18124                .collect();
18125            csv.push_str(&vals.join(","));
18126            csv.push('\n');
18127        }
18128        let frame = read_csv_str(&csv).expect("parse");
18129        assert_eq!(frame.columns().len(), col_count);
18130        assert_eq!(frame.index().len(), 3);
18131        // Spot-check: c000 row 0 = 0, c119 row 2 = 2119
18132        assert_eq!(frame.column("c000").unwrap().values()[0], Scalar::Int64(0));
18133        assert_eq!(
18134            frame.column("c119").unwrap().values()[2],
18135            Scalar::Int64(2119)
18136        );
18137        eprintln!("[TEST] test_csv_many_columns | rows=3 cols={col_count} parse_ok=true | PASS");
18138    }
18139
18140    #[test]
18141    fn test_csv_mixed_dtypes() {
18142        // Columns with uniform int/float/string/bool/null -> correct type inference.
18143        let input = "ints,floats,strings,bools,nulls\n\
18144                     1,1.5,hello,true,\n\
18145                     2,2.7,world,false,\n\
18146                     3,3.14,foo,true,\n";
18147        let frame = read_csv_str(input).expect("parse");
18148
18149        let ints = frame.column("ints").unwrap();
18150        assert_eq!(ints.values()[0], Scalar::Int64(1));
18151
18152        let floats = frame.column("floats").unwrap();
18153        assert_eq!(floats.values()[1], Scalar::Float64(2.7));
18154
18155        let strings = frame.column("strings").unwrap();
18156        assert_eq!(strings.values()[2], Scalar::Utf8("foo".to_owned()));
18157
18158        let bools = frame.column("bools").unwrap();
18159        assert_eq!(bools.values()[0], Scalar::Bool(true));
18160        assert_eq!(bools.values()[1], Scalar::Bool(false));
18161
18162        // "nulls" column is all empty -> all null/NaN
18163        let nulls = frame.column("nulls").unwrap();
18164        for v in nulls.values() {
18165            assert!(v.is_missing(), "null column values should be missing");
18166        }
18167        eprintln!(
18168            "[TEST] test_csv_mixed_dtypes | rows=3 cols=5 parse_ok=true | dtype_per_col=[int64,float64,utf8,bool,null] | PASS"
18169        );
18170    }
18171
18172    #[test]
18173    fn test_csv_unicode_headers() {
18174        // CSV with unicode header names -> correct column names.
18175        let input = "名前,Größe,café\nAlice,170,latte\nBob,180,espresso\n";
18176        let frame = read_csv_str(input).expect("parse");
18177        assert!(frame.column("名前").is_some());
18178        assert!(frame.column("Größe").is_some());
18179        assert!(frame.column("café").is_some());
18180        assert_eq!(
18181            frame.column("名前").unwrap().values()[0],
18182            Scalar::Utf8("Alice".to_owned())
18183        );
18184        eprintln!("[TEST] test_csv_unicode_headers | rows=2 cols=3 parse_ok=true | PASS");
18185    }
18186
18187    #[test]
18188    fn test_csv_quoted_fields() {
18189        // CSV with quoted fields containing commas and newlines -> correct parsing.
18190        let input =
18191            "name,address\n\"Smith, John\",\"123 Main St\nApt 4\"\nJane,\"456 Oak, Suite 1\"\n";
18192        let frame = read_csv_str(input).expect("parse");
18193        assert_eq!(frame.index().len(), 2);
18194        assert_eq!(
18195            frame.column("name").unwrap().values()[0],
18196            Scalar::Utf8("Smith, John".to_owned())
18197        );
18198        // Quoted field with embedded newline
18199        let addr0 = &frame.column("address").unwrap().values()[0];
18200        assert!(
18201            matches!(addr0, Scalar::Utf8(s) if s.contains('\n')),
18202            "expected Utf8 containing embedded newline, got {addr0:?}"
18203        );
18204        eprintln!("[TEST] test_csv_quoted_fields | rows=2 cols=2 parse_ok=true | PASS");
18205    }
18206
18207    #[test]
18208    fn test_csv_trailing_newline() {
18209        // CSV with/without trailing newline -> identical DataFrame.
18210        let with = "a,b\n1,2\n3,4\n";
18211        let without = "a,b\n1,2\n3,4";
18212        let f1 = read_csv_str(with).expect("with newline");
18213        let f2 = read_csv_str(without).expect("without newline");
18214
18215        assert_eq!(f1.index().len(), f2.index().len());
18216        assert_eq!(f1.columns().len(), f2.columns().len());
18217        for key in f1.columns().keys() {
18218            let c1 = f1.column(key).unwrap();
18219            let c2 = f2.column(key).unwrap();
18220            assert_eq!(c1.values(), c2.values(), "column {key} mismatch");
18221        }
18222        eprintln!("[TEST] test_csv_trailing_newline | rows=2 cols=2 parse_ok=true | PASS");
18223    }
18224
18225    #[test]
18226    fn test_csv_round_trip_unchanged() {
18227        // read_csv_str then write_csv_string produces semantically equivalent output.
18228        let input = "id,name,score\n1,Alice,95.5\n2,Bob,87\n3,,100\n";
18229        let frame = read_csv_str(input).expect("read");
18230        let output = write_csv_string(&frame).expect("write");
18231        // Re-parse the output and compare
18232        let frame2 = read_csv_str(&output).expect("re-read");
18233        assert_eq!(frame.index().len(), frame2.index().len());
18234        for key in frame.columns().keys() {
18235            let c1 = frame.column(key).unwrap();
18236            let c2 = frame2.column(key).unwrap();
18237            assert!(
18238                c1.semantic_eq(c2),
18239                "column {key} not semantically equal after round-trip"
18240            );
18241        }
18242        eprintln!("[TEST] test_csv_round_trip_unchanged | rows=3 cols=3 parse_ok=true | PASS");
18243    }
18244
18245    #[test]
18246    fn test_write_csv_options_custom_delimiter() {
18247        let input = "a,b\n1,x\n2,y\n";
18248        let frame = read_csv_str(input).expect("read");
18249        let output = write_csv_string_with_options(
18250            &frame,
18251            &CsvWriteOptions {
18252                delimiter: b';',
18253                ..CsvWriteOptions::default()
18254            },
18255        )
18256        .expect("write");
18257        assert!(output.starts_with("a;b\n"));
18258        assert!(output.contains("1;x\n"));
18259        assert!(output.contains("2;y\n"));
18260    }
18261
18262    #[test]
18263    fn test_write_csv_options_na_rep_replaces_nulls() {
18264        let input = "id,name\n1,Alice\n2,\n";
18265        let frame = read_csv_str(input).expect("read");
18266        let output = write_csv_string_with_options(
18267            &frame,
18268            &CsvWriteOptions {
18269                na_rep: "NA".to_string(),
18270                ..CsvWriteOptions::default()
18271            },
18272        )
18273        .expect("write");
18274        // Second data row's name should render as NA, not empty.
18275        assert!(output.contains("2,NA\n"));
18276        assert!(!output.contains("2,\n"));
18277    }
18278
18279    #[test]
18280    fn test_write_csv_nullable_utf8_fast_matches_general() {
18281        // A nullable contiguous-Utf8 column (LazyNullableUtf8) now takes the fast typed
18282        // writer (FastCol::UN). It must produce BYTE-IDENTICAL output to the general
18283        // (Scalar + csv-record) writer, which an EAGER Utf8 column with the same data
18284        // falls to. Covers present/missing rows, empty strings, and QUOTE_MINIMAL
18285        // triggers (comma / quote / CR / LF), across default + na_rep + no-header +
18286        // single-column (empty-na quoting) configs.
18287        let rows: Vec<Option<&str>> = vec![
18288            Some("Alice"),
18289            None,
18290            Some("a,b"),        // comma ⇒ quoted
18291            Some("he\"llo"),    // embedded quote ⇒ quoted + doubled
18292            Some(""),           // present empty string
18293            None,
18294            Some("line\nbrk"),  // LF ⇒ quoted
18295            Some("tab\tok"),    // tab (not a QUOTE_MINIMAL trigger) ⇒ unquoted
18296            Some("plain"),
18297        ];
18298        let n = rows.len();
18299
18300        // Build the nullable Utf8 column two ways.
18301        let mut bytes: Vec<u8> = Vec::new();
18302        let mut offsets: Vec<usize> = vec![0];
18303        let mut validity = fp_columnar::ValidityMask::all_valid(n);
18304        let mut eager: Vec<Scalar> = Vec::with_capacity(n);
18305        for (i, r) in rows.iter().enumerate() {
18306            match r {
18307                Some(s) => {
18308                    bytes.extend_from_slice(s.as_bytes());
18309                    eager.push(Scalar::Utf8((*s).to_string()));
18310                }
18311                None => {
18312                    validity.set(i, false);
18313                    eager.push(Scalar::Null(fp_types::NullKind::Null));
18314                }
18315            }
18316            offsets.push(bytes.len());
18317        }
18318
18319        let mk = |name_col: Column| -> DataFrame {
18320            let mut cols = std::collections::BTreeMap::new();
18321            cols.insert(
18322                "id".to_string(),
18323                Column::from_i64_values_owned((0..n as i64).collect()),
18324            );
18325            cols.insert("name".to_string(), name_col);
18326            DataFrame::new_with_column_order(
18327                Index::new_known_unique_int64_unit_range(0, n),
18328                cols,
18329                vec!["id".to_string(), "name".to_string()],
18330            )
18331            .unwrap()
18332        };
18333        let frame_fast = mk(Column::from_utf8_values_with_validity(
18334            bytes,
18335            offsets,
18336            validity,
18337        ));
18338        let frame_general = mk(Column::from_values(eager).unwrap());
18339
18340        // The general frame's name column must be OFF the fast Utf8 path.
18341        let ctl = frame_general.column("name").unwrap();
18342        assert!(
18343            ctl.as_utf8_contiguous().is_none() && ctl.as_nullable_utf8_contiguous().is_none(),
18344            "control name column must be on the general writer"
18345        );
18346
18347        for options in [
18348            CsvWriteOptions::default(),
18349            CsvWriteOptions {
18350                na_rep: "NA".to_string(),
18351                ..CsvWriteOptions::default()
18352            },
18353            CsvWriteOptions {
18354                header: false,
18355                ..CsvWriteOptions::default()
18356            },
18357        ] {
18358            let fast = write_csv_string_with_options(&frame_fast, &options).expect("fast");
18359            let general = write_csv_string_with_options(&frame_general, &options).expect("general");
18360            assert_eq!(fast, general, "fast nullable-Utf8 CSV must byte-match the general writer");
18361        }
18362
18363        // Single-column nullable Utf8 frame: exercises the empty-na `""` quoting on a
18364        // missing sole field.
18365        let single_fast = {
18366            let mut c = std::collections::BTreeMap::new();
18367            let mut b: Vec<u8> = Vec::new();
18368            let mut o: Vec<usize> = vec![0];
18369            let mut v = fp_columnar::ValidityMask::all_valid(n);
18370            for (i, r) in rows.iter().enumerate() {
18371                if let Some(s) = r {
18372                    b.extend_from_slice(s.as_bytes());
18373                } else {
18374                    v.set(i, false);
18375                }
18376                o.push(b.len());
18377            }
18378            c.insert("name".to_string(), Column::from_utf8_values_with_validity(b, o, v));
18379            DataFrame::new(Index::new_known_unique_int64_unit_range(0, n), c).unwrap()
18380        };
18381        let single_general = {
18382            let mut c = std::collections::BTreeMap::new();
18383            c.insert("name".to_string(), Column::from_values(eager_clone(&rows)).unwrap());
18384            DataFrame::new(Index::new_known_unique_int64_unit_range(0, n), c).unwrap()
18385        };
18386        let f = write_csv_string(&single_fast).expect("fast single");
18387        let g = write_csv_string(&single_general).expect("general single");
18388        assert_eq!(f, g, "single-column nullable-Utf8 CSV must byte-match the general writer");
18389    }
18390
18391    #[cfg(test)]
18392    fn eager_clone(rows: &[Option<&str>]) -> Vec<Scalar> {
18393        rows.iter()
18394            .map(|r| match r {
18395                Some(s) => Scalar::Utf8((*s).to_string()),
18396                None => Scalar::Null(fp_types::NullKind::Null),
18397            })
18398            .collect()
18399    }
18400
18401    #[test]
18402    fn test_write_json_nullable_utf8_fast_matches_serde() {
18403        // A nullable contiguous-Utf8 column (LazyNullableUtf8) now takes the typed JSON
18404        // fast writer (JCol::UN). It must produce BYTE-IDENTICAL output to the serde-tree
18405        // fallback, which an EAGER Utf8 column with the same data falls to. Covers
18406        // present/missing (→ null), empty strings, and JSON escape triggers (quote,
18407        // backslash, control byte) across Records + Columns orients.
18408        let rows: Vec<Option<&str>> = vec![
18409            Some("Alice"),
18410            None,
18411            Some("a\"b"),      // embedded quote ⇒ JSON-escaped
18412            Some("back\\sl"),  // backslash ⇒ escaped
18413            Some(""),          // present empty string
18414            None,
18415            Some("tab\tnl\n"), // control bytes ⇒ escaped
18416            Some("héllo"),     // multi-byte UTF-8 (passes through)
18417            Some("plain"),
18418        ];
18419        let n = rows.len();
18420
18421        let mut bytes: Vec<u8> = Vec::new();
18422        let mut offsets: Vec<usize> = vec![0];
18423        let mut validity = fp_columnar::ValidityMask::all_valid(n);
18424        for (i, r) in rows.iter().enumerate() {
18425            if let Some(s) = r {
18426                bytes.extend_from_slice(s.as_bytes());
18427            } else {
18428                validity.set(i, false);
18429            }
18430            offsets.push(bytes.len());
18431        }
18432
18433        let mk = |name_col: Column| -> DataFrame {
18434            let mut cols = std::collections::BTreeMap::new();
18435            cols.insert(
18436                "id".to_string(),
18437                Column::from_i64_values_owned((0..n as i64).collect()),
18438            );
18439            cols.insert("name".to_string(), name_col);
18440            DataFrame::new_with_column_order(
18441                Index::new_known_unique_int64_unit_range(0, n),
18442                cols,
18443                vec!["id".to_string(), "name".to_string()],
18444            )
18445            .unwrap()
18446        };
18447        let frame_fast = mk(Column::from_utf8_values_with_validity(bytes, offsets, validity));
18448        let frame_general = mk(Column::from_values(eager_clone(&rows)).unwrap());
18449
18450        let ctl = frame_general.column("name").unwrap();
18451        assert!(
18452            ctl.as_utf8_contiguous().is_none() && ctl.as_nullable_utf8_contiguous().is_none(),
18453            "control name column must be on the serde tree"
18454        );
18455
18456        for orient in [JsonOrient::Records, JsonOrient::Columns] {
18457            let fast = write_json_string(&frame_fast, orient).expect("fast json");
18458            let general = write_json_string(&frame_general, orient).expect("general json");
18459            assert_eq!(
18460                fast, general,
18461                "fast nullable-Utf8 JSON ({orient:?}) must byte-match the serde tree"
18462            );
18463        }
18464    }
18465
18466    #[test]
18467    fn test_write_json_nullable_numeric_fast_matches_serde() {
18468        // Nullable Float64 (JCol::FN) and Int64 (JCol::IN) columns take the typed JSON
18469        // fast writer. Output must be BYTE-IDENTICAL to the serde tree (which the same
18470        // frame falls to when an EAGER Utf8 column forces it off the fast path). Covers:
18471        // validity-clear missing (→ null), valid-bit NaN (→ null), ±inf (→ null), whole
18472        // numbers, negatives, 1e20, i64::MIN/MAX; Records + Columns orients.
18473        let n = 9usize;
18474        let fdata: Vec<f64> = vec![
18475            1.0,
18476            -2.5,
18477            0.0,
18478            f64::NAN,
18479            1e20,
18480            f64::INFINITY,
18481            3.14159,
18482            f64::NEG_INFINITY,
18483            42.0,
18484        ];
18485        let mut fv = fp_columnar::ValidityMask::all_valid(n);
18486        fv.set(2, false); // validity-clear (data 0.0 → null)
18487        // slot 3 valid-bit NaN, slots 5/7 valid ±inf → all render null.
18488
18489        let idata: Vec<i64> = vec![0, i64::MIN, i64::MAX, -1, 1000, 0, -999999, 7, 123456789];
18490        let mut iv = fp_columnar::ValidityMask::all_valid(n);
18491        iv.set(0, false);
18492        iv.set(5, false);
18493
18494        // nullable Bool (JCol::BN): present ⇒ true/false, missing ⇒ null.
18495        let bdata: Vec<bool> = vec![true, false, true, false, true, false, true, false, true];
18496        let mut bv = fp_columnar::ValidityMask::all_valid(n);
18497        bv.set(2, false);
18498        bv.set(6, false);
18499
18500        let names: Vec<&str> = vec!["a", "b", "c", "d", "e", "f", "g", "h", "z"];
18501        let mut nb: Vec<u8> = Vec::new();
18502        let mut no: Vec<usize> = vec![0];
18503        for s in &names {
18504            nb.extend_from_slice(s.as_bytes());
18505            no.push(nb.len());
18506        }
18507        let eager_names: Vec<Scalar> =
18508            names.iter().map(|s| Scalar::Utf8((*s).to_string())).collect();
18509
18510        let mk = |name_col: Column| -> DataFrame {
18511            let mut cols = std::collections::BTreeMap::new();
18512            cols.insert(
18513                "f".to_string(),
18514                Column::from_f64_values_with_validity(fdata.clone(), fv.clone()),
18515            );
18516            cols.insert(
18517                "i".to_string(),
18518                Column::from_i64_values_with_validity(idata.clone(), iv.clone()),
18519            );
18520            cols.insert(
18521                "b".to_string(),
18522                Column::from_bool_values_with_validity(bdata.clone(), bv.clone()),
18523            );
18524            cols.insert("name".to_string(), name_col);
18525            DataFrame::new_with_column_order(
18526                Index::new_known_unique_int64_unit_range(0, n),
18527                cols,
18528                vec![
18529                    "f".to_string(),
18530                    "i".to_string(),
18531                    "b".to_string(),
18532                    "name".to_string(),
18533                ],
18534            )
18535            .unwrap()
18536        };
18537        let frame_fast = mk(Column::from_utf8_contiguous(nb, no));
18538        let frame_general = mk(Column::from_values(eager_names).unwrap());
18539
18540        let ctl = frame_general.column("name").unwrap();
18541        assert!(
18542            ctl.as_utf8_contiguous().is_none() && ctl.as_nullable_utf8_contiguous().is_none(),
18543            "control name column must force the serde tree"
18544        );
18545
18546        for orient in [JsonOrient::Records, JsonOrient::Columns] {
18547            let fast = write_json_string(&frame_fast, orient).expect("fast json");
18548            let general = write_json_string(&frame_general, orient).expect("general json");
18549            assert_eq!(
18550                fast, general,
18551                "fast nullable-numeric JSON ({orient:?}) must byte-match the serde tree"
18552            );
18553        }
18554    }
18555
18556    #[test]
18557    fn test_write_csv_nullable_typed_fast_matches_general() {
18558        // Nullable Float64 (FastCol::FN), Int64 (FastCol::IN), and Bool (FastCol::BN)
18559        // columns take the fast CSV writer. Output must be BYTE-IDENTICAL to the general
18560        // (Scalar) writer, which the same frame falls to when an EAGER Utf8 column forces
18561        // it off the fast path.
18562        // Covers: validity-clear missing, a valid-bit NaN (still → na_rep), whole numbers
18563        // ("1.0"), negatives, large magnitude (sci notation), i64::MIN/MAX; default +
18564        // na_rep configs.
18565        let n = 9usize;
18566        let fdata: Vec<f64> = vec![1.0, -2.5, 0.0, f64::NAN, 1e20, -0.0, 3.14159, 100.0, 42.0];
18567        let mut fv = fp_columnar::ValidityMask::all_valid(n);
18568        fv.set(2, false); // validity-clear (data 0.0 → must render na_rep, not "0.0")
18569        fv.set(7, false); // validity-clear
18570        // slot 3 is a VALID-bit NaN (fv still set) → must also render na_rep.
18571
18572        let idata: Vec<i64> = vec![0, i64::MIN, i64::MAX, -1, 1000, 0, -999999, 7, 123456789];
18573        let mut iv = fp_columnar::ValidityMask::all_valid(n);
18574        iv.set(0, false); // validity-clear (data 0 → na_rep, not "0")
18575        iv.set(5, false);
18576
18577        // nullable Bool: present ⇒ True/False, missing ⇒ na_rep.
18578        let bdata = vec![true, false, true, false, true, false, true, false, true];
18579        let mut bv = fp_columnar::ValidityMask::all_valid(n);
18580        bv.set(1, false); // validity-clear (data false → na_rep, not "False")
18581        bv.set(8, false); // validity-clear (data true → na_rep, not "True")
18582
18583        let names: Vec<&str> = vec![
18584            "a", "b,c", "d", "e", "", "f\"g", "h", "plain", "z",
18585        ];
18586        let mut nb: Vec<u8> = Vec::new();
18587        let mut no: Vec<usize> = vec![0];
18588        for s in &names {
18589            nb.extend_from_slice(s.as_bytes());
18590            no.push(nb.len());
18591        }
18592        let eager_names: Vec<Scalar> =
18593            names.iter().map(|s| Scalar::Utf8((*s).to_string())).collect();
18594
18595        let mk = |name_col: Column| -> DataFrame {
18596            let mut cols = std::collections::BTreeMap::new();
18597            cols.insert(
18598                "f".to_string(),
18599                Column::from_f64_values_with_validity(fdata.clone(), fv.clone()),
18600            );
18601            cols.insert(
18602                "i".to_string(),
18603                Column::from_i64_values_with_validity(idata.clone(), iv.clone()),
18604            );
18605            cols.insert(
18606                "b".to_string(),
18607                Column::from_bool_values_with_validity(bdata.clone(), bv.clone()),
18608            );
18609            cols.insert("name".to_string(), name_col);
18610            DataFrame::new_with_column_order(
18611                Index::new_known_unique_int64_unit_range(0, n),
18612                cols,
18613                vec![
18614                    "f".to_string(),
18615                    "i".to_string(),
18616                    "b".to_string(),
18617                    "name".to_string(),
18618                ],
18619            )
18620            .unwrap()
18621        };
18622        let frame_fast = mk(Column::from_utf8_contiguous(nb, no));
18623        let frame_general = mk(Column::from_values(eager_names).unwrap());
18624
18625        // The eager name column forces the whole general frame off the fast path.
18626        let ctl = frame_general.column("name").unwrap();
18627        assert!(
18628            ctl.as_utf8_contiguous().is_none() && ctl.as_nullable_utf8_contiguous().is_none(),
18629            "control name column must force the general writer"
18630        );
18631
18632        for options in [
18633            CsvWriteOptions::default(),
18634            CsvWriteOptions {
18635                na_rep: "NA".to_string(),
18636                ..CsvWriteOptions::default()
18637            },
18638        ] {
18639            assert!(
18640                super::try_write_csv_typed(&frame_fast, &options).is_some(),
18641                "nullable typed frame must stay on the fast CSV writer"
18642            );
18643            let fast = write_csv_string_with_options(&frame_fast, &options).expect("fast");
18644            let general = write_csv_string_with_options(&frame_general, &options).expect("general");
18645            assert_eq!(
18646                fast, general,
18647                "fast nullable-numeric CSV must byte-match the general writer"
18648            );
18649        }
18650    }
18651
18652    #[test]
18653    fn test_write_csv_options_header_false_omits_header_row() {
18654        let input = "a,b\n1,2\n";
18655        let frame = read_csv_str(input).expect("read");
18656        let output = write_csv_string_with_options(
18657            &frame,
18658            &CsvWriteOptions {
18659                header: false,
18660                ..CsvWriteOptions::default()
18661            },
18662        )
18663        .expect("write");
18664        assert_eq!(output, "1,2\n");
18665    }
18666
18667    #[test]
18668    fn test_write_csv_options_include_index_and_index_label() {
18669        let input = "a,b\n1,2\n3,4\n";
18670        let frame = read_csv_str(input).expect("read");
18671        let output = write_csv_string_with_options(
18672            &frame,
18673            &CsvWriteOptions {
18674                include_index: true,
18675                index_label: Some("row_id".to_string()),
18676                ..CsvWriteOptions::default()
18677            },
18678        )
18679        .expect("write");
18680
18681        assert_eq!(output, "row_id,a,b\n0,1,2\n1,3,4\n");
18682    }
18683
18684    #[test]
18685    fn test_write_csv_options_include_index_uses_named_index_when_label_omitted() {
18686        let mut cols = std::collections::BTreeMap::new();
18687        cols.insert(
18688            "a".to_string(),
18689            Column::from_values(vec![Scalar::Int64(10), Scalar::Int64(20)]).unwrap(),
18690        );
18691        let frame = DataFrame::new_with_column_order(
18692            Index::from_i64(vec![100, 200]).set_name("sample_id"),
18693            cols,
18694            vec!["a".to_string()],
18695        )
18696        .unwrap();
18697
18698        let output = write_csv_string_with_options(
18699            &frame,
18700            &CsvWriteOptions {
18701                include_index: true,
18702                ..CsvWriteOptions::default()
18703            },
18704        )
18705        .expect("write");
18706
18707        assert_eq!(output, "sample_id,a\n100,10\n200,20\n");
18708    }
18709
18710    #[test]
18711    fn test_write_csv_options_include_index_label_overrides_index_name() {
18712        let mut cols = std::collections::BTreeMap::new();
18713        cols.insert(
18714            "a".to_string(),
18715            Column::from_values(vec![Scalar::Int64(10), Scalar::Int64(20)]).unwrap(),
18716        );
18717        let frame = DataFrame::new_with_column_order(
18718            Index::from_i64(vec![100, 200]).set_name("sample_id"),
18719            cols,
18720            vec!["a".to_string()],
18721        )
18722        .unwrap();
18723
18724        let output = write_csv_string_with_options(
18725            &frame,
18726            &CsvWriteOptions {
18727                include_index: true,
18728                index_label: Some("row".to_string()),
18729                ..CsvWriteOptions::default()
18730            },
18731        )
18732        .expect("write");
18733
18734        assert_eq!(output, "row,a\n100,10\n200,20\n");
18735    }
18736
18737    #[test]
18738    fn test_csv_multiindex_roundtrip_with_explicit_index_cols() {
18739        let frame = make_row_multiindex_test_dataframe();
18740        let csv = write_csv_string_with_options(
18741            &frame,
18742            &CsvWriteOptions {
18743                include_index: true,
18744                ..CsvWriteOptions::default()
18745            },
18746        )
18747        .expect("write");
18748
18749        let roundtrip = read_csv_with_index_cols(
18750            &csv,
18751            &CsvReadOptions::default(),
18752            &["region", "product", "year"],
18753        )
18754        .expect("read");
18755
18756        assert!(roundtrip.equals(&frame));
18757        assert_eq!(roundtrip.row_multiindex(), frame.row_multiindex());
18758    }
18759
18760    #[test]
18761    fn test_write_csv_options_default_matches_write_csv_string() {
18762        let input = "a,b\n1,2\n3,4\n";
18763        let frame = read_csv_str(input).expect("read");
18764        let default_output = write_csv_string(&frame).expect("write");
18765        let options_output =
18766            write_csv_string_with_options(&frame, &CsvWriteOptions::default()).expect("write");
18767        assert_eq!(default_output, options_output);
18768    }
18769
18770    #[test]
18771    fn test_write_csv_options_na_rep_with_float_nan() {
18772        // Generate a frame with an explicit NaN float.
18773        use fp_columnar::Column;
18774        let mut cols = std::collections::BTreeMap::new();
18775        cols.insert(
18776            "score".to_string(),
18777            Column::from_values(vec![Scalar::Float64(1.5), Scalar::Float64(f64::NAN)]).unwrap(),
18778        );
18779        let frame = DataFrame::new_with_column_order(
18780            Index::from_i64(vec![0, 1]),
18781            cols,
18782            vec!["score".to_string()],
18783        )
18784        .unwrap();
18785        let output = write_csv_string_with_options(
18786            &frame,
18787            &CsvWriteOptions {
18788                na_rep: "NaN".to_string(),
18789                ..CsvWriteOptions::default()
18790            },
18791        )
18792        .expect("write");
18793        assert!(output.contains("NaN"));
18794    }
18795
18796    #[test]
18797    fn test_csv_large_file_perf() {
18798        // 100K-row, 10-column CSV -> parse completes, correct row/column counts.
18799        let col_count = 10;
18800        let row_count = 100_000;
18801        let headers: Vec<String> = (0..col_count).map(|i| format!("col{i}")).collect();
18802        let mut csv = String::with_capacity(row_count * 50);
18803        csv.push_str(&headers.join(","));
18804        csv.push('\n');
18805        for r in 0..row_count {
18806            for c in 0..col_count {
18807                if c > 0 {
18808                    csv.push(',');
18809                }
18810                csv.push_str(&(r * col_count + c).to_string());
18811            }
18812            csv.push('\n');
18813        }
18814
18815        let frame = read_csv_str(&csv).expect("parse 100K rows");
18816        assert_eq!(frame.index().len(), row_count);
18817        assert_eq!(frame.columns().len(), col_count);
18818        // Spot-check first and last rows
18819        assert_eq!(frame.column("col0").unwrap().values()[0], Scalar::Int64(0));
18820        assert_eq!(
18821            frame.column("col9").unwrap().values()[row_count - 1],
18822            Scalar::Int64(((row_count - 1) * col_count + 9) as i64)
18823        );
18824        eprintln!(
18825            "[TEST] test_csv_large_file_perf | rows={row_count} cols={col_count} parse_ok=true | PASS"
18826        );
18827    }
18828
18829    #[test]
18830    fn test_csv_golden_output() {
18831        // Fixed CSV input -> write_csv_string output matches golden reference exactly.
18832        let input = "a,b,c\n1,hello,3.14\n2,,true\n3,world,\n";
18833        let frame = read_csv_str(input).expect("parse");
18834        let output = write_csv_string(&frame).expect("write");
18835
18836        // Golden reference: columns in BTreeMap order; Bool(true) coerced to Float64
18837        // in column c (which has Float64 + Bool → Float64), so true → 1.0. A Float64
18838        // column writes whole values with a trailing ".0" like pandas (str(float)).
18839        let expected = "a,b,c\n1,hello,3.14\n2,,1.0\n3,world,\n";
18840        assert_eq!(
18841            output, expected,
18842            "output does not match golden reference.\nGot:\n{output}\nExpected:\n{expected}"
18843        );
18844        eprintln!("[TEST] test_csv_golden_output | golden_match=true | PASS");
18845    }
18846
18847    // === bd-2gi.19: IO Complete Contract Tests ===
18848
18849    use super::{CsvOnBadLines, CsvReadOptions, read_csv_with_options};
18850
18851    #[test]
18852    fn csv_with_custom_delimiter() {
18853        let input = "a\tb\tc\n1\t2\t3\n4\t5\t6\n";
18854        let opts = CsvReadOptions {
18855            delimiter: b'\t',
18856            ..Default::default()
18857        };
18858        let frame = read_csv_with_options(input, &opts).expect("parse tsv");
18859        assert_eq!(frame.index().len(), 2);
18860        assert_eq!(frame.column("a").unwrap().values()[0], Scalar::Int64(1));
18861    }
18862
18863    #[test]
18864    fn csv_without_headers_generates_default_names_and_keeps_first_row() {
18865        let input = "1,2\n3,4\n";
18866        let opts = CsvReadOptions {
18867            has_headers: false,
18868            ..Default::default()
18869        };
18870        let frame = read_csv_with_options(input, &opts).expect("parse");
18871        assert_eq!(frame.index().len(), 2);
18872        assert_eq!(
18873            frame.column("column_0").unwrap().values()[0],
18874            Scalar::Int64(1)
18875        );
18876        assert_eq!(
18877            frame.column("column_1").unwrap().values()[0],
18878            Scalar::Int64(2)
18879        );
18880        assert_eq!(
18881            frame.column("column_0").unwrap().values()[1],
18882            Scalar::Int64(3)
18883        );
18884        assert_eq!(
18885            frame.column("column_1").unwrap().values()[1],
18886            Scalar::Int64(4)
18887        );
18888    }
18889
18890    #[test]
18891    fn csv_usecols_missing_column_errors() {
18892        let input = "a,b\n1,2\n";
18893        let opts = CsvReadOptions {
18894            usecols: Some(vec!["c".to_string()]),
18895            ..Default::default()
18896        };
18897        let err = read_csv_with_options(input, &opts).expect_err("missing usecols");
18898        assert!(
18899            matches!(err, IoError::MissingUsecols(missing) if missing == vec!["c".to_string()])
18900        );
18901    }
18902
18903    #[test]
18904    fn csv_without_headers_supports_generated_index_col_name() {
18905        let input = "10,alpha\n20,beta\n";
18906        let opts = CsvReadOptions {
18907            has_headers: false,
18908            index_col: Some("column_0".into()),
18909            ..Default::default()
18910        };
18911        let frame = read_csv_with_options(input, &opts).expect("parse");
18912        assert_eq!(frame.index().len(), 2);
18913        assert_eq!(frame.index().labels()[0], IndexLabel::Int64(10));
18914        assert_eq!(frame.index().labels()[1], IndexLabel::Int64(20));
18915        assert!(frame.column("column_0").is_none());
18916        assert_eq!(
18917            frame.column("column_1").unwrap().values()[0],
18918            Scalar::Utf8("alpha".into())
18919        );
18920        assert_eq!(
18921            frame.column("column_1").unwrap().values()[1],
18922            Scalar::Utf8("beta".into())
18923        );
18924    }
18925
18926    #[test]
18927    fn csv_with_na_values() {
18928        let input = "a,b\n1,NA\n2,n/a\n3,valid\n";
18929        let opts = CsvReadOptions {
18930            na_values: vec!["NA".into(), "n/a".into()],
18931            ..Default::default()
18932        };
18933        let frame = read_csv_with_options(input, &opts).expect("parse");
18934        let b = frame.column("b").unwrap();
18935        assert!(b.values()[0].is_missing());
18936        assert!(b.values()[1].is_missing());
18937        assert_eq!(b.values()[2], Scalar::Utf8("valid".into()));
18938    }
18939
18940    #[test]
18941    fn csv_none_is_default_na() {
18942        // "None" is a pandas default NA value (Python's None)
18943        let input = "a,b\n1,None\n2,valid\n";
18944        let frame = read_csv_str(input).expect("parse");
18945        let b = frame.column("b").unwrap();
18946        assert!(b.values()[0].is_missing(), "None should be parsed as NA");
18947        assert_eq!(b.values()[1], Scalar::Utf8("valid".into()));
18948    }
18949
18950    #[test]
18951    fn csv_scalar_inference_matches_pandas_2_2_3() {
18952        // Per-cell type inference verified against pandas 2.2.3 read_csv.
18953        let cell = |csv: &str| {
18954            let frame = read_csv_str(&format!("x\n{csv}\n")).expect("parse");
18955            frame.column("x").unwrap().values()[0].clone()
18956        };
18957        // Signed / leading-zero integers parse as Int64 (Rust + pandas agree).
18958        assert_eq!(cell("+1"), Scalar::Int64(1));
18959        assert_eq!(cell("01"), Scalar::Int64(1));
18960        assert_eq!(cell("-5"), Scalar::Int64(-5));
18961        // Scientific notation is float64 in pandas.
18962        assert_eq!(cell("1e3"), Scalar::Float64(1000.0));
18963        // inf / -inf are float values (NOT default-NA tokens, unlike nan).
18964        assert_eq!(cell("inf"), Scalar::Float64(f64::INFINITY));
18965        assert_eq!(cell("-inf"), Scalar::Float64(f64::NEG_INFINITY));
18966        // Bool inference is case-insensitive in pandas 2.2.3.
18967        assert_eq!(cell("TRUE"), Scalar::Bool(true));
18968        assert_eq!(cell("true"), Scalar::Bool(true));
18969        assert_eq!(cell("False"), Scalar::Bool(false));
18970        // Surrounding whitespace is trimmed ONLY for numeric inference.
18971        assert_eq!(cell(" 1 "), Scalar::Int64(1));
18972        assert_eq!(cell("  3.5  "), Scalar::Float64(3.5));
18973        // Non-numeric, non-bool stays Utf8.
18974        assert_eq!(cell("hello"), Scalar::Utf8("hello".into()));
18975        // NA markers, booleans, and plain strings keep their surrounding
18976        // whitespace — a padded value is a STRING, not null/bool. Verified vs
18977        // live pandas 2.2.3: " abc "/"true "/" NA " all stay object strings.
18978        assert_eq!(cell(" abc "), Scalar::Utf8(" abc ".into()));
18979        assert_eq!(cell("true "), Scalar::Utf8("true ".into()));
18980        assert_eq!(cell(" True "), Scalar::Utf8(" True ".into()));
18981        assert_eq!(cell(" NA "), Scalar::Utf8(" NA ".into()));
18982        assert!(!matches!(cell(" NA "), Scalar::Null(_)));
18983    }
18984
18985    #[test]
18986    fn json_write_non_finite_floats_as_null_like_pandas() {
18987        // pandas to_json(orient="records") converts inf / -inf / NaN to JSON
18988        // `null` (JSON has no inf/nan literals). Verified vs pandas 2.2.3:
18989        // read_csv("x\n1.5\ninf\n-inf\n").to_json(orient="records")
18990        //   == [{"x":1.5},{"x":null},{"x":null}]
18991        let frame = read_csv_str("x\n1.5\ninf\n-inf\n").expect("parse");
18992        let json = write_json_string(&frame, JsonOrient::Records).expect("json");
18993        assert_eq!(json, r#"[{"x":1.5},{"x":null},{"x":null}]"#);
18994    }
18995
18996    #[test]
18997    fn csv_default_na_token_set_matches_pandas_table() {
18998        let default_tokens = [
18999            "", "#N/A", "#N/A N/A", "#NA", "-1.#IND", "-1.#QNAN", "-NaN", "-nan", "1.#IND",
19000            "1.#QNAN", "<NA>", "N/A", "NA", "NULL", "NaN", "None", "n/a", "nan", "null",
19001        ];
19002        for token in default_tokens {
19003            assert!(super::is_pandas_default_na(token), "{token:?}");
19004        }
19005
19006        for token in ["none", "NAN", "n/a ", " NULL", "0", "false"] {
19007            assert!(!super::is_pandas_default_na(token), "{token:?}");
19008        }
19009    }
19010
19011    #[test]
19012    fn csv_keep_default_na_false() {
19013        // With keep_default_na=false, only custom na_values are recognized
19014        let input = "a,b\n1,NA\n2,CUSTOM\n3,valid\n";
19015        let opts = CsvReadOptions {
19016            na_values: vec!["CUSTOM".into()],
19017            keep_default_na: false,
19018            ..Default::default()
19019        };
19020        let frame = read_csv_with_options(input, &opts).expect("parse");
19021        let b = frame.column("b").unwrap();
19022        // "NA" should NOT be missing because keep_default_na=false
19023        assert_eq!(b.values()[0], Scalar::Utf8("NA".into()));
19024        // "CUSTOM" should be missing because it's in na_values
19025        assert!(b.values()[1].is_missing());
19026        assert_eq!(b.values()[2], Scalar::Utf8("valid".into()));
19027    }
19028
19029    #[test]
19030    fn csv_na_filter_false() {
19031        // With na_filter=false, no NA detection at all (for performance)
19032        let input = "a,b\n1,NA\n2,\n3,None\n";
19033        let opts = CsvReadOptions {
19034            na_filter: false,
19035            ..Default::default()
19036        };
19037        let frame = read_csv_with_options(input, &opts).expect("parse");
19038        let b = frame.column("b").unwrap();
19039        // All values should be kept as strings, no NA detection
19040        assert_eq!(b.values()[0], Scalar::Utf8("NA".into()));
19041        assert_eq!(b.values()[1], Scalar::Utf8("".into()));
19042        assert_eq!(b.values()[2], Scalar::Utf8("None".into()));
19043    }
19044
19045    #[test]
19046    fn csv_with_index_col() {
19047        let input = "id,val\na,10\nb,20\nc,30\n";
19048        let opts = CsvReadOptions {
19049            index_col: Some("id".into()),
19050            ..Default::default()
19051        };
19052        let frame = read_csv_with_options(input, &opts).expect("parse");
19053        assert_eq!(frame.index().len(), 3);
19054        assert_eq!(
19055            frame.index().labels()[0],
19056            fp_index::IndexLabel::Utf8("a".into())
19057        );
19058        assert!(frame.column("id").is_none());
19059        assert_eq!(frame.column("val").unwrap().values()[0], Scalar::Int64(10));
19060    }
19061
19062    #[test]
19063    fn csv_with_missing_index_col_errors() {
19064        let input = "id,val\na,10\nb,20\n";
19065        let opts = CsvReadOptions {
19066            index_col: Some("missing".into()),
19067            ..Default::default()
19068        };
19069
19070        let err = read_csv_with_options(input, &opts).expect_err("missing index_col should error");
19071        assert!(
19072            matches!(&err, IoError::MissingIndexColumn(name) if name == "missing"),
19073            "expected MissingIndexColumn(\"missing\"), got {err:?}"
19074        );
19075    }
19076
19077    #[test]
19078    fn csv_with_malformed_row_errors() {
19079        let input = "a,b\n1,2\n3\n";
19080        let opts = CsvReadOptions::default();
19081
19082        let err = read_csv_with_options(input, &opts).expect_err("malformed CSV row should error");
19083        assert!(
19084            matches!(&err, IoError::Csv(_)),
19085            "expected CSV parser error for ragged row, got {err:?}"
19086        );
19087    }
19088
19089    #[test]
19090    fn csv_on_bad_lines_skip_skips_extra_field_rows() {
19091        let input = "a,b\n1,2\n3,4,5\n6,7\n";
19092        let opts = CsvReadOptions {
19093            on_bad_lines: CsvOnBadLines::Skip,
19094            ..Default::default()
19095        };
19096
19097        let frame = read_csv_with_options(input, &opts).expect("parse with skipped bad line");
19098        assert_eq!(frame.index().len(), 2);
19099        assert_eq!(frame.column("a").unwrap().values()[0], Scalar::Int64(1));
19100        assert_eq!(frame.column("b").unwrap().values()[0], Scalar::Int64(2));
19101        assert_eq!(frame.column("a").unwrap().values()[1], Scalar::Int64(6));
19102        assert_eq!(frame.column("b").unwrap().values()[1], Scalar::Int64(7));
19103    }
19104
19105    #[test]
19106    fn csv_on_bad_lines_warn_skips_extra_field_rows() {
19107        let input = "a,b\n1,2\n3,4,5\n6,7\n";
19108        let opts = CsvReadOptions {
19109            on_bad_lines: CsvOnBadLines::Warn,
19110            ..Default::default()
19111        };
19112
19113        let frame = read_csv_with_options(input, &opts).expect("parse with warned bad line");
19114        assert_eq!(frame.index().len(), 2);
19115        assert_eq!(frame.column("a").unwrap().values()[0], Scalar::Int64(1));
19116        assert_eq!(frame.column("b").unwrap().values()[1], Scalar::Int64(7));
19117    }
19118
19119    #[test]
19120    fn csv_on_bad_lines_skip_preserves_short_rows_as_missing() {
19121        // DISC-011: Int64 columns with missing values stay Int64 (extension dtype parity).
19122        // Missing values use NullKind::Null (pd.NA semantics) not NullKind::NaN.
19123        let input = "a,b\n1,2\n3\n6,7\n";
19124        let opts = CsvReadOptions {
19125            on_bad_lines: CsvOnBadLines::Skip,
19126            ..Default::default()
19127        };
19128
19129        let frame = read_csv_with_options(input, &opts).expect("parse short row");
19130        assert_eq!(frame.index().len(), 3);
19131        assert_eq!(frame.column("a").unwrap().values()[1], Scalar::Int64(3));
19132        assert_eq!(
19133            frame.column("b").unwrap().values()[1],
19134            Scalar::Null(NullKind::Null)
19135        );
19136    }
19137
19138    #[test]
19139    fn json_temporal_values_and_index_are_epoch_millis() {
19140        // pandas to_json (date_unit='ms') serializes datetime64/timedelta64 as
19141        // epoch-millisecond integers for both values and index — not ISO/format
19142        // strings (values) nor raw nanoseconds (index). (br-frankenpandas-lb0iu)
19143        // 2020-01-01T00:00:00 == 1_577_836_800_000 ms; 1s timedelta == 1000 ms.
19144        let dt_ns = 1_577_836_800_000_000_000_i64;
19145        let mut columns = BTreeMap::new();
19146        columns.insert(
19147            "d".to_owned(),
19148            Column::from_values(vec![Scalar::Datetime64(dt_ns)]).expect("d"),
19149        );
19150        columns.insert(
19151            "t".to_owned(),
19152            Column::from_values(vec![Scalar::Timedelta64(1_000_000_000)]).expect("t"),
19153        );
19154        let index = Index::new(vec![IndexLabel::Datetime64(dt_ns)]);
19155        let frame =
19156            DataFrame::new_with_column_order(index, columns, vec!["d".to_owned(), "t".to_owned()])
19157                .expect("frame");
19158
19159        let out = write_json_string(&frame, JsonOrient::Columns).expect("json");
19160        assert!(
19161            out.contains("1577836800000"),
19162            "datetime value/index should be epoch-millis int, got {out}"
19163        );
19164        assert!(
19165            out.contains("1000"),
19166            "timedelta value should be epoch-millis int (1000), got {out}"
19167        );
19168        // Must NOT contain the old ISO string or raw-nanosecond forms.
19169        assert!(
19170            !out.contains("2020-01-01"),
19171            "should not emit ISO string: {out}"
19172        );
19173        assert!(
19174            !out.contains("1577836800000000000"),
19175            "should not emit raw nanoseconds: {out}"
19176        );
19177    }
19178
19179    #[test]
19180    fn json_records_read_write_roundtrip() {
19181        let input = r#"[{"name":"Alice","age":30},{"name":"Bob","age":25}]"#;
19182        let frame = read_json_str(input, JsonOrient::Records).expect("read json records");
19183        assert_eq!(frame.index().len(), 2);
19184        assert_eq!(
19185            frame.column("name").unwrap().values()[0],
19186            Scalar::Utf8("Alice".into())
19187        );
19188        assert_eq!(frame.column("age").unwrap().values()[1], Scalar::Int64(25));
19189
19190        let output = write_json_string(&frame, JsonOrient::Records).expect("write");
19191        let frame2 = read_json_str(&output, JsonOrient::Records).expect("re-read");
19192        assert_eq!(frame2.index().len(), 2);
19193    }
19194
19195    #[test]
19196    fn json_records_nullable_int_roundtrip_is_stable() {
19197        let input = r#"[{"city":"Boston","temp":72},{"city":"Paris","temp":null}]"#;
19198        let frame = read_json_str(input, JsonOrient::Records).expect("read json records");
19199        let output = write_json_string(&frame, JsonOrient::Records).expect("write records");
19200        let frame2 = read_json_str(&output, JsonOrient::Records).expect("re-read records");
19201
19202        assert!(frame.equals(&frame2));
19203    }
19204
19205    #[test]
19206    fn json_records_preserves_column_order() {
19207        let input = r#"[{"b":1,"a":2},{"c":3}]"#;
19208        let frame = read_json_str(input, JsonOrient::Records).expect("read json records");
19209        let order: Vec<&str> = frame
19210            .column_names()
19211            .iter()
19212            .map(|name| name.as_str())
19213            .collect();
19214        assert_eq!(order, vec!["b", "a", "c"]);
19215    }
19216
19217    #[test]
19218    fn json_columns_read_write_roundtrip() {
19219        let input = r#"{"name":{"row_a":"Alice","row_b":"Bob"},"age":{"row_a":30,"row_b":25}}"#;
19220        let frame = read_json_str(input, JsonOrient::Columns).expect("read json columns");
19221        assert_eq!(frame.index().len(), 2);
19222        assert_eq!(frame.index().labels()[0], IndexLabel::Utf8("row_a".into()));
19223
19224        let output = write_json_string(&frame, JsonOrient::Columns).expect("write");
19225        let frame2 = read_json_str(&output, JsonOrient::Columns).expect("re-read");
19226        assert_eq!(frame2.index().labels(), frame.index().labels());
19227    }
19228
19229    #[test]
19230    fn json_columns_write_duplicate_index_rejects() {
19231        let index = Index::new(vec![IndexLabel::Int64(1), IndexLabel::Utf8("1".into())]);
19232        let mut columns = BTreeMap::new();
19233        columns.insert(
19234            "v".into(),
19235            Column::from_values(vec![Scalar::Int64(10), Scalar::Int64(20)]).expect("col"),
19236        );
19237        let frame = DataFrame::new(index, columns).expect("frame");
19238
19239        let err = write_json_string(&frame, JsonOrient::Columns)
19240            .expect_err("duplicate JSON object keys should reject");
19241        assert!(
19242            matches!(&err, IoError::JsonFormat(msg) if msg.contains("duplicate index label key")),
19243            "expected duplicate-index-key JsonFormat, got {err:?}"
19244        );
19245    }
19246
19247    #[test]
19248    fn json_split_read_write_roundtrip() {
19249        let input = r#"{"columns":["x","y"],"index":["r1","r2","r3"],"data":[[1,4],[2,5],[3,6]]}"#;
19250        let frame = read_json_str(input, JsonOrient::Split).expect("read json split");
19251        assert_eq!(frame.index().len(), 3);
19252        assert_eq!(
19253            frame.index().labels()[0],
19254            fp_index::IndexLabel::Utf8("r1".into())
19255        );
19256        assert_eq!(frame.column("x").unwrap().values()[0], Scalar::Int64(1));
19257        assert_eq!(frame.column("y").unwrap().values()[2], Scalar::Int64(6));
19258
19259        let output = write_json_string(&frame, JsonOrient::Split).expect("write");
19260        let frame2 = read_json_str(&output, JsonOrient::Split).expect("re-read");
19261        assert_eq!(frame2.index().len(), 3);
19262        assert_eq!(frame2.index().labels(), frame.index().labels());
19263    }
19264
19265    #[test]
19266    fn json_records_multiindex_roundtrip_restores_logical_row_axis() {
19267        let frame = make_row_multiindex_test_dataframe();
19268        let json = write_json_string(&frame, JsonOrient::Records).expect("write");
19269        let roundtrip = read_json_str(&json, JsonOrient::Records).expect("read");
19270
19271        assert!(roundtrip.equals(&frame));
19272        assert!(roundtrip.row_multiindex().is_some());
19273        assert!(roundtrip.column("__index_level_0__").is_none());
19274    }
19275
19276    #[test]
19277    fn json_split_multiindex_roundtrip_restores_logical_row_axis() {
19278        let frame = make_row_multiindex_test_dataframe();
19279        let json = write_json_string(&frame, JsonOrient::Split).expect("write");
19280        let roundtrip = read_json_str(&json, JsonOrient::Split).expect("read");
19281
19282        assert!(roundtrip.equals(&frame));
19283        assert!(roundtrip.row_multiindex().is_some());
19284        assert!(roundtrip.column("__index_level_0__").is_none());
19285    }
19286
19287    #[test]
19288    fn json_split_without_index_defaults_to_range_index() {
19289        let input = r#"{"columns":["x"],"data":[[10],[20]]}"#;
19290        let frame = read_json_str(input, JsonOrient::Split).expect("read json split");
19291        assert_eq!(frame.index().labels()[0], fp_index::IndexLabel::Int64(0));
19292        assert_eq!(frame.index().labels()[1], fp_index::IndexLabel::Int64(1));
19293    }
19294
19295    #[test]
19296    fn json_split_index_length_mismatch_errors() {
19297        let input = r#"{"columns":["x"],"index":[0],"data":[[1],[2]]}"#;
19298        let err = read_json_str(input, JsonOrient::Split)
19299            .expect_err("split orient index/data length mismatch should error");
19300        assert!(
19301            matches!(&err, IoError::JsonFormat(msg) if msg.contains("index length")),
19302            "expected split index length error, got {err:?}"
19303        );
19304    }
19305
19306    #[test]
19307    fn json_split_row_length_mismatch_errors() {
19308        let input = r#"{"columns":["x","y"],"data":[[1],[2,3]]}"#;
19309        let err = read_json_str(input, JsonOrient::Split)
19310            .expect_err("split orient row length mismatch should error");
19311        assert!(
19312            matches!(&err, IoError::JsonFormat(msg) if msg.contains("row 0 length")),
19313            "expected split row length error, got {err:?}"
19314        );
19315    }
19316
19317    #[test]
19318    fn json_split_non_string_columns_are_stringified() {
19319        let input = r#"{"columns":[1,true,null,"name"],"data":[[10,20,30,40]]}"#;
19320        let frame = read_json_str(input, JsonOrient::Split).expect("read json split");
19321        assert_eq!(frame.column("1").unwrap().values()[0], Scalar::Int64(10));
19322        assert_eq!(frame.column("true").unwrap().values()[0], Scalar::Int64(20));
19323        assert_eq!(frame.column("null").unwrap().values()[0], Scalar::Int64(30));
19324        assert_eq!(frame.column("name").unwrap().values()[0], Scalar::Int64(40));
19325    }
19326
19327    #[test]
19328    fn json_split_duplicate_column_names_error() {
19329        let input = r#"{"columns":[1,"1"],"data":[[10,20]]}"#;
19330        let err = read_json_str(input, JsonOrient::Split).expect_err("dup columns");
19331        assert!(matches!(err, IoError::DuplicateColumnName(name) if name == "1"));
19332    }
19333
19334    #[test]
19335    fn json_index_read_write_roundtrip() {
19336        let input = r#"{"row_a":{"name":"Alice","age":30},"row_b":{"name":"Bob","age":25}}"#;
19337        let frame = read_json_str(input, JsonOrient::Index).expect("read json index");
19338        assert_eq!(frame.index().len(), 2);
19339        assert_eq!(frame.index().labels()[0], IndexLabel::Utf8("row_a".into()));
19340        assert_eq!(
19341            frame.column("name").unwrap().values()[1],
19342            Scalar::Utf8("Bob".into())
19343        );
19344
19345        let output = write_json_string(&frame, JsonOrient::Index).expect("write");
19346        let frame2 = read_json_str(&output, JsonOrient::Index).expect("re-read");
19347        assert_eq!(frame2.index().labels(), frame.index().labels());
19348        assert_eq!(frame2.column("age").unwrap().values()[0], Scalar::Int64(30));
19349    }
19350
19351    #[test]
19352    fn json_index_preserves_column_order() {
19353        let input = r#"{"r1":{"b":1,"a":2},"r2":{"c":3}}"#;
19354        let frame = read_json_str(input, JsonOrient::Index).expect("parse");
19355        let order: Vec<&str> = frame
19356            .column_names()
19357            .iter()
19358            .map(|name| name.as_str())
19359            .collect();
19360        assert_eq!(order, vec!["b", "a", "c"]);
19361    }
19362
19363    #[test]
19364    fn json_index_missing_columns_null_fill() {
19365        let input = r#"{"r1":{"a":1},"r2":{"b":2}}"#;
19366        let frame = read_json_str(input, JsonOrient::Index).expect("parse");
19367        let a = frame.column("a").expect("a");
19368        let b = frame.column("b").expect("b");
19369
19370        assert_eq!(a.values()[0], Scalar::Float64(1.0));
19371        assert!(a.values()[1].is_missing());
19372        assert!(b.values()[0].is_missing());
19373        assert_eq!(b.values()[1], Scalar::Float64(2.0));
19374    }
19375
19376    #[test]
19377    fn json_index_write_duplicate_index_rejects() {
19378        let index = Index::new(vec![IndexLabel::Int64(1), IndexLabel::Utf8("1".into())]);
19379        let mut columns = BTreeMap::new();
19380        columns.insert(
19381            "v".into(),
19382            Column::from_values(vec![Scalar::Int64(10), Scalar::Int64(20)]).expect("col"),
19383        );
19384        let frame = DataFrame::new(index, columns).expect("frame");
19385
19386        let err = write_json_string(&frame, JsonOrient::Index)
19387            .expect_err("duplicate JSON object keys should reject");
19388        assert!(
19389            matches!(&err, IoError::JsonFormat(msg) if msg.contains("duplicate index label key")),
19390            "expected duplicate-index-key JsonFormat, got {err:?}"
19391        );
19392    }
19393
19394    #[test]
19395    fn json_index_read_non_object_row_rejects() {
19396        let input = r#"{"r1":{"a":1},"r2":[1,2]}"#;
19397        let err = read_json_str(input, JsonOrient::Index)
19398            .expect_err("index orient rows must be JSON objects");
19399        assert!(
19400            matches!(&err, IoError::JsonFormat(msg) if msg.contains("rows must be objects")),
19401            "expected row-object error, got {err:?}"
19402        );
19403    }
19404
19405    #[test]
19406    fn json_values_read_write_roundtrip() {
19407        let input = r#"[[1,"Alice"],[null,"Bob"]]"#;
19408        let frame = read_json_str(input, JsonOrient::Values).expect("read json values");
19409        assert_eq!(frame.index().len(), 2);
19410        assert_eq!(frame.column_names(), vec!["0", "1"]);
19411        assert_eq!(frame.column("0").unwrap().values()[0], Scalar::Float64(1.0));
19412        assert_eq!(
19413            frame.column("1").unwrap().values()[1],
19414            Scalar::Utf8("Bob".into())
19415        );
19416
19417        let output = write_json_string(&frame, JsonOrient::Values).expect("write");
19418        let frame2 = read_json_str(&output, JsonOrient::Values).expect("re-read");
19419        assert_eq!(frame2.index().len(), 2);
19420        assert_eq!(frame2.column_names(), frame.column_names());
19421        assert_eq!(
19422            frame2.column("0").unwrap().values(),
19423            frame.column("0").unwrap().values()
19424        );
19425        assert_eq!(
19426            frame2.column("1").unwrap().values(),
19427            frame.column("1").unwrap().values()
19428        );
19429    }
19430
19431    #[test]
19432    fn json_records_with_nulls() {
19433        let input = r#"[{"a":1,"b":null},{"a":null,"b":"hello"}]"#;
19434        let frame = read_json_str(input, JsonOrient::Records).expect("parse");
19435        assert!(frame.column("a").unwrap().values()[1].is_missing());
19436        assert!(frame.column("b").unwrap().values()[0].is_missing());
19437    }
19438
19439    #[test]
19440    fn json_read_accepts_pandas_bare_nan_tokens() {
19441        let cases = [
19442            (JsonOrient::Records, r#"[{"a":NaN}]"#),
19443            (JsonOrient::Columns, r#"{"a":{"0":NaN}}"#),
19444            (
19445                JsonOrient::Split,
19446                r#"{"columns":["a"],"index":[0],"data":[[NaN]]}"#,
19447            ),
19448            (JsonOrient::Values, r#"[[NaN]]"#),
19449        ];
19450
19451        for (orient, input) in cases {
19452            let frame = read_json_str(input, orient).expect("parse bare NaN");
19453            let column_name = if orient == JsonOrient::Values {
19454                "0"
19455            } else {
19456                "a"
19457            };
19458            assert!(frame.column(column_name).unwrap().values()[0].is_missing());
19459        }
19460    }
19461
19462    #[test]
19463    fn json_records_write_preserves_nullable_int_column() {
19464        // DISC-011: Nullable extension Int64 dtype parity - Int64 preserved, not promoted to Float64.
19465        let frame = DataFrame::from_dict_with_index(
19466            vec![("a", vec![Scalar::Int64(1), Scalar::Null(NullKind::Null)])],
19467            vec!["row".into(), "row".into()],
19468        )
19469        .unwrap();
19470        let json = write_json_string(&frame, JsonOrient::Records).expect("write");
19471        let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();
19472        assert_eq!(parsed, serde_json::json!([{"a": 1}, {"a": null}]));
19473    }
19474
19475    #[test]
19476    fn json_non_records_nullable_int_reads_promote_to_float() {
19477        let cases = [
19478            (JsonOrient::Columns, r#"{"a":{"0":1,"1":null}}"#),
19479            (JsonOrient::Index, r#"{"0":{"a":1},"1":{"a":null}}"#),
19480            (
19481                JsonOrient::Split,
19482                r#"{"columns":["a"],"index":[0,1],"data":[[1],[null]]}"#,
19483            ),
19484            (JsonOrient::Values, r#"[[1],[null]]"#),
19485        ];
19486
19487        for (orient, input) in cases {
19488            let frame = read_json_str(input, orient).expect("read json");
19489            let column_name = if orient == JsonOrient::Values {
19490                "0"
19491            } else {
19492                "a"
19493            };
19494            let values = frame.column(column_name).expect("column").values();
19495            assert_eq!(values[0], Scalar::Float64(1.0));
19496            assert!(matches!(values[1], Scalar::Null(NullKind::NaN)));
19497        }
19498    }
19499
19500    #[test]
19501    fn json_non_records_nullable_int_writes_preserve_int() {
19502        // DISC-011: Nullable extension Int64 dtype parity - Int64 preserved, not promoted to Float64.
19503        let frame = DataFrame::from_dict(
19504            &["a"],
19505            vec![("a", vec![Scalar::Int64(1), Scalar::Null(NullKind::Null)])],
19506        )
19507        .unwrap();
19508
19509        let columns_json: serde_json::Value =
19510            serde_json::from_str(&write_json_string(&frame, JsonOrient::Columns).unwrap()).unwrap();
19511        assert_eq!(columns_json, serde_json::json!({"a": {"0": 1, "1": null}}));
19512
19513        let index_json: serde_json::Value =
19514            serde_json::from_str(&write_json_string(&frame, JsonOrient::Index).unwrap()).unwrap();
19515        assert_eq!(
19516            index_json,
19517            serde_json::json!({"0": {"a": 1}, "1": {"a": null}})
19518        );
19519
19520        let split_json: serde_json::Value =
19521            serde_json::from_str(&write_json_string(&frame, JsonOrient::Split).unwrap()).unwrap();
19522        assert_eq!(
19523            split_json,
19524            serde_json::json!({"columns": ["a"], "index": [0, 1], "data": [[1], [null]]})
19525        );
19526
19527        let values_json: serde_json::Value =
19528            serde_json::from_str(&write_json_string(&frame, JsonOrient::Values).unwrap()).unwrap();
19529        assert_eq!(values_json, serde_json::json!([[1], [null]]));
19530    }
19531
19532    #[test]
19533    fn json_records_empty_array() {
19534        let input = r#"[]"#;
19535        let frame = read_json_str(input, JsonOrient::Records).expect("parse");
19536        assert_eq!(frame.index().len(), 0);
19537    }
19538
19539    #[test]
19540    fn json_records_mixed_numeric_coerces() {
19541        let input = r#"[{"v":1},{"v":2.5},{"v":true}]"#;
19542        let frame = read_json_str(input, JsonOrient::Records).expect("parse");
19543        // Int64 + Float64 + Bool all coerce to Float64
19544        assert_eq!(frame.column("v").unwrap().values()[0], Scalar::Float64(1.0));
19545        assert_eq!(frame.column("v").unwrap().values()[1], Scalar::Float64(2.5));
19546        assert_eq!(frame.column("v").unwrap().values()[2], Scalar::Float64(1.0));
19547    }
19548
19549    #[test]
19550    fn json_records_mixed_utf8_numeric_preserves_object_values() {
19551        let input = r#"[{"v":1},{"v":"text"}]"#;
19552        let frame = read_json_str(input, JsonOrient::Records).expect("parse");
19553        assert_eq!(
19554            frame.column("v").unwrap().values(),
19555            &[Scalar::Int64(1), Scalar::Utf8("text".into())]
19556        );
19557    }
19558
19559    #[test]
19560    fn file_csv_roundtrip() {
19561        let input = "a,b\n1,2\n3,4\n";
19562        let frame = read_csv_str(input).expect("parse");
19563
19564        let dir = std::env::temp_dir();
19565        let path = dir.join("fp_io_test_roundtrip.csv");
19566        super::write_csv(&frame, &path).expect("write file");
19567        let frame2 = super::read_csv(&path).expect("read file");
19568        assert_eq!(frame2.index().len(), 2);
19569        std::fs::remove_file(&path).ok();
19570    }
19571
19572    #[test]
19573    fn file_csv_with_options_path() {
19574        // DISC-011: Nullable extension Int64 dtype parity - Int64 preserved, not promoted to Float64.
19575        let input = "id\tval\na\tNA\nb\t2\n";
19576        let dir = std::env::temp_dir();
19577        let path = dir.join("fp_io_test_options.csv");
19578        std::fs::write(&path, input).expect("write fixture");
19579
19580        let options = CsvReadOptions {
19581            delimiter: b'\t',
19582            na_values: vec!["NA".into()],
19583            index_col: Some("id".into()),
19584            ..Default::default()
19585        };
19586
19587        let frame = super::read_csv_with_options_path(&path, &options).expect("read with options");
19588        assert_eq!(
19589            frame.index().labels()[0],
19590            fp_index::IndexLabel::Utf8("a".into())
19591        );
19592        assert!(frame.column("id").is_none());
19593        assert!(frame.column("val").unwrap().values()[0].is_missing());
19594        assert_eq!(frame.column("val").unwrap().values()[1], Scalar::Int64(2));
19595
19596        std::fs::remove_file(&path).ok();
19597    }
19598
19599    #[test]
19600    fn file_json_roundtrip() {
19601        let input = r#"[{"x":1},{"x":2}]"#;
19602        let frame = read_json_str(input, JsonOrient::Records).expect("parse");
19603
19604        let dir = std::env::temp_dir();
19605        let path = dir.join("fp_io_test_roundtrip.json");
19606        super::write_json(&frame, &path, JsonOrient::Records).expect("write file");
19607        let frame2 = super::read_json(&path, JsonOrient::Records).expect("read file");
19608        assert_eq!(frame2.index().len(), 2);
19609        std::fs::remove_file(&path).ok();
19610    }
19611
19612    // ── read_table 4pwr9 ───────────────────────────────────────────────
19613
19614    #[test]
19615    fn read_table_str_parses_tab_separated_4pwr9() {
19616        let input = "a\tb\tc\n1\t2\t3\n4\t5\t6\n";
19617        let frame = super::read_table_str(input).expect("parse tsv");
19618        assert_eq!(frame.index().len(), 2);
19619        assert_eq!(frame.column("a").unwrap().values()[0], Scalar::Int64(1));
19620        assert_eq!(frame.column("c").unwrap().values()[1], Scalar::Int64(6));
19621    }
19622
19623    #[test]
19624    fn read_table_with_options_overrides_default_delimiter_4pwr9() {
19625        // DISC-011: Nullable extension Int64 dtype parity - Int64 preserved, not promoted to Float64.
19626        let input = "x\ty\n1\tNA\n2\t3\n";
19627        let opts = CsvReadOptions {
19628            na_values: vec!["NA".into()],
19629            ..Default::default()
19630        };
19631        let frame = super::read_table_with_options(input, &opts).expect("parse tsv with na");
19632        assert!(frame.column("y").unwrap().values()[0].is_missing());
19633        assert_eq!(frame.column("y").unwrap().values()[1], Scalar::Int64(3));
19634    }
19635
19636    #[test]
19637    fn read_table_with_options_honours_explicit_pipe_delimiter_4pwr9() {
19638        let input = "x|y\n1|2\n3|4\n";
19639        let opts = CsvReadOptions {
19640            delimiter: b'|',
19641            ..Default::default()
19642        };
19643        let frame = super::read_table_with_options(input, &opts).expect("parse pipe");
19644        assert_eq!(frame.column("x").unwrap().values()[0], Scalar::Int64(1));
19645        assert_eq!(frame.column("y").unwrap().values()[1], Scalar::Int64(4));
19646    }
19647
19648    // ── read_fwf 23n8u ─────────────────────────────────────────────────
19649
19650    #[test]
19651    fn read_fwf_str_with_colspecs_parses_aligned_records_23n8u() {
19652        let input = "name    age   active\nalice   30    true\nbob     25    false\n";
19653        let opts = super::FwfReadOptions {
19654            colspecs: Some(vec![(0, 8), (8, 14), (14, 20)]),
19655            true_values: vec!["true".into()],
19656            false_values: vec!["false".into()],
19657            ..Default::default()
19658        };
19659        let frame = super::read_fwf_str(input, &opts).expect("parse fwf");
19660        assert_eq!(frame.index().len(), 2);
19661        assert_eq!(
19662            frame.column("name").unwrap().values()[0],
19663            Scalar::Utf8("alice".into())
19664        );
19665        assert_eq!(frame.column("age").unwrap().values()[0], Scalar::Int64(30));
19666        assert_eq!(
19667            frame.column("active").unwrap().values()[0],
19668            Scalar::Bool(true)
19669        );
19670    }
19671
19672    #[test]
19673    fn read_fwf_str_with_widths_derives_colspecs_23n8u() {
19674        let input = "x  y \n1  2 \n3  4 \n";
19675        let opts = super::FwfReadOptions {
19676            widths: Some(vec![3, 3]),
19677            ..Default::default()
19678        };
19679        let frame = super::read_fwf_str(input, &opts).expect("parse fwf widths");
19680        assert_eq!(frame.column("x").unwrap().values()[0], Scalar::Int64(1));
19681        assert_eq!(frame.column("y").unwrap().values()[1], Scalar::Int64(4));
19682    }
19683
19684    #[test]
19685    fn read_fwf_str_threads_na_handling_23n8u() {
19686        // DISC-011: Nullable extension Int64 dtype parity - Int64 preserved, not promoted to Float64.
19687        let input = "id   val\nA    NA \nB    7  \n";
19688        let opts = super::FwfReadOptions {
19689            colspecs: Some(vec![(0, 5), (5, 9)]),
19690            na_values: vec!["NA".into()],
19691            ..Default::default()
19692        };
19693        let frame = super::read_fwf_str(input, &opts).expect("parse fwf na");
19694        let col = frame.column("val").unwrap().values();
19695        assert!(col[0].is_missing());
19696        assert_eq!(col[1], Scalar::Int64(7));
19697    }
19698
19699    #[test]
19700    fn read_fwf_rejects_both_colspecs_and_widths_23n8u() {
19701        let opts = super::FwfReadOptions {
19702            colspecs: Some(vec![(0, 3)]),
19703            widths: Some(vec![3]),
19704            ..Default::default()
19705        };
19706        let err = super::read_fwf_str("x\n1\n", &opts).expect_err("must reject");
19707        assert!(
19708            matches!(&err, super::IoError::Fwf(message) if message.contains("only one of")),
19709            "unexpected error: {err:?}"
19710        );
19711    }
19712
19713    #[test]
19714    fn read_fwf_infers_colspecs_when_specs_are_omitted_htdmp() {
19715        let opts = super::FwfReadOptions::default();
19716        let frame = super::read_fwf_str("a b\n1 2\n3 4\n", &opts).expect("infer fwf specs");
19717        assert_eq!(frame.column("a").unwrap().values()[0], Scalar::Int64(1));
19718        assert_eq!(frame.column("b").unwrap().values()[1], Scalar::Int64(4));
19719    }
19720
19721    #[test]
19722    fn read_fwf_infers_aligned_wide_colspecs_htdmp() {
19723        let input = "name    age   active\nalice   30    true\nbob     25    false\n";
19724        let opts = super::FwfReadOptions {
19725            true_values: vec!["true".into()],
19726            false_values: vec!["false".into()],
19727            ..Default::default()
19728        };
19729        let frame = super::read_fwf_str(input, &opts).expect("infer aligned fwf specs");
19730        assert_eq!(
19731            frame.column("name").unwrap().values()[0],
19732            Scalar::Utf8("alice".into())
19733        );
19734        assert_eq!(frame.column("age").unwrap().values()[1], Scalar::Int64(25));
19735        assert_eq!(
19736            frame.column("active").unwrap().values()[1],
19737            Scalar::Bool(false)
19738        );
19739    }
19740
19741    #[test]
19742    fn read_fwf_infer_honors_skiprows_and_skipfooter_htdmp() {
19743        let input = "ignored wide banner\nx y\n1 2\nfooter text ignored\n";
19744        let opts = super::FwfReadOptions {
19745            skiprows: 1,
19746            skipfooter: 1,
19747            ..Default::default()
19748        };
19749        let frame = super::read_fwf_str(input, &opts).expect("infer after skipping");
19750        assert_eq!(frame.column("x").unwrap().values()[0], Scalar::Int64(1));
19751        assert_eq!(frame.column("y").unwrap().values()[0], Scalar::Int64(2));
19752    }
19753
19754    // ── Deferred reader surfaces 2yy4d ─────────────────────────────────
19755
19756    #[test]
19757    fn clipboard_tsv_round_trips_through_read_clipboard_str() {
19758        let frame = make_test_dataframe();
19759        // The pure write core: the exact tab-separated bytes `to_clipboard` puts
19760        // on the clipboard (index included, pandas excel=True).
19761        let tsv = super::clipboard_tsv(&frame).expect("tsv");
19762        assert!(
19763            tsv.contains('\t'),
19764            "clipboard payload must be tab-separated"
19765        );
19766
19767        // The pure read core round-trips the payload back to a frame with the
19768        // same shape (the written index becomes a leading column, matching
19769        // pandas read_clipboard's default no-index-col behavior).
19770        let parsed = super::read_clipboard_str(&tsv).expect("parse clipboard tsv");
19771        assert_eq!(parsed.len(), frame.len());
19772        assert_eq!(parsed.column_names().len(), frame.column_names().len() + 1);
19773    }
19774
19775    #[test]
19776    fn read_clipboard_is_ok_or_reports_missing_backend() {
19777        // Environment-independent: on a box with wl-paste/xclip/xsel/pbpaste it
19778        // reads real clipboard text (Ok or a parse error); headless it reports a
19779        // Clipboard backend error. Never a Deferred reject and never a panic.
19780        match super::read_clipboard() {
19781            Ok(_) => {}
19782            Err(super::IoError::Clipboard(_)) | Err(super::IoError::Csv(_)) => {}
19783            Err(super::IoError::MissingHeaders) => {}
19784            other => panic!("unexpected read_clipboard result: {other:?}"),
19785        }
19786    }
19787
19788    #[test]
19789    fn read_gbq_rejects_with_deferred_marker_2yy4d() {
19790        let err = super::read_gbq("SELECT 1", Some("proj")).expect_err("must reject");
19791        assert!(
19792            matches!(&err, super::IoError::Deferred(message)
19793                if message.contains("read_gbq") && message.contains("BigQuery")),
19794            "unexpected error: {err:?}"
19795        );
19796        let no_project_err = super::read_gbq("SELECT 1", None).expect_err("must reject");
19797        assert!(matches!(no_project_err, super::IoError::Deferred(_)));
19798    }
19799
19800    #[test]
19801    fn dataframe_deferred_writer_surfaces_report_method_names_e6jrk() {
19802        use super::DataFrameIoExt;
19803
19804        let frame = make_test_dataframe();
19805        // Clipboard writer is implemented (subprocess backend): Ok where a
19806        // backend exists, else a Clipboard error — never a Deferred reject.
19807        match frame.to_clipboard() {
19808            Ok(()) => {}
19809            Err(super::IoError::Clipboard(_)) => {}
19810            other => panic!("unexpected to_clipboard result: {other:?}"),
19811        }
19812
19813        let gbq_err = frame
19814            .to_gbq("dataset.table", Some("project"))
19815            .expect_err("must reject BigQuery writer");
19816        assert!(
19817            matches!(&gbq_err, super::IoError::Deferred(message) if message.contains("to_gbq") && message.contains("BigQuery"))
19818        );
19819
19820        let no_project_err = frame
19821            .to_gbq("dataset.table", None)
19822            .expect_err("must reject BigQuery writer without project");
19823        assert!(matches!(no_project_err, super::IoError::Deferred(_)));
19824    }
19825
19826    #[test]
19827    fn series_clipboard_writer_is_ok_or_reports_missing_backend() {
19828        use super::SeriesIoExt;
19829
19830        let source = Series::from_values(
19831            "sales",
19832            vec!["r1".into(), "r2".into()],
19833            vec![Scalar::Int64(10), Scalar::Int64(12)],
19834        )
19835        .expect("source series");
19836        match source.to_clipboard() {
19837            Ok(()) => {}
19838            Err(super::IoError::Clipboard(_)) => {}
19839            other => panic!("unexpected series to_clipboard result: {other:?}"),
19840        }
19841    }
19842
19843    #[test]
19844    fn read_sas_rejects_with_deferred_marker_2yy4d() {
19845        let path = std::path::Path::new("/nonexistent.sas7bdat");
19846        let err = super::read_sas(path).expect_err("must reject");
19847        assert!(
19848            matches!(&err, super::IoError::Deferred(message)
19849                if message.contains("read_sas") && message.contains("sas7bdat")),
19850            "unexpected error: {err:?}"
19851        );
19852    }
19853
19854    #[test]
19855    fn read_spss_rejects_with_deferred_marker_2yy4d() {
19856        let path = std::path::Path::new("/nonexistent.sav");
19857        let err = super::read_spss(path).expect_err("must reject");
19858        assert!(
19859            matches!(&err, super::IoError::Deferred(message)
19860                if message.contains("read_spss") && message.contains(".sav")),
19861            "unexpected error: {err:?}"
19862        );
19863    }
19864
19865    #[test]
19866    fn read_fwf_path_reads_fixed_width_file_23n8u() {
19867        let input = "a   b\n1   2\n3   4\n";
19868        let dir = std::env::temp_dir();
19869        let path = dir.join("fp_io_test_read_fwf_23n8u.txt");
19870        std::fs::write(&path, input).expect("write fixture");
19871
19872        let opts = super::FwfReadOptions {
19873            colspecs: Some(vec![(0, 4), (4, 5)]),
19874            ..Default::default()
19875        };
19876        let frame = super::read_fwf(&path, &opts).expect("read fwf path");
19877        assert_eq!(frame.index().len(), 2);
19878        assert_eq!(frame.column("a").unwrap().values()[1], Scalar::Int64(3));
19879        assert_eq!(frame.column("b").unwrap().values()[0], Scalar::Int64(2));
19880
19881        std::fs::remove_file(&path).ok();
19882    }
19883
19884    #[test]
19885    fn read_table_path_roundtrips_through_read_csv_path_4pwr9() {
19886        let input = "id\tval\na\t1\nb\t2\n";
19887        let dir = std::env::temp_dir();
19888        let path = dir.join("fp_io_test_read_table_4pwr9.tsv");
19889        std::fs::write(&path, input).expect("write fixture");
19890
19891        let frame = super::read_table(&path).expect("read tsv");
19892        assert_eq!(frame.index().len(), 2);
19893        assert_eq!(
19894            frame.column("id").unwrap().values()[0],
19895            Scalar::Utf8("a".into())
19896        );
19897        assert_eq!(frame.column("val").unwrap().values()[1], Scalar::Int64(2));
19898
19899        let opts = CsvReadOptions {
19900            index_col: Some("id".into()),
19901            ..Default::default()
19902        };
19903        let frame2 =
19904            super::read_table_with_options_path(&path, &opts).expect("read tsv with options");
19905        assert!(frame2.column("id").is_none());
19906        assert_eq!(
19907            frame2.index().labels()[0],
19908            fp_index::IndexLabel::Utf8("a".into())
19909        );
19910        assert_eq!(frame2.column("val").unwrap().values()[1], Scalar::Int64(2));
19911
19912        std::fs::remove_file(&path).ok();
19913    }
19914
19915    // ── Parquet I/O tests ──────────────────────────────────────────────
19916
19917    fn make_test_dataframe() -> DataFrame {
19918        use fp_types::DType;
19919
19920        let mut columns = BTreeMap::new();
19921        columns.insert(
19922            "ints".to_string(),
19923            Column::new(
19924                DType::Int64,
19925                vec![Scalar::Int64(10), Scalar::Int64(20), Scalar::Int64(30)],
19926            )
19927            .unwrap(),
19928        );
19929        columns.insert(
19930            "floats".to_string(),
19931            Column::new(
19932                DType::Float64,
19933                vec![
19934                    Scalar::Float64(1.5),
19935                    Scalar::Float64(2.5),
19936                    Scalar::Float64(3.5),
19937                ],
19938            )
19939            .unwrap(),
19940        );
19941        columns.insert(
19942            "names".to_string(),
19943            Column::from_values(vec![
19944                Scalar::Utf8("alice".into()),
19945                Scalar::Utf8("bob".into()),
19946                Scalar::Utf8("carol".into()),
19947            ])
19948            .unwrap(),
19949        );
19950
19951        let labels = vec![
19952            IndexLabel::Int64(0),
19953            IndexLabel::Int64(1),
19954            IndexLabel::Int64(2),
19955        ];
19956        DataFrame::new_with_column_order(
19957            Index::new(labels),
19958            columns,
19959            vec![
19960                "ints".to_string(),
19961                "floats".to_string(),
19962                "names".to_string(),
19963            ],
19964        )
19965        .unwrap()
19966    }
19967
19968    #[test]
19969    fn dataframe_io_ext_pandas_named_aliases_cover_supported_writers() {
19970        use super::DataFrameIoExt;
19971
19972        let frame = make_test_dataframe();
19973        let csv = frame.to_csv_string().expect("csv string");
19974        assert_eq!(csv, super::write_csv_string(&frame).expect("free csv"));
19975        assert_eq!(
19976            frame.to_markdown_string().expect("markdown string"),
19977            write_markdown_string(&frame).expect("free markdown")
19978        );
19979        assert_eq!(
19980            frame.to_latex_string().expect("latex string"),
19981            write_latex_string(&frame).expect("free latex")
19982        );
19983        let dir = std::env::temp_dir();
19984        let stem = format!("fp_io_dataframe_io_ext_{}", std::process::id());
19985        let excel_path = dir.join(format!("{stem}.xlsx"));
19986        let feather_path = dir.join(format!("{stem}.feather"));
19987        let parquet_path = dir.join(format!("{stem}.parquet"));
19988
19989        frame.to_excel(&excel_path).expect("to_excel alias");
19990        frame.to_feather(&feather_path).expect("to_feather alias");
19991        frame.to_parquet(&parquet_path).expect("to_parquet alias");
19992
19993        assert!(
19994            std::fs::metadata(&excel_path)
19995                .expect("excel metadata")
19996                .len()
19997                > 0
19998        );
19999        assert_eq!(
20000            super::read_feather(&feather_path)
20001                .expect("read feather")
20002                .index()
20003                .len(),
20004            frame.index().len()
20005        );
20006        assert_eq!(
20007            super::read_parquet(&parquet_path)
20008                .expect("read parquet")
20009                .index()
20010                .len(),
20011            frame.index().len()
20012        );
20013
20014        std::fs::remove_file(&excel_path).ok();
20015        std::fs::remove_file(&feather_path).ok();
20016        std::fs::remove_file(&parquet_path).ok();
20017    }
20018
20019    #[test]
20020    fn dataframe_io_ext_rjs51_in_memory_methods_match_free_functions() {
20021        use super::DataFrameIoExt;
20022
20023        let frame = make_test_dataframe();
20024        let csv_options = CsvWriteOptions {
20025            delimiter: b';',
20026            na_rep: "<NA>".to_owned(),
20027            header: true,
20028            include_index: true,
20029            index_label: Some("row".to_owned()),
20030        };
20031        assert_eq!(
20032            frame
20033                .to_csv_string_with_options(&csv_options)
20034                .expect("csv options through extension"),
20035            write_csv_string_with_options(&frame, &csv_options).expect("csv options free fn")
20036        );
20037        assert_eq!(
20038            frame
20039                .to_json_string(JsonOrient::Split)
20040                .expect("json split through extension"),
20041            write_json_string(&frame, JsonOrient::Split).expect("json split free fn")
20042        );
20043        assert_eq!(
20044            frame.to_jsonl_string().expect("jsonl through extension"),
20045            write_jsonl_string(&frame).expect("jsonl free fn")
20046        );
20047        let html_options = HtmlWriteOptions {
20048            include_index: false,
20049            ..HtmlWriteOptions::default()
20050        };
20051        assert_eq!(
20052            frame
20053                .to_html_string_with_options(&html_options)
20054                .expect("html options through extension"),
20055            write_html_string_with_options(&frame, &html_options).expect("html options free fn")
20056        );
20057        let xml_options = XmlWriteOptions {
20058            include_index: false,
20059            root_name: "records".to_owned(),
20060            row_name: "record".to_owned(),
20061            index_label: None,
20062        };
20063        assert_eq!(
20064            frame
20065                .to_xml_string_with_options(&xml_options)
20066                .expect("xml options through extension"),
20067            write_xml_string_with_options(&frame, &xml_options).expect("xml options free fn")
20068        );
20069
20070        let parquet = frame
20071            .to_parquet_bytes()
20072            .expect("parquet bytes through extension");
20073        assert_eq!(
20074            read_parquet_bytes(&parquet)
20075                .expect("parquet roundtrip")
20076                .index()
20077                .len(),
20078            frame.index().len()
20079        );
20080        assert_orc_disabled(
20081            frame
20082                .to_orc_bytes()
20083                .expect_err("ORC must fail closed under no-Tokio policy"),
20084        );
20085        let feather = frame
20086            .to_feather_bytes()
20087            .expect("feather bytes through extension");
20088        assert_eq!(
20089            read_feather_bytes(&feather)
20090                .expect("feather roundtrip")
20091                .index()
20092                .len(),
20093            frame.index().len()
20094        );
20095        let excel = frame
20096            .to_excel_bytes()
20097            .expect("excel bytes through extension");
20098        assert_eq!(
20099            read_excel_bytes(&excel, &ExcelReadOptions::default())
20100                .expect("excel roundtrip")
20101                .index()
20102                .len(),
20103            frame.index().len()
20104        );
20105    }
20106
20107    fn make_row_multiindex_test_dataframe() -> DataFrame {
20108        let df = DataFrame::from_dict(
20109            &["region", "product", "year", "sales", "cost"],
20110            vec![
20111                (
20112                    "region",
20113                    vec![
20114                        Scalar::Utf8("north".into()),
20115                        Scalar::Utf8("north".into()),
20116                        Scalar::Utf8("south".into()),
20117                    ],
20118                ),
20119                (
20120                    "product",
20121                    vec![
20122                        Scalar::Utf8("apple".into()),
20123                        Scalar::Utf8("pear".into()),
20124                        Scalar::Utf8("apple".into()),
20125                    ],
20126                ),
20127                (
20128                    "year",
20129                    vec![
20130                        Scalar::Int64(2023),
20131                        Scalar::Int64(2024),
20132                        Scalar::Int64(2023),
20133                    ],
20134                ),
20135                (
20136                    "sales",
20137                    vec![Scalar::Int64(10), Scalar::Int64(20), Scalar::Int64(30)],
20138                ),
20139                (
20140                    "cost",
20141                    vec![Scalar::Int64(4), Scalar::Int64(7), Scalar::Int64(12)],
20142                ),
20143            ],
20144        )
20145        .unwrap();
20146        df.set_index_multi(&["region", "product", "year"], true, "|")
20147            .unwrap()
20148    }
20149
20150    #[test]
20151    fn parquet_bytes_roundtrip() {
20152        let frame = make_test_dataframe();
20153        let bytes = super::write_parquet_bytes(&frame).expect("write parquet");
20154        assert!(!bytes.is_empty());
20155
20156        let frame2 = super::read_parquet_bytes(&bytes).expect("read parquet");
20157        assert_eq!(frame2.index().len(), 3);
20158        assert_eq!(
20159            frame2
20160                .column_names()
20161                .iter()
20162                .map(|s| s.as_str())
20163                .collect::<Vec<_>>(),
20164            vec!["ints", "floats", "names"]
20165        );
20166
20167        // Check values round-tripped correctly
20168        let ints = frame2.column("ints").unwrap();
20169        assert_eq!(ints.values()[0], Scalar::Int64(10));
20170        assert_eq!(ints.values()[1], Scalar::Int64(20));
20171        assert_eq!(ints.values()[2], Scalar::Int64(30));
20172
20173        let floats = frame2.column("floats").unwrap();
20174        assert_eq!(floats.values()[0], Scalar::Float64(1.5));
20175        assert_eq!(floats.values()[1], Scalar::Float64(2.5));
20176        assert_eq!(floats.values()[2], Scalar::Float64(3.5));
20177
20178        let names = frame2.column("names").unwrap();
20179        assert_eq!(names.values()[0], Scalar::Utf8("alice".into()));
20180        assert_eq!(names.values()[1], Scalar::Utf8("bob".into()));
20181        assert_eq!(names.values()[2], Scalar::Utf8("carol".into()));
20182    }
20183
20184    #[test]
20185    fn parquet_row_multiindex_roundtrip_restores_logical_row_axis() {
20186        let frame = make_row_multiindex_test_dataframe();
20187        let bytes = super::write_parquet_bytes(&frame).expect("write parquet");
20188        let roundtrip = super::read_parquet_bytes(&bytes).expect("read parquet");
20189
20190        assert!(roundtrip.equals(&frame));
20191        assert!(roundtrip.column("__index_level_0__").is_none());
20192        assert_eq!(
20193            roundtrip
20194                .row_multiindex()
20195                .expect("row multiindex should be restored")
20196                .get_level_values(0)
20197                .unwrap()
20198                .labels(),
20199            frame
20200                .row_multiindex()
20201                .expect("source row multiindex")
20202                .get_level_values(0)
20203                .unwrap()
20204                .labels()
20205        );
20206    }
20207
20208    #[test]
20209    fn parquet_file_roundtrip() {
20210        let frame = make_test_dataframe();
20211        let dir = std::env::temp_dir();
20212        let path = dir.join("fp_io_test_parquet_roundtrip.parquet");
20213
20214        super::write_parquet(&frame, &path).expect("write parquet file");
20215        let frame2 = super::read_parquet(&path).expect("read parquet file");
20216        assert_eq!(frame2.index().len(), 3);
20217        assert_eq!(
20218            frame2.column("ints").unwrap().values()[0],
20219            Scalar::Int64(10)
20220        );
20221        std::fs::remove_file(&path).ok();
20222    }
20223
20224    #[test]
20225    fn parquet_with_nulls() {
20226        use fp_types::DType;
20227
20228        let mut columns = BTreeMap::new();
20229        columns.insert(
20230            "vals".to_string(),
20231            Column::new(
20232                DType::Float64,
20233                vec![
20234                    Scalar::Float64(1.0),
20235                    Scalar::Null(NullKind::NaN),
20236                    Scalar::Float64(3.0),
20237                ],
20238            )
20239            .unwrap(),
20240        );
20241        columns.insert(
20242            "strs".to_string(),
20243            Column::from_values(vec![
20244                Scalar::Utf8("a".into()),
20245                Scalar::Null(NullKind::Null),
20246                Scalar::Utf8("c".into()),
20247            ])
20248            .unwrap(),
20249        );
20250
20251        let labels = vec![
20252            IndexLabel::Int64(0),
20253            IndexLabel::Int64(1),
20254            IndexLabel::Int64(2),
20255        ];
20256        let frame = DataFrame::new_with_column_order(
20257            Index::new(labels),
20258            columns,
20259            vec!["vals".to_string(), "strs".to_string()],
20260        )
20261        .unwrap();
20262
20263        let bytes = super::write_parquet_bytes(&frame).expect("write");
20264        let frame2 = super::read_parquet_bytes(&bytes).expect("read");
20265
20266        assert_eq!(
20267            frame2.column("vals").unwrap().values()[0],
20268            Scalar::Float64(1.0)
20269        );
20270        assert!(frame2.column("vals").unwrap().values()[1].is_missing());
20271        assert_eq!(
20272            frame2.column("vals").unwrap().values()[2],
20273            Scalar::Float64(3.0)
20274        );
20275
20276        assert_eq!(
20277            frame2.column("strs").unwrap().values()[0],
20278            Scalar::Utf8("a".into())
20279        );
20280        assert!(frame2.column("strs").unwrap().values()[1].is_missing());
20281        assert_eq!(
20282            frame2.column("strs").unwrap().values()[2],
20283            Scalar::Utf8("c".into())
20284        );
20285    }
20286
20287    #[test]
20288    fn parquet_bool_column() {
20289        use fp_types::DType;
20290
20291        let mut columns = BTreeMap::new();
20292        columns.insert(
20293            "flags".to_string(),
20294            Column::new(
20295                DType::Bool,
20296                vec![Scalar::Bool(true), Scalar::Bool(false), Scalar::Bool(true)],
20297            )
20298            .unwrap(),
20299        );
20300
20301        let labels = vec![
20302            IndexLabel::Int64(0),
20303            IndexLabel::Int64(1),
20304            IndexLabel::Int64(2),
20305        ];
20306        let frame = DataFrame::new_with_column_order(
20307            Index::new(labels),
20308            columns,
20309            vec!["flags".to_string()],
20310        )
20311        .unwrap();
20312
20313        let bytes = super::write_parquet_bytes(&frame).expect("write");
20314        let frame2 = super::read_parquet_bytes(&bytes).expect("read");
20315
20316        assert_eq!(
20317            frame2.column("flags").unwrap().values()[0],
20318            Scalar::Bool(true)
20319        );
20320        assert_eq!(
20321            frame2.column("flags").unwrap().values()[1],
20322            Scalar::Bool(false)
20323        );
20324        assert_eq!(
20325            frame2.column("flags").unwrap().values()[2],
20326            Scalar::Bool(true)
20327        );
20328    }
20329
20330    #[test]
20331    fn parquet_empty_dataframe_errors() {
20332        // Parquet format requires at least one column — empty DataFrames
20333        // cannot be represented, matching pandas behavior where
20334        // pd.DataFrame().to_parquet() also fails.
20335        let frame =
20336            DataFrame::new_with_column_order(Index::new(vec![]), BTreeMap::new(), vec![]).unwrap();
20337
20338        let result = super::write_parquet_bytes(&frame);
20339        assert!(result.is_err());
20340    }
20341
20342    #[test]
20343    fn orc_bytes_fail_closed_under_no_tokio_policy() {
20344        let frame = make_test_dataframe();
20345        assert_orc_disabled(write_orc_bytes(&frame).expect_err("ORC writer must fail closed"));
20346        assert_orc_disabled(read_orc_bytes(b"ORC").expect_err("ORC reader must fail closed"));
20347    }
20348
20349    #[test]
20350    fn orc_file_and_extension_aliases_fail_closed_under_no_tokio_policy() {
20351        use super::DataFrameIoExt;
20352
20353        let frame = make_test_dataframe();
20354        let free_path = std::env::temp_dir().join(format!(
20355            "fp_io_orc_free_{}_{}.orc",
20356            std::process::id(),
20357            line!()
20358        ));
20359        let trait_path = std::env::temp_dir().join(format!(
20360            "fp_io_orc_trait_{}_{}.orc",
20361            std::process::id(),
20362            line!()
20363        ));
20364
20365        assert_orc_disabled(write_orc(&frame, &free_path).expect_err("free ORC path writer"));
20366        assert_orc_disabled(read_orc(&free_path).expect_err("free ORC path reader"));
20367        assert_orc_disabled(
20368            frame
20369                .to_orc_file(&trait_path)
20370                .expect_err("trait ORC path writer"),
20371        );
20372        assert_orc_disabled(frame.to_orc_bytes().expect_err("trait ORC bytes writer"));
20373    }
20374
20375    #[test]
20376    fn orc_row_multiindex_fails_closed_before_materialization() {
20377        let frame = make_row_multiindex_test_dataframe();
20378        assert_orc_disabled(
20379            write_orc_bytes(&frame).expect_err("ORC writer must fail closed for any frame shape"),
20380        );
20381    }
20382
20383    #[test]
20384    fn orc_reader_rejects_malformed_input_without_loading_backend() {
20385        let err = read_orc_bytes(b"not an orc file").expect_err("malformed orc should fail");
20386        assert_orc_disabled(err);
20387    }
20388
20389    // ── Excel I/O tests ──────────────────────────────────────────────
20390
20391    #[test]
20392    fn write_excel_with_options_custom_sheet_name_survives_round_trip() {
20393        let frame = make_test_dataframe();
20394        let bytes = super::write_excel_bytes_with_options(
20395            &frame,
20396            &super::ExcelWriteOptions {
20397                sheet_name: "Results".to_string(),
20398                ..super::ExcelWriteOptions::default()
20399            },
20400        )
20401        .expect("write");
20402        let sheets =
20403            super::read_excel_sheets_bytes(&bytes, None, &super::ExcelReadOptions::default())
20404                .expect("read");
20405        assert_eq!(sheets.len(), 1);
20406        assert!(sheets.contains_key("Results"));
20407    }
20408
20409    #[test]
20410    fn write_excel_with_options_index_false_omits_index_column() {
20411        let frame = make_test_dataframe();
20412        let bytes = super::write_excel_bytes_with_options(
20413            &frame,
20414            &super::ExcelWriteOptions {
20415                index: false,
20416                ..super::ExcelWriteOptions::default()
20417            },
20418        )
20419        .expect("write");
20420        let frame2 =
20421            super::read_excel_bytes(&bytes, &super::ExcelReadOptions::default()).expect("read");
20422        // With index=false the first column is "ints" directly (no
20423        // anonymous leading index column).
20424        let names = frame2.column_names();
20425        assert_eq!(
20426            names.iter().map(|s| s.as_str()).collect::<Vec<_>>(),
20427            vec!["ints", "floats", "names"]
20428        );
20429    }
20430
20431    #[test]
20432    fn write_excel_with_options_index_label_overrides_header() {
20433        let frame = make_test_dataframe();
20434        let bytes = super::write_excel_bytes_with_options(
20435            &frame,
20436            &super::ExcelWriteOptions {
20437                index_label: Some("row_id".to_string()),
20438                ..super::ExcelWriteOptions::default()
20439            },
20440        )
20441        .expect("write");
20442        let frame2 =
20443            super::read_excel_bytes(&bytes, &super::ExcelReadOptions::default()).expect("read");
20444        // The index column now shows up as "row_id" before the data columns.
20445        let names = frame2.column_names();
20446        assert_eq!(names[0], "row_id");
20447    }
20448
20449    #[test]
20450    fn write_excel_with_options_header_false_omits_header_row() {
20451        let frame = make_test_dataframe();
20452        let bytes = super::write_excel_bytes_with_options(
20453            &frame,
20454            &super::ExcelWriteOptions {
20455                header: false,
20456                index: false,
20457                ..super::ExcelWriteOptions::default()
20458            },
20459        )
20460        .expect("write");
20461        // Without header, the reader treats row 0 as headers. We
20462        // expect the first data row to become the column names
20463        // instead of literal "ints"/"floats"/"names".
20464        let frame2 =
20465            super::read_excel_bytes(&bytes, &super::ExcelReadOptions::default()).expect("read");
20466        let names = frame2.column_names();
20467        let name_strs: Vec<&str> = names.iter().map(|s| s.as_str()).collect();
20468        assert!(!name_strs.contains(&"ints"));
20469    }
20470
20471    #[test]
20472    fn write_excel_with_options_default_matches_write_excel_bytes() {
20473        let frame = make_test_dataframe();
20474        let default_bytes = super::write_excel_bytes(&frame).expect("default");
20475        let options_bytes =
20476            super::write_excel_bytes_with_options(&frame, &super::ExcelWriteOptions::default())
20477                .expect("options");
20478        assert_eq!(default_bytes, options_bytes);
20479    }
20480
20481    #[test]
20482    fn excel_multiindex_roundtrip_with_explicit_index_cols() {
20483        let frame = make_row_multiindex_test_dataframe();
20484        let bytes =
20485            super::write_excel_bytes_with_options(&frame, &super::ExcelWriteOptions::default())
20486                .expect("write");
20487        let roundtrip = super::read_excel_bytes_with_index_cols(
20488            &bytes,
20489            &super::ExcelReadOptions::default(),
20490            &["region", "product", "year"],
20491        )
20492        .expect("read");
20493
20494        assert!(roundtrip.equals(&frame));
20495        assert_eq!(roundtrip.row_multiindex(), frame.row_multiindex());
20496    }
20497
20498    fn build_two_sheet_workbook_bytes() -> Vec<u8> {
20499        use rust_xlsxwriter::Workbook;
20500        let mut workbook = Workbook::new();
20501        let sheet1 = workbook.add_worksheet();
20502        sheet1.set_name("Alpha").expect("sheet name");
20503        sheet1.write_string(0, 0, "a").expect("header");
20504        sheet1.write_string(0, 1, "b").expect("header");
20505        sheet1.write_number(1, 0, 1.0).expect("data");
20506        sheet1.write_number(1, 1, 10.0).expect("data");
20507        sheet1.write_number(2, 0, 2.0).expect("data");
20508        sheet1.write_number(2, 1, 20.0).expect("data");
20509
20510        let sheet2 = workbook.add_worksheet();
20511        sheet2.set_name("Bravo").expect("sheet name");
20512        sheet2.write_string(0, 0, "name").expect("header");
20513        sheet2.write_string(1, 0, "alice").expect("data");
20514        sheet2.write_string(2, 0, "bob").expect("data");
20515
20516        let sheet3 = workbook.add_worksheet();
20517        sheet3.set_name("Charlie").expect("sheet name");
20518        sheet3.write_string(0, 0, "x").expect("header");
20519        sheet3.write_number(1, 0, 99.0).expect("data");
20520
20521        workbook.save_to_buffer().expect("save")
20522    }
20523
20524    #[test]
20525    fn read_excel_sheets_ordered_bytes_preserves_workbook_order() {
20526        // Workbook sheet order: Alpha, Bravo, Charlie. A sorted map
20527        // would still give Alpha/Bravo/Charlie alphabetically — but
20528        // pandas guarantees workbook order regardless of alphabetic
20529        // relationship, so this test uses a fixture where the ordered
20530        // result differs from sorted order.
20531        use rust_xlsxwriter::Workbook;
20532        let mut workbook = Workbook::new();
20533        let s1 = workbook.add_worksheet();
20534        s1.set_name("Zulu").expect("name");
20535        s1.write_string(0, 0, "v").expect("header");
20536        s1.write_number(1, 0, 1.0).expect("data");
20537        let s2 = workbook.add_worksheet();
20538        s2.set_name("Alpha").expect("name");
20539        s2.write_string(0, 0, "v").expect("header");
20540        s2.write_number(1, 0, 2.0).expect("data");
20541        let s3 = workbook.add_worksheet();
20542        s3.set_name("Mike").expect("name");
20543        s3.write_string(0, 0, "v").expect("header");
20544        s3.write_number(1, 0, 3.0).expect("data");
20545        let bytes = workbook.save_to_buffer().expect("save");
20546
20547        let ordered = super::read_excel_sheets_ordered_bytes(
20548            &bytes,
20549            None,
20550            &super::ExcelReadOptions::default(),
20551        )
20552        .expect("read ordered");
20553        assert_eq!(
20554            ordered.iter().map(|(k, _)| k.as_str()).collect::<Vec<_>>(),
20555            vec!["Zulu", "Alpha", "Mike"],
20556            "ordered form preserves workbook order"
20557        );
20558
20559        // Sorted form alphabetizes (existing contract for BTreeMap).
20560        let sorted =
20561            super::read_excel_sheets_bytes(&bytes, None, &super::ExcelReadOptions::default())
20562                .expect("read sorted");
20563        assert_eq!(
20564            sorted.keys().map(String::as_str).collect::<Vec<_>>(),
20565            vec!["Alpha", "Mike", "Zulu"],
20566            "BTreeMap form alphabetizes"
20567        );
20568    }
20569
20570    #[test]
20571    fn read_excel_sheets_ordered_bytes_selected_subset_keeps_caller_order() {
20572        let bytes = build_two_sheet_workbook_bytes();
20573        // Caller-specified order: Charlie, Alpha — deliberately reversed
20574        // from workbook order. Pandas docs say sheet_name=[list] returns
20575        // a dict whose iteration reflects the argument order; we match.
20576        let req = vec!["Charlie".to_string(), "Alpha".to_string()];
20577        let ordered = super::read_excel_sheets_ordered_bytes(
20578            &bytes,
20579            Some(&req),
20580            &super::ExcelReadOptions::default(),
20581        )
20582        .expect("ordered subset");
20583        assert_eq!(
20584            ordered.iter().map(|(k, _)| k.as_str()).collect::<Vec<_>>(),
20585            vec!["Charlie", "Alpha"]
20586        );
20587    }
20588
20589    #[test]
20590    fn read_excel_sheets_ordered_path_matches_bytes() {
20591        let bytes = build_two_sheet_workbook_bytes();
20592        let temp = std::env::temp_dir().join("fp_io_wrt3_ordered.xlsx");
20593        std::fs::write(&temp, &bytes).expect("write temp");
20594        let via_path =
20595            super::read_excel_sheets_ordered(&temp, None, &super::ExcelReadOptions::default())
20596                .expect("read path");
20597        let via_bytes = super::read_excel_sheets_ordered_bytes(
20598            &bytes,
20599            None,
20600            &super::ExcelReadOptions::default(),
20601        )
20602        .expect("read bytes");
20603        assert_eq!(
20604            via_path.iter().map(|(k, _)| k.clone()).collect::<Vec<_>>(),
20605            via_bytes.iter().map(|(k, _)| k.clone()).collect::<Vec<_>>()
20606        );
20607    }
20608
20609    #[test]
20610    fn read_excel_sheets_bytes_all_sheets_returns_map() {
20611        let bytes = build_two_sheet_workbook_bytes();
20612        let sheets =
20613            super::read_excel_sheets_bytes(&bytes, None, &super::ExcelReadOptions::default())
20614                .expect("read sheets");
20615        assert_eq!(sheets.len(), 3);
20616        assert!(sheets.contains_key("Alpha"));
20617        assert!(sheets.contains_key("Bravo"));
20618        assert!(sheets.contains_key("Charlie"));
20619
20620        let alpha = &sheets["Alpha"];
20621        assert_eq!(alpha.index().len(), 2);
20622        assert_eq!(alpha.column_names().len(), 2);
20623
20624        let bravo = &sheets["Bravo"];
20625        assert_eq!(bravo.index().len(), 2);
20626        assert_eq!(
20627            bravo.column("name").unwrap().values()[0],
20628            Scalar::Utf8("alice".into())
20629        );
20630    }
20631
20632    #[test]
20633    fn read_excel_sheets_bytes_selects_subset() {
20634        let bytes = build_two_sheet_workbook_bytes();
20635        let selected = vec!["Alpha".to_string(), "Charlie".to_string()];
20636        let sheets = super::read_excel_sheets_bytes(
20637            &bytes,
20638            Some(&selected),
20639            &super::ExcelReadOptions::default(),
20640        )
20641        .expect("read subset");
20642        assert_eq!(sheets.len(), 2);
20643        assert!(sheets.contains_key("Alpha"));
20644        assert!(sheets.contains_key("Charlie"));
20645        assert!(!sheets.contains_key("Bravo"));
20646    }
20647
20648    #[test]
20649    fn read_excel_sheets_bytes_unknown_sheet_errors() {
20650        let bytes = build_two_sheet_workbook_bytes();
20651        let bogus = vec!["Zeta".to_string()];
20652        let err = super::read_excel_sheets_bytes(
20653            &bytes,
20654            Some(&bogus),
20655            &super::ExcelReadOptions::default(),
20656        )
20657        .unwrap_err();
20658        assert!(matches!(err, super::IoError::Excel(_)));
20659    }
20660
20661    #[test]
20662    fn read_excel_sheets_path_matches_bytes() {
20663        let bytes = build_two_sheet_workbook_bytes();
20664        let temp = std::env::temp_dir().join("fp_io_9my2_multisheet.xlsx");
20665        std::fs::write(&temp, &bytes).expect("write temp");
20666        let via_path = super::read_excel_sheets(&temp, None, &super::ExcelReadOptions::default())
20667            .expect("read path");
20668        let via_bytes =
20669            super::read_excel_sheets_bytes(&bytes, None, &super::ExcelReadOptions::default())
20670                .expect("read bytes");
20671        assert_eq!(
20672            via_path.keys().collect::<Vec<_>>(),
20673            via_bytes.keys().collect::<Vec<_>>()
20674        );
20675    }
20676
20677    #[test]
20678    fn excel_bytes_roundtrip() {
20679        let frame = make_test_dataframe();
20680        let bytes = super::write_excel_bytes(&frame).expect("write excel");
20681        assert!(!bytes.is_empty());
20682
20683        let frame2 = super::read_excel_bytes(
20684            &bytes,
20685            &super::ExcelReadOptions {
20686                index_col: Some("column_0".into()),
20687                ..Default::default()
20688            },
20689        )
20690        .expect("read excel");
20691        assert_eq!(frame2.index().len(), 3);
20692        assert_eq!(frame2.index().labels(), frame.index().labels());
20693        assert_eq!(frame2.index().name(), None);
20694        // Excel preserves the write-time column order (ints, floats, names).
20695        assert_eq!(
20696            frame2
20697                .column_names()
20698                .iter()
20699                .map(|s| s.as_str())
20700                .collect::<Vec<_>>(),
20701            vec!["ints", "floats", "names"]
20702        );
20703
20704        // Int values survive round-trip (Excel stores as f64, we recover Int64).
20705        let ints = frame2.column("ints").unwrap();
20706        assert_eq!(ints.values()[0], Scalar::Int64(10));
20707        assert_eq!(ints.values()[1], Scalar::Int64(20));
20708        assert_eq!(ints.values()[2], Scalar::Int64(30));
20709
20710        // Float values survive round-trip.
20711        let floats = frame2.column("floats").unwrap();
20712        assert_eq!(floats.values()[0], Scalar::Float64(1.5));
20713        assert_eq!(floats.values()[1], Scalar::Float64(2.5));
20714        assert_eq!(floats.values()[2], Scalar::Float64(3.5));
20715
20716        // String values survive round-trip.
20717        let names = frame2.column("names").unwrap();
20718        assert_eq!(names.values()[0], Scalar::Utf8("alice".into()));
20719        assert_eq!(names.values()[1], Scalar::Utf8("bob".into()));
20720        assert_eq!(names.values()[2], Scalar::Utf8("carol".into()));
20721    }
20722
20723    #[test]
20724    fn excel_file_roundtrip() {
20725        let frame = make_test_dataframe();
20726        let dir = std::env::temp_dir();
20727        let path = dir.join("fp_io_test_excel_roundtrip.xlsx");
20728
20729        super::write_excel(&frame, &path).expect("write excel file");
20730        let frame2 = super::read_excel(
20731            &path,
20732            &super::ExcelReadOptions {
20733                index_col: Some("column_0".into()),
20734                ..Default::default()
20735            },
20736        )
20737        .expect("read excel file");
20738        assert_eq!(frame2.index().len(), 3);
20739        assert_eq!(frame2.index().labels(), frame.index().labels());
20740        assert_eq!(
20741            frame2.column("ints").unwrap().values()[0],
20742            Scalar::Int64(10)
20743        );
20744        std::fs::remove_file(&path).ok();
20745    }
20746
20747    #[test]
20748    fn excel_with_nulls() {
20749        use fp_types::DType;
20750
20751        let mut columns = BTreeMap::new();
20752        columns.insert(
20753            "vals".to_string(),
20754            Column::new(
20755                DType::Float64,
20756                vec![
20757                    Scalar::Float64(1.0),
20758                    Scalar::Null(NullKind::NaN),
20759                    Scalar::Float64(3.0),
20760                ],
20761            )
20762            .unwrap(),
20763        );
20764
20765        let labels = vec![
20766            IndexLabel::Int64(0),
20767            IndexLabel::Int64(1),
20768            IndexLabel::Int64(2),
20769        ];
20770        let frame =
20771            DataFrame::new_with_column_order(Index::new(labels), columns, vec!["vals".to_string()])
20772                .unwrap();
20773
20774        let bytes = super::write_excel_bytes(&frame).expect("write");
20775        let frame2 = super::read_excel_bytes(
20776            &bytes,
20777            &super::ExcelReadOptions {
20778                index_col: Some("column_0".into()),
20779                ..Default::default()
20780            },
20781        )
20782        .expect("read");
20783
20784        // Non-null values round-trip.
20785        assert_eq!(frame2.column("vals").unwrap().values()[0], Scalar::Int64(1));
20786        // NaN written as empty cell, read back as Null.
20787        assert!(frame2.column("vals").unwrap().values()[1].is_missing());
20788        assert_eq!(frame2.column("vals").unwrap().values()[2], Scalar::Int64(3));
20789    }
20790
20791    #[test]
20792    fn excel_bool_column() {
20793        use fp_types::DType;
20794
20795        let mut columns = BTreeMap::new();
20796        columns.insert(
20797            "flags".to_string(),
20798            Column::new(
20799                DType::Bool,
20800                vec![Scalar::Bool(true), Scalar::Bool(false), Scalar::Bool(true)],
20801            )
20802            .unwrap(),
20803        );
20804
20805        let labels = vec![
20806            IndexLabel::Int64(0),
20807            IndexLabel::Int64(1),
20808            IndexLabel::Int64(2),
20809        ];
20810        let frame = DataFrame::new_with_column_order(
20811            Index::new(labels),
20812            columns,
20813            vec!["flags".to_string()],
20814        )
20815        .unwrap();
20816
20817        let bytes = super::write_excel_bytes(&frame).expect("write");
20818        let frame2 = super::read_excel_bytes(
20819            &bytes,
20820            &super::ExcelReadOptions {
20821                index_col: Some("column_0".into()),
20822                ..Default::default()
20823            },
20824        )
20825        .expect("read");
20826
20827        assert_eq!(
20828            frame2.column("flags").unwrap().values()[0],
20829            Scalar::Bool(true)
20830        );
20831        assert_eq!(
20832            frame2.column("flags").unwrap().values()[1],
20833            Scalar::Bool(false)
20834        );
20835        assert_eq!(
20836            frame2.column("flags").unwrap().values()[2],
20837            Scalar::Bool(true)
20838        );
20839    }
20840
20841    #[test]
20842    fn excel_skip_rows() {
20843        // Build an xlsx with 5 data rows, then read with skip_rows=2 to skip
20844        // 2 rows before the header.
20845        use fp_types::DType;
20846
20847        let mut columns = BTreeMap::new();
20848        columns.insert(
20849            "x".to_string(),
20850            Column::new(DType::Int64, vec![Scalar::Int64(1), Scalar::Int64(2)]).unwrap(),
20851        );
20852        let labels = vec![IndexLabel::Int64(0), IndexLabel::Int64(1)];
20853        let frame =
20854            DataFrame::new_with_column_order(Index::new(labels), columns, vec!["x".to_string()])
20855                .unwrap();
20856
20857        let bytes = super::write_excel_bytes(&frame).expect("write");
20858        let frame2 = super::read_excel_bytes(
20859            &bytes,
20860            &super::ExcelReadOptions {
20861                skip_rows: 1,
20862                has_headers: false,
20863                ..Default::default()
20864            },
20865        )
20866        .expect("read with skip");
20867
20868        // Skipped the header row, so first data row becomes first row.
20869        // With has_headers=false, column names are auto-generated.
20870        assert_eq!(frame2.index().len(), 2);
20871        assert!(frame2.column("column_0").is_some());
20872    }
20873
20874    #[test]
20875    fn excel_header_none_with_explicit_names_uses_names_and_keeps_first_row() {
20876        let rows = vec![
20877            vec![
20878                calamine::Data::Int(1),
20879                calamine::Data::String("alpha".to_owned()),
20880            ],
20881            vec![
20882                calamine::Data::Int(2),
20883                calamine::Data::String("beta".to_owned()),
20884            ],
20885        ];
20886
20887        let frame = super::parse_excel_rows(
20888            rows,
20889            &super::ExcelReadOptions {
20890                has_headers: false,
20891                names: Some(vec!["id".to_owned(), "label".to_owned()]),
20892                ..Default::default()
20893            },
20894        )
20895        .expect("parse excel rows with explicit names");
20896
20897        assert_eq!(frame.column_names(), vec!["id", "label"]);
20898        assert_eq!(frame.index().len(), 2);
20899        assert_eq!(frame.column("id").unwrap().values()[0], Scalar::Int64(1));
20900        assert_eq!(
20901            frame.column("label").unwrap().values()[0],
20902            Scalar::Utf8("alpha".into())
20903        );
20904        assert_eq!(frame.column("id").unwrap().values()[1], Scalar::Int64(2));
20905    }
20906
20907    #[test]
20908    fn excel_header_none_with_explicit_names_preserves_index_name() {
20909        let rows = vec![
20910            vec![
20911                calamine::Data::Int(10),
20912                calamine::Data::String("alpha".to_owned()),
20913            ],
20914            vec![
20915                calamine::Data::Int(20),
20916                calamine::Data::String("beta".to_owned()),
20917            ],
20918        ];
20919
20920        let frame = super::parse_excel_rows(
20921            rows,
20922            &super::ExcelReadOptions {
20923                has_headers: false,
20924                names: Some(vec!["row_id".to_owned(), "value".to_owned()]),
20925                index_col: Some("row_id".to_owned()),
20926                ..Default::default()
20927            },
20928        )
20929        .expect("parse excel rows with named index column");
20930
20931        assert_eq!(frame.index().name(), Some("row_id"));
20932        assert_eq!(frame.index().labels()[0], IndexLabel::Int64(10));
20933        assert_eq!(frame.index().labels()[1], IndexLabel::Int64(20));
20934        assert!(frame.column("row_id").is_none());
20935        assert_eq!(
20936            frame.column("value").unwrap().values(),
20937            &[Scalar::Utf8("alpha".into()), Scalar::Utf8("beta".into())]
20938        );
20939    }
20940
20941    #[test]
20942    fn excel_explicit_names_width_mismatch_errors() {
20943        let rows = vec![vec![calamine::Data::Int(1), calamine::Data::Int(2)]];
20944
20945        let err = super::parse_excel_rows(
20946            rows,
20947            &super::ExcelReadOptions {
20948                has_headers: false,
20949                names: Some(vec!["only_one".to_owned()]),
20950                ..Default::default()
20951            },
20952        )
20953        .expect_err("names width mismatch should error");
20954
20955        assert!(
20956            matches!(err, IoError::Excel(message) if message.contains("expected 2 column names, got 1"))
20957        );
20958    }
20959
20960    #[test]
20961    fn excel_usecols_selects_subset_in_sheet_order() {
20962        let rows = vec![
20963            vec![
20964                calamine::Data::String("a".to_owned()),
20965                calamine::Data::String("b".to_owned()),
20966                calamine::Data::String("c".to_owned()),
20967            ],
20968            vec![
20969                calamine::Data::Int(1),
20970                calamine::Data::Int(2),
20971                calamine::Data::Int(3),
20972            ],
20973        ];
20974
20975        let frame = super::parse_excel_rows(
20976            rows,
20977            &super::ExcelReadOptions {
20978                usecols: Some(vec!["c".to_owned(), "a".to_owned()]),
20979                ..Default::default()
20980            },
20981        )
20982        .expect("parse excel rows with usecols");
20983
20984        assert_eq!(frame.column_names(), vec!["a", "c"]);
20985        assert_eq!(frame.column("a").unwrap().values(), &[Scalar::Int64(1)]);
20986        assert_eq!(frame.column("c").unwrap().values(), &[Scalar::Int64(3)]);
20987        assert!(frame.column("b").is_none());
20988    }
20989
20990    #[test]
20991    fn excel_usecols_with_explicit_names_filters_renamed_columns() {
20992        let rows = vec![
20993            vec![
20994                calamine::Data::Int(1),
20995                calamine::Data::String("alpha".to_owned()),
20996            ],
20997            vec![
20998                calamine::Data::Int(2),
20999                calamine::Data::String("beta".to_owned()),
21000            ],
21001        ];
21002
21003        let frame = super::parse_excel_rows(
21004            rows,
21005            &super::ExcelReadOptions {
21006                has_headers: false,
21007                names: Some(vec!["id".to_owned(), "label".to_owned()]),
21008                usecols: Some(vec!["label".to_owned()]),
21009                ..Default::default()
21010            },
21011        )
21012        .expect("parse headerless excel rows with names and usecols");
21013
21014        assert_eq!(frame.column_names(), vec!["label"]);
21015        assert_eq!(
21016            frame.column("label").unwrap().values(),
21017            &[Scalar::Utf8("alpha".into()), Scalar::Utf8("beta".into())]
21018        );
21019        assert!(frame.column("id").is_none());
21020    }
21021
21022    #[test]
21023    fn excel_usecols_missing_column_errors() {
21024        let rows = vec![
21025            vec![
21026                calamine::Data::String("a".to_owned()),
21027                calamine::Data::String("b".to_owned()),
21028            ],
21029            vec![calamine::Data::Int(1), calamine::Data::Int(2)],
21030        ];
21031
21032        let err = super::parse_excel_rows(
21033            rows,
21034            &super::ExcelReadOptions {
21035                usecols: Some(vec!["missing".to_owned()]),
21036                ..Default::default()
21037            },
21038        )
21039        .expect_err("missing excel usecols should error");
21040
21041        assert!(
21042            matches!(err, IoError::MissingUsecols(missing) if missing == vec!["missing".to_owned()])
21043        );
21044    }
21045
21046    #[test]
21047    fn excel_default_read_promotes_writer_range_index_back_to_index() {
21048        let frame = make_test_dataframe();
21049        let bytes = super::write_excel_bytes(&frame).expect("write excel");
21050
21051        let frame2 = super::read_excel_bytes(&bytes, &super::ExcelReadOptions::default())
21052            .expect("read excel");
21053
21054        assert_eq!(frame2.index().labels(), frame.index().labels());
21055        assert_eq!(frame2.index().name(), None);
21056        assert_eq!(frame2.column_names(), vec!["ints", "floats", "names"],);
21057        assert!(frame2.column("column_0").is_none());
21058    }
21059
21060    #[test]
21061    fn excel_default_read_keeps_non_range_generated_leading_column_as_data() {
21062        let rows = vec![
21063            vec![
21064                calamine::Data::Empty,
21065                calamine::Data::String("value".to_owned()),
21066            ],
21067            vec![calamine::Data::Int(10), calamine::Data::Int(1)],
21068            vec![calamine::Data::Int(20), calamine::Data::Int(2)],
21069        ];
21070
21071        let frame = super::parse_excel_rows(rows, &super::ExcelReadOptions::default())
21072            .expect("parse excel rows");
21073
21074        assert_eq!(
21075            frame.index().labels(),
21076            &[IndexLabel::Int64(0), IndexLabel::Int64(1)]
21077        );
21078        assert_eq!(frame.column_names(), vec!["column_0", "value"]);
21079        assert_eq!(
21080            frame.column("column_0").unwrap().values(),
21081            &[Scalar::Int64(10), Scalar::Int64(20)],
21082        );
21083    }
21084
21085    #[test]
21086    fn excel_named_index_roundtrip_preserves_index_name() {
21087        use fp_types::DType;
21088
21089        let mut columns = BTreeMap::new();
21090        columns.insert(
21091            "vals".to_string(),
21092            Column::new(DType::Int64, vec![Scalar::Int64(10), Scalar::Int64(20)]).unwrap(),
21093        );
21094
21095        let frame = DataFrame::new_with_column_order(
21096            Index::new(vec![IndexLabel::Int64(10), IndexLabel::Int64(20)]).set_name("row_id"),
21097            columns,
21098            vec!["vals".to_string()],
21099        )
21100        .unwrap();
21101
21102        let bytes = super::write_excel_bytes(&frame).expect("write excel");
21103        let frame2 = super::read_excel_bytes(
21104            &bytes,
21105            &super::ExcelReadOptions {
21106                index_col: Some("row_id".into()),
21107                ..Default::default()
21108            },
21109        )
21110        .expect("read excel");
21111
21112        assert_eq!(frame2.index().labels(), frame.index().labels());
21113        assert_eq!(frame2.index().name(), Some("row_id"));
21114        assert!(frame2.column("row_id").is_none());
21115        assert_eq!(
21116            frame2.column("vals").unwrap().values(),
21117            &[Scalar::Int64(10), Scalar::Int64(20)]
21118        );
21119    }
21120
21121    #[test]
21122    fn excel_duplicate_headers_error() {
21123        let rows = vec![
21124            vec![
21125                calamine::Data::String("dup".to_owned()),
21126                calamine::Data::String("dup".to_owned()),
21127            ],
21128            vec![calamine::Data::Int(1), calamine::Data::Int(2)],
21129        ];
21130
21131        let err = super::parse_excel_rows(rows, &super::ExcelReadOptions::default())
21132            .expect_err("duplicate headers should error");
21133        assert!(matches!(err, IoError::DuplicateColumnName(_)));
21134    }
21135
21136    // ── SQL I/O tests ──────────────────────────────────────────────
21137    //
21138    // Per br-frankenpandas-7a49 (fd90.48): keep the import block
21139    // unconditional so stub-backend tests (which only need types and
21140    // free-fns, not rusqlite) compile under --no-default-features.
21141    // `#[allow(unused_imports)]` covers the few free fns that are
21142    // exclusively used inside the cfg-gated SQLite-backed tests.
21143
21144    // Per fd90.48: TYPE imports + introspection-helper free fns are
21145    // used by both stub-backend tests (which compile under
21146    // --no-default-features) and SQLite-backed tests. The
21147    // read_sql_* / write_sql_* row-materialization free fns are only
21148    // exercised inside SQLite-backed tests (cfg-gated below) so they
21149    // get their own gated import group to avoid unused warnings.
21150    // Per fd90.48: TYPE imports + introspection-helper free fns +
21151    // write_sql / write_sql_with_options are used by both stub-backend
21152    // tests (which compile under --no-default-features) and
21153    // SQLite-backed tests. The read_sql_* row-materialization free fns
21154    // are only exercised inside SQLite-backed tests (cfg-gated below).
21155    use super::{
21156        SqlBackendCaps, SqlColumnSchema, SqlForeignKeySchema, SqlIfExists, SqlIndexSchema,
21157        SqlInsertMethod, SqlInspector, SqlQueryResult, SqlReadOptions, SqlReflectedTable,
21158        SqlTableSchema, SqlUniqueConstraintSchema, SqlWriteOptions, list_sql_foreign_keys,
21159        list_sql_indexes, list_sql_schemas, list_sql_tables, list_sql_unique_constraints,
21160        list_sql_views, sql_backend_caps, sql_max_identifier_length, sql_max_insert_rows,
21161        sql_max_param_count, sql_primary_key_columns, sql_server_version, sql_supports_returning,
21162        sql_supports_schemas, sql_table_comment, sql_table_schema, truncate_sql_table, write_sql,
21163        write_sql_with_options,
21164    };
21165    #[cfg(feature = "sql-sqlite")]
21166    use super::{
21167        read_sql, read_sql_chunks, read_sql_chunks_with_index_col, read_sql_chunks_with_options,
21168        read_sql_chunks_with_options_and_index_col, read_sql_query, read_sql_query_chunks,
21169        read_sql_query_chunks_with_index_col, read_sql_query_chunks_with_options,
21170        read_sql_query_chunks_with_options_and_index_col, read_sql_query_with_index_col,
21171        read_sql_query_with_options, read_sql_query_with_options_and_index_col, read_sql_table,
21172        read_sql_table_chunks, read_sql_table_chunks_with_index_col,
21173        read_sql_table_chunks_with_options, read_sql_table_chunks_with_options_and_index_col,
21174        read_sql_table_columns, read_sql_table_columns_chunks,
21175        read_sql_table_columns_chunks_with_index_col, read_sql_table_columns_with_index_col,
21176        read_sql_table_with_index_col, read_sql_table_with_options,
21177        read_sql_table_with_options_and_index_col, read_sql_with_index_col, read_sql_with_options,
21178    };
21179
21180    // Per br-frankenpandas-7a49 (fd90.48): the helper itself only
21181    // exists when sql-sqlite is on, since it directly references
21182    // rusqlite::Connection. All tests that call this are also
21183    // cfg-gated on the same feature.
21184    #[cfg(feature = "sql-sqlite")]
21185    fn make_sql_test_conn() -> rusqlite::Connection {
21186        rusqlite::Connection::open_in_memory().expect("in-memory sqlite")
21187    }
21188
21189    #[cfg(feature = "sql-sqlite")]
21190    #[test]
21191    fn sql_read_with_index_col_promotes_named_column() {
21192        let frame = make_test_dataframe();
21193        let conn = make_sql_test_conn();
21194        write_sql(&frame, &conn, "indexed_tbl", SqlIfExists::Fail).expect("write");
21195
21196        // Promote the "ints" column to the row index. The data
21197        // columns should drop ints and the index labels should be the
21198        // ints values.
21199        let result = read_sql_table_with_index_col(&conn, "indexed_tbl", Some("ints"))
21200            .expect("read with index");
21201        assert_eq!(result.index().name(), Some("ints"));
21202        assert_eq!(result.index().labels()[0], crate::IndexLabel::Int64(10));
21203        assert_eq!(result.index().labels()[1], crate::IndexLabel::Int64(20));
21204        assert_eq!(result.index().labels()[2], crate::IndexLabel::Int64(30));
21205        // Data columns: only the non-index columns remain.
21206        let names: Vec<&str> = result.column_names().iter().map(|s| s.as_str()).collect();
21207        assert!(!names.contains(&"ints"));
21208        assert!(names.contains(&"floats"));
21209        assert!(names.contains(&"names"));
21210    }
21211
21212    #[cfg(feature = "sql-sqlite")]
21213    #[test]
21214    fn sql_read_with_index_col_none_is_unchanged() {
21215        let frame = make_test_dataframe();
21216        let conn = make_sql_test_conn();
21217        write_sql(&frame, &conn, "noindex_tbl", SqlIfExists::Fail).expect("write");
21218        let baseline = read_sql_table(&conn, "noindex_tbl").expect("baseline");
21219        let result =
21220            read_sql_table_with_index_col(&conn, "noindex_tbl", None).expect("noop variant");
21221        assert_eq!(result.index().labels(), baseline.index().labels());
21222        assert_eq!(result.column_names(), baseline.column_names());
21223    }
21224
21225    #[cfg(feature = "sql-sqlite")]
21226    #[test]
21227    fn sql_read_with_index_col_unknown_column_errors() {
21228        let frame = make_test_dataframe();
21229        let conn = make_sql_test_conn();
21230        write_sql(&frame, &conn, "missing_tbl", SqlIfExists::Fail).expect("write");
21231        let err = read_sql_table_with_index_col(&conn, "missing_tbl", Some("nope")).unwrap_err();
21232        assert!(matches!(err, crate::IoError::Sql(_)));
21233    }
21234
21235    #[cfg(feature = "sql-sqlite")]
21236    #[test]
21237    fn sql_read_table_columns_returns_requested_projection_in_order() {
21238        let frame = make_test_dataframe();
21239        let conn = make_sql_test_conn();
21240        write_sql(&frame, &conn, "proj_tbl", SqlIfExists::Fail).expect("write");
21241
21242        let result = read_sql_table_columns(&conn, "proj_tbl", &["names", "ints"])
21243            .expect("subset projection");
21244        let names: Vec<&str> = result.column_names().iter().map(|s| s.as_str()).collect();
21245        assert_eq!(names, vec!["names", "ints"]);
21246        assert_eq!(result.index().len(), 3);
21247        assert_eq!(
21248            result.column("ints").unwrap().values()[0],
21249            Scalar::Int64(10)
21250        );
21251        assert_eq!(
21252            result.column("names").unwrap().values()[2],
21253            Scalar::Utf8("carol".into())
21254        );
21255    }
21256
21257    #[cfg(feature = "sql-sqlite")]
21258    #[test]
21259    fn sql_read_table_columns_single_column_projection() {
21260        let frame = make_test_dataframe();
21261        let conn = make_sql_test_conn();
21262        write_sql(&frame, &conn, "single_tbl", SqlIfExists::Fail).expect("write");
21263
21264        let result =
21265            read_sql_table_columns(&conn, "single_tbl", &["floats"]).expect("single projection");
21266        let names: Vec<&str> = result.column_names().iter().map(|s| s.as_str()).collect();
21267        assert_eq!(names, vec!["floats"]);
21268        assert_eq!(
21269            result.column("floats").unwrap().values()[1],
21270            Scalar::Float64(2.5)
21271        );
21272    }
21273
21274    #[cfg(feature = "sql-sqlite")]
21275    #[test]
21276    fn sql_read_table_columns_rejects_empty_columns() {
21277        let conn = make_sql_test_conn();
21278        let err = read_sql_table_columns(&conn, "any_tbl", &[]).unwrap_err();
21279        assert!(matches!(err, crate::IoError::Sql(_)));
21280    }
21281
21282    #[cfg(feature = "sql-sqlite")]
21283    #[test]
21284    fn sql_read_table_columns_rejects_invalid_column_name() {
21285        let frame = make_test_dataframe();
21286        let conn = make_sql_test_conn();
21287        write_sql(&frame, &conn, "valid_tbl", SqlIfExists::Fail).expect("write");
21288        let err = read_sql_table_columns(&conn, "valid_tbl", &["ints; DROP TABLE valid_tbl"])
21289            .unwrap_err();
21290        assert!(matches!(err, crate::IoError::Sql(_)));
21291    }
21292
21293    #[cfg(feature = "sql-sqlite")]
21294    #[test]
21295    fn sql_read_table_columns_rejects_invalid_table_name() {
21296        let conn = make_sql_test_conn();
21297        let err = read_sql_table_columns(&conn, "bad table", &["ints"]).unwrap_err();
21298        assert!(matches!(err, crate::IoError::Sql(_)));
21299    }
21300
21301    #[cfg(feature = "sql-sqlite")]
21302    #[test]
21303    fn sql_read_table_columns_chunks_returns_requested_projection_in_order() {
21304        let frame = make_test_dataframe();
21305        let conn = make_sql_test_conn();
21306        write_sql(&frame, &conn, "proj_chunk_tbl", SqlIfExists::Fail).expect("write");
21307
21308        let chunks = read_sql_table_columns_chunks(&conn, "proj_chunk_tbl", &["names", "ints"], 2)
21309            .expect("projection chunk iterator")
21310            .collect::<Result<Vec<_>, _>>()
21311            .expect("all chunks");
21312
21313        assert_eq!(chunks.len(), 2);
21314        assert_eq!(chunks[0].column_names(), vec!["names", "ints"]);
21315        assert_eq!(
21316            chunks[0].column("names").unwrap().values(),
21317            &[
21318                Scalar::Utf8("alice".to_owned()),
21319                Scalar::Utf8("bob".to_owned())
21320            ]
21321        );
21322        assert_eq!(
21323            chunks[1].column("ints").unwrap().values(),
21324            &[Scalar::Int64(30)]
21325        );
21326    }
21327
21328    #[cfg(feature = "sql-sqlite")]
21329    #[test]
21330    fn sql_read_table_columns_chunks_rejects_zero_chunksize() {
21331        let frame = make_test_dataframe();
21332        let conn = make_sql_test_conn();
21333        write_sql(&frame, &conn, "proj_zero_chunk_tbl", SqlIfExists::Fail).expect("write");
21334
21335        let err = read_sql_table_columns_chunks(&conn, "proj_zero_chunk_tbl", &["names"], 0)
21336            .expect_err("zero projection chunksize should be rejected");
21337
21338        assert!(matches!(err, IoError::Sql(msg) if msg.contains("chunksize")));
21339    }
21340
21341    #[cfg(feature = "sql-sqlite")]
21342    #[test]
21343    fn sql_read_table_columns_chunks_rejects_invalid_projection_inputs() {
21344        let conn = make_sql_test_conn();
21345
21346        let empty = read_sql_table_columns_chunks(&conn, "proj_chunk_tbl", &[], 1)
21347            .expect_err("empty projection should be rejected");
21348        assert!(matches!(empty, IoError::Sql(msg) if msg.contains("columns must be non-empty")));
21349
21350        let invalid = read_sql_table_columns_chunks(&conn, "proj_chunk_tbl", &["bad column"], 1)
21351            .expect_err("invalid projection name should be rejected");
21352        assert!(matches!(invalid, IoError::Sql(msg) if msg.contains("invalid column name")));
21353    }
21354
21355    #[cfg(feature = "sql-sqlite")]
21356    #[test]
21357    fn sql_read_table_columns_with_index_col_promotes_projected_column() {
21358        let frame = make_test_dataframe();
21359        let conn = make_sql_test_conn();
21360        write_sql(&frame, &conn, "proj_index_tbl", SqlIfExists::Fail).expect("write");
21361
21362        let result = read_sql_table_columns_with_index_col(
21363            &conn,
21364            "proj_index_tbl",
21365            &["names", "ints"],
21366            Some("ints"),
21367        )
21368        .expect("projection with index_col");
21369
21370        assert_eq!(result.index().name(), Some("ints"));
21371        assert_eq!(
21372            result.index().labels(),
21373            &[
21374                IndexLabel::Int64(10),
21375                IndexLabel::Int64(20),
21376                IndexLabel::Int64(30)
21377            ]
21378        );
21379        assert_eq!(result.column_names(), vec!["names"]);
21380        assert_eq!(
21381            result.column("names").unwrap().values(),
21382            &[
21383                Scalar::Utf8("alice".to_owned()),
21384                Scalar::Utf8("bob".to_owned()),
21385                Scalar::Utf8("carol".to_owned())
21386            ]
21387        );
21388        assert!(result.column("ints").is_none());
21389    }
21390
21391    // br-frankenpandas-6n0uz: when index_col is set but NOT in columns,
21392    // pandas auto-projects it into the SELECT (then drops it from data
21393    // columns after promotion). Mirrors fd90.76's behavior on the
21394    // options-based reader.
21395    #[cfg(feature = "sql-sqlite")]
21396    #[test]
21397    fn sql_read_table_columns_with_index_col_auto_projects_when_absent() {
21398        let frame = make_test_dataframe();
21399        let conn = make_sql_test_conn();
21400        write_sql(&frame, &conn, "auto_proj_tbl", SqlIfExists::Fail).expect("write");
21401
21402        // index_col "ints" is NOT in columns — must be auto-projected, then
21403        // promoted to the index, then removed from the data columns.
21404        let result =
21405            read_sql_table_columns_with_index_col(&conn, "auto_proj_tbl", &["names"], Some("ints"))
21406                .expect("auto-project index_col");
21407
21408        assert_eq!(result.index().name(), Some("ints"));
21409        assert_eq!(
21410            result.index().labels(),
21411            &[
21412                IndexLabel::Int64(10),
21413                IndexLabel::Int64(20),
21414                IndexLabel::Int64(30)
21415            ]
21416        );
21417        assert_eq!(result.column_names(), vec!["names"]);
21418        assert!(result.column("ints").is_none());
21419        assert_eq!(
21420            result.column("names").unwrap().values(),
21421            &[
21422                Scalar::Utf8("alice".to_owned()),
21423                Scalar::Utf8("bob".to_owned()),
21424                Scalar::Utf8("carol".to_owned())
21425            ]
21426        );
21427    }
21428
21429    #[cfg(feature = "sql-sqlite")]
21430    #[test]
21431    fn sql_read_table_columns_chunks_with_index_col_auto_projects_when_absent() {
21432        let frame = make_test_dataframe();
21433        let conn = make_sql_test_conn();
21434        write_sql(&frame, &conn, "auto_proj_chunks_tbl", SqlIfExists::Fail).expect("write");
21435
21436        // index_col "ints" is NOT in columns — must be auto-projected per
21437        // chunk and dropped from each chunk's data columns.
21438        let chunks = read_sql_table_columns_chunks_with_index_col(
21439            &conn,
21440            "auto_proj_chunks_tbl",
21441            &["names"],
21442            Some("ints"),
21443            2,
21444        )
21445        .expect("auto-project chunks")
21446        .collect::<Result<Vec<_>, _>>()
21447        .expect("all chunks");
21448
21449        assert_eq!(chunks.len(), 2);
21450        assert_eq!(chunks[0].index().name(), Some("ints"));
21451        assert_eq!(
21452            chunks[0].index().labels(),
21453            &[IndexLabel::Int64(10), IndexLabel::Int64(20)]
21454        );
21455        assert_eq!(chunks[0].column_names(), vec!["names"]);
21456        assert!(chunks[0].column("ints").is_none());
21457        assert_eq!(
21458            chunks[0].column("names").unwrap().values(),
21459            &[
21460                Scalar::Utf8("alice".to_owned()),
21461                Scalar::Utf8("bob".to_owned())
21462            ]
21463        );
21464        assert_eq!(chunks[1].index().labels(), &[IndexLabel::Int64(30)]);
21465        assert_eq!(chunks[1].column_names(), vec!["names"]);
21466        assert!(chunks[1].column("ints").is_none());
21467    }
21468
21469    // br-frankenpandas-6n0uz: idempotency check — when index_col IS already
21470    // in columns, the auto-project helper must not duplicate it. Same final
21471    // result as the original explicit-include test, but proves the helper's
21472    // dedupe path.
21473    #[cfg(feature = "sql-sqlite")]
21474    #[test]
21475    fn sql_read_table_columns_with_index_col_no_duplication_when_listed() {
21476        let frame = make_test_dataframe();
21477        let conn = make_sql_test_conn();
21478        write_sql(&frame, &conn, "no_dup_tbl", SqlIfExists::Fail).expect("write");
21479
21480        // index_col "ints" IS in columns — must NOT be duplicated in SELECT.
21481        let result = read_sql_table_columns_with_index_col(
21482            &conn,
21483            "no_dup_tbl",
21484            &["names", "ints"],
21485            Some("ints"),
21486        )
21487        .expect("explicit include + index_col");
21488
21489        assert_eq!(result.index().name(), Some("ints"));
21490        assert_eq!(result.column_names(), vec!["names"]);
21491        assert!(result.column("ints").is_none());
21492    }
21493
21494    #[cfg(feature = "sql-sqlite")]
21495    #[test]
21496    fn sql_read_table_columns_with_index_col_none_keeps_projection_and_range_index() {
21497        let frame = make_test_dataframe();
21498        let conn = make_sql_test_conn();
21499        write_sql(&frame, &conn, "proj_no_index_tbl", SqlIfExists::Fail).expect("write");
21500
21501        let result = read_sql_table_columns_with_index_col(
21502            &conn,
21503            "proj_no_index_tbl",
21504            &["floats", "names"],
21505            None,
21506        )
21507        .expect("projection without index_col");
21508
21509        assert_eq!(
21510            result.index().labels(),
21511            &[
21512                IndexLabel::Int64(0),
21513                IndexLabel::Int64(1),
21514                IndexLabel::Int64(2)
21515            ]
21516        );
21517        assert_eq!(result.column_names(), vec!["floats", "names"]);
21518        assert_eq!(
21519            result.column("floats").unwrap().values()[1],
21520            Scalar::Float64(2.5)
21521        );
21522    }
21523
21524    #[cfg(feature = "sql-sqlite")]
21525    #[test]
21526    fn sql_read_table_columns_chunks_with_index_col_promotes_each_chunk_index() {
21527        let frame = make_test_dataframe();
21528        let conn = make_sql_test_conn();
21529        write_sql(&frame, &conn, "proj_index_chunk_tbl", SqlIfExists::Fail).expect("write");
21530
21531        let chunks = read_sql_table_columns_chunks_with_index_col(
21532            &conn,
21533            "proj_index_chunk_tbl",
21534            &["ints", "names"],
21535            Some("ints"),
21536            2,
21537        )
21538        .expect("indexed projection chunk iterator")
21539        .collect::<Result<Vec<_>, _>>()
21540        .expect("all chunks");
21541
21542        assert_eq!(chunks.len(), 2);
21543        assert_eq!(chunks[0].index().name(), Some("ints"));
21544        assert_eq!(
21545            chunks[0].index().labels(),
21546            &[IndexLabel::Int64(10), IndexLabel::Int64(20)]
21547        );
21548        assert_eq!(chunks[0].column_names(), vec!["names"]);
21549        assert_eq!(
21550            chunks[0].column("names").unwrap().values(),
21551            &[
21552                Scalar::Utf8("alice".to_owned()),
21553                Scalar::Utf8("bob".to_owned())
21554            ]
21555        );
21556        assert_eq!(chunks[1].index().labels(), &[IndexLabel::Int64(30)]);
21557        assert_eq!(
21558            chunks[1].column("names").unwrap().values(),
21559            &[Scalar::Utf8("carol".to_owned())]
21560        );
21561    }
21562
21563    #[cfg(feature = "sql-sqlite")]
21564    #[test]
21565    fn sql_read_table_columns_chunks_with_index_col_validates_projection_and_index() {
21566        let frame = make_test_dataframe();
21567        let conn = make_sql_test_conn();
21568        write_sql(&frame, &conn, "proj_index_error_tbl", SqlIfExists::Fail).expect("write");
21569
21570        let empty = read_sql_table_columns_chunks_with_index_col(
21571            &conn,
21572            "proj_index_error_tbl",
21573            &[],
21574            Some("ints"),
21575            1,
21576        )
21577        .expect_err("empty projection should be rejected");
21578        assert!(matches!(empty, IoError::Sql(msg) if msg.contains("columns must be non-empty")));
21579
21580        let invalid = read_sql_table_columns_with_index_col(
21581            &conn,
21582            "proj_index_error_tbl",
21583            &["bad column"],
21584            Some("ints"),
21585        )
21586        .expect_err("invalid projection name should be rejected");
21587        assert!(matches!(invalid, IoError::Sql(msg) if msg.contains("invalid column name")));
21588    }
21589
21590    #[cfg(feature = "sql-sqlite")]
21591    #[test]
21592    fn sql_read_query_with_index_col_works_on_arbitrary_select() {
21593        let frame = make_test_dataframe();
21594        let conn = make_sql_test_conn();
21595        write_sql(&frame, &conn, "queried_tbl", SqlIfExists::Fail).expect("write");
21596        let result = read_sql_with_index_col(
21597            &conn,
21598            "SELECT names AS label, ints, floats FROM queried_tbl ORDER BY ints DESC",
21599            Some("label"),
21600        )
21601        .expect("read query with index");
21602        assert_eq!(result.index().name(), Some("label"));
21603        // Order respected by the SELECT (ints DESC) → index labels in
21604        // reversed name order.
21605        assert_eq!(
21606            result.index().labels()[0],
21607            crate::IndexLabel::Utf8("carol".into())
21608        );
21609        assert_eq!(
21610            result.index().labels()[2],
21611            crate::IndexLabel::Utf8("alice".into())
21612        );
21613    }
21614
21615    #[cfg(feature = "sql-sqlite")]
21616    #[test]
21617    fn sql_write_read_roundtrip() {
21618        let frame = make_test_dataframe();
21619        let conn = make_sql_test_conn();
21620
21621        write_sql(&frame, &conn, "test_table", SqlIfExists::Fail).expect("write sql");
21622
21623        let frame2 = read_sql_table(&conn, "test_table").expect("read sql");
21624        assert_eq!(frame2.index().len(), 3);
21625
21626        // Int values survive round-trip.
21627        let ints = frame2.column("ints").unwrap();
21628        assert_eq!(ints.values()[0], Scalar::Int64(10));
21629        assert_eq!(ints.values()[1], Scalar::Int64(20));
21630        assert_eq!(ints.values()[2], Scalar::Int64(30));
21631
21632        // Float values survive round-trip.
21633        let floats = frame2.column("floats").unwrap();
21634        assert_eq!(floats.values()[0], Scalar::Float64(1.5));
21635        assert_eq!(floats.values()[1], Scalar::Float64(2.5));
21636        assert_eq!(floats.values()[2], Scalar::Float64(3.5));
21637
21638        // String values survive round-trip.
21639        let names = frame2.column("names").unwrap();
21640        assert_eq!(names.values()[0], Scalar::Utf8("alice".into()));
21641        assert_eq!(names.values()[1], Scalar::Utf8("bob".into()));
21642        assert_eq!(names.values()[2], Scalar::Utf8("carol".into()));
21643    }
21644
21645    #[derive(Default)]
21646    struct DollarMarkerSqlConn {
21647        insert_sql: std::cell::RefCell<Vec<String>>,
21648        inserted_rows: std::cell::RefCell<Vec<Vec<Vec<Scalar>>>>,
21649    }
21650
21651    impl super::SqlConnection for DollarMarkerSqlConn {
21652        fn query(
21653            &self,
21654            _query: &str,
21655            _params: &[Scalar],
21656        ) -> Result<super::SqlQueryResult, IoError> {
21657            Err(IoError::Sql("mock connection does not read".to_owned()))
21658        }
21659
21660        fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
21661            Ok(())
21662        }
21663
21664        fn table_exists(&self, _table_name: &str) -> Result<bool, IoError> {
21665            Ok(false)
21666        }
21667
21668        fn insert_rows(&self, insert_sql: &str, rows: &[Vec<Scalar>]) -> Result<(), IoError> {
21669            self.insert_sql.borrow_mut().push(insert_sql.to_owned());
21670            self.inserted_rows.borrow_mut().push(rows.to_vec());
21671            Ok(())
21672        }
21673
21674        fn dtype_sql(&self, dtype: DType) -> &'static str {
21675            match dtype {
21676                DType::Int64
21677                | DType::Int64Nullable
21678                | DType::Bool
21679                | DType::BoolNullable
21680                | DType::Timedelta64
21681                | DType::Datetime64 => "BIGINT",
21682                DType::Float64 => "DOUBLE PRECISION",
21683                DType::Utf8
21684                | DType::Categorical
21685                | DType::Null
21686                | DType::Sparse
21687                | DType::Period
21688                | DType::Interval => "TEXT",
21689            }
21690        }
21691
21692        fn index_dtype_sql(&self, _index: &Index) -> &'static str {
21693            "TEXT"
21694        }
21695
21696        fn parameter_marker(&self, ordinal: usize) -> String {
21697            format!("${ordinal}")
21698        }
21699    }
21700
21701    #[test]
21702    fn sql_query_builders_quote_select_and_projection_identifiers() {
21703        let conn = DollarMarkerSqlConn::default();
21704        assert_eq!(
21705            super::sql_select_all_query(&conn, "portable_tbl").expect("select all query"),
21706            "SELECT * FROM \"portable_tbl\""
21707        );
21708        assert_eq!(
21709            super::sql_select_columns_query(&conn, "portable_tbl", &["names", "ints"])
21710                .expect("projection query"),
21711            "SELECT \"names\", \"ints\" FROM \"portable_tbl\""
21712        );
21713
21714        let err = super::sql_select_columns_query(&conn, "portable_tbl", &["bad column"])
21715            .expect_err("projection identifiers stay validated");
21716        assert!(matches!(err, IoError::Sql(msg) if msg.contains("invalid column name")));
21717    }
21718
21719    #[test]
21720    fn sql_query_builders_create_and_insert_use_backend_contracts() {
21721        let conn = DollarMarkerSqlConn::default();
21722        let column_defs = vec![
21723            super::sql_column_definition(&conn, "row id", "TEXT").expect("index column definition"),
21724            super::sql_column_definition(&conn, "value\"raw", "BIGINT")
21725                .expect("value column definition"),
21726        ];
21727
21728        assert_eq!(
21729            super::sql_create_table_query(&conn, "typed_tbl", &column_defs)
21730                .expect("create table query"),
21731            "CREATE TABLE IF NOT EXISTS \"typed_tbl\" (\"row id\" TEXT, \"value\"\"raw\" BIGINT)"
21732        );
21733
21734        let insert_columns = vec!["row id".to_owned(), "value\"raw".to_owned()];
21735        assert_eq!(
21736            super::sql_insert_rows_query(&conn, "typed_tbl", &insert_columns)
21737                .expect("insert row query"),
21738            "INSERT INTO \"typed_tbl\" (\"row id\", \"value\"\"raw\") VALUES ($1, $2)"
21739        );
21740    }
21741
21742    /// Verify that quote_identifier overrides on a custom backend ACTUALLY
21743    /// flow through the helper functions (br-frankenpandas-cx2x / fd90.12).
21744    /// A MySQL-style backend that returns backticks must produce backticked
21745    /// identifiers in CREATE / SELECT / INSERT statements without any
21746    /// further plumbing.
21747    #[test]
21748    fn sql_query_builders_use_backend_quote_identifier_override() {
21749        #[derive(Default)]
21750        struct BacktickSqlConn;
21751        impl super::SqlConnection for BacktickSqlConn {
21752            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<super::SqlQueryResult, IoError> {
21753                Ok(super::SqlQueryResult {
21754                    columns: vec![],
21755                    rows: vec![],
21756                })
21757            }
21758            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
21759                Ok(())
21760            }
21761            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
21762                Ok(false)
21763            }
21764            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
21765                Ok(())
21766            }
21767            fn dtype_sql(&self, _dtype: DType) -> &'static str {
21768                "TEXT"
21769            }
21770            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
21771                "TEXT"
21772            }
21773            fn quote_identifier(&self, ident: &str) -> Result<String, IoError> {
21774                if ident.contains('\0') {
21775                    return Err(IoError::Sql("invalid SQL identifier: NUL byte".to_owned()));
21776                }
21777                // MySQL-style backtick quoting; embedded backticks doubled.
21778                Ok(format!("`{}`", ident.replace('`', "``")))
21779            }
21780        }
21781
21782        let conn = BacktickSqlConn;
21783        // SELECT / projection helpers flow through quote_identifier.
21784        assert_eq!(
21785            super::sql_select_all_query(&conn, "users").expect("select all"),
21786            "SELECT * FROM `users`"
21787        );
21788        assert_eq!(
21789            super::sql_select_columns_query(&conn, "users", &["id", "name"]).expect("projection"),
21790            "SELECT `id`, `name` FROM `users`"
21791        );
21792        // CREATE / INSERT helpers flow through quote_identifier.
21793        let col_defs = vec![super::sql_column_definition(&conn, "id", "INTEGER").expect("col def")];
21794        assert_eq!(
21795            super::sql_create_table_query(&conn, "users", &col_defs).expect("create"),
21796            "CREATE TABLE IF NOT EXISTS `users` (`id` INTEGER)"
21797        );
21798        let insert_cols = vec!["id".to_owned(), "name".to_owned()];
21799        assert_eq!(
21800            super::sql_insert_rows_query(&conn, "users", &insert_cols).expect("insert"),
21801            "INSERT INTO `users` (`id`, `name`) VALUES (?, ?)"
21802        );
21803    }
21804
21805    #[test]
21806    fn sql_write_uses_backend_parameter_markers() {
21807        let frame = make_test_dataframe();
21808        let conn = DollarMarkerSqlConn::default();
21809
21810        write_sql(&frame, &conn, "portable_tbl", SqlIfExists::Fail)
21811            .expect("write through marker-aware mock backend");
21812
21813        let insert_sql = conn.insert_sql.borrow();
21814        assert_eq!(
21815            insert_sql.as_slice(),
21816            &["INSERT INTO \"portable_tbl\" (\"ints\", \"floats\", \"names\") VALUES ($1, $2, $3)"
21817                .to_owned()]
21818        );
21819        let inserted_rows = conn.inserted_rows.borrow();
21820        assert_eq!(inserted_rows[0].len(), frame.index().len());
21821        assert_eq!(inserted_rows[0][0][0], Scalar::Int64(10));
21822        assert_eq!(inserted_rows[0][2][2], Scalar::Utf8("carol".into()));
21823    }
21824
21825    #[cfg(feature = "sql-sqlite")]
21826    #[test]
21827    fn sql_write_with_options_includes_named_index_column() {
21828        let mut columns = BTreeMap::new();
21829        columns.insert(
21830            "vals".to_string(),
21831            Column::new(DType::Int64, vec![Scalar::Int64(10), Scalar::Int64(20)]).unwrap(),
21832        );
21833
21834        let frame = DataFrame::new_with_column_order(
21835            Index::new(vec![IndexLabel::Int64(101), IndexLabel::Int64(102)]).set_name("row_id"),
21836            columns,
21837            vec!["vals".to_string()],
21838        )
21839        .unwrap();
21840        let conn = make_sql_test_conn();
21841
21842        write_sql_with_options(
21843            &frame,
21844            &conn,
21845            "indexed_write_tbl",
21846            &SqlWriteOptions {
21847                if_exists: SqlIfExists::Fail,
21848                index: true,
21849                index_label: None,
21850                schema: None,
21851                dtype: None,
21852                method: SqlInsertMethod::Single,
21853                chunksize: None,
21854            },
21855        )
21856        .expect("write with named index");
21857
21858        let roundtrip = read_sql_table_with_index_col(&conn, "indexed_write_tbl", Some("row_id"))
21859            .expect("read with promoted index");
21860        assert_eq!(roundtrip.index().name(), Some("row_id"));
21861        assert_eq!(roundtrip.index().labels(), frame.index().labels());
21862        assert!(roundtrip.column("row_id").is_none());
21863        assert_eq!(
21864            roundtrip.column("vals").unwrap().values(),
21865            &[Scalar::Int64(10), Scalar::Int64(20)]
21866        );
21867    }
21868
21869    #[cfg(feature = "sql-sqlite")]
21870    #[test]
21871    fn sql_write_with_options_unnamed_index_defaults_to_index_column_name() {
21872        let frame = make_test_dataframe();
21873        let conn = make_sql_test_conn();
21874
21875        write_sql_with_options(
21876            &frame,
21877            &conn,
21878            "default_index_tbl",
21879            &SqlWriteOptions {
21880                if_exists: SqlIfExists::Fail,
21881                index: true,
21882                index_label: None,
21883                schema: None,
21884                dtype: None,
21885                method: SqlInsertMethod::Single,
21886                chunksize: None,
21887            },
21888        )
21889        .expect("write with unnamed index");
21890
21891        let raw = read_sql_table(&conn, "default_index_tbl").expect("read raw table");
21892        assert!(raw.column("index").is_some());
21893        assert_eq!(raw.column("index").unwrap().values()[0], Scalar::Int64(0));
21894        assert_eq!(raw.column("index").unwrap().values()[2], Scalar::Int64(2));
21895    }
21896
21897    #[cfg(feature = "sql-sqlite")]
21898    #[test]
21899    fn sql_write_with_options_index_label_overrides_name() {
21900        let mut columns = BTreeMap::new();
21901        columns.insert(
21902            "vals".to_string(),
21903            Column::new(DType::Int64, vec![Scalar::Int64(7), Scalar::Int64(8)]).unwrap(),
21904        );
21905
21906        let frame = DataFrame::new_with_column_order(
21907            Index::new(vec![IndexLabel::Int64(1), IndexLabel::Int64(2)]).set_name("row_id"),
21908            columns,
21909            vec!["vals".to_string()],
21910        )
21911        .unwrap();
21912        let conn = make_sql_test_conn();
21913
21914        write_sql_with_options(
21915            &frame,
21916            &conn,
21917            "override_index_tbl",
21918            &SqlWriteOptions {
21919                if_exists: SqlIfExists::Fail,
21920                index: true,
21921                index_label: Some("custom_id".to_string()),
21922                schema: None,
21923                dtype: None,
21924                method: SqlInsertMethod::Single,
21925                chunksize: None,
21926            },
21927        )
21928        .expect("write with custom index label");
21929
21930        let raw = read_sql_table(&conn, "override_index_tbl").expect("read raw table");
21931        assert!(raw.column("custom_id").is_some());
21932        assert!(raw.column("row_id").is_none());
21933        assert_eq!(
21934            raw.column("custom_id").unwrap().values()[0],
21935            Scalar::Int64(1)
21936        );
21937        assert_eq!(
21938            raw.column("custom_id").unwrap().values()[1],
21939            Scalar::Int64(2)
21940        );
21941    }
21942
21943    #[cfg(feature = "sql-sqlite")]
21944    #[test]
21945    fn sql_write_with_options_index_false_omits_index_column() {
21946        let mut columns = BTreeMap::new();
21947        columns.insert(
21948            "vals".to_string(),
21949            Column::new(DType::Int64, vec![Scalar::Int64(5), Scalar::Int64(6)]).unwrap(),
21950        );
21951
21952        let frame = DataFrame::new_with_column_order(
21953            Index::new(vec![IndexLabel::Int64(9), IndexLabel::Int64(10)]).set_name("row_id"),
21954            columns,
21955            vec!["vals".to_string()],
21956        )
21957        .unwrap();
21958        let conn = make_sql_test_conn();
21959
21960        write_sql_with_options(
21961            &frame,
21962            &conn,
21963            "no_index_write_tbl",
21964            &SqlWriteOptions {
21965                if_exists: SqlIfExists::Fail,
21966                index: false,
21967                index_label: Some("custom_id".to_string()),
21968                schema: None,
21969                dtype: None,
21970                method: SqlInsertMethod::Single,
21971                chunksize: None,
21972            },
21973        )
21974        .expect("write without index");
21975
21976        let raw = read_sql_table(&conn, "no_index_write_tbl").expect("read raw table");
21977        assert!(raw.column("row_id").is_none());
21978        assert!(raw.column("custom_id").is_none());
21979        let names: Vec<&str> = raw
21980            .column_names()
21981            .iter()
21982            .map(|name| name.as_str())
21983            .collect();
21984        assert_eq!(names, vec!["vals"]);
21985    }
21986
21987    #[cfg(feature = "sql-sqlite")]
21988    #[test]
21989    fn sql_read_with_query() {
21990        let frame = make_test_dataframe();
21991        let conn = make_sql_test_conn();
21992        write_sql(&frame, &conn, "data", SqlIfExists::Fail).unwrap();
21993
21994        let filtered = read_sql(&conn, "SELECT ints, names FROM data WHERE ints > 15").unwrap();
21995        assert_eq!(filtered.index().len(), 2); // rows with ints=20,30
21996        assert_eq!(
21997            filtered.column("ints").unwrap().values()[0],
21998            Scalar::Int64(20)
21999        );
22000        assert_eq!(
22001            filtered.column("names").unwrap().values()[1],
22002            Scalar::Utf8("carol".into())
22003        );
22004    }
22005
22006    #[cfg(feature = "sql-sqlite")]
22007    #[test]
22008    fn sql_read_query_alias_matches_read_sql_query_path() {
22009        let frame = make_test_dataframe();
22010        let conn = make_sql_test_conn();
22011        write_sql(&frame, &conn, "data", SqlIfExists::Fail).unwrap();
22012
22013        let queried = read_sql_query(
22014            &conn,
22015            "SELECT names, ints FROM data WHERE ints >= 20 ORDER BY ints",
22016        )
22017        .unwrap();
22018
22019        assert_eq!(queried.column_names(), vec!["names", "ints"]);
22020        assert_eq!(queried.index().len(), 2);
22021        assert_eq!(
22022            queried.column("names").unwrap().values(),
22023            &[
22024                Scalar::Utf8("bob".to_owned()),
22025                Scalar::Utf8("carol".to_owned())
22026            ]
22027        );
22028        assert_eq!(
22029            queried.column("ints").unwrap().values(),
22030            &[Scalar::Int64(20), Scalar::Int64(30)]
22031        );
22032    }
22033
22034    #[cfg(feature = "sql-sqlite")]
22035    #[test]
22036    fn sql_read_query_with_options_applies_params_and_parse_dates() {
22037        let conn = make_sql_test_conn();
22038        conn.execute_batch(
22039            "CREATE TABLE events (ts TEXT, value INTEGER);
22040             INSERT INTO events (ts, value) VALUES
22041                ('2024-01-15', 1),
22042                ('2024-02-01 05:06:07', 2),
22043                ('2024-03-03', 3);",
22044        )
22045        .expect("create events table");
22046
22047        let frame = read_sql_query_with_options(
22048            &conn,
22049            "SELECT ts, value FROM events WHERE value > ? ORDER BY value",
22050            &SqlReadOptions {
22051                params: Some(vec![Scalar::Int64(1)]),
22052                parse_dates: Some(vec!["ts".to_owned()]),
22053                coerce_float: false,
22054                dtype: None,
22055                schema: None,
22056                columns: None,
22057                index_col: None,
22058            },
22059        )
22060        .expect("read_sql_query with options");
22061
22062        assert_eq!(frame.column_names(), vec!["ts", "value"]);
22063        // parse_dates now yields typed Datetime64[ns] (br-frankenpandas-0ezw7).
22064        assert_eq!(
22065            frame.column("ts").unwrap().values(),
22066            &[
22067                Scalar::Datetime64(1_706_763_967_000_000_000),
22068                Scalar::Datetime64(1_709_424_000_000_000_000)
22069            ]
22070        );
22071        assert_eq!(
22072            frame.column("value").unwrap().values(),
22073            &[Scalar::Int64(2), Scalar::Int64(3)]
22074        );
22075    }
22076
22077    #[test]
22078    fn sql_read_query_with_options_and_index_col_uses_generic_connection() {
22079        use std::cell::RefCell;
22080
22081        struct RecordingSqlConn {
22082            seen_query: RefCell<Option<String>>,
22083            seen_params: RefCell<Vec<Scalar>>,
22084        }
22085
22086        impl super::SqlConnection for RecordingSqlConn {
22087            fn query(&self, query: &str, params: &[Scalar]) -> Result<SqlQueryResult, IoError> {
22088                *self.seen_query.borrow_mut() = Some(query.to_owned());
22089                *self.seen_params.borrow_mut() = params.to_vec();
22090                Ok(SqlQueryResult {
22091                    columns: vec![
22092                        "row_id".to_owned(),
22093                        "ts".to_owned(),
22094                        "amount".to_owned(),
22095                        "label".to_owned(),
22096                    ],
22097                    rows: vec![
22098                        vec![
22099                            Scalar::Int64(101),
22100                            Scalar::Utf8("2024-01-15".to_owned()),
22101                            Scalar::Utf8("$1.25".to_owned()),
22102                            Scalar::Utf8("alpha".to_owned()),
22103                        ],
22104                        vec![
22105                            Scalar::Int64(102),
22106                            Scalar::Utf8("2024-01-16".to_owned()),
22107                            Scalar::Utf8("2.50".to_owned()),
22108                            Scalar::Utf8("beta".to_owned()),
22109                        ],
22110                    ],
22111                })
22112            }
22113
22114            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
22115                Ok(())
22116            }
22117
22118            fn table_exists(&self, _table_name: &str) -> Result<bool, IoError> {
22119                Ok(false)
22120            }
22121
22122            fn insert_rows(&self, _insert_sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
22123                Ok(())
22124            }
22125
22126            fn dtype_sql(&self, _dtype: DType) -> &'static str {
22127                "TEXT"
22128            }
22129
22130            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
22131                "BIGINT"
22132            }
22133        }
22134
22135        let conn = RecordingSqlConn {
22136            seen_query: RefCell::new(None),
22137            seen_params: RefCell::new(Vec::new()),
22138        };
22139        let query = "SELECT row_id, ts, amount, label FROM events WHERE amount > ?";
22140        let frame = super::read_sql_query_with_options_and_index_col(
22141            &conn,
22142            query,
22143            &SqlReadOptions {
22144                params: Some(vec![Scalar::Float64(1.0)]),
22145                parse_dates: Some(vec!["ts".to_owned()]),
22146                coerce_float: true,
22147                dtype: None,
22148                schema: None,
22149                columns: None,
22150                index_col: Some("amount".to_owned()),
22151            },
22152            Some("row_id"),
22153        )
22154        .expect("generic read_sql query with options and index_col");
22155
22156        assert_eq!(conn.seen_query.borrow().as_deref(), Some(query));
22157        assert_eq!(
22158            conn.seen_params.borrow().as_slice(),
22159            &[Scalar::Float64(1.0)]
22160        );
22161        assert_eq!(frame.index().name(), Some("row_id"));
22162        assert_eq!(
22163            frame.index().labels(),
22164            &[IndexLabel::Int64(101), IndexLabel::Int64(102)]
22165        );
22166        assert_eq!(frame.column_names(), vec!["ts", "amount", "label"]);
22167        // parse_dates now yields typed Datetime64[ns] (br-frankenpandas-0ezw7).
22168        assert_eq!(
22169            frame.column("ts").unwrap().values(),
22170            &[
22171                Scalar::Datetime64(1_705_276_800_000_000_000),
22172                Scalar::Datetime64(1_705_363_200_000_000_000)
22173            ]
22174        );
22175        assert_eq!(
22176            frame.column("amount").unwrap().values(),
22177            &[Scalar::Float64(1.25), Scalar::Float64(2.5)]
22178        );
22179        assert_eq!(
22180            frame.column("label").unwrap().values(),
22181            &[
22182                Scalar::Utf8("alpha".to_owned()),
22183                Scalar::Utf8("beta".to_owned())
22184            ]
22185        );
22186    }
22187
22188    #[cfg(feature = "sql-sqlite")]
22189    #[test]
22190    fn sql_read_query_with_index_col_promotes_named_column() {
22191        let frame = make_test_dataframe();
22192        let conn = make_sql_test_conn();
22193        write_sql(&frame, &conn, "data", SqlIfExists::Fail).unwrap();
22194
22195        let indexed = read_sql_query_with_index_col(
22196            &conn,
22197            "SELECT names, ints FROM data ORDER BY ints",
22198            Some("names"),
22199        )
22200        .unwrap();
22201
22202        assert_eq!(
22203            indexed.index().labels(),
22204            &[
22205                IndexLabel::Utf8("alice".to_owned()),
22206                IndexLabel::Utf8("bob".to_owned()),
22207                IndexLabel::Utf8("carol".to_owned())
22208            ]
22209        );
22210        assert_eq!(indexed.index().name(), Some("names"));
22211        assert!(indexed.column("names").is_none());
22212        assert_eq!(
22213            indexed.column("ints").unwrap().values(),
22214            &[Scalar::Int64(10), Scalar::Int64(20), Scalar::Int64(30)]
22215        );
22216    }
22217
22218    #[cfg(feature = "sql-sqlite")]
22219    #[test]
22220    fn sql_read_query_chunks_alias_batches_rows() {
22221        let conn = make_sql_test_conn();
22222        conn.execute_batch(
22223            "CREATE TABLE query_chunked (id INTEGER, name TEXT);
22224             INSERT INTO query_chunked (id, name) VALUES
22225                (1, 'alpha'),
22226                (2, 'beta'),
22227                (3, 'gamma');",
22228        )
22229        .expect("create query_chunked table");
22230
22231        let chunks =
22232            read_sql_query_chunks(&conn, "SELECT id, name FROM query_chunked ORDER BY id", 2)
22233                .expect("query chunk iterator")
22234                .collect::<Result<Vec<_>, _>>()
22235                .expect("all chunks");
22236
22237        assert_eq!(chunks.len(), 2);
22238        assert_eq!(chunks[0].column_names(), vec!["id", "name"]);
22239        assert_eq!(
22240            chunks[0].column("id").unwrap().values(),
22241            &[Scalar::Int64(1), Scalar::Int64(2)]
22242        );
22243        assert_eq!(
22244            chunks[1].column("name").unwrap().values(),
22245            &[Scalar::Utf8("gamma".to_owned())]
22246        );
22247    }
22248
22249    #[cfg(feature = "sql-sqlite")]
22250    #[test]
22251    fn sql_read_query_chunks_with_options_applies_params_parse_dates_and_coerce_float() {
22252        let conn = make_sql_test_conn();
22253        conn.execute_batch(
22254            "CREATE TABLE query_events (ts TEXT, amount TEXT, keep INTEGER);
22255             INSERT INTO query_events (ts, amount, keep) VALUES
22256                ('2024-01-15', '12.50', 0),
22257                ('2024-02-01 05:06:07', '$1,234.50', 1),
22258                ('2024-03-03', '-3.25', 1);",
22259        )
22260        .expect("create query_events table");
22261
22262        let chunks = read_sql_query_chunks_with_options(
22263            &conn,
22264            "SELECT ts, amount FROM query_events WHERE keep = ? ORDER BY ts",
22265            &SqlReadOptions {
22266                params: Some(vec![Scalar::Int64(1)]),
22267                parse_dates: Some(vec!["ts".to_owned()]),
22268                coerce_float: true,
22269                dtype: None,
22270                schema: None,
22271                columns: None,
22272                index_col: None,
22273            },
22274            1,
22275        )
22276        .expect("query chunk iterator")
22277        .collect::<Result<Vec<_>, _>>()
22278        .expect("all chunks");
22279
22280        assert_eq!(chunks.len(), 2);
22281        // parse_dates now yields typed Datetime64[ns] (br-frankenpandas-0ezw7).
22282        assert_eq!(
22283            chunks[0].column("ts").unwrap().values(),
22284            &[Scalar::Datetime64(1_706_763_967_000_000_000)]
22285        );
22286        assert_eq!(
22287            chunks[0].column("amount").unwrap().values(),
22288            &[Scalar::Float64(1234.5)]
22289        );
22290        assert_eq!(
22291            chunks[1].column("ts").unwrap().values(),
22292            &[Scalar::Datetime64(1_709_424_000_000_000_000)]
22293        );
22294        assert_eq!(
22295            chunks[1].column("amount").unwrap().values(),
22296            &[Scalar::Float64(-3.25)]
22297        );
22298    }
22299
22300    #[test]
22301    fn sql_read_chunks_uses_paged_queries_when_backend_opts_in() {
22302        use std::cell::RefCell;
22303
22304        struct PagedChunksConn {
22305            queries: RefCell<Vec<(String, Vec<Scalar>)>>,
22306            rows: Vec<Vec<Scalar>>,
22307        }
22308
22309        impl PagedChunksConn {
22310            fn page_bounds(params: &[Scalar]) -> (usize, usize) {
22311                let [
22312                    Scalar::Int64(1),
22313                    Scalar::Int64(limit),
22314                    Scalar::Int64(offset),
22315                ] = params
22316                else {
22317                    assert_eq!(
22318                        params,
22319                        &[Scalar::Int64(1), Scalar::Int64(0), Scalar::Int64(0),],
22320                        "expected original param plus LIMIT/OFFSET params"
22321                    );
22322                    return (0, 0);
22323                };
22324                (
22325                    usize::try_from(*limit).expect("non-negative limit"),
22326                    usize::try_from(*offset).expect("non-negative offset"),
22327                )
22328            }
22329        }
22330
22331        impl super::SqlConnection for PagedChunksConn {
22332            fn query(&self, query: &str, params: &[Scalar]) -> Result<SqlQueryResult, IoError> {
22333                self.queries
22334                    .borrow_mut()
22335                    .push((query.to_owned(), params.to_vec()));
22336                assert!(
22337                    query.contains("frankenpandas_sql_chunk_source")
22338                        && query.contains("LIMIT ? OFFSET ?"),
22339                    "paged chunk path should wrap the caller query with LIMIT/OFFSET, got {query}"
22340                );
22341
22342                let (limit, offset) = Self::page_bounds(params);
22343                let rows = self.rows.iter().skip(offset).take(limit).cloned().collect();
22344                Ok(SqlQueryResult {
22345                    columns: vec!["id".to_owned(), "name".to_owned()],
22346                    rows,
22347                })
22348            }
22349
22350            fn supports_paged_sql_chunks(&self) -> bool {
22351                true
22352            }
22353
22354            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
22355                Ok(())
22356            }
22357
22358            fn table_exists(&self, _table_name: &str) -> Result<bool, IoError> {
22359                Ok(false)
22360            }
22361
22362            fn insert_rows(&self, _insert_sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
22363                Ok(())
22364            }
22365
22366            fn dtype_sql(&self, _dtype: DType) -> &'static str {
22367                "TEXT"
22368            }
22369
22370            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
22371                "TEXT"
22372            }
22373        }
22374
22375        let conn = PagedChunksConn {
22376            queries: RefCell::new(Vec::new()),
22377            rows: vec![
22378                vec![Scalar::Int64(1), Scalar::Utf8("a".to_owned())],
22379                vec![Scalar::Int64(2), Scalar::Utf8("b".to_owned())],
22380                vec![Scalar::Int64(3), Scalar::Utf8("c".to_owned())],
22381                vec![Scalar::Int64(4), Scalar::Utf8("d".to_owned())],
22382                vec![Scalar::Int64(5), Scalar::Utf8("e".to_owned())],
22383            ],
22384        };
22385
22386        let chunks = read_sql_chunks_with_options(
22387            &conn,
22388            "SELECT id, name FROM paged_source WHERE keep = ? ORDER BY id;",
22389            &SqlReadOptions {
22390                params: Some(vec![Scalar::Int64(1)]),
22391                ..SqlReadOptions::default()
22392            },
22393            2,
22394        )
22395        .expect("paged chunk iterator")
22396        .collect::<Result<Vec<_>, _>>()
22397        .expect("all chunks");
22398
22399        assert_eq!(chunks.len(), 3);
22400        assert_eq!(
22401            chunks[0].column("id").unwrap().values(),
22402            &[Scalar::Int64(1), Scalar::Int64(2)]
22403        );
22404        assert_eq!(
22405            chunks[1].column("id").unwrap().values(),
22406            &[Scalar::Int64(3), Scalar::Int64(4)]
22407        );
22408        assert_eq!(
22409            chunks[2].column("name").unwrap().values(),
22410            &[Scalar::Utf8("e".to_owned())]
22411        );
22412
22413        let queries = conn.queries.borrow();
22414        let expected_params = vec![
22415            vec![Scalar::Int64(1), Scalar::Int64(0), Scalar::Int64(0)],
22416            vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(0)],
22417            vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(2)],
22418            vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(4)],
22419        ];
22420        assert_eq!(
22421            queries
22422                .iter()
22423                .map(|(_, params)| params.clone())
22424                .collect::<Vec<_>>(),
22425            expected_params
22426        );
22427    }
22428
22429    #[cfg(feature = "sql-sqlite")]
22430    #[test]
22431    fn sql_read_query_chunks_with_options_and_index_col_applies_options_before_indexing() {
22432        let conn = make_sql_test_conn();
22433        conn.execute_batch(
22434            "CREATE TABLE query_index_events (ts TEXT, amount TEXT, keep INTEGER);
22435             INSERT INTO query_index_events (ts, amount, keep) VALUES
22436                ('2024-01-15', '12.50', 0),
22437                ('2024-02-01 05:06:07', '$1,234.50', 1),
22438                ('2024-03-03', '-3.25', 1);",
22439        )
22440        .expect("create query_index_events table");
22441
22442        let chunks = read_sql_query_chunks_with_options_and_index_col(
22443            &conn,
22444            "SELECT ts, amount FROM query_index_events WHERE keep = ? ORDER BY ts",
22445            &SqlReadOptions {
22446                params: Some(vec![Scalar::Int64(1)]),
22447                parse_dates: Some(vec!["ts".to_owned()]),
22448                coerce_float: true,
22449                dtype: None,
22450                schema: None,
22451                columns: None,
22452                index_col: None,
22453            },
22454            Some("ts"),
22455            1,
22456        )
22457        .expect("indexed query chunk iterator")
22458        .collect::<Result<Vec<_>, _>>()
22459        .expect("all chunks");
22460
22461        assert_eq!(chunks.len(), 2);
22462        assert_eq!(chunks[0].index().name(), Some("ts"));
22463        // parse_dates column promoted to index → DatetimeIndex (br-frankenpandas-0ezw7).
22464        assert_eq!(
22465            chunks[0].index().labels(),
22466            &[IndexLabel::Datetime64(1_706_763_967_000_000_000)]
22467        );
22468        assert!(chunks[0].column("ts").is_none());
22469        assert_eq!(
22470            chunks[0].column("amount").unwrap().values(),
22471            &[Scalar::Float64(1234.5)]
22472        );
22473        assert_eq!(
22474            chunks[1].index().labels(),
22475            &[IndexLabel::Datetime64(1_709_424_000_000_000_000)]
22476        );
22477        assert_eq!(
22478            chunks[1].column("amount").unwrap().values(),
22479            &[Scalar::Float64(-3.25)]
22480        );
22481    }
22482
22483    #[cfg(feature = "sql-sqlite")]
22484    #[test]
22485    fn sql_read_chunks_with_options_and_index_col_none_keeps_options_and_range_index() {
22486        let conn = make_sql_test_conn();
22487        conn.execute_batch(
22488            "CREATE TABLE query_options_no_index (id INTEGER, amount TEXT);
22489             INSERT INTO query_options_no_index (id, amount) VALUES
22490                (1, '$10.50'),
22491                (2, '11.25');",
22492        )
22493        .expect("create query_options_no_index table");
22494
22495        let chunks = read_sql_chunks_with_options_and_index_col(
22496            &conn,
22497            "SELECT id, amount FROM query_options_no_index ORDER BY id",
22498            &SqlReadOptions {
22499                params: None,
22500                parse_dates: None,
22501                coerce_float: true,
22502                dtype: None,
22503                schema: None,
22504                columns: None,
22505                index_col: None,
22506            },
22507            None,
22508            1,
22509        )
22510        .expect("query chunk iterator")
22511        .collect::<Result<Vec<_>, _>>()
22512        .expect("all chunks");
22513
22514        assert_eq!(chunks.len(), 2);
22515        assert_eq!(chunks[0].index().labels(), &[IndexLabel::Int64(0)]);
22516        assert_eq!(chunks[1].index().labels(), &[IndexLabel::Int64(0)]);
22517        assert_eq!(
22518            chunks[0].column("amount").unwrap().values(),
22519            &[Scalar::Float64(10.5)]
22520        );
22521        assert_eq!(
22522            chunks[1].column("amount").unwrap().values(),
22523            &[Scalar::Float64(11.25)]
22524        );
22525    }
22526
22527    #[cfg(feature = "sql-sqlite")]
22528    #[test]
22529    fn sql_read_chunks_with_options_and_index_col_uses_options_index_when_explicit_none() {
22530        let conn = make_sql_test_conn();
22531        conn.execute_batch(
22532            "CREATE TABLE query_options_struct_index (id INTEGER, amount TEXT);
22533             INSERT INTO query_options_struct_index (id, amount) VALUES
22534                (10, '$10.50'),
22535                (20, '11.25');",
22536        )
22537        .expect("create query_options_struct_index table");
22538
22539        let chunks = read_sql_chunks_with_options_and_index_col(
22540            &conn,
22541            "SELECT id, amount FROM query_options_struct_index ORDER BY id",
22542            &SqlReadOptions {
22543                params: None,
22544                parse_dates: None,
22545                coerce_float: true,
22546                dtype: None,
22547                schema: None,
22548                columns: None,
22549                index_col: Some("id".to_owned()),
22550            },
22551            None,
22552            1,
22553        )
22554        .expect("query chunk iterator")
22555        .collect::<Result<Vec<_>, _>>()
22556        .expect("all chunks");
22557
22558        assert_eq!(chunks.len(), 2);
22559        assert_eq!(chunks[0].index().name(), Some("id"));
22560        assert_eq!(chunks[0].index().labels(), &[IndexLabel::Int64(10)]);
22561        assert!(chunks[0].column("id").is_none());
22562        assert_eq!(chunks[1].index().labels(), &[IndexLabel::Int64(20)]);
22563        assert_eq!(
22564            chunks[1].column("amount").unwrap().values(),
22565            &[Scalar::Float64(11.25)]
22566        );
22567    }
22568
22569    #[cfg(feature = "sql-sqlite")]
22570    #[test]
22571    fn sql_read_query_chunks_with_options_and_index_col_missing_column_errors() {
22572        let conn = make_sql_test_conn();
22573        conn.execute_batch(
22574            "CREATE TABLE query_options_missing_index (id INTEGER, amount TEXT);
22575             INSERT INTO query_options_missing_index (id, amount) VALUES (1, '10.5');",
22576        )
22577        .expect("create query_options_missing_index table");
22578
22579        let err = read_sql_query_chunks_with_options_and_index_col(
22580            &conn,
22581            "SELECT id, amount FROM query_options_missing_index",
22582            &SqlReadOptions {
22583                params: None,
22584                parse_dates: None,
22585                coerce_float: true,
22586                dtype: None,
22587                schema: None,
22588                columns: None,
22589                index_col: None,
22590            },
22591            Some("missing"),
22592            1,
22593        )
22594        .expect_err("missing index_col should error during iterator construction");
22595
22596        assert!(matches!(err, IoError::Sql(msg) if msg.contains("index_col")));
22597    }
22598
22599    #[cfg(feature = "sql-sqlite")]
22600    #[test]
22601    fn sql_read_query_with_options_and_index_col_applies_options_before_indexing() {
22602        let conn = make_sql_test_conn();
22603        conn.execute_batch(
22604            "CREATE TABLE query_frame_index_events (ts TEXT, amount TEXT, keep INTEGER);
22605             INSERT INTO query_frame_index_events (ts, amount, keep) VALUES
22606                ('2024-01-15', '12.50', 0),
22607                ('2024-02-01 05:06:07', '$1,234.50', 1),
22608                ('2024-03-03', '-3.25', 1);",
22609        )
22610        .expect("create query_frame_index_events table");
22611
22612        let frame = read_sql_query_with_options_and_index_col(
22613            &conn,
22614            "SELECT ts, amount FROM query_frame_index_events WHERE keep = ? ORDER BY ts",
22615            &SqlReadOptions {
22616                params: Some(vec![Scalar::Int64(1)]),
22617                parse_dates: Some(vec!["ts".to_owned()]),
22618                coerce_float: true,
22619                dtype: None,
22620                schema: None,
22621                columns: None,
22622                index_col: None,
22623            },
22624            Some("ts"),
22625        )
22626        .expect("read indexed query frame");
22627
22628        assert_eq!(frame.index().name(), Some("ts"));
22629        // parse_dates column promoted to index → DatetimeIndex (br-frankenpandas-0ezw7).
22630        assert_eq!(
22631            frame.index().labels(),
22632            &[
22633                IndexLabel::Datetime64(1_706_763_967_000_000_000),
22634                IndexLabel::Datetime64(1_709_424_000_000_000_000)
22635            ]
22636        );
22637        assert!(frame.column("ts").is_none());
22638        assert_eq!(
22639            frame.column("amount").unwrap().values(),
22640            &[Scalar::Float64(1234.5), Scalar::Float64(-3.25)]
22641        );
22642    }
22643
22644    #[cfg(feature = "sql-sqlite")]
22645    #[test]
22646    fn sql_read_query_with_options_and_index_col_explicit_arg_wins() {
22647        let conn = make_sql_test_conn();
22648        conn.execute_batch(
22649            "CREATE TABLE query_frame_index_override (a INTEGER, b INTEGER, val TEXT);
22650             INSERT INTO query_frame_index_override (a, b, val) VALUES
22651                (1, 100, 'x'),
22652                (2, 200, 'y');",
22653        )
22654        .expect("create query_frame_index_override table");
22655
22656        let frame = read_sql_query_with_options_and_index_col(
22657            &conn,
22658            "SELECT a, b, val FROM query_frame_index_override ORDER BY a",
22659            &SqlReadOptions {
22660                index_col: Some("a".to_owned()),
22661                ..SqlReadOptions::default()
22662            },
22663            Some("b"),
22664        )
22665        .expect("read indexed query frame with override");
22666
22667        assert_eq!(frame.column_names(), vec!["a", "val"]);
22668        assert_eq!(
22669            frame.index().labels(),
22670            &[IndexLabel::Int64(100), IndexLabel::Int64(200)]
22671        );
22672    }
22673
22674    #[cfg(feature = "sql-sqlite")]
22675    #[test]
22676    fn sql_read_query_chunks_rejects_zero_chunksize() {
22677        let conn = make_sql_test_conn();
22678
22679        let err = read_sql_query_chunks(&conn, "SELECT 1", 0)
22680            .expect_err("zero query chunksize should be rejected");
22681
22682        assert!(matches!(err, IoError::Sql(msg) if msg.contains("chunksize")));
22683    }
22684
22685    #[cfg(feature = "sql-sqlite")]
22686    #[test]
22687    fn sql_read_query_chunks_with_index_col_promotes_each_chunk_index() {
22688        let conn = make_sql_test_conn();
22689        conn.execute_batch(
22690            "CREATE TABLE query_index_chunked (id INTEGER, label TEXT, value INTEGER);
22691             INSERT INTO query_index_chunked (id, label, value) VALUES
22692                (1, 'alpha', 10),
22693                (2, 'beta', 20),
22694                (3, 'gamma', 30);",
22695        )
22696        .expect("create query_index_chunked table");
22697
22698        let chunks = read_sql_query_chunks_with_index_col(
22699            &conn,
22700            "SELECT id, label, value FROM query_index_chunked ORDER BY id",
22701            Some("label"),
22702            2,
22703        )
22704        .expect("query indexed chunk iterator")
22705        .collect::<Result<Vec<_>, _>>()
22706        .expect("all chunks");
22707
22708        assert_eq!(chunks.len(), 2);
22709        assert_eq!(chunks[0].index().name(), Some("label"));
22710        assert_eq!(
22711            chunks[0].index().labels(),
22712            &[
22713                IndexLabel::Utf8("alpha".to_owned()),
22714                IndexLabel::Utf8("beta".to_owned())
22715            ]
22716        );
22717        assert!(chunks[0].column("label").is_none());
22718        assert_eq!(
22719            chunks[1].index().labels(),
22720            &[IndexLabel::Utf8("gamma".to_owned())]
22721        );
22722        assert_eq!(
22723            chunks[1].column("value").unwrap().values(),
22724            &[Scalar::Int64(30)]
22725        );
22726    }
22727
22728    #[cfg(feature = "sql-sqlite")]
22729    #[test]
22730    fn sql_read_chunks_with_index_col_none_keeps_fresh_chunk_range_indexes() {
22731        let conn = make_sql_test_conn();
22732        conn.execute_batch(
22733            "CREATE TABLE query_no_index_chunked (id INTEGER, label TEXT);
22734             INSERT INTO query_no_index_chunked (id, label) VALUES
22735                (1, 'alpha'),
22736                (2, 'beta');",
22737        )
22738        .expect("create query_no_index_chunked table");
22739
22740        let chunks = read_sql_chunks_with_index_col(
22741            &conn,
22742            "SELECT id, label FROM query_no_index_chunked ORDER BY id",
22743            None,
22744            1,
22745        )
22746        .expect("query chunk iterator")
22747        .collect::<Result<Vec<_>, _>>()
22748        .expect("all chunks");
22749
22750        assert_eq!(chunks.len(), 2);
22751        assert_eq!(chunks[0].index().labels(), &[IndexLabel::Int64(0)]);
22752        assert_eq!(chunks[1].index().labels(), &[IndexLabel::Int64(0)]);
22753        assert_eq!(chunks[1].column_names(), vec!["id", "label"]);
22754    }
22755
22756    #[cfg(feature = "sql-sqlite")]
22757    #[test]
22758    fn sql_read_query_chunks_with_index_col_missing_column_errors() {
22759        let conn = make_sql_test_conn();
22760        conn.execute_batch(
22761            "CREATE TABLE query_missing_index_chunked (id INTEGER, value INTEGER);
22762             INSERT INTO query_missing_index_chunked (id, value) VALUES (1, 10);",
22763        )
22764        .expect("create query_missing_index_chunked table");
22765
22766        let err = read_sql_query_chunks_with_index_col(
22767            &conn,
22768            "SELECT id, value FROM query_missing_index_chunked",
22769            Some("missing"),
22770            1,
22771        )
22772        .expect_err("missing index_col should error during iterator construction");
22773
22774        assert!(matches!(err, IoError::Sql(msg) if msg.contains("index_col")));
22775    }
22776
22777    #[cfg(feature = "sql-sqlite")]
22778    #[test]
22779    fn sql_read_table_chunks_batches_rows() {
22780        let conn = make_sql_test_conn();
22781        conn.execute_batch(
22782            "CREATE TABLE table_chunked (id INTEGER, name TEXT);
22783             INSERT INTO table_chunked (id, name) VALUES
22784                (1, 'alpha'),
22785                (2, 'beta'),
22786                (3, 'gamma'),
22787                (4, 'delta');",
22788        )
22789        .expect("create table_chunked table");
22790
22791        let chunks = read_sql_table_chunks(&conn, "table_chunked", 3)
22792            .expect("table chunk iterator")
22793            .collect::<Result<Vec<_>, _>>()
22794            .expect("all chunks");
22795
22796        assert_eq!(chunks.len(), 2);
22797        assert_eq!(chunks[0].column_names(), vec!["id", "name"]);
22798        assert_eq!(
22799            chunks[0].column("id").unwrap().values(),
22800            &[Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)]
22801        );
22802        assert_eq!(
22803            chunks[1].column("name").unwrap().values(),
22804            &[Scalar::Utf8("delta".to_owned())]
22805        );
22806    }
22807
22808    #[cfg(feature = "sql-sqlite")]
22809    #[test]
22810    fn sql_read_table_chunks_rejects_zero_chunksize() {
22811        let conn = make_sql_test_conn();
22812        conn.execute_batch("CREATE TABLE zero_chunked (id INTEGER);")
22813            .expect("create zero_chunked table");
22814
22815        let err = read_sql_table_chunks(&conn, "zero_chunked", 0)
22816            .expect_err("zero table chunksize should be rejected");
22817
22818        assert!(matches!(err, IoError::Sql(msg) if msg.contains("chunksize")));
22819    }
22820
22821    #[cfg(feature = "sql-sqlite")]
22822    #[test]
22823    fn sql_read_table_chunks_rejects_invalid_table_name() {
22824        let conn = make_sql_test_conn();
22825
22826        let err = read_sql_table_chunks(&conn, "bad table", 1)
22827            .expect_err("invalid table name should be rejected");
22828
22829        assert!(matches!(err, IoError::Sql(msg) if msg.contains("invalid table name")));
22830    }
22831
22832    #[cfg(feature = "sql-sqlite")]
22833    #[test]
22834    fn sql_read_table_chunks_with_index_col_promotes_each_chunk_index() {
22835        let conn = make_sql_test_conn();
22836        conn.execute_batch(
22837            "CREATE TABLE table_index_chunked (id INTEGER, name TEXT, score INTEGER);
22838             INSERT INTO table_index_chunked (id, name, score) VALUES
22839                (10, 'alpha', 100),
22840                (20, 'beta', 200),
22841                (30, 'gamma', 300);",
22842        )
22843        .expect("create table_index_chunked table");
22844
22845        let chunks =
22846            read_sql_table_chunks_with_index_col(&conn, "table_index_chunked", Some("id"), 2)
22847                .expect("table indexed chunk iterator")
22848                .collect::<Result<Vec<_>, _>>()
22849                .expect("all chunks");
22850
22851        assert_eq!(chunks.len(), 2);
22852        assert_eq!(chunks[0].index().name(), Some("id"));
22853        assert_eq!(
22854            chunks[0].index().labels(),
22855            &[IndexLabel::Int64(10), IndexLabel::Int64(20)]
22856        );
22857        assert!(chunks[0].column("id").is_none());
22858        assert_eq!(
22859            chunks[1].column("score").unwrap().values(),
22860            &[Scalar::Int64(300)]
22861        );
22862    }
22863
22864    #[cfg(feature = "sql-sqlite")]
22865    #[test]
22866    fn sql_read_table_with_options_applies_parse_dates_and_coerce_float() {
22867        let conn = make_sql_test_conn();
22868        conn.execute_batch(
22869            "CREATE TABLE table_options (ts TEXT, amount TEXT, label TEXT);
22870             INSERT INTO table_options (ts, amount, label) VALUES
22871                ('2024-01-15', '$12.50', 'a'),
22872                ('2024-02-01 05:06:07', '1,234.50', 'b');",
22873        )
22874        .expect("create table_options table");
22875
22876        let frame = read_sql_table_with_options(
22877            &conn,
22878            "table_options",
22879            &SqlReadOptions {
22880                params: None,
22881                parse_dates: Some(vec!["ts".to_owned()]),
22882                coerce_float: true,
22883                dtype: None,
22884                schema: None,
22885                columns: None,
22886                index_col: None,
22887            },
22888        )
22889        .expect("read table with options");
22890
22891        // parse_dates now yields typed Datetime64[ns] (br-frankenpandas-0ezw7).
22892        assert_eq!(
22893            frame.column("ts").unwrap().values(),
22894            &[
22895                Scalar::Datetime64(1_705_276_800_000_000_000),
22896                Scalar::Datetime64(1_706_763_967_000_000_000)
22897            ]
22898        );
22899        assert_eq!(
22900            frame.column("amount").unwrap().values(),
22901            &[Scalar::Float64(12.5), Scalar::Float64(1234.5)]
22902        );
22903        assert_eq!(
22904            frame.column("label").unwrap().values(),
22905            &[Scalar::Utf8("a".to_owned()), Scalar::Utf8("b".to_owned())]
22906        );
22907    }
22908
22909    #[cfg(feature = "sql-sqlite")]
22910    #[test]
22911    fn sql_read_table_chunks_with_options_applies_options_before_chunking() {
22912        let conn = make_sql_test_conn();
22913        conn.execute_batch(
22914            "CREATE TABLE table_options_chunked (ts TEXT, amount TEXT);
22915             INSERT INTO table_options_chunked (ts, amount) VALUES
22916                ('2024-03-01', '$10.00'),
22917                ('2024-03-02', '$20.50'),
22918                ('2024-03-03', '-3.25');",
22919        )
22920        .expect("create table_options_chunked table");
22921
22922        let chunks = read_sql_table_chunks_with_options(
22923            &conn,
22924            "table_options_chunked",
22925            &SqlReadOptions {
22926                params: None,
22927                parse_dates: Some(vec!["ts".to_owned()]),
22928                coerce_float: true,
22929                dtype: None,
22930                schema: None,
22931                columns: None,
22932                index_col: None,
22933            },
22934            2,
22935        )
22936        .expect("table option chunk iterator")
22937        .collect::<Result<Vec<_>, _>>()
22938        .expect("all chunks");
22939
22940        assert_eq!(chunks.len(), 2);
22941        // parse_dates now yields typed Datetime64[ns] (br-frankenpandas-0ezw7).
22942        assert_eq!(
22943            chunks[0].column("ts").unwrap().values(),
22944            &[
22945                Scalar::Datetime64(1_709_251_200_000_000_000),
22946                Scalar::Datetime64(1_709_337_600_000_000_000)
22947            ]
22948        );
22949        assert_eq!(
22950            chunks[0].column("amount").unwrap().values(),
22951            &[Scalar::Float64(10.0), Scalar::Float64(20.5)]
22952        );
22953        assert_eq!(
22954            chunks[1].column("amount").unwrap().values(),
22955            &[Scalar::Float64(-3.25)]
22956        );
22957    }
22958
22959    #[cfg(feature = "sql-sqlite")]
22960    #[test]
22961    fn sql_read_table_chunks_with_options_validates_chunksize_and_table_name() {
22962        let conn = make_sql_test_conn();
22963        conn.execute_batch(
22964            "CREATE TABLE table_options_errors (ts TEXT);
22965             INSERT INTO table_options_errors (ts) VALUES ('2024-01-01');",
22966        )
22967        .expect("create table_options_errors table");
22968
22969        let zero = read_sql_table_chunks_with_options(
22970            &conn,
22971            "table_options_errors",
22972            &SqlReadOptions::default(),
22973            0,
22974        )
22975        .expect_err("zero chunksize should be rejected");
22976        assert!(matches!(zero, IoError::Sql(msg) if msg.contains("chunksize")));
22977
22978        let invalid = read_sql_table_with_options(
22979            &conn,
22980            "bad table",
22981            &SqlReadOptions {
22982                parse_dates: Some(vec!["ts".to_owned()]),
22983                ..SqlReadOptions::default()
22984            },
22985        )
22986        .expect_err("invalid table name should be rejected");
22987        assert!(matches!(invalid, IoError::Sql(msg) if msg.contains("invalid table name")));
22988    }
22989
22990    // br-frankenpandas-i8kja: read_sql_table_chunks_with_options previously
22991    // accepted SqlReadOptions { index_col: Some(...) } and silently dropped
22992    // the index_col while the full-frame sibling honored it. Surface the
22993    // mismatch with a typed error so callers route to the
22994    // `_and_index_col` variant. The plain entrypoint stays
22995    // `Result<SqlChunkIterator, _>` for backwards compatibility — the
22996    // indexed surface is what carries promotion logic.
22997    #[cfg(feature = "sql-sqlite")]
22998    #[test]
22999    fn read_sql_table_chunks_with_options_rejects_options_index_col() {
23000        let conn = make_sql_test_conn();
23001        super::SqlConnection::execute_batch(
23002            &conn,
23003            "CREATE TABLE i8kja_table_chunks_reject (id INTEGER, val TEXT);",
23004        )
23005        .unwrap();
23006        super::SqlConnection::execute_batch(
23007            &conn,
23008            "INSERT INTO i8kja_table_chunks_reject VALUES (1, 'a'), (2, 'b');",
23009        )
23010        .unwrap();
23011
23012        let err = read_sql_table_chunks_with_options(
23013            &conn,
23014            "i8kja_table_chunks_reject",
23015            &SqlReadOptions {
23016                index_col: Some("id".to_owned()),
23017                ..Default::default()
23018            },
23019            2,
23020        )
23021        .expect_err("options.index_col on non-indexed entrypoint must be rejected");
23022        assert!(
23023            matches!(&err, IoError::Sql(msg) if msg.contains("index_col") && msg.contains("read_sql_table_chunks_with_options_and_index_col")),
23024            "expected typed error pointing to the _and_index_col variant, got: {err:?}"
23025        );
23026
23027        // Sanity: same options struct on the indexed sibling honors index_col.
23028        let chunks: Vec<DataFrame> = read_sql_table_chunks_with_options_and_index_col(
23029            &conn,
23030            "i8kja_table_chunks_reject",
23031            &SqlReadOptions {
23032                index_col: Some("id".to_owned()),
23033                ..Default::default()
23034            },
23035            None,
23036            2,
23037        )
23038        .expect("indexed sibling honors options.index_col")
23039        .collect::<Result<Vec<_>, _>>()
23040        .expect("all chunks");
23041        assert_eq!(chunks.len(), 1);
23042        assert!(chunks[0].column("id").is_none());
23043        assert_eq!(
23044            chunks[0].index().labels(),
23045            &[IndexLabel::Int64(1), IndexLabel::Int64(2)]
23046        );
23047        assert_eq!(
23048            chunks[0].column("val").unwrap().values(),
23049            &[Scalar::Utf8("a".into()), Scalar::Utf8("b".into())]
23050        );
23051    }
23052
23053    #[cfg(feature = "sql-sqlite")]
23054    #[test]
23055    fn read_sql_chunks_with_options_rejects_options_index_col() {
23056        let conn = make_sql_test_conn();
23057        super::SqlConnection::execute_batch(
23058            &conn,
23059            "CREATE TABLE i8kja_query_chunks_reject (id INTEGER, val TEXT);",
23060        )
23061        .unwrap();
23062        super::SqlConnection::execute_batch(
23063            &conn,
23064            "INSERT INTO i8kja_query_chunks_reject VALUES (1, 'a');",
23065        )
23066        .unwrap();
23067
23068        let err = read_sql_chunks_with_options(
23069            &conn,
23070            "SELECT * FROM i8kja_query_chunks_reject",
23071            &SqlReadOptions {
23072                index_col: Some("id".to_owned()),
23073                ..Default::default()
23074            },
23075            2,
23076        )
23077        .expect_err("options.index_col on non-indexed entrypoint must be rejected");
23078        assert!(
23079            matches!(&err, IoError::Sql(msg) if msg.contains("index_col") && msg.contains("read_sql_chunks_with_options_and_index_col")),
23080            "expected typed error pointing to the _and_index_col variant, got: {err:?}"
23081        );
23082
23083        let err = read_sql_query_chunks_with_options(
23084            &conn,
23085            "SELECT * FROM i8kja_query_chunks_reject",
23086            &SqlReadOptions {
23087                index_col: Some("id".to_owned()),
23088                ..Default::default()
23089            },
23090            2,
23091        )
23092        .expect_err("query delegator should propagate the rejection");
23093        assert!(
23094            matches!(&err, IoError::Sql(msg) if msg.contains("index_col") && msg.contains("read_sql_query_chunks_with_options_and_index_col")),
23095            "expected query-specific _and_index_col suggestion, got: {err:?}"
23096        );
23097    }
23098
23099    // br-frankenpandas-t1777: query readers can't apply options.columns
23100    // (caller writes the SELECT, projection is fixed). Silently ignoring
23101    // diverged from the table-reader sibling. All 7 query-reader entry
23102    // points (3 foundations + 4 delegators) must reject options.columns
23103    // with a typed error pointing to the appropriate table reader.
23104    #[cfg(feature = "sql-sqlite")]
23105    #[test]
23106    fn read_sql_with_options_rejects_options_columns_across_query_entrypoints() {
23107        let conn = make_sql_test_conn();
23108        super::SqlConnection::execute_batch(
23109            &conn,
23110            "CREATE TABLE t1777_query_cols_reject (id INTEGER, val TEXT);",
23111        )
23112        .unwrap();
23113        super::SqlConnection::execute_batch(
23114            &conn,
23115            "INSERT INTO t1777_query_cols_reject VALUES (1, 'a'), (2, 'b');",
23116        )
23117        .unwrap();
23118
23119        fn assert_columns_rejection(err: &IoError, expected_sibling: &str) {
23120            assert!(
23121                matches!(err, IoError::Sql(msg)
23122                    if msg.contains("options.columns") && msg.contains(expected_sibling)),
23123                "expected options.columns error pointing to `{expected_sibling}`, got: {err:?}"
23124            );
23125        }
23126
23127        let opts_with_cols = || SqlReadOptions {
23128            columns: Some(vec!["id".to_owned()]),
23129            ..Default::default()
23130        };
23131
23132        // 1. read_sql_with_options (foundation, full-frame)
23133        let err = read_sql_with_options(
23134            &conn,
23135            "SELECT id, val FROM t1777_query_cols_reject",
23136            &opts_with_cols(),
23137        )
23138        .expect_err("read_sql_with_options must reject options.columns");
23139        assert_columns_rejection(&err, "read_sql_table_with_options");
23140
23141        // 2. read_sql_chunks_with_options (foundation, chunked)
23142        let err = read_sql_chunks_with_options(
23143            &conn,
23144            "SELECT id, val FROM t1777_query_cols_reject",
23145            &opts_with_cols(),
23146            2,
23147        )
23148        .expect_err("read_sql_chunks_with_options must reject options.columns");
23149        assert_columns_rejection(&err, "read_sql_table_chunks_with_options");
23150
23151        // 3. read_sql_chunks_with_options_and_index_col (foundation, indexed chunked)
23152        let err = read_sql_chunks_with_options_and_index_col(
23153            &conn,
23154            "SELECT id, val FROM t1777_query_cols_reject",
23155            &opts_with_cols(),
23156            Some("id"),
23157            2,
23158        )
23159        .expect_err("indexed chunks must reject options.columns");
23160        assert_columns_rejection(&err, "read_sql_table_chunks_with_options_and_index_col");
23161
23162        // 4. read_sql_query_with_options (delegator → read_sql_with_options)
23163        let err = read_sql_query_with_options(
23164            &conn,
23165            "SELECT id, val FROM t1777_query_cols_reject",
23166            &opts_with_cols(),
23167        )
23168        .expect_err("read_sql_query_with_options must propagate the rejection");
23169        assert_columns_rejection(&err, "read_sql_table_with_options");
23170
23171        // 5. read_sql_query_with_options_and_index_col (delegator)
23172        let err = read_sql_query_with_options_and_index_col(
23173            &conn,
23174            "SELECT id, val FROM t1777_query_cols_reject",
23175            &opts_with_cols(),
23176            Some("id"),
23177        )
23178        .expect_err("indexed query reader must reject options.columns");
23179        assert_columns_rejection(&err, "read_sql_table_with_options");
23180
23181        // 6. read_sql_query_chunks_with_options (delegator → read_sql_chunks_with_options)
23182        let err = read_sql_query_chunks_with_options(
23183            &conn,
23184            "SELECT id, val FROM t1777_query_cols_reject",
23185            &opts_with_cols(),
23186            2,
23187        )
23188        .expect_err("query chunks delegator must reject options.columns");
23189        assert_columns_rejection(&err, "read_sql_table_chunks_with_options");
23190
23191        // 7. read_sql_query_chunks_with_options_and_index_col (delegator)
23192        let err = read_sql_query_chunks_with_options_and_index_col(
23193            &conn,
23194            "SELECT id, val FROM t1777_query_cols_reject",
23195            &opts_with_cols(),
23196            Some("id"),
23197            2,
23198        )
23199        .expect_err("indexed query chunks delegator must reject options.columns");
23200        assert_columns_rejection(&err, "read_sql_table_chunks_with_options_and_index_col");
23201    }
23202
23203    // br-frankenpandas-t1777: table readers must continue to honor
23204    // options.columns (proves the cleared-options pass-through to the
23205    // query foundation didn't accidentally break the columns projection).
23206    #[cfg(feature = "sql-sqlite")]
23207    #[test]
23208    fn read_sql_table_with_options_still_honors_options_columns_after_t1777() {
23209        let conn = make_sql_test_conn();
23210        super::SqlConnection::execute_batch(
23211            &conn,
23212            "CREATE TABLE t1777_table_cols_honor (id INTEGER, val TEXT, secret TEXT);",
23213        )
23214        .unwrap();
23215        super::SqlConnection::execute_batch(
23216            &conn,
23217            "INSERT INTO t1777_table_cols_honor VALUES (1, 'a', 'x'), (2, 'b', 'y');",
23218        )
23219        .unwrap();
23220
23221        // Full-frame table reader with columns should project `id, val`
23222        // and drop `secret`.
23223        let frame = read_sql_table_with_options(
23224            &conn,
23225            "t1777_table_cols_honor",
23226            &SqlReadOptions {
23227                columns: Some(vec!["id".to_owned(), "val".to_owned()]),
23228                ..Default::default()
23229            },
23230        )
23231        .expect("table reader honors options.columns");
23232        assert_eq!(frame.column_names(), vec!["id", "val"]);
23233        assert!(frame.column("secret").is_none());
23234
23235        // Chunked table reader, same behavior per chunk.
23236        let chunks: Vec<DataFrame> = read_sql_table_chunks_with_options(
23237            &conn,
23238            "t1777_table_cols_honor",
23239            &SqlReadOptions {
23240                columns: Some(vec!["id".to_owned(), "val".to_owned()]),
23241                ..Default::default()
23242            },
23243            1,
23244        )
23245        .expect("chunked table reader honors options.columns")
23246        .collect::<Result<Vec<_>, _>>()
23247        .expect("all chunks");
23248        assert_eq!(chunks.len(), 2);
23249        for c in &chunks {
23250            assert_eq!(c.column_names(), vec!["id", "val"]);
23251            assert!(c.column("secret").is_none());
23252        }
23253
23254        // Indexed full-frame table reader: columns + index_col compose.
23255        let frame = read_sql_table_with_options_and_index_col(
23256            &conn,
23257            "t1777_table_cols_honor",
23258            &SqlReadOptions {
23259                columns: Some(vec!["val".to_owned()]),
23260                ..Default::default()
23261            },
23262            Some("id"),
23263        )
23264        .expect("indexed table reader honors options.columns");
23265        assert_eq!(frame.index().name(), Some("id"));
23266        assert_eq!(frame.column_names(), vec!["val"]);
23267        assert!(frame.column("id").is_none());
23268        assert!(frame.column("secret").is_none());
23269
23270        // Indexed chunked table reader.
23271        let chunks: Vec<DataFrame> = read_sql_table_chunks_with_options_and_index_col(
23272            &conn,
23273            "t1777_table_cols_honor",
23274            &SqlReadOptions {
23275                columns: Some(vec!["val".to_owned()]),
23276                ..Default::default()
23277            },
23278            Some("id"),
23279            1,
23280        )
23281        .expect("indexed chunked table reader honors options.columns")
23282        .collect::<Result<Vec<_>, _>>()
23283        .expect("all chunks");
23284        assert_eq!(chunks.len(), 2);
23285        for c in &chunks {
23286            assert_eq!(c.column_names(), vec!["val"]);
23287            assert!(c.column("id").is_none());
23288            assert!(c.column("secret").is_none());
23289        }
23290    }
23291
23292    #[cfg(feature = "sql-sqlite")]
23293    #[test]
23294    fn sql_read_table_with_options_and_index_col_applies_options_before_indexing() {
23295        let conn = make_sql_test_conn();
23296        conn.execute_batch(
23297            "CREATE TABLE table_options_index (ts TEXT, amount TEXT, label TEXT);
23298             INSERT INTO table_options_index (ts, amount, label) VALUES
23299                ('2024-04-01', '$10.00', 'a'),
23300                ('2024-04-02 03:04:05', '20.50', 'b');",
23301        )
23302        .expect("create table_options_index table");
23303
23304        let frame = read_sql_table_with_options_and_index_col(
23305            &conn,
23306            "table_options_index",
23307            &SqlReadOptions {
23308                params: None,
23309                parse_dates: Some(vec!["ts".to_owned()]),
23310                coerce_float: true,
23311                dtype: None,
23312                schema: None,
23313                columns: None,
23314                index_col: None,
23315            },
23316            Some("ts"),
23317        )
23318        .expect("read table with options and index_col");
23319
23320        assert_eq!(frame.index().name(), Some("ts"));
23321        assert_eq!(
23322            frame.index().labels(),
23323            &[
23324                IndexLabel::Datetime64(1_711_929_600_000_000_000),
23325                IndexLabel::Datetime64(1_712_027_045_000_000_000)
23326            ]
23327        );
23328        assert!(frame.column("ts").is_none());
23329        assert_eq!(
23330            frame.column("amount").unwrap().values(),
23331            &[Scalar::Float64(10.0), Scalar::Float64(20.5)]
23332        );
23333    }
23334
23335    #[cfg(feature = "sql-sqlite")]
23336    #[test]
23337    fn sql_read_table_with_options_and_index_col_none_keeps_options_and_range_index() {
23338        let conn = make_sql_test_conn();
23339        conn.execute_batch(
23340            "CREATE TABLE table_options_no_index (id INTEGER, amount TEXT);
23341             INSERT INTO table_options_no_index (id, amount) VALUES
23342                (1, '$1.25'),
23343                (2, '$2.50');",
23344        )
23345        .expect("create table_options_no_index table");
23346
23347        let frame = read_sql_table_with_options_and_index_col(
23348            &conn,
23349            "table_options_no_index",
23350            &SqlReadOptions {
23351                params: None,
23352                parse_dates: None,
23353                coerce_float: true,
23354                dtype: None,
23355                schema: None,
23356                columns: None,
23357                index_col: None,
23358            },
23359            None,
23360        )
23361        .expect("read table with options and no index_col");
23362
23363        assert_eq!(
23364            frame.index().labels(),
23365            &[IndexLabel::Int64(0), IndexLabel::Int64(1)]
23366        );
23367        assert_eq!(frame.column_names(), vec!["id", "amount"]);
23368        assert_eq!(
23369            frame.column("amount").unwrap().values(),
23370            &[Scalar::Float64(1.25), Scalar::Float64(2.5)]
23371        );
23372    }
23373
23374    #[cfg(feature = "sql-sqlite")]
23375    #[test]
23376    fn sql_read_table_chunks_with_options_and_index_col_promotes_each_chunk_index() {
23377        let conn = make_sql_test_conn();
23378        conn.execute_batch(
23379            "CREATE TABLE table_options_index_chunked (ts TEXT, amount TEXT);
23380             INSERT INTO table_options_index_chunked (ts, amount) VALUES
23381                ('2024-05-01', '$10.00'),
23382                ('2024-05-02', '$20.00'),
23383                ('2024-05-03', '$30.50');",
23384        )
23385        .expect("create table_options_index_chunked table");
23386
23387        let chunks = read_sql_table_chunks_with_options_and_index_col(
23388            &conn,
23389            "table_options_index_chunked",
23390            &SqlReadOptions {
23391                params: None,
23392                parse_dates: Some(vec!["ts".to_owned()]),
23393                coerce_float: true,
23394                dtype: None,
23395                schema: None,
23396                columns: None,
23397                index_col: None,
23398            },
23399            Some("ts"),
23400            2,
23401        )
23402        .expect("table indexed option chunk iterator")
23403        .collect::<Result<Vec<_>, _>>()
23404        .expect("all chunks");
23405
23406        assert_eq!(chunks.len(), 2);
23407        assert_eq!(chunks[0].index().name(), Some("ts"));
23408        // parse_dates column promoted to index → DatetimeIndex (br-frankenpandas-0ezw7).
23409        assert_eq!(
23410            chunks[0].index().labels(),
23411            &[
23412                IndexLabel::Datetime64(1_714_521_600_000_000_000),
23413                IndexLabel::Datetime64(1_714_608_000_000_000_000)
23414            ]
23415        );
23416        assert!(chunks[0].column("ts").is_none());
23417        assert_eq!(
23418            chunks[0].column("amount").unwrap().values(),
23419            &[Scalar::Float64(10.0), Scalar::Float64(20.0)]
23420        );
23421        assert_eq!(
23422            chunks[1].index().labels(),
23423            &[IndexLabel::Datetime64(1_714_694_400_000_000_000)]
23424        );
23425        assert_eq!(
23426            chunks[1].column("amount").unwrap().values(),
23427            &[Scalar::Float64(30.5)]
23428        );
23429    }
23430
23431    #[cfg(feature = "sql-sqlite")]
23432    #[test]
23433    fn sql_read_table_chunks_with_options_and_index_col_uses_options_index_when_explicit_none() {
23434        let conn = make_sql_test_conn();
23435        conn.execute_batch(
23436            "CREATE TABLE table_options_struct_index (id INTEGER, amount TEXT);
23437             INSERT INTO table_options_struct_index (id, amount) VALUES
23438                (10, '$10.00'),
23439                (20, '$20.00'),
23440                (30, '$30.50');",
23441        )
23442        .expect("create table_options_struct_index table");
23443
23444        let chunks = read_sql_table_chunks_with_options_and_index_col(
23445            &conn,
23446            "table_options_struct_index",
23447            &SqlReadOptions {
23448                params: None,
23449                parse_dates: None,
23450                coerce_float: true,
23451                dtype: None,
23452                schema: None,
23453                columns: None,
23454                index_col: Some("id".to_owned()),
23455            },
23456            None,
23457            2,
23458        )
23459        .expect("table indexed option chunk iterator")
23460        .collect::<Result<Vec<_>, _>>()
23461        .expect("all chunks");
23462
23463        assert_eq!(chunks.len(), 2);
23464        assert_eq!(
23465            chunks[0].index().labels(),
23466            &[IndexLabel::Int64(10), IndexLabel::Int64(20)]
23467        );
23468        assert!(chunks[0].column("id").is_none());
23469        assert_eq!(chunks[1].index().labels(), &[IndexLabel::Int64(30)]);
23470        assert_eq!(
23471            chunks[1].column("amount").unwrap().values(),
23472            &[Scalar::Float64(30.5)]
23473        );
23474    }
23475
23476    #[cfg(feature = "sql-sqlite")]
23477    #[test]
23478    fn sql_read_table_chunks_with_options_and_index_col_missing_column_errors() {
23479        let conn = make_sql_test_conn();
23480        conn.execute_batch(
23481            "CREATE TABLE table_options_missing_index (id INTEGER, amount TEXT);
23482             INSERT INTO table_options_missing_index (id, amount) VALUES (1, '$10.00');",
23483        )
23484        .expect("create table_options_missing_index table");
23485
23486        let err = read_sql_table_chunks_with_options_and_index_col(
23487            &conn,
23488            "table_options_missing_index",
23489            &SqlReadOptions {
23490                params: None,
23491                parse_dates: None,
23492                coerce_float: true,
23493                dtype: None,
23494                schema: None,
23495                columns: None,
23496                index_col: None,
23497            },
23498            Some("missing"),
23499            1,
23500        )
23501        .expect_err("missing index_col should error during iterator construction");
23502
23503        assert!(matches!(err, IoError::Sql(msg) if msg.contains("index_col")));
23504    }
23505
23506    #[cfg(feature = "sql-sqlite")]
23507    #[test]
23508    fn sql_read_with_parse_dates_coerces_named_columns() {
23509        let conn = make_sql_test_conn();
23510        conn.execute_batch(
23511            "CREATE TABLE events (ts TEXT, value INTEGER);
23512             INSERT INTO events (ts, value) VALUES
23513                ('2024-01-15', 1),
23514                ('2024-02-01 05:06:07', 2);",
23515        )
23516        .expect("create events table");
23517
23518        let frame = read_sql_with_options(
23519            &conn,
23520            "SELECT ts, value FROM events ORDER BY value",
23521            &SqlReadOptions {
23522                params: None,
23523                parse_dates: Some(vec!["ts".to_owned()]),
23524                coerce_float: false,
23525                dtype: None,
23526                schema: None,
23527                columns: None,
23528                index_col: None,
23529            },
23530        )
23531        .expect("read sql with parse_dates");
23532
23533        // parse_dates now yields typed Datetime64[ns] (br-frankenpandas-0ezw7).
23534        assert_eq!(
23535            frame.column("ts").unwrap().values()[0],
23536            Scalar::Datetime64(1_705_276_800_000_000_000)
23537        );
23538        assert_eq!(
23539            frame.column("ts").unwrap().values()[1],
23540            Scalar::Datetime64(1_706_763_967_000_000_000)
23541        );
23542        assert_eq!(frame.column("value").unwrap().values()[0], Scalar::Int64(1));
23543        assert_eq!(frame.column("value").unwrap().values()[1], Scalar::Int64(2));
23544    }
23545
23546    #[cfg(feature = "sql-sqlite")]
23547    #[test]
23548    fn sql_read_with_parse_dates_missing_column_errors() {
23549        let conn = make_sql_test_conn();
23550        conn.execute_batch(
23551            "CREATE TABLE metrics (value INTEGER);
23552             INSERT INTO metrics (value) VALUES (1);",
23553        )
23554        .expect("create metrics table");
23555
23556        let err = read_sql_with_options(
23557            &conn,
23558            "SELECT value FROM metrics",
23559            &SqlReadOptions {
23560                params: None,
23561                parse_dates: Some(vec!["ts".to_owned()]),
23562                coerce_float: false,
23563                dtype: None,
23564                schema: None,
23565                columns: None,
23566                index_col: None,
23567            },
23568        )
23569        .expect_err("missing parse_dates column should error");
23570
23571        assert!(
23572            matches!(err, IoError::MissingParseDateColumns(missing) if missing == vec!["ts".to_owned()])
23573        );
23574    }
23575
23576    #[cfg(feature = "sql-sqlite")]
23577    #[test]
23578    fn sql_read_with_params_binds_positional_placeholders() {
23579        let frame = make_test_dataframe();
23580        let conn = make_sql_test_conn();
23581        write_sql(&frame, &conn, "data", SqlIfExists::Fail).unwrap();
23582
23583        let filtered = read_sql_with_options(
23584            &conn,
23585            "SELECT ints, names FROM data WHERE ints > ? AND names != ? ORDER BY ints",
23586            &SqlReadOptions {
23587                params: Some(vec![Scalar::Int64(15), Scalar::Utf8("bob".to_owned())]),
23588                parse_dates: None,
23589                coerce_float: false,
23590                dtype: None,
23591                schema: None,
23592                columns: None,
23593                index_col: None,
23594            },
23595        )
23596        .expect("read sql with params");
23597
23598        assert_eq!(filtered.index().len(), 1);
23599        assert_eq!(
23600            filtered.column("ints").unwrap().values(),
23601            &[Scalar::Int64(30)]
23602        );
23603        assert_eq!(
23604            filtered.column("names").unwrap().values(),
23605            &[Scalar::Utf8("carol".into())]
23606        );
23607    }
23608
23609    #[cfg(feature = "sql-sqlite")]
23610    #[test]
23611    fn sql_read_with_params_wrong_arity_errors() {
23612        let frame = make_test_dataframe();
23613        let conn = make_sql_test_conn();
23614        write_sql(&frame, &conn, "data", SqlIfExists::Fail).unwrap();
23615
23616        let err = read_sql_with_options(
23617            &conn,
23618            "SELECT ints FROM data WHERE ints > ? AND names != ?",
23619            &SqlReadOptions {
23620                params: Some(vec![Scalar::Int64(15)]),
23621                parse_dates: None,
23622                coerce_float: false,
23623                dtype: None,
23624                schema: None,
23625                columns: None,
23626                index_col: None,
23627            },
23628        )
23629        .expect_err("wrong arity should error");
23630
23631        assert!(matches!(err, IoError::Sql(msg) if msg.contains("parameter")));
23632    }
23633
23634    #[cfg(feature = "sql-sqlite")]
23635    #[test]
23636    fn sql_read_coerce_float_promotes_decimal_like_text_columns() {
23637        let conn = make_sql_test_conn();
23638        conn.execute_batch(
23639            "CREATE TABLE payments (id INTEGER, amount TEXT, fee TEXT);
23640             INSERT INTO payments (id, amount, fee) VALUES
23641                (1, '12.50', '$1,234.50'),
23642                (2, '-3.25', NULL);",
23643        )
23644        .expect("create payments table");
23645
23646        // Per fd90.41: pandas default for coerce_float is True, and our
23647        // SqlReadOptions::default() now matches. So the bare read_sql
23648        // path coerces decimal-like text columns to Float64 by default.
23649        let default_frame =
23650            read_sql(&conn, "SELECT amount FROM payments ORDER BY id").expect("default read");
23651        assert_eq!(
23652            default_frame.column("amount").unwrap().dtype(),
23653            DType::Float64
23654        );
23655        assert_eq!(
23656            default_frame.column("amount").unwrap().values(),
23657            &[Scalar::Float64(12.5), Scalar::Float64(-3.25)],
23658        );
23659
23660        // Explicitly opting out of coerce_float keeps the raw Utf8.
23661        let no_coerce = read_sql_with_options(
23662            &conn,
23663            "SELECT amount FROM payments ORDER BY id",
23664            &SqlReadOptions {
23665                coerce_float: false,
23666                ..SqlReadOptions::default()
23667            },
23668        )
23669        .expect("read without coerce_float");
23670        assert_eq!(
23671            no_coerce.column("amount").unwrap().values(),
23672            &[
23673                Scalar::Utf8("12.50".to_owned()),
23674                Scalar::Utf8("-3.25".to_owned()),
23675            ],
23676        );
23677
23678        let coerced = read_sql_with_options(
23679            &conn,
23680            "SELECT amount, fee FROM payments ORDER BY id",
23681            &SqlReadOptions {
23682                coerce_float: true,
23683                ..SqlReadOptions::default()
23684            },
23685        )
23686        .expect("read with coerce_float");
23687
23688        let amount = coerced.column("amount").expect("amount");
23689        assert_eq!(amount.dtype(), DType::Float64);
23690        assert_eq!(
23691            amount.values(),
23692            &[Scalar::Float64(12.5), Scalar::Float64(-3.25)],
23693        );
23694
23695        let fee = coerced.column("fee").expect("fee");
23696        assert_eq!(fee.dtype(), DType::Float64);
23697        assert_eq!(fee.values()[0], Scalar::Float64(1234.5));
23698        assert!(matches!(fee.values()[1], Scalar::Null(NullKind::NaN)));
23699    }
23700
23701    #[cfg(feature = "sql-sqlite")]
23702    #[test]
23703    fn sql_read_coerce_float_leaves_non_numeric_text_columns_unchanged() {
23704        let conn = make_sql_test_conn();
23705        conn.execute_batch(
23706            "CREATE TABLE mixed (id INTEGER, maybe_amount TEXT, label TEXT);
23707             INSERT INTO mixed (id, maybe_amount, label) VALUES
23708                (1, '12.50', 'alpha'),
23709                (2, 'not numeric', '20.0');",
23710        )
23711        .expect("create mixed table");
23712
23713        let frame = read_sql_with_options(
23714            &conn,
23715            "SELECT maybe_amount, label FROM mixed ORDER BY id",
23716            &SqlReadOptions {
23717                coerce_float: true,
23718                dtype: None,
23719                schema: None,
23720                columns: None,
23721                index_col: None,
23722                ..SqlReadOptions::default()
23723            },
23724        )
23725        .expect("read with coerce_float");
23726
23727        assert_eq!(
23728            frame.column("maybe_amount").unwrap().values(),
23729            &[
23730                Scalar::Utf8("12.50".to_owned()),
23731                Scalar::Utf8("not numeric".to_owned()),
23732            ],
23733        );
23734        assert_eq!(
23735            frame.column("label").unwrap().values(),
23736            &[
23737                Scalar::Utf8("alpha".to_owned()),
23738                Scalar::Utf8("20.0".to_owned()),
23739            ],
23740        );
23741    }
23742
23743    #[cfg(feature = "sql-sqlite")]
23744    #[test]
23745    fn sql_read_chunks_batches_rows_and_resets_index_per_chunk() {
23746        let conn = make_sql_test_conn();
23747        conn.execute_batch(
23748            "CREATE TABLE chunked (id INTEGER, name TEXT);
23749             INSERT INTO chunked (id, name) VALUES
23750                (1, 'alpha'),
23751                (2, 'beta'),
23752                (3, 'gamma'),
23753                (4, 'delta'),
23754                (5, 'epsilon');",
23755        )
23756        .expect("create chunked table");
23757
23758        let chunks = read_sql_chunks(&conn, "SELECT id, name FROM chunked ORDER BY id", 2)
23759            .expect("chunk iterator")
23760            .collect::<Result<Vec<_>, _>>()
23761            .expect("all chunks");
23762
23763        assert_eq!(chunks.len(), 3);
23764        assert_eq!(
23765            chunks[0].index().labels(),
23766            &[IndexLabel::Int64(0), IndexLabel::Int64(1)]
23767        );
23768        assert_eq!(
23769            chunks[1].index().labels(),
23770            &[IndexLabel::Int64(0), IndexLabel::Int64(1)]
23771        );
23772        assert_eq!(chunks[2].index().labels(), &[IndexLabel::Int64(0)]);
23773        assert_eq!(
23774            chunks[0].column("id").unwrap().values(),
23775            &[Scalar::Int64(1), Scalar::Int64(2)]
23776        );
23777        assert_eq!(
23778            chunks[1].column("id").unwrap().values(),
23779            &[Scalar::Int64(3), Scalar::Int64(4)]
23780        );
23781        assert_eq!(
23782            chunks[2].column("name").unwrap().values(),
23783            &[Scalar::Utf8("epsilon".to_owned())]
23784        );
23785    }
23786
23787    #[cfg(feature = "sql-sqlite")]
23788    #[test]
23789    fn sql_read_chunks_sqlite_uses_paged_iterator_state() {
23790        let conn = make_sql_test_conn();
23791        conn.execute_batch(
23792            "CREATE TABLE fp_sqlite_paged_chunks (id INTEGER, name TEXT);
23793             INSERT INTO fp_sqlite_paged_chunks (id, name) VALUES
23794                (1, 'alpha'),
23795                (2, 'beta');",
23796        )
23797        .expect("create sqlite_paged_chunks table");
23798
23799        let mut chunks = read_sql_chunks(
23800            &conn,
23801            "SELECT id, name FROM fp_sqlite_paged_chunks ORDER BY id",
23802            1,
23803        )
23804        .expect("chunk iterator");
23805
23806        let initial_debug = format!("{chunks:?}");
23807        assert!(
23808            initial_debug.contains("mode: \"paged\""),
23809            "SQLite chunk reads must use paged mode, got {initial_debug}"
23810        );
23811        assert!(initial_debug.contains("next_offset: 0"));
23812
23813        let first = chunks
23814            .next()
23815            .expect("first chunk")
23816            .expect("first chunk should read");
23817        assert_eq!(first.column("id").unwrap().values(), &[Scalar::Int64(1)]);
23818
23819        let after_first_debug = format!("{chunks:?}");
23820        assert!(after_first_debug.contains("next_offset: 1"));
23821    }
23822
23823    #[cfg(feature = "sql-sqlite")]
23824    #[test]
23825    fn sql_read_chunks_with_options_applies_params_parse_dates_and_coerce_float() {
23826        let conn = make_sql_test_conn();
23827        conn.execute_batch(
23828            "CREATE TABLE events (ts TEXT, amount TEXT, keep INTEGER);
23829             INSERT INTO events (ts, amount, keep) VALUES
23830                ('2024-01-15', '12.50', 0),
23831                ('2024-02-01 05:06:07', '$1,234.50', 1),
23832                ('2024-03-03', '-3.25', 1);",
23833        )
23834        .expect("create events table");
23835
23836        let chunks = read_sql_chunks_with_options(
23837            &conn,
23838            "SELECT ts, amount FROM events WHERE keep = ? ORDER BY ts",
23839            &SqlReadOptions {
23840                params: Some(vec![Scalar::Int64(1)]),
23841                parse_dates: Some(vec!["ts".to_owned()]),
23842                coerce_float: true,
23843                dtype: None,
23844                schema: None,
23845                columns: None,
23846                index_col: None,
23847            },
23848            1,
23849        )
23850        .expect("chunk iterator")
23851        .collect::<Result<Vec<_>, _>>()
23852        .expect("all chunks");
23853
23854        assert_eq!(chunks.len(), 2);
23855        // parse_dates now yields typed Datetime64[ns] (br-frankenpandas-0ezw7).
23856        assert_eq!(
23857            chunks[0].column("ts").unwrap().values(),
23858            &[Scalar::Datetime64(1_706_763_967_000_000_000)]
23859        );
23860        assert_eq!(
23861            chunks[0].column("amount").unwrap().values(),
23862            &[Scalar::Float64(1234.5)]
23863        );
23864        assert_eq!(
23865            chunks[1].column("ts").unwrap().values(),
23866            &[Scalar::Datetime64(1_709_424_000_000_000_000)]
23867        );
23868        assert_eq!(
23869            chunks[1].column("amount").unwrap().values(),
23870            &[Scalar::Float64(-3.25)]
23871        );
23872    }
23873
23874    #[cfg(feature = "sql-sqlite")]
23875    #[test]
23876    fn sql_read_chunks_rejects_zero_chunksize() {
23877        let conn = make_sql_test_conn();
23878
23879        let err =
23880            read_sql_chunks(&conn, "SELECT 1", 0).expect_err("zero chunksize should be rejected");
23881
23882        assert!(matches!(err, IoError::Sql(msg) if msg.contains("chunksize")));
23883    }
23884
23885    #[cfg(feature = "sql-sqlite")]
23886    #[test]
23887    fn sql_duplicate_column_names_error() {
23888        let conn = make_sql_test_conn();
23889        let err = read_sql(&conn, "SELECT 1 as dup, 2 as dup");
23890        assert!(matches!(err, Err(IoError::DuplicateColumnName(name)) if name == "dup"));
23891    }
23892
23893    #[cfg(feature = "sql-sqlite")]
23894    #[test]
23895    fn sql_if_exists_fail() {
23896        let frame = make_test_dataframe();
23897        let conn = make_sql_test_conn();
23898        write_sql(&frame, &conn, "tbl", SqlIfExists::Fail).unwrap();
23899
23900        let err = write_sql(&frame, &conn, "tbl", SqlIfExists::Fail);
23901        assert!(err.is_err());
23902        assert!(matches!(&err.unwrap_err(), IoError::Sql(msg) if msg.contains("already exists")),);
23903    }
23904
23905    #[cfg(feature = "sql-sqlite")]
23906    #[test]
23907    fn sql_if_exists_replace() {
23908        let frame = make_test_dataframe();
23909        let conn = make_sql_test_conn();
23910        write_sql(&frame, &conn, "tbl", SqlIfExists::Fail).unwrap();
23911
23912        // Replace should succeed and overwrite.
23913        write_sql(&frame, &conn, "tbl", SqlIfExists::Replace).unwrap();
23914        let frame2 = read_sql_table(&conn, "tbl").unwrap();
23915        assert_eq!(frame2.index().len(), 3);
23916    }
23917
23918    #[cfg(feature = "sql-sqlite")]
23919    #[test]
23920    fn sql_if_exists_append() {
23921        let frame = make_test_dataframe();
23922        let conn = make_sql_test_conn();
23923        write_sql(&frame, &conn, "tbl", SqlIfExists::Fail).unwrap();
23924
23925        // Append should add rows.
23926        write_sql(&frame, &conn, "tbl", SqlIfExists::Append).unwrap();
23927        let frame2 = read_sql_table(&conn, "tbl").unwrap();
23928        assert_eq!(frame2.index().len(), 6); // 3 + 3
23929    }
23930
23931    #[cfg(feature = "sql-sqlite")]
23932    #[test]
23933    fn sql_with_nulls() {
23934        use fp_types::DType;
23935
23936        let mut columns = BTreeMap::new();
23937        columns.insert(
23938            "vals".to_string(),
23939            Column::new(
23940                DType::Float64,
23941                vec![
23942                    Scalar::Float64(1.0),
23943                    Scalar::Null(NullKind::NaN),
23944                    Scalar::Float64(3.0),
23945                ],
23946            )
23947            .unwrap(),
23948        );
23949
23950        let labels = vec![
23951            IndexLabel::Int64(0),
23952            IndexLabel::Int64(1),
23953            IndexLabel::Int64(2),
23954        ];
23955        let frame =
23956            DataFrame::new_with_column_order(Index::new(labels), columns, vec!["vals".to_string()])
23957                .unwrap();
23958
23959        let conn = make_sql_test_conn();
23960        write_sql(&frame, &conn, "nulltest", SqlIfExists::Fail).unwrap();
23961        let frame2 = read_sql_table(&conn, "nulltest").unwrap();
23962
23963        assert_eq!(
23964            frame2.column("vals").unwrap().values()[0],
23965            Scalar::Float64(1.0)
23966        );
23967        assert!(frame2.column("vals").unwrap().values()[1].is_missing());
23968        assert_eq!(
23969            frame2.column("vals").unwrap().values()[2],
23970            Scalar::Float64(3.0)
23971        );
23972    }
23973
23974    #[cfg(feature = "sql-sqlite")]
23975    #[test]
23976    fn sql_bool_roundtrip() {
23977        use fp_types::DType;
23978
23979        let mut columns = BTreeMap::new();
23980        columns.insert(
23981            "flags".to_string(),
23982            Column::new(
23983                DType::Bool,
23984                vec![Scalar::Bool(true), Scalar::Bool(false), Scalar::Bool(true)],
23985            )
23986            .unwrap(),
23987        );
23988
23989        let labels = vec![
23990            IndexLabel::Int64(0),
23991            IndexLabel::Int64(1),
23992            IndexLabel::Int64(2),
23993        ];
23994        let frame = DataFrame::new_with_column_order(
23995            Index::new(labels),
23996            columns,
23997            vec!["flags".to_string()],
23998        )
23999        .unwrap();
24000
24001        let conn = make_sql_test_conn();
24002        write_sql(&frame, &conn, "booltest", SqlIfExists::Fail).unwrap();
24003        let frame2 = read_sql_table(&conn, "booltest").unwrap();
24004
24005        // Bools stored as INTEGER(0/1), read back as Int64.
24006        assert_eq!(
24007            frame2.column("flags").unwrap().values()[0],
24008            Scalar::Int64(1)
24009        );
24010        assert_eq!(
24011            frame2.column("flags").unwrap().values()[1],
24012            Scalar::Int64(0)
24013        );
24014    }
24015
24016    #[cfg(feature = "sql-sqlite")]
24017    #[test]
24018    fn sql_invalid_table_name_rejected() {
24019        let conn = make_sql_test_conn();
24020        let err = read_sql_table(&conn, "Robert'; DROP TABLE students; --");
24021        assert!(err.is_err());
24022        assert!(
24023            matches!(&err.unwrap_err(), IoError::Sql(msg) if msg.contains("invalid table name")),
24024        );
24025    }
24026
24027    #[cfg(feature = "sql-sqlite")]
24028    #[test]
24029    fn sql_empty_table_name_rejected() {
24030        let conn = make_sql_test_conn();
24031        let err = read_sql_table(&conn, "");
24032        assert!(err.is_err());
24033        assert!(
24034            matches!(&err.unwrap_err(), IoError::Sql(msg) if msg.contains("invalid table name")),
24035        );
24036
24037        let frame = make_test_dataframe();
24038        let err = write_sql(&frame, &conn, "", SqlIfExists::Fail);
24039        assert!(err.is_err());
24040    }
24041
24042    #[cfg(feature = "sql-sqlite")]
24043    #[test]
24044    fn sql_empty_result() {
24045        let conn = make_sql_test_conn();
24046        conn.execute_batch("CREATE TABLE empty (x INTEGER, y TEXT)")
24047            .unwrap();
24048        let frame = read_sql_table(&conn, "empty").unwrap();
24049        assert_eq!(frame.index().len(), 0);
24050        assert_eq!(frame.column_names().len(), 2);
24051        assert_eq!(frame.column("x").unwrap().dtype(), DType::Int64);
24052        assert_eq!(frame.column("y").unwrap().dtype(), DType::Utf8);
24053
24054        conn.execute_batch(
24055            "CREATE TABLE typed_nulls (i INTEGER, r REAL, t TEXT);
24056             INSERT INTO typed_nulls VALUES (NULL, NULL, NULL);",
24057        )
24058        .unwrap();
24059        let null_frame = read_sql_table(&conn, "typed_nulls").unwrap();
24060        assert_eq!(null_frame.index().len(), 1);
24061        assert_eq!(null_frame.column("i").unwrap().dtype(), DType::Int64);
24062        assert_eq!(null_frame.column("r").unwrap().dtype(), DType::Float64);
24063        assert_eq!(null_frame.column("t").unwrap().dtype(), DType::Utf8);
24064    }
24065
24066    #[cfg(feature = "sql-sqlite")]
24067    #[test]
24068    fn sql_empty_filtered_query_preserves_declared_dtypes() {
24069        let conn = make_sql_test_conn();
24070        conn.execute_batch(
24071            "CREATE TABLE filtered_empty (i INTEGER, r REAL, t TEXT);
24072             INSERT INTO filtered_empty VALUES (1, 1.25, 'kept');",
24073        )
24074        .unwrap();
24075
24076        let frame = read_sql_with_options(
24077            &conn,
24078            "SELECT i, r, t FROM filtered_empty WHERE i > ?",
24079            &SqlReadOptions {
24080                params: Some(vec![Scalar::Int64(10)]),
24081                ..SqlReadOptions::default()
24082            },
24083        )
24084        .expect("empty filtered query must preserve cursor dtype hints");
24085
24086        assert_eq!(frame.index().len(), 0);
24087        assert_eq!(frame.column_names(), vec!["i", "r", "t"]);
24088        assert_eq!(frame.column("i").unwrap().dtype(), DType::Int64);
24089        assert_eq!(frame.column("r").unwrap().dtype(), DType::Float64);
24090        assert_eq!(frame.column("t").unwrap().dtype(), DType::Utf8);
24091    }
24092
24093    #[cfg(feature = "sql-sqlite")]
24094    #[test]
24095    fn sql_extension_trait() {
24096        let frame = make_test_dataframe();
24097        let conn = make_sql_test_conn();
24098
24099        // Use the extension trait method.
24100        use super::DataFrameIoExt;
24101        frame.to_sql(&conn, "ext_test", SqlIfExists::Fail).unwrap();
24102        frame
24103            .to_sql_with_options(
24104                &conn,
24105                "ext_test_options",
24106                &SqlWriteOptions {
24107                    if_exists: SqlIfExists::Fail,
24108                    index: false,
24109                    index_label: None,
24110                    schema: None,
24111                    dtype: None,
24112                    method: SqlInsertMethod::Single,
24113                    chunksize: None,
24114                },
24115            )
24116            .unwrap();
24117
24118        let frame2 = read_sql_table(&conn, "ext_test").unwrap();
24119        assert_eq!(frame2.index().len(), 3);
24120        let frame3 = read_sql_table(&conn, "ext_test_options").unwrap();
24121        assert_eq!(frame3.index().len(), 3);
24122    }
24123
24124    #[cfg(feature = "sql-sqlite")]
24125    #[test]
24126    fn series_sql_extension_aliases_roundtrip_to_single_column_table() {
24127        use super::SeriesIoExt;
24128
24129        let source = Series::from_values(
24130            "sales",
24131            vec!["r1".into(), "r2".into()],
24132            vec![Scalar::Int64(10), Scalar::Int64(12)],
24133        )
24134        .expect("source series");
24135
24136        let conn = make_sql_test_conn();
24137        source
24138            .to_sql(&conn, "series_ext", SqlIfExists::Fail)
24139            .expect("series to_sql");
24140        let roundtrip = read_sql_table(&conn, "series_ext").expect("read series table");
24141        assert_eq!(roundtrip.column_names(), vec!["index", "sales"]);
24142        assert_eq!(
24143            roundtrip.column("index").expect("index column").values(),
24144            &[Scalar::Utf8("r1".into()), Scalar::Utf8("r2".into())]
24145        );
24146        assert_eq!(
24147            roundtrip.column("sales").expect("sales column").values(),
24148            source.values()
24149        );
24150
24151        source
24152            .to_sql_with_options(
24153                &conn,
24154                "series_ext_no_index",
24155                &SqlWriteOptions {
24156                    if_exists: SqlIfExists::Fail,
24157                    index: false,
24158                    index_label: None,
24159                    schema: None,
24160                    dtype: None,
24161                    method: SqlInsertMethod::Single,
24162                    chunksize: None,
24163                },
24164            )
24165            .expect("series to_sql index false");
24166        let no_index =
24167            read_sql_table(&conn, "series_ext_no_index").expect("read no-index series table");
24168        assert_eq!(no_index.column_names(), vec!["sales"]);
24169        assert_eq!(
24170            no_index.column("sales").expect("sales column").values(),
24171            source.values()
24172        );
24173    }
24174
24175    // ── Arrow IPC / Feather tests ────────────────────────────────────
24176
24177    #[test]
24178    fn feather_bytes_roundtrip() {
24179        let frame = make_test_dataframe();
24180        let bytes = super::write_feather_bytes(&frame).expect("write feather");
24181        assert!(!bytes.is_empty());
24182
24183        let frame2 = super::read_feather_bytes(&bytes).expect("read feather");
24184        assert_eq!(frame2.index().len(), 3);
24185
24186        // Check all column values survive round-trip exactly.
24187        let ints = frame2.column("ints").unwrap();
24188        assert_eq!(ints.values()[0], Scalar::Int64(10));
24189        assert_eq!(ints.values()[1], Scalar::Int64(20));
24190        assert_eq!(ints.values()[2], Scalar::Int64(30));
24191
24192        let floats = frame2.column("floats").unwrap();
24193        assert_eq!(floats.values()[0], Scalar::Float64(1.5));
24194        assert_eq!(floats.values()[2], Scalar::Float64(3.5));
24195
24196        let names = frame2.column("names").unwrap();
24197        assert_eq!(names.values()[0], Scalar::Utf8("alice".into()));
24198        assert_eq!(names.values()[2], Scalar::Utf8("carol".into()));
24199    }
24200
24201    #[test]
24202    fn feather_row_multiindex_roundtrip_restores_logical_row_axis() {
24203        let frame = make_row_multiindex_test_dataframe();
24204        let bytes = super::write_feather_bytes(&frame).expect("write feather");
24205        let roundtrip = super::read_feather_bytes(&bytes).expect("read feather");
24206
24207        assert!(roundtrip.equals(&frame));
24208        assert!(roundtrip.column("__index_level_0__").is_none());
24209        assert_eq!(
24210            roundtrip
24211                .row_multiindex()
24212                .expect("row multiindex should be restored")
24213                .get_level_values(1)
24214                .unwrap()
24215                .labels(),
24216            frame
24217                .row_multiindex()
24218                .expect("source row multiindex")
24219                .get_level_values(1)
24220                .unwrap()
24221                .labels()
24222        );
24223    }
24224
24225    #[test]
24226    fn feather_file_roundtrip() {
24227        let frame = make_test_dataframe();
24228        let dir = std::env::temp_dir();
24229        let path = dir.join("fp_io_test_feather_roundtrip.feather");
24230
24231        super::write_feather(&frame, &path).expect("write feather file");
24232        let frame2 = super::read_feather(&path).expect("read feather file");
24233        assert_eq!(frame2.index().len(), 3);
24234        assert_eq!(
24235            frame2.column("ints").unwrap().values()[0],
24236            Scalar::Int64(10)
24237        );
24238        std::fs::remove_file(&path).ok();
24239    }
24240
24241    #[test]
24242    fn ipc_stream_bytes_roundtrip() {
24243        let frame = make_test_dataframe();
24244        let bytes = super::write_ipc_stream_bytes(&frame).expect("write ipc stream");
24245        assert!(!bytes.is_empty());
24246
24247        let frame2 = super::read_ipc_stream_bytes(&bytes).expect("read ipc stream");
24248        assert_eq!(frame2.index().len(), 3);
24249        assert_eq!(
24250            frame2.column("ints").unwrap().values()[1],
24251            Scalar::Int64(20)
24252        );
24253        assert_eq!(
24254            frame2.column("names").unwrap().values()[1],
24255            Scalar::Utf8("bob".into())
24256        );
24257    }
24258
24259    #[test]
24260    fn ipc_stream_row_multiindex_roundtrip_restores_logical_row_axis() {
24261        let frame = make_row_multiindex_test_dataframe();
24262        let bytes = super::write_ipc_stream_bytes(&frame).expect("write ipc stream");
24263        let roundtrip = super::read_ipc_stream_bytes(&bytes).expect("read ipc stream");
24264
24265        assert!(roundtrip.equals(&frame));
24266        assert!(roundtrip.row_multiindex().is_some());
24267    }
24268
24269    #[test]
24270    fn feather_with_nulls() {
24271        use fp_types::DType;
24272
24273        let mut columns = BTreeMap::new();
24274        columns.insert(
24275            "vals".to_string(),
24276            Column::new(
24277                DType::Float64,
24278                vec![
24279                    Scalar::Float64(1.0),
24280                    Scalar::Null(NullKind::NaN),
24281                    Scalar::Float64(3.0),
24282                ],
24283            )
24284            .unwrap(),
24285        );
24286
24287        let labels = vec![
24288            IndexLabel::Int64(0),
24289            IndexLabel::Int64(1),
24290            IndexLabel::Int64(2),
24291        ];
24292        let frame =
24293            DataFrame::new_with_column_order(Index::new(labels), columns, vec!["vals".to_string()])
24294                .unwrap();
24295
24296        let bytes = super::write_feather_bytes(&frame).expect("write");
24297        let frame2 = super::read_feather_bytes(&bytes).expect("read");
24298
24299        assert_eq!(
24300            frame2.column("vals").unwrap().values()[0],
24301            Scalar::Float64(1.0)
24302        );
24303        assert!(frame2.column("vals").unwrap().values()[1].is_missing());
24304        assert_eq!(
24305            frame2.column("vals").unwrap().values()[2],
24306            Scalar::Float64(3.0)
24307        );
24308    }
24309
24310    #[test]
24311    fn feather_nullable_int_roundtrip_preserves_int_dtype() {
24312        use fp_types::DType;
24313
24314        let mut columns = BTreeMap::new();
24315        columns.insert(
24316            "vals".to_string(),
24317            Column::new(
24318                DType::Int64,
24319                vec![
24320                    Scalar::Int64(10),
24321                    Scalar::Null(NullKind::Null),
24322                    Scalar::Int64(30),
24323                ],
24324            )
24325            .unwrap(),
24326        );
24327
24328        let labels = vec![
24329            IndexLabel::Int64(0),
24330            IndexLabel::Int64(1),
24331            IndexLabel::Int64(2),
24332        ];
24333        let frame =
24334            DataFrame::new_with_column_order(Index::new(labels), columns, vec!["vals".to_string()])
24335                .unwrap();
24336
24337        let bytes = super::write_feather_bytes(&frame).expect("write");
24338        let frame2 = super::read_feather_bytes(&bytes).expect("read");
24339        let vals = frame2.column("vals").unwrap();
24340
24341        assert_eq!(vals.dtype(), DType::Int64);
24342        assert_eq!(vals.values()[0], Scalar::Int64(10));
24343        assert_eq!(vals.values()[1], Scalar::Null(NullKind::Null));
24344        assert_eq!(vals.values()[2], Scalar::Int64(30));
24345    }
24346
24347    #[test]
24348    fn series_arrow_array_nullable_int_roundtrip() {
24349        let series = Series::from_values(
24350            "vals",
24351            vec![
24352                IndexLabel::Utf8("r0".into()),
24353                IndexLabel::Utf8("r1".into()),
24354                IndexLabel::Utf8("r2".into()),
24355            ],
24356            vec![
24357                Scalar::Int64(10),
24358                Scalar::Null(NullKind::Null),
24359                Scalar::Int64(30),
24360            ],
24361        )
24362        .unwrap();
24363
24364        let (dt, arr) = super::series_to_arrow_array(&series).expect("arrow encode");
24365        assert_eq!(dt, ArrowDataType::Int64);
24366
24367        let typed = arr
24368            .as_any()
24369            .downcast_ref::<Int64Array>()
24370            .expect("int64 arrow array");
24371        assert_eq!(typed.value(0), 10);
24372        assert!(typed.is_null(1));
24373        assert_eq!(typed.value(2), 30);
24374
24375        let roundtrip = super::series_from_arrow_array(
24376            series.name(),
24377            series.index().labels().to_vec(),
24378            arr.as_ref(),
24379            &dt,
24380        )
24381        .expect("arrow decode");
24382
24383        assert_eq!(roundtrip.name(), "vals");
24384        assert_eq!(roundtrip.index().labels(), series.index().labels());
24385        assert_eq!(roundtrip.column().dtype(), DType::Int64);
24386        assert_eq!(roundtrip.values(), series.values());
24387    }
24388
24389    #[test]
24390    fn feather_bool_column() {
24391        use fp_types::DType;
24392
24393        let mut columns = BTreeMap::new();
24394        columns.insert(
24395            "flags".to_string(),
24396            Column::new(
24397                DType::Bool,
24398                vec![Scalar::Bool(true), Scalar::Bool(false), Scalar::Bool(true)],
24399            )
24400            .unwrap(),
24401        );
24402
24403        let labels = vec![
24404            IndexLabel::Int64(0),
24405            IndexLabel::Int64(1),
24406            IndexLabel::Int64(2),
24407        ];
24408        let frame = DataFrame::new_with_column_order(
24409            Index::new(labels),
24410            columns,
24411            vec!["flags".to_string()],
24412        )
24413        .unwrap();
24414
24415        let bytes = super::write_feather_bytes(&frame).expect("write");
24416        let frame2 = super::read_feather_bytes(&bytes).expect("read");
24417
24418        assert_eq!(
24419            frame2.column("flags").unwrap().values()[0],
24420            Scalar::Bool(true)
24421        );
24422        assert_eq!(
24423            frame2.column("flags").unwrap().values()[1],
24424            Scalar::Bool(false)
24425        );
24426    }
24427
24428    #[test]
24429    fn feather_preserves_column_order() {
24430        let frame = make_test_dataframe();
24431        let bytes = super::write_feather_bytes(&frame).expect("write");
24432        let frame2 = super::read_feather_bytes(&bytes).expect("read");
24433
24434        assert_eq!(
24435            frame2
24436                .column_names()
24437                .iter()
24438                .map(|s| s.as_str())
24439                .collect::<Vec<_>>(),
24440            frame
24441                .column_names()
24442                .iter()
24443                .map(|s| s.as_str())
24444                .collect::<Vec<_>>()
24445        );
24446    }
24447
24448    #[test]
24449    fn feather_extension_trait() {
24450        use super::DataFrameIoExt;
24451
24452        let frame = make_test_dataframe();
24453        let bytes = frame.to_feather_bytes().unwrap();
24454        let frame2 = super::read_feather_bytes(&bytes).unwrap();
24455        assert_eq!(frame2.index().len(), 3);
24456    }
24457
24458    // ── Adversarial parser tests (frankenpandas-yby) ─────────────────
24459
24460    // ── CsvReadOptions extended params tests (frankenpandas-qoz) ────
24461
24462    #[test]
24463    fn csv_nrows_limits_rows() {
24464        let input = "x\n1\n2\n3\n4\n5\n";
24465        let opts = CsvReadOptions {
24466            nrows: Some(3),
24467            ..Default::default()
24468        };
24469        let frame = read_csv_with_options(input, &opts).expect("parse");
24470        assert_eq!(frame.index().len(), 3);
24471        assert_eq!(frame.column("x").unwrap().values()[2], Scalar::Int64(3));
24472    }
24473
24474    #[test]
24475    fn csv_skiprows_skips_data_rows() {
24476        let input = "x\n1\n2\n3\n4\n5\n";
24477        let opts = CsvReadOptions {
24478            skiprows: 2,
24479            ..Default::default()
24480        };
24481        let frame = read_csv_with_options(input, &opts).expect("parse");
24482        assert_eq!(frame.index().len(), 3); // skipped header + first data row
24483        assert_eq!(frame.column("2").unwrap().values()[0], Scalar::Int64(3));
24484    }
24485
24486    #[test]
24487    fn csv_skiprows_and_nrows_combined() {
24488        let input = "x\n1\n2\n3\n4\n5\n";
24489        let opts = CsvReadOptions {
24490            skiprows: 1,
24491            nrows: Some(2),
24492            ..Default::default()
24493        };
24494        let frame = read_csv_with_options(input, &opts).expect("parse");
24495        assert_eq!(frame.index().len(), 2); // skipped header; read 2 data rows
24496        assert_eq!(frame.column("1").unwrap().values()[0], Scalar::Int64(2));
24497        assert_eq!(frame.column("1").unwrap().values()[1], Scalar::Int64(3));
24498    }
24499
24500    #[test]
24501    fn csv_usecols_selects_columns() {
24502        let input = "a,b,c\n1,2,3\n4,5,6\n";
24503        let opts = CsvReadOptions {
24504            usecols: Some(vec!["a".into(), "c".into()]),
24505            ..Default::default()
24506        };
24507        let frame = read_csv_with_options(input, &opts).expect("parse");
24508        assert_eq!(frame.column_names().len(), 2);
24509        assert!(frame.column("a").is_some());
24510        assert!(frame.column("b").is_none());
24511        assert!(frame.column("c").is_some());
24512        assert_eq!(frame.column("a").unwrap().values()[0], Scalar::Int64(1));
24513        assert_eq!(frame.column("c").unwrap().values()[1], Scalar::Int64(6));
24514    }
24515
24516    #[test]
24517    fn csv_usecols_nonexistent_column_errors() {
24518        let input = "a,b\n1,2\n";
24519        let opts = CsvReadOptions {
24520            usecols: Some(vec!["a".into(), "nonexistent".into()]),
24521            ..Default::default()
24522        };
24523        let err = read_csv_with_options(input, &opts).expect_err("missing usecols should error");
24524        assert!(matches!(err, IoError::MissingUsecols(_)));
24525    }
24526
24527    #[test]
24528    fn csv_dtype_coercion() {
24529        let input = "id,score\n1,95\n2,87\n";
24530        let mut dtype_map = std::collections::HashMap::new();
24531        dtype_map.insert("score".to_owned(), fp_types::DType::Float64);
24532        let opts = CsvReadOptions {
24533            dtype: Some(dtype_map),
24534            ..Default::default()
24535        };
24536        let frame = read_csv_with_options(input, &opts).expect("parse");
24537        // score column should be Float64, not Int64
24538        assert_eq!(
24539            frame.column("score").unwrap().values()[0],
24540            Scalar::Float64(95.0)
24541        );
24542        assert_eq!(
24543            frame.column("score").unwrap().values()[1],
24544            Scalar::Float64(87.0)
24545        );
24546        // id column should remain Int64 (not in dtype map)
24547        assert_eq!(frame.column("id").unwrap().values()[0], Scalar::Int64(1));
24548    }
24549
24550    #[test]
24551    fn csv_dtype_coercion_invalid_value_errors() {
24552        let input = "id,score\n1,abc\n";
24553        let mut dtype_map = std::collections::HashMap::new();
24554        dtype_map.insert("score".to_owned(), fp_types::DType::Int64);
24555        let opts = CsvReadOptions {
24556            dtype: Some(dtype_map),
24557            ..Default::default()
24558        };
24559        let err = read_csv_with_options(input, &opts).expect_err("invalid cast must error");
24560        assert!(matches!(
24561            err,
24562            IoError::Column(fp_columnar::ColumnError::Type(
24563                fp_types::TypeError::InvalidCast { .. }
24564            ))
24565        ));
24566    }
24567
24568    #[test]
24569    fn csv_skiprows_beyond_data_errors() {
24570        let input = "x\n1\n2\n";
24571        let opts = CsvReadOptions {
24572            skiprows: 100,
24573            ..Default::default()
24574        };
24575        let err = read_csv_with_options(input, &opts).expect_err("skiprows removes header");
24576        assert!(matches!(err, IoError::MissingHeaders));
24577    }
24578
24579    #[test]
24580    fn csv_nrows_zero_returns_empty() {
24581        let input = "x\n1\n2\n3\n";
24582        let opts = CsvReadOptions {
24583            nrows: Some(0),
24584            ..Default::default()
24585        };
24586        let frame = read_csv_with_options(input, &opts).expect("parse");
24587        assert_eq!(frame.index().len(), 0);
24588    }
24589
24590    #[test]
24591    fn csv_decimal_comma_parses_quoted_float_fields() {
24592        let input = "price\n\"1,50\"\n\"3,75\"\n";
24593        let opts = CsvReadOptions {
24594            decimal: b',',
24595            ..Default::default()
24596        };
24597        let frame = read_csv_with_options(input, &opts).expect("parse");
24598        assert_eq!(
24599            frame.column("price").unwrap().values(),
24600            &[Scalar::Float64(1.5), Scalar::Float64(3.75)]
24601        );
24602    }
24603
24604    #[test]
24605    fn csv_default_decimal_keeps_comma_decimal_strings_as_utf8() {
24606        let input = "price\n\"1,50\"\n";
24607        let frame = read_csv_with_options(input, &CsvReadOptions::default()).expect("parse");
24608        assert_eq!(
24609            frame.column("price").unwrap().values(),
24610            &[Scalar::Utf8("1,50".to_owned())]
24611        );
24612    }
24613
24614    #[test]
24615    fn csv_true_false_values_do_not_override_numeric_inference() {
24616        let input = "flag\n1\n0\n";
24617        let opts = CsvReadOptions {
24618            true_values: vec!["1".to_owned()],
24619            false_values: vec!["0".to_owned()],
24620            ..Default::default()
24621        };
24622        let frame = read_csv_with_options(input, &opts).expect("parse");
24623        assert_eq!(
24624            frame.column("flag").unwrap().values(),
24625            &[Scalar::Int64(1), Scalar::Int64(0)]
24626        );
24627    }
24628
24629    #[test]
24630    fn csv_true_false_values_convert_non_numeric_tokens() {
24631        let input = "flag\nyes\nno\n";
24632        let opts = CsvReadOptions {
24633            true_values: vec!["yes".to_owned()],
24634            false_values: vec!["no".to_owned()],
24635            ..Default::default()
24636        };
24637        let frame = read_csv_with_options(input, &opts).expect("parse");
24638        assert_eq!(
24639            frame.column("flag").unwrap().values(),
24640            &[Scalar::Bool(true), Scalar::Bool(false)]
24641        );
24642    }
24643
24644    #[test]
24645    fn csv_default_parsing_keeps_numeric_boolean_tokens_as_ints() {
24646        let input = "flag\n1\n0\n";
24647        let frame = read_csv_with_options(input, &CsvReadOptions::default()).expect("parse");
24648        assert_eq!(
24649            frame.column("flag").unwrap().values(),
24650            &[Scalar::Int64(1), Scalar::Int64(0)]
24651        );
24652    }
24653
24654    #[test]
24655    fn csv_missing_numeric_column_preserves_int() {
24656        // DISC-011: Nullable extension Int64 dtype parity - Int64 preserved, not promoted to Float64.
24657        let input = "a,b,c\n,NA,NaN\n1,,x\n";
24658        let frame = read_csv_with_options(input, &CsvReadOptions::default()).expect("parse");
24659        assert_eq!(
24660            frame.column("a").unwrap().values(),
24661            &[Scalar::Null(NullKind::Null), Scalar::Int64(1)]
24662        );
24663        assert!(frame.column("b").unwrap().values()[0].is_missing());
24664        assert!(frame.column("b").unwrap().values()[1].is_missing());
24665        assert_eq!(
24666            frame.column("c").unwrap().values(),
24667            &[Scalar::Null(NullKind::Null), Scalar::Utf8("x".to_owned())]
24668        );
24669    }
24670
24671    #[test]
24672    fn csv_parse_dates_mixed_naive_and_aware_strings_normalizes_per_value() {
24673        // pandas pd.read_csv(parse_dates=["ts"]) CANNOT unify a column mixing
24674        // tz-naive and tz-aware timestamps into datetime64[ns], so it keeps the
24675        // whole column as object — a Series of mixed Timestamp objects whose
24676        // str() forms are the naive `YYYY-MM-DD HH:MM:SS` and the aware
24677        // `... +HH:MM`. FrankenPandas reproduces that (br-frankenpandas-unz0t):
24678        // both entries are normalized to their pandas object-string form rather
24679        // than coercing the naive one to Datetime64 (which contradicted both
24680        // pandas and conformance fixture FP-P2D-mixed-timezone).
24681        let input = "ts,value\n2024-01-15 10:30:00,1\n2024-01-15T10:30:00Z,2\n";
24682        let opts = CsvReadOptions {
24683            parse_dates: Some(vec!["ts".to_owned()]),
24684            ..Default::default()
24685        };
24686        let frame = read_csv_with_options(input, &opts).expect("parse");
24687        assert_eq!(
24688            frame.column("ts").unwrap().values(),
24689            &[
24690                Scalar::Utf8("2024-01-15 10:30:00".to_owned()),
24691                Scalar::Utf8("2024-01-15 10:30:00+00:00".to_owned()),
24692            ]
24693        );
24694        assert_eq!(
24695            frame.column("value").unwrap().values(),
24696            &[Scalar::Int64(1), Scalar::Int64(2)]
24697        );
24698    }
24699
24700    #[test]
24701    fn csv_parse_dates_fixed_naive_fast_path_accepts_only_safe_domain() {
24702        let values = vec![
24703            Scalar::Utf8("2024-01-15 10:30:00".to_owned()),
24704            Scalar::Utf8("2024-02-29".to_owned()),
24705            Scalar::Null(NullKind::NaT),
24706        ];
24707        let parsed = super::parse_csv_fixed_naive_datetime_values(&values).expect("fixed parse");
24708        assert_eq!(
24709            parsed,
24710            vec![
24711                Scalar::Datetime64(1_705_314_600_000_000_000),
24712                Scalar::Datetime64(1_709_164_800_000_000_000),
24713                Scalar::Datetime64(Timestamp::NAT),
24714            ]
24715        );
24716
24717        for rejected in [
24718            "2024-01-15T10:30:00Z",
24719            "2024-02-30",
24720            "2024-01-15 10:30:00.123",
24721        ] {
24722            assert!(
24723                super::parse_csv_fixed_naive_datetime_values(&[Scalar::Utf8(rejected.to_owned())])
24724                    .is_none(),
24725                "{rejected:?} must use the general parse_dates path"
24726            );
24727        }
24728    }
24729
24730    #[test]
24731    fn csv_parse_dates_raw_fast_path_preserves_na_semantics() {
24732        let input = "ts,value\nMISSING,1\n2024-01-15 10:30:00,2\n";
24733        let opts = CsvReadOptions {
24734            parse_dates: Some(vec!["ts".to_owned()]),
24735            na_values: vec!["MISSING".to_owned()],
24736            ..Default::default()
24737        };
24738        let frame = read_csv_with_options(input, &opts).expect("parse");
24739        assert_eq!(
24740            frame.column("ts").unwrap().values(),
24741            &[
24742                Scalar::Datetime64(Timestamp::NAT),
24743                Scalar::Datetime64(1_705_314_600_000_000_000),
24744            ]
24745        );
24746        assert_eq!(
24747            frame.column("value").unwrap().values(),
24748            &[Scalar::Int64(1), Scalar::Int64(2)]
24749        );
24750    }
24751
24752    #[test]
24753    fn csv_parse_dates_deferred_fallback_replays_scalar_inference() {
24754        let input = "ts,value\n2024-01-15 10:30:00,1\nnot-a-date,2\n";
24755        let opts = CsvReadOptions {
24756            parse_dates: Some(vec!["ts".to_owned()]),
24757            ..Default::default()
24758        };
24759        let frame = read_csv_with_options(input, &opts).expect("parse");
24760        assert_eq!(
24761            frame.column("ts").unwrap().values(),
24762            &[
24763                Scalar::Utf8("2024-01-15 10:30:00".to_owned()),
24764                Scalar::Utf8("not-a-date".to_owned()),
24765            ]
24766        );
24767
24768        let keep_na_literal = CsvReadOptions {
24769            parse_dates: Some(vec!["ts".to_owned()]),
24770            keep_default_na: false,
24771            ..Default::default()
24772        };
24773        let frame = read_csv_with_options("ts\nNA\n2024-01-15\n", &keep_na_literal).expect("parse");
24774        assert_eq!(
24775            frame.column("ts").unwrap().values(),
24776            &[
24777                Scalar::Utf8("NA".to_owned()),
24778                Scalar::Utf8("2024-01-15".to_owned()),
24779            ]
24780        );
24781    }
24782
24783    #[test]
24784    fn csv_parse_dates_deferred_mask_tracks_usecols_and_headerless() {
24785        let input = "2024-01-15 10:30:00,10\n2024-01-16 11:45:30,20\n";
24786        let opts = CsvReadOptions {
24787            has_headers: false,
24788            parse_dates: Some(vec!["column_0".to_owned()]),
24789            usecols: Some(vec!["column_0".to_owned()]),
24790            ..Default::default()
24791        };
24792        let frame = read_csv_with_options(input, &opts).expect("parse");
24793        assert_eq!(frame.column_names(), vec!["column_0"]);
24794        assert_eq!(
24795            frame.column("column_0").unwrap().values(),
24796            &[
24797                Scalar::Datetime64(1_705_314_600_000_000_000),
24798                Scalar::Datetime64(1_705_405_530_000_000_000),
24799            ]
24800        );
24801    }
24802
24803    #[test]
24804    fn csv_parse_dates_combined_columns_replaces_source_columns() {
24805        let input = "date,time,value\n2024-01-15,10:30:00,1\n2024-01-16,11:45:30,2\n";
24806        let opts = CsvReadOptions {
24807            parse_date_combinations: Some(vec![vec!["date".to_owned(), "time".to_owned()]]),
24808            ..Default::default()
24809        };
24810        let frame = read_csv_with_options(input, &opts).expect("parse");
24811        assert_eq!(frame.column_names(), vec!["date_time", "value"]);
24812        assert_eq!(
24813            frame.column("date_time").unwrap().values(),
24814            &[
24815                Scalar::Datetime64(1_705_314_600_000_000_000),
24816                Scalar::Datetime64(1_705_405_530_000_000_000),
24817            ]
24818        );
24819        assert!(frame.column("date").is_none());
24820        assert!(frame.column("time").is_none());
24821        assert_eq!(
24822            frame.column("value").unwrap().values(),
24823            &[Scalar::Int64(1), Scalar::Int64(2)]
24824        );
24825    }
24826
24827    #[test]
24828    fn csv_parse_date_combinations_named_uses_caller_supplied_name() {
24829        let input = "date,time,value\n2024-01-15,10:30:00,1\n2024-01-16,11:45:30,2\n";
24830        let opts = CsvReadOptions {
24831            parse_date_combinations_named: Some(vec![(
24832                "timestamp".to_owned(),
24833                vec!["date".to_owned(), "time".to_owned()],
24834            )]),
24835            ..Default::default()
24836        };
24837        let frame = read_csv_with_options(input, &opts).expect("parse");
24838        // Dict-style rename: combined column named "timestamp" rather than
24839        // the default underscore-joined "date_time".
24840        assert_eq!(frame.column_names(), vec!["timestamp", "value"]);
24841        assert!(frame.column("date").is_none());
24842        assert!(frame.column("time").is_none());
24843        assert_eq!(
24844            frame.column("timestamp").unwrap().values(),
24845            &[
24846                Scalar::Datetime64(1_705_314_600_000_000_000),
24847                Scalar::Datetime64(1_705_405_530_000_000_000),
24848            ]
24849        );
24850    }
24851
24852    #[test]
24853    fn csv_parse_date_combinations_named_multiple_groups() {
24854        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";
24855        let opts = CsvReadOptions {
24856            parse_date_combinations_named: Some(vec![
24857                ("start".to_owned(), vec!["d1".to_owned(), "t1".to_owned()]),
24858                ("end".to_owned(), vec!["d2".to_owned(), "t2".to_owned()]),
24859            ]),
24860            ..Default::default()
24861        };
24862        let frame = read_csv_with_options(input, &opts).expect("parse");
24863        let names = frame.column_names();
24864        assert!(names.iter().any(|n| n.as_str() == "start"));
24865        assert!(names.iter().any(|n| n.as_str() == "end"));
24866        assert!(!names.iter().any(|n| n.as_str() == "d1"));
24867        assert!(!names.iter().any(|n| n.as_str() == "t2"));
24868        assert_eq!(
24869            frame.column("value").unwrap().values(),
24870            &[Scalar::Int64(10), Scalar::Int64(20)]
24871        );
24872        assert_eq!(
24873            frame.column("start").unwrap().values(),
24874            &[
24875                Scalar::Datetime64(1_704_099_600_000_000_000),
24876                Scalar::Datetime64(1_706_778_000_000_000_000),
24877            ]
24878        );
24879    }
24880
24881    #[test]
24882    fn csv_parse_date_combinations_named_rejects_duplicate_output_names() {
24883        let input = "a,b,c,d\n2024,01,2024,02\n";
24884        let opts = CsvReadOptions {
24885            parse_date_combinations_named: Some(vec![
24886                ("ts".to_owned(), vec!["a".to_owned(), "b".to_owned()]),
24887                ("ts".to_owned(), vec!["c".to_owned(), "d".to_owned()]),
24888            ]),
24889            ..Default::default()
24890        };
24891        let err = read_csv_with_options(input, &opts).unwrap_err();
24892        assert!(matches!(err, IoError::DuplicateColumnName(name) if name == "ts"));
24893    }
24894
24895    #[test]
24896    fn csv_parse_date_combinations_named_rejects_missing_source_column() {
24897        let input = "date,time,value\n2024-01-01,09:00:00,1\n";
24898        let opts = CsvReadOptions {
24899            parse_date_combinations_named: Some(vec![(
24900                "ts".to_owned(),
24901                vec!["date".to_owned(), "missing".to_owned()],
24902            )]),
24903            ..Default::default()
24904        };
24905        let err = read_csv_with_options(input, &opts).unwrap_err();
24906        assert!(matches!(err, IoError::MissingParseDateColumns(_)));
24907    }
24908
24909    #[test]
24910    fn csv_parse_date_combinations_named_empty_sources_skipped() {
24911        let input = "a,b\n1,2\n";
24912        let opts = CsvReadOptions {
24913            parse_date_combinations_named: Some(vec![("unused".to_owned(), Vec::new())]),
24914            ..Default::default()
24915        };
24916        let frame = read_csv_with_options(input, &opts).expect("parse");
24917        // Empty source list is a no-op; original columns remain.
24918        assert_eq!(frame.column_names(), vec!["a", "b"]);
24919    }
24920
24921    // ── JSONL tests (frankenpandas-sue) ──────────────────────────────
24922
24923    #[test]
24924    fn jsonl_write_read_roundtrip() {
24925        let frame = make_test_dataframe();
24926        let jsonl = super::write_jsonl_string(&frame).expect("JSONL write failed");
24927
24928        // Each line should be a valid JSON object.
24929        let line_count = jsonl.lines().count();
24930        assert_eq!(line_count, 3, "3 rows = 3 lines");
24931
24932        let back = super::read_jsonl_str(&jsonl).expect("JSONL read failed");
24933        assert_eq!(back.index().len(), 3);
24934        assert_eq!(back.column("ints").unwrap().values()[0], Scalar::Int64(10));
24935        assert_eq!(
24936            back.column("names").unwrap().values()[2],
24937            Scalar::Utf8("carol".into())
24938        );
24939    }
24940
24941    #[test]
24942    fn jsonl_preserves_column_order() {
24943        let input = r#"
24944{"b":1,"a":2}
24945{"c":3}
24946"#;
24947        let frame = super::read_jsonl_str(input).expect("JSONL read failed");
24948        let order: Vec<&str> = frame
24949            .column_names()
24950            .iter()
24951            .map(|name| name.as_str())
24952            .collect();
24953        assert_eq!(order, vec!["b", "a", "c"]);
24954    }
24955
24956    #[test]
24957    fn jsonl_each_line_is_valid_json() {
24958        let frame = make_test_dataframe();
24959        let jsonl = super::write_jsonl_string(&frame).unwrap();
24960
24961        for (i, line) in jsonl.lines().enumerate() {
24962            let parsed: serde_json::Value =
24963                serde_json::from_str(line).expect("jsonl line must be valid JSON");
24964            assert!(parsed.is_object(), "line {i} must be a JSON object");
24965        }
24966    }
24967
24968    #[test]
24969    fn jsonl_with_nulls() {
24970        use fp_types::DType;
24971
24972        let mut columns = BTreeMap::new();
24973        columns.insert(
24974            "v".to_string(),
24975            Column::new(
24976                DType::Float64,
24977                vec![
24978                    Scalar::Float64(1.0),
24979                    Scalar::Null(NullKind::NaN),
24980                    Scalar::Float64(3.0),
24981                ],
24982            )
24983            .unwrap(),
24984        );
24985        let labels = vec![
24986            IndexLabel::Int64(0),
24987            IndexLabel::Int64(1),
24988            IndexLabel::Int64(2),
24989        ];
24990        let frame =
24991            DataFrame::new_with_column_order(Index::new(labels), columns, vec!["v".to_string()])
24992                .unwrap();
24993
24994        let jsonl = super::write_jsonl_string(&frame).unwrap();
24995        let back = super::read_jsonl_str(&jsonl).unwrap();
24996        assert!(back.column("v").unwrap().values()[1].is_missing());
24997    }
24998
24999    #[test]
25000    fn jsonl_records_write_preserves_nullable_int_column() {
25001        // DISC-011: Nullable extension Int64 dtype parity - Int64 preserved, not promoted to Float64.
25002        let frame = DataFrame::from_dict(
25003            &["a"],
25004            vec![("a", vec![Scalar::Int64(1), Scalar::Null(NullKind::Null)])],
25005        )
25006        .unwrap();
25007
25008        let jsonl = super::write_jsonl_string(&frame).expect("write jsonl");
25009        let rows = jsonl
25010            .lines()
25011            .map(|line| serde_json::from_str::<serde_json::Value>(line).unwrap())
25012            .collect::<Vec<_>>();
25013
25014        assert_eq!(
25015            rows,
25016            vec![serde_json::json!({"a": 1}), serde_json::json!({"a": null})]
25017        );
25018    }
25019
25020    #[test]
25021    fn jsonl_empty_input() {
25022        let back = super::read_jsonl_str("").expect("empty JSONL must parse");
25023        assert_eq!(back.index().len(), 0);
25024    }
25025
25026    #[test]
25027    fn jsonl_blank_lines_skipped() {
25028        let input = "{\"a\":1}\n\n{\"a\":2}\n\n";
25029        let back = super::read_jsonl_str(input).expect("JSONL with blanks must parse");
25030        assert_eq!(back.index().len(), 2);
25031    }
25032
25033    #[test]
25034    fn jsonl_non_object_line_errors() {
25035        let input = "{\"a\":1}\n[1,2,3]\n";
25036        let err = super::read_jsonl_str(input);
25037        assert!(err.is_err());
25038    }
25039
25040    #[test]
25041    fn jsonl_different_keys_across_rows() {
25042        // Rows with different keys should produce union of all columns.
25043        let input = "{\"a\":1,\"b\":2}\n{\"a\":3,\"c\":4}\n";
25044        let frame = super::read_jsonl_str(input).expect("JSONL with different keys must parse");
25045        assert_eq!(frame.index().len(), 2);
25046        // Should have columns a, b, c (union of all keys).
25047        assert!(frame.column("a").is_some(), "column a must exist");
25048        assert!(frame.column("b").is_some(), "column b must exist");
25049        assert!(frame.column("c").is_some(), "column c must exist");
25050        // Row 0: a=1, b=2, c=null.
25051        assert_eq!(frame.column("a").unwrap().values()[0], Scalar::Int64(1));
25052        assert_eq!(frame.column("b").unwrap().values()[0], Scalar::Float64(2.0));
25053        assert!(frame.column("c").unwrap().values()[0].is_missing());
25054        // Row 1: a=3, b=null, c=4.
25055        assert_eq!(frame.column("a").unwrap().values()[1], Scalar::Int64(3));
25056        assert!(frame.column("b").unwrap().values()[1].is_missing());
25057        assert_eq!(frame.column("c").unwrap().values()[1], Scalar::Float64(4.0));
25058    }
25059
25060    #[test]
25061    fn adversarial_csv_very_long_field() {
25062        // A single field with >100K characters should parse without panic.
25063        let long_val = "x".repeat(200_000);
25064        let input = format!("col\n{long_val}\n");
25065        let frame = read_csv_str(&input).expect("long field must parse");
25066        assert_eq!(frame.index().len(), 1);
25067        match &frame.column("col").unwrap().values()[0] {
25068            Scalar::Utf8(s) => assert_eq!(s.len(), 200_000),
25069            other => assert!(
25070                matches!(other, Scalar::Utf8(_)),
25071                "expected Utf8 for long field"
25072            ),
25073        }
25074    }
25075
25076    #[test]
25077    fn adversarial_csv_many_columns() {
25078        // CSV with 1000 columns should parse correctly.
25079        let ncols = 1000;
25080        let headers: Vec<String> = (0..ncols).map(|i| format!("c{i}")).collect();
25081        let mut csv = headers.join(",");
25082        csv.push('\n');
25083        let vals: Vec<String> = (0..ncols).map(|i| i.to_string()).collect();
25084        csv.push_str(&vals.join(","));
25085        csv.push('\n');
25086
25087        let frame = read_csv_str(&csv).expect("1000-column CSV must parse");
25088        assert_eq!(frame.columns().len(), ncols);
25089        assert_eq!(frame.index().len(), 1);
25090    }
25091
25092    #[test]
25093    fn adversarial_csv_empty_rows() {
25094        // CSV with empty rows between data should handle gracefully.
25095        // The csv crate skips truly empty records, but rows with the right
25096        // number of empty fields produce null values.
25097        let input = "a,b\n1,2\n,\n3,4\n";
25098        let frame = read_csv_str(input).expect("parse");
25099        assert_eq!(frame.index().len(), 3);
25100        // Row 1 (index 1) has empty fields → null
25101        assert!(frame.column("a").unwrap().values()[1].is_missing());
25102    }
25103
25104    #[test]
25105    fn adversarial_csv_field_with_newlines_in_quotes() {
25106        // Embedded newlines in quoted fields must not break row boundaries.
25107        let input = "msg\n\"line1\nline2\nline3\"\n\"single\"\n";
25108        let frame = read_csv_str(input).expect("quoted newlines must parse");
25109        assert_eq!(frame.index().len(), 2);
25110    }
25111
25112    #[test]
25113    fn adversarial_csv_header_only_no_data() {
25114        let input = "x,y,z\n";
25115        let frame = read_csv_str(input).expect("header-only must parse");
25116        assert_eq!(frame.index().len(), 0);
25117        assert_eq!(frame.columns().len(), 3);
25118    }
25119
25120    #[test]
25121    fn adversarial_json_deeply_nested_values() {
25122        // JSON with nested objects as values should store them as strings.
25123        let input = r#"[{"a":1,"b":{"nested":"value"}}]"#;
25124        let frame = read_json_str(input, JsonOrient::Records).expect("nested JSON must parse");
25125        assert_eq!(frame.index().len(), 1);
25126        // The nested object becomes a Utf8 representation.
25127        let b_val = &frame.column("b").unwrap().values()[0];
25128        assert!(matches!(b_val, Scalar::Utf8(_)));
25129    }
25130
25131    #[test]
25132    fn adversarial_json_i64_max_value() {
25133        // JSON with values at i64 boundary.
25134        let input = format!(r#"[{{"v":{}}}]"#, i64::MAX);
25135        let frame = read_json_str(&input, JsonOrient::Records).expect("i64::MAX must parse");
25136        assert_eq!(
25137            frame.column("v").unwrap().values()[0],
25138            Scalar::Int64(i64::MAX)
25139        );
25140    }
25141
25142    #[test]
25143    fn adversarial_json_i64_min_value() {
25144        let input = format!(r#"[{{"v":{}}}]"#, i64::MIN);
25145        let frame = read_json_str(&input, JsonOrient::Records).expect("i64::MIN must parse");
25146        assert_eq!(
25147            frame.column("v").unwrap().values()[0],
25148            Scalar::Int64(i64::MIN)
25149        );
25150    }
25151
25152    #[test]
25153    fn adversarial_json_float_special_values() {
25154        // JSON doesn't natively support Infinity/NaN, but we should handle
25155        // null gracefully.
25156        let input = r#"[{"v":null},{"v":1.7976931348623157e+308}]"#;
25157        let frame = read_json_str(input, JsonOrient::Records).expect("special floats must parse");
25158        assert!(frame.column("v").unwrap().values()[0].is_missing());
25159        // f64::MAX is approximately 1.7976931348623157e+308
25160        if let Scalar::Float64(v) = frame.column("v").unwrap().values()[1] {
25161            assert!(v.is_finite());
25162        }
25163    }
25164
25165    #[test]
25166    fn adversarial_json_empty_records_array() {
25167        let input = r#"[]"#;
25168        let frame = read_json_str(input, JsonOrient::Records).expect("empty array must parse");
25169        assert_eq!(frame.index().len(), 0);
25170    }
25171
25172    #[test]
25173    fn adversarial_json_empty_columns_object() {
25174        let input = r#"{}"#;
25175        let frame = read_json_str(input, JsonOrient::Columns).expect("empty object must parse");
25176        assert_eq!(frame.index().len(), 0);
25177        assert_eq!(frame.columns().len(), 0);
25178    }
25179
25180    #[test]
25181    fn adversarial_csv_unicode_values() {
25182        // CSV with multi-byte UTF-8 characters in values.
25183        let input = "name,emoji\n日本語,🎉\nрусский,🚀\n";
25184        let frame = read_csv_str(input).expect("unicode CSV must parse");
25185        assert_eq!(frame.index().len(), 2);
25186        assert_eq!(
25187            frame.column("name").unwrap().values()[0],
25188            Scalar::Utf8("日本語".into())
25189        );
25190        assert_eq!(
25191            frame.column("emoji").unwrap().values()[1],
25192            Scalar::Utf8("🚀".into())
25193        );
25194    }
25195
25196    #[test]
25197    fn adversarial_csv_single_column_no_trailing_newline() {
25198        let input = "val\n42";
25199        let frame = read_csv_str(input).expect("no trailing newline must parse");
25200        assert_eq!(frame.index().len(), 1);
25201        assert_eq!(frame.column("val").unwrap().values()[0], Scalar::Int64(42));
25202    }
25203
25204    #[cfg(feature = "sql-sqlite")]
25205    #[test]
25206    fn adversarial_sql_large_batch_insert() {
25207        // Insert 10K rows in a single write_sql call.
25208        let n = 10_000;
25209        let vals: Vec<Scalar> = (0..n).map(|i| Scalar::Int64(i as i64)).collect();
25210        let df = fp_frame::DataFrame::from_dict(&["x"], vec![("x", vals)]).unwrap();
25211
25212        let conn = make_sql_test_conn();
25213        write_sql(&df, &conn, "big_table", SqlIfExists::Fail).unwrap();
25214        let back = read_sql_table(&conn, "big_table").unwrap();
25215        assert_eq!(back.index().len(), n);
25216        assert_eq!(
25217            back.column("x").unwrap().values()[n - 1],
25218            Scalar::Int64((n - 1) as i64)
25219        );
25220    }
25221
25222    #[cfg(feature = "sql-sqlite")]
25223    #[test]
25224    fn adversarial_sql_column_name_with_spaces_accepted() {
25225        // Column names with spaces are valid in SQL (quoted identifiers).
25226        // Table names are restricted, but column names go through quoting.
25227        let df = fp_frame::DataFrame::from_dict(
25228            &["has space"],
25229            vec![("has space", vec![Scalar::Int64(1)])],
25230        )
25231        .unwrap();
25232
25233        let conn = make_sql_test_conn();
25234        // This should work since column names are quoted.
25235        let result = write_sql(&df, &conn, "test_spaces", SqlIfExists::Fail);
25236        assert!(
25237            result.is_ok(),
25238            "columns with spaces should work: {:?}",
25239            result.err()
25240        );
25241
25242        let back = read_sql_table(&conn, "test_spaces").unwrap();
25243        assert!(back.column("has space").is_some());
25244    }
25245
25246    #[cfg(feature = "sql-sqlite")]
25247    #[test]
25248    fn adversarial_sql_column_name_with_quotes_accepted() {
25249        let col_name = "has\"quote";
25250        let df =
25251            fp_frame::DataFrame::from_dict(&[col_name], vec![(col_name, vec![Scalar::Int64(7)])])
25252                .unwrap();
25253
25254        let conn = make_sql_test_conn();
25255        let result = write_sql(&df, &conn, "test_quotes", SqlIfExists::Fail);
25256        assert!(
25257            result.is_ok(),
25258            "columns with quotes should work: {:?}",
25259            result.err()
25260        );
25261
25262        let back = read_sql_table(&conn, "test_quotes").unwrap();
25263        assert_eq!(back.column(col_name).unwrap().values()[0], Scalar::Int64(7));
25264    }
25265
25266    // ── SqlConnection capability + dialect probes (br-frankenpandas-6dtf) ────
25267
25268    #[cfg(feature = "sql-sqlite")]
25269    #[test]
25270    fn rusqlite_dialect_name_is_sqlite() {
25271        let conn = make_sql_test_conn();
25272        assert_eq!(super::SqlConnection::dialect_name(&conn), "sqlite");
25273    }
25274
25275    #[cfg(feature = "sql-sqlite")]
25276    #[test]
25277    fn rusqlite_supports_returning_is_true() {
25278        // Bundled SQLite is 3.35+, so RETURNING is supported.
25279        let conn = make_sql_test_conn();
25280        assert!(super::SqlConnection::supports_returning(&conn));
25281    }
25282
25283    #[cfg(feature = "sql-sqlite")]
25284    #[test]
25285    fn rusqlite_max_param_count_is_32766() {
25286        let conn = make_sql_test_conn();
25287        assert_eq!(super::SqlConnection::max_param_count(&conn), Some(32766));
25288    }
25289
25290    #[cfg(feature = "sql-sqlite")]
25291    #[test]
25292    fn rusqlite_with_transaction_commits_on_ok() {
25293        let conn = make_sql_test_conn();
25294        super::SqlConnection::execute_batch(&conn, "CREATE TABLE txn_test (x INTEGER)").unwrap();
25295        let result: Result<i64, IoError> = super::SqlConnection::with_transaction(&conn, |c| {
25296            super::SqlConnection::execute_batch(c, "INSERT INTO txn_test VALUES (42)")?;
25297            Ok(42)
25298        });
25299        assert_eq!(result.unwrap(), 42);
25300        // Verify the row committed.
25301        let row_count =
25302            super::SqlConnection::query(&conn, "SELECT COUNT(*) FROM txn_test", &[]).unwrap();
25303        assert_eq!(row_count.rows.len(), 1);
25304        assert_eq!(row_count.rows[0][0], Scalar::Int64(1));
25305    }
25306
25307    #[cfg(feature = "sql-sqlite")]
25308    #[test]
25309    fn rusqlite_with_transaction_rolls_back_on_err() {
25310        let conn = make_sql_test_conn();
25311        super::SqlConnection::execute_batch(&conn, "CREATE TABLE txn_rollback (x INTEGER)")
25312            .unwrap();
25313        let result: Result<(), IoError> = super::SqlConnection::with_transaction(&conn, |c| {
25314            super::SqlConnection::execute_batch(c, "INSERT INTO txn_rollback VALUES (99)")?;
25315            Err(IoError::Sql("simulated failure".to_string()))
25316        });
25317        assert!(result.is_err());
25318        // Row should NOT have committed.
25319        let row_count =
25320            super::SqlConnection::query(&conn, "SELECT COUNT(*) FROM txn_rollback", &[]).unwrap();
25321        assert_eq!(row_count.rows[0][0], Scalar::Int64(0));
25322    }
25323
25324    #[cfg(feature = "sql-sqlite")]
25325    #[test]
25326    fn rusqlite_with_transaction_rolls_back_on_panic() {
25327        let conn = make_sql_test_conn();
25328        super::SqlConnection::execute_batch(&conn, "CREATE TABLE txn_panic (x INTEGER)").unwrap();
25329
25330        let panic_result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
25331            let _: Result<(), IoError> = super::SqlConnection::with_transaction(&conn, |c| {
25332                super::SqlConnection::execute_batch(c, "INSERT INTO txn_panic VALUES (99)")?;
25333                std::panic::resume_unwind(Box::new("simulated transaction panic"));
25334            });
25335        }));
25336        assert!(panic_result.is_err());
25337
25338        let row_count =
25339            super::SqlConnection::query(&conn, "SELECT COUNT(*) FROM txn_panic", &[]).unwrap();
25340        assert_eq!(row_count.rows[0][0], Scalar::Int64(0));
25341
25342        let result: Result<(), IoError> = super::SqlConnection::with_transaction(&conn, |c| {
25343            super::SqlConnection::execute_batch(c, "INSERT INTO txn_panic VALUES (7)")
25344        });
25345        assert!(result.is_ok());
25346        let rows =
25347            super::SqlConnection::query(&conn, "SELECT x FROM txn_panic ORDER BY x", &[]).unwrap();
25348        assert_eq!(rows.rows, vec![vec![Scalar::Int64(7)]]);
25349    }
25350
25351    #[test]
25352    fn default_capability_probes_are_conservative() {
25353        // A test-double SqlConnection that doesn't override defaults
25354        // should report the conservative-default values from the trait.
25355        struct StubSql;
25356        impl super::SqlConnection for StubSql {
25357            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<super::SqlQueryResult, IoError> {
25358                Ok(super::SqlQueryResult {
25359                    columns: vec![],
25360                    rows: vec![],
25361                })
25362            }
25363            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
25364                Ok(())
25365            }
25366            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
25367                Ok(false)
25368            }
25369            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
25370                Ok(())
25371            }
25372            fn dtype_sql(&self, _dtype: DType) -> &'static str {
25373                "TEXT"
25374            }
25375            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
25376                "TEXT"
25377            }
25378        }
25379
25380        let stub = StubSql;
25381        assert_eq!(super::SqlConnection::dialect_name(&stub), "unknown");
25382        assert!(!super::SqlConnection::supports_returning(&stub));
25383        assert_eq!(super::SqlConnection::max_param_count(&stub), None);
25384        // Default with_transaction passes through (no BEGIN/COMMIT).
25385        let result: Result<i64, IoError> = super::SqlConnection::with_transaction(&stub, |_| Ok(7));
25386        assert_eq!(result.unwrap(), 7);
25387        // Default quote_identifier produces ANSI double-quotes.
25388        assert_eq!(
25389            super::SqlConnection::quote_identifier(&stub, "col").unwrap(),
25390            r#""col""#
25391        );
25392    }
25393
25394    // ── quote_identifier tests (br-frankenpandas-2y7w / fd90.10) ────────
25395
25396    #[cfg(feature = "sql-sqlite")]
25397    #[test]
25398    fn rusqlite_quote_identifier_uses_ansi_double_quotes() {
25399        let conn = make_sql_test_conn();
25400        assert_eq!(
25401            super::SqlConnection::quote_identifier(&conn, "users").unwrap(),
25402            r#""users""#
25403        );
25404    }
25405
25406    #[cfg(feature = "sql-sqlite")]
25407    #[test]
25408    fn rusqlite_quote_identifier_doubles_embedded_quotes() {
25409        let conn = make_sql_test_conn();
25410        // Identifier containing a `"` must be escaped by doubling the quote.
25411        assert_eq!(
25412            super::SqlConnection::quote_identifier(&conn, r#"value"raw"#).unwrap(),
25413            r#""value""raw""#
25414        );
25415    }
25416
25417    #[cfg(feature = "sql-sqlite")]
25418    #[test]
25419    fn rusqlite_quote_identifier_rejects_null_bytes() {
25420        let conn = make_sql_test_conn();
25421        let err = super::SqlConnection::quote_identifier(&conn, "evil\0name").expect_err("nul");
25422        assert!(matches!(err, IoError::Sql(_)));
25423    }
25424
25425    #[test]
25426    fn default_quote_identifier_doubles_embedded_quotes() {
25427        // Verify the default impl on a non-overriding stub matches the
25428        // SQLite behavior (ANSI is the shared default for SQLite + Postgres).
25429        struct StubSql;
25430        impl super::SqlConnection for StubSql {
25431            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<super::SqlQueryResult, IoError> {
25432                Ok(super::SqlQueryResult {
25433                    columns: vec![],
25434                    rows: vec![],
25435                })
25436            }
25437            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
25438                Ok(())
25439            }
25440            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
25441                Ok(false)
25442            }
25443            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
25444                Ok(())
25445            }
25446            fn dtype_sql(&self, _dtype: DType) -> &'static str {
25447                "TEXT"
25448            }
25449            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
25450                "TEXT"
25451            }
25452        }
25453        let stub = StubSql;
25454        assert_eq!(
25455            super::SqlConnection::quote_identifier(&stub, r#"value"raw"#).unwrap(),
25456            r#""value""raw""#
25457        );
25458        assert!(super::SqlConnection::quote_identifier(&stub, "evil\0").is_err());
25459    }
25460
25461    // ── SqlReadOptions::dtype tests (br-frankenpandas-l9pt / fd90.11) ───
25462
25463    #[cfg(feature = "sql-sqlite")]
25464    #[test]
25465    fn read_sql_dtype_override_int_to_float() {
25466        let conn = make_sql_test_conn();
25467        super::SqlConnection::execute_batch(
25468            &conn,
25469            "CREATE TABLE amounts (amount INTEGER); INSERT INTO amounts VALUES (1), (2), (3);",
25470        )
25471        .unwrap();
25472        let mut dtype_map = BTreeMap::new();
25473        dtype_map.insert("amount".to_owned(), DType::Float64);
25474        let frame = read_sql_with_options(
25475            &conn,
25476            "SELECT amount FROM amounts ORDER BY amount",
25477            &SqlReadOptions {
25478                params: None,
25479                parse_dates: None,
25480                coerce_float: false,
25481                dtype: Some(dtype_map),
25482                schema: None,
25483                columns: None,
25484                index_col: None,
25485            },
25486        )
25487        .expect("read with dtype");
25488        let col = frame.column("amount").expect("amount");
25489        assert_eq!(col.dtype(), DType::Float64);
25490        assert_eq!(col.values()[0], Scalar::Float64(1.0));
25491        assert_eq!(col.values()[2], Scalar::Float64(3.0));
25492    }
25493
25494    #[cfg(feature = "sql-sqlite")]
25495    #[test]
25496    fn read_sql_dtype_override_unsupported_cast_returns_typed_error() {
25497        // This test asserts that when a dtype override cast is unsupported,
25498        // SQL IO surfaces a typed IoError::Sql with diagnostic context, NOT a
25499        // panic and not a silent skip.
25500        let conn = make_sql_test_conn();
25501        super::SqlConnection::execute_batch(
25502            &conn,
25503            "CREATE TABLE labels (id TEXT); INSERT INTO labels VALUES ('yes'), ('no');",
25504        )
25505        .unwrap();
25506        let mut dtype_map = BTreeMap::new();
25507        dtype_map.insert("id".to_owned(), DType::Bool);
25508        let err = read_sql_with_options(
25509            &conn,
25510            "SELECT id FROM labels ORDER BY id",
25511            &SqlReadOptions {
25512                params: None,
25513                parse_dates: None,
25514                coerce_float: false,
25515                dtype: Some(dtype_map),
25516                schema: None,
25517                columns: None,
25518                index_col: None,
25519            },
25520        )
25521        .expect_err("expected dtype override error");
25522        match err {
25523            IoError::Sql(message) => {
25524                assert!(
25525                    message.contains("dtype override on column 'id'"),
25526                    "unexpected error message: {message}"
25527                );
25528                assert!(
25529                    message.contains("Bool"),
25530                    "unexpected error message: {message}"
25531                );
25532            }
25533            other => unreachable!("expected IoError::Sql, got {other:?}"),
25534        }
25535    }
25536
25537    #[cfg(feature = "sql-sqlite")]
25538    #[test]
25539    fn read_sql_dtype_override_missing_column_is_ignored() {
25540        let conn = make_sql_test_conn();
25541        super::SqlConnection::execute_batch(
25542            &conn,
25543            "CREATE TABLE t (x INTEGER); INSERT INTO t VALUES (1);",
25544        )
25545        .unwrap();
25546        let mut dtype_map = BTreeMap::new();
25547        dtype_map.insert("nonexistent".to_owned(), DType::Float64);
25548        let frame = read_sql_with_options(
25549            &conn,
25550            "SELECT x FROM t",
25551            &SqlReadOptions {
25552                params: None,
25553                parse_dates: None,
25554                coerce_float: false,
25555                dtype: Some(dtype_map),
25556                schema: None,
25557                columns: None,
25558                index_col: None,
25559            },
25560        )
25561        .expect("read with dtype-on-missing-col");
25562        let col = frame.column("x").expect("x");
25563        assert_eq!(col.dtype(), DType::Int64);
25564    }
25565
25566    #[cfg(feature = "sql-sqlite")]
25567    #[test]
25568    fn read_sql_dtype_override_preserves_nulls() {
25569        let conn = make_sql_test_conn();
25570        super::SqlConnection::execute_batch(
25571            &conn,
25572            "CREATE TABLE nulls_tbl (v INTEGER); INSERT INTO nulls_tbl VALUES (1), (NULL), (3);",
25573        )
25574        .unwrap();
25575        let mut dtype_map = BTreeMap::new();
25576        dtype_map.insert("v".to_owned(), DType::Float64);
25577        let frame = read_sql_with_options(
25578            &conn,
25579            "SELECT v FROM nulls_tbl ORDER BY rowid",
25580            &SqlReadOptions {
25581                params: None,
25582                parse_dates: None,
25583                coerce_float: false,
25584                dtype: Some(dtype_map),
25585                schema: None,
25586                columns: None,
25587                index_col: None,
25588            },
25589        )
25590        .expect("read with dtype + nulls");
25591        let col = frame.column("v").expect("v");
25592        assert_eq!(col.dtype(), DType::Float64);
25593        assert!(col.values()[1].is_missing());
25594    }
25595
25596    #[cfg(feature = "sql-sqlite")]
25597    #[test]
25598    fn read_sql_dtype_skipped_when_column_in_parse_dates() {
25599        let conn = make_sql_test_conn();
25600        super::SqlConnection::execute_batch(
25601            &conn,
25602            "CREATE TABLE evt (ts TEXT); INSERT INTO evt VALUES ('2024-01-01 00:00:00');",
25603        )
25604        .unwrap();
25605        let mut dtype_map = BTreeMap::new();
25606        dtype_map.insert("ts".to_owned(), DType::Float64);
25607        let frame = read_sql_with_options(
25608            &conn,
25609            "SELECT ts FROM evt",
25610            &SqlReadOptions {
25611                params: None,
25612                parse_dates: Some(vec!["ts".to_owned()]),
25613                coerce_float: false,
25614                dtype: Some(dtype_map),
25615                schema: None,
25616                columns: None,
25617                index_col: None,
25618            },
25619        )
25620        .expect("read with parse_dates priority");
25621        let col = frame.column("ts").expect("ts");
25622        // parse_dates wins over the dtype override and yields typed
25623        // Datetime64[ns] (br-frankenpandas-0ezw7).
25624        assert_eq!(col.dtype(), DType::Datetime64);
25625    }
25626
25627    // ── Schema probes (br-frankenpandas-6dk9 / fd90.13) ─────────────────
25628
25629    #[cfg(feature = "sql-sqlite")]
25630    #[test]
25631    fn rusqlite_does_not_support_schemas_by_default() {
25632        let conn = make_sql_test_conn();
25633        assert!(!super::SqlConnection::supports_schemas(&conn));
25634        assert_eq!(super::SqlConnection::default_schema(&conn), None);
25635    }
25636
25637    #[test]
25638    fn default_schema_probes_are_conservative() {
25639        // A test-double with no schema overrides reports the conservative
25640        // single-namespace defaults (matches SQLite + most embedded
25641        // backends). Production multi-schema backends (PG, MySQL) override.
25642        struct StubSql;
25643        impl super::SqlConnection for StubSql {
25644            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<super::SqlQueryResult, IoError> {
25645                Ok(super::SqlQueryResult {
25646                    columns: vec![],
25647                    rows: vec![],
25648                })
25649            }
25650            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
25651                Ok(())
25652            }
25653            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
25654                Ok(false)
25655            }
25656            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
25657                Ok(())
25658            }
25659            fn dtype_sql(&self, _dtype: DType) -> &'static str {
25660                "TEXT"
25661            }
25662            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
25663                "TEXT"
25664            }
25665        }
25666        let stub = StubSql;
25667        assert!(!super::SqlConnection::supports_schemas(&stub));
25668        assert_eq!(super::SqlConnection::default_schema(&stub), None);
25669    }
25670
25671    #[test]
25672    fn schema_probe_overrides_take_effect() {
25673        // A multi-schema-style test backend (e.g. simulating PostgreSQL)
25674        // overrides supports_schemas + default_schema. The overrides MUST
25675        // win over the trait defaults.
25676        struct PgLikeSqlConn;
25677        impl super::SqlConnection for PgLikeSqlConn {
25678            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<super::SqlQueryResult, IoError> {
25679                Ok(super::SqlQueryResult {
25680                    columns: vec![],
25681                    rows: vec![],
25682                })
25683            }
25684            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
25685                Ok(())
25686            }
25687            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
25688                Ok(false)
25689            }
25690            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
25691                Ok(())
25692            }
25693            fn dtype_sql(&self, _dtype: DType) -> &'static str {
25694                "TEXT"
25695            }
25696            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
25697                "TEXT"
25698            }
25699            fn supports_schemas(&self) -> bool {
25700                true
25701            }
25702            fn default_schema(&self) -> Option<String> {
25703                Some("public".to_owned())
25704            }
25705        }
25706        let conn = PgLikeSqlConn;
25707        assert!(super::SqlConnection::supports_schemas(&conn));
25708        assert_eq!(
25709            super::SqlConnection::default_schema(&conn).as_deref(),
25710            Some("public")
25711        );
25712    }
25713
25714    // ── SqlReadOptions::schema tests (br-frankenpandas-u6zn / fd90.14) ──
25715
25716    #[test]
25717    fn sql_select_all_query_no_schema_uses_bare_table() {
25718        struct StubSql;
25719        impl super::SqlConnection for StubSql {
25720            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<super::SqlQueryResult, IoError> {
25721                Ok(super::SqlQueryResult {
25722                    columns: vec![],
25723                    rows: vec![],
25724                })
25725            }
25726            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
25727                Ok(())
25728            }
25729            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
25730                Ok(false)
25731            }
25732            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
25733                Ok(())
25734            }
25735            fn dtype_sql(&self, _dtype: DType) -> &'static str {
25736                "TEXT"
25737            }
25738            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
25739                "TEXT"
25740            }
25741        }
25742        let conn = StubSql;
25743        let q1 = super::sql_select_all_query_in_schema(&conn, "users", None).expect("q1");
25744        assert_eq!(q1, "SELECT * FROM \"users\"");
25745    }
25746
25747    #[test]
25748    fn sql_select_query_with_schema_rejects_non_schema_backend() {
25749        struct StubSql;
25750        impl super::SqlConnection for StubSql {
25751            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<super::SqlQueryResult, IoError> {
25752                Ok(super::SqlQueryResult {
25753                    columns: vec![],
25754                    rows: vec![],
25755                })
25756            }
25757            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
25758                Ok(())
25759            }
25760            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
25761                Ok(false)
25762            }
25763            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
25764                Ok(())
25765            }
25766            fn dtype_sql(&self, _dtype: DType) -> &'static str {
25767                "TEXT"
25768            }
25769            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
25770                "TEXT"
25771            }
25772            fn dialect_name(&self) -> &'static str {
25773                "stub"
25774            }
25775        }
25776        let conn = StubSql;
25777        let err = super::sql_select_all_query_in_schema(&conn, "users", Some("analytics"))
25778            .expect_err("schema must reject when backend has no schema support");
25779        assert!(
25780            matches!(err, IoError::Sql(msg) if msg.contains("schema is not supported by stub backend"))
25781        );
25782
25783        let err =
25784            super::sql_select_columns_query_in_schema(&conn, "users", Some("analytics"), &["id"])
25785                .expect_err("projected schema select must reject too");
25786        assert!(
25787            matches!(err, IoError::Sql(msg) if msg.contains("schema is not supported by stub backend"))
25788        );
25789    }
25790
25791    #[test]
25792    fn sql_select_all_query_with_schema_qualifies_on_multi_schema_backend() {
25793        struct PgLikeSchemaSql;
25794        impl super::SqlConnection for PgLikeSchemaSql {
25795            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<super::SqlQueryResult, IoError> {
25796                Ok(super::SqlQueryResult {
25797                    columns: vec![],
25798                    rows: vec![],
25799                })
25800            }
25801            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
25802                Ok(())
25803            }
25804            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
25805                Ok(false)
25806            }
25807            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
25808                Ok(())
25809            }
25810            fn dtype_sql(&self, _dtype: DType) -> &'static str {
25811                "TEXT"
25812            }
25813            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
25814                "TEXT"
25815            }
25816            fn supports_schemas(&self) -> bool {
25817                true
25818            }
25819        }
25820        let conn = PgLikeSchemaSql;
25821        let q =
25822            super::sql_select_all_query_in_schema(&conn, "users", Some("analytics")).expect("q");
25823        assert_eq!(q, "SELECT * FROM \"analytics\".\"users\"");
25824        let bare = super::sql_select_all_query_in_schema(&conn, "users", None).expect("bare");
25825        assert_eq!(bare, "SELECT * FROM \"users\"");
25826    }
25827
25828    #[cfg(feature = "sql-sqlite")]
25829    #[test]
25830    fn read_sql_table_with_options_schema_rejected_on_sqlite() {
25831        let conn = make_sql_test_conn();
25832        super::SqlConnection::execute_batch(
25833            &conn,
25834            "CREATE TABLE bare_tbl (x INTEGER); INSERT INTO bare_tbl VALUES (1), (2);",
25835        )
25836        .unwrap();
25837        let err = read_sql_table_with_options(
25838            &conn,
25839            "bare_tbl",
25840            &SqlReadOptions {
25841                params: None,
25842                parse_dates: None,
25843                coerce_float: false,
25844                dtype: None,
25845                schema: Some("ignored_on_sqlite".to_owned()),
25846                columns: None,
25847                index_col: None,
25848            },
25849        )
25850        .expect_err("read_sql_table schema=Some must reject on SQLite");
25851        assert!(
25852            matches!(err, IoError::Sql(msg) if msg.contains("schema is not supported by sqlite backend"))
25853        );
25854    }
25855
25856    #[cfg(feature = "sql-sqlite")]
25857    #[test]
25858    fn read_sql_table_chunks_with_options_schema_rejected_on_sqlite() {
25859        let conn = make_sql_test_conn();
25860        super::SqlConnection::execute_batch(
25861            &conn,
25862            "CREATE TABLE chunk_bare_tbl (x INTEGER); INSERT INTO chunk_bare_tbl VALUES (1), (2);",
25863        )
25864        .unwrap();
25865        let err = read_sql_table_chunks_with_options(
25866            &conn,
25867            "chunk_bare_tbl",
25868            &SqlReadOptions {
25869                schema: Some("ignored_on_sqlite".to_owned()),
25870                ..Default::default()
25871            },
25872            1,
25873        )
25874        .expect_err("chunked read_sql_table schema=Some must reject on SQLite");
25875        assert!(
25876            matches!(err, IoError::Sql(msg) if msg.contains("schema is not supported by sqlite backend"))
25877        );
25878    }
25879
25880    #[test]
25881    fn sql_select_all_query_in_schema_validates_schema_name() {
25882        struct PgLikeValidate;
25883        impl super::SqlConnection for PgLikeValidate {
25884            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<super::SqlQueryResult, IoError> {
25885                Ok(super::SqlQueryResult {
25886                    columns: vec![],
25887                    rows: vec![],
25888                })
25889            }
25890            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
25891                Ok(())
25892            }
25893            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
25894                Ok(false)
25895            }
25896            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
25897                Ok(())
25898            }
25899            fn dtype_sql(&self, _dtype: DType) -> &'static str {
25900                "TEXT"
25901            }
25902            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
25903                "TEXT"
25904            }
25905            fn supports_schemas(&self) -> bool {
25906                true
25907            }
25908        }
25909        let conn = PgLikeValidate;
25910        let err = super::sql_select_all_query_in_schema(&conn, "users", Some("evil; DROP"))
25911            .expect_err("malformed schema must reject");
25912        // Per fd90.56: error message now correctly identifies the
25913        // bad identifier as a schema, not a table.
25914        assert!(matches!(err, IoError::Sql(msg) if msg.contains("invalid schema name")));
25915    }
25916
25917    // ── SqlWriteOptions::schema tests (br-frankenpandas-udn6 / fd90.15) ─
25918
25919    #[test]
25920    fn sql_create_table_query_in_schema_qualifies_on_multi_schema_backend() {
25921        struct PgLikeWrite;
25922        impl super::SqlConnection for PgLikeWrite {
25923            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<super::SqlQueryResult, IoError> {
25924                Ok(super::SqlQueryResult {
25925                    columns: vec![],
25926                    rows: vec![],
25927                })
25928            }
25929            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
25930                Ok(())
25931            }
25932            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
25933                Ok(false)
25934            }
25935            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
25936                Ok(())
25937            }
25938            fn dtype_sql(&self, _dtype: DType) -> &'static str {
25939                "TEXT"
25940            }
25941            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
25942                "TEXT"
25943            }
25944            fn supports_schemas(&self) -> bool {
25945                true
25946            }
25947        }
25948        let conn = PgLikeWrite;
25949        let cols = vec!["id INTEGER".to_owned(), "name TEXT".to_owned()];
25950        let q = super::sql_create_table_query_in_schema(&conn, "users", Some("analytics"), &cols)
25951            .expect("create");
25952        assert_eq!(
25953            q,
25954            "CREATE TABLE IF NOT EXISTS \"analytics\".\"users\" (id INTEGER, name TEXT)"
25955        );
25956        let bare =
25957            super::sql_create_table_query_in_schema(&conn, "users", None, &cols).expect("bare");
25958        assert_eq!(
25959            bare,
25960            "CREATE TABLE IF NOT EXISTS \"users\" (id INTEGER, name TEXT)"
25961        );
25962    }
25963
25964    #[test]
25965    fn sql_insert_rows_query_in_schema_qualifies_on_multi_schema_backend() {
25966        struct PgLikeInsert;
25967        impl super::SqlConnection for PgLikeInsert {
25968            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<super::SqlQueryResult, IoError> {
25969                Ok(super::SqlQueryResult {
25970                    columns: vec![],
25971                    rows: vec![],
25972                })
25973            }
25974            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
25975                Ok(())
25976            }
25977            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
25978                Ok(false)
25979            }
25980            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
25981                Ok(())
25982            }
25983            fn dtype_sql(&self, _dtype: DType) -> &'static str {
25984                "TEXT"
25985            }
25986            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
25987                "TEXT"
25988            }
25989            fn supports_schemas(&self) -> bool {
25990                true
25991            }
25992        }
25993        let conn = PgLikeInsert;
25994        let cols = vec!["id".to_owned(), "name".to_owned()];
25995        let q = super::sql_insert_rows_query_in_schema(&conn, "users", Some("analytics"), &cols)
25996            .expect("insert");
25997        assert_eq!(
25998            q,
25999            "INSERT INTO \"analytics\".\"users\" (\"id\", \"name\") VALUES (?, ?)"
26000        );
26001    }
26002
26003    #[cfg(feature = "sql-sqlite")]
26004    #[test]
26005    fn write_sql_with_options_schema_silently_ignored_on_sqlite() {
26006        let conn = make_sql_test_conn();
26007        let frame = fp_frame::DataFrame::from_dict(
26008            &["x"],
26009            vec![("x", vec![Scalar::Int64(1), Scalar::Int64(2)])],
26010        )
26011        .unwrap();
26012        // SQLite reports supports_schemas=false; passing schema=Some(s) must
26013        // not break the write — the bare table reference is used.
26014        write_sql_with_options(
26015            &frame,
26016            &conn,
26017            "bare_write_tbl",
26018            &SqlWriteOptions {
26019                if_exists: SqlIfExists::Fail,
26020                index: false,
26021                index_label: None,
26022                schema: Some("ignored_on_sqlite".to_owned()),
26023                dtype: None,
26024                method: SqlInsertMethod::Single,
26025                chunksize: None,
26026            },
26027        )
26028        .expect("write with schema=Some on SQLite");
26029        let back = read_sql_table(&conn, "bare_write_tbl").expect("read");
26030        let col = back.column("x").expect("x");
26031        assert_eq!(col.values()[0], Scalar::Int64(1));
26032        assert_eq!(col.values()[1], Scalar::Int64(2));
26033    }
26034
26035    #[test]
26036    fn sql_create_table_query_in_schema_validates_schema_name() {
26037        struct PgLikeValidate;
26038        impl super::SqlConnection for PgLikeValidate {
26039            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<super::SqlQueryResult, IoError> {
26040                Ok(super::SqlQueryResult {
26041                    columns: vec![],
26042                    rows: vec![],
26043                })
26044            }
26045            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
26046                Ok(())
26047            }
26048            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
26049                Ok(false)
26050            }
26051            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
26052                Ok(())
26053            }
26054            fn dtype_sql(&self, _dtype: DType) -> &'static str {
26055                "TEXT"
26056            }
26057            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
26058                "TEXT"
26059            }
26060            fn supports_schemas(&self) -> bool {
26061                true
26062            }
26063        }
26064        let conn = PgLikeValidate;
26065        let cols = vec!["x INTEGER".to_owned()];
26066        let err =
26067            super::sql_create_table_query_in_schema(&conn, "users", Some("evil; DROP"), &cols)
26068                .expect_err("malformed schema must reject");
26069        // Per fd90.56: schema validation error now says invalid
26070        // schema name (not invalid table name).
26071        assert!(matches!(err, IoError::Sql(msg) if msg.contains("invalid schema name")));
26072    }
26073
26074    // ── DROP TABLE schema-qualification (br-frankenpandas-hxob / fd90.16) ─
26075
26076    #[test]
26077    fn sql_drop_table_query_bare_on_non_multi_schema() {
26078        struct StubSql;
26079        impl super::SqlConnection for StubSql {
26080            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<super::SqlQueryResult, IoError> {
26081                Ok(super::SqlQueryResult {
26082                    columns: vec![],
26083                    rows: vec![],
26084                })
26085            }
26086            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
26087                Ok(())
26088            }
26089            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
26090                Ok(false)
26091            }
26092            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
26093                Ok(())
26094            }
26095            fn dtype_sql(&self, _dtype: DType) -> &'static str {
26096                "TEXT"
26097            }
26098            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
26099                "TEXT"
26100            }
26101        }
26102        let conn = StubSql;
26103        let q = super::sql_drop_table_query_in_schema(&conn, "users", None).expect("drop none");
26104        assert_eq!(q, "DROP TABLE IF EXISTS \"users\"");
26105        // schema=Some on non-multi-schema is silently ignored.
26106        let q2 =
26107            super::sql_drop_table_query_in_schema(&conn, "users", Some("ignored")).expect("drop");
26108        assert_eq!(q2, "DROP TABLE IF EXISTS \"users\"");
26109    }
26110
26111    #[test]
26112    fn sql_drop_table_query_qualifies_on_multi_schema_backend() {
26113        struct PgLikeDrop;
26114        impl super::SqlConnection for PgLikeDrop {
26115            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<super::SqlQueryResult, IoError> {
26116                Ok(super::SqlQueryResult {
26117                    columns: vec![],
26118                    rows: vec![],
26119                })
26120            }
26121            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
26122                Ok(())
26123            }
26124            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
26125                Ok(false)
26126            }
26127            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
26128                Ok(())
26129            }
26130            fn dtype_sql(&self, _dtype: DType) -> &'static str {
26131                "TEXT"
26132            }
26133            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
26134                "TEXT"
26135            }
26136            fn supports_schemas(&self) -> bool {
26137                true
26138            }
26139        }
26140        let conn = PgLikeDrop;
26141        let q = super::sql_drop_table_query_in_schema(&conn, "users", Some("analytics"))
26142            .expect("drop qualified");
26143        assert_eq!(q, "DROP TABLE IF EXISTS \"analytics\".\"users\"");
26144        let bare = super::sql_drop_table_query_in_schema(&conn, "users", None).expect("drop bare");
26145        assert_eq!(bare, "DROP TABLE IF EXISTS \"users\"");
26146    }
26147
26148    #[cfg(feature = "sql-sqlite")]
26149    #[test]
26150    fn write_sql_replace_with_schema_silently_ignored_on_sqlite() {
26151        // Replace path drops + recreates. SQLite reports supports_schemas
26152        // == false; the schema is silently ignored on the DROP and on the
26153        // CREATE/INSERT — the round trip lands data in the bare table.
26154        let conn = make_sql_test_conn();
26155        super::SqlConnection::execute_batch(
26156            &conn,
26157            "CREATE TABLE replace_tbl (x INTEGER); INSERT INTO replace_tbl VALUES (99);",
26158        )
26159        .unwrap();
26160        let frame = fp_frame::DataFrame::from_dict(
26161            &["x"],
26162            vec![("x", vec![Scalar::Int64(1), Scalar::Int64(2)])],
26163        )
26164        .unwrap();
26165        write_sql_with_options(
26166            &frame,
26167            &conn,
26168            "replace_tbl",
26169            &SqlWriteOptions {
26170                if_exists: SqlIfExists::Replace,
26171                index: false,
26172                index_label: None,
26173                schema: Some("ignored_on_sqlite".to_owned()),
26174                dtype: None,
26175                method: SqlInsertMethod::Single,
26176                chunksize: None,
26177            },
26178        )
26179        .expect("replace + schema=Some on SQLite");
26180        let back = read_sql_table(&conn, "replace_tbl").expect("read");
26181        let col = back.column("x").expect("x");
26182        // Pre-existing 99 was dropped; new rows present.
26183        assert_eq!(col.values().len(), 2);
26184        assert_eq!(col.values()[0], Scalar::Int64(1));
26185        assert_eq!(col.values()[1], Scalar::Int64(2));
26186    }
26187
26188    // ── table_exists_in_schema (br-frankenpandas-70d1 / fd90.17) ────────
26189
26190    #[test]
26191    fn default_table_exists_in_schema_delegates_to_table_exists() {
26192        // A stub that returns table_exists=true for "users" must report the
26193        // same value via the schema-aware default impl regardless of schema.
26194        struct StubExistsTrue;
26195        impl super::SqlConnection for StubExistsTrue {
26196            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<super::SqlQueryResult, IoError> {
26197                Ok(super::SqlQueryResult {
26198                    columns: vec![],
26199                    rows: vec![],
26200                })
26201            }
26202            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
26203                Ok(())
26204            }
26205            fn table_exists(&self, name: &str) -> Result<bool, IoError> {
26206                Ok(name == "users")
26207            }
26208            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
26209                Ok(())
26210            }
26211            fn dtype_sql(&self, _dtype: DType) -> &'static str {
26212                "TEXT"
26213            }
26214            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
26215                "TEXT"
26216            }
26217        }
26218        let conn = StubExistsTrue;
26219        // Schema is ignored by the default impl.
26220        assert!(super::SqlConnection::table_exists_in_schema(&conn, "users", None).unwrap());
26221        assert!(
26222            super::SqlConnection::table_exists_in_schema(&conn, "users", Some("ignored")).unwrap()
26223        );
26224        assert!(!super::SqlConnection::table_exists_in_schema(&conn, "missing", None).unwrap());
26225    }
26226
26227    #[test]
26228    fn multi_schema_override_scopes_table_exists() {
26229        // PgLikeSchemaCheck overrides table_exists_in_schema to scope by
26230        // schema: only ('analytics', 'users') exists.
26231        struct PgLikeSchemaCheck;
26232        impl super::SqlConnection for PgLikeSchemaCheck {
26233            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<super::SqlQueryResult, IoError> {
26234                Ok(super::SqlQueryResult {
26235                    columns: vec![],
26236                    rows: vec![],
26237                })
26238            }
26239            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
26240                Ok(())
26241            }
26242            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
26243                // Bare table_exists isn't queried by the override path.
26244                Ok(false)
26245            }
26246            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
26247                Ok(())
26248            }
26249            fn dtype_sql(&self, _dtype: DType) -> &'static str {
26250                "TEXT"
26251            }
26252            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
26253                "TEXT"
26254            }
26255            fn supports_schemas(&self) -> bool {
26256                true
26257            }
26258            fn table_exists_in_schema(
26259                &self,
26260                table: &str,
26261                schema: Option<&str>,
26262            ) -> Result<bool, IoError> {
26263                Ok(table == "users" && schema == Some("analytics"))
26264            }
26265        }
26266        let conn = PgLikeSchemaCheck;
26267        assert!(
26268            super::SqlConnection::table_exists_in_schema(&conn, "users", Some("analytics"))
26269                .unwrap()
26270        );
26271        // Different schema → false.
26272        assert!(
26273            !super::SqlConnection::table_exists_in_schema(&conn, "users", Some("audit")).unwrap()
26274        );
26275        // No schema → false (override scopes by Some).
26276        assert!(!super::SqlConnection::table_exists_in_schema(&conn, "users", None).unwrap());
26277    }
26278
26279    #[cfg(feature = "sql-sqlite")]
26280    #[test]
26281    fn write_sql_fail_with_schema_some_still_rejects_existing_on_sqlite() {
26282        // SQLite ignores schema everywhere; the Fail branch still reports
26283        // 'table already exists' when the bare table is present.
26284        let conn = make_sql_test_conn();
26285        super::SqlConnection::execute_batch(&conn, "CREATE TABLE preexists_tbl (x INTEGER);")
26286            .unwrap();
26287        let frame =
26288            fp_frame::DataFrame::from_dict(&["x"], vec![("x", vec![Scalar::Int64(1)])]).unwrap();
26289        let err = write_sql_with_options(
26290            &frame,
26291            &conn,
26292            "preexists_tbl",
26293            &SqlWriteOptions {
26294                if_exists: SqlIfExists::Fail,
26295                index: false,
26296                index_label: None,
26297                schema: Some("ignored_on_sqlite".to_owned()),
26298                dtype: None,
26299                method: SqlInsertMethod::Single,
26300                chunksize: None,
26301            },
26302        )
26303        .expect_err("Fail branch must still reject pre-existing");
26304        assert!(matches!(err, IoError::Sql(msg) if msg.contains("already exists")));
26305    }
26306
26307    // ── SqlWriteOptions::dtype overrides (br-frankenpandas-ev2s / fd90.18) ─
26308
26309    #[cfg(feature = "sql-sqlite")]
26310    #[test]
26311    fn write_sql_dtype_override_emits_custom_sql_type() {
26312        // SQLite is permissive on declared types — the column-type string
26313        // ends up in sqlite_master.sql verbatim, which we can grep to verify
26314        // the override took effect during CREATE TABLE.
26315        let conn = make_sql_test_conn();
26316        let frame = fp_frame::DataFrame::from_dict(
26317            &["amount"],
26318            vec![("amount", vec![Scalar::Int64(100), Scalar::Int64(250)])],
26319        )
26320        .unwrap();
26321        let mut overrides = BTreeMap::new();
26322        overrides.insert("amount".to_owned(), "NUMERIC(10,2)".to_owned());
26323        write_sql_with_options(
26324            &frame,
26325            &conn,
26326            "money_tbl",
26327            &SqlWriteOptions {
26328                if_exists: SqlIfExists::Fail,
26329                index: false,
26330                index_label: None,
26331                schema: None,
26332                dtype: Some(overrides),
26333                method: SqlInsertMethod::Single,
26334                chunksize: None,
26335            },
26336        )
26337        .expect("write with dtype override");
26338        let sm = super::SqlConnection::query(
26339            &conn,
26340            "SELECT sql FROM sqlite_master WHERE name = 'money_tbl'",
26341            &[],
26342        )
26343        .unwrap();
26344        let create_sql = match &sm.rows[0][0] {
26345            Scalar::Utf8(s) => s.clone(),
26346            other => unreachable!("unexpected sqlite_master payload: {other:?}"),
26347        };
26348        assert!(
26349            create_sql.contains("NUMERIC(10,2)"),
26350            "expected override to land in CREATE TABLE; got: {create_sql}"
26351        );
26352    }
26353
26354    #[cfg(feature = "sql-sqlite")]
26355    #[test]
26356    fn write_sql_dtype_override_multiple_columns() {
26357        let conn = make_sql_test_conn();
26358        let frame = fp_frame::DataFrame::from_dict(
26359            &["a", "b"],
26360            vec![
26361                ("a", vec![Scalar::Int64(1)]),
26362                ("b", vec![Scalar::Float64(1.5)]),
26363            ],
26364        )
26365        .unwrap();
26366        let mut overrides = BTreeMap::new();
26367        overrides.insert("a".to_owned(), "BIGINT".to_owned());
26368        overrides.insert("b".to_owned(), "DECIMAL(8,4)".to_owned());
26369        write_sql_with_options(
26370            &frame,
26371            &conn,
26372            "multi_tbl",
26373            &SqlWriteOptions {
26374                if_exists: SqlIfExists::Fail,
26375                index: false,
26376                index_label: None,
26377                schema: None,
26378                dtype: Some(overrides),
26379                method: SqlInsertMethod::Single,
26380                chunksize: None,
26381            },
26382        )
26383        .expect("write with multi-column overrides");
26384        let sm = super::SqlConnection::query(
26385            &conn,
26386            "SELECT sql FROM sqlite_master WHERE name = 'multi_tbl'",
26387            &[],
26388        )
26389        .unwrap();
26390        let create_sql = match &sm.rows[0][0] {
26391            Scalar::Utf8(s) => s.clone(),
26392            other => unreachable!("unexpected sqlite_master payload: {other:?}"),
26393        };
26394        assert!(create_sql.contains("BIGINT"));
26395        assert!(create_sql.contains("DECIMAL(8,4)"));
26396    }
26397
26398    #[cfg(feature = "sql-sqlite")]
26399    #[test]
26400    fn write_sql_dtype_override_for_missing_column_silently_ignored() {
26401        let conn = make_sql_test_conn();
26402        let frame =
26403            fp_frame::DataFrame::from_dict(&["x"], vec![("x", vec![Scalar::Int64(1)])]).unwrap();
26404        let mut overrides = BTreeMap::new();
26405        overrides.insert("nonexistent".to_owned(), "BIGINT".to_owned());
26406        // No error — pandas silently ignores dtype entries for columns not in the frame.
26407        write_sql_with_options(
26408            &frame,
26409            &conn,
26410            "missing_col_tbl",
26411            &SqlWriteOptions {
26412                if_exists: SqlIfExists::Fail,
26413                index: false,
26414                index_label: None,
26415                schema: None,
26416                dtype: Some(overrides),
26417                method: SqlInsertMethod::Single,
26418                chunksize: None,
26419            },
26420        )
26421        .expect("write with override on missing col");
26422        // The actual 'x' column kept its inferred type.
26423        let sm = super::SqlConnection::query(
26424            &conn,
26425            "SELECT sql FROM sqlite_master WHERE name = 'missing_col_tbl'",
26426            &[],
26427        )
26428        .unwrap();
26429        let create_sql = match &sm.rows[0][0] {
26430            Scalar::Utf8(s) => s.clone(),
26431            other => unreachable!("unexpected sqlite_master payload: {other:?}"),
26432        };
26433        assert!(create_sql.contains("INTEGER"));
26434        assert!(!create_sql.contains("BIGINT"));
26435    }
26436
26437    #[cfg(feature = "sql-sqlite")]
26438    #[test]
26439    fn write_sql_dtype_none_falls_back_to_inferred_type() {
26440        let conn = make_sql_test_conn();
26441        let frame =
26442            fp_frame::DataFrame::from_dict(&["x"], vec![("x", vec![Scalar::Int64(1)])]).unwrap();
26443        write_sql_with_options(
26444            &frame,
26445            &conn,
26446            "no_override_tbl",
26447            &SqlWriteOptions {
26448                if_exists: SqlIfExists::Fail,
26449                index: false,
26450                index_label: None,
26451                schema: None,
26452                dtype: None,
26453                method: SqlInsertMethod::Single,
26454                chunksize: None,
26455            },
26456        )
26457        .expect("write without override");
26458        let sm = super::SqlConnection::query(
26459            &conn,
26460            "SELECT sql FROM sqlite_master WHERE name = 'no_override_tbl'",
26461            &[],
26462        )
26463        .unwrap();
26464        let create_sql = match &sm.rows[0][0] {
26465            Scalar::Utf8(s) => s.clone(),
26466            other => unreachable!("unexpected sqlite_master payload: {other:?}"),
26467        };
26468        // INTEGER is conn.dtype_sql(DType::Int64) for rusqlite.
26469        assert!(create_sql.contains("INTEGER"));
26470    }
26471
26472    // ── SqlInsertMethod::Multi (br-frankenpandas-i0ml / fd90.19) ─────────
26473
26474    #[cfg(feature = "sql-sqlite")]
26475    #[test]
26476    fn write_sql_multi_round_trip_matches_single() {
26477        // Same frame written via Single vs Multi must produce identical
26478        // SELECT * results — the only observable difference should be
26479        // the wire-format efficiency, never the stored values.
26480        let frame = fp_frame::DataFrame::from_dict(
26481            &["id", "name", "amount"],
26482            vec![
26483                (
26484                    "id",
26485                    vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
26486                ),
26487                (
26488                    "name",
26489                    vec![
26490                        Scalar::Utf8("alice".into()),
26491                        Scalar::Utf8("bob".into()),
26492                        Scalar::Utf8("carol".into()),
26493                    ],
26494                ),
26495                (
26496                    "amount",
26497                    vec![
26498                        Scalar::Float64(1.5),
26499                        Scalar::Float64(2.5),
26500                        Scalar::Float64(3.5),
26501                    ],
26502                ),
26503            ],
26504        )
26505        .unwrap();
26506
26507        let conn_single = make_sql_test_conn();
26508        write_sql_with_options(
26509            &frame,
26510            &conn_single,
26511            "single_tbl",
26512            &SqlWriteOptions {
26513                if_exists: SqlIfExists::Fail,
26514                index: false,
26515                index_label: None,
26516                schema: None,
26517                dtype: None,
26518                method: SqlInsertMethod::Single,
26519                chunksize: None,
26520            },
26521        )
26522        .unwrap();
26523        let single = read_sql(&conn_single, "SELECT * FROM single_tbl ORDER BY id").unwrap();
26524
26525        let conn_multi = make_sql_test_conn();
26526        write_sql_with_options(
26527            &frame,
26528            &conn_multi,
26529            "multi_tbl",
26530            &SqlWriteOptions {
26531                if_exists: SqlIfExists::Fail,
26532                index: false,
26533                index_label: None,
26534                schema: None,
26535                dtype: None,
26536                method: SqlInsertMethod::Multi,
26537                chunksize: None,
26538            },
26539        )
26540        .unwrap();
26541        let multi = read_sql(&conn_multi, "SELECT * FROM multi_tbl ORDER BY id").unwrap();
26542
26543        assert_eq!(single.column_names(), multi.column_names());
26544        for name in single.column_names() {
26545            let s = single.column(name).unwrap().values().to_vec();
26546            let m = multi.column(name).unwrap().values().to_vec();
26547            assert_eq!(s, m, "column {name} diverged between Single and Multi");
26548        }
26549    }
26550
26551    #[test]
26552    fn sql_multi_row_insert_query_emits_correct_placeholder_count() {
26553        // 3 rows × 2 cols = 6 placeholders, ordinals 1..=6.
26554        struct PgLikeStub;
26555        impl super::SqlConnection for PgLikeStub {
26556            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
26557                Ok(SqlQueryResult {
26558                    columns: vec![],
26559                    rows: vec![],
26560                })
26561            }
26562            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
26563                Ok(())
26564            }
26565            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
26566                Ok(false)
26567            }
26568            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
26569                Ok(())
26570            }
26571            fn dtype_sql(&self, _dtype: DType) -> &'static str {
26572                "TEXT"
26573            }
26574            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
26575                "TEXT"
26576            }
26577            fn parameter_marker(&self, ordinal: usize) -> String {
26578                format!("${ordinal}")
26579            }
26580        }
26581        let conn = PgLikeStub;
26582        let cols = vec!["a".to_owned(), "b".to_owned()];
26583        let sql =
26584            super::sql_multi_row_insert_query_in_schema(&conn, "tbl", None, &cols, 3).unwrap();
26585        // Expect: INSERT INTO "tbl" ("a", "b") VALUES ($1, $2), ($3, $4), ($5, $6)
26586        assert!(
26587            sql.contains("VALUES ($1, $2), ($3, $4), ($5, $6)"),
26588            "got: {sql}"
26589        );
26590    }
26591
26592    #[test]
26593    fn sql_multi_row_insert_query_rejects_zero_rows() {
26594        struct StubConn;
26595        impl super::SqlConnection for StubConn {
26596            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
26597                Ok(SqlQueryResult {
26598                    columns: vec![],
26599                    rows: vec![],
26600                })
26601            }
26602            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
26603                Ok(())
26604            }
26605            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
26606                Ok(false)
26607            }
26608            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
26609                Ok(())
26610            }
26611            fn dtype_sql(&self, _dtype: DType) -> &'static str {
26612                "TEXT"
26613            }
26614            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
26615                "TEXT"
26616            }
26617        }
26618        let conn = StubConn;
26619        let cols = vec!["a".to_owned()];
26620        let err = super::sql_multi_row_insert_query_in_schema(&conn, "tbl", None, &cols, 0)
26621            .expect_err("zero rows must be rejected");
26622        assert!(matches!(err, IoError::Sql(msg) if msg.contains("at least one row")));
26623    }
26624
26625    #[cfg(feature = "sql-sqlite")]
26626    #[test]
26627    fn write_sql_multi_chunks_at_max_param_boundary() {
26628        // Verify the chunking logic dispatches multiple INSERT statements
26629        // when num_rows * num_cols exceeds max_param_count. We override
26630        // max_param_count on a recording stub to force a tiny budget.
26631        use std::cell::RefCell;
26632        struct ChunkRecorder {
26633            statements: RefCell<Vec<String>>,
26634            row_counts: RefCell<Vec<usize>>,
26635        }
26636        impl super::SqlConnection for ChunkRecorder {
26637            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
26638                Ok(SqlQueryResult {
26639                    columns: vec![],
26640                    rows: vec![],
26641                })
26642            }
26643            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
26644                Ok(())
26645            }
26646            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
26647                Ok(false)
26648            }
26649            fn insert_rows(&self, sql: &str, rows: &[Vec<Scalar>]) -> Result<(), IoError> {
26650                self.statements.borrow_mut().push(sql.to_owned());
26651                self.row_counts
26652                    .borrow_mut()
26653                    .push(rows.first().map_or(0, std::vec::Vec::len));
26654                Ok(())
26655            }
26656            fn dtype_sql(&self, _dtype: DType) -> &'static str {
26657                "TEXT"
26658            }
26659            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
26660                "TEXT"
26661            }
26662            fn max_param_count(&self) -> Option<usize> {
26663                // 4 params total, ncols=2 → 2 rows per chunk.
26664                Some(4)
26665            }
26666        }
26667        let conn = ChunkRecorder {
26668            statements: RefCell::new(vec![]),
26669            row_counts: RefCell::new(vec![]),
26670        };
26671        let frame = fp_frame::DataFrame::from_dict(
26672            &["a", "b"],
26673            vec![
26674                (
26675                    "a",
26676                    vec![
26677                        Scalar::Int64(1),
26678                        Scalar::Int64(2),
26679                        Scalar::Int64(3),
26680                        Scalar::Int64(4),
26681                        Scalar::Int64(5),
26682                    ],
26683                ),
26684                (
26685                    "b",
26686                    vec![
26687                        Scalar::Int64(10),
26688                        Scalar::Int64(20),
26689                        Scalar::Int64(30),
26690                        Scalar::Int64(40),
26691                        Scalar::Int64(50),
26692                    ],
26693                ),
26694            ],
26695        )
26696        .unwrap();
26697        write_sql_with_options(
26698            &frame,
26699            &conn,
26700            "chunked",
26701            &SqlWriteOptions {
26702                if_exists: SqlIfExists::Fail,
26703                index: false,
26704                index_label: None,
26705                schema: None,
26706                dtype: None,
26707                method: SqlInsertMethod::Multi,
26708                chunksize: None,
26709            },
26710        )
26711        .unwrap();
26712        // 5 rows / 2 per chunk = 3 chunks (2, 2, 1).
26713        let stmts = conn.statements.borrow();
26714        let counts = conn.row_counts.borrow();
26715        assert_eq!(stmts.len(), 3, "expected 3 chunked INSERTs");
26716        // Flat row payloads: 2 rows * 2 cols = 4 scalars, 4, then 1 row * 2 = 2.
26717        assert_eq!(counts.as_slice(), &[4, 4, 2]);
26718    }
26719
26720    #[cfg(feature = "sql-sqlite")]
26721    #[test]
26722    fn write_sql_multi_no_max_param_sends_single_statement() {
26723        // When the backend reports max_param_count() == None, the whole
26724        // frame should ship in a single multi-row INSERT.
26725        use std::cell::RefCell;
26726        struct UnboundedStub {
26727            statements: RefCell<Vec<String>>,
26728        }
26729        impl super::SqlConnection for UnboundedStub {
26730            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
26731                Ok(SqlQueryResult {
26732                    columns: vec![],
26733                    rows: vec![],
26734                })
26735            }
26736            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
26737                Ok(())
26738            }
26739            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
26740                Ok(false)
26741            }
26742            fn insert_rows(&self, sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
26743                self.statements.borrow_mut().push(sql.to_owned());
26744                Ok(())
26745            }
26746            fn dtype_sql(&self, _dtype: DType) -> &'static str {
26747                "TEXT"
26748            }
26749            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
26750                "TEXT"
26751            }
26752            fn max_param_count(&self) -> Option<usize> {
26753                None
26754            }
26755        }
26756        let conn = UnboundedStub {
26757            statements: RefCell::new(vec![]),
26758        };
26759        let frame = fp_frame::DataFrame::from_dict(
26760            &["x"],
26761            vec![(
26762                "x",
26763                vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
26764            )],
26765        )
26766        .unwrap();
26767        write_sql_with_options(
26768            &frame,
26769            &conn,
26770            "uncapped",
26771            &SqlWriteOptions {
26772                if_exists: SqlIfExists::Fail,
26773                index: false,
26774                index_label: None,
26775                schema: None,
26776                dtype: None,
26777                method: SqlInsertMethod::Multi,
26778                chunksize: None,
26779            },
26780        )
26781        .unwrap();
26782        let stmts = conn.statements.borrow();
26783        assert_eq!(stmts.len(), 1, "expected exactly one multi-row INSERT");
26784        // 3 tuples → 2 commas separating tuples in VALUES (...), (...), (...).
26785        let stmt = &stmts[0];
26786        assert_eq!(
26787            stmt.matches("(?)").count(),
26788            3,
26789            "expected 3 row tuples in: {stmt}"
26790        );
26791    }
26792
26793    #[cfg(feature = "sql-sqlite")]
26794    #[test]
26795    fn write_sql_multi_preserves_nulls() {
26796        // NaT/Null values must round-trip through the multi-row path.
26797        let frame = fp_frame::DataFrame::from_dict(
26798            &["a", "b"],
26799            vec![
26800                (
26801                    "a",
26802                    vec![
26803                        Scalar::Int64(1),
26804                        Scalar::Null(NullKind::Null),
26805                        Scalar::Int64(3),
26806                    ],
26807                ),
26808                (
26809                    "b",
26810                    vec![
26811                        Scalar::Utf8("x".into()),
26812                        Scalar::Utf8("y".into()),
26813                        Scalar::Null(NullKind::Null),
26814                    ],
26815                ),
26816            ],
26817        )
26818        .unwrap();
26819        let conn = make_sql_test_conn();
26820        write_sql_with_options(
26821            &frame,
26822            &conn,
26823            "nulls_tbl",
26824            &SqlWriteOptions {
26825                if_exists: SqlIfExists::Fail,
26826                index: false,
26827                index_label: None,
26828                schema: None,
26829                dtype: None,
26830                method: SqlInsertMethod::Multi,
26831                chunksize: None,
26832            },
26833        )
26834        .unwrap();
26835        let back = read_sql(&conn, "SELECT a, b FROM nulls_tbl ORDER BY rowid").unwrap();
26836        let a = back.column("a").unwrap().values();
26837        let b = back.column("b").unwrap().values();
26838        assert_eq!(a[0], Scalar::Int64(1));
26839        assert!(matches!(a[1], Scalar::Null(_)));
26840        assert_eq!(a[2], Scalar::Int64(3));
26841        assert_eq!(b[0], Scalar::Utf8("x".into()));
26842        assert_eq!(b[1], Scalar::Utf8("y".into()));
26843        assert!(matches!(b[2], Scalar::Null(_)));
26844    }
26845
26846    #[test]
26847    fn sql_insert_method_default_is_single() {
26848        assert_eq!(SqlInsertMethod::default(), SqlInsertMethod::Single);
26849    }
26850
26851    // ── list_sql_tables / SqlConnection::list_tables (br-vhq2 / fd90.20) ─
26852
26853    #[cfg(feature = "sql-sqlite")]
26854    #[test]
26855    fn list_sql_tables_empty_db_returns_empty_vec() {
26856        let conn = make_sql_test_conn();
26857        let tables = list_sql_tables(&conn, None).unwrap();
26858        assert!(tables.is_empty(), "expected no tables; got {tables:?}");
26859    }
26860
26861    #[cfg(feature = "sql-sqlite")]
26862    #[test]
26863    fn list_sql_tables_returns_user_tables_sorted() {
26864        let conn = make_sql_test_conn();
26865        super::SqlConnection::execute_batch(&conn, "CREATE TABLE zebra (x INTEGER);").unwrap();
26866        super::SqlConnection::execute_batch(&conn, "CREATE TABLE alpha (y TEXT);").unwrap();
26867        super::SqlConnection::execute_batch(&conn, "CREATE TABLE mango (z REAL);").unwrap();
26868        let tables = list_sql_tables(&conn, None).unwrap();
26869        assert_eq!(tables, vec!["alpha", "mango", "zebra"]);
26870    }
26871
26872    #[cfg(feature = "sql-sqlite")]
26873    #[test]
26874    fn list_sql_tables_excludes_sqlite_internal_tables() {
26875        let conn = make_sql_test_conn();
26876        // Forcing creation of an internal sqlite_sequence table by using
26877        // AUTOINCREMENT — that table must NOT appear in the result.
26878        super::SqlConnection::execute_batch(
26879            &conn,
26880            "CREATE TABLE seq_demo (id INTEGER PRIMARY KEY AUTOINCREMENT, v TEXT);",
26881        )
26882        .unwrap();
26883        super::SqlConnection::execute_batch(&conn, "INSERT INTO seq_demo (v) VALUES ('one');")
26884            .unwrap();
26885        let tables = list_sql_tables(&conn, None).unwrap();
26886        assert_eq!(tables, vec!["seq_demo"]);
26887        assert!(!tables.iter().any(|name| name.starts_with("sqlite_")));
26888    }
26889
26890    #[cfg(feature = "sql-sqlite")]
26891    #[test]
26892    fn list_sql_tables_keeps_user_tables_with_sqlite_prefix_no_underscore() {
26893        // Per fd90.50: a user table named like 'sqliteX' (no underscore
26894        // between 'sqlite' and the rest) was being incorrectly excluded
26895        // by the buggy `NOT LIKE 'sqlite_%'` filter (where `_` is a
26896        // single-char wildcard). After the ESCAPE '\' fix the
26897        // underscore is treated literally, so only names starting with
26898        // the literal substring 'sqlite_' are excluded.
26899        let conn = make_sql_test_conn();
26900        super::SqlConnection::execute_batch(&conn, "CREATE TABLE sqliteX (x INTEGER);").unwrap();
26901        super::SqlConnection::execute_batch(&conn, "CREATE TABLE sqliteY (y TEXT);").unwrap();
26902        super::SqlConnection::execute_batch(&conn, "CREATE TABLE sqlite1234 (z REAL);").unwrap();
26903        let tables = list_sql_tables(&conn, None).unwrap();
26904        assert_eq!(tables, vec!["sqlite1234", "sqliteX", "sqliteY"]);
26905    }
26906
26907    #[cfg(feature = "sql-sqlite")]
26908    #[test]
26909    fn list_sql_views_keeps_user_views_with_sqlite_prefix_no_underscore() {
26910        // Companion to the list_tables case (fd90.50): same escape fix
26911        // applies to list_views.
26912        let conn = make_sql_test_conn();
26913        super::SqlConnection::execute_batch(&conn, "CREATE TABLE base (x INTEGER);").unwrap();
26914        super::SqlConnection::execute_batch(
26915            &conn,
26916            "CREATE VIEW sqliteX_view AS SELECT x FROM base;",
26917        )
26918        .unwrap();
26919        let views = list_sql_views(&conn, None).unwrap();
26920        // sqliteX_view: 'sqliteX' (no underscore after 'sqlite') so the
26921        // literal-underscore filter accepts it.
26922        assert_eq!(views, vec!["sqliteX_view"]);
26923    }
26924
26925    #[cfg(feature = "sql-sqlite")]
26926    #[test]
26927    fn list_sql_tables_schema_silently_ignored_on_sqlite() {
26928        // SQLite reports supports_schemas() == false. Passing a schema
26929        // arg must NOT error; it is silently dropped and all tables are
26930        // returned (matches the documented option-struct ignore policy).
26931        let conn = make_sql_test_conn();
26932        super::SqlConnection::execute_batch(&conn, "CREATE TABLE only_one (x INTEGER);").unwrap();
26933        let with_schema =
26934            list_sql_tables(&conn, Some("ignored_on_sqlite")).expect("schema arg must not error");
26935        let without_schema = list_sql_tables(&conn, None).unwrap();
26936        assert_eq!(with_schema, without_schema);
26937    }
26938
26939    #[test]
26940    fn list_sql_tables_default_impl_returns_empty() {
26941        // A backend that doesn't override list_tables falls through to
26942        // the trait default — returns empty rather than erroring.
26943        struct NoIntrospection;
26944        impl super::SqlConnection for NoIntrospection {
26945            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
26946                Ok(SqlQueryResult {
26947                    columns: vec![],
26948                    rows: vec![],
26949                })
26950            }
26951            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
26952                Ok(())
26953            }
26954            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
26955                Ok(false)
26956            }
26957            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
26958                Ok(())
26959            }
26960            fn dtype_sql(&self, _dtype: DType) -> &'static str {
26961                "TEXT"
26962            }
26963            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
26964                "TEXT"
26965            }
26966        }
26967        let conn = NoIntrospection;
26968        let tables = list_sql_tables(&conn, None).unwrap();
26969        assert!(tables.is_empty());
26970        let with_schema = list_sql_tables(&conn, Some("any")).unwrap();
26971        assert!(with_schema.is_empty());
26972    }
26973
26974    #[test]
26975    fn list_sql_tables_routes_schema_to_backend_override() {
26976        // Multi-schema backend stub: returns different tables per schema.
26977        struct MultiSchema;
26978        impl super::SqlConnection for MultiSchema {
26979            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
26980                Ok(SqlQueryResult {
26981                    columns: vec![],
26982                    rows: vec![],
26983                })
26984            }
26985            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
26986                Ok(())
26987            }
26988            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
26989                Ok(false)
26990            }
26991            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
26992                Ok(())
26993            }
26994            fn dtype_sql(&self, _dtype: DType) -> &'static str {
26995                "TEXT"
26996            }
26997            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
26998                "TEXT"
26999            }
27000            fn supports_schemas(&self) -> bool {
27001                true
27002            }
27003            fn list_tables(&self, schema: Option<&str>) -> Result<Vec<String>, IoError> {
27004                Ok(match schema {
27005                    Some("analytics") => {
27006                        vec!["users".to_owned(), "events".to_owned()]
27007                    }
27008                    Some("audit") => vec!["logs".to_owned()],
27009                    Some(_) => vec![],
27010                    None => vec!["public_table".to_owned()],
27011                })
27012            }
27013        }
27014        let conn = MultiSchema;
27015        assert_eq!(
27016            list_sql_tables(&conn, Some("analytics")).unwrap(),
27017            vec!["users", "events"]
27018        );
27019        assert_eq!(list_sql_tables(&conn, Some("audit")).unwrap(), vec!["logs"]);
27020        assert_eq!(
27021            list_sql_tables(&conn, Some("missing")).unwrap(),
27022            Vec::<String>::new()
27023        );
27024        assert_eq!(list_sql_tables(&conn, None).unwrap(), vec!["public_table"]);
27025    }
27026
27027    // ── sql_table_schema / SqlConnection::table_schema (br-w43q / fd90.21) ─
27028
27029    #[cfg(feature = "sql-sqlite")]
27030    #[test]
27031    fn sql_table_schema_unknown_table_returns_none() {
27032        let conn = make_sql_test_conn();
27033        let result = sql_table_schema(&conn, "no_such_table", None).unwrap();
27034        assert!(result.is_none());
27035    }
27036
27037    #[cfg(feature = "sql-sqlite")]
27038    #[test]
27039    fn sql_table_schema_simple_table() {
27040        let conn = make_sql_test_conn();
27041        super::SqlConnection::execute_batch(&conn, "CREATE TABLE simple (id INTEGER, name TEXT);")
27042            .unwrap();
27043        let schema = sql_table_schema(&conn, "simple", None).unwrap().unwrap();
27044        assert_eq!(schema.table_name, "simple");
27045        assert_eq!(schema.columns.len(), 2);
27046        assert_eq!(schema.columns[0].name, "id");
27047        assert_eq!(schema.columns[0].declared_type.as_deref(), Some("INTEGER"));
27048        assert!(schema.columns[0].nullable);
27049        assert!(schema.columns[0].primary_key_ordinal.is_none());
27050        assert_eq!(schema.columns[1].name, "name");
27051        assert_eq!(schema.columns[1].declared_type.as_deref(), Some("TEXT"));
27052        assert!(schema.columns[1].nullable);
27053    }
27054
27055    #[cfg(feature = "sql-sqlite")]
27056    #[test]
27057    fn sql_table_schema_pk_notnull_default() {
27058        let conn = make_sql_test_conn();
27059        super::SqlConnection::execute_batch(
27060            &conn,
27061            "CREATE TABLE meta ( \
27062                id INTEGER PRIMARY KEY, \
27063                name TEXT NOT NULL, \
27064                status TEXT DEFAULT 'active' \
27065             );",
27066        )
27067        .unwrap();
27068        let schema = sql_table_schema(&conn, "meta", None).unwrap().unwrap();
27069        assert_eq!(schema.columns.len(), 3);
27070
27071        let id = schema.column("id").expect("id col");
27072        assert_eq!(id.primary_key_ordinal, Some(0));
27073        // PRIMARY KEY columns in SQLite (without explicit NOT NULL on
27074        // INTEGER PRIMARY KEY) are reported as nullable=true by
27075        // table_info — we surface that as-is rather than fabricating.
27076        // The point is just that primary_key_ordinal is populated.
27077
27078        let name = schema.column("name").expect("name col");
27079        assert!(!name.nullable);
27080        assert!(name.default_value.is_none());
27081        assert!(name.primary_key_ordinal.is_none());
27082
27083        let status = schema.column("status").expect("status col");
27084        assert!(status.nullable);
27085        assert_eq!(
27086            status.default_value.as_deref(),
27087            Some("'active'"),
27088            "expected SQL literal default text"
27089        );
27090    }
27091
27092    #[cfg(feature = "sql-sqlite")]
27093    #[test]
27094    fn sql_table_schema_schema_silently_ignored_on_sqlite() {
27095        let conn = make_sql_test_conn();
27096        super::SqlConnection::execute_batch(&conn, "CREATE TABLE only_one (x INTEGER);").unwrap();
27097        let with_schema = sql_table_schema(&conn, "only_one", Some("ignored_on_sqlite"))
27098            .expect("schema arg must not error")
27099            .expect("table exists");
27100        let without_schema = sql_table_schema(&conn, "only_one", None).unwrap().unwrap();
27101        assert_eq!(with_schema, without_schema);
27102    }
27103
27104    #[cfg(feature = "sql-sqlite")]
27105    #[test]
27106    fn sql_table_schema_rejects_invalid_table_name() {
27107        // The PRAGMA path can't bind parameters, so we validate the
27108        // identifier first. Reject anything with non-alphanumeric chars.
27109        let conn = make_sql_test_conn();
27110        let err = sql_table_schema(&conn, "x; DROP TABLE users", None).expect_err("must reject");
27111        assert!(matches!(err, IoError::Sql(msg) if msg.contains("invalid")));
27112    }
27113
27114    #[test]
27115    fn sql_table_schema_default_impl_returns_none() {
27116        struct NoIntrospection;
27117        impl super::SqlConnection for NoIntrospection {
27118            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
27119                Ok(SqlQueryResult {
27120                    columns: vec![],
27121                    rows: vec![],
27122                })
27123            }
27124            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
27125                Ok(())
27126            }
27127            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
27128                Ok(false)
27129            }
27130            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
27131                Ok(())
27132            }
27133            fn dtype_sql(&self, _dtype: DType) -> &'static str {
27134                "TEXT"
27135            }
27136            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
27137                "TEXT"
27138            }
27139        }
27140        let conn = NoIntrospection;
27141        assert!(sql_table_schema(&conn, "anything", None).unwrap().is_none());
27142    }
27143
27144    #[test]
27145    fn sql_table_schema_routes_schema_to_backend_override() {
27146        struct MultiSchema;
27147        impl super::SqlConnection for MultiSchema {
27148            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
27149                Ok(SqlQueryResult {
27150                    columns: vec![],
27151                    rows: vec![],
27152                })
27153            }
27154            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
27155                Ok(())
27156            }
27157            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
27158                Ok(false)
27159            }
27160            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
27161                Ok(())
27162            }
27163            fn dtype_sql(&self, _dtype: DType) -> &'static str {
27164                "TEXT"
27165            }
27166            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
27167                "TEXT"
27168            }
27169            fn supports_schemas(&self) -> bool {
27170                true
27171            }
27172            fn table_schema(
27173                &self,
27174                table: &str,
27175                schema: Option<&str>,
27176            ) -> Result<Option<SqlTableSchema>, IoError> {
27177                if table == "users" && schema == Some("analytics") {
27178                    Ok(Some(SqlTableSchema {
27179                        table_name: "users".to_owned(),
27180                        columns: vec![SqlColumnSchema {
27181                            name: "id".to_owned(),
27182                            declared_type: Some("BIGINT".to_owned()),
27183                            nullable: false,
27184                            default_value: None,
27185                            primary_key_ordinal: Some(0),
27186                            comment: None,
27187                            autoincrement: false,
27188                        }],
27189                    }))
27190                } else {
27191                    Ok(None)
27192                }
27193            }
27194        }
27195        let conn = MultiSchema;
27196        let analytics_users = sql_table_schema(&conn, "users", Some("analytics"))
27197            .unwrap()
27198            .expect("found");
27199        assert_eq!(
27200            analytics_users.columns[0].declared_type.as_deref(),
27201            Some("BIGINT")
27202        );
27203        assert!(
27204            sql_table_schema(&conn, "users", Some("audit"))
27205                .unwrap()
27206                .is_none()
27207        );
27208        assert!(sql_table_schema(&conn, "users", None).unwrap().is_none());
27209    }
27210
27211    // ── list_sql_schemas / SqlConnection::list_schemas (br-lxhi / fd90.22) ─
27212
27213    #[cfg(feature = "sql-sqlite")]
27214    #[test]
27215    fn list_sql_schemas_returns_empty_on_sqlite() {
27216        // SQLite has no meaningful schema concept; the trait default
27217        // (empty Vec) is the right answer.
27218        let conn = make_sql_test_conn();
27219        let schemas = list_sql_schemas(&conn).unwrap();
27220        assert!(schemas.is_empty(), "expected no schemas; got {schemas:?}");
27221    }
27222
27223    #[test]
27224    fn list_sql_schemas_default_impl_returns_empty() {
27225        struct NoIntrospection;
27226        impl super::SqlConnection for NoIntrospection {
27227            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
27228                Ok(SqlQueryResult {
27229                    columns: vec![],
27230                    rows: vec![],
27231                })
27232            }
27233            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
27234                Ok(())
27235            }
27236            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
27237                Ok(false)
27238            }
27239            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
27240                Ok(())
27241            }
27242            fn dtype_sql(&self, _dtype: DType) -> &'static str {
27243                "TEXT"
27244            }
27245            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
27246                "TEXT"
27247            }
27248        }
27249        let conn = NoIntrospection;
27250        assert!(list_sql_schemas(&conn).unwrap().is_empty());
27251    }
27252
27253    #[test]
27254    fn list_sql_schemas_routes_to_backend_override() {
27255        // Multi-schema backend stub: returns the schemas the connection's
27256        // role can see, with internal schemas filtered out.
27257        struct MultiSchemaServer;
27258        impl super::SqlConnection for MultiSchemaServer {
27259            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
27260                Ok(SqlQueryResult {
27261                    columns: vec![],
27262                    rows: vec![],
27263                })
27264            }
27265            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
27266                Ok(())
27267            }
27268            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
27269                Ok(false)
27270            }
27271            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
27272                Ok(())
27273            }
27274            fn dtype_sql(&self, _dtype: DType) -> &'static str {
27275                "TEXT"
27276            }
27277            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
27278                "TEXT"
27279            }
27280            fn supports_schemas(&self) -> bool {
27281                true
27282            }
27283            fn list_schemas(&self) -> Result<Vec<String>, IoError> {
27284                // Filter out information_schema + pg_catalog by default.
27285                Ok(vec![
27286                    "public".to_owned(),
27287                    "analytics".to_owned(),
27288                    "audit".to_owned(),
27289                ])
27290            }
27291        }
27292        let conn = MultiSchemaServer;
27293        let schemas = list_sql_schemas(&conn).unwrap();
27294        assert_eq!(schemas, vec!["public", "analytics", "audit"]);
27295        // Verify the override actually filters internal schemas
27296        // (test contract: stub never returns 'pg_catalog' or
27297        // 'information_schema').
27298        assert!(!schemas.iter().any(|s| s.starts_with("pg_")));
27299        assert!(!schemas.iter().any(|s| s == "information_schema"));
27300    }
27301
27302    #[test]
27303    fn list_sql_schemas_propagates_backend_error() {
27304        // If the backend errors during introspection, the error should
27305        // surface through the wrapper unchanged.
27306        struct BrokenIntrospection;
27307        impl super::SqlConnection for BrokenIntrospection {
27308            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
27309                Ok(SqlQueryResult {
27310                    columns: vec![],
27311                    rows: vec![],
27312                })
27313            }
27314            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
27315                Ok(())
27316            }
27317            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
27318                Ok(false)
27319            }
27320            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
27321                Ok(())
27322            }
27323            fn dtype_sql(&self, _dtype: DType) -> &'static str {
27324                "TEXT"
27325            }
27326            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
27327                "TEXT"
27328            }
27329            fn list_schemas(&self) -> Result<Vec<String>, IoError> {
27330                Err(IoError::Sql("permission denied for catalog".to_owned()))
27331            }
27332        }
27333        let conn = BrokenIntrospection;
27334        let err = list_sql_schemas(&conn).expect_err("should surface backend error");
27335        assert!(matches!(err, IoError::Sql(msg) if msg.contains("permission denied")));
27336    }
27337
27338    // ── truncate_sql_table / SqlConnection::truncate_table (br-phum / fd90.23) ─
27339
27340    #[cfg(feature = "sql-sqlite")]
27341    #[test]
27342    fn truncate_sql_table_clears_rows_but_preserves_schema() {
27343        let conn = make_sql_test_conn();
27344        super::SqlConnection::execute_batch(&conn, "CREATE TABLE rolling (id INTEGER, val TEXT);")
27345            .unwrap();
27346        super::SqlConnection::execute_batch(
27347            &conn,
27348            "INSERT INTO rolling VALUES (1, 'a'), (2, 'b'), (3, 'c');",
27349        )
27350        .unwrap();
27351        // Sanity: rows present.
27352        let before =
27353            super::SqlConnection::query(&conn, "SELECT COUNT(*) FROM rolling", &[]).unwrap();
27354        assert_eq!(before.rows[0][0], Scalar::Int64(3));
27355
27356        truncate_sql_table(&conn, "rolling", None).unwrap();
27357
27358        // Rows gone, table still there.
27359        let after =
27360            super::SqlConnection::query(&conn, "SELECT COUNT(*) FROM rolling", &[]).unwrap();
27361        assert_eq!(after.rows[0][0], Scalar::Int64(0));
27362        assert!(super::SqlConnection::table_exists(&conn, "rolling").unwrap());
27363    }
27364
27365    #[cfg(feature = "sql-sqlite")]
27366    #[test]
27367    fn truncate_sql_table_schema_silently_ignored_on_sqlite() {
27368        let conn = make_sql_test_conn();
27369        super::SqlConnection::execute_batch(&conn, "CREATE TABLE t (x INTEGER);").unwrap();
27370        super::SqlConnection::execute_batch(&conn, "INSERT INTO t VALUES (1);").unwrap();
27371        truncate_sql_table(&conn, "t", Some("ignored_on_sqlite"))
27372            .expect("schema arg must not error on SQLite");
27373        let count = super::SqlConnection::query(&conn, "SELECT COUNT(*) FROM t", &[]).unwrap();
27374        assert_eq!(count.rows[0][0], Scalar::Int64(0));
27375    }
27376
27377    #[cfg(feature = "sql-sqlite")]
27378    #[test]
27379    fn truncate_sql_table_rejects_invalid_table_name() {
27380        let conn = make_sql_test_conn();
27381        let err = truncate_sql_table(&conn, "x; DROP TABLE users", None)
27382            .expect_err("must reject invalid identifier");
27383        assert!(matches!(err, IoError::Sql(msg) if msg.contains("invalid")));
27384    }
27385
27386    #[test]
27387    fn truncate_sql_table_routes_schema_to_quote_identifier() {
27388        // Multi-schema backend stub records the SQL it receives.
27389        use std::cell::RefCell;
27390        struct PgLikeRecorder {
27391            statements: RefCell<Vec<String>>,
27392        }
27393        impl super::SqlConnection for PgLikeRecorder {
27394            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
27395                Ok(SqlQueryResult {
27396                    columns: vec![],
27397                    rows: vec![],
27398                })
27399            }
27400            fn execute_batch(&self, sql: &str) -> Result<(), IoError> {
27401                self.statements.borrow_mut().push(sql.to_owned());
27402                Ok(())
27403            }
27404            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
27405                Ok(false)
27406            }
27407            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
27408                Ok(())
27409            }
27410            fn dtype_sql(&self, _dtype: DType) -> &'static str {
27411                "TEXT"
27412            }
27413            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
27414                "TEXT"
27415            }
27416            fn supports_schemas(&self) -> bool {
27417                true
27418            }
27419        }
27420        let conn = PgLikeRecorder {
27421            statements: RefCell::new(vec![]),
27422        };
27423        truncate_sql_table(&conn, "events", Some("analytics")).unwrap();
27424        let stmts = conn.statements.borrow();
27425        assert_eq!(stmts.len(), 1);
27426        // Default impl uses DELETE FROM ... and quote_identifier on
27427        // both schema + table parts.
27428        assert!(
27429            stmts[0].contains("DELETE FROM \"analytics\".\"events\""),
27430            "expected schema-qualified DELETE; got: {}",
27431            stmts[0]
27432        );
27433    }
27434
27435    #[test]
27436    fn truncate_sql_table_backend_override_uses_truncate_keyword() {
27437        // PG/MySQL impls would override with TRUNCATE TABLE for speed.
27438        // Verify the trait dispatch picks up the override.
27439        use std::cell::RefCell;
27440        struct FastTruncate {
27441            statements: RefCell<Vec<String>>,
27442        }
27443        impl super::SqlConnection for FastTruncate {
27444            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
27445                Ok(SqlQueryResult {
27446                    columns: vec![],
27447                    rows: vec![],
27448                })
27449            }
27450            fn execute_batch(&self, sql: &str) -> Result<(), IoError> {
27451                self.statements.borrow_mut().push(sql.to_owned());
27452                Ok(())
27453            }
27454            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
27455                Ok(false)
27456            }
27457            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
27458                Ok(())
27459            }
27460            fn dtype_sql(&self, _dtype: DType) -> &'static str {
27461                "TEXT"
27462            }
27463            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
27464                "TEXT"
27465            }
27466            fn truncate_table(
27467                &self,
27468                table_name: &str,
27469                _schema: Option<&str>,
27470            ) -> Result<(), IoError> {
27471                self.execute_batch(&format!("TRUNCATE TABLE \"{table_name}\""))
27472            }
27473        }
27474        let conn = FastTruncate {
27475            statements: RefCell::new(vec![]),
27476        };
27477        truncate_sql_table(&conn, "events", None).unwrap();
27478        let stmts = conn.statements.borrow();
27479        assert_eq!(stmts.len(), 1);
27480        assert!(stmts[0].starts_with("TRUNCATE TABLE"), "got: {}", stmts[0]);
27481    }
27482
27483    // ── sql_server_version / SqlConnection::server_version (br-e23k / fd90.24) ─
27484
27485    #[cfg(feature = "sql-sqlite")]
27486    #[test]
27487    fn sql_server_version_returns_sqlite_version_string() {
27488        let conn = make_sql_test_conn();
27489        let version = sql_server_version(&conn)
27490            .unwrap()
27491            .expect("SQLite reports version");
27492        // Expect dotted-version format like "3.45.1". The parts must be
27493        // non-empty digits — exact value depends on the bundled SQLite.
27494        let parts: Vec<&str> = version.split('.').collect();
27495        assert!(parts.len() >= 2, "expected dotted version; got: {version}");
27496        for part in &parts {
27497            assert!(
27498                !part.is_empty() && part.chars().all(|c| c.is_ascii_digit()),
27499                "expected numeric version parts; got {version}"
27500            );
27501        }
27502    }
27503
27504    #[cfg(feature = "sql-sqlite")]
27505    #[test]
27506    fn sql_server_version_starts_with_three_for_sqlite_3_x() {
27507        // SQLite has been at major version 3 since 2004; bundled
27508        // rusqlite is current (3.40+), so the major must be "3".
27509        let conn = make_sql_test_conn();
27510        let version = sql_server_version(&conn).unwrap().unwrap();
27511        assert!(
27512            version.starts_with("3."),
27513            "expected SQLite 3.x; got {version}"
27514        );
27515    }
27516
27517    #[test]
27518    fn sql_server_version_default_impl_returns_none() {
27519        struct NoIntrospection;
27520        impl super::SqlConnection for NoIntrospection {
27521            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
27522                Ok(SqlQueryResult {
27523                    columns: vec![],
27524                    rows: vec![],
27525                })
27526            }
27527            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
27528                Ok(())
27529            }
27530            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
27531                Ok(false)
27532            }
27533            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
27534                Ok(())
27535            }
27536            fn dtype_sql(&self, _dtype: DType) -> &'static str {
27537                "TEXT"
27538            }
27539            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
27540                "TEXT"
27541            }
27542        }
27543        let conn = NoIntrospection;
27544        assert!(sql_server_version(&conn).unwrap().is_none());
27545    }
27546
27547    #[test]
27548    fn sql_server_version_routes_to_backend_override() {
27549        struct PgLikeStub;
27550        impl super::SqlConnection for PgLikeStub {
27551            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
27552                Ok(SqlQueryResult {
27553                    columns: vec![],
27554                    rows: vec![],
27555                })
27556            }
27557            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
27558                Ok(())
27559            }
27560            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
27561                Ok(false)
27562            }
27563            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
27564                Ok(())
27565            }
27566            fn dtype_sql(&self, _dtype: DType) -> &'static str {
27567                "TEXT"
27568            }
27569            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
27570                "TEXT"
27571            }
27572            fn server_version(&self) -> Result<Option<String>, IoError> {
27573                // Mimic `SHOW server_version` payload.
27574                Ok(Some("16.2".to_owned()))
27575            }
27576        }
27577        let conn = PgLikeStub;
27578        assert_eq!(sql_server_version(&conn).unwrap().as_deref(), Some("16.2"));
27579    }
27580
27581    #[test]
27582    fn sql_server_version_propagates_backend_error() {
27583        struct BrokenIntrospection;
27584        impl super::SqlConnection for BrokenIntrospection {
27585            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
27586                Ok(SqlQueryResult {
27587                    columns: vec![],
27588                    rows: vec![],
27589                })
27590            }
27591            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
27592                Ok(())
27593            }
27594            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
27595                Ok(false)
27596            }
27597            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
27598                Ok(())
27599            }
27600            fn dtype_sql(&self, _dtype: DType) -> &'static str {
27601                "TEXT"
27602            }
27603            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
27604                "TEXT"
27605            }
27606            fn server_version(&self) -> Result<Option<String>, IoError> {
27607                Err(IoError::Sql("connection lost".to_owned()))
27608            }
27609        }
27610        let conn = BrokenIntrospection;
27611        let err = sql_server_version(&conn).expect_err("should surface backend error");
27612        assert!(matches!(err, IoError::Sql(msg) if msg.contains("connection lost")));
27613    }
27614
27615    // ── sql_primary_key_columns / SqlConnection::primary_key_columns
27616    //    (br-uw3y / fd90.25) ────────────────────────────────────────────────
27617
27618    #[cfg(feature = "sql-sqlite")]
27619    #[test]
27620    fn sql_primary_key_columns_unknown_table_returns_empty() {
27621        let conn = make_sql_test_conn();
27622        let pk = sql_primary_key_columns(&conn, "no_such_table", None).unwrap();
27623        assert!(pk.is_empty());
27624    }
27625
27626    #[cfg(feature = "sql-sqlite")]
27627    #[test]
27628    fn sql_primary_key_columns_table_without_pk_returns_empty() {
27629        let conn = make_sql_test_conn();
27630        super::SqlConnection::execute_batch(&conn, "CREATE TABLE no_pk (a INTEGER, b TEXT);")
27631            .unwrap();
27632        let pk = sql_primary_key_columns(&conn, "no_pk", None).unwrap();
27633        assert!(pk.is_empty());
27634    }
27635
27636    #[cfg(feature = "sql-sqlite")]
27637    #[test]
27638    fn sql_primary_key_columns_single_pk() {
27639        let conn = make_sql_test_conn();
27640        super::SqlConnection::execute_batch(
27641            &conn,
27642            "CREATE TABLE single_pk (id INTEGER PRIMARY KEY, name TEXT);",
27643        )
27644        .unwrap();
27645        let pk = sql_primary_key_columns(&conn, "single_pk", None).unwrap();
27646        assert_eq!(pk, vec!["id"]);
27647    }
27648
27649    #[cfg(feature = "sql-sqlite")]
27650    #[test]
27651    fn sql_primary_key_columns_composite_pk_ordered_by_ordinal() {
27652        let conn = make_sql_test_conn();
27653        super::SqlConnection::execute_batch(
27654            &conn,
27655            "CREATE TABLE composite ( \
27656                year INTEGER NOT NULL, \
27657                month INTEGER NOT NULL, \
27658                code TEXT NOT NULL, \
27659                value REAL, \
27660                PRIMARY KEY (year, month, code) \
27661             );",
27662        )
27663        .unwrap();
27664        let pk = sql_primary_key_columns(&conn, "composite", None).unwrap();
27665        // PK declaration order: year, month, code.
27666        assert_eq!(pk, vec!["year", "month", "code"]);
27667    }
27668
27669    #[test]
27670    fn sql_primary_key_columns_default_impl_returns_empty_when_no_introspection() {
27671        // Backend with no table_schema override returns Ok(None) →
27672        // primary_key_columns falls through to empty Vec.
27673        struct NoIntrospection;
27674        impl super::SqlConnection for NoIntrospection {
27675            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
27676                Ok(SqlQueryResult {
27677                    columns: vec![],
27678                    rows: vec![],
27679                })
27680            }
27681            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
27682                Ok(())
27683            }
27684            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
27685                Ok(false)
27686            }
27687            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
27688                Ok(())
27689            }
27690            fn dtype_sql(&self, _dtype: DType) -> &'static str {
27691                "TEXT"
27692            }
27693            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
27694                "TEXT"
27695            }
27696        }
27697        let conn = NoIntrospection;
27698        assert!(
27699            sql_primary_key_columns(&conn, "anything", None)
27700                .unwrap()
27701                .is_empty()
27702        );
27703    }
27704
27705    #[test]
27706    fn sql_primary_key_columns_routes_schema_to_table_schema_override() {
27707        // Backend that returns ordinal-sorted PK columns from a
27708        // multi-schema introspection.
27709        struct MultiSchemaPk;
27710        impl super::SqlConnection for MultiSchemaPk {
27711            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
27712                Ok(SqlQueryResult {
27713                    columns: vec![],
27714                    rows: vec![],
27715                })
27716            }
27717            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
27718                Ok(())
27719            }
27720            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
27721                Ok(false)
27722            }
27723            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
27724                Ok(())
27725            }
27726            fn dtype_sql(&self, _dtype: DType) -> &'static str {
27727                "TEXT"
27728            }
27729            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
27730                "TEXT"
27731            }
27732            fn supports_schemas(&self) -> bool {
27733                true
27734            }
27735            fn table_schema(
27736                &self,
27737                table: &str,
27738                schema: Option<&str>,
27739            ) -> Result<Option<SqlTableSchema>, IoError> {
27740                if table == "events" && schema == Some("analytics") {
27741                    Ok(Some(SqlTableSchema {
27742                        table_name: "events".to_owned(),
27743                        columns: vec![
27744                            // Intentionally out-of-declaration-order to
27745                            // verify the helper sorts by ordinal.
27746                            SqlColumnSchema {
27747                                name: "code".to_owned(),
27748                                declared_type: Some("TEXT".to_owned()),
27749                                nullable: false,
27750                                default_value: None,
27751                                primary_key_ordinal: Some(2),
27752                                comment: None,
27753                                autoincrement: false,
27754                            },
27755                            SqlColumnSchema {
27756                                name: "year".to_owned(),
27757                                declared_type: Some("INTEGER".to_owned()),
27758                                nullable: false,
27759                                default_value: None,
27760                                primary_key_ordinal: Some(0),
27761                                comment: None,
27762                                autoincrement: false,
27763                            },
27764                            SqlColumnSchema {
27765                                name: "value".to_owned(),
27766                                declared_type: Some("REAL".to_owned()),
27767                                nullable: true,
27768                                default_value: None,
27769                                primary_key_ordinal: None,
27770                                comment: None,
27771                                autoincrement: false,
27772                            },
27773                            SqlColumnSchema {
27774                                name: "month".to_owned(),
27775                                declared_type: Some("INTEGER".to_owned()),
27776                                nullable: false,
27777                                default_value: None,
27778                                primary_key_ordinal: Some(1),
27779                                comment: None,
27780                                autoincrement: false,
27781                            },
27782                        ],
27783                    }))
27784                } else {
27785                    Ok(None)
27786                }
27787            }
27788        }
27789        let conn = MultiSchemaPk;
27790        let pk = sql_primary_key_columns(&conn, "events", Some("analytics")).unwrap();
27791        // Sorted by primary_key_ordinal: 0=year, 1=month, 2=code.
27792        assert_eq!(pk, vec!["year", "month", "code"]);
27793        // Wrong schema → empty (table_schema returns None).
27794        assert!(
27795            sql_primary_key_columns(&conn, "events", Some("audit"))
27796                .unwrap()
27797                .is_empty()
27798        );
27799    }
27800
27801    // ── sql_max_identifier_length / SqlConnection::max_identifier_length
27802    //    (br-cs81 / fd90.26) ────────────────────────────────────────────────
27803
27804    #[cfg(feature = "sql-sqlite")]
27805    #[test]
27806    fn sql_max_identifier_length_returns_none_on_sqlite() {
27807        // SQLite has no documented identifier-length limit; the trait
27808        // default (None) is the right answer.
27809        let conn = make_sql_test_conn();
27810        assert_eq!(sql_max_identifier_length(&conn), None);
27811    }
27812
27813    #[test]
27814    fn sql_max_identifier_length_default_impl_returns_none() {
27815        struct Generic;
27816        impl super::SqlConnection for Generic {
27817            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
27818                Ok(SqlQueryResult {
27819                    columns: vec![],
27820                    rows: vec![],
27821                })
27822            }
27823            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
27824                Ok(())
27825            }
27826            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
27827                Ok(false)
27828            }
27829            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
27830                Ok(())
27831            }
27832            fn dtype_sql(&self, _dtype: DType) -> &'static str {
27833                "TEXT"
27834            }
27835            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
27836                "TEXT"
27837            }
27838        }
27839        assert_eq!(sql_max_identifier_length(&Generic), None);
27840    }
27841
27842    #[test]
27843    fn sql_max_identifier_length_pg_override_reports_63() {
27844        struct PgLikeStub;
27845        impl super::SqlConnection for PgLikeStub {
27846            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
27847                Ok(SqlQueryResult {
27848                    columns: vec![],
27849                    rows: vec![],
27850                })
27851            }
27852            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
27853                Ok(())
27854            }
27855            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
27856                Ok(false)
27857            }
27858            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
27859                Ok(())
27860            }
27861            fn dtype_sql(&self, _dtype: DType) -> &'static str {
27862                "TEXT"
27863            }
27864            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
27865                "TEXT"
27866            }
27867            fn max_identifier_length(&self) -> Option<usize> {
27868                Some(63)
27869            }
27870        }
27871        assert_eq!(sql_max_identifier_length(&PgLikeStub), Some(63));
27872    }
27873
27874    #[test]
27875    fn sql_max_identifier_length_mysql_override_reports_64() {
27876        struct MySqlLikeStub;
27877        impl super::SqlConnection for MySqlLikeStub {
27878            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
27879                Ok(SqlQueryResult {
27880                    columns: vec![],
27881                    rows: vec![],
27882                })
27883            }
27884            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
27885                Ok(())
27886            }
27887            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
27888                Ok(false)
27889            }
27890            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
27891                Ok(())
27892            }
27893            fn dtype_sql(&self, _dtype: DType) -> &'static str {
27894                "TEXT"
27895            }
27896            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
27897                "TEXT"
27898            }
27899            fn max_identifier_length(&self) -> Option<usize> {
27900                Some(64)
27901            }
27902        }
27903        assert_eq!(sql_max_identifier_length(&MySqlLikeStub), Some(64));
27904    }
27905
27906    #[test]
27907    fn sql_max_identifier_length_mssql_override_reports_128() {
27908        struct MsSqlLikeStub;
27909        impl super::SqlConnection for MsSqlLikeStub {
27910            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
27911                Ok(SqlQueryResult {
27912                    columns: vec![],
27913                    rows: vec![],
27914                })
27915            }
27916            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
27917                Ok(())
27918            }
27919            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
27920                Ok(false)
27921            }
27922            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
27923                Ok(())
27924            }
27925            fn dtype_sql(&self, _dtype: DType) -> &'static str {
27926                "TEXT"
27927            }
27928            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
27929                "TEXT"
27930            }
27931            fn max_identifier_length(&self) -> Option<usize> {
27932                Some(128)
27933            }
27934        }
27935        assert_eq!(sql_max_identifier_length(&MsSqlLikeStub), Some(128));
27936    }
27937
27938    // ── sql backend capability probes / SqlInspector caps
27939    //    (frankenpandas-fd90.10) ───────────────────────────────────────────
27940
27941    #[cfg(feature = "sql-sqlite")]
27942    #[test]
27943    fn sql_backend_caps_sqlite_reports_param_and_row_caps() {
27944        let conn = make_sql_test_conn();
27945        let caps = sql_backend_caps(&conn).unwrap();
27946
27947        assert_eq!(caps.dialect_name, "sqlite");
27948        assert!(
27949            caps.server_version
27950                .as_deref()
27951                .is_some_and(|v| v.starts_with("3."))
27952        );
27953        assert!(caps.supports_returning);
27954        assert!(!caps.supports_schemas);
27955        assert_eq!(caps.max_param_count, Some(32766));
27956        assert_eq!(caps.max_identifier_length, None);
27957        assert_eq!(caps.max_insert_rows(3), Some(10922));
27958        assert_eq!(caps.max_insert_rows(0), None);
27959        assert_eq!(sql_max_param_count(&conn), Some(32766));
27960        assert_eq!(sql_max_insert_rows(&conn, 4), Some(8191));
27961        assert!(sql_supports_returning(&conn));
27962        assert!(!sql_supports_schemas(&conn));
27963    }
27964
27965    #[test]
27966    fn sql_inspector_backend_caps_pg_like_stub_reports_limits() {
27967        struct PgLikeCaps;
27968        impl super::SqlConnection for PgLikeCaps {
27969            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
27970                Ok(SqlQueryResult {
27971                    columns: vec![],
27972                    rows: vec![],
27973                })
27974            }
27975            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
27976                Ok(())
27977            }
27978            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
27979                Ok(false)
27980            }
27981            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
27982                Ok(())
27983            }
27984            fn dtype_sql(&self, _dtype: DType) -> &'static str {
27985                "TEXT"
27986            }
27987            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
27988                "TEXT"
27989            }
27990            fn dialect_name(&self) -> &'static str {
27991                "postgresql"
27992            }
27993            fn server_version(&self) -> Result<Option<String>, IoError> {
27994                Ok(Some("16.3".to_owned()))
27995            }
27996            fn supports_returning(&self) -> bool {
27997                true
27998            }
27999            fn supports_schemas(&self) -> bool {
28000                true
28001            }
28002            fn max_param_count(&self) -> Option<usize> {
28003                Some(65535)
28004            }
28005            fn max_identifier_length(&self) -> Option<usize> {
28006                Some(63)
28007            }
28008        }
28009
28010        let conn = PgLikeCaps;
28011        let inspector = SqlInspector::new(&conn);
28012        let caps = inspector.backend_caps().unwrap();
28013
28014        assert_eq!(inspector.dialect_name(), "postgresql");
28015        assert_eq!(inspector.server_version().unwrap().as_deref(), Some("16.3"));
28016        assert!(inspector.supports_returning());
28017        assert!(inspector.supports_schemas());
28018        assert_eq!(inspector.max_param_count(), Some(65535));
28019        assert_eq!(inspector.max_identifier_length(), Some(63));
28020        assert_eq!(inspector.max_insert_rows(4), Some(16383));
28021        assert_eq!(caps.max_insert_rows(4), Some(16383));
28022        assert_eq!(
28023            caps,
28024            SqlBackendCaps {
28025                dialect_name: "postgresql",
28026                server_version: Some("16.3".to_owned()),
28027                supports_returning: true,
28028                supports_schemas: true,
28029                max_param_count: Some(65535),
28030                max_identifier_length: Some(63),
28031            }
28032        );
28033    }
28034
28035    // ── write_sql identifier-length validation (br-9ynk / fd90.27) ────────
28036
28037    #[cfg(feature = "sql-sqlite")]
28038    #[test]
28039    fn write_sql_long_column_name_succeeds_on_sqlite() {
28040        // SQLite reports max_identifier_length() == None → no validation.
28041        let conn = make_sql_test_conn();
28042        // 80 chars > PG/MySQL caps but fine on SQLite.
28043        let long_col: String = std::iter::repeat_n('a', 80).collect();
28044        let frame = fp_frame::DataFrame::from_dict(
28045            &[long_col.as_str()],
28046            vec![(long_col.as_str(), vec![Scalar::Int64(1)])],
28047        )
28048        .unwrap();
28049        write_sql_with_options(
28050            &frame,
28051            &conn,
28052            "long_col_tbl",
28053            &SqlWriteOptions {
28054                if_exists: SqlIfExists::Fail,
28055                index: false,
28056                index_label: None,
28057                schema: None,
28058                dtype: None,
28059                method: SqlInsertMethod::Single,
28060                chunksize: None,
28061            },
28062        )
28063        .expect("SQLite has no identifier limit");
28064    }
28065
28066    fn make_pg_like_recorder() -> impl super::SqlConnection + 'static {
28067        // Stub PG-like backend: enforces 63-char limit, accepts all
28068        // execute_batch / insert_rows so write_sql can reach the
28069        // identifier-length check before failing on emit.
28070        struct PgLikeLimit;
28071        impl super::SqlConnection for PgLikeLimit {
28072            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
28073                Ok(SqlQueryResult {
28074                    columns: vec![],
28075                    rows: vec![],
28076                })
28077            }
28078            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
28079                Ok(())
28080            }
28081            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
28082                Ok(false)
28083            }
28084            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
28085                Ok(())
28086            }
28087            fn dtype_sql(&self, _dtype: DType) -> &'static str {
28088                "TEXT"
28089            }
28090            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
28091                "TEXT"
28092            }
28093            fn max_identifier_length(&self) -> Option<usize> {
28094                Some(63)
28095            }
28096            fn supports_schemas(&self) -> bool {
28097                true
28098            }
28099        }
28100        PgLikeLimit
28101    }
28102
28103    #[test]
28104    fn write_sql_rejects_long_column_name_on_pg_like_backend() {
28105        let conn = make_pg_like_recorder();
28106        let long_col: String = std::iter::repeat_n('c', 64).collect();
28107        let frame = fp_frame::DataFrame::from_dict(
28108            &[long_col.as_str()],
28109            vec![(long_col.as_str(), vec![Scalar::Int64(1)])],
28110        )
28111        .unwrap();
28112        let err = write_sql_with_options(
28113            &frame,
28114            &conn,
28115            "ok_tbl",
28116            &SqlWriteOptions {
28117                if_exists: SqlIfExists::Fail,
28118                index: false,
28119                index_label: None,
28120                schema: None,
28121                dtype: None,
28122                method: SqlInsertMethod::Single,
28123                chunksize: None,
28124            },
28125        )
28126        .expect_err("64-char column must exceed PG limit");
28127        assert!(matches!(err, IoError::Sql(msg) if msg.contains("column") && msg.contains("63")));
28128    }
28129
28130    #[test]
28131    fn write_sql_rejects_long_table_name_on_pg_like_backend() {
28132        let conn = make_pg_like_recorder();
28133        // 64-char identifier (table names also subject to the PG cap).
28134        // Use only alphanumeric so validate_sql_table_name passes first.
28135        let long_tbl: String = std::iter::repeat_n('t', 64).collect();
28136        let frame =
28137            fp_frame::DataFrame::from_dict(&["x"], vec![("x", vec![Scalar::Int64(1)])]).unwrap();
28138        let err = write_sql_with_options(
28139            &frame,
28140            &conn,
28141            &long_tbl,
28142            &SqlWriteOptions {
28143                if_exists: SqlIfExists::Fail,
28144                index: false,
28145                index_label: None,
28146                schema: None,
28147                dtype: None,
28148                method: SqlInsertMethod::Single,
28149                chunksize: None,
28150            },
28151        )
28152        .expect_err("64-char table must exceed PG limit");
28153        assert!(matches!(err, IoError::Sql(msg) if msg.contains("table") && msg.contains("63")));
28154    }
28155
28156    #[test]
28157    fn write_sql_rejects_long_index_label_on_pg_like_backend() {
28158        let conn = make_pg_like_recorder();
28159        let long_label: String = std::iter::repeat_n('i', 64).collect();
28160        let frame =
28161            fp_frame::DataFrame::from_dict(&["x"], vec![("x", vec![Scalar::Int64(1)])]).unwrap();
28162        let err = write_sql_with_options(
28163            &frame,
28164            &conn,
28165            "ok_tbl",
28166            &SqlWriteOptions {
28167                if_exists: SqlIfExists::Fail,
28168                index: true,
28169                index_label: Some(long_label),
28170                schema: None,
28171                dtype: None,
28172                method: SqlInsertMethod::Single,
28173                chunksize: None,
28174            },
28175        )
28176        .expect_err("64-char index label must exceed PG limit");
28177        assert!(
28178            matches!(err, IoError::Sql(msg) if msg.contains("index label") && msg.contains("63"))
28179        );
28180    }
28181
28182    #[test]
28183    fn write_sql_rejects_long_schema_name_on_pg_like_backend() {
28184        let conn = make_pg_like_recorder();
28185        let long_schema: String = std::iter::repeat_n('s', 64).collect();
28186        let frame =
28187            fp_frame::DataFrame::from_dict(&["x"], vec![("x", vec![Scalar::Int64(1)])]).unwrap();
28188        let err = write_sql_with_options(
28189            &frame,
28190            &conn,
28191            "ok_tbl",
28192            &SqlWriteOptions {
28193                if_exists: SqlIfExists::Fail,
28194                index: false,
28195                index_label: None,
28196                schema: Some(long_schema),
28197                dtype: None,
28198                method: SqlInsertMethod::Single,
28199                chunksize: None,
28200            },
28201        )
28202        .expect_err("64-char schema must exceed PG limit");
28203        assert!(matches!(err, IoError::Sql(msg) if msg.contains("schema") && msg.contains("63")));
28204    }
28205
28206    #[test]
28207    fn write_sql_just_at_the_boundary_is_accepted() {
28208        let conn = make_pg_like_recorder();
28209        // Exactly 63 chars: at the PG limit, must be accepted.
28210        let just_fits: String = std::iter::repeat_n('a', 63).collect();
28211        let frame = fp_frame::DataFrame::from_dict(
28212            &[just_fits.as_str()],
28213            vec![(just_fits.as_str(), vec![Scalar::Int64(1)])],
28214        )
28215        .unwrap();
28216        write_sql_with_options(
28217            &frame,
28218            &conn,
28219            "ok_tbl",
28220            &SqlWriteOptions {
28221                if_exists: SqlIfExists::Fail,
28222                index: false,
28223                index_label: None,
28224                schema: None,
28225                dtype: None,
28226                method: SqlInsertMethod::Single,
28227                chunksize: None,
28228            },
28229        )
28230        .expect("63-char column at boundary should be accepted");
28231    }
28232
28233    // ── list_sql_indexes / SqlConnection::list_indexes (br-bgv9 / fd90.28) ─
28234
28235    #[cfg(feature = "sql-sqlite")]
28236    #[test]
28237    fn list_sql_indexes_unknown_table_returns_empty() {
28238        let conn = make_sql_test_conn();
28239        let indexes = list_sql_indexes(&conn, "no_such_tbl", None).unwrap();
28240        assert!(indexes.is_empty());
28241    }
28242
28243    #[cfg(feature = "sql-sqlite")]
28244    #[test]
28245    fn list_sql_indexes_table_without_indexes() {
28246        let conn = make_sql_test_conn();
28247        super::SqlConnection::execute_batch(&conn, "CREATE TABLE plain (a INTEGER, b TEXT);")
28248            .unwrap();
28249        let indexes = list_sql_indexes(&conn, "plain", None).unwrap();
28250        assert!(indexes.is_empty());
28251    }
28252
28253    #[cfg(feature = "sql-sqlite")]
28254    #[test]
28255    fn list_sql_indexes_single_column() {
28256        let conn = make_sql_test_conn();
28257        super::SqlConnection::execute_batch(&conn, "CREATE TABLE events (id INTEGER, ts TEXT);")
28258            .unwrap();
28259        super::SqlConnection::execute_batch(&conn, "CREATE INDEX idx_events_ts ON events (ts);")
28260            .unwrap();
28261        let indexes = list_sql_indexes(&conn, "events", None).unwrap();
28262        assert_eq!(indexes.len(), 1);
28263        assert_eq!(indexes[0].name, "idx_events_ts");
28264        assert_eq!(indexes[0].columns, vec!["ts"]);
28265        assert!(!indexes[0].unique);
28266    }
28267
28268    #[cfg(feature = "sql-sqlite")]
28269    #[test]
28270    fn list_sql_indexes_unique_index() {
28271        let conn = make_sql_test_conn();
28272        super::SqlConnection::execute_batch(&conn, "CREATE TABLE users (id INTEGER, email TEXT);")
28273            .unwrap();
28274        super::SqlConnection::execute_batch(
28275            &conn,
28276            "CREATE UNIQUE INDEX idx_users_email ON users (email);",
28277        )
28278        .unwrap();
28279        let indexes = list_sql_indexes(&conn, "users", None).unwrap();
28280        assert_eq!(indexes.len(), 1);
28281        assert_eq!(indexes[0].name, "idx_users_email");
28282        assert_eq!(indexes[0].columns, vec!["email"]);
28283        assert!(indexes[0].unique);
28284    }
28285
28286    #[cfg(feature = "sql-sqlite")]
28287    #[test]
28288    fn list_sql_indexes_composite_columns_in_definition_order() {
28289        let conn = make_sql_test_conn();
28290        super::SqlConnection::execute_batch(
28291            &conn,
28292            "CREATE TABLE rolling (year INT, month INT, code TEXT, val REAL);",
28293        )
28294        .unwrap();
28295        super::SqlConnection::execute_batch(
28296            &conn,
28297            "CREATE INDEX idx_rolling_y_m_c ON rolling (year, month, code);",
28298        )
28299        .unwrap();
28300        let indexes = list_sql_indexes(&conn, "rolling", None).unwrap();
28301        assert_eq!(indexes.len(), 1);
28302        assert_eq!(indexes[0].columns, vec!["year", "month", "code"]);
28303    }
28304
28305    #[cfg(feature = "sql-sqlite")]
28306    #[test]
28307    fn list_sql_indexes_filters_pk_auto_index() {
28308        // INTEGER PRIMARY KEY in SQLite creates an automatic index that
28309        // SQLAlchemy.Inspector hides. We must hide it too — only the
28310        // explicit CREATE INDEX should surface.
28311        let conn = make_sql_test_conn();
28312        super::SqlConnection::execute_batch(
28313            &conn,
28314            "CREATE TABLE pk_only (id INTEGER PRIMARY KEY, name TEXT);",
28315        )
28316        .unwrap();
28317        super::SqlConnection::execute_batch(
28318            &conn,
28319            "CREATE INDEX idx_pk_only_name ON pk_only (name);",
28320        )
28321        .unwrap();
28322        let indexes = list_sql_indexes(&conn, "pk_only", None).unwrap();
28323        // Only the explicit user index should appear.
28324        assert_eq!(indexes.len(), 1);
28325        assert_eq!(indexes[0].name, "idx_pk_only_name");
28326    }
28327
28328    #[cfg(feature = "sql-sqlite")]
28329    #[test]
28330    fn list_sql_indexes_rejects_invalid_table_name() {
28331        let conn = make_sql_test_conn();
28332        let err = list_sql_indexes(&conn, "x; DROP TABLE users", None)
28333            .expect_err("must reject invalid identifier");
28334        assert!(matches!(err, IoError::Sql(msg) if msg.contains("invalid")));
28335    }
28336
28337    #[test]
28338    fn list_sql_indexes_default_impl_returns_empty() {
28339        struct NoIntrospection;
28340        impl super::SqlConnection for NoIntrospection {
28341            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
28342                Ok(SqlQueryResult {
28343                    columns: vec![],
28344                    rows: vec![],
28345                })
28346            }
28347            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
28348                Ok(())
28349            }
28350            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
28351                Ok(false)
28352            }
28353            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
28354                Ok(())
28355            }
28356            fn dtype_sql(&self, _dtype: DType) -> &'static str {
28357                "TEXT"
28358            }
28359            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
28360                "TEXT"
28361            }
28362        }
28363        assert!(
28364            list_sql_indexes(&NoIntrospection, "anything", None)
28365                .unwrap()
28366                .is_empty()
28367        );
28368    }
28369
28370    #[test]
28371    fn list_sql_indexes_routes_to_backend_override() {
28372        struct MultiSchemaIdx;
28373        impl super::SqlConnection for MultiSchemaIdx {
28374            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
28375                Ok(SqlQueryResult {
28376                    columns: vec![],
28377                    rows: vec![],
28378                })
28379            }
28380            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
28381                Ok(())
28382            }
28383            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
28384                Ok(false)
28385            }
28386            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
28387                Ok(())
28388            }
28389            fn dtype_sql(&self, _dtype: DType) -> &'static str {
28390                "TEXT"
28391            }
28392            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
28393                "TEXT"
28394            }
28395            fn supports_schemas(&self) -> bool {
28396                true
28397            }
28398            fn list_indexes(
28399                &self,
28400                table: &str,
28401                schema: Option<&str>,
28402            ) -> Result<Vec<SqlIndexSchema>, IoError> {
28403                if table == "events" && schema == Some("analytics") {
28404                    Ok(vec![
28405                        SqlIndexSchema {
28406                            name: "idx_events_ts".to_owned(),
28407                            columns: vec!["ts".to_owned()],
28408                            unique: false,
28409                        },
28410                        SqlIndexSchema {
28411                            name: "uq_events_uid".to_owned(),
28412                            columns: vec!["user_id".to_owned()],
28413                            unique: true,
28414                        },
28415                    ])
28416                } else {
28417                    Ok(vec![])
28418                }
28419            }
28420        }
28421        let conn = MultiSchemaIdx;
28422        let indexes = list_sql_indexes(&conn, "events", Some("analytics")).unwrap();
28423        assert_eq!(indexes.len(), 2);
28424        assert!(
28425            indexes
28426                .iter()
28427                .any(|i| i.unique && i.name == "uq_events_uid")
28428        );
28429        // Wrong schema → empty (override scopes by Some).
28430        assert!(
28431            list_sql_indexes(&conn, "events", Some("audit"))
28432                .unwrap()
28433                .is_empty()
28434        );
28435    }
28436
28437    // ── list_sql_foreign_keys / SqlConnection::list_foreign_keys
28438    //    (br-uht8 / fd90.29) ────────────────────────────────────────────────
28439
28440    #[cfg(feature = "sql-sqlite")]
28441    #[test]
28442    fn list_sql_foreign_keys_unknown_table_returns_empty() {
28443        let conn = make_sql_test_conn();
28444        let fks = list_sql_foreign_keys(&conn, "no_such_tbl", None).unwrap();
28445        assert!(fks.is_empty());
28446    }
28447
28448    #[cfg(feature = "sql-sqlite")]
28449    #[test]
28450    fn list_sql_foreign_keys_table_without_fk() {
28451        let conn = make_sql_test_conn();
28452        super::SqlConnection::execute_batch(&conn, "CREATE TABLE plain (a INTEGER, b TEXT);")
28453            .unwrap();
28454        let fks = list_sql_foreign_keys(&conn, "plain", None).unwrap();
28455        assert!(fks.is_empty());
28456    }
28457
28458    #[cfg(feature = "sql-sqlite")]
28459    #[test]
28460    fn list_sql_foreign_keys_single_column_fk() {
28461        let conn = make_sql_test_conn();
28462        super::SqlConnection::execute_batch(
28463            &conn,
28464            "CREATE TABLE parent (id INTEGER PRIMARY KEY, label TEXT);",
28465        )
28466        .unwrap();
28467        super::SqlConnection::execute_batch(
28468            &conn,
28469            "CREATE TABLE child (cid INTEGER, parent_id INTEGER, \
28470             FOREIGN KEY (parent_id) REFERENCES parent(id));",
28471        )
28472        .unwrap();
28473        let fks = list_sql_foreign_keys(&conn, "child", None).unwrap();
28474        assert_eq!(fks.len(), 1);
28475        assert_eq!(fks[0].columns, vec!["parent_id"]);
28476        assert_eq!(fks[0].referenced_table, "parent");
28477        assert_eq!(fks[0].referenced_columns, vec!["id"]);
28478        // SQLite PRAGMA does not surface constraint names.
28479        assert!(fks[0].constraint_name.is_none());
28480    }
28481
28482    #[cfg(feature = "sql-sqlite")]
28483    #[test]
28484    fn list_sql_foreign_keys_composite_fk_ordered_by_seq() {
28485        let conn = make_sql_test_conn();
28486        super::SqlConnection::execute_batch(
28487            &conn,
28488            "CREATE TABLE rolling ( \
28489                year INTEGER NOT NULL, \
28490                month INTEGER NOT NULL, \
28491                code TEXT NOT NULL, \
28492                PRIMARY KEY (year, month, code) \
28493             );",
28494        )
28495        .unwrap();
28496        super::SqlConnection::execute_batch(
28497            &conn,
28498            "CREATE TABLE rolling_fact ( \
28499                fact_id INTEGER, year INTEGER, month INTEGER, code TEXT, \
28500                FOREIGN KEY (year, month, code) \
28501                  REFERENCES rolling(year, month, code) \
28502             );",
28503        )
28504        .unwrap();
28505        let fks = list_sql_foreign_keys(&conn, "rolling_fact", None).unwrap();
28506        assert_eq!(fks.len(), 1);
28507        // Pairs preserved in declaration order (seq=0,1,2).
28508        assert_eq!(fks[0].columns, vec!["year", "month", "code"]);
28509        assert_eq!(fks[0].referenced_columns, vec!["year", "month", "code"]);
28510        assert_eq!(fks[0].referenced_table, "rolling");
28511    }
28512
28513    #[cfg(feature = "sql-sqlite")]
28514    #[test]
28515    fn list_sql_foreign_keys_multiple_fks_on_one_table() {
28516        let conn = make_sql_test_conn();
28517        super::SqlConnection::execute_batch(&conn, "CREATE TABLE users (id INTEGER PRIMARY KEY);")
28518            .unwrap();
28519        super::SqlConnection::execute_batch(&conn, "CREATE TABLE products (sku TEXT PRIMARY KEY);")
28520            .unwrap();
28521        super::SqlConnection::execute_batch(
28522            &conn,
28523            "CREATE TABLE orders ( \
28524                oid INTEGER, \
28525                user_id INTEGER, \
28526                product_sku TEXT, \
28527                FOREIGN KEY (user_id) REFERENCES users(id), \
28528                FOREIGN KEY (product_sku) REFERENCES products(sku) \
28529             );",
28530        )
28531        .unwrap();
28532        let fks = list_sql_foreign_keys(&conn, "orders", None).unwrap();
28533        assert_eq!(fks.len(), 2);
28534        let user_fk = fks.iter().find(|f| f.referenced_table == "users").unwrap();
28535        assert_eq!(user_fk.columns, vec!["user_id"]);
28536        assert_eq!(user_fk.referenced_columns, vec!["id"]);
28537        let prod_fk = fks
28538            .iter()
28539            .find(|f| f.referenced_table == "products")
28540            .unwrap();
28541        assert_eq!(prod_fk.columns, vec!["product_sku"]);
28542        assert_eq!(prod_fk.referenced_columns, vec!["sku"]);
28543    }
28544
28545    #[cfg(feature = "sql-sqlite")]
28546    #[test]
28547    fn list_sql_foreign_keys_rejects_invalid_table_name() {
28548        let conn = make_sql_test_conn();
28549        let err = list_sql_foreign_keys(&conn, "x; DROP TABLE users", None)
28550            .expect_err("must reject invalid identifier");
28551        assert!(matches!(err, IoError::Sql(msg) if msg.contains("invalid")));
28552    }
28553
28554    #[cfg(feature = "sql-sqlite")]
28555    #[test]
28556    fn list_sql_foreign_keys_resolves_implicit_pk_single_column() {
28557        // Per fd90.44: FOREIGN KEY (parent_id) REFERENCES parent
28558        // (no column list) is an implicit reference to parent's PK.
28559        // SQLite returns NULL for the 'to' column; we now resolve via
28560        // the parent's primary_key_columns.
28561        let conn = make_sql_test_conn();
28562        super::SqlConnection::execute_batch(
28563            &conn,
28564            "CREATE TABLE imp_parent (pid INTEGER PRIMARY KEY, label TEXT);",
28565        )
28566        .unwrap();
28567        super::SqlConnection::execute_batch(
28568            &conn,
28569            "CREATE TABLE imp_child ( \
28570                cid INTEGER, \
28571                parent_id INTEGER, \
28572                FOREIGN KEY (parent_id) REFERENCES imp_parent \
28573             );",
28574        )
28575        .unwrap();
28576        let fks = list_sql_foreign_keys(&conn, "imp_child", None).unwrap();
28577        assert_eq!(
28578            fks.len(),
28579            1,
28580            "implicit-PK FK must surface (was being silently dropped)"
28581        );
28582        assert_eq!(fks[0].columns, vec!["parent_id"]);
28583        assert_eq!(fks[0].referenced_table, "imp_parent");
28584        // resolved from parent's PK.
28585        assert_eq!(fks[0].referenced_columns, vec!["pid"]);
28586    }
28587
28588    #[cfg(feature = "sql-sqlite")]
28589    #[test]
28590    fn list_sql_foreign_keys_resolves_implicit_pk_composite() {
28591        // Composite FK with implicit reference to composite PK.
28592        let conn = make_sql_test_conn();
28593        super::SqlConnection::execute_batch(
28594            &conn,
28595            "CREATE TABLE imp_parent_comp ( \
28596                year INTEGER NOT NULL, \
28597                month INTEGER NOT NULL, \
28598                PRIMARY KEY (year, month) \
28599             );",
28600        )
28601        .unwrap();
28602        super::SqlConnection::execute_batch(
28603            &conn,
28604            "CREATE TABLE imp_child_comp ( \
28605                cid INTEGER, \
28606                fyear INTEGER NOT NULL, \
28607                fmonth INTEGER NOT NULL, \
28608                FOREIGN KEY (fyear, fmonth) REFERENCES imp_parent_comp \
28609             );",
28610        )
28611        .unwrap();
28612        let fks = list_sql_foreign_keys(&conn, "imp_child_comp", None).unwrap();
28613        assert_eq!(fks.len(), 1);
28614        assert_eq!(fks[0].columns, vec!["fyear", "fmonth"]);
28615        assert_eq!(fks[0].referenced_table, "imp_parent_comp");
28616        // Resolved from composite PK in declaration order.
28617        assert_eq!(fks[0].referenced_columns, vec!["year", "month"]);
28618    }
28619
28620    #[cfg(feature = "sql-sqlite")]
28621    #[test]
28622    fn list_sql_foreign_keys_explicit_columns_unchanged() {
28623        // Existing behavior preserved: explicit columns still
28624        // round-trip exactly as before fd90.44.
28625        let conn = make_sql_test_conn();
28626        super::SqlConnection::execute_batch(
28627            &conn,
28628            "CREATE TABLE exp_parent (pid INTEGER PRIMARY KEY);",
28629        )
28630        .unwrap();
28631        super::SqlConnection::execute_batch(
28632            &conn,
28633            "CREATE TABLE exp_child ( \
28634                cid INTEGER, \
28635                parent_id INTEGER, \
28636                FOREIGN KEY (parent_id) REFERENCES exp_parent(pid) \
28637             );",
28638        )
28639        .unwrap();
28640        let fks = list_sql_foreign_keys(&conn, "exp_child", None).unwrap();
28641        assert_eq!(fks.len(), 1);
28642        assert_eq!(fks[0].columns, vec!["parent_id"]);
28643        assert_eq!(fks[0].referenced_columns, vec!["pid"]);
28644    }
28645
28646    #[test]
28647    fn list_sql_foreign_keys_default_impl_returns_empty() {
28648        struct NoIntrospection;
28649        impl super::SqlConnection for NoIntrospection {
28650            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
28651                Ok(SqlQueryResult {
28652                    columns: vec![],
28653                    rows: vec![],
28654                })
28655            }
28656            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
28657                Ok(())
28658            }
28659            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
28660                Ok(false)
28661            }
28662            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
28663                Ok(())
28664            }
28665            fn dtype_sql(&self, _dtype: DType) -> &'static str {
28666                "TEXT"
28667            }
28668            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
28669                "TEXT"
28670            }
28671        }
28672        assert!(
28673            list_sql_foreign_keys(&NoIntrospection, "anything", None)
28674                .unwrap()
28675                .is_empty()
28676        );
28677    }
28678
28679    #[test]
28680    fn list_sql_foreign_keys_routes_to_backend_override() {
28681        struct MultiSchemaFk;
28682        impl super::SqlConnection for MultiSchemaFk {
28683            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
28684                Ok(SqlQueryResult {
28685                    columns: vec![],
28686                    rows: vec![],
28687                })
28688            }
28689            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
28690                Ok(())
28691            }
28692            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
28693                Ok(false)
28694            }
28695            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
28696                Ok(())
28697            }
28698            fn dtype_sql(&self, _dtype: DType) -> &'static str {
28699                "TEXT"
28700            }
28701            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
28702                "TEXT"
28703            }
28704            fn supports_schemas(&self) -> bool {
28705                true
28706            }
28707            fn list_foreign_keys(
28708                &self,
28709                table: &str,
28710                schema: Option<&str>,
28711            ) -> Result<Vec<SqlForeignKeySchema>, IoError> {
28712                if table == "orders" && schema == Some("sales") {
28713                    Ok(vec![SqlForeignKeySchema {
28714                        constraint_name: Some("orders_user_fk".to_owned()),
28715                        columns: vec!["user_id".to_owned()],
28716                        referenced_table: "users".to_owned(),
28717                        referenced_columns: vec!["id".to_owned()],
28718                    }])
28719                } else {
28720                    Ok(vec![])
28721                }
28722            }
28723        }
28724        let conn = MultiSchemaFk;
28725        let fks = list_sql_foreign_keys(&conn, "orders", Some("sales")).unwrap();
28726        assert_eq!(fks.len(), 1);
28727        assert_eq!(fks[0].constraint_name.as_deref(), Some("orders_user_fk"));
28728        assert_eq!(fks[0].referenced_table, "users");
28729        // Wrong schema → empty (override scopes by Some).
28730        assert!(
28731            list_sql_foreign_keys(&conn, "orders", Some("audit"))
28732                .unwrap()
28733                .is_empty()
28734        );
28735    }
28736
28737    // ── list_sql_views / SqlConnection::list_views (br-gm3r / fd90.30) ────
28738
28739    #[cfg(feature = "sql-sqlite")]
28740    #[test]
28741    fn list_sql_views_empty_db_returns_empty() {
28742        let conn = make_sql_test_conn();
28743        let views = list_sql_views(&conn, None).unwrap();
28744        assert!(views.is_empty());
28745    }
28746
28747    #[cfg(feature = "sql-sqlite")]
28748    #[test]
28749    fn list_sql_views_returns_user_views_sorted() {
28750        let conn = make_sql_test_conn();
28751        super::SqlConnection::execute_batch(&conn, "CREATE TABLE base (id INTEGER, val TEXT);")
28752            .unwrap();
28753        super::SqlConnection::execute_batch(
28754            &conn,
28755            "CREATE VIEW zebra_view AS SELECT id FROM base;",
28756        )
28757        .unwrap();
28758        super::SqlConnection::execute_batch(
28759            &conn,
28760            "CREATE VIEW alpha_view AS SELECT val FROM base;",
28761        )
28762        .unwrap();
28763        let views = list_sql_views(&conn, None).unwrap();
28764        assert_eq!(views, vec!["alpha_view", "zebra_view"]);
28765    }
28766
28767    #[cfg(feature = "sql-sqlite")]
28768    #[test]
28769    fn list_sql_views_separated_from_list_tables() {
28770        // list_views must NOT surface tables; list_tables must NOT surface
28771        // views. The two buckets are disjoint per SQLAlchemy.Inspector.
28772        let conn = make_sql_test_conn();
28773        super::SqlConnection::execute_batch(&conn, "CREATE TABLE just_tbl (x INTEGER);").unwrap();
28774        super::SqlConnection::execute_batch(
28775            &conn,
28776            "CREATE VIEW just_view AS SELECT x FROM just_tbl;",
28777        )
28778        .unwrap();
28779
28780        let tables = list_sql_tables(&conn, None).unwrap();
28781        let views = list_sql_views(&conn, None).unwrap();
28782        assert_eq!(tables, vec!["just_tbl"]);
28783        assert_eq!(views, vec!["just_view"]);
28784        assert!(!tables.contains(&"just_view".to_owned()));
28785        assert!(!views.contains(&"just_tbl".to_owned()));
28786    }
28787
28788    #[cfg(feature = "sql-sqlite")]
28789    #[test]
28790    fn list_sql_views_schema_silently_ignored_on_sqlite() {
28791        let conn = make_sql_test_conn();
28792        super::SqlConnection::execute_batch(&conn, "CREATE TABLE t (x INTEGER);").unwrap();
28793        super::SqlConnection::execute_batch(&conn, "CREATE VIEW v AS SELECT x FROM t;").unwrap();
28794        let with_schema =
28795            list_sql_views(&conn, Some("ignored_on_sqlite")).expect("schema arg must not error");
28796        let without_schema = list_sql_views(&conn, None).unwrap();
28797        assert_eq!(with_schema, without_schema);
28798    }
28799
28800    #[test]
28801    fn list_sql_views_default_impl_returns_empty() {
28802        struct NoIntrospection;
28803        impl super::SqlConnection for NoIntrospection {
28804            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
28805                Ok(SqlQueryResult {
28806                    columns: vec![],
28807                    rows: vec![],
28808                })
28809            }
28810            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
28811                Ok(())
28812            }
28813            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
28814                Ok(false)
28815            }
28816            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
28817                Ok(())
28818            }
28819            fn dtype_sql(&self, _dtype: DType) -> &'static str {
28820                "TEXT"
28821            }
28822            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
28823                "TEXT"
28824            }
28825        }
28826        let conn = NoIntrospection;
28827        assert!(list_sql_views(&conn, None).unwrap().is_empty());
28828        assert!(list_sql_views(&conn, Some("any")).unwrap().is_empty());
28829    }
28830
28831    #[test]
28832    fn list_sql_views_routes_schema_to_backend_override() {
28833        struct MultiSchemaViews;
28834        impl super::SqlConnection for MultiSchemaViews {
28835            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
28836                Ok(SqlQueryResult {
28837                    columns: vec![],
28838                    rows: vec![],
28839                })
28840            }
28841            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
28842                Ok(())
28843            }
28844            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
28845                Ok(false)
28846            }
28847            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
28848                Ok(())
28849            }
28850            fn dtype_sql(&self, _dtype: DType) -> &'static str {
28851                "TEXT"
28852            }
28853            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
28854                "TEXT"
28855            }
28856            fn supports_schemas(&self) -> bool {
28857                true
28858            }
28859            fn list_views(&self, schema: Option<&str>) -> Result<Vec<String>, IoError> {
28860                Ok(match schema {
28861                    Some("reporting") => vec!["daily".to_owned(), "weekly".to_owned()],
28862                    Some("audit") => vec!["log_view".to_owned()],
28863                    _ => vec![],
28864                })
28865            }
28866        }
28867        let conn = MultiSchemaViews;
28868        assert_eq!(
28869            list_sql_views(&conn, Some("reporting")).unwrap(),
28870            vec!["daily", "weekly"]
28871        );
28872        assert_eq!(
28873            list_sql_views(&conn, Some("audit")).unwrap(),
28874            vec!["log_view"]
28875        );
28876        assert!(list_sql_views(&conn, None).unwrap().is_empty());
28877    }
28878
28879    // ── list_sql_unique_constraints / SqlConnection::list_unique_constraints
28880    //    (br-sh4v / fd90.31) ────────────────────────────────────────────────
28881
28882    #[cfg(feature = "sql-sqlite")]
28883    #[test]
28884    fn list_sql_unique_constraints_unknown_table_returns_empty() {
28885        let conn = make_sql_test_conn();
28886        let uqs = list_sql_unique_constraints(&conn, "no_such", None).unwrap();
28887        assert!(uqs.is_empty());
28888    }
28889
28890    #[cfg(feature = "sql-sqlite")]
28891    #[test]
28892    fn list_sql_unique_constraints_table_without_uq() {
28893        let conn = make_sql_test_conn();
28894        super::SqlConnection::execute_batch(&conn, "CREATE TABLE plain (a INTEGER, b TEXT);")
28895            .unwrap();
28896        let uqs = list_sql_unique_constraints(&conn, "plain", None).unwrap();
28897        assert!(uqs.is_empty());
28898    }
28899
28900    #[cfg(feature = "sql-sqlite")]
28901    #[test]
28902    fn list_sql_unique_constraints_inline_unique() {
28903        let conn = make_sql_test_conn();
28904        super::SqlConnection::execute_batch(
28905            &conn,
28906            "CREATE TABLE users (id INTEGER PRIMARY KEY, email TEXT UNIQUE);",
28907        )
28908        .unwrap();
28909        let uqs = list_sql_unique_constraints(&conn, "users", None).unwrap();
28910        assert_eq!(uqs.len(), 1);
28911        assert_eq!(uqs[0].columns, vec!["email"]);
28912        // SQLite gives backend-generated names like sqlite_autoindex_users_1.
28913        assert!(
28914            uqs[0].name.starts_with("sqlite_autoindex_users_"),
28915            "expected sqlite_autoindex_ name; got {}",
28916            uqs[0].name
28917        );
28918    }
28919
28920    #[cfg(feature = "sql-sqlite")]
28921    #[test]
28922    fn list_sql_unique_constraints_composite_table_constraint() {
28923        let conn = make_sql_test_conn();
28924        super::SqlConnection::execute_batch(
28925            &conn,
28926            "CREATE TABLE rolling ( \
28927                year INTEGER, month INTEGER, code TEXT, val REAL, \
28928                UNIQUE (year, month, code) \
28929             );",
28930        )
28931        .unwrap();
28932        let uqs = list_sql_unique_constraints(&conn, "rolling", None).unwrap();
28933        assert_eq!(uqs.len(), 1);
28934        assert_eq!(uqs[0].columns, vec!["year", "month", "code"]);
28935    }
28936
28937    #[cfg(feature = "sql-sqlite")]
28938    #[test]
28939    fn list_sql_unique_constraints_disjoint_from_create_unique_index() {
28940        // Per SQLAlchemy: get_unique_constraints surfaces declared UNIQUE
28941        // constraints (origin='u'); get_indexes surfaces user-created
28942        // CREATE UNIQUE INDEX (origin='c'). The two must be disjoint.
28943        let conn = make_sql_test_conn();
28944        super::SqlConnection::execute_batch(
28945            &conn,
28946            "CREATE TABLE mixed ( \
28947                a INTEGER, \
28948                b TEXT, \
28949                c TEXT, \
28950                UNIQUE (a) \
28951             );",
28952        )
28953        .unwrap();
28954        super::SqlConnection::execute_batch(&conn, "CREATE UNIQUE INDEX idx_mixed_b ON mixed (b);")
28955            .unwrap();
28956
28957        let uqs = list_sql_unique_constraints(&conn, "mixed", None).unwrap();
28958        let idxs = list_sql_indexes(&conn, "mixed", None).unwrap();
28959
28960        // The UNIQUE constraint is in uqs only.
28961        assert_eq!(uqs.len(), 1);
28962        assert_eq!(uqs[0].columns, vec!["a"]);
28963        // The CREATE UNIQUE INDEX is in idxs only.
28964        assert_eq!(idxs.len(), 1);
28965        assert_eq!(idxs[0].name, "idx_mixed_b");
28966        assert!(idxs[0].unique);
28967        assert_eq!(idxs[0].columns, vec!["b"]);
28968
28969        // No overlap by name (uqs uses sqlite_autoindex_, idxs uses idx_).
28970        assert!(!uqs.iter().any(|u| u.name == "idx_mixed_b"));
28971        assert!(!idxs.iter().any(|i| i.name.starts_with("sqlite_autoindex_")));
28972    }
28973
28974    #[cfg(feature = "sql-sqlite")]
28975    #[test]
28976    fn list_sql_unique_constraints_rejects_invalid_table_name() {
28977        let conn = make_sql_test_conn();
28978        let err = list_sql_unique_constraints(&conn, "x; DROP TABLE users", None)
28979            .expect_err("must reject invalid identifier");
28980        assert!(matches!(err, IoError::Sql(msg) if msg.contains("invalid")));
28981    }
28982
28983    #[test]
28984    fn list_sql_unique_constraints_default_impl_returns_empty() {
28985        struct NoIntrospection;
28986        impl super::SqlConnection for NoIntrospection {
28987            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
28988                Ok(SqlQueryResult {
28989                    columns: vec![],
28990                    rows: vec![],
28991                })
28992            }
28993            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
28994                Ok(())
28995            }
28996            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
28997                Ok(false)
28998            }
28999            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
29000                Ok(())
29001            }
29002            fn dtype_sql(&self, _dtype: DType) -> &'static str {
29003                "TEXT"
29004            }
29005            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
29006                "TEXT"
29007            }
29008        }
29009        assert!(
29010            list_sql_unique_constraints(&NoIntrospection, "anything", None)
29011                .unwrap()
29012                .is_empty()
29013        );
29014    }
29015
29016    #[test]
29017    fn list_sql_unique_constraints_routes_to_backend_override() {
29018        struct MultiSchemaUq;
29019        impl super::SqlConnection for MultiSchemaUq {
29020            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
29021                Ok(SqlQueryResult {
29022                    columns: vec![],
29023                    rows: vec![],
29024                })
29025            }
29026            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
29027                Ok(())
29028            }
29029            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
29030                Ok(false)
29031            }
29032            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
29033                Ok(())
29034            }
29035            fn dtype_sql(&self, _dtype: DType) -> &'static str {
29036                "TEXT"
29037            }
29038            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
29039                "TEXT"
29040            }
29041            fn supports_schemas(&self) -> bool {
29042                true
29043            }
29044            fn list_unique_constraints(
29045                &self,
29046                table: &str,
29047                schema: Option<&str>,
29048            ) -> Result<Vec<SqlUniqueConstraintSchema>, IoError> {
29049                if table == "users" && schema == Some("public") {
29050                    Ok(vec![SqlUniqueConstraintSchema {
29051                        name: "users_email_key".to_owned(),
29052                        columns: vec!["email".to_owned()],
29053                    }])
29054                } else {
29055                    Ok(vec![])
29056                }
29057            }
29058        }
29059        let conn = MultiSchemaUq;
29060        let uqs = list_sql_unique_constraints(&conn, "users", Some("public")).unwrap();
29061        assert_eq!(uqs.len(), 1);
29062        assert_eq!(uqs[0].name, "users_email_key");
29063        assert!(
29064            list_sql_unique_constraints(&conn, "users", Some("audit"))
29065                .unwrap()
29066                .is_empty()
29067        );
29068    }
29069
29070    // ── sql_table_comment / SqlConnection::table_comment (br-yu3w / fd90.32) ─
29071
29072    #[cfg(feature = "sql-sqlite")]
29073    #[test]
29074    fn sql_table_comment_returns_none_on_sqlite() {
29075        // SQLite has no native table-comment storage; the trait default
29076        // returns None even for a real table.
29077        let conn = make_sql_test_conn();
29078        super::SqlConnection::execute_batch(&conn, "CREATE TABLE t (x INTEGER);").unwrap();
29079        let comment = sql_table_comment(&conn, "t", None).unwrap();
29080        assert!(comment.is_none());
29081    }
29082
29083    #[cfg(feature = "sql-sqlite")]
29084    #[test]
29085    fn sql_table_comment_returns_none_on_sqlite_for_unknown_table() {
29086        let conn = make_sql_test_conn();
29087        let comment = sql_table_comment(&conn, "no_such", None).unwrap();
29088        assert!(comment.is_none());
29089    }
29090
29091    #[test]
29092    fn sql_table_comment_default_impl_returns_none() {
29093        struct NoIntrospection;
29094        impl super::SqlConnection for NoIntrospection {
29095            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
29096                Ok(SqlQueryResult {
29097                    columns: vec![],
29098                    rows: vec![],
29099                })
29100            }
29101            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
29102                Ok(())
29103            }
29104            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
29105                Ok(false)
29106            }
29107            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
29108                Ok(())
29109            }
29110            fn dtype_sql(&self, _dtype: DType) -> &'static str {
29111                "TEXT"
29112            }
29113            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
29114                "TEXT"
29115            }
29116        }
29117        let conn = NoIntrospection;
29118        assert!(
29119            sql_table_comment(&conn, "anything", None)
29120                .unwrap()
29121                .is_none()
29122        );
29123    }
29124
29125    #[test]
29126    fn sql_table_comment_routes_to_backend_override() {
29127        struct PgLikeStub;
29128        impl super::SqlConnection for PgLikeStub {
29129            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
29130                Ok(SqlQueryResult {
29131                    columns: vec![],
29132                    rows: vec![],
29133                })
29134            }
29135            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
29136                Ok(())
29137            }
29138            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
29139                Ok(false)
29140            }
29141            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
29142                Ok(())
29143            }
29144            fn dtype_sql(&self, _dtype: DType) -> &'static str {
29145                "TEXT"
29146            }
29147            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
29148                "TEXT"
29149            }
29150            fn supports_schemas(&self) -> bool {
29151                true
29152            }
29153            fn table_comment(
29154                &self,
29155                table: &str,
29156                schema: Option<&str>,
29157            ) -> Result<Option<String>, IoError> {
29158                if table == "users" && schema == Some("public") {
29159                    Ok(Some("Customer accounts table".to_owned()))
29160                } else {
29161                    Ok(None)
29162                }
29163            }
29164        }
29165        let conn = PgLikeStub;
29166        assert_eq!(
29167            sql_table_comment(&conn, "users", Some("public"))
29168                .unwrap()
29169                .as_deref(),
29170            Some("Customer accounts table")
29171        );
29172        assert!(
29173            sql_table_comment(&conn, "users", Some("audit"))
29174                .unwrap()
29175                .is_none()
29176        );
29177        assert!(
29178            sql_table_comment(&conn, "missing", Some("public"))
29179                .unwrap()
29180                .is_none()
29181        );
29182    }
29183
29184    #[test]
29185    fn sql_table_comment_propagates_backend_error() {
29186        struct BrokenIntrospection;
29187        impl super::SqlConnection for BrokenIntrospection {
29188            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
29189                Ok(SqlQueryResult {
29190                    columns: vec![],
29191                    rows: vec![],
29192                })
29193            }
29194            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
29195                Ok(())
29196            }
29197            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
29198                Ok(false)
29199            }
29200            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
29201                Ok(())
29202            }
29203            fn dtype_sql(&self, _dtype: DType) -> &'static str {
29204                "TEXT"
29205            }
29206            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
29207                "TEXT"
29208            }
29209            fn table_comment(
29210                &self,
29211                _table: &str,
29212                _schema: Option<&str>,
29213            ) -> Result<Option<String>, IoError> {
29214                Err(IoError::Sql(
29215                    "permission denied for pg_description".to_owned(),
29216                ))
29217            }
29218        }
29219        let conn = BrokenIntrospection;
29220        let err =
29221            sql_table_comment(&conn, "anything", None).expect_err("backend error must surface");
29222        assert!(matches!(err, IoError::Sql(msg) if msg.contains("permission denied")));
29223    }
29224
29225    // ── SqlWriteOptions::chunksize (br-ls9z / fd90.33) ────────────────────
29226
29227    #[cfg(feature = "sql-sqlite")]
29228    #[test]
29229    fn write_sql_chunksize_zero_rejected() {
29230        let conn = make_sql_test_conn();
29231        let frame =
29232            fp_frame::DataFrame::from_dict(&["x"], vec![("x", vec![Scalar::Int64(1)])]).unwrap();
29233        let err = write_sql_with_options(
29234            &frame,
29235            &conn,
29236            "t",
29237            &SqlWriteOptions {
29238                if_exists: SqlIfExists::Fail,
29239                index: false,
29240                index_label: None,
29241                schema: None,
29242                dtype: None,
29243                method: SqlInsertMethod::Single,
29244                chunksize: Some(0),
29245            },
29246        )
29247        .expect_err("chunksize=0 must be rejected");
29248        assert!(matches!(err, IoError::Sql(msg) if msg.contains("chunksize")));
29249    }
29250
29251    #[cfg(feature = "sql-sqlite")]
29252    #[test]
29253    fn write_sql_chunksize_none_preserves_single_transaction_semantics() {
29254        // 5 rows, chunksize=None — should round-trip cleanly into one
29255        // transaction (same as before fd90.33 landed).
29256        let conn = make_sql_test_conn();
29257        let frame = fp_frame::DataFrame::from_dict(
29258            &["id"],
29259            vec![(
29260                "id",
29261                vec![
29262                    Scalar::Int64(1),
29263                    Scalar::Int64(2),
29264                    Scalar::Int64(3),
29265                    Scalar::Int64(4),
29266                    Scalar::Int64(5),
29267                ],
29268            )],
29269        )
29270        .unwrap();
29271        write_sql_with_options(
29272            &frame,
29273            &conn,
29274            "no_chunk",
29275            &SqlWriteOptions {
29276                if_exists: SqlIfExists::Fail,
29277                index: false,
29278                index_label: None,
29279                schema: None,
29280                dtype: None,
29281                method: SqlInsertMethod::Single,
29282                chunksize: None,
29283            },
29284        )
29285        .unwrap();
29286        let count =
29287            super::SqlConnection::query(&conn, "SELECT COUNT(*) FROM no_chunk", &[]).unwrap();
29288        assert_eq!(count.rows[0][0], Scalar::Int64(5));
29289    }
29290
29291    #[cfg(feature = "sql-sqlite")]
29292    #[test]
29293    fn write_sql_single_chunksize_round_trips_all_rows() {
29294        // 5 rows with chunksize=2: chunks of (2, 2, 1). All rows must
29295        // round-trip and the table must contain every row regardless
29296        // of how the chunks committed.
29297        let conn = make_sql_test_conn();
29298        let frame = fp_frame::DataFrame::from_dict(
29299            &["id"],
29300            vec![(
29301                "id",
29302                vec![
29303                    Scalar::Int64(1),
29304                    Scalar::Int64(2),
29305                    Scalar::Int64(3),
29306                    Scalar::Int64(4),
29307                    Scalar::Int64(5),
29308                ],
29309            )],
29310        )
29311        .unwrap();
29312        write_sql_with_options(
29313            &frame,
29314            &conn,
29315            "chunked",
29316            &SqlWriteOptions {
29317                if_exists: SqlIfExists::Fail,
29318                index: false,
29319                index_label: None,
29320                schema: None,
29321                dtype: None,
29322                method: SqlInsertMethod::Single,
29323                chunksize: Some(2),
29324            },
29325        )
29326        .unwrap();
29327        let result =
29328            super::SqlConnection::query(&conn, "SELECT id FROM chunked ORDER BY id", &[]).unwrap();
29329        let ids: Vec<i64> = result
29330            .rows
29331            .iter()
29332            .map(|r| match &r[0] {
29333                Scalar::Int64(v) => *v,
29334                other => unreachable!("unexpected scalar: {other:?}"),
29335            })
29336            .collect();
29337        assert_eq!(ids, vec![1, 2, 3, 4, 5]);
29338    }
29339
29340    #[test]
29341    fn write_sql_single_chunksize_dispatches_correct_chunk_counts() {
29342        // Recording stub verifies the chunk boundaries.
29343        use std::cell::RefCell;
29344        struct Recorder {
29345            row_counts: RefCell<Vec<usize>>,
29346        }
29347        impl super::SqlConnection for Recorder {
29348            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
29349                Ok(SqlQueryResult {
29350                    columns: vec![],
29351                    rows: vec![],
29352                })
29353            }
29354            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
29355                Ok(())
29356            }
29357            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
29358                Ok(false)
29359            }
29360            fn insert_rows(&self, _sql: &str, rows: &[Vec<Scalar>]) -> Result<(), IoError> {
29361                self.row_counts.borrow_mut().push(rows.len());
29362                Ok(())
29363            }
29364            fn dtype_sql(&self, _dtype: DType) -> &'static str {
29365                "TEXT"
29366            }
29367            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
29368                "TEXT"
29369            }
29370        }
29371        let conn = Recorder {
29372            row_counts: RefCell::new(vec![]),
29373        };
29374        let frame = fp_frame::DataFrame::from_dict(
29375            &["x"],
29376            vec![(
29377                "x",
29378                vec![
29379                    Scalar::Int64(1),
29380                    Scalar::Int64(2),
29381                    Scalar::Int64(3),
29382                    Scalar::Int64(4),
29383                    Scalar::Int64(5),
29384                ],
29385            )],
29386        )
29387        .unwrap();
29388        write_sql_with_options(
29389            &frame,
29390            &conn,
29391            "chunked",
29392            &SqlWriteOptions {
29393                if_exists: SqlIfExists::Fail,
29394                index: false,
29395                index_label: None,
29396                schema: None,
29397                dtype: None,
29398                method: SqlInsertMethod::Single,
29399                chunksize: Some(2),
29400            },
29401        )
29402        .unwrap();
29403        // Single mode: each chunk submits a slice of rows to insert_rows.
29404        // chunks of size 2, 2, 1 → 3 calls with row counts [2, 2, 1].
29405        assert_eq!(*conn.row_counts.borrow(), vec![2usize, 2, 1]);
29406    }
29407
29408    #[test]
29409    fn write_sql_multi_chunksize_takes_min_with_param_cap() {
29410        // Multi mode with max_param_count=10, ncols=2 → param chunk = 5
29411        // rows. chunksize=3 should win (min(3, 5) = 3).
29412        // Multi mode flattens each chunk to a single insert_rows call
29413        // where rows[0].len() = chunk_size * ncols.
29414        use std::cell::RefCell;
29415        struct ParamCapRecorder {
29416            row_counts: RefCell<Vec<usize>>,
29417        }
29418        impl super::SqlConnection for ParamCapRecorder {
29419            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
29420                Ok(SqlQueryResult {
29421                    columns: vec![],
29422                    rows: vec![],
29423                })
29424            }
29425            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
29426                Ok(())
29427            }
29428            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
29429                Ok(false)
29430            }
29431            fn insert_rows(&self, _sql: &str, rows: &[Vec<Scalar>]) -> Result<(), IoError> {
29432                // Multi mode passes a single flattened "row" per chunk.
29433                self.row_counts
29434                    .borrow_mut()
29435                    .push(rows.first().map_or(0, std::vec::Vec::len));
29436                Ok(())
29437            }
29438            fn dtype_sql(&self, _dtype: DType) -> &'static str {
29439                "TEXT"
29440            }
29441            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
29442                "TEXT"
29443            }
29444            fn max_param_count(&self) -> Option<usize> {
29445                Some(10)
29446            }
29447        }
29448        let conn = ParamCapRecorder {
29449            row_counts: RefCell::new(vec![]),
29450        };
29451        let frame = fp_frame::DataFrame::from_dict(
29452            &["a", "b"],
29453            vec![
29454                (
29455                    "a",
29456                    vec![
29457                        Scalar::Int64(1),
29458                        Scalar::Int64(2),
29459                        Scalar::Int64(3),
29460                        Scalar::Int64(4),
29461                        Scalar::Int64(5),
29462                    ],
29463                ),
29464                (
29465                    "b",
29466                    vec![
29467                        Scalar::Int64(10),
29468                        Scalar::Int64(20),
29469                        Scalar::Int64(30),
29470                        Scalar::Int64(40),
29471                        Scalar::Int64(50),
29472                    ],
29473                ),
29474            ],
29475        )
29476        .unwrap();
29477        write_sql_with_options(
29478            &frame,
29479            &conn,
29480            "chunked",
29481            &SqlWriteOptions {
29482                if_exists: SqlIfExists::Fail,
29483                index: false,
29484                index_label: None,
29485                schema: None,
29486                dtype: None,
29487                method: SqlInsertMethod::Multi,
29488                chunksize: Some(3),
29489            },
29490        )
29491        .unwrap();
29492        // chunksize=3 wins over param cap (5). 5 rows / 3 per chunk = 2
29493        // chunks (3, 2). Flat scalars per chunk: 3*2=6 then 2*2=4.
29494        assert_eq!(*conn.row_counts.borrow(), vec![6usize, 4]);
29495    }
29496
29497    #[test]
29498    fn write_sql_multi_chunksize_param_cap_wins_when_smaller() {
29499        // Param cap = 4 (ncols=2 → 2 rows/chunk). chunksize=10 (loose).
29500        // Effective chunk = min(10, 2) = 2.
29501        use std::cell::RefCell;
29502        struct TightCap {
29503            row_counts: RefCell<Vec<usize>>,
29504        }
29505        impl super::SqlConnection for TightCap {
29506            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
29507                Ok(SqlQueryResult {
29508                    columns: vec![],
29509                    rows: vec![],
29510                })
29511            }
29512            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
29513                Ok(())
29514            }
29515            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
29516                Ok(false)
29517            }
29518            fn insert_rows(&self, _sql: &str, rows: &[Vec<Scalar>]) -> Result<(), IoError> {
29519                self.row_counts
29520                    .borrow_mut()
29521                    .push(rows.first().map_or(0, std::vec::Vec::len));
29522                Ok(())
29523            }
29524            fn dtype_sql(&self, _dtype: DType) -> &'static str {
29525                "TEXT"
29526            }
29527            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
29528                "TEXT"
29529            }
29530            fn max_param_count(&self) -> Option<usize> {
29531                Some(4)
29532            }
29533        }
29534        let conn = TightCap {
29535            row_counts: RefCell::new(vec![]),
29536        };
29537        let frame = fp_frame::DataFrame::from_dict(
29538            &["a", "b"],
29539            vec![
29540                (
29541                    "a",
29542                    vec![
29543                        Scalar::Int64(1),
29544                        Scalar::Int64(2),
29545                        Scalar::Int64(3),
29546                        Scalar::Int64(4),
29547                        Scalar::Int64(5),
29548                    ],
29549                ),
29550                (
29551                    "b",
29552                    vec![
29553                        Scalar::Int64(10),
29554                        Scalar::Int64(20),
29555                        Scalar::Int64(30),
29556                        Scalar::Int64(40),
29557                        Scalar::Int64(50),
29558                    ],
29559                ),
29560            ],
29561        )
29562        .unwrap();
29563        write_sql_with_options(
29564            &frame,
29565            &conn,
29566            "chunked",
29567            &SqlWriteOptions {
29568                if_exists: SqlIfExists::Fail,
29569                index: false,
29570                index_label: None,
29571                schema: None,
29572                dtype: None,
29573                method: SqlInsertMethod::Multi,
29574                chunksize: Some(10),
29575            },
29576        )
29577        .unwrap();
29578        // 5 rows / 2 per chunk = 3 chunks (2, 2, 1). Flat scalars: 4, 4, 2.
29579        assert_eq!(*conn.row_counts.borrow(), vec![4usize, 4, 2]);
29580    }
29581
29582    // ── SqlReadOptions::columns (br-d3e9 / fd90.34) ──────────────────────
29583
29584    #[cfg(feature = "sql-sqlite")]
29585    #[test]
29586    fn read_sql_table_with_options_columns_none_selects_all() {
29587        let conn = make_sql_test_conn();
29588        super::SqlConnection::execute_batch(
29589            &conn,
29590            "CREATE TABLE projection_default (a INTEGER, b TEXT, c REAL);",
29591        )
29592        .unwrap();
29593        super::SqlConnection::execute_batch(
29594            &conn,
29595            "INSERT INTO projection_default VALUES (1, 'x', 1.5);",
29596        )
29597        .unwrap();
29598        let frame = read_sql_table_with_options(
29599            &conn,
29600            "projection_default",
29601            &SqlReadOptions {
29602                columns: None,
29603                ..Default::default()
29604            },
29605        )
29606        .unwrap();
29607        assert_eq!(frame.column_names(), vec!["a", "b", "c"]);
29608    }
29609
29610    #[cfg(feature = "sql-sqlite")]
29611    #[test]
29612    fn read_sql_table_with_options_columns_projects_subset() {
29613        let conn = make_sql_test_conn();
29614        super::SqlConnection::execute_batch(
29615            &conn,
29616            "CREATE TABLE projection (id INTEGER, name TEXT, ts TEXT, value REAL);",
29617        )
29618        .unwrap();
29619        super::SqlConnection::execute_batch(
29620            &conn,
29621            "INSERT INTO projection VALUES (1, 'a', '2024-01-01', 1.5), \
29622                                            (2, 'b', '2024-01-02', 2.5);",
29623        )
29624        .unwrap();
29625        let frame = read_sql_table_with_options(
29626            &conn,
29627            "projection",
29628            &SqlReadOptions {
29629                columns: Some(vec!["id".to_owned(), "name".to_owned()]),
29630                ..Default::default()
29631            },
29632        )
29633        .unwrap();
29634        // Only id + name, in that order.
29635        assert_eq!(frame.column_names(), vec!["id", "name"]);
29636        assert_eq!(frame.column("id").unwrap().values()[0], Scalar::Int64(1));
29637        assert_eq!(
29638            frame.column("name").unwrap().values()[0],
29639            Scalar::Utf8("a".into())
29640        );
29641    }
29642
29643    #[cfg(feature = "sql-sqlite")]
29644    #[test]
29645    fn read_sql_table_with_options_columns_preserves_specified_order() {
29646        // pandas: pd.read_sql_table(t, con, columns=['c', 'a']) →
29647        // returns ['c', 'a'] in that exact order, NOT alphabetical.
29648        let conn = make_sql_test_conn();
29649        super::SqlConnection::execute_batch(
29650            &conn,
29651            "CREATE TABLE ordered_proj (a INT, b INT, c INT);",
29652        )
29653        .unwrap();
29654        super::SqlConnection::execute_batch(&conn, "INSERT INTO ordered_proj VALUES (1, 2, 3);")
29655            .unwrap();
29656        let frame = read_sql_table_with_options(
29657            &conn,
29658            "ordered_proj",
29659            &SqlReadOptions {
29660                columns: Some(vec!["c".to_owned(), "a".to_owned()]),
29661                ..Default::default()
29662            },
29663        )
29664        .unwrap();
29665        assert_eq!(frame.column_names(), vec!["c", "a"]);
29666    }
29667
29668    #[cfg(feature = "sql-sqlite")]
29669    #[test]
29670    fn read_sql_table_with_options_columns_empty_vec_rejected() {
29671        let conn = make_sql_test_conn();
29672        super::SqlConnection::execute_batch(&conn, "CREATE TABLE t (x INTEGER);").unwrap();
29673        let err = read_sql_table_with_options(
29674            &conn,
29675            "t",
29676            &SqlReadOptions {
29677                columns: Some(vec![]),
29678                ..Default::default()
29679            },
29680        )
29681        .expect_err("empty columns must be rejected");
29682        assert!(matches!(err, IoError::Sql(msg) if msg.contains("columns must be non-empty")));
29683    }
29684
29685    #[cfg(feature = "sql-sqlite")]
29686    #[test]
29687    fn read_sql_table_with_options_columns_invalid_name_rejected() {
29688        let conn = make_sql_test_conn();
29689        super::SqlConnection::execute_batch(&conn, "CREATE TABLE t (x INTEGER);").unwrap();
29690        let err = read_sql_table_with_options(
29691            &conn,
29692            "t",
29693            &SqlReadOptions {
29694                columns: Some(vec!["x; DROP TABLE t".to_owned()]),
29695                ..Default::default()
29696            },
29697        )
29698        .expect_err("invalid column name must be rejected");
29699        assert!(matches!(err, IoError::Sql(msg) if msg.contains("invalid")));
29700    }
29701
29702    #[cfg(feature = "sql-sqlite")]
29703    #[test]
29704    fn read_sql_table_with_options_columns_combines_with_parse_dates() {
29705        // columns + parse_dates: project a subset, then date-coerce.
29706        let conn = make_sql_test_conn();
29707        super::SqlConnection::execute_batch(
29708            &conn,
29709            "CREATE TABLE events (id INT, ts TEXT, note TEXT);",
29710        )
29711        .unwrap();
29712        super::SqlConnection::execute_batch(
29713            &conn,
29714            "INSERT INTO events VALUES (1, '2024-01-15', 'launched');",
29715        )
29716        .unwrap();
29717        let frame = read_sql_table_with_options(
29718            &conn,
29719            "events",
29720            &SqlReadOptions {
29721                columns: Some(vec!["id".to_owned(), "ts".to_owned()]),
29722                index_col: None,
29723                parse_dates: Some(vec!["ts".to_owned()]),
29724                ..Default::default()
29725            },
29726        )
29727        .unwrap();
29728        // Only id + ts surfaced; ts was coerced by parse_dates into a typed
29729        // Datetime64[ns] column (br-frankenpandas-0ezw7).
29730        assert_eq!(frame.column_names(), vec!["id", "ts"]);
29731        assert_eq!(
29732            frame.column("ts").unwrap().values()[0],
29733            Scalar::Datetime64(1_705_276_800_000_000_000)
29734        );
29735    }
29736
29737    #[cfg(feature = "sql-sqlite")]
29738    #[test]
29739    fn read_sql_table_chunks_with_options_columns_projects_before_chunking() {
29740        let conn = make_sql_test_conn();
29741        super::SqlConnection::execute_batch(
29742            &conn,
29743            "CREATE TABLE chunk_projection (id INTEGER, name TEXT, hidden REAL);",
29744        )
29745        .unwrap();
29746        super::SqlConnection::execute_batch(
29747            &conn,
29748            "INSERT INTO chunk_projection VALUES \
29749                (1, 'a', 10.0), \
29750                (2, 'b', 20.0), \
29751                (3, 'c', 30.0);",
29752        )
29753        .unwrap();
29754
29755        let chunks: Vec<DataFrame> = read_sql_table_chunks_with_options(
29756            &conn,
29757            "chunk_projection",
29758            &SqlReadOptions {
29759                columns: Some(vec!["name".to_owned(), "id".to_owned()]),
29760                ..Default::default()
29761            },
29762            2,
29763        )
29764        .unwrap()
29765        .collect::<Result<Vec<_>, _>>()
29766        .unwrap();
29767
29768        assert_eq!(chunks.len(), 2);
29769        assert_eq!(chunks[0].column_names(), vec!["name", "id"]);
29770        assert_eq!(chunks[1].column_names(), vec!["name", "id"]);
29771        assert_eq!(
29772            chunks[0].column("name").unwrap().values(),
29773            &[Scalar::Utf8("a".into()), Scalar::Utf8("b".into())]
29774        );
29775        assert_eq!(
29776            chunks[1].column("id").unwrap().values(),
29777            &[Scalar::Int64(3)]
29778        );
29779        assert!(chunks[0].column("hidden").is_none());
29780    }
29781
29782    #[test]
29783    fn read_sql_table_chunks_with_options_schema_projects_before_chunking() {
29784        use std::cell::RefCell;
29785
29786        struct MultiSchemaProjectedChunks {
29787            queries: RefCell<Vec<String>>,
29788        }
29789
29790        impl super::SqlConnection for MultiSchemaProjectedChunks {
29791            fn query(&self, query: &str, _params: &[Scalar]) -> Result<SqlQueryResult, IoError> {
29792                self.queries.borrow_mut().push(query.to_owned());
29793                Ok(SqlQueryResult {
29794                    columns: vec!["name".to_owned(), "id".to_owned()],
29795                    rows: vec![
29796                        vec![Scalar::Utf8("a".to_owned()), Scalar::Int64(1)],
29797                        vec![Scalar::Utf8("b".to_owned()), Scalar::Int64(2)],
29798                        vec![Scalar::Utf8("c".to_owned()), Scalar::Int64(3)],
29799                    ],
29800                })
29801            }
29802
29803            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
29804                Ok(())
29805            }
29806
29807            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
29808                Ok(false)
29809            }
29810
29811            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
29812                Ok(())
29813            }
29814
29815            fn dtype_sql(&self, _dtype: DType) -> &'static str {
29816                "TEXT"
29817            }
29818
29819            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
29820                "TEXT"
29821            }
29822
29823            fn supports_schemas(&self) -> bool {
29824                true
29825            }
29826        }
29827
29828        let conn = MultiSchemaProjectedChunks {
29829            queries: RefCell::new(Vec::new()),
29830        };
29831
29832        let chunks: Vec<DataFrame> = super::read_sql_table_chunks_with_options(
29833            &conn,
29834            "events",
29835            &SqlReadOptions {
29836                schema: Some("analytics".to_owned()),
29837                columns: Some(vec!["name".to_owned(), "id".to_owned()]),
29838                ..Default::default()
29839            },
29840            2,
29841        )
29842        .unwrap()
29843        .collect::<Result<Vec<_>, _>>()
29844        .unwrap();
29845
29846        assert_eq!(
29847            conn.queries.borrow().as_slice(),
29848            &["SELECT \"name\", \"id\" FROM \"analytics\".\"events\"".to_owned()]
29849        );
29850        assert_eq!(chunks.len(), 2);
29851        assert_eq!(chunks[0].column_names(), vec!["name", "id"]);
29852        assert_eq!(chunks[1].column_names(), vec!["name", "id"]);
29853        assert_eq!(
29854            chunks[0].index().labels(),
29855            &[IndexLabel::Int64(0), IndexLabel::Int64(1)]
29856        );
29857        assert_eq!(chunks[1].index().labels(), &[IndexLabel::Int64(0)]);
29858        assert_eq!(
29859            chunks[0].column("name").unwrap().values(),
29860            &[Scalar::Utf8("a".into()), Scalar::Utf8("b".into())]
29861        );
29862        assert_eq!(
29863            chunks[1].column("id").unwrap().values(),
29864            &[Scalar::Int64(3)]
29865        );
29866    }
29867
29868    // ── SqlColumnSchema::comment (br-cfld / fd90.35) ─────────────────────
29869
29870    #[cfg(feature = "sql-sqlite")]
29871    #[test]
29872    fn sql_table_schema_comment_is_none_on_sqlite() {
29873        // SQLite has no column-comment storage; the rusqlite override
29874        // must always emit comment=None even when the table is real.
29875        let conn = make_sql_test_conn();
29876        super::SqlConnection::execute_batch(&conn, "CREATE TABLE labeled (id INTEGER, name TEXT);")
29877            .unwrap();
29878        let schema = sql_table_schema(&conn, "labeled", None).unwrap().unwrap();
29879        for col in &schema.columns {
29880            assert!(
29881                col.comment.is_none(),
29882                "SQLite should report no column comment; got {:?} on {}",
29883                col.comment,
29884                col.name
29885            );
29886        }
29887    }
29888
29889    #[test]
29890    fn sql_table_schema_comment_routes_to_backend_override() {
29891        // PG-like backend stub returns explicit comment text per column.
29892        struct PgLikeWithComments;
29893        impl super::SqlConnection for PgLikeWithComments {
29894            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
29895                Ok(SqlQueryResult {
29896                    columns: vec![],
29897                    rows: vec![],
29898                })
29899            }
29900            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
29901                Ok(())
29902            }
29903            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
29904                Ok(false)
29905            }
29906            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
29907                Ok(())
29908            }
29909            fn dtype_sql(&self, _dtype: DType) -> &'static str {
29910                "TEXT"
29911            }
29912            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
29913                "TEXT"
29914            }
29915            fn supports_schemas(&self) -> bool {
29916                true
29917            }
29918            fn table_schema(
29919                &self,
29920                table: &str,
29921                _schema: Option<&str>,
29922            ) -> Result<Option<SqlTableSchema>, IoError> {
29923                if table == "users" {
29924                    Ok(Some(SqlTableSchema {
29925                        table_name: "users".to_owned(),
29926                        columns: vec![
29927                            SqlColumnSchema {
29928                                name: "id".to_owned(),
29929                                declared_type: Some("BIGINT".to_owned()),
29930                                nullable: false,
29931                                default_value: None,
29932                                primary_key_ordinal: Some(0),
29933                                comment: Some("Surrogate primary key".to_owned()),
29934                                autoincrement: false,
29935                            },
29936                            SqlColumnSchema {
29937                                name: "email".to_owned(),
29938                                declared_type: Some("TEXT".to_owned()),
29939                                nullable: false,
29940                                default_value: None,
29941                                primary_key_ordinal: None,
29942                                comment: Some("Login identifier".to_owned()),
29943                                autoincrement: false,
29944                            },
29945                            SqlColumnSchema {
29946                                name: "name".to_owned(),
29947                                declared_type: Some("TEXT".to_owned()),
29948                                nullable: true,
29949                                default_value: None,
29950                                primary_key_ordinal: None,
29951                                comment: None,
29952                                autoincrement: false,
29953                            },
29954                        ],
29955                    }))
29956                } else {
29957                    Ok(None)
29958                }
29959            }
29960        }
29961        let conn = PgLikeWithComments;
29962        let schema = sql_table_schema(&conn, "users", None).unwrap().unwrap();
29963        let id = schema.column("id").unwrap();
29964        assert_eq!(id.comment.as_deref(), Some("Surrogate primary key"));
29965        let email = schema.column("email").unwrap();
29966        assert_eq!(email.comment.as_deref(), Some("Login identifier"));
29967        // Mixed: some columns may have no comment even on PG.
29968        let name = schema.column("name").unwrap();
29969        assert!(name.comment.is_none());
29970    }
29971
29972    // ── SqlReadOptions::index_col (br-c1h9 / fd90.36) ─────────────────────
29973
29974    #[cfg(feature = "sql-sqlite")]
29975    #[test]
29976    fn read_sql_with_options_index_col_none_keeps_range_index() {
29977        let conn = make_sql_test_conn();
29978        super::SqlConnection::execute_batch(&conn, "CREATE TABLE keyed (id INTEGER, val INTEGER);")
29979            .unwrap();
29980        super::SqlConnection::execute_batch(&conn, "INSERT INTO keyed VALUES (1, 10), (2, 20);")
29981            .unwrap();
29982        let frame = read_sql_with_options(
29983            &conn,
29984            "SELECT id, val FROM keyed ORDER BY id",
29985            &SqlReadOptions {
29986                index_col: None,
29987                ..Default::default()
29988            },
29989        )
29990        .unwrap();
29991        // Default RangeIndex: labels 0, 1.
29992        assert_eq!(frame.index().len(), 2);
29993        assert_eq!(frame.column_names(), vec!["id", "val"]);
29994    }
29995
29996    #[cfg(feature = "sql-sqlite")]
29997    #[test]
29998    fn read_sql_with_options_index_col_promotes_named_column() {
29999        let conn = make_sql_test_conn();
30000        super::SqlConnection::execute_batch(&conn, "CREATE TABLE keyed (id INTEGER, val INTEGER);")
30001            .unwrap();
30002        super::SqlConnection::execute_batch(&conn, "INSERT INTO keyed VALUES (10, 1), (20, 2);")
30003            .unwrap();
30004        let frame = read_sql_with_options(
30005            &conn,
30006            "SELECT id, val FROM keyed ORDER BY id",
30007            &SqlReadOptions {
30008                index_col: Some("id".to_owned()),
30009                ..Default::default()
30010            },
30011        )
30012        .unwrap();
30013        // 'id' removed from columns, used as index labels.
30014        assert_eq!(frame.column_names(), vec!["val"]);
30015        assert_eq!(frame.index().len(), 2);
30016        // Index labels should be the id values (10, 20).
30017        let labels: Vec<i64> = frame
30018            .index()
30019            .labels()
30020            .iter()
30021            .filter_map(|l| match l {
30022                IndexLabel::Int64(v) => Some(*v),
30023                _ => None,
30024            })
30025            .collect();
30026        assert_eq!(labels, vec![10, 20]);
30027    }
30028
30029    #[cfg(feature = "sql-sqlite")]
30030    #[test]
30031    fn read_sql_with_options_index_col_missing_column_errors() {
30032        let conn = make_sql_test_conn();
30033        super::SqlConnection::execute_batch(&conn, "CREATE TABLE t (a INTEGER);").unwrap();
30034        super::SqlConnection::execute_batch(&conn, "INSERT INTO t VALUES (1);").unwrap();
30035        let err = read_sql_with_options(
30036            &conn,
30037            "SELECT a FROM t",
30038            &SqlReadOptions {
30039                index_col: Some("nonexistent".to_owned()),
30040                ..Default::default()
30041            },
30042        )
30043        .expect_err("missing index_col must error");
30044        assert!(matches!(err, IoError::Sql(msg) if msg.contains("not present")));
30045    }
30046
30047    #[cfg(feature = "sql-sqlite")]
30048    #[test]
30049    fn read_sql_with_options_index_col_empty_string_rejected() {
30050        let conn = make_sql_test_conn();
30051        super::SqlConnection::execute_batch(&conn, "CREATE TABLE t (a INTEGER);").unwrap();
30052        let err = read_sql_with_options(
30053            &conn,
30054            "SELECT a FROM t",
30055            &SqlReadOptions {
30056                index_col: Some(String::new()),
30057                ..Default::default()
30058            },
30059        )
30060        .expect_err("empty index_col must be rejected");
30061        assert!(matches!(err, IoError::Sql(msg) if msg.contains("empty string")));
30062    }
30063
30064    #[cfg(feature = "sql-sqlite")]
30065    #[test]
30066    fn read_sql_explicit_index_col_empty_string_rejected_across_entrypoints() {
30067        fn assert_empty_index_col(err: IoError) {
30068            assert!(
30069                matches!(err, IoError::Sql(ref msg) if msg.contains("empty string")),
30070                "expected empty index_col error, got {err:?}"
30071            );
30072        }
30073
30074        let conn = make_sql_test_conn();
30075        super::SqlConnection::execute_batch(
30076            &conn,
30077            "CREATE TABLE explicit_idx (a INTEGER, b TEXT);
30078             INSERT INTO explicit_idx VALUES (1, 'x'), (2, 'y');",
30079        )
30080        .unwrap();
30081
30082        assert_empty_index_col(
30083            read_sql_with_index_col(&conn, "SELECT a, b FROM explicit_idx", Some(""))
30084                .expect_err("empty explicit read_sql index_col must be rejected"),
30085        );
30086        assert_empty_index_col(
30087            read_sql_query_with_options_and_index_col(
30088                &conn,
30089                "SELECT a, b FROM explicit_idx",
30090                &SqlReadOptions::default(),
30091                Some(""),
30092            )
30093            .expect_err("empty explicit read_sql_query index_col must be rejected"),
30094        );
30095        assert_empty_index_col(
30096            read_sql_query_chunks_with_options_and_index_col(
30097                &conn,
30098                "SELECT a, b FROM explicit_idx",
30099                &SqlReadOptions::default(),
30100                Some(""),
30101                1,
30102            )
30103            .expect_err("empty explicit query chunk index_col must be rejected"),
30104        );
30105        assert_empty_index_col(
30106            read_sql_table_with_index_col(&conn, "explicit_idx", Some(""))
30107                .expect_err("empty explicit table index_col must be rejected"),
30108        );
30109        assert_empty_index_col(
30110            read_sql_table_with_options_and_index_col(
30111                &conn,
30112                "explicit_idx",
30113                &SqlReadOptions::default(),
30114                Some(""),
30115            )
30116            .expect_err("empty explicit table options index_col must be rejected"),
30117        );
30118        assert_empty_index_col(
30119            read_sql_table_columns_with_index_col(&conn, "explicit_idx", &["a"], Some(""))
30120                .expect_err("empty explicit table-columns index_col must be rejected"),
30121        );
30122        assert_empty_index_col(
30123            read_sql_table_columns_chunks_with_index_col(
30124                &conn,
30125                "explicit_idx",
30126                &["a"],
30127                Some(""),
30128                1,
30129            )
30130            .expect_err("empty explicit table-columns chunk index_col must be rejected"),
30131        );
30132    }
30133
30134    #[cfg(feature = "sql-sqlite")]
30135    #[test]
30136    fn read_sql_table_with_options_index_col_combines_with_columns_projection() {
30137        // columns + index_col: project ['id', 'val'], promote 'id' to
30138        // index, leaving only 'val' as a data column.
30139        let conn = make_sql_test_conn();
30140        super::SqlConnection::execute_batch(
30141            &conn,
30142            "CREATE TABLE wide (id INTEGER, val INTEGER, ts TEXT, note TEXT);",
30143        )
30144        .unwrap();
30145        super::SqlConnection::execute_batch(
30146            &conn,
30147            "INSERT INTO wide VALUES (5, 100, 't1', 'first');",
30148        )
30149        .unwrap();
30150        let frame = read_sql_table_with_options(
30151            &conn,
30152            "wide",
30153            &SqlReadOptions {
30154                columns: Some(vec!["id".to_owned(), "val".to_owned()]),
30155                index_col: Some("id".to_owned()),
30156                ..Default::default()
30157            },
30158        )
30159        .unwrap();
30160        assert_eq!(frame.column_names(), vec!["val"]);
30161        let labels: Vec<i64> = frame
30162            .index()
30163            .labels()
30164            .iter()
30165            .filter_map(|l| match l {
30166                IndexLabel::Int64(v) => Some(*v),
30167                _ => None,
30168            })
30169            .collect();
30170        assert_eq!(labels, vec![5]);
30171    }
30172
30173    #[cfg(feature = "sql-sqlite")]
30174    #[test]
30175    fn read_sql_table_with_options_columns_auto_project_index_col() {
30176        let conn = make_sql_test_conn();
30177        super::SqlConnection::execute_batch(
30178            &conn,
30179            "CREATE TABLE projected_index (id INTEGER, val TEXT, hidden TEXT);",
30180        )
30181        .unwrap();
30182        super::SqlConnection::execute_batch(
30183            &conn,
30184            "INSERT INTO projected_index VALUES (10, 'a', 'x'), (20, 'b', 'y');",
30185        )
30186        .unwrap();
30187
30188        let frame = read_sql_table_with_options(
30189            &conn,
30190            "projected_index",
30191            &SqlReadOptions {
30192                columns: Some(vec!["val".to_owned()]),
30193                index_col: Some("id".to_owned()),
30194                ..Default::default()
30195            },
30196        )
30197        .unwrap();
30198
30199        assert_eq!(frame.column_names(), vec!["val"]);
30200        assert!(frame.column("id").is_none());
30201        assert!(frame.column("hidden").is_none());
30202        assert_eq!(
30203            frame.index().labels(),
30204            &[IndexLabel::Int64(10), IndexLabel::Int64(20)]
30205        );
30206        assert_eq!(
30207            frame.column("val").unwrap().values(),
30208            &[Scalar::Utf8("a".into()), Scalar::Utf8("b".into())]
30209        );
30210    }
30211
30212    #[cfg(feature = "sql-sqlite")]
30213    #[test]
30214    fn read_sql_table_chunks_with_options_columns_auto_project_index_col() {
30215        let conn = make_sql_test_conn();
30216        super::SqlConnection::execute_batch(
30217            &conn,
30218            "CREATE TABLE projected_index_chunks (id INTEGER, val TEXT, hidden TEXT);",
30219        )
30220        .unwrap();
30221        super::SqlConnection::execute_batch(
30222            &conn,
30223            "INSERT INTO projected_index_chunks VALUES \
30224                (10, 'a', 'x'), \
30225                (20, 'b', 'y'), \
30226                (30, 'c', 'z');",
30227        )
30228        .unwrap();
30229
30230        let chunks: Vec<DataFrame> = read_sql_table_chunks_with_options_and_index_col(
30231            &conn,
30232            "projected_index_chunks",
30233            &SqlReadOptions {
30234                columns: Some(vec!["val".to_owned()]),
30235                ..Default::default()
30236            },
30237            Some("id"),
30238            2,
30239        )
30240        .unwrap()
30241        .collect::<Result<Vec<_>, _>>()
30242        .unwrap();
30243
30244        assert_eq!(chunks.len(), 2);
30245        assert_eq!(chunks[0].column_names(), vec!["val"]);
30246        assert!(chunks[0].column("id").is_none());
30247        assert!(chunks[0].column("hidden").is_none());
30248        assert_eq!(
30249            chunks[0].index().labels(),
30250            &[IndexLabel::Int64(10), IndexLabel::Int64(20)]
30251        );
30252        assert_eq!(chunks[1].index().labels(), &[IndexLabel::Int64(30)]);
30253        assert_eq!(
30254            chunks[1].column("val").unwrap().values(),
30255            &[Scalar::Utf8("c".into())]
30256        );
30257    }
30258
30259    #[cfg(feature = "sql-sqlite")]
30260    #[test]
30261    fn read_sql_table_with_options_and_index_col_explicit_arg_wins_over_options() {
30262        // Both options.index_col=Some('a') and explicit index_col=Some('b').
30263        // The explicit arg must win — options.index_col is silently
30264        // overridden to avoid double-promotion.
30265        let conn = make_sql_test_conn();
30266        super::SqlConnection::execute_batch(
30267            &conn,
30268            "CREATE TABLE both (a INTEGER, b INTEGER, c TEXT);",
30269        )
30270        .unwrap();
30271        super::SqlConnection::execute_batch(
30272            &conn,
30273            "INSERT INTO both VALUES (1, 100, 'x'), (2, 200, 'y');",
30274        )
30275        .unwrap();
30276        let frame = read_sql_table_with_options_and_index_col(
30277            &conn,
30278            "both",
30279            &SqlReadOptions {
30280                index_col: Some("a".to_owned()),
30281                ..Default::default()
30282            },
30283            Some("b"),
30284        )
30285        .unwrap();
30286        // 'b' is promoted to index, 'a' and 'c' remain as columns.
30287        assert_eq!(frame.column_names(), vec!["a", "c"]);
30288        let labels: Vec<i64> = frame
30289            .index()
30290            .labels()
30291            .iter()
30292            .filter_map(|l| match l {
30293                IndexLabel::Int64(v) => Some(*v),
30294                _ => None,
30295            })
30296            .collect();
30297        assert_eq!(labels, vec![100, 200]);
30298    }
30299
30300    // ── SqlColumnSchema::autoincrement (br-bkl2 / fd90.37) ────────────────
30301
30302    #[cfg(feature = "sql-sqlite")]
30303    #[test]
30304    fn sql_table_schema_autoincrement_detected_on_integer_primary_key() {
30305        // SQLite rowid-alias rule: INTEGER PRIMARY KEY is an
30306        // auto-incrementing rowid alias.
30307        let conn = make_sql_test_conn();
30308        super::SqlConnection::execute_batch(
30309            &conn,
30310            "CREATE TABLE auto_a (id INTEGER PRIMARY KEY, name TEXT);",
30311        )
30312        .unwrap();
30313        let schema = sql_table_schema(&conn, "auto_a", None).unwrap().unwrap();
30314        let id = schema.column("id").unwrap();
30315        assert!(
30316            id.autoincrement,
30317            "INTEGER PRIMARY KEY must be autoincrement; got {id:?}"
30318        );
30319        let name = schema.column("name").unwrap();
30320        assert!(
30321            !name.autoincrement,
30322            "non-PK column must not be autoincrement"
30323        );
30324    }
30325
30326    #[cfg(feature = "sql-sqlite")]
30327    #[test]
30328    fn sql_table_schema_autoincrement_detected_with_explicit_keyword() {
30329        // The explicit AUTOINCREMENT keyword affects rowid reuse, not
30330        // the autoincrement property pandas surfaces.
30331        let conn = make_sql_test_conn();
30332        super::SqlConnection::execute_batch(
30333            &conn,
30334            "CREATE TABLE auto_b (id INTEGER PRIMARY KEY AUTOINCREMENT, val TEXT);",
30335        )
30336        .unwrap();
30337        let schema = sql_table_schema(&conn, "auto_b", None).unwrap().unwrap();
30338        let id = schema.column("id").unwrap();
30339        assert!(id.autoincrement);
30340    }
30341
30342    #[cfg(feature = "sql-sqlite")]
30343    #[test]
30344    fn sql_table_schema_autoincrement_not_set_for_text_primary_key() {
30345        // TEXT PRIMARY KEY is NOT a rowid alias; not auto-incrementing.
30346        let conn = make_sql_test_conn();
30347        super::SqlConnection::execute_batch(
30348            &conn,
30349            "CREATE TABLE text_pk (code TEXT PRIMARY KEY, name TEXT);",
30350        )
30351        .unwrap();
30352        let schema = sql_table_schema(&conn, "text_pk", None).unwrap().unwrap();
30353        let code = schema.column("code").unwrap();
30354        assert!(
30355            !code.autoincrement,
30356            "TEXT PRIMARY KEY is not autoincrement; got {code:?}"
30357        );
30358    }
30359
30360    #[cfg(feature = "sql-sqlite")]
30361    #[test]
30362    fn sql_table_schema_autoincrement_not_set_for_non_pk_integer() {
30363        let conn = make_sql_test_conn();
30364        super::SqlConnection::execute_batch(
30365            &conn,
30366            "CREATE TABLE plain_int (val INTEGER, name TEXT);",
30367        )
30368        .unwrap();
30369        let schema = sql_table_schema(&conn, "plain_int", None).unwrap().unwrap();
30370        let val = schema.column("val").unwrap();
30371        assert!(!val.autoincrement, "non-PK INTEGER is not autoincrement");
30372    }
30373
30374    #[cfg(feature = "sql-sqlite")]
30375    #[test]
30376    fn sql_table_schema_autoincrement_not_set_for_composite_pk_integer() {
30377        // Per fd90.42: SQLite's rowid-alias rule requires the column
30378        // to be the SOLE primary key. The tightened heuristic counts
30379        // PK columns first; composite PKs (multiple pk>0 rows) never
30380        // qualify even when the first column is INTEGER.
30381        let conn = make_sql_test_conn();
30382        super::SqlConnection::execute_batch(
30383            &conn,
30384            "CREATE TABLE composite_pk ( \
30385                year INTEGER NOT NULL, \
30386                month INTEGER NOT NULL, \
30387                code TEXT NOT NULL, \
30388                PRIMARY KEY (year, month, code) \
30389             );",
30390        )
30391        .unwrap();
30392        let schema = sql_table_schema(&conn, "composite_pk", None)
30393            .unwrap()
30394            .unwrap();
30395        let year = schema.column("year").unwrap();
30396        let month = schema.column("month").unwrap();
30397        let code = schema.column("code").unwrap();
30398        // Each part of the composite PK keeps its declaration-order
30399        // ordinal but NONE of them is autoincrement.
30400        assert_eq!(year.primary_key_ordinal, Some(0));
30401        assert_eq!(month.primary_key_ordinal, Some(1));
30402        assert_eq!(code.primary_key_ordinal, Some(2));
30403        assert!(
30404            !year.autoincrement,
30405            "composite PK first col must not be autoincrement"
30406        );
30407        assert!(!month.autoincrement);
30408        assert!(!code.autoincrement);
30409    }
30410
30411    #[cfg(feature = "sql-sqlite")]
30412    #[test]
30413    fn sql_table_schema_autoincrement_two_pass_count_distinguishes_single_vs_composite() {
30414        // Confirm the fix path: single-column INTEGER PRIMARY KEY -> true,
30415        // composite INTEGER+INTEGER PRIMARY KEY -> false on both.
30416        let conn = make_sql_test_conn();
30417        super::SqlConnection::execute_batch(
30418            &conn,
30419            "CREATE TABLE single_int_pk (id INTEGER PRIMARY KEY, label TEXT);",
30420        )
30421        .unwrap();
30422        super::SqlConnection::execute_batch(
30423            &conn,
30424            "CREATE TABLE composite_int_pk ( \
30425                a INTEGER NOT NULL, \
30426                b INTEGER NOT NULL, \
30427                PRIMARY KEY (a, b) \
30428             );",
30429        )
30430        .unwrap();
30431
30432        let single = sql_table_schema(&conn, "single_int_pk", None)
30433            .unwrap()
30434            .unwrap();
30435        assert!(single.column("id").unwrap().autoincrement);
30436
30437        let composite = sql_table_schema(&conn, "composite_int_pk", None)
30438            .unwrap()
30439            .unwrap();
30440        // Both columns have INTEGER type and pk>0 but neither qualifies.
30441        assert!(!composite.column("a").unwrap().autoincrement);
30442        assert!(!composite.column("b").unwrap().autoincrement);
30443    }
30444
30445    #[test]
30446    fn sql_table_schema_autoincrement_routes_to_backend_override() {
30447        // PG-like backend stub returns explicit autoincrement true for
30448        // a SERIAL/IDENTITY column.
30449        struct PgLikeAutoinc;
30450        impl super::SqlConnection for PgLikeAutoinc {
30451            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
30452                Ok(SqlQueryResult {
30453                    columns: vec![],
30454                    rows: vec![],
30455                })
30456            }
30457            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
30458                Ok(())
30459            }
30460            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
30461                Ok(false)
30462            }
30463            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
30464                Ok(())
30465            }
30466            fn dtype_sql(&self, _dtype: DType) -> &'static str {
30467                "TEXT"
30468            }
30469            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
30470                "TEXT"
30471            }
30472            fn supports_schemas(&self) -> bool {
30473                true
30474            }
30475            fn table_schema(
30476                &self,
30477                table: &str,
30478                _schema: Option<&str>,
30479            ) -> Result<Option<SqlTableSchema>, IoError> {
30480                if table == "users" {
30481                    Ok(Some(SqlTableSchema {
30482                        table_name: "users".to_owned(),
30483                        columns: vec![
30484                            SqlColumnSchema {
30485                                name: "id".to_owned(),
30486                                declared_type: Some("BIGSERIAL".to_owned()),
30487                                nullable: false,
30488                                default_value: None,
30489                                primary_key_ordinal: Some(0),
30490                                comment: None,
30491                                autoincrement: true,
30492                            },
30493                            SqlColumnSchema {
30494                                name: "email".to_owned(),
30495                                declared_type: Some("TEXT".to_owned()),
30496                                nullable: false,
30497                                default_value: None,
30498                                primary_key_ordinal: None,
30499                                comment: None,
30500                                autoincrement: false,
30501                            },
30502                        ],
30503                    }))
30504                } else {
30505                    Ok(None)
30506                }
30507            }
30508        }
30509        let conn = PgLikeAutoinc;
30510        let schema = sql_table_schema(&conn, "users", None).unwrap().unwrap();
30511        assert!(schema.column("id").unwrap().autoincrement);
30512        assert!(!schema.column("email").unwrap().autoincrement);
30513    }
30514
30515    // ── SqlInspector facade (br-szs9 / fd90.38) ──────────────────────────
30516
30517    #[cfg(feature = "sql-sqlite")]
30518    #[test]
30519    fn sql_inspector_tables_views_schemas() {
30520        let conn = make_sql_test_conn();
30521        super::SqlConnection::execute_batch(&conn, "CREATE TABLE t1 (x INTEGER);").unwrap();
30522        super::SqlConnection::execute_batch(&conn, "CREATE TABLE t2 (y TEXT);").unwrap();
30523        super::SqlConnection::execute_batch(&conn, "CREATE VIEW v1 AS SELECT x FROM t1;").unwrap();
30524
30525        let inspector = SqlInspector::new(&conn);
30526        assert_eq!(inspector.tables(None).unwrap(), vec!["t1", "t2"]);
30527        assert_eq!(inspector.views(None).unwrap(), vec!["v1"]);
30528        // SQLite has no meaningful schemas → empty vec.
30529        assert!(inspector.schemas().unwrap().is_empty());
30530    }
30531
30532    #[cfg(feature = "sql-sqlite")]
30533    #[test]
30534    fn sql_inspector_columns_pk_indexes_fks() {
30535        let conn = make_sql_test_conn();
30536        super::SqlConnection::execute_batch(
30537            &conn,
30538            "CREATE TABLE parent (pid INTEGER PRIMARY KEY);",
30539        )
30540        .unwrap();
30541        super::SqlConnection::execute_batch(
30542            &conn,
30543            "CREATE TABLE child ( \
30544                cid INTEGER PRIMARY KEY, \
30545                parent_id INTEGER, \
30546                tag TEXT, \
30547                FOREIGN KEY (parent_id) REFERENCES parent(pid) \
30548             );",
30549        )
30550        .unwrap();
30551        super::SqlConnection::execute_batch(&conn, "CREATE INDEX idx_child_tag ON child(tag);")
30552            .unwrap();
30553
30554        let inspector = SqlInspector::new(&conn);
30555
30556        // columns: 3 columns on 'child', cid + parent_id + tag.
30557        let schema = inspector.columns("child", None).unwrap().unwrap();
30558        let names: Vec<&str> = schema.columns.iter().map(|c| c.name.as_str()).collect();
30559        assert_eq!(names, vec!["cid", "parent_id", "tag"]);
30560
30561        // primary_key_columns: cid is the sole PK.
30562        let pk = inspector.primary_key_columns("child", None).unwrap();
30563        assert_eq!(pk, vec!["cid"]);
30564
30565        // indexes: only the explicit user index (PK auto-index filtered).
30566        let indexes = inspector.indexes("child", None).unwrap();
30567        assert_eq!(indexes.len(), 1);
30568        assert_eq!(indexes[0].name, "idx_child_tag");
30569
30570        // foreign_keys: child references parent.
30571        let fks = inspector.foreign_keys("child", None).unwrap();
30572        assert_eq!(fks.len(), 1);
30573        assert_eq!(fks[0].columns, vec!["parent_id"]);
30574        assert_eq!(fks[0].referenced_table, "parent");
30575        assert_eq!(fks[0].referenced_columns, vec!["pid"]);
30576    }
30577
30578    #[cfg(feature = "sql-sqlite")]
30579    #[test]
30580    fn sql_inspector_unique_constraints_and_table_exists() {
30581        let conn = make_sql_test_conn();
30582        super::SqlConnection::execute_batch(
30583            &conn,
30584            "CREATE TABLE users (id INTEGER PRIMARY KEY, email TEXT UNIQUE);",
30585        )
30586        .unwrap();
30587        let inspector = SqlInspector::new(&conn);
30588        let uqs = inspector.unique_constraints("users", None).unwrap();
30589        assert_eq!(uqs.len(), 1);
30590        assert_eq!(uqs[0].columns, vec!["email"]);
30591        assert!(inspector.table_exists("users", None).unwrap());
30592        assert!(!inspector.table_exists("not_there", None).unwrap());
30593    }
30594
30595    #[cfg(feature = "sql-sqlite")]
30596    #[test]
30597    fn sql_inspector_server_version_and_dialect() {
30598        let conn = make_sql_test_conn();
30599        let inspector = SqlInspector::new(&conn);
30600        let version = inspector.server_version().unwrap().unwrap();
30601        assert!(version.starts_with("3."));
30602        assert_eq!(inspector.dialect_name(), "sqlite");
30603        // SQLite has no documented identifier-length cap.
30604        assert_eq!(inspector.max_identifier_length(), None);
30605    }
30606
30607    #[cfg(feature = "sql-sqlite")]
30608    #[test]
30609    fn sql_inspector_table_comment_returns_none_on_sqlite() {
30610        let conn = make_sql_test_conn();
30611        super::SqlConnection::execute_batch(&conn, "CREATE TABLE t (x INTEGER);").unwrap();
30612        let inspector = SqlInspector::new(&conn);
30613        assert!(inspector.table_comment("t", None).unwrap().is_none());
30614    }
30615
30616    #[cfg(feature = "sql-sqlite")]
30617    #[test]
30618    fn sql_inspector_via_inspect_helper() {
30619        // The free-fn `inspect(&conn)` is the one-shot construction helper.
30620        // Per fd90.46: import lives inside the test so --no-default-features
30621        // builds don't see it as unused.
30622        use super::inspect;
30623        let conn = make_sql_test_conn();
30624        super::SqlConnection::execute_batch(&conn, "CREATE TABLE one (x INTEGER);").unwrap();
30625        let inspector = inspect(&conn);
30626        assert_eq!(inspector.tables(None).unwrap(), vec!["one"]);
30627    }
30628
30629    #[test]
30630    fn sql_inspector_routes_schema_arg_to_backend() {
30631        // Multi-schema backend: verifies SqlInspector forwards the schema
30632        // arg to every method that accepts one.
30633        struct PgLikeStub;
30634        impl super::SqlConnection for PgLikeStub {
30635            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
30636                Ok(SqlQueryResult {
30637                    columns: vec![],
30638                    rows: vec![],
30639                })
30640            }
30641            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
30642                Ok(())
30643            }
30644            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
30645                Ok(false)
30646            }
30647            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
30648                Ok(())
30649            }
30650            fn dtype_sql(&self, _dtype: DType) -> &'static str {
30651                "TEXT"
30652            }
30653            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
30654                "TEXT"
30655            }
30656            fn supports_schemas(&self) -> bool {
30657                true
30658            }
30659            fn list_tables(&self, schema: Option<&str>) -> Result<Vec<String>, IoError> {
30660                Ok(match schema {
30661                    Some("analytics") => vec!["events".to_owned()],
30662                    _ => vec![],
30663                })
30664            }
30665            fn list_views(&self, schema: Option<&str>) -> Result<Vec<String>, IoError> {
30666                Ok(match schema {
30667                    Some("analytics") => vec!["daily".to_owned()],
30668                    _ => vec![],
30669                })
30670            }
30671            fn list_schemas(&self) -> Result<Vec<String>, IoError> {
30672                Ok(vec!["public".to_owned(), "analytics".to_owned()])
30673            }
30674            fn dialect_name(&self) -> &'static str {
30675                "postgresql"
30676            }
30677            fn max_identifier_length(&self) -> Option<usize> {
30678                Some(63)
30679            }
30680        }
30681        let conn = PgLikeStub;
30682        let inspector = SqlInspector::new(&conn);
30683
30684        assert_eq!(inspector.tables(Some("analytics")).unwrap(), vec!["events"]);
30685        assert_eq!(inspector.views(Some("analytics")).unwrap(), vec!["daily"]);
30686        assert!(inspector.tables(Some("audit")).unwrap().is_empty());
30687        assert_eq!(inspector.schemas().unwrap(), vec!["public", "analytics"]);
30688        assert_eq!(inspector.dialect_name(), "postgresql");
30689        assert_eq!(inspector.max_identifier_length(), Some(63));
30690    }
30691
30692    // ── SqlInspector::has_column / column (br-ppry / fd90.39) ─────────────
30693
30694    #[cfg(feature = "sql-sqlite")]
30695    #[test]
30696    fn sql_inspector_has_column_returns_true_for_present_column() {
30697        let conn = make_sql_test_conn();
30698        super::SqlConnection::execute_batch(
30699            &conn,
30700            "CREATE TABLE has_col_tbl (id INTEGER, name TEXT);",
30701        )
30702        .unwrap();
30703        let inspector = SqlInspector::new(&conn);
30704        assert!(inspector.has_column("has_col_tbl", "id", None).unwrap());
30705        assert!(inspector.has_column("has_col_tbl", "name", None).unwrap());
30706    }
30707
30708    #[cfg(feature = "sql-sqlite")]
30709    #[test]
30710    fn sql_inspector_has_column_returns_false_for_missing_column() {
30711        let conn = make_sql_test_conn();
30712        super::SqlConnection::execute_batch(&conn, "CREATE TABLE only_id (id INTEGER);").unwrap();
30713        let inspector = SqlInspector::new(&conn);
30714        // Table exists but no such column.
30715        assert!(!inspector.has_column("only_id", "name", None).unwrap());
30716    }
30717
30718    #[cfg(feature = "sql-sqlite")]
30719    #[test]
30720    fn sql_inspector_has_column_returns_false_for_missing_table() {
30721        let conn = make_sql_test_conn();
30722        let inspector = SqlInspector::new(&conn);
30723        // Table doesn't exist → has_column propagates Ok(false), not error.
30724        assert!(
30725            !inspector
30726                .has_column("no_such_tbl", "any_col", None)
30727                .unwrap()
30728        );
30729    }
30730
30731    #[cfg(feature = "sql-sqlite")]
30732    #[test]
30733    fn sql_inspector_column_returns_full_metadata_for_present_column() {
30734        let conn = make_sql_test_conn();
30735        super::SqlConnection::execute_batch(
30736            &conn,
30737            "CREATE TABLE detailed (id INTEGER PRIMARY KEY, status TEXT DEFAULT 'active');",
30738        )
30739        .unwrap();
30740        let inspector = SqlInspector::new(&conn);
30741        let id = inspector.column("detailed", "id", None).unwrap().unwrap();
30742        assert_eq!(id.name, "id");
30743        assert_eq!(id.declared_type.as_deref(), Some("INTEGER"));
30744        assert_eq!(id.primary_key_ordinal, Some(0));
30745        // INTEGER PRIMARY KEY → SQLite autoincrement (rowid alias).
30746        assert!(id.autoincrement);
30747
30748        let status = inspector
30749            .column("detailed", "status", None)
30750            .unwrap()
30751            .unwrap();
30752        assert_eq!(status.declared_type.as_deref(), Some("TEXT"));
30753        assert!(status.nullable);
30754        assert_eq!(status.default_value.as_deref(), Some("'active'"));
30755        assert!(!status.autoincrement);
30756    }
30757
30758    #[cfg(feature = "sql-sqlite")]
30759    #[test]
30760    fn sql_inspector_column_returns_none_for_missing_column_or_table() {
30761        let conn = make_sql_test_conn();
30762        super::SqlConnection::execute_batch(&conn, "CREATE TABLE only_x (x INTEGER);").unwrap();
30763        let inspector = SqlInspector::new(&conn);
30764        // Existing table, missing column → None.
30765        assert!(
30766            inspector
30767                .column("only_x", "missing", None)
30768                .unwrap()
30769                .is_none()
30770        );
30771        // Missing table → None.
30772        assert!(inspector.column("no_such", "any", None).unwrap().is_none());
30773    }
30774
30775    #[test]
30776    fn sql_inspector_has_column_routes_schema_arg_to_backend() {
30777        struct PgLikeColumns;
30778        impl super::SqlConnection for PgLikeColumns {
30779            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
30780                Ok(SqlQueryResult {
30781                    columns: vec![],
30782                    rows: vec![],
30783                })
30784            }
30785            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
30786                Ok(())
30787            }
30788            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
30789                Ok(false)
30790            }
30791            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
30792                Ok(())
30793            }
30794            fn dtype_sql(&self, _dtype: DType) -> &'static str {
30795                "TEXT"
30796            }
30797            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
30798                "TEXT"
30799            }
30800            fn supports_schemas(&self) -> bool {
30801                true
30802            }
30803            fn table_schema(
30804                &self,
30805                table: &str,
30806                schema: Option<&str>,
30807            ) -> Result<Option<SqlTableSchema>, IoError> {
30808                if table == "users" && schema == Some("public") {
30809                    Ok(Some(SqlTableSchema {
30810                        table_name: "users".to_owned(),
30811                        columns: vec![SqlColumnSchema {
30812                            name: "id".to_owned(),
30813                            declared_type: Some("BIGINT".to_owned()),
30814                            nullable: false,
30815                            default_value: None,
30816                            primary_key_ordinal: Some(0),
30817                            comment: None,
30818                            autoincrement: true,
30819                        }],
30820                    }))
30821                } else {
30822                    Ok(None)
30823                }
30824            }
30825        }
30826        let conn = PgLikeColumns;
30827        let inspector = SqlInspector::new(&conn);
30828        assert!(inspector.has_column("users", "id", Some("public")).unwrap());
30829        assert!(!inspector.has_column("users", "id", Some("audit")).unwrap());
30830        assert!(
30831            !inspector
30832                .has_column("users", "missing", Some("public"))
30833                .unwrap()
30834        );
30835
30836        let id_col = inspector
30837            .column("users", "id", Some("public"))
30838            .unwrap()
30839            .unwrap();
30840        assert_eq!(id_col.declared_type.as_deref(), Some("BIGINT"));
30841        assert!(id_col.autoincrement);
30842        assert!(
30843            inspector
30844                .column("users", "id", Some("audit"))
30845                .unwrap()
30846                .is_none()
30847        );
30848    }
30849
30850    // ── SqlInspector::reflect_table (br-76mw / fd90.40) ──────────────────
30851
30852    #[cfg(feature = "sql-sqlite")]
30853    #[test]
30854    fn sql_inspector_reflect_table_unknown_returns_none() {
30855        let conn = make_sql_test_conn();
30856        let inspector = SqlInspector::new(&conn);
30857        let result = inspector.reflect_table("no_such", None).unwrap();
30858        assert!(result.is_none());
30859    }
30860
30861    #[cfg(feature = "sql-sqlite")]
30862    #[test]
30863    fn sql_inspector_reflect_table_bundles_all_metadata() {
30864        let conn = make_sql_test_conn();
30865        super::SqlConnection::execute_batch(
30866            &conn,
30867            "CREATE TABLE parent (pid INTEGER PRIMARY KEY, code TEXT);",
30868        )
30869        .unwrap();
30870        super::SqlConnection::execute_batch(
30871            &conn,
30872            "CREATE TABLE bundled ( \
30873                id INTEGER PRIMARY KEY, \
30874                parent_id INTEGER, \
30875                slug TEXT, \
30876                email TEXT UNIQUE, \
30877                FOREIGN KEY (parent_id) REFERENCES parent(pid) \
30878             );",
30879        )
30880        .unwrap();
30881        super::SqlConnection::execute_batch(
30882            &conn,
30883            "CREATE INDEX idx_bundled_slug ON bundled(slug);",
30884        )
30885        .unwrap();
30886
30887        let inspector = SqlInspector::new(&conn);
30888        let bundle = inspector
30889            .reflect_table("bundled", None)
30890            .unwrap()
30891            .expect("table exists");
30892
30893        assert_eq!(bundle.table_name, "bundled");
30894
30895        // Columns: id, parent_id, slug, email.
30896        let names: Vec<&str> = bundle.columns.iter().map(|c| c.name.as_str()).collect();
30897        assert_eq!(names, vec!["id", "parent_id", "slug", "email"]);
30898        // INTEGER PRIMARY KEY id is autoincrement.
30899        let id_col = bundle
30900            .columns
30901            .iter()
30902            .find(|c| c.name == "id")
30903            .expect("id col");
30904        assert!(id_col.autoincrement);
30905
30906        // Primary key.
30907        assert_eq!(bundle.primary_key_columns, vec!["id"]);
30908
30909        // Indexes (only the user CREATE INDEX; the UNIQUE constraint
30910        // index goes via unique_constraints, the PK auto-index is
30911        // hidden).
30912        assert_eq!(bundle.indexes.len(), 1);
30913        assert_eq!(bundle.indexes[0].name, "idx_bundled_slug");
30914
30915        // Unique constraints (the inline UNIQUE on email).
30916        assert_eq!(bundle.unique_constraints.len(), 1);
30917        assert_eq!(bundle.unique_constraints[0].columns, vec!["email"]);
30918
30919        // Foreign keys (parent_id -> parent.pid).
30920        assert_eq!(bundle.foreign_keys.len(), 1);
30921        assert_eq!(bundle.foreign_keys[0].columns, vec!["parent_id"]);
30922        assert_eq!(bundle.foreign_keys[0].referenced_table, "parent");
30923
30924        // SQLite has no native column/table comment; comment is None.
30925        assert!(bundle.comment.is_none());
30926    }
30927
30928    #[test]
30929    fn sql_inspector_reflect_table_routes_to_backend_override() {
30930        // Multi-schema PG-like backend that returns explicit comment +
30931        // populated metadata. Verifies all five sub-calls flow through
30932        // and end up in the bundled struct.
30933        struct PgLikeBundle;
30934        impl super::SqlConnection for PgLikeBundle {
30935            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
30936                Ok(SqlQueryResult {
30937                    columns: vec![],
30938                    rows: vec![],
30939                })
30940            }
30941            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
30942                Ok(())
30943            }
30944            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
30945                Ok(false)
30946            }
30947            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
30948                Ok(())
30949            }
30950            fn dtype_sql(&self, _dtype: DType) -> &'static str {
30951                "TEXT"
30952            }
30953            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
30954                "TEXT"
30955            }
30956            fn supports_schemas(&self) -> bool {
30957                true
30958            }
30959            fn table_schema(
30960                &self,
30961                table: &str,
30962                schema: Option<&str>,
30963            ) -> Result<Option<SqlTableSchema>, IoError> {
30964                if table == "users" && schema == Some("public") {
30965                    Ok(Some(SqlTableSchema {
30966                        table_name: "users".to_owned(),
30967                        columns: vec![SqlColumnSchema {
30968                            name: "id".to_owned(),
30969                            declared_type: Some("BIGINT".to_owned()),
30970                            nullable: false,
30971                            default_value: None,
30972                            primary_key_ordinal: Some(0),
30973                            comment: None,
30974                            autoincrement: true,
30975                        }],
30976                    }))
30977                } else {
30978                    Ok(None)
30979                }
30980            }
30981            fn primary_key_columns(
30982                &self,
30983                table: &str,
30984                schema: Option<&str>,
30985            ) -> Result<Vec<String>, IoError> {
30986                if table == "users" && schema == Some("public") {
30987                    Ok(vec!["id".to_owned()])
30988                } else {
30989                    Ok(vec![])
30990                }
30991            }
30992            fn list_indexes(
30993                &self,
30994                _table: &str,
30995                _schema: Option<&str>,
30996            ) -> Result<Vec<SqlIndexSchema>, IoError> {
30997                Ok(vec![SqlIndexSchema {
30998                    name: "users_status_idx".to_owned(),
30999                    columns: vec!["status".to_owned()],
31000                    unique: false,
31001                }])
31002            }
31003            fn list_foreign_keys(
31004                &self,
31005                _table: &str,
31006                _schema: Option<&str>,
31007            ) -> Result<Vec<SqlForeignKeySchema>, IoError> {
31008                Ok(vec![])
31009            }
31010            fn list_unique_constraints(
31011                &self,
31012                _table: &str,
31013                _schema: Option<&str>,
31014            ) -> Result<Vec<SqlUniqueConstraintSchema>, IoError> {
31015                Ok(vec![SqlUniqueConstraintSchema {
31016                    name: "users_email_key".to_owned(),
31017                    columns: vec!["email".to_owned()],
31018                }])
31019            }
31020            fn table_comment(
31021                &self,
31022                _table: &str,
31023                _schema: Option<&str>,
31024            ) -> Result<Option<String>, IoError> {
31025                Ok(Some("Customer accounts".to_owned()))
31026            }
31027        }
31028        let conn = PgLikeBundle;
31029        let inspector = SqlInspector::new(&conn);
31030        let bundle = inspector
31031            .reflect_table("users", Some("public"))
31032            .unwrap()
31033            .expect("present");
31034        assert_eq!(bundle.table_name, "users");
31035        assert_eq!(bundle.columns.len(), 1);
31036        assert_eq!(bundle.primary_key_columns, vec!["id"]);
31037        assert_eq!(bundle.indexes.len(), 1);
31038        assert_eq!(bundle.indexes[0].name, "users_status_idx");
31039        assert_eq!(bundle.unique_constraints.len(), 1);
31040        assert_eq!(bundle.foreign_keys.len(), 0);
31041        assert_eq!(bundle.comment.as_deref(), Some("Customer accounts"));
31042
31043        // Wrong schema -> None (table_schema returns None).
31044        assert!(
31045            inspector
31046                .reflect_table("users", Some("audit"))
31047                .unwrap()
31048                .is_none()
31049        );
31050    }
31051
31052    // Use SqlReflectedTable in a smoke test so the struct's named
31053    // fields are exercised at the use-site too.
31054    #[test]
31055    fn sql_reflected_table_bundle_smoke_test() {
31056        let bundle = SqlReflectedTable {
31057            table_name: "t".to_owned(),
31058            columns: vec![],
31059            primary_key_columns: vec![],
31060            indexes: vec![],
31061            foreign_keys: vec![],
31062            unique_constraints: vec![],
31063            comment: None,
31064        };
31065        assert_eq!(bundle.table_name, "t");
31066        assert!(bundle.columns.is_empty());
31067    }
31068
31069    // ── SqlReflectedTable accessor methods (br-63ac / fd90.51) ────────────
31070
31071    #[test]
31072    fn sql_reflected_table_accessors_find_named_entries() {
31073        let bundle = SqlReflectedTable {
31074            table_name: "orders".to_owned(),
31075            columns: vec![
31076                SqlColumnSchema {
31077                    name: "id".to_owned(),
31078                    declared_type: Some("INTEGER".to_owned()),
31079                    nullable: false,
31080                    default_value: None,
31081                    primary_key_ordinal: Some(0),
31082                    comment: None,
31083                    autoincrement: true,
31084                },
31085                SqlColumnSchema {
31086                    name: "user_id".to_owned(),
31087                    declared_type: Some("INTEGER".to_owned()),
31088                    nullable: false,
31089                    default_value: None,
31090                    primary_key_ordinal: None,
31091                    comment: None,
31092                    autoincrement: false,
31093                },
31094            ],
31095            primary_key_columns: vec!["id".to_owned()],
31096            indexes: vec![SqlIndexSchema {
31097                name: "idx_orders_user".to_owned(),
31098                columns: vec!["user_id".to_owned()],
31099                unique: false,
31100            }],
31101            foreign_keys: vec![SqlForeignKeySchema {
31102                constraint_name: None,
31103                columns: vec!["user_id".to_owned()],
31104                referenced_table: "users".to_owned(),
31105                referenced_columns: vec!["id".to_owned()],
31106            }],
31107            unique_constraints: vec![SqlUniqueConstraintSchema {
31108                name: "uq_orders_id".to_owned(),
31109                columns: vec!["id".to_owned()],
31110            }],
31111            comment: Some("Customer orders".to_owned()),
31112        };
31113
31114        // column(name): present + missing.
31115        let id = bundle.column("id").expect("id column");
31116        assert_eq!(id.declared_type.as_deref(), Some("INTEGER"));
31117        assert!(id.autoincrement);
31118        assert!(bundle.column("missing").is_none());
31119
31120        // index(name): present + missing.
31121        let idx = bundle.index("idx_orders_user").expect("idx");
31122        assert_eq!(idx.columns, vec!["user_id"]);
31123        assert!(bundle.index("idx_does_not_exist").is_none());
31124
31125        // unique_constraint(name).
31126        let uq = bundle.unique_constraint("uq_orders_id").expect("uq");
31127        assert_eq!(uq.columns, vec!["id"]);
31128        assert!(bundle.unique_constraint("uq_missing").is_none());
31129
31130        // foreign_keys_for_column(col): matches the FK touching user_id.
31131        let fks = bundle.foreign_keys_for_column("user_id");
31132        assert_eq!(fks.len(), 1);
31133        assert_eq!(fks[0].referenced_table, "users");
31134        // Column not part of any FK -> empty.
31135        assert!(bundle.foreign_keys_for_column("id").is_empty());
31136        assert!(bundle.foreign_keys_for_column("nonexistent").is_empty());
31137    }
31138
31139    #[test]
31140    fn sql_reflected_table_foreign_keys_for_column_handles_composite_fks() {
31141        let bundle = SqlReflectedTable {
31142            table_name: "rolling_fact".to_owned(),
31143            columns: vec![],
31144            primary_key_columns: vec![],
31145            indexes: vec![],
31146            foreign_keys: vec![SqlForeignKeySchema {
31147                constraint_name: None,
31148                columns: vec!["fyear".to_owned(), "fmonth".to_owned()],
31149                referenced_table: "rolling".to_owned(),
31150                referenced_columns: vec!["year".to_owned(), "month".to_owned()],
31151            }],
31152            unique_constraints: vec![],
31153            comment: None,
31154        };
31155        // Composite FK touches both fyear and fmonth — both should
31156        // surface the same FK.
31157        assert_eq!(bundle.foreign_keys_for_column("fyear").len(), 1);
31158        assert_eq!(bundle.foreign_keys_for_column("fmonth").len(), 1);
31159        assert!(bundle.foreign_keys_for_column("year").is_empty()); // referenced col, not from col
31160    }
31161
31162    #[test]
31163    fn sql_reflected_table_foreign_keys_for_column_returns_multiple_when_relevant() {
31164        // Rare but valid: one column participates in two FKs (e.g.
31165        // same column referenced by separate FKs to two parents).
31166        let bundle = SqlReflectedTable {
31167            table_name: "audit".to_owned(),
31168            columns: vec![],
31169            primary_key_columns: vec![],
31170            indexes: vec![],
31171            foreign_keys: vec![
31172                SqlForeignKeySchema {
31173                    constraint_name: Some("fk_audit_a".to_owned()),
31174                    columns: vec!["entity_id".to_owned()],
31175                    referenced_table: "users".to_owned(),
31176                    referenced_columns: vec!["id".to_owned()],
31177                },
31178                SqlForeignKeySchema {
31179                    constraint_name: Some("fk_audit_b".to_owned()),
31180                    columns: vec!["entity_id".to_owned()],
31181                    referenced_table: "products".to_owned(),
31182                    referenced_columns: vec!["id".to_owned()],
31183                },
31184            ],
31185            unique_constraints: vec![],
31186            comment: None,
31187        };
31188        let fks = bundle.foreign_keys_for_column("entity_id");
31189        assert_eq!(fks.len(), 2);
31190        // Order preserved.
31191        assert_eq!(fks[0].constraint_name.as_deref(), Some("fk_audit_a"));
31192        assert_eq!(fks[1].constraint_name.as_deref(), Some("fk_audit_b"));
31193    }
31194
31195    // ── indexes_for_column / unique_constraints_for_column (br-37uy / fd90.52) ─
31196
31197    #[test]
31198    fn sql_reflected_table_indexes_for_column_matches_any_position() {
31199        let bundle = SqlReflectedTable {
31200            table_name: "rolling".to_owned(),
31201            columns: vec![],
31202            primary_key_columns: vec![],
31203            indexes: vec![
31204                SqlIndexSchema {
31205                    name: "idx_rolling_year".to_owned(),
31206                    columns: vec!["year".to_owned()],
31207                    unique: false,
31208                },
31209                SqlIndexSchema {
31210                    name: "idx_rolling_y_m_c".to_owned(),
31211                    columns: vec!["year".to_owned(), "month".to_owned(), "code".to_owned()],
31212                    unique: false,
31213                },
31214            ],
31215            foreign_keys: vec![],
31216            unique_constraints: vec![],
31217            comment: None,
31218        };
31219
31220        // 'year' appears in both indexes (first in idx_year, first in
31221        // composite). Returns both.
31222        let year_idxs = bundle.indexes_for_column("year");
31223        assert_eq!(year_idxs.len(), 2);
31224
31225        // 'month' only appears in the composite index, in middle position.
31226        let month_idxs = bundle.indexes_for_column("month");
31227        assert_eq!(month_idxs.len(), 1);
31228        assert_eq!(month_idxs[0].name, "idx_rolling_y_m_c");
31229
31230        // 'code' appears only in the composite, last position.
31231        let code_idxs = bundle.indexes_for_column("code");
31232        assert_eq!(code_idxs.len(), 1);
31233
31234        // Column not in any index.
31235        assert!(bundle.indexes_for_column("nonexistent").is_empty());
31236    }
31237
31238    #[test]
31239    fn sql_reflected_table_unique_constraints_for_column_matches_any_position() {
31240        let bundle = SqlReflectedTable {
31241            table_name: "events".to_owned(),
31242            columns: vec![],
31243            primary_key_columns: vec![],
31244            indexes: vec![],
31245            foreign_keys: vec![],
31246            unique_constraints: vec![
31247                SqlUniqueConstraintSchema {
31248                    name: "uq_events_email".to_owned(),
31249                    columns: vec!["email".to_owned()],
31250                },
31251                SqlUniqueConstraintSchema {
31252                    name: "uq_events_user_event_ts".to_owned(),
31253                    columns: vec!["user_id".to_owned(), "event_id".to_owned(), "ts".to_owned()],
31254                },
31255            ],
31256            comment: None,
31257        };
31258
31259        let email_uqs = bundle.unique_constraints_for_column("email");
31260        assert_eq!(email_uqs.len(), 1);
31261        assert_eq!(email_uqs[0].name, "uq_events_email");
31262
31263        // 'event_id' middle position in composite.
31264        let event_uqs = bundle.unique_constraints_for_column("event_id");
31265        assert_eq!(event_uqs.len(), 1);
31266        assert_eq!(event_uqs[0].columns, vec!["user_id", "event_id", "ts"]);
31267
31268        // 'ts' last position in composite.
31269        let ts_uqs = bundle.unique_constraints_for_column("ts");
31270        assert_eq!(ts_uqs.len(), 1);
31271
31272        assert!(
31273            bundle
31274                .unique_constraints_for_column("nonexistent")
31275                .is_empty()
31276        );
31277    }
31278
31279    #[test]
31280    fn sql_reflected_table_for_column_accessors_return_multiple() {
31281        // A column can appear in multiple indexes / unique constraints.
31282        let bundle = SqlReflectedTable {
31283            table_name: "wide".to_owned(),
31284            columns: vec![],
31285            primary_key_columns: vec![],
31286            indexes: vec![
31287                SqlIndexSchema {
31288                    name: "idx_a".to_owned(),
31289                    columns: vec!["x".to_owned()],
31290                    unique: false,
31291                },
31292                SqlIndexSchema {
31293                    name: "idx_b".to_owned(),
31294                    columns: vec!["x".to_owned(), "y".to_owned()],
31295                    unique: true,
31296                },
31297            ],
31298            foreign_keys: vec![],
31299            unique_constraints: vec![
31300                SqlUniqueConstraintSchema {
31301                    name: "uq_a".to_owned(),
31302                    columns: vec!["x".to_owned()],
31303                },
31304                SqlUniqueConstraintSchema {
31305                    name: "uq_b".to_owned(),
31306                    columns: vec!["x".to_owned(), "z".to_owned()],
31307                },
31308            ],
31309            comment: None,
31310        };
31311
31312        let idx_for_x = bundle.indexes_for_column("x");
31313        assert_eq!(idx_for_x.len(), 2);
31314        assert_eq!(idx_for_x[0].name, "idx_a");
31315        assert_eq!(idx_for_x[1].name, "idx_b");
31316
31317        let uq_for_x = bundle.unique_constraints_for_column("x");
31318        assert_eq!(uq_for_x.len(), 2);
31319        assert_eq!(uq_for_x[0].name, "uq_a");
31320        assert_eq!(uq_for_x[1].name, "uq_b");
31321    }
31322
31323    // ── SqlInspector::reflect_all_tables (br-jmmo / fd90.53) ─────────────
31324
31325    #[cfg(feature = "sql-sqlite")]
31326    #[test]
31327    fn sql_inspector_reflect_all_tables_empty_db() {
31328        let conn = make_sql_test_conn();
31329        let inspector = SqlInspector::new(&conn);
31330        let bundles = inspector.reflect_all_tables(None).unwrap();
31331        assert!(bundles.is_empty());
31332    }
31333
31334    #[cfg(feature = "sql-sqlite")]
31335    #[test]
31336    fn sql_inspector_reflect_all_tables_returns_one_bundle_per_table() {
31337        let conn = make_sql_test_conn();
31338        super::SqlConnection::execute_batch(
31339            &conn,
31340            "CREATE TABLE alpha (id INTEGER PRIMARY KEY, name TEXT);",
31341        )
31342        .unwrap();
31343        super::SqlConnection::execute_batch(&conn, "CREATE TABLE beta (uid INTEGER, label TEXT);")
31344            .unwrap();
31345        let inspector = SqlInspector::new(&conn);
31346        let bundles = inspector.reflect_all_tables(None).unwrap();
31347        assert_eq!(bundles.len(), 2);
31348        // Ordered alphabetically by list_tables.
31349        assert_eq!(bundles[0].table_name, "alpha");
31350        assert_eq!(bundles[1].table_name, "beta");
31351        // Each bundle has full metadata.
31352        assert_eq!(
31353            bundles[0]
31354                .columns
31355                .iter()
31356                .map(|c| c.name.as_str())
31357                .collect::<Vec<_>>(),
31358            vec!["id", "name"]
31359        );
31360        assert_eq!(bundles[0].primary_key_columns, vec!["id"]);
31361        assert_eq!(bundles[1].columns.len(), 2);
31362        assert!(bundles[1].primary_key_columns.is_empty());
31363    }
31364
31365    #[test]
31366    fn sql_inspector_reflect_all_tables_skips_disappearing_tables() {
31367        // Race-condition stub: list_tables returns ["a", "b"] but
31368        // table_schema returns None for "b" (simulating a concurrent
31369        // DROP between list and reflect). reflect_all_tables must
31370        // skip "b" without erroring.
31371        struct DisappearingTable;
31372        impl super::SqlConnection for DisappearingTable {
31373            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
31374                Ok(SqlQueryResult {
31375                    columns: vec![],
31376                    rows: vec![],
31377                })
31378            }
31379            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
31380                Ok(())
31381            }
31382            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
31383                Ok(false)
31384            }
31385            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
31386                Ok(())
31387            }
31388            fn dtype_sql(&self, _dtype: DType) -> &'static str {
31389                "TEXT"
31390            }
31391            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
31392                "TEXT"
31393            }
31394            fn list_tables(&self, _schema: Option<&str>) -> Result<Vec<String>, IoError> {
31395                Ok(vec!["a".to_owned(), "b".to_owned()])
31396            }
31397            fn table_schema(
31398                &self,
31399                table: &str,
31400                _schema: Option<&str>,
31401            ) -> Result<Option<SqlTableSchema>, IoError> {
31402                if table == "a" {
31403                    Ok(Some(SqlTableSchema {
31404                        table_name: "a".to_owned(),
31405                        columns: vec![SqlColumnSchema {
31406                            name: "x".to_owned(),
31407                            declared_type: Some("INTEGER".to_owned()),
31408                            nullable: true,
31409                            default_value: None,
31410                            primary_key_ordinal: None,
31411                            comment: None,
31412                            autoincrement: false,
31413                        }],
31414                    }))
31415                } else {
31416                    // b "disappeared" between list and reflect.
31417                    Ok(None)
31418                }
31419            }
31420        }
31421        let conn = DisappearingTable;
31422        let inspector = SqlInspector::new(&conn);
31423        let bundles = inspector.reflect_all_tables(None).unwrap();
31424        assert_eq!(bundles.len(), 1);
31425        assert_eq!(bundles[0].table_name, "a");
31426    }
31427
31428    #[test]
31429    fn sql_inspector_reflect_all_tables_routes_schema_arg() {
31430        // Multi-schema stub: list_tables returns different sets per
31431        // schema; reflect_all_tables must propagate the schema arg.
31432        struct MultiSchemaReflect;
31433        impl super::SqlConnection for MultiSchemaReflect {
31434            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
31435                Ok(SqlQueryResult {
31436                    columns: vec![],
31437                    rows: vec![],
31438                })
31439            }
31440            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
31441                Ok(())
31442            }
31443            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
31444                Ok(false)
31445            }
31446            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
31447                Ok(())
31448            }
31449            fn dtype_sql(&self, _dtype: DType) -> &'static str {
31450                "TEXT"
31451            }
31452            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
31453                "TEXT"
31454            }
31455            fn supports_schemas(&self) -> bool {
31456                true
31457            }
31458            fn list_tables(&self, schema: Option<&str>) -> Result<Vec<String>, IoError> {
31459                Ok(match schema {
31460                    Some("analytics") => vec!["events".to_owned()],
31461                    _ => vec![],
31462                })
31463            }
31464            fn table_schema(
31465                &self,
31466                table: &str,
31467                schema: Option<&str>,
31468            ) -> Result<Option<SqlTableSchema>, IoError> {
31469                if table == "events" && schema == Some("analytics") {
31470                    Ok(Some(SqlTableSchema {
31471                        table_name: "events".to_owned(),
31472                        columns: vec![SqlColumnSchema {
31473                            name: "ts".to_owned(),
31474                            declared_type: Some("TIMESTAMPTZ".to_owned()),
31475                            nullable: false,
31476                            default_value: None,
31477                            primary_key_ordinal: None,
31478                            comment: None,
31479                            autoincrement: false,
31480                        }],
31481                    }))
31482                } else {
31483                    Ok(None)
31484                }
31485            }
31486        }
31487        let conn = MultiSchemaReflect;
31488        let inspector = SqlInspector::new(&conn);
31489        let bundles = inspector.reflect_all_tables(Some("analytics")).unwrap();
31490        assert_eq!(bundles.len(), 1);
31491        assert_eq!(bundles[0].table_name, "events");
31492        assert_eq!(
31493            bundles[0].columns[0].declared_type.as_deref(),
31494            Some("TIMESTAMPTZ")
31495        );
31496        // Wrong schema -> empty.
31497        assert!(
31498            inspector
31499                .reflect_all_tables(Some("audit"))
31500                .unwrap()
31501                .is_empty()
31502        );
31503    }
31504
31505    // ── SqlInspector::reflect_all_views (br-zuqt / fd90.54) ──────────────
31506
31507    #[cfg(feature = "sql-sqlite")]
31508    #[test]
31509    fn sql_inspector_reflect_all_views_empty_db() {
31510        let conn = make_sql_test_conn();
31511        let inspector = SqlInspector::new(&conn);
31512        let bundles = inspector.reflect_all_views(None).unwrap();
31513        assert!(bundles.is_empty());
31514    }
31515
31516    #[cfg(feature = "sql-sqlite")]
31517    #[test]
31518    fn sql_inspector_reflect_all_views_returns_one_bundle_per_view() {
31519        let conn = make_sql_test_conn();
31520        super::SqlConnection::execute_batch(&conn, "CREATE TABLE base (id INTEGER, label TEXT);")
31521            .unwrap();
31522        super::SqlConnection::execute_batch(
31523            &conn,
31524            "CREATE VIEW alpha_view AS SELECT id FROM base;",
31525        )
31526        .unwrap();
31527        super::SqlConnection::execute_batch(
31528            &conn,
31529            "CREATE VIEW zebra_view AS SELECT label FROM base;",
31530        )
31531        .unwrap();
31532        let inspector = SqlInspector::new(&conn);
31533        let bundles = inspector.reflect_all_views(None).unwrap();
31534        // Tables ARE NOT included — only views.
31535        assert_eq!(bundles.len(), 2);
31536        assert_eq!(bundles[0].table_name, "alpha_view");
31537        assert_eq!(bundles[1].table_name, "zebra_view");
31538        // Each view's columns are surfaced via PRAGMA table_info.
31539        assert_eq!(
31540            bundles[0]
31541                .columns
31542                .iter()
31543                .map(|c| c.name.as_str())
31544                .collect::<Vec<_>>(),
31545            vec!["id"]
31546        );
31547        assert_eq!(
31548            bundles[1]
31549                .columns
31550                .iter()
31551                .map(|c| c.name.as_str())
31552                .collect::<Vec<_>>(),
31553            vec!["label"]
31554        );
31555        // Views don't carry constraints — PK/FK/UC/index lists are empty.
31556        for bundle in &bundles {
31557            assert!(bundle.primary_key_columns.is_empty());
31558            assert!(bundle.indexes.is_empty());
31559            assert!(bundle.foreign_keys.is_empty());
31560            assert!(bundle.unique_constraints.is_empty());
31561        }
31562    }
31563
31564    #[test]
31565    fn sql_inspector_reflect_all_views_routes_schema_arg() {
31566        // Multi-schema stub: list_views returns different sets per schema.
31567        struct MultiSchemaViewReflect;
31568        impl super::SqlConnection for MultiSchemaViewReflect {
31569            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
31570                Ok(SqlQueryResult {
31571                    columns: vec![],
31572                    rows: vec![],
31573                })
31574            }
31575            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
31576                Ok(())
31577            }
31578            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
31579                Ok(false)
31580            }
31581            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
31582                Ok(())
31583            }
31584            fn dtype_sql(&self, _dtype: DType) -> &'static str {
31585                "TEXT"
31586            }
31587            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
31588                "TEXT"
31589            }
31590            fn supports_schemas(&self) -> bool {
31591                true
31592            }
31593            fn list_views(&self, schema: Option<&str>) -> Result<Vec<String>, IoError> {
31594                Ok(match schema {
31595                    Some("reporting") => vec!["weekly_summary".to_owned()],
31596                    _ => vec![],
31597                })
31598            }
31599            fn table_schema(
31600                &self,
31601                table: &str,
31602                schema: Option<&str>,
31603            ) -> Result<Option<SqlTableSchema>, IoError> {
31604                if table == "weekly_summary" && schema == Some("reporting") {
31605                    Ok(Some(SqlTableSchema {
31606                        table_name: "weekly_summary".to_owned(),
31607                        columns: vec![SqlColumnSchema {
31608                            name: "week".to_owned(),
31609                            declared_type: Some("DATE".to_owned()),
31610                            nullable: true,
31611                            default_value: None,
31612                            primary_key_ordinal: None,
31613                            comment: None,
31614                            autoincrement: false,
31615                        }],
31616                    }))
31617                } else {
31618                    Ok(None)
31619                }
31620            }
31621        }
31622        let conn = MultiSchemaViewReflect;
31623        let inspector = SqlInspector::new(&conn);
31624        let bundles = inspector.reflect_all_views(Some("reporting")).unwrap();
31625        assert_eq!(bundles.len(), 1);
31626        assert_eq!(bundles[0].table_name, "weekly_summary");
31627        assert_eq!(bundles[0].columns[0].declared_type.as_deref(), Some("DATE"));
31628        // Wrong schema -> empty.
31629        assert!(
31630            inspector
31631                .reflect_all_views(Some("audit"))
31632                .unwrap()
31633                .is_empty()
31634        );
31635    }
31636
31637    #[test]
31638    fn sql_inspector_reflect_table_calls_table_schema_only_once() {
31639        // Per fd90.43: reflect_table must derive primary_key_columns
31640        // from the fetched SqlTableSchema rather than dispatching
31641        // primary_key_columns() (which itself calls table_schema). A
31642        // recording stub counts table_schema invocations and asserts
31643        // exactly one round-trip.
31644        use std::cell::Cell;
31645        struct CountingTableSchema {
31646            table_schema_calls: Cell<usize>,
31647        }
31648        impl super::SqlConnection for CountingTableSchema {
31649            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
31650                Ok(SqlQueryResult {
31651                    columns: vec![],
31652                    rows: vec![],
31653                })
31654            }
31655            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
31656                Ok(())
31657            }
31658            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
31659                Ok(false)
31660            }
31661            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
31662                Ok(())
31663            }
31664            fn dtype_sql(&self, _dtype: DType) -> &'static str {
31665                "TEXT"
31666            }
31667            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
31668                "TEXT"
31669            }
31670            fn table_schema(
31671                &self,
31672                _table: &str,
31673                _schema: Option<&str>,
31674            ) -> Result<Option<SqlTableSchema>, IoError> {
31675                self.table_schema_calls
31676                    .set(self.table_schema_calls.get() + 1);
31677                Ok(Some(SqlTableSchema {
31678                    table_name: "x".to_owned(),
31679                    columns: vec![SqlColumnSchema {
31680                        name: "id".to_owned(),
31681                        declared_type: Some("BIGINT".to_owned()),
31682                        nullable: false,
31683                        default_value: None,
31684                        primary_key_ordinal: Some(0),
31685                        comment: None,
31686                        autoincrement: true,
31687                    }],
31688                }))
31689            }
31690        }
31691        let conn = CountingTableSchema {
31692            table_schema_calls: Cell::new(0),
31693        };
31694        let inspector = SqlInspector::new(&conn);
31695        let bundle = inspector.reflect_table("x", None).unwrap().unwrap();
31696        // Exactly one table_schema fetch — primary_key_columns derived
31697        // from the fetched meta, NOT a second round-trip.
31698        assert_eq!(conn.table_schema_calls.get(), 1);
31699        assert_eq!(bundle.primary_key_columns, vec!["id"]);
31700    }
31701
31702    // ── SqlReadOptions default coerce_float (br-o0x6 / fd90.41) ──────────
31703
31704    #[test]
31705    fn sql_read_options_default_coerce_float_matches_pandas() {
31706        // Pandas defaults coerce_float=True for read_sql / read_sql_query
31707        // / read_sql_table. We must match — any bare ::default() call
31708        // should opt INTO coerce_float, not opt out.
31709        let opts = SqlReadOptions::default();
31710        assert!(
31711            opts.coerce_float,
31712            "default coerce_float must be true (pandas parity)"
31713        );
31714        // Sanity: other defaults are the natural empty / None values.
31715        assert!(opts.params.is_none());
31716        assert!(opts.parse_dates.is_none());
31717        assert!(opts.dtype.is_none());
31718        assert!(opts.schema.is_none());
31719        assert!(opts.columns.is_none());
31720        assert!(opts.index_col.is_none());
31721    }
31722
31723    // ── SQL identifier quoting regression matrix (br-frankenpandas-fd90.12) ─
31724    //
31725    // Cross-product of (ANSI / MySQL backtick / MSSQL bracket) quoting
31726    // backends × (SELECT * / SELECT cols / CREATE TABLE / INSERT /
31727    // multi-row INSERT / DROP / TRUNCATE) × identifier shapes that the
31728    // shared validator currently allows: reserved-word names, mixed case,
31729    // leading digits, embedded quote chars (where the backend defines an
31730    // escape rule). All tests are pure query-builder assertions — no live
31731    // backend touched.
31732
31733    #[derive(Default)]
31734    struct AnsiSchemaConn;
31735    impl super::SqlConnection for AnsiSchemaConn {
31736        fn query(&self, _q: &str, _p: &[Scalar]) -> Result<super::SqlQueryResult, IoError> {
31737            Ok(super::SqlQueryResult {
31738                columns: vec![],
31739                rows: vec![],
31740            })
31741        }
31742        fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
31743            Ok(())
31744        }
31745        fn table_exists(&self, _n: &str) -> Result<bool, IoError> {
31746            Ok(false)
31747        }
31748        fn insert_rows(&self, _s: &str, _r: &[Vec<Scalar>]) -> Result<(), IoError> {
31749            Ok(())
31750        }
31751        fn dtype_sql(&self, _d: DType) -> &'static str {
31752            "TEXT"
31753        }
31754        fn index_dtype_sql(&self, _i: &Index) -> &'static str {
31755            "TEXT"
31756        }
31757        fn supports_schemas(&self) -> bool {
31758            true
31759        }
31760        fn parameter_marker(&self, ordinal: usize) -> String {
31761            format!("${ordinal}")
31762        }
31763        fn max_identifier_length(&self) -> Option<usize> {
31764            Some(63)
31765        }
31766    }
31767
31768    #[derive(Default)]
31769    struct MysqlBacktickConn;
31770    impl super::SqlConnection for MysqlBacktickConn {
31771        fn query(&self, _q: &str, _p: &[Scalar]) -> Result<super::SqlQueryResult, IoError> {
31772            Ok(super::SqlQueryResult {
31773                columns: vec![],
31774                rows: vec![],
31775            })
31776        }
31777        fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
31778            Ok(())
31779        }
31780        fn table_exists(&self, _n: &str) -> Result<bool, IoError> {
31781            Ok(false)
31782        }
31783        fn insert_rows(&self, _s: &str, _r: &[Vec<Scalar>]) -> Result<(), IoError> {
31784            Ok(())
31785        }
31786        fn dtype_sql(&self, _d: DType) -> &'static str {
31787            "TEXT"
31788        }
31789        fn index_dtype_sql(&self, _i: &Index) -> &'static str {
31790            "TEXT"
31791        }
31792        fn supports_schemas(&self) -> bool {
31793            true
31794        }
31795        fn parameter_marker(&self, _ordinal: usize) -> String {
31796            "?".to_owned()
31797        }
31798        fn max_identifier_length(&self) -> Option<usize> {
31799            Some(64)
31800        }
31801        fn quote_identifier(&self, ident: &str) -> Result<String, IoError> {
31802            if ident.contains('\0') {
31803                return Err(IoError::Sql("invalid SQL identifier: NUL byte".to_owned()));
31804            }
31805            Ok(format!("`{}`", ident.replace('`', "``")))
31806        }
31807    }
31808
31809    #[derive(Default)]
31810    struct MssqlBracketConn;
31811    impl super::SqlConnection for MssqlBracketConn {
31812        fn query(&self, _q: &str, _p: &[Scalar]) -> Result<super::SqlQueryResult, IoError> {
31813            Ok(super::SqlQueryResult {
31814                columns: vec![],
31815                rows: vec![],
31816            })
31817        }
31818        fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
31819            Ok(())
31820        }
31821        fn table_exists(&self, _n: &str) -> Result<bool, IoError> {
31822            Ok(false)
31823        }
31824        fn insert_rows(&self, _s: &str, _r: &[Vec<Scalar>]) -> Result<(), IoError> {
31825            Ok(())
31826        }
31827        fn dtype_sql(&self, _d: DType) -> &'static str {
31828            "NVARCHAR(MAX)"
31829        }
31830        fn index_dtype_sql(&self, _i: &Index) -> &'static str {
31831            "NVARCHAR(MAX)"
31832        }
31833        fn supports_schemas(&self) -> bool {
31834            true
31835        }
31836        fn parameter_marker(&self, ordinal: usize) -> String {
31837            format!("@p{ordinal}")
31838        }
31839        fn max_identifier_length(&self) -> Option<usize> {
31840            Some(128)
31841        }
31842        fn quote_identifier(&self, ident: &str) -> Result<String, IoError> {
31843            if ident.contains('\0') {
31844                return Err(IoError::Sql("invalid SQL identifier: NUL byte".to_owned()));
31845            }
31846            // T-SQL bracket quoting: doubled `]` escapes a literal `]`.
31847            Ok(format!("[{}]", ident.replace(']', "]]")))
31848        }
31849    }
31850
31851    /// Reserved SQL keywords that the shape validator allows as
31852    /// alphanumeric identifiers — they must round-trip through every
31853    /// query builder safely (i.e. quoted, never bare).
31854    const FD90_12_RESERVED_WORDS: &[&str] = &[
31855        "select", "from", "where", "order", "group", "table", "index", "join",
31856    ];
31857
31858    #[test]
31859    fn fd90_12_quoting_matrix_select_all_reserved_words_quoted_per_dialect() {
31860        let ansi = AnsiSchemaConn;
31861        let mysql = MysqlBacktickConn;
31862        let mssql = MssqlBracketConn;
31863        for word in FD90_12_RESERVED_WORDS {
31864            assert_eq!(
31865                super::sql_select_all_query(&ansi, word).expect("ansi select"),
31866                format!("SELECT * FROM \"{word}\""),
31867                "ansi reserved word `{word}`"
31868            );
31869            assert_eq!(
31870                super::sql_select_all_query(&mysql, word).expect("mysql select"),
31871                format!("SELECT * FROM `{word}`"),
31872                "mysql reserved word `{word}`"
31873            );
31874            assert_eq!(
31875                super::sql_select_all_query(&mssql, word).expect("mssql select"),
31876                format!("SELECT * FROM [{word}]"),
31877                "mssql reserved word `{word}`"
31878            );
31879        }
31880    }
31881
31882    #[test]
31883    fn fd90_12_quoting_matrix_select_columns_mixed_case_preserved_per_dialect() {
31884        let ansi = AnsiSchemaConn;
31885        let mysql = MysqlBacktickConn;
31886        let mssql = MssqlBracketConn;
31887        let cases: &[&str] = &["MyCol", "MIXEDcase", "camelCase", "SCREAMING_SNAKE"];
31888        for col in cases {
31889            assert_eq!(
31890                super::sql_select_columns_query(&ansi, "users", &[col]).expect("ansi cols"),
31891                format!("SELECT \"{col}\" FROM \"users\""),
31892                "ansi mixed-case col `{col}`"
31893            );
31894            assert_eq!(
31895                super::sql_select_columns_query(&mysql, "users", &[col]).expect("mysql cols"),
31896                format!("SELECT `{col}` FROM `users`"),
31897                "mysql mixed-case col `{col}`"
31898            );
31899            assert_eq!(
31900                super::sql_select_columns_query(&mssql, "users", &[col]).expect("mssql cols"),
31901                format!("SELECT [{col}] FROM [users]"),
31902                "mssql mixed-case col `{col}`"
31903            );
31904        }
31905    }
31906
31907    #[test]
31908    fn fd90_12_quoting_matrix_leading_digit_identifiers_quoted_per_dialect() {
31909        let ansi = AnsiSchemaConn;
31910        let mysql = MysqlBacktickConn;
31911        let mssql = MssqlBracketConn;
31912        let cases: &[&str] = &["1col", "2nd_place", "9lives", "123"];
31913        for col in cases {
31914            assert_eq!(
31915                super::sql_select_columns_query(&ansi, "tbl", &[col]).expect("ansi"),
31916                format!("SELECT \"{col}\" FROM \"tbl\"")
31917            );
31918            assert_eq!(
31919                super::sql_select_columns_query(&mysql, "tbl", &[col]).expect("mysql"),
31920                format!("SELECT `{col}` FROM `tbl`")
31921            );
31922            assert_eq!(
31923                super::sql_select_columns_query(&mssql, "tbl", &[col]).expect("mssql"),
31924                format!("SELECT [{col}] FROM [tbl]")
31925            );
31926        }
31927    }
31928
31929    #[test]
31930    fn fd90_12_quoting_matrix_schema_qualified_select_per_dialect() {
31931        let ansi = AnsiSchemaConn;
31932        let mysql = MysqlBacktickConn;
31933        let mssql = MssqlBracketConn;
31934        assert_eq!(
31935            super::sql_select_all_query_in_schema(&ansi, "users", Some("analytics")).expect("ansi"),
31936            "SELECT * FROM \"analytics\".\"users\""
31937        );
31938        assert_eq!(
31939            super::sql_select_all_query_in_schema(&mysql, "users", Some("analytics"))
31940                .expect("mysql"),
31941            "SELECT * FROM `analytics`.`users`"
31942        );
31943        assert_eq!(
31944            super::sql_select_all_query_in_schema(&mssql, "users", Some("dbo")).expect("mssql"),
31945            "SELECT * FROM [dbo].[users]"
31946        );
31947    }
31948
31949    #[test]
31950    fn fd90_12_quoting_matrix_create_table_per_dialect() {
31951        let ansi = AnsiSchemaConn;
31952        let mysql = MysqlBacktickConn;
31953        let mssql = MssqlBracketConn;
31954        let cols = vec![
31955            super::sql_column_definition(&ansi, "id", "BIGINT").expect("ansi col"),
31956            super::sql_column_definition(&ansi, "select", "TEXT").expect("ansi reserved col"),
31957        ];
31958        assert_eq!(
31959            super::sql_create_table_query_in_schema(&ansi, "events", Some("public"), &cols)
31960                .expect("ansi create"),
31961            "CREATE TABLE IF NOT EXISTS \"public\".\"events\" (\"id\" BIGINT, \"select\" TEXT)"
31962        );
31963        let mysql_cols = vec![
31964            super::sql_column_definition(&mysql, "id", "BIGINT").expect("mysql col"),
31965            super::sql_column_definition(&mysql, "select", "TEXT").expect("mysql reserved col"),
31966        ];
31967        assert_eq!(
31968            super::sql_create_table_query_in_schema(
31969                &mysql,
31970                "events",
31971                Some("analytics"),
31972                &mysql_cols
31973            )
31974            .expect("mysql create"),
31975            "CREATE TABLE IF NOT EXISTS `analytics`.`events` (`id` BIGINT, `select` TEXT)"
31976        );
31977        let mssql_cols = vec![
31978            super::sql_column_definition(&mssql, "id", "BIGINT").expect("mssql col"),
31979            super::sql_column_definition(&mssql, "select", "NVARCHAR(MAX)")
31980                .expect("mssql reserved col"),
31981        ];
31982        assert_eq!(
31983            super::sql_create_table_query_in_schema(&mssql, "events", Some("dbo"), &mssql_cols)
31984                .expect("mssql create"),
31985            "CREATE TABLE IF NOT EXISTS [dbo].[events] ([id] BIGINT, [select] NVARCHAR(MAX))"
31986        );
31987    }
31988
31989    #[test]
31990    fn fd90_12_quoting_matrix_insert_per_dialect_with_param_markers() {
31991        let ansi = AnsiSchemaConn;
31992        let mysql = MysqlBacktickConn;
31993        let mssql = MssqlBracketConn;
31994        let cols = vec!["id".to_owned(), "MixedCase".to_owned(), "select".to_owned()];
31995        assert_eq!(
31996            super::sql_insert_rows_query_in_schema(&ansi, "events", Some("public"), &cols)
31997                .expect("ansi insert"),
31998            "INSERT INTO \"public\".\"events\" (\"id\", \"MixedCase\", \"select\") VALUES ($1, $2, $3)"
31999        );
32000        assert_eq!(
32001            super::sql_insert_rows_query_in_schema(&mysql, "events", Some("analytics"), &cols)
32002                .expect("mysql insert"),
32003            "INSERT INTO `analytics`.`events` (`id`, `MixedCase`, `select`) VALUES (?, ?, ?)"
32004        );
32005        assert_eq!(
32006            super::sql_insert_rows_query_in_schema(&mssql, "events", Some("dbo"), &cols)
32007                .expect("mssql insert"),
32008            "INSERT INTO [dbo].[events] ([id], [MixedCase], [select]) VALUES (@p1, @p2, @p3)"
32009        );
32010    }
32011
32012    #[test]
32013    fn fd90_12_quoting_matrix_multi_row_insert_param_ordinals_span_rows() {
32014        let ansi = AnsiSchemaConn;
32015        let mysql = MysqlBacktickConn;
32016        let cols = vec!["a".to_owned(), "b".to_owned()];
32017        assert_eq!(
32018            super::sql_multi_row_insert_query_in_schema(&ansi, "tbl", None, &cols, 2)
32019                .expect("ansi multi"),
32020            "INSERT INTO \"tbl\" (\"a\", \"b\") VALUES ($1, $2), ($3, $4)"
32021        );
32022        assert_eq!(
32023            super::sql_multi_row_insert_query_in_schema(&mysql, "tbl", None, &cols, 2)
32024                .expect("mysql multi"),
32025            "INSERT INTO `tbl` (`a`, `b`) VALUES (?, ?), (?, ?)"
32026        );
32027    }
32028
32029    #[test]
32030    fn fd90_12_quoting_matrix_drop_table_per_dialect() {
32031        let ansi = AnsiSchemaConn;
32032        let mysql = MysqlBacktickConn;
32033        let mssql = MssqlBracketConn;
32034        assert_eq!(
32035            super::sql_drop_table_query_in_schema(&ansi, "events", Some("public"))
32036                .expect("ansi drop"),
32037            "DROP TABLE IF EXISTS \"public\".\"events\""
32038        );
32039        assert_eq!(
32040            super::sql_drop_table_query_in_schema(&mysql, "events", Some("analytics"))
32041                .expect("mysql drop"),
32042            "DROP TABLE IF EXISTS `analytics`.`events`"
32043        );
32044        assert_eq!(
32045            super::sql_drop_table_query_in_schema(&mssql, "events", Some("dbo"))
32046                .expect("mssql drop"),
32047            "DROP TABLE IF EXISTS [dbo].[events]"
32048        );
32049    }
32050
32051    #[test]
32052    fn fd90_12_quoting_matrix_truncate_uses_default_delete_with_per_dialect_quoting() {
32053        // Default truncate_table impl emits `DELETE FROM <quoted>` and
32054        // routes through the backend's quote_identifier.
32055        #[derive(Default)]
32056        struct CapturingAnsi {
32057            captured: std::cell::RefCell<Vec<String>>,
32058        }
32059        impl super::SqlConnection for CapturingAnsi {
32060            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<super::SqlQueryResult, IoError> {
32061                Ok(super::SqlQueryResult {
32062                    columns: vec![],
32063                    rows: vec![],
32064                })
32065            }
32066            fn execute_batch(&self, sql: &str) -> Result<(), IoError> {
32067                self.captured.borrow_mut().push(sql.to_owned());
32068                Ok(())
32069            }
32070            fn table_exists(&self, _n: &str) -> Result<bool, IoError> {
32071                Ok(false)
32072            }
32073            fn insert_rows(&self, _s: &str, _r: &[Vec<Scalar>]) -> Result<(), IoError> {
32074                Ok(())
32075            }
32076            fn dtype_sql(&self, _d: DType) -> &'static str {
32077                "TEXT"
32078            }
32079            fn index_dtype_sql(&self, _i: &Index) -> &'static str {
32080                "TEXT"
32081            }
32082            fn supports_schemas(&self) -> bool {
32083                true
32084            }
32085        }
32086        let ansi = CapturingAnsi::default();
32087        super::SqlConnection::truncate_table(&ansi, "events", Some("public"))
32088            .expect("ansi truncate");
32089        assert_eq!(
32090            ansi.captured.borrow().as_slice(),
32091            &["DELETE FROM \"public\".\"events\"".to_owned()]
32092        );
32093
32094        #[derive(Default)]
32095        struct CapturingMysql {
32096            captured: std::cell::RefCell<Vec<String>>,
32097        }
32098        impl super::SqlConnection for CapturingMysql {
32099            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<super::SqlQueryResult, IoError> {
32100                Ok(super::SqlQueryResult {
32101                    columns: vec![],
32102                    rows: vec![],
32103                })
32104            }
32105            fn execute_batch(&self, sql: &str) -> Result<(), IoError> {
32106                self.captured.borrow_mut().push(sql.to_owned());
32107                Ok(())
32108            }
32109            fn table_exists(&self, _n: &str) -> Result<bool, IoError> {
32110                Ok(false)
32111            }
32112            fn insert_rows(&self, _s: &str, _r: &[Vec<Scalar>]) -> Result<(), IoError> {
32113                Ok(())
32114            }
32115            fn dtype_sql(&self, _d: DType) -> &'static str {
32116                "TEXT"
32117            }
32118            fn index_dtype_sql(&self, _i: &Index) -> &'static str {
32119                "TEXT"
32120            }
32121            fn supports_schemas(&self) -> bool {
32122                true
32123            }
32124            fn quote_identifier(&self, ident: &str) -> Result<String, IoError> {
32125                if ident.contains('\0') {
32126                    return Err(IoError::Sql("invalid SQL identifier: NUL byte".to_owned()));
32127                }
32128                Ok(format!("`{}`", ident.replace('`', "``")))
32129            }
32130        }
32131        let mysql = CapturingMysql::default();
32132        super::SqlConnection::truncate_table(&mysql, "events", Some("analytics"))
32133            .expect("mysql truncate");
32134        assert_eq!(
32135            mysql.captured.borrow().as_slice(),
32136            &["DELETE FROM `analytics`.`events`".to_owned()]
32137        );
32138    }
32139
32140    #[test]
32141    fn fd90_12_quoting_matrix_embedded_quote_chars_doubled_per_dialect() {
32142        // Embedded quote chars must be doubled per the dialect's escape
32143        // rule. quote_identifier is exposed for column names which may
32144        // legitimately contain embedded quotes (sql_column_definition
32145        // takes any string).
32146        let ansi = AnsiSchemaConn;
32147        let mysql = MysqlBacktickConn;
32148        let mssql = MssqlBracketConn;
32149        use super::SqlConnection as _;
32150        assert_eq!(ansi.quote_identifier("a\"b").expect("ansi"), "\"a\"\"b\"");
32151        assert_eq!(mysql.quote_identifier("a`b").expect("mysql"), "`a``b`");
32152        assert_eq!(mssql.quote_identifier("a]b").expect("mssql"), "[a]]b]");
32153        // Cross-dialect non-escape: ANSI doesn't escape backticks, etc.
32154        assert_eq!(
32155            ansi.quote_identifier("a`b")
32156                .expect("ansi backtick passthrough"),
32157            "\"a`b\""
32158        );
32159        assert_eq!(
32160            mysql
32161                .quote_identifier("a\"b")
32162                .expect("mysql quote passthrough"),
32163            "`a\"b`"
32164        );
32165        assert_eq!(
32166            mssql
32167                .quote_identifier("a\"b")
32168                .expect("mssql quote passthrough"),
32169            "[a\"b]"
32170        );
32171    }
32172
32173    #[test]
32174    fn fd90_12_quoting_matrix_long_identifier_within_cap_succeeds_over_cap_rejected() {
32175        // PG cap = 63, MySQL cap = 64, MSSQL cap = 128.
32176        use super::SqlConnection as _;
32177        let ansi = AnsiSchemaConn;
32178        let mysql = MysqlBacktickConn;
32179        let mssql = MssqlBracketConn;
32180        let pg63 = "a".repeat(63);
32181        let pg64 = "a".repeat(64);
32182        let mysql64 = "b".repeat(64);
32183        let mysql65 = "b".repeat(65);
32184        let mssql128 = "c".repeat(128);
32185        let mssql129 = "c".repeat(129);
32186
32187        super::validate_sql_identifier_length(&pg63, ansi.max_identifier_length(), "table")
32188            .expect("pg 63 ok");
32189        super::validate_sql_identifier_length(&mysql64, mysql.max_identifier_length(), "table")
32190            .expect("mysql 64 ok");
32191        super::validate_sql_identifier_length(&mssql128, mssql.max_identifier_length(), "table")
32192            .expect("mssql 128 ok");
32193
32194        let err =
32195            super::validate_sql_identifier_length(&pg64, ansi.max_identifier_length(), "table")
32196                .expect_err("pg 64 over cap");
32197        assert!(matches!(err, IoError::Sql(msg) if msg.contains("63") && msg.contains("table")));
32198        let err =
32199            super::validate_sql_identifier_length(&mysql65, mysql.max_identifier_length(), "table")
32200                .expect_err("mysql 65 over cap");
32201        assert!(matches!(err, IoError::Sql(msg) if msg.contains("64")));
32202        let err = super::validate_sql_identifier_length(
32203            &mssql129,
32204            mssql.max_identifier_length(),
32205            "table",
32206        )
32207        .expect_err("mssql 129 over cap");
32208        assert!(matches!(err, IoError::Sql(msg) if msg.contains("128")));
32209    }
32210
32211    #[test]
32212    fn fd90_12_query_builders_enforce_identifier_length_caps() {
32213        fn assert_length_error(err: IoError, kind: &str) {
32214            assert!(
32215                matches!(&err, IoError::Sql(msg)
32216                    if msg.contains(kind)
32217                        && msg.contains("63")
32218                        && msg.contains("backend identifier limit")),
32219                "expected SQL identifier-length error for {kind}, got {err:?}"
32220            );
32221        }
32222
32223        let conn = AnsiSchemaConn;
32224        let over_cap = "a".repeat(64);
32225        let cols = vec![over_cap.clone()];
32226        let defs = vec!["id BIGINT".to_owned()];
32227
32228        assert_length_error(
32229            super::sql_select_all_query_in_schema(&conn, &over_cap, None)
32230                .expect_err("SELECT * table over cap"),
32231            "table",
32232        );
32233        assert_length_error(
32234            super::sql_select_all_query_in_schema(&conn, "events", Some(&over_cap))
32235                .expect_err("SELECT * schema over cap"),
32236            "schema",
32237        );
32238        assert_length_error(
32239            super::sql_select_columns_query_in_schema(&conn, "events", None, &[over_cap.as_str()])
32240                .expect_err("SELECT column over cap"),
32241            "column",
32242        );
32243        assert_length_error(
32244            super::sql_create_table_query_in_schema(&conn, &over_cap, None, &defs)
32245                .expect_err("CREATE table over cap"),
32246            "table",
32247        );
32248        assert_length_error(
32249            super::sql_insert_rows_query_in_schema(&conn, "events", None, &cols)
32250                .expect_err("INSERT column over cap"),
32251            "column",
32252        );
32253        assert_length_error(
32254            super::sql_multi_row_insert_query_in_schema(&conn, "events", None, &cols, 1)
32255                .expect_err("multi-row INSERT column over cap"),
32256            "column",
32257        );
32258        assert_length_error(
32259            super::sql_drop_table_query_in_schema(&conn, &over_cap, None)
32260                .expect_err("DROP table over cap"),
32261            "table",
32262        );
32263        assert_length_error(
32264            super::SqlConnection::truncate_table(&conn, &over_cap, None)
32265                .expect_err("TRUNCATE fallback table over cap"),
32266            "table",
32267        );
32268    }
32269
32270    #[test]
32271    fn fd90_12_quoting_matrix_special_characters_rejected_by_validator() {
32272        // Per validate_sql_ident: only alphanumeric + underscore allowed.
32273        // Special chars (`-`, `.`, ` `, `:`, `'`, `"`, `;`) and dotted
32274        // names must be rejected before they ever reach quote_identifier.
32275        let bad: &[&str] = &[
32276            "my-col",
32277            "my.col",
32278            "my col",
32279            "my:col",
32280            "my'col",
32281            "my\"col",
32282            "my;col",
32283            "schema.table",
32284            "DROP--",
32285            "",
32286        ];
32287        for name in bad {
32288            let err =
32289                super::validate_sql_table_name(name).expect_err(&format!("must reject `{name}`"));
32290            assert!(matches!(err, IoError::Sql(msg) if msg.contains("invalid table name")));
32291            let err = super::validate_sql_column_name(name)
32292                .expect_err(&format!("must reject col `{name}`"));
32293            assert!(matches!(err, IoError::Sql(msg) if msg.contains("invalid column name")));
32294        }
32295    }
32296
32297    #[test]
32298    fn fd90_12_quoting_matrix_nul_byte_rejected_at_quote_identifier_layer() {
32299        // Defense in depth: even if a backend's quote_identifier is
32300        // called with a NUL-containing string (bypassing
32301        // validate_sql_ident), every dialect must reject — guards
32302        // against C-string driver-layer statement injection via
32303        // embedded null terminators.
32304        use super::SqlConnection as _;
32305        let ansi = AnsiSchemaConn;
32306        let mysql = MysqlBacktickConn;
32307        let mssql = MssqlBracketConn;
32308        let err_ansi = ansi
32309            .quote_identifier("ab\0cd")
32310            .expect_err("ansi must reject NUL");
32311        assert!(matches!(err_ansi, IoError::Sql(msg) if msg.contains("NUL")));
32312        let err_mysql = mysql
32313            .quote_identifier("ab\0cd")
32314            .expect_err("mysql must reject NUL");
32315        assert!(matches!(err_mysql, IoError::Sql(msg) if msg.contains("NUL")));
32316        let err_mssql = mssql
32317            .quote_identifier("ab\0cd")
32318            .expect_err("mssql must reject NUL");
32319        assert!(matches!(err_mssql, IoError::Sql(msg) if msg.contains("NUL")));
32320    }
32321
32322    #[cfg(feature = "sql-sqlite")]
32323    #[test]
32324    fn read_sql_empty_typed_table_preserves_column_dtypes_ex8ec() {
32325        let conn = make_sql_test_conn();
32326        super::SqlConnection::execute_batch(
32327            &conn,
32328            "CREATE TABLE empty_typed_ex8ec (i INTEGER, t TEXT, r REAL);",
32329        )
32330        .expect("create");
32331        // No INSERTs — empty result set.
32332
32333        let frame = read_sql(&conn, "SELECT * FROM empty_typed_ex8ec").expect("read empty");
32334        assert_eq!(frame.index().len(), 0, "empty table should yield zero rows");
32335
32336        let i_col = frame.column("i").expect("column i must exist");
32337        assert_eq!(i_col.dtype(), crate::DType::Int64);
32338        let t_col = frame.column("t").expect("column t must exist");
32339        assert_eq!(t_col.dtype(), crate::DType::Utf8);
32340        let r_col = frame.column("r").expect("column r must exist");
32341        assert_eq!(r_col.dtype(), crate::DType::Float64);
32342    }
32343
32344    #[cfg(feature = "sql-sqlite")]
32345    #[test]
32346    fn read_sql_all_null_typed_table_preserves_column_dtypes_0qo9c() {
32347        let conn = make_sql_test_conn();
32348        super::SqlConnection::execute_batch(
32349            &conn,
32350            "CREATE TABLE all_null_typed_0qo9c (i INTEGER, t TEXT, r REAL);
32351             INSERT INTO all_null_typed_0qo9c (i, t, r) VALUES (NULL, NULL, NULL);",
32352        )
32353        .expect("create and insert");
32354
32355        let frame = read_sql(&conn, "SELECT * FROM all_null_typed_0qo9c")
32356            .expect("read all-null typed table");
32357        assert_eq!(frame.index().len(), 1);
32358
32359        let i_col = frame.column("i").expect("column i must exist");
32360        assert_eq!(i_col.dtype(), crate::DType::Int64);
32361        assert!(i_col.values()[0].is_missing());
32362        let t_col = frame.column("t").expect("column t must exist");
32363        assert_eq!(t_col.dtype(), crate::DType::Utf8);
32364        assert!(t_col.values()[0].is_missing());
32365        let r_col = frame.column("r").expect("column r must exist");
32366        assert_eq!(r_col.dtype(), crate::DType::Float64);
32367        assert!(r_col.values()[0].is_missing());
32368    }
32369}
32370
32371#[cfg(test)]
32372mod fused_numeric_csv_field_tests {
32373    use super::{
32374        CsvTypedColumnValues, fuse_scan_numeric_csv_field, push_csv_default_numeric_field,
32375        push_fused_numeric_csv_field,
32376    };
32377
32378    fn assert_same_columns(base: &CsvTypedColumnValues, fused: &CsvTypedColumnValues, token: &str) {
32379        match (base, fused) {
32380            (CsvTypedColumnValues::Int64(lhs), CsvTypedColumnValues::Int64(rhs)) => {
32381                assert_eq!(lhs, rhs, "Int64 mismatch for token {token:?}");
32382            }
32383            (CsvTypedColumnValues::Float64(lhs), CsvTypedColumnValues::Float64(rhs)) => {
32384                let lhs_bits: Vec<u64> = lhs.iter().map(|value| value.to_bits()).collect();
32385                let rhs_bits: Vec<u64> = rhs.iter().map(|value| value.to_bits()).collect();
32386                assert_eq!(
32387                    lhs_bits, rhs_bits,
32388                    "Float64 bit mismatch for token {token:?}"
32389                );
32390            }
32391            _ => panic!("column dtype diverged for token {token:?}"),
32392        }
32393    }
32394
32395    /// Every token the fused scanner admits must produce bit-identical column
32396    /// state to the `push_csv_default_numeric_field` fallback, for both a
32397    /// fresh Int64 column and a Float64 column, under every terminator.
32398    #[test]
32399    fn fused_field_matches_fallback_parser() {
32400        let tokens = [
32401            "0",
32402            "-0",
32403            "+7",
32404            "007",
32405            "5",
32406            "-5",
32407            "123456789",
32408            "999999999999999999",
32409            "-999999999999999999",
32410            "9007199254740993",
32411            "1234567890123456789",
32412            "0.1",
32413            "-0.1",
32414            "+0.5",
32415            ".5",
32416            "-.5",
32417            "00.5",
32418            "5.",
32419            "12.34",
32420            "123456.7",
32421            "0.30000000000000004",
32422            "9007199254740993.0",
32423            "1e5",
32424            "1E5",
32425            "1.5e-3",
32426            "inf",
32427            "-inf",
32428            "nan",
32429            "NaN",
32430            "",
32431            " 5",
32432            "5 ",
32433            "true",
32434            "false",
32435            "TRUE",
32436            "1.2.3",
32437            "--5",
32438            "+-5",
32439            "1-2",
32440            "#N/A",
32441            "NULL",
32442            "abc",
32443        ];
32444
32445        for token in tokens {
32446            for suffix in ["", ",", "\n", ",9\n"] {
32447                let data = format!("{token}{suffix}");
32448                let Some(field) = fuse_scan_numeric_csv_field(data.as_bytes(), 0) else {
32449                    // Rejected tokens take the unchanged fallback route;
32450                    // nothing further to prove.
32451                    continue;
32452                };
32453                assert_eq!(
32454                    field.end,
32455                    token.len(),
32456                    "fused scanner must stop at the delimiter for token {token:?}"
32457                );
32458
32459                // The fallback must accept every token the fused scanner
32460                // admits (the fused grammar is a strict subset).
32461                let mut base_int = CsvTypedColumnValues::Int64(Vec::new());
32462                assert!(
32463                    push_csv_default_numeric_field(&mut base_int, token.as_bytes()),
32464                    "fallback rejected fused-admitted token {token:?}"
32465                );
32466                let mut fused_int = CsvTypedColumnValues::Int64(Vec::new());
32467                push_fused_numeric_csv_field(&mut fused_int, &field);
32468                assert_same_columns(&base_int, &fused_int, token);
32469
32470                let mut base_float = CsvTypedColumnValues::Float64(Vec::new());
32471                assert!(
32472                    push_csv_default_numeric_field(&mut base_float, token.as_bytes()),
32473                    "fallback Float64 rejected fused-admitted token {token:?}"
32474                );
32475                let mut fused_float = CsvTypedColumnValues::Float64(Vec::new());
32476                push_fused_numeric_csv_field(&mut fused_float, &field);
32477                assert_same_columns(&base_float, &fused_float, token);
32478            }
32479        }
32480    }
32481
32482    /// The sign of zero must survive the fused route on Float64 columns:
32483    /// `-0` parses to -0.0 via `parse_f64_csv_number`, and the fused field
32484    /// must carry the same bits.
32485    #[test]
32486    fn fused_field_preserves_negative_zero_bits() {
32487        let field = fuse_scan_numeric_csv_field(b"-0,", 0).expect("fused scanner must admit -0");
32488        assert_eq!(field.int_value, Some(0));
32489        assert_eq!(field.float_value.to_bits(), (-0.0f64).to_bits());
32490
32491        let mut float_column = CsvTypedColumnValues::Float64(Vec::new());
32492        push_fused_numeric_csv_field(&mut float_column, &field);
32493        match float_column {
32494            CsvTypedColumnValues::Float64(values) => {
32495                assert_eq!(values.len(), 1);
32496                assert_eq!(values[0].to_bits(), (-0.0f64).to_bits());
32497            }
32498            CsvTypedColumnValues::Int64(_) => panic!("expected Float64 column"),
32499        }
32500    }
32501}
32502
32503#[cfg(test)]
32504mod merge_simple_numeric_csv_chunks_tests {
32505    use super::{CsvTypedColumnValues, merge_simple_numeric_csv_chunks};
32506
32507    /// Verbatim copy of the pre-parallel chunk-major merge, kept as the
32508    /// reference implementation for the differential test below.
32509    fn reference_merge(
32510        parsed_chunks: Vec<(Vec<CsvTypedColumnValues>, i64)>,
32511        header_count: usize,
32512    ) -> Option<(Vec<CsvTypedColumnValues>, i64)> {
32513        let mut final_is_float = vec![false; header_count];
32514        let mut row_count = 0i64;
32515        for (columns, rows) in &parsed_chunks {
32516            if columns.len() != header_count {
32517                return None;
32518            }
32519            row_count = row_count.checked_add(*rows)?;
32520            for (idx, column) in columns.iter().enumerate() {
32521                final_is_float[idx] |= matches!(column, CsvTypedColumnValues::Float64(_));
32522            }
32523        }
32524
32525        let capacity = usize::try_from(row_count).ok()?;
32526        let mut merged: Vec<CsvTypedColumnValues> = final_is_float
32527            .into_iter()
32528            .map(|is_float| {
32529                if is_float {
32530                    CsvTypedColumnValues::Float64(Vec::with_capacity(capacity))
32531                } else {
32532                    CsvTypedColumnValues::Int64(Vec::with_capacity(capacity))
32533                }
32534            })
32535            .collect();
32536
32537        for (columns, _) in parsed_chunks {
32538            for (dst, src) in merged.iter_mut().zip(columns) {
32539                match (dst, src) {
32540                    (CsvTypedColumnValues::Int64(dst), CsvTypedColumnValues::Int64(src)) => {
32541                        dst.extend(src);
32542                    }
32543                    (CsvTypedColumnValues::Float64(dst), CsvTypedColumnValues::Int64(src)) => {
32544                        dst.extend(src.into_iter().map(|value| value as f64));
32545                    }
32546                    (CsvTypedColumnValues::Float64(dst), CsvTypedColumnValues::Float64(src)) => {
32547                        dst.extend(src);
32548                    }
32549                    (CsvTypedColumnValues::Int64(_), CsvTypedColumnValues::Float64(_)) => {
32550                        return None;
32551                    }
32552                }
32553            }
32554        }
32555
32556        Some((merged, row_count))
32557    }
32558
32559    fn build_chunks(
32560        chunk_count: usize,
32561        rows_per_chunk: usize,
32562        header_count: usize,
32563        float_from_chunk_for_col: impl Fn(usize) -> usize,
32564    ) -> Vec<(Vec<CsvTypedColumnValues>, i64)> {
32565        (0..chunk_count)
32566            .map(|chunk| {
32567                let columns = (0..header_count)
32568                    .map(|col| {
32569                        if chunk >= float_from_chunk_for_col(col) {
32570                            CsvTypedColumnValues::Float64(
32571                                (0..rows_per_chunk)
32572                                    .map(|row| {
32573                                        (chunk * rows_per_chunk + row) as f64 * 0.5
32574                                            + col as f64 * 1000.0
32575                                    })
32576                                    .collect(),
32577                            )
32578                        } else {
32579                            CsvTypedColumnValues::Int64(
32580                                (0..rows_per_chunk)
32581                                    .map(|row| {
32582                                        (chunk * rows_per_chunk + row) as i64 + col as i64 * 1000
32583                                    })
32584                                    .collect(),
32585                            )
32586                        }
32587                    })
32588                    .collect();
32589                (columns, rows_per_chunk as i64)
32590            })
32591            .collect()
32592    }
32593
32594    fn assert_merge_matches_reference(
32595        chunks: Vec<(Vec<CsvTypedColumnValues>, i64)>,
32596        header_count: usize,
32597    ) {
32598        let reference_chunks: Vec<(Vec<CsvTypedColumnValues>, i64)> = chunks
32599            .iter()
32600            .map(|(columns, rows)| {
32601                let cloned = columns
32602                    .iter()
32603                    .map(|column| match column {
32604                        CsvTypedColumnValues::Int64(values) => {
32605                            CsvTypedColumnValues::Int64(values.clone())
32606                        }
32607                        CsvTypedColumnValues::Float64(values) => {
32608                            CsvTypedColumnValues::Float64(values.clone())
32609                        }
32610                    })
32611                    .collect();
32612                (cloned, *rows)
32613            })
32614            .collect();
32615
32616        let expected = reference_merge(reference_chunks, header_count);
32617        let actual = merge_simple_numeric_csv_chunks(chunks, header_count);
32618
32619        match (expected, actual) {
32620            (None, None) => {}
32621            (Some((expected_columns, expected_rows)), Some((actual_columns, actual_rows))) => {
32622                assert_eq!(expected_rows, actual_rows);
32623                assert_eq!(expected_columns.len(), actual_columns.len());
32624                for (idx, (lhs, rhs)) in expected_columns
32625                    .iter()
32626                    .zip(actual_columns.iter())
32627                    .enumerate()
32628                {
32629                    match (lhs, rhs) {
32630                        (CsvTypedColumnValues::Int64(lhs), CsvTypedColumnValues::Int64(rhs)) => {
32631                            assert_eq!(lhs, rhs, "Int64 column {idx} diverged");
32632                        }
32633                        (
32634                            CsvTypedColumnValues::Float64(lhs),
32635                            CsvTypedColumnValues::Float64(rhs),
32636                        ) => {
32637                            let lhs_bits: Vec<u64> =
32638                                lhs.iter().map(|value| value.to_bits()).collect();
32639                            let rhs_bits: Vec<u64> =
32640                                rhs.iter().map(|value| value.to_bits()).collect();
32641                            assert_eq!(lhs_bits, rhs_bits, "Float64 column {idx} bits diverged");
32642                        }
32643                        _ => panic!("column {idx} dtype diverged"),
32644                    }
32645                }
32646            }
32647            (expected, actual) => panic!(
32648                "merge outcome diverged: reference some={} actual some={}",
32649                expected.is_some(),
32650                actual.is_some()
32651            ),
32652        }
32653    }
32654
32655    /// Big merge (crosses the parallel threshold): mixed promotion patterns —
32656    /// some columns all-Int64, some all-Float64, some promoting mid-stream —
32657    /// must match the chunk-major reference bit-for-bit, in column order.
32658    #[test]
32659    fn parallel_merge_matches_reference_with_mixed_promotion() {
32660        // 8 chunks x 1000 rows x 12 columns = 96000 values > 65536 threshold.
32661        let chunks = build_chunks(8, 1000, 12, |col| match col % 4 {
32662            0 => usize::MAX, // never float: stays Int64
32663            1 => 0,          // float from the first chunk
32664            2 => 3,          // promotes mid-stream
32665            _ => 7,          // promotes at the last chunk
32666        });
32667        assert_merge_matches_reference(chunks, 12);
32668    }
32669
32670    /// Small merge (below the parallel threshold) takes the sequential path
32671    /// and must also match.
32672    #[test]
32673    fn sequential_merge_matches_reference() {
32674        let chunks = build_chunks(3, 4, 5, |col| if col % 2 == 0 { usize::MAX } else { 1 });
32675        assert_merge_matches_reference(chunks, 5);
32676    }
32677
32678    /// More worker groups than columns (header_count < MAX_WORKERS) and
32679    /// header_count not divisible by the group size must keep column order.
32680    #[test]
32681    fn parallel_merge_handles_narrow_and_ragged_widths() {
32682        for header_count in [2, 3, 7, 9, 17] {
32683            let chunks = build_chunks(5, 2000, header_count, |col| col % 6);
32684            assert_merge_matches_reference(chunks, header_count);
32685        }
32686    }
32687
32688    /// A chunk whose column count disagrees with the header must reject, as
32689    /// before.
32690    #[test]
32691    fn merge_rejects_mismatched_chunk_width() {
32692        let mut chunks = build_chunks(2, 10, 4, |_| usize::MAX);
32693        chunks[1].0.pop();
32694        assert!(merge_simple_numeric_csv_chunks(chunks, 4).is_none());
32695    }
32696
32697    /// The typed streaming `to_json(records)` fast path must be byte-for-byte
32698    /// identical to the serde-tree reference across numeric edge values, key
32699    /// escaping, and the fall-back surface. (br-frankenpandas-jsonrec)
32700    #[test]
32701    fn to_json_records_typed_fast_path_bit_identical_to_serde() {
32702        use std::collections::BTreeMap;
32703
32704        use fp_columnar::Column;
32705        use fp_frame::DataFrame;
32706        use fp_index::Index;
32707        use fp_types::Scalar;
32708
32709        use super::{JsonOrient, write_json_string};
32710        fn serde_ref(frame: &DataFrame) -> String {
32711            let headers: Vec<String> = frame.column_names().into_iter().cloned().collect();
32712            let promotions = vec![false; headers.len()];
32713            super::write_json_records_serde(frame, &headers, &promotions).expect("serde ref")
32714        }
32715        // JSONL serde reference: a Map per row serialized independently, joined
32716        // by '\n' (exactly the pre-fast-path `write_jsonl_string` body).
32717        fn jsonl_serde_ref(frame: &DataFrame) -> String {
32718            let headers: Vec<String> = frame.column_names().into_iter().cloned().collect();
32719            let row_count = frame.index().len();
32720            let mut lines = Vec::with_capacity(row_count);
32721            for row_idx in 0..row_count {
32722                let mut obj = serde_json::Map::new();
32723                for name in &headers {
32724                    let val = frame
32725                        .column(name)
32726                        .and_then(|c| c.value(row_idx))
32727                        .map(|v| super::scalar_to_json_with_column_promotion(v, false))
32728                        .unwrap_or(serde_json::Value::Null);
32729                    obj.insert(name.clone(), val);
32730                }
32731                lines.push(serde_json::to_string(&serde_json::Value::Object(obj)).unwrap());
32732            }
32733            lines.join("\n")
32734        }
32735        fn assert_jsonl_matches(frame: &DataFrame) {
32736            assert_eq!(
32737                super::write_jsonl_string(frame).expect("jsonl"),
32738                jsonl_serde_ref(frame)
32739            );
32740        }
32741        // Columns orient: compare the typed fast path's end-to-end output to the
32742        // serde-tree output captured by temporarily... there is no separate serde
32743        // entry point, so compare against a from-scratch serde Map-of-Maps ref.
32744        fn columns_serde_ref(frame: &DataFrame) -> String {
32745            let headers: Vec<String> = frame.column_names().into_iter().cloned().collect();
32746            let mut outer = serde_json::Map::new();
32747            for name in &headers {
32748                let mut col_obj = serde_json::Map::new();
32749                if let Some(col) = frame.column(name.as_str()) {
32750                    for (label, val) in frame.index().labels().iter().zip(col.values()) {
32751                        col_obj.insert(
32752                            super::index_label_json_key(label),
32753                            super::scalar_to_json_with_column_promotion(val, false),
32754                        );
32755                    }
32756                }
32757                outer.insert(name.clone(), serde_json::Value::Object(col_obj));
32758            }
32759            serde_json::to_string(&serde_json::Value::Object(outer)).unwrap()
32760        }
32761        fn assert_columns_matches(frame: &DataFrame) {
32762            assert_eq!(
32763                write_json_string(frame, JsonOrient::Columns).expect("cols"),
32764                columns_serde_ref(frame),
32765            );
32766        }
32767        // Index orient: from-scratch serde Map-of-row-Maps reference.
32768        fn index_serde_ref(frame: &DataFrame) -> String {
32769            let headers: Vec<String> = frame.column_names().into_iter().cloned().collect();
32770            let mut outer = serde_json::Map::new();
32771            for row_idx in 0..frame.index().len() {
32772                let mut row_obj = serde_json::Map::new();
32773                for name in &headers {
32774                    let val = frame
32775                        .column(name.as_str())
32776                        .and_then(|c| c.value(row_idx))
32777                        .map(|v| super::scalar_to_json_with_column_promotion(v, false))
32778                        .unwrap_or(serde_json::Value::Null);
32779                    row_obj.insert(name.clone(), val);
32780                }
32781                let key = super::index_label_json_key(&frame.index().labels()[row_idx]);
32782                outer.insert(key, serde_json::Value::Object(row_obj));
32783            }
32784            serde_json::to_string(&serde_json::Value::Object(outer)).unwrap()
32785        }
32786        fn assert_index_matches(frame: &DataFrame) {
32787            assert_eq!(
32788                write_json_string(frame, JsonOrient::Index).expect("index"),
32789                index_serde_ref(frame),
32790            );
32791        }
32792        // Values orient: from-scratch serde array-of-arrays reference.
32793        fn values_serde_ref(frame: &DataFrame) -> String {
32794            let headers: Vec<String> = frame.column_names().into_iter().cloned().collect();
32795            let mut data = Vec::with_capacity(frame.index().len());
32796            for row_idx in 0..frame.index().len() {
32797                let row: Vec<serde_json::Value> = headers
32798                    .iter()
32799                    .map(|name| {
32800                        frame
32801                            .column(name.as_str())
32802                            .and_then(|c| c.value(row_idx))
32803                            .map(|v| super::scalar_to_json_with_column_promotion(v, false))
32804                            .unwrap_or(serde_json::Value::Null)
32805                    })
32806                    .collect();
32807                data.push(serde_json::Value::Array(row));
32808            }
32809            serde_json::to_string(&serde_json::Value::Array(data)).unwrap()
32810        }
32811        fn assert_values_matches(frame: &DataFrame) {
32812            assert_eq!(
32813                write_json_string(frame, JsonOrient::Values).expect("values"),
32814                values_serde_ref(frame),
32815            );
32816        }
32817        // Split orient: from-scratch serde {columns, index, data} reference.
32818        fn split_serde_ref(frame: &DataFrame) -> String {
32819            let headers: Vec<String> = frame.column_names().into_iter().cloned().collect();
32820            let col_array: Vec<serde_json::Value> = headers
32821                .iter()
32822                .map(|h| serde_json::Value::String(h.clone()))
32823                .collect();
32824            let index_array: Vec<serde_json::Value> = frame
32825                .index()
32826                .labels()
32827                .iter()
32828                .map(super::index_label_to_json)
32829                .collect();
32830            let mut data = Vec::with_capacity(frame.index().len());
32831            for row_idx in 0..frame.index().len() {
32832                let row: Vec<serde_json::Value> = headers
32833                    .iter()
32834                    .map(|name| {
32835                        frame
32836                            .column(name.as_str())
32837                            .and_then(|c| c.value(row_idx))
32838                            .map(|v| super::scalar_to_json_with_column_promotion(v, false))
32839                            .unwrap_or(serde_json::Value::Null)
32840                    })
32841                    .collect();
32842                data.push(serde_json::Value::Array(row));
32843            }
32844            let mut obj = serde_json::Map::new();
32845            obj.insert("columns".into(), serde_json::Value::Array(col_array));
32846            obj.insert("index".into(), serde_json::Value::Array(index_array));
32847            obj.insert("data".into(), serde_json::Value::Array(data));
32848            serde_json::to_string(&serde_json::Value::Object(obj)).unwrap()
32849        }
32850        fn assert_split_matches(frame: &DataFrame) {
32851            assert_eq!(
32852                write_json_string(frame, JsonOrient::Split).expect("split"),
32853                split_serde_ref(frame),
32854            );
32855        }
32856        fn idx(n: usize) -> Index {
32857            Index::new_known_unique_int64_unit_range(0, n)
32858        }
32859
32860        // Edge-laden Int64 + Float64 + Bool frame; the floats span integer-valued,
32861        // signed-zero, sub-1e-4 (ryu exponent), huge, tiny, and ±Inf (which the
32862        // typed path emits as `null`, matching serde's NaN/Inf arm).
32863        let ints = vec![
32864            0i64,
32865            -1,
32866            1,
32867            i64::MIN,
32868            i64::MAX,
32869            -123456789,
32870            999,
32871            -7,
32872            42,
32873            1_000_000_000,
32874        ];
32875        let floats = vec![
32876            0.0,
32877            -0.0,
32878            0.5,
32879            100.0,
32880            -100.0,
32881            1e20,
32882            1e-20,
32883            1.5e-300,
32884            f64::MAX,
32885            f64::INFINITY,
32886        ];
32887        let bools = vec![
32888            true, false, true, true, false, false, true, false, true, false,
32889        ];
32890        let n = ints.len();
32891        let mut cols: BTreeMap<String, Column> = BTreeMap::new();
32892        cols.insert("a".to_string(), Column::from_i64_values(ints));
32893        cols.insert("b".to_string(), Column::from_f64_values(floats));
32894        cols.insert("c".to_string(), Column::from_bool_values(bools));
32895        // Datetime64 column (epoch-ms ints in JSON), incl. a NaT (→ null) and a
32896        // pre-epoch negative ns (truncating /1_000_000 toward zero, matching serde).
32897        let dts = vec![
32898            0i64,
32899            946_684_800_000_000_000,
32900            i64::MIN, // NaT
32901            -1_500_000_000,
32902            1_000,
32903            1_500_000,
32904            -86_400_000_000_000,
32905            999_999,
32906            123_456_789,
32907            -999_999,
32908        ];
32909        cols.insert("dt".to_string(), Column::from_datetime64_values(dts));
32910        // A column name that requires JSON escaping, to exercise pre-serialized keys.
32911        cols.insert(
32912            "we\"ird\tkey".to_string(),
32913            Column::from_i64_values((0..n as i64).collect()),
32914        );
32915        let frame = DataFrame::new(idx(n), cols).expect("frame");
32916        // Fast path must actually fire here (all-valid numeric/bool).
32917        assert!(super::try_write_json_records_typed(&frame, false).is_some());
32918        assert!(super::try_write_json_records_typed(&frame, true).is_some());
32919        assert!(super::try_write_json_columns_typed(&frame).is_some());
32920        assert!(super::try_write_json_index_typed(&frame).is_some());
32921        assert!(super::try_write_json_values_typed(&frame).is_some());
32922        assert!(super::try_write_json_split_typed(&frame).is_some());
32923        assert_eq!(
32924            write_json_string(&frame, JsonOrient::Records).expect("json"),
32925            serde_ref(&frame),
32926        );
32927        assert_jsonl_matches(&frame);
32928        assert_columns_matches(&frame);
32929        assert_index_matches(&frame);
32930        assert_values_matches(&frame);
32931        assert_split_matches(&frame);
32932
32933        // -Inf in isolation.
32934        let mut c2: BTreeMap<String, Column> = BTreeMap::new();
32935        c2.insert(
32936            "x".to_string(),
32937            Column::from_f64_values(vec![f64::NEG_INFINITY, -2.5, 3.0]),
32938        );
32939        let f2 = DataFrame::new(idx(3), c2).expect("frame2");
32940        assert_eq!(
32941            write_json_string(&f2, JsonOrient::Records).expect("json2"),
32942            serde_ref(&f2),
32943        );
32944        assert_jsonl_matches(&f2);
32945        assert_columns_matches(&f2);
32946        assert_index_matches(&f2);
32947        assert_values_matches(&f2);
32948        assert_split_matches(&f2);
32949
32950        // Empty frame (0 rows) and a single-column int frame.
32951        let mut c3: BTreeMap<String, Column> = BTreeMap::new();
32952        c3.insert("only".to_string(), Column::from_i64_values(vec![]));
32953        let f3 = DataFrame::new(idx(0), c3).expect("frame3");
32954        assert_eq!(
32955            write_json_string(&f3, JsonOrient::Records).expect("json3"),
32956            serde_ref(&f3),
32957        );
32958        assert_jsonl_matches(&f3);
32959        assert_columns_matches(&f3);
32960        assert_index_matches(&f3);
32961        assert_values_matches(&f3);
32962        assert_split_matches(&f3);
32963
32964        // A Utf8 column forces the serde fallback; equality must still hold
32965        // (trivially, since the fast path declines).
32966        let mut c4: BTreeMap<String, Column> = BTreeMap::new();
32967        c4.insert("n".to_string(), Column::from_i64_values(vec![1, 2]));
32968        c4.insert(
32969            "s".to_string(),
32970            Column::from_values(vec![Scalar::Utf8("hi".into()), Scalar::Utf8("x".into())])
32971                .expect("utf8 col"),
32972        );
32973        let f4 = DataFrame::new(idx(2), c4).expect("frame4");
32974        assert!(super::try_write_json_records_typed(&f4, false).is_none());
32975        assert_eq!(
32976            write_json_string(&f4, JsonOrient::Records).expect("json4"),
32977            serde_ref(&f4),
32978        );
32979        assert_jsonl_matches(&f4);
32980        assert_columns_matches(&f4);
32981        assert_index_matches(&f4);
32982        assert_values_matches(&f4);
32983        assert_split_matches(&f4);
32984
32985        // Contiguous Utf8 column (the read-path backing the typed Utf8 arm
32986        // accepts), with strings spanning the no-escape fast path and every
32987        // serde escape case: quote, backslash, control bytes, and multi-byte
32988        // UTF-8 (which serde passes through verbatim).
32989        let strs = [
32990            "plain",
32991            "a\"b",
32992            "c\\d",
32993            "e\nf",
32994            "g\th",
32995            "i\u{0001}j",
32996            "café",
32997            "🦀x",
32998            "",
32999            "trailing ",
33000        ];
33001        let mut sbytes: Vec<u8> = Vec::new();
33002        let mut soff: Vec<usize> = vec![0];
33003        for s in strs {
33004            sbytes.extend_from_slice(s.as_bytes());
33005            soff.push(sbytes.len());
33006        }
33007        let mut c5: BTreeMap<String, Column> = BTreeMap::new();
33008        c5.insert(
33009            "n".to_string(),
33010            Column::from_i64_values((0..strs.len() as i64).collect()),
33011        );
33012        c5.insert("s".to_string(), Column::from_utf8_contiguous(sbytes, soff));
33013        let f5 = DataFrame::new(idx(strs.len()), c5).expect("frame5");
33014        assert!(super::try_write_json_records_typed(&f5, false).is_some());
33015        assert_eq!(
33016            write_json_string(&f5, JsonOrient::Records).expect("json5"),
33017            serde_ref(&f5),
33018        );
33019        assert_jsonl_matches(&f5);
33020        assert_columns_matches(&f5);
33021        assert_index_matches(&f5);
33022        assert_values_matches(&f5);
33023        assert_split_matches(&f5);
33024
33025        // Pseudo-random sweep (LCG, no external rng) over Int64/Float64 values.
33026        let mut state: u64 = 0x9E3779B97F4A7C15;
33027        let mut next = || {
33028            state = state
33029                .wrapping_mul(6364136223846793005)
33030                .wrapping_add(1442695040888963407);
33031            state
33032        };
33033        let m = 2000usize;
33034        let mut ri = Vec::with_capacity(m);
33035        let mut rf = Vec::with_capacity(m);
33036        for _ in 0..m {
33037            ri.push(next() as i64);
33038            // Mix of magnitudes including integer-valued and tiny.
33039            let bits = next();
33040            let f = f64::from_bits(bits);
33041            rf.push(if f.is_nan() {
33042                (next() % 1000) as f64 * 0.25
33043            } else {
33044                f
33045            });
33046        }
33047        let mut rc: BTreeMap<String, Column> = BTreeMap::new();
33048        rc.insert("ri".to_string(), Column::from_i64_values(ri));
33049        rc.insert("rf".to_string(), Column::from_f64_values(rf));
33050        let rframe = DataFrame::new(idx(m), rc).expect("rframe");
33051        assert_eq!(
33052            write_json_string(&rframe, JsonOrient::Records).expect("rjson"),
33053            serde_ref(&rframe),
33054        );
33055        assert_jsonl_matches(&rframe);
33056        assert_columns_matches(&rframe);
33057        assert_index_matches(&rframe);
33058        assert_values_matches(&rframe);
33059        assert_split_matches(&rframe);
33060    }
33061}