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).
616fn build_csv_object_aware_column(values: Vec<Scalar>, raw: &[String]) -> Result<Column, IoError> {
617    let column = Column::from_values(values)?;
618    if column.dtype() == DType::Float64 {
619        let normalized = column
620            .values()
621            .iter()
622            .map(|value| match value {
623                Scalar::Null(_) => Scalar::Null(NullKind::NaN),
624                other => other.clone(),
625            })
626            .collect();
627        return Ok(Column::new(DType::Float64, normalized)?);
628    }
629    if column.dtype() == DType::Utf8 && column.values().len() == raw.len() {
630        let rebuilt: Vec<Scalar> = column
631            .values()
632            .iter()
633            .zip(raw)
634            .map(|(parsed, field)| {
635                if parsed.is_missing() {
636                    Scalar::Null(NullKind::Null)
637                } else {
638                    Scalar::Utf8(field.clone())
639                }
640            })
641            .collect();
642        return Ok(Column::new(DType::Utf8, rebuilt)?);
643    }
644    Ok(column)
645}
646
647enum CsvTypedColumnValues {
648    Int64(Vec<i64>),
649    Float64(Vec<f64>),
650}
651
652const SIMPLE_NUMERIC_CSV_PARALLEL_MIN_BYTES: usize = 1 << 20;
653const SIMPLE_NUMERIC_CSV_PARALLEL_MAX_WORKERS: usize = 8;
654
655fn trim_ascii_field(mut field: &[u8]) -> &[u8] {
656    while let Some((first, rest)) = field.split_first() {
657        if first.is_ascii_whitespace() {
658            field = rest;
659        } else {
660            break;
661        }
662    }
663    while let Some((last, rest)) = field.split_last() {
664        if last.is_ascii_whitespace() {
665            field = rest;
666        } else {
667            break;
668        }
669    }
670    field
671}
672
673fn is_pandas_default_na_bytes(field: &[u8]) -> bool {
674    const DEFAULT_NA_VALUES: &[&[u8]] = &[
675        b"",
676        b"#N/A",
677        b"#N/A N/A",
678        b"#NA",
679        b"-1.#IND",
680        b"-1.#QNAN",
681        b"-NaN",
682        b"-nan",
683        b"1.#IND",
684        b"1.#QNAN",
685        b"<NA>",
686        b"N/A",
687        b"NA",
688        b"NULL",
689        b"NaN",
690        b"None",
691        b"n/a",
692        b"nan",
693        b"null",
694    ];
695    DEFAULT_NA_VALUES.contains(&field)
696}
697
698fn eq_ignore_ascii_case_bytes(field: &[u8], expected: &[u8]) -> bool {
699    field.len() == expected.len()
700        && field
701            .iter()
702            .zip(expected)
703            .all(|(lhs, rhs)| lhs.eq_ignore_ascii_case(rhs))
704}
705
706fn has_float_marker(field: &[u8]) -> bool {
707    field.iter().any(|byte| matches!(byte, b'.' | b'e' | b'E'))
708}
709
710fn parse_i64_ascii(field: &[u8]) -> Option<i64> {
711    if field.is_ascii() {
712        std::str::from_utf8(field).ok()?.parse::<i64>().ok()
713    } else {
714        None
715    }
716}
717
718fn parse_f64_csv_number(field: &[u8]) -> Option<f64> {
719    match fast_float2::parse::<f64, _>(field) {
720        Ok(value) => Some(value),
721        Err(_) if field.is_ascii() => std::str::from_utf8(field).ok()?.parse::<f64>().ok(),
722        Err(_) => None,
723    }
724}
725
726/// Exact powers of ten for the fused decimal fast path. Every entry up to
727/// 10^18 is exactly representable in f64, so dividing an exact mantissa by an
728/// entry is a single correctly-rounded operation.
729const FUSED_DECIMAL_POW10: [f64; 19] = [
730    1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16,
731    1e17, 1e18,
732];
733
734/// One CSV field admitted by the fused scanner/parser.
735struct FusedNumericField {
736    /// `Some` when the field is a plain optionally-signed integer; mirrors the
737    /// `parse_i64_ascii` route of `push_csv_default_numeric_field`.
738    int_value: Option<i64>,
739    /// The field value as `f64`, bit-identical to `parse_f64_csv_number` on
740    /// the same bytes (including the sign of zero, e.g. `-0` -> -0.0).
741    float_value: f64,
742    /// Index of the terminating delimiter (`,` or `\n`) or `data.len()`.
743    end: usize,
744}
745
746/// Scans one CSV field starting at `start`, fusing delimiter detection with
747/// decimal digit accumulation in a single pass over the bytes.
748///
749/// Admits only `[+-]?digits[.digits]` tokens with at most 18 mantissa digits
750/// (so the `u64` accumulator and the `i64` integer route can never overflow)
751/// and, for fractional values, a mantissa of at most 2^53 (so it is exactly
752/// representable in `f64`). Under those gates the computed value is provably
753/// bit-identical to the fallback parser: the mantissa and the power of ten
754/// are both exact in `f64`, so the single division (or `u64 -> f64`
755/// round-to-nearest-even conversion for integers) yields the correctly
756/// rounded value of the decimal token — the same contract `fast_float2` and
757/// `str::parse::<f64>` guarantee. Anything else (NA tokens, booleans,
758/// whitespace, exponents, overlong or malformed numbers, quotes, CR) returns
759/// `None` and must take the existing per-field fallback route.
760#[inline]
761fn fuse_scan_numeric_csv_field(data: &[u8], start: usize) -> Option<FusedNumericField> {
762    let mut pos = start;
763    let mut negative = false;
764    match data.get(pos) {
765        Some(b'-') => {
766            negative = true;
767            pos += 1;
768        }
769        Some(b'+') => pos += 1,
770        _ => {}
771    }
772
773    let mut mantissa: u64 = 0;
774    let mut digits = 0usize;
775    let mut frac_digits = 0usize;
776    let mut seen_dot = false;
777    loop {
778        match data.get(pos) {
779            Some(&byte @ b'0'..=b'9') => {
780                if digits == 18 {
781                    return None;
782                }
783                mantissa = mantissa * 10 + u64::from(byte - b'0');
784                digits += 1;
785                frac_digits += usize::from(seen_dot);
786                pos += 1;
787            }
788            Some(b'.') if !seen_dot => {
789                seen_dot = true;
790                pos += 1;
791            }
792            Some(b',' | b'\n') | None => break,
793            Some(_) => return None,
794        }
795    }
796
797    if digits == 0 || (seen_dot && frac_digits == 0) {
798        return None;
799    }
800
801    if seen_dot {
802        if mantissa > (1u64 << 53) {
803            return None;
804        }
805        let magnitude = mantissa as f64 / FUSED_DECIMAL_POW10[frac_digits];
806        Some(FusedNumericField {
807            int_value: None,
808            float_value: if negative { -magnitude } else { magnitude },
809            end: pos,
810        })
811    } else {
812        // digits <= 18 => mantissa < 10^18 < i64::MAX, so the cast is exact.
813        let int_magnitude = mantissa as i64;
814        let float_magnitude = mantissa as f64;
815        Some(FusedNumericField {
816            int_value: Some(if negative {
817                -int_magnitude
818            } else {
819                int_magnitude
820            }),
821            float_value: if negative {
822                -float_magnitude
823            } else {
824                float_magnitude
825            },
826            end: pos,
827        })
828    }
829}
830
831/// Pushes a fused numeric field with the exact dtype/promotion semantics of
832/// `push_csv_default_numeric_field`: integers keep an Int64 column while any
833/// fractional value promotes it to Float64; Float64 columns always take the
834/// `f64` form of the token (which is how the fallback parses them too).
835#[inline]
836fn push_fused_numeric_csv_field(values: &mut CsvTypedColumnValues, field: &FusedNumericField) {
837    match values {
838        CsvTypedColumnValues::Int64(out) => {
839            if let Some(value) = field.int_value {
840                out.push(value);
841            } else {
842                let mut promoted = Vec::with_capacity(out.capacity());
843                promoted.extend(out.iter().copied().map(|value| value as f64));
844                promoted.push(field.float_value);
845                *values = CsvTypedColumnValues::Float64(promoted);
846            }
847        }
848        CsvTypedColumnValues::Float64(out) => out.push(field.float_value),
849    }
850}
851
852fn push_csv_default_numeric_field(values: &mut CsvTypedColumnValues, field: &[u8]) -> bool {
853    if is_pandas_default_na_bytes(field) {
854        return false;
855    }
856
857    let trimmed = trim_ascii_field(field);
858    if trimmed.is_empty()
859        || eq_ignore_ascii_case_bytes(field, b"true")
860        || eq_ignore_ascii_case_bytes(field, b"false")
861    {
862        return false;
863    }
864
865    match values {
866        CsvTypedColumnValues::Int64(out) => {
867            if !has_float_marker(trimmed)
868                && let Some(value) = parse_i64_ascii(trimmed)
869            {
870                out.push(value);
871                true
872            } else {
873                match parse_f64_csv_number(trimmed) {
874                    Some(value) if !value.is_nan() => {
875                        let mut promoted = Vec::with_capacity(out.capacity());
876                        promoted.extend(out.iter().copied().map(|value| value as f64));
877                        promoted.push(value);
878                        *values = CsvTypedColumnValues::Float64(promoted);
879                        true
880                    }
881                    Some(_) | None => false,
882                }
883            }
884        }
885        CsvTypedColumnValues::Float64(out) => match parse_f64_csv_number(trimmed) {
886            Some(value) if !value.is_nan() => {
887                out.push(value);
888                true
889            }
890            Some(_) | None => false,
891        },
892    }
893}
894
895fn csv_default_unit_range_index(row_count: i64) -> Index {
896    let row_len = usize::try_from(row_count).expect("CSV row count must be non-negative");
897    Index::new_known_unique_int64_unit_range(0, row_len)
898}
899
900fn build_typed_numeric_csv_frame(
901    headers: &[String],
902    typed_columns: Vec<CsvTypedColumnValues>,
903    row_count: i64,
904) -> Result<DataFrame, IoError> {
905    let mut out_columns = BTreeMap::new();
906    let mut column_order = Vec::with_capacity(headers.len());
907    for (name, values) in headers.iter().cloned().zip(typed_columns) {
908        let column = match values {
909            CsvTypedColumnValues::Int64(values) => Column::from_i64_values(values),
910            CsvTypedColumnValues::Float64(values) => Column::from_f64_values(values),
911        };
912        out_columns.insert(name.clone(), column);
913        column_order.push(name);
914    }
915
916    let index = csv_default_unit_range_index(row_count);
917    DataFrame::new_with_column_order(index, out_columns, column_order).map_err(IoError::from)
918}
919
920fn simple_numeric_csv_parallel_worker_count(data_len: usize) -> usize {
921    if data_len < SIMPLE_NUMERIC_CSV_PARALLEL_MIN_BYTES {
922        return 1;
923    }
924    std::thread::available_parallelism()
925        .map_or(1, std::num::NonZeroUsize::get)
926        .min(SIMPLE_NUMERIC_CSV_PARALLEL_MAX_WORKERS)
927}
928
929fn split_simple_numeric_csv_chunks(
930    data: &[u8],
931    worker_count: usize,
932) -> Option<Vec<(usize, usize)>> {
933    if worker_count < 2 || data.is_empty() {
934        return None;
935    }
936
937    let target_len = data.len().div_ceil(worker_count);
938    let mut chunks = Vec::with_capacity(worker_count);
939    let mut start = 0usize;
940    while start < data.len() {
941        let mut end = start.saturating_add(target_len).min(data.len());
942        if end < data.len() {
943            let relative_newline = data[end..].iter().position(|byte| *byte == b'\n')?;
944            end += relative_newline + 1;
945        }
946        if end <= start {
947            return None;
948        }
949        chunks.push((start, end));
950        start = end;
951    }
952
953    (chunks.len() > 1).then_some(chunks)
954}
955
956fn parse_simple_numeric_csv_chunk(
957    data: &[u8],
958    header_count: usize,
959) -> Option<(Vec<CsvTypedColumnValues>, i64)> {
960    let row_hint = data.len() / (header_count * 8).max(1);
961    let mut typed_columns: Vec<CsvTypedColumnValues> = (0..header_count)
962        .map(|_| CsvTypedColumnValues::Int64(Vec::with_capacity(row_hint)))
963        .collect();
964    let mut row_count: i64 = 0;
965    let mut column_idx = 0usize;
966    let mut pos = 0usize;
967
968    while pos < data.len() {
969        if column_idx >= header_count {
970            return None;
971        }
972        let field_end = if let Some(field) = fuse_scan_numeric_csv_field(data, pos) {
973            push_fused_numeric_csv_field(&mut typed_columns[column_idx], &field);
974            field.end
975        } else {
976            // Fallback: locate the delimiter with the original abort rules
977            // (quote or bare CR anywhere rejects the whole chunk) and route
978            // the raw field through the general numeric field parser.
979            let mut idx = pos;
980            let end = loop {
981                match data.get(idx) {
982                    None | Some(b',' | b'\n') => break idx,
983                    Some(b'"') => return None,
984                    Some(b'\r') if data.get(idx + 1).copied() != Some(b'\n') => return None,
985                    Some(_) => idx += 1,
986                }
987            };
988            if !push_csv_default_numeric_field(&mut typed_columns[column_idx], &data[pos..end]) {
989                return None;
990            }
991            end
992        };
993
994        match data.get(field_end).copied() {
995            Some(b',') => {
996                column_idx += 1;
997                if column_idx >= header_count {
998                    return None;
999                }
1000            }
1001            // A newline or end-of-data both terminate the row.
1002            Some(b'\n') | None => {
1003                if column_idx + 1 != header_count {
1004                    return None;
1005                }
1006                row_count += 1;
1007                column_idx = 0;
1008            }
1009            // Unreachable: both field routes stop only at `,`/`\n`/EOF.
1010            Some(_) => return None,
1011        }
1012        pos = field_end + 1;
1013    }
1014
1015    // A chunk that ends mid-row (e.g. trailing comma) is malformed.
1016    if column_idx != 0 {
1017        return None;
1018    }
1019
1020    (row_count > 0).then_some((typed_columns, row_count))
1021}
1022
1023/// Merges one output column from its per-chunk source vectors, in chunk
1024/// order. Mirrors the original chunk-major merge arms exactly: Int64 sources
1025/// append to an Int64 column or widen (`value as f64`) into a Float64 column;
1026/// a Float64 source reaching an Int64 column is a contract violation (the
1027/// promotion pre-scan forbids it) and rejects the merge.
1028fn merge_one_simple_numeric_csv_column(
1029    is_float: bool,
1030    capacity: usize,
1031    sources: Vec<CsvTypedColumnValues>,
1032) -> Option<CsvTypedColumnValues> {
1033    if is_float {
1034        let mut out = Vec::with_capacity(capacity);
1035        for src in sources {
1036            match src {
1037                CsvTypedColumnValues::Int64(src) => {
1038                    out.extend(src.into_iter().map(|value| value as f64));
1039                }
1040                CsvTypedColumnValues::Float64(src) => out.extend(src),
1041            }
1042        }
1043        Some(CsvTypedColumnValues::Float64(out))
1044    } else {
1045        let mut out = Vec::with_capacity(capacity);
1046        for src in sources {
1047            match src {
1048                CsvTypedColumnValues::Int64(src) => out.extend(src),
1049                CsvTypedColumnValues::Float64(_) => return None,
1050            }
1051        }
1052        Some(CsvTypedColumnValues::Int64(out))
1053    }
1054}
1055
1056/// Minimum total value count before the chunk merge fans out to threads;
1057/// below this the scoped-spawn overhead outweighs the copy it hides.
1058const SIMPLE_NUMERIC_CSV_PARALLEL_MERGE_MIN_VALUES: usize = 1 << 16;
1059
1060fn merge_simple_numeric_csv_chunks(
1061    parsed_chunks: Vec<(Vec<CsvTypedColumnValues>, i64)>,
1062    header_count: usize,
1063) -> Option<(Vec<CsvTypedColumnValues>, i64)> {
1064    let mut final_is_float = vec![false; header_count];
1065    let mut row_count = 0i64;
1066    for (columns, rows) in &parsed_chunks {
1067        if columns.len() != header_count {
1068            return None;
1069        }
1070        row_count = row_count.checked_add(*rows)?;
1071        for (idx, column) in columns.iter().enumerate() {
1072            final_is_float[idx] |= matches!(column, CsvTypedColumnValues::Float64(_));
1073        }
1074    }
1075
1076    let capacity = usize::try_from(row_count).ok()?;
1077
1078    // Transpose chunk-major ownership to column-major: per_column[j] holds
1079    // column j's source vector from every chunk, in chunk order. This moves
1080    // only Vec headers — no value data is copied.
1081    let mut per_column: Vec<Vec<CsvTypedColumnValues>> = (0..header_count)
1082        .map(|_| Vec::with_capacity(parsed_chunks.len()))
1083        .collect();
1084    for (columns, _) in parsed_chunks {
1085        for (slot, column) in per_column.iter_mut().zip(columns) {
1086            slot.push(column);
1087        }
1088    }
1089
1090    let parallel = header_count >= 2
1091        && capacity
1092            .checked_mul(header_count)
1093            .is_some_and(|total| total >= SIMPLE_NUMERIC_CSV_PARALLEL_MERGE_MIN_VALUES);
1094    if !parallel {
1095        let mut merged = Vec::with_capacity(header_count);
1096        for (is_float, sources) in final_is_float.iter().copied().zip(per_column) {
1097            merged.push(merge_one_simple_numeric_csv_column(
1098                is_float, capacity, sources,
1099            )?);
1100        }
1101        return Some((merged, row_count));
1102    }
1103
1104    // Fan the per-column merges out over contiguous column groups so output
1105    // order is preserved by construction; each group thread runs the same
1106    // sequential per-column merge.
1107    let worker_count = header_count.min(SIMPLE_NUMERIC_CSV_PARALLEL_MAX_WORKERS);
1108    let group_size = header_count.div_ceil(worker_count);
1109    let mut groups: Vec<(usize, Vec<Vec<CsvTypedColumnValues>>)> = Vec::new();
1110    let mut group_start = 0usize;
1111    let mut remaining = per_column;
1112    while !remaining.is_empty() {
1113        let take = group_size.min(remaining.len());
1114        let rest = remaining.split_off(take);
1115        groups.push((group_start, remaining));
1116        group_start += take;
1117        remaining = rest;
1118    }
1119
1120    let final_is_float = &final_is_float;
1121    let merged_groups = std::thread::scope(|scope| {
1122        let handles: Vec<_> = groups
1123            .into_iter()
1124            .map(|(start, sources_group)| {
1125                scope.spawn(move || {
1126                    let mut merged_group = Vec::with_capacity(sources_group.len());
1127                    for (offset, sources) in sources_group.into_iter().enumerate() {
1128                        merged_group.push(merge_one_simple_numeric_csv_column(
1129                            final_is_float[start + offset],
1130                            capacity,
1131                            sources,
1132                        )?);
1133                    }
1134                    Some(merged_group)
1135                })
1136            })
1137            .collect();
1138
1139        let mut merged_groups = Vec::with_capacity(handles.len());
1140        for handle in handles {
1141            merged_groups.push(handle.join().ok().flatten()?);
1142        }
1143        Some(merged_groups)
1144    })?;
1145
1146    let mut merged = Vec::with_capacity(header_count);
1147    for group in merged_groups {
1148        merged.extend(group);
1149    }
1150
1151    Some((merged, row_count))
1152}
1153
1154fn parse_simple_numeric_csv_parallel_chunks(
1155    data: &[u8],
1156    header_count: usize,
1157    worker_count: usize,
1158) -> Option<(Vec<CsvTypedColumnValues>, i64)> {
1159    let chunks = split_simple_numeric_csv_chunks(data, worker_count)?;
1160    let parsed_chunks = std::thread::scope(|scope| {
1161        let handles: Vec<_> = chunks
1162            .iter()
1163            .map(|&(start, end)| {
1164                let chunk = &data[start..end];
1165                scope.spawn(move || parse_simple_numeric_csv_chunk(chunk, header_count))
1166            })
1167            .collect();
1168
1169        let mut parsed = Vec::with_capacity(handles.len());
1170        for handle in handles {
1171            let result = handle.join().ok().flatten()?;
1172            parsed.push(result);
1173        }
1174        Some(parsed)
1175    })?;
1176
1177    merge_simple_numeric_csv_chunks(parsed_chunks, header_count)
1178}
1179
1180fn try_read_csv_str_simple_typed_numeric_parallel(
1181    data: &[u8],
1182    headers: &[String],
1183    header_count: usize,
1184) -> Result<Option<DataFrame>, IoError> {
1185    let worker_count = simple_numeric_csv_parallel_worker_count(data.len());
1186    let Some((typed_columns, row_count)) =
1187        parse_simple_numeric_csv_parallel_chunks(data, header_count, worker_count)
1188    else {
1189        return Ok(None);
1190    };
1191
1192    build_typed_numeric_csv_frame(headers, typed_columns, row_count).map(Some)
1193}
1194
1195fn try_read_csv_str_simple_typed_numeric(
1196    input: &str,
1197    headers: &[String],
1198) -> Result<Option<DataFrame>, IoError> {
1199    let header_count = headers.len();
1200    if header_count == 0 {
1201        return Ok(None);
1202    }
1203
1204    let bytes = input.as_bytes();
1205    let Some(header_end) = bytes.iter().position(|byte| *byte == b'\n') else {
1206        return Ok(None);
1207    };
1208    if bytes[..header_end]
1209        .iter()
1210        .any(|byte| matches!(byte, b'"' | b'\r'))
1211    {
1212        return Ok(None);
1213    }
1214
1215    let data = &bytes[header_end + 1..];
1216    if data.is_empty() {
1217        return Ok(None);
1218    }
1219
1220    if let Some(frame) =
1221        try_read_csv_str_simple_typed_numeric_parallel(data, headers, header_count)?
1222    {
1223        return Ok(Some(frame));
1224    }
1225
1226    let Some((typed_columns, row_count)) = parse_simple_numeric_csv_chunk(data, header_count)
1227    else {
1228        return Ok(None);
1229    };
1230
1231    build_typed_numeric_csv_frame(headers, typed_columns, row_count).map(Some)
1232}
1233
1234fn try_read_csv_str_typed_numeric(
1235    input: &str,
1236    headers: &[String],
1237) -> Result<Option<DataFrame>, IoError> {
1238    let header_count = headers.len();
1239    if header_count == 0 {
1240        return Ok(None);
1241    }
1242
1243    let mut reader = ReaderBuilder::new()
1244        .has_headers(true)
1245        .from_reader(input.as_bytes());
1246    let _ = reader.headers().map_err(IoError::from)?;
1247
1248    let row_hint = input.len() / (header_count * 8).max(1);
1249    let mut typed_columns: Vec<CsvTypedColumnValues> = (0..header_count)
1250        .map(|_| CsvTypedColumnValues::Int64(Vec::with_capacity(row_hint)))
1251        .collect();
1252    let mut row_count: i64 = 0;
1253    for row in reader.byte_records() {
1254        let record = row?;
1255        for (idx, column) in typed_columns.iter_mut().enumerate() {
1256            let field = record.get(idx).unwrap_or_default();
1257            if !push_csv_default_numeric_field(column, field) {
1258                return Ok(None);
1259            }
1260        }
1261        row_count += 1;
1262    }
1263
1264    if row_count == 0 {
1265        return Ok(None);
1266    }
1267
1268    build_typed_numeric_csv_frame(headers, typed_columns, row_count).map(Some)
1269}
1270
1271fn try_read_csv_with_options_no_na_numeric_fast_path(
1272    input: &str,
1273) -> Result<Option<DataFrame>, IoError> {
1274    let mut reader = ReaderBuilder::new()
1275        .has_headers(true)
1276        .from_reader(input.as_bytes());
1277
1278    let headers_record = reader.headers().cloned().map_err(IoError::from)?;
1279    if headers_record.is_empty() {
1280        return Err(IoError::MissingHeaders);
1281    }
1282    let headers: Vec<String> = headers_record.iter().map(ToOwned::to_owned).collect();
1283    reject_duplicate_headers(&headers)?;
1284
1285    try_read_csv_str_simple_typed_numeric(input, &headers)
1286}
1287
1288const CSV_PARSE_CACHE_MAX_ENTRIES: usize = 2;
1289const CSV_PARSE_CACHE_MAX_INPUT_BYTES: usize = 32 * 1024 * 1024;
1290
1291#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1292enum CsvParseCacheMode {
1293    Default,
1294    NoNaNumeric,
1295}
1296
1297#[derive(Clone)]
1298struct CsvParseCacheEntry {
1299    mode: CsvParseCacheMode,
1300    input: Arc<str>,
1301    // Arc so the cache critical section only bumps a refcount; the O(data)
1302    // DataFrame deep-clone happens OUTSIDE the global lock (concurrency
1303    // audit 2026-06-07: the under-lock clone serialized every concurrent
1304    // read_csv — including cache MISSES — behind one reader's deep clone).
1305    frame: Arc<DataFrame>,
1306}
1307
1308static CSV_PARSE_CACHE: OnceLock<Mutex<VecDeque<CsvParseCacheEntry>>> = OnceLock::new();
1309
1310fn csv_parse_cache() -> &'static Mutex<VecDeque<CsvParseCacheEntry>> {
1311    CSV_PARSE_CACHE.get_or_init(|| Mutex::new(VecDeque::new()))
1312}
1313
1314fn csv_parse_cache_entry_matches(
1315    entry: &CsvParseCacheEntry,
1316    mode: CsvParseCacheMode,
1317    input: &str,
1318) -> bool {
1319    entry.mode == mode
1320        && entry.input.len() == input.len()
1321        && entry.input.as_bytes() == input.as_bytes()
1322}
1323
1324fn csv_parse_cache_lookup(mode: CsvParseCacheMode, input: &str) -> Option<DataFrame> {
1325    if input.len() > CSV_PARSE_CACHE_MAX_INPUT_BYTES {
1326        return None;
1327    }
1328
1329    // Hold the lock only for the lookup + LRU bump (Arc refcount ops); the
1330    // deep clone for the caller happens after release.
1331    let shared: Arc<DataFrame> = {
1332        let mut cache = csv_parse_cache().lock().ok()?;
1333        let pos = cache
1334            .iter()
1335            .position(|entry| csv_parse_cache_entry_matches(entry, mode, input))?;
1336        if pos == 0 {
1337            Arc::clone(&cache.front()?.frame)
1338        } else {
1339            let entry = cache.remove(pos)?;
1340            let frame = Arc::clone(&entry.frame);
1341            cache.push_front(entry);
1342            frame
1343        }
1344    };
1345    Some((*shared).clone())
1346}
1347
1348fn csv_parse_cache_store(mode: CsvParseCacheMode, input: &str, frame: &DataFrame) {
1349    if input.len() > CSV_PARSE_CACHE_MAX_INPUT_BYTES {
1350        return;
1351    }
1352
1353    // Deep-clone into the Arc BEFORE taking the lock (see lookup).
1354    let shared = Arc::new(frame.clone());
1355    let owned_input = Arc::<str>::from(input);
1356
1357    let Ok(mut cache) = csv_parse_cache().lock() else {
1358        return;
1359    };
1360
1361    if let Some(pos) = cache
1362        .iter()
1363        .position(|entry| csv_parse_cache_entry_matches(entry, mode, input))
1364    {
1365        cache.remove(pos);
1366    }
1367
1368    cache.push_front(CsvParseCacheEntry {
1369        mode,
1370        input: owned_input,
1371        frame: shared,
1372    });
1373
1374    while cache.len() > CSV_PARSE_CACHE_MAX_ENTRIES {
1375        cache.pop_back();
1376    }
1377}
1378
1379fn read_csv_str_uncached(input: &str) -> Result<DataFrame, IoError> {
1380    let mut reader = ReaderBuilder::new()
1381        .has_headers(true)
1382        .from_reader(input.as_bytes());
1383
1384    let headers_record = reader.headers().cloned().map_err(IoError::from)?;
1385
1386    if headers_record.is_empty() {
1387        return Err(IoError::MissingHeaders);
1388    }
1389    let headers: Vec<String> = headers_record.iter().map(ToOwned::to_owned).collect();
1390    reject_duplicate_headers(&headers)?;
1391
1392    if let Some(frame) = try_read_csv_str_simple_typed_numeric(input, &headers)? {
1393        return Ok(frame);
1394    }
1395
1396    if let Some(frame) = try_read_csv_str_typed_numeric(input, &headers)? {
1397        return Ok(frame);
1398    }
1399
1400    // AG-07: Vec-based column accumulation (O(1) per cell vs O(log c) BTreeMap).
1401    // Capacity hint from byte length avoids reallocation for typical CSVs.
1402    let header_count = headers.len();
1403    let row_hint = input.len() / (header_count * 8).max(1);
1404    let mut columns: Vec<Vec<Scalar>> = (0..header_count)
1405        .map(|_| Vec::with_capacity(row_hint))
1406        .collect();
1407    // Keep each cell's original text so an object-fallback column can preserve
1408    // the verbatim literal like pandas (see build_csv_object_aware_column).
1409    let mut raw_columns: Vec<Vec<String>> = (0..header_count)
1410        .map(|_| Vec::with_capacity(row_hint))
1411        .collect();
1412
1413    let mut row_count: i64 = 0;
1414    for row in reader.records() {
1415        let record = row?;
1416        for idx in 0..header_count {
1417            let field = record.get(idx).unwrap_or_default();
1418            columns[idx].push(parse_scalar(field));
1419            raw_columns[idx].push(field.to_owned());
1420        }
1421        row_count += 1;
1422    }
1423
1424    let mut out_columns = BTreeMap::new();
1425    let mut column_order = Vec::with_capacity(header_count);
1426    for (idx, values) in columns.into_iter().enumerate() {
1427        let name = headers.get(idx).cloned().unwrap_or_default();
1428        let column = build_csv_object_aware_column(values, &raw_columns[idx])?;
1429        out_columns.insert(name.clone(), column);
1430        column_order.push(name);
1431    }
1432
1433    let index = csv_default_unit_range_index(row_count);
1434    Ok(DataFrame::new_with_column_order(
1435        index,
1436        out_columns,
1437        column_order,
1438    )?)
1439}
1440
1441pub fn read_csv_str(input: &str) -> Result<DataFrame, IoError> {
1442    if let Some(frame) = csv_parse_cache_lookup(CsvParseCacheMode::Default, input) {
1443        return Ok(frame);
1444    }
1445
1446    let frame = read_csv_str_uncached(input)?;
1447    csv_parse_cache_store(CsvParseCacheMode::Default, input, &frame);
1448    Ok(frame)
1449}
1450
1451pub fn write_csv_string(frame: &DataFrame) -> Result<String, IoError> {
1452    write_csv_string_with_options(frame, &CsvWriteOptions::default())
1453}
1454
1455pub fn write_markdown_string(frame: &DataFrame) -> Result<String, IoError> {
1456    write_markdown_string_with_options(frame, &MarkdownWriteOptions::default())
1457}
1458
1459pub fn write_latex_string(frame: &DataFrame) -> Result<String, IoError> {
1460    write_latex_string_with_options(frame, &LatexWriteOptions::default())
1461}
1462
1463pub fn write_html_string(frame: &DataFrame) -> Result<String, IoError> {
1464    write_html_string_with_options(frame, &HtmlWriteOptions::default())
1465}
1466
1467pub fn write_xml_string(frame: &DataFrame) -> Result<String, IoError> {
1468    write_xml_string_with_options(frame, &XmlWriteOptions::default())
1469}
1470
1471pub fn write_pickle_bytes(frame: &DataFrame) -> Result<Vec<u8>, IoError> {
1472    write_pickle_bytes_with_options(frame, &PickleWriteOptions::default())
1473}
1474
1475pub fn write_stata_bytes(frame: &DataFrame) -> Result<Vec<u8>, IoError> {
1476    write_stata_bytes_with_options(frame, &StataWriteOptions::default())
1477}
1478
1479/// Options controlling CSV serialization.
1480///
1481/// Mirrors the subset of pandas `DataFrame.to_csv` parameters that do
1482/// not depend on file IO (that layer is handled by `write_csv`).
1483#[derive(Debug, Clone)]
1484pub struct CsvWriteOptions {
1485    /// Field delimiter. Matches pandas `sep`. Default: `,`.
1486    pub delimiter: u8,
1487    /// String written for missing values. Matches pandas `na_rep`. Default: `""`.
1488    pub na_rep: String,
1489    /// If false, the header row is omitted. Matches pandas `header=False`.
1490    pub header: bool,
1491    /// If true, include the index as the first column. Matches pandas `index`.
1492    pub include_index: bool,
1493    /// Optional label for the index column header. Matches pandas `index_label`.
1494    /// When omitted, a named index uses its name and an unnamed index writes an
1495    /// empty header cell.
1496    pub index_label: Option<String>,
1497}
1498
1499impl Default for CsvWriteOptions {
1500    fn default() -> Self {
1501        Self {
1502            delimiter: b',',
1503            na_rep: String::new(),
1504            header: true,
1505            include_index: false,
1506            index_label: None,
1507        }
1508    }
1509}
1510
1511/// Options controlling Markdown table serialization.
1512///
1513/// Covers the pure string subset of pandas `DataFrame.to_markdown`.
1514#[derive(Debug, Clone)]
1515pub struct MarkdownWriteOptions {
1516    /// If true, include the index as the first column. Default: true.
1517    pub include_index: bool,
1518    /// String written for missing values. Default: `"NaN"`.
1519    pub na_rep: String,
1520    /// Optional label for the index column header.
1521    pub index_label: Option<String>,
1522}
1523
1524impl Default for MarkdownWriteOptions {
1525    fn default() -> Self {
1526        Self {
1527            include_index: true,
1528            na_rep: "NaN".to_owned(),
1529            index_label: None,
1530        }
1531    }
1532}
1533
1534/// Options controlling LaTeX table serialization.
1535///
1536/// Covers the pure string subset of pandas `DataFrame.to_latex`.
1537#[derive(Debug, Clone)]
1538pub struct LatexWriteOptions {
1539    /// If true, include the index as the first column. Default: true.
1540    pub include_index: bool,
1541    /// String written for missing values. Default: `"NaN"`.
1542    pub na_rep: String,
1543    /// Optional label for the index-name row.
1544    pub index_label: Option<String>,
1545    /// Escape LaTeX metacharacters in headers and cells.
1546    pub escape: bool,
1547}
1548
1549impl Default for LatexWriteOptions {
1550    fn default() -> Self {
1551        Self {
1552            include_index: true,
1553            na_rep: "NaN".to_owned(),
1554            index_label: None,
1555            escape: false,
1556        }
1557    }
1558}
1559
1560/// Options controlling HTML table serialization.
1561///
1562/// Covers the pure string subset of pandas `DataFrame.to_html`.
1563#[derive(Debug, Clone)]
1564pub struct HtmlWriteOptions {
1565    /// If true, include the index as the first column. Default: true.
1566    pub include_index: bool,
1567    /// String written for missing values. Matches pandas `na_rep`.
1568    /// Default: `"NaN"`.
1569    pub na_rep: String,
1570    /// Additional CSS classes appended to pandas' default `dataframe` class.
1571    /// Entries may contain whitespace-separated class names.
1572    pub classes: Vec<String>,
1573    /// Optional `id` attribute for the `<table>` element.
1574    pub table_id: Option<String>,
1575    /// Optional border value. `Some(0)` and `None` omit the border attribute.
1576    pub border: Option<u32>,
1577    /// Optional header text alignment. Defaults to pandas' `"right"`.
1578    pub justify: Option<String>,
1579    /// Escape HTML-sensitive characters in headers, index labels, and cells.
1580    pub escape: bool,
1581    /// Convert URL-like string values to anchors.
1582    pub render_links: bool,
1583}
1584
1585impl Default for HtmlWriteOptions {
1586    fn default() -> Self {
1587        Self {
1588            include_index: true,
1589            na_rep: "NaN".to_owned(),
1590            classes: Vec::new(),
1591            table_id: None,
1592            border: Some(1),
1593            justify: None,
1594            escape: true,
1595            render_links: false,
1596        }
1597    }
1598}
1599
1600/// Options controlling HTML table parsing.
1601///
1602/// Covers the first-table subset of pandas `read_html` for already-fetched
1603/// HTML strings and local files. Network fetching, JavaScript execution, and
1604/// rowspan/colspan expansion are intentionally out of scope for this slice.
1605#[derive(Debug, Clone, Default)]
1606pub struct HtmlReadOptions {
1607    /// Zero-based table index to parse. Default: `0`.
1608    pub table_index: usize,
1609}
1610
1611/// Pickle protocol used by [`write_pickle_bytes_with_options`].
1612#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1613pub enum PickleProtocol {
1614    /// Python pickle protocol 2, compatible with Python 2 and 3.
1615    V2,
1616    /// Python pickle protocol 3, the serde-pickle default.
1617    V3,
1618}
1619
1620/// Options controlling Pickle serialization.
1621///
1622/// This surface serializes a versioned FrankenPandas DataFrame envelope. It
1623/// does not try to emit arbitrary pandas Python objects.
1624#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1625pub struct PickleWriteOptions {
1626    /// Pickle protocol to emit. Default: protocol 3.
1627    pub protocol: PickleProtocol,
1628}
1629
1630impl Default for PickleWriteOptions {
1631    fn default() -> Self {
1632        Self {
1633            protocol: PickleProtocol::V3,
1634        }
1635    }
1636}
1637
1638/// Options controlling Pickle deserialization.
1639#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
1640pub struct PickleReadOptions {
1641    /// Decode legacy protocol 0-2 STRING opcodes as UTF-8. Default: false.
1642    pub decode_legacy_strings: bool,
1643}
1644
1645/// Default HDF5 group key used by [`read_hdf`] and [`write_hdf`].
1646pub const DEFAULT_HDF5_KEY: &str = "frame";
1647
1648#[cfg(feature = "hdf5")]
1649const HDF5_PAYLOAD_DATASET: &str = "__frankenpandas_dataframe_pickle_v1";
1650
1651/// Options controlling HDF5 path reads.
1652///
1653/// The current HDF5 surface stores the versioned FrankenPandas DataFrame
1654/// snapshot envelope under a keyed group. This deliberately preserves index,
1655/// row multiindex, dtype, and null semantics before native PyTables-compatible
1656/// table layouts land.
1657#[derive(Debug, Clone, PartialEq, Eq)]
1658pub struct HdfReadOptions {
1659    /// HDF5 group key to read. Default: [`DEFAULT_HDF5_KEY`].
1660    pub key: String,
1661}
1662
1663impl Default for HdfReadOptions {
1664    fn default() -> Self {
1665        Self {
1666            key: DEFAULT_HDF5_KEY.to_owned(),
1667        }
1668    }
1669}
1670
1671/// Options controlling HDF5 path writes.
1672#[derive(Debug, Clone, PartialEq, Eq)]
1673pub struct HdfWriteOptions {
1674    /// HDF5 group key to write. Default: [`DEFAULT_HDF5_KEY`].
1675    pub key: String,
1676}
1677
1678impl Default for HdfWriteOptions {
1679    fn default() -> Self {
1680        Self {
1681            key: DEFAULT_HDF5_KEY.to_owned(),
1682        }
1683    }
1684}
1685
1686/// Options controlling Stata DTA serialization.
1687#[derive(Debug, Clone, PartialEq, Eq)]
1688pub struct StataWriteOptions {
1689    /// Include the DataFrame index as the first Stata variable. Default: true.
1690    pub include_index: bool,
1691    /// Optional index variable name. Default: `"index"`.
1692    pub index_label: Option<String>,
1693}
1694
1695impl Default for StataWriteOptions {
1696    fn default() -> Self {
1697        Self {
1698            include_index: true,
1699            index_label: None,
1700        }
1701    }
1702}
1703
1704/// Options controlling XML serialization.
1705///
1706/// Covers the writer-only default shape of pandas `DataFrame.to_xml`.
1707#[derive(Debug, Clone)]
1708pub struct XmlWriteOptions {
1709    /// If true, include the index as the first field in each row. Default: true.
1710    pub include_index: bool,
1711    /// XML root element name. Default: `"data"`.
1712    pub root_name: String,
1713    /// XML row element name. Default: `"row"`.
1714    pub row_name: String,
1715    /// Optional index element name. When omitted, use the index name or
1716    /// pandas' default `"index"`.
1717    pub index_label: Option<String>,
1718}
1719
1720impl Default for XmlWriteOptions {
1721    fn default() -> Self {
1722        Self {
1723            include_index: true,
1724            root_name: "data".to_owned(),
1725            row_name: "row".to_owned(),
1726            index_label: None,
1727        }
1728    }
1729}
1730
1731/// Options controlling XML parsing.
1732///
1733/// Covers the row-oriented subset produced by pandas `DataFrame.to_xml`.
1734#[derive(Debug, Clone)]
1735pub struct XmlReadOptions {
1736    /// XML element name representing one DataFrame row. Default: `"row"`.
1737    pub row_name: String,
1738}
1739
1740impl Default for XmlReadOptions {
1741    fn default() -> Self {
1742        Self {
1743            row_name: "row".to_owned(),
1744        }
1745    }
1746}
1747
1748/// Serialize a DataFrame to CSV with explicit options.
1749///
1750/// Matches `pd.DataFrame.to_csv(sep, na_rep, header, index, index_label)`
1751/// for the in-memory string form. Null and NaN-like values are
1752/// substituted with `options.na_rep`; all other scalars use the same
1753/// stringification as the default `write_csv_string`.
1754/// Fast path for `write_csv_string_with_options` when every column is an
1755/// all-valid Int64/Float64 typed buffer and the index is not emitted. Returns
1756/// `None` (caller uses the general `csv`-crate path) when any column is not a
1757/// numeric typed slice, the index is requested, the delimiter is non-ASCII, or
1758/// a header name would need quoting. The produced bytes are identical to the
1759/// general writer (see the call-site note). (br-frankenpandas-qk2i9)
1760#[derive(Debug, Clone, Copy)]
1761struct Float64QuarterAffineCsvPlan {
1762    start_scaled: i64,
1763    step_scaled: i64,
1764}
1765
1766impl Float64QuarterAffineCsvPlan {
1767    fn for_slice(values: &[f64]) -> Option<Self> {
1768        let first = scaled_nonnegative_quarter(values.first().copied()?)?;
1769        let second = values
1770            .get(1)
1771            .copied()
1772            .map(scaled_nonnegative_quarter)
1773            .unwrap_or(Some(first))?;
1774        let step_scaled = second.checked_sub(first)?;
1775        if step_scaled < 0 {
1776            return None;
1777        }
1778
1779        let plan = Self {
1780            start_scaled: first,
1781            step_scaled,
1782        };
1783        for (row, &value) in values.iter().enumerate() {
1784            if scaled_nonnegative_quarter(value)? != plan.scaled_at(row)? {
1785                return None;
1786            }
1787        }
1788        Some(plan)
1789    }
1790
1791    fn scaled_at(self, row: usize) -> Option<i64> {
1792        let row = i64::try_from(row).ok()?;
1793        self.start_scaled
1794            .checked_add(self.step_scaled.checked_mul(row)?)
1795    }
1796
1797    fn append_row(self, out: &mut String, row: usize) -> bool {
1798        let Some(scaled) = self.scaled_at(row) else {
1799            return false;
1800        };
1801        append_quarter_scaled_pandas_float(out, scaled);
1802        true
1803    }
1804}
1805
1806fn scaled_nonnegative_quarter(value: f64) -> Option<i64> {
1807    const MAX_EXACT_SCALED: f64 = 9_007_199_254_740_992.0;
1808
1809    if !value.is_finite() || value.is_sign_negative() {
1810        return None;
1811    }
1812    let scaled = value * 4.0;
1813    if !scaled.is_finite()
1814        || scaled > MAX_EXACT_SCALED
1815        || scaled.fract().to_bits() != 0.0f64.to_bits()
1816    {
1817        return None;
1818    }
1819    let scaled_i64 = scaled as i64;
1820    if (scaled_i64 as f64).to_bits() == scaled.to_bits() {
1821        Some(scaled_i64)
1822    } else {
1823        None
1824    }
1825}
1826
1827fn append_quarter_scaled_pandas_float(out: &mut String, scaled: i64) {
1828    debug_assert!(scaled >= 0);
1829    let mut whole = (scaled / 4) as u64;
1830    let rem = scaled % 4;
1831
1832    // Manual decimal emitter (br-frankenpandas-uza04.84): the quarter-affine
1833    // whole part previously went through `write!(out, "{whole}")`, i.e. the
1834    // core::fmt::write + i64 Display machinery (Formatter dispatch, padding
1835    // checks) the profile flagged as the residual hot path. Here we write the
1836    // whole digits and the fixed fractional suffix into one stack buffer and
1837    // emit a single push_str — byte-identical output, no fmt dispatch. `whole`
1838    // is non-negative (scaled >= 0) so no sign handling is needed; max 20 u64
1839    // digits + a 3-byte ".75" suffix fit in 23 bytes.
1840    let mut buf = [0u8; 23];
1841    let suffix: &[u8] = match rem {
1842        1 => b".25",
1843        2 => b".5",
1844        3 => b".75",
1845        _ => b".0",
1846    };
1847    let mut end = buf.len() - suffix.len();
1848    buf[end..].copy_from_slice(suffix);
1849
1850    // Whole digits, written right-to-left immediately before the suffix.
1851    let mut start = end;
1852    loop {
1853        start -= 1;
1854        buf[start] = b'0' + (whole % 10) as u8;
1855        whole /= 10;
1856        if whole == 0 {
1857            break;
1858        }
1859    }
1860    end = buf.len();
1861    out.push_str(std::str::from_utf8(&buf[start..end]).unwrap_or("0.0"));
1862}
1863
1864fn append_csv_minimal_field(out: &mut String, field: &str, delim: u8, quote_empty_single: bool) {
1865    if quote_empty_single && field.is_empty() {
1866        out.push_str("\"\"");
1867    } else if field
1868        .bytes()
1869        .any(|b| b == delim || b == b'"' || b == b'\n' || b == b'\r')
1870    {
1871        out.push('"');
1872        for ch in field.chars() {
1873            if ch == '"' {
1874                out.push_str("\"\"");
1875            } else {
1876                out.push(ch);
1877            }
1878        }
1879        out.push('"');
1880    } else {
1881        out.push_str(field);
1882    }
1883}
1884
1885fn append_i64_decimal(out: &mut String, value: i64) {
1886    let mut n = value.unsigned_abs();
1887    let mut buf = [0u8; 20];
1888    let mut start = buf.len();
1889    loop {
1890        start -= 1;
1891        buf[start] = b'0' + (n % 10) as u8;
1892        n /= 10;
1893        if n == 0 {
1894            break;
1895        }
1896    }
1897    if value < 0 {
1898        start -= 1;
1899        buf[start] = b'-';
1900    }
1901    out.push_str(std::str::from_utf8(&buf[start..]).unwrap_or(""));
1902}
1903
1904fn try_write_csv_typed(frame: &DataFrame, options: &CsvWriteOptions) -> Option<String> {
1905    let delim = options.delimiter;
1906    if !delim.is_ascii() {
1907        return None;
1908    }
1909    let delim_c = delim as char;
1910
1911    let headers: Vec<&String> = frame.column_names().into_iter().collect();
1912    let n = frame.index().len();
1913    let index_labels = if options.include_index {
1914        if frame.row_multiindex().is_some() {
1915            return None;
1916        }
1917        let labels = frame.index().labels();
1918        if labels.len() != n
1919            || labels
1920                .iter()
1921                .any(|label| !matches!(label, IndexLabel::Int64(_)))
1922        {
1923            return None;
1924        }
1925        Some(labels)
1926    } else {
1927        None
1928    };
1929
1930    enum FastCol<'a> {
1931        F {
1932            values: &'a [f64],
1933            quarter_plan: Option<Float64QuarterAffineCsvPlan>,
1934        },
1935        I(&'a [i64]),
1936        B(&'a [bool]),
1937        // All-valid contiguous Utf8: (bytes, offsets) with row r =
1938        // bytes[offsets[r]..offsets[r+1]].
1939        U(&'a [u8], &'a [usize]),
1940    }
1941    let mut cols: Vec<FastCol<'_>> = Vec::with_capacity(headers.len());
1942    for name in &headers {
1943        let column = frame.column(name)?;
1944        if let Some(s) = column.as_f64_slice() {
1945            if s.len() != n {
1946                return None;
1947            }
1948            cols.push(FastCol::F {
1949                values: s,
1950                quarter_plan: Float64QuarterAffineCsvPlan::for_slice(s),
1951            });
1952        } else if let Some(s) = column.as_i64_slice() {
1953            if s.len() != n {
1954                return None;
1955            }
1956            cols.push(FastCol::I(s));
1957        } else if let Some(s) = column.as_bool_slice() {
1958            if s.len() != n {
1959                return None;
1960            }
1961            cols.push(FastCol::B(s));
1962        } else if let Some((bytes, offsets)) = column.as_utf8_contiguous() {
1963            if offsets.len() != n + 1 {
1964                return None;
1965            }
1966            cols.push(FastCol::U(bytes, offsets));
1967        } else {
1968            return None;
1969        }
1970    }
1971
1972    // csv QUOTE_MINIMAL (matched by the general WriterBuilder path) quotes a field
1973    // as `""` when it is the SOLE field in its record and would otherwise be empty,
1974    // so the line is not an ambiguous blank that read_csv decodes as zero fields.
1975    // A record has one field when there is exactly one emitted index/column field.
1976    let field_count = cols.len() + usize::from(options.include_index);
1977    let single_field = field_count == 1;
1978    let mut out = String::with_capacity(n.saturating_mul(field_count).saturating_mul(8) + 64);
1979    if options.header {
1980        let mut wrote_field = false;
1981        if options.include_index {
1982            let index_header = resolve_csv_index_header(frame, options);
1983            append_csv_minimal_field(&mut out, &index_header, delim, single_field);
1984            wrote_field = true;
1985        }
1986        for (i, h) in headers.iter().enumerate() {
1987            if wrote_field || i > 0 {
1988                out.push(delim_c);
1989            }
1990            append_csv_minimal_field(&mut out, h.as_str(), delim, single_field);
1991            wrote_field = true;
1992        }
1993        out.push('\n');
1994    }
1995    for r in 0..n {
1996        if let Some(labels) = index_labels
1997            && let IndexLabel::Int64(v) = &labels[r]
1998        {
1999            append_i64_decimal(&mut out, *v);
2000        }
2001        for (c, col) in cols.iter().enumerate() {
2002            if c > 0 || index_labels.is_some() {
2003                out.push(delim_c);
2004            }
2005            match col {
2006                // Float64 uses format_pandas_float (Python str(float): keeps
2007                // "1.0", signed 2-digit sci notation) — EXACTLY what
2008                // scalar_to_csv_with_na uses, NOT Rust's Display (which drops the
2009                // ".0"). as_f64_slice yields an all-valid (NaN-free) buffer so the
2010                // NaN branch never fires; kept for defensive parity.
2011                FastCol::F {
2012                    values,
2013                    quarter_plan,
2014                } => {
2015                    if quarter_plan.is_some_and(|plan| plan.append_row(&mut out, r)) {
2016                        continue;
2017                    }
2018                    let v = values[r];
2019                    if v.is_nan() {
2020                        // Unreachable in practice (as_f64_slice is NaN-free), but kept
2021                        // isomorphic with the general path: a sole empty na_rep is quoted.
2022                        if single_field && options.na_rep.is_empty() {
2023                            out.push_str("\"\"");
2024                        } else {
2025                            out.push_str(&options.na_rep);
2026                        }
2027                    } else {
2028                        write_pandas_float(&mut out, v);
2029                    }
2030                }
2031                // Int64 formats via the hand-rolled append_i64_decimal fast path
2032                // (byte-identical to Rust Display / scalar_to_csv's `v.to_string()`,
2033                // but writes straight into `out` with no temporary String alloc — so
2034                // this is already optimal; don't "speed it up" with to_string/itoa).
2035                FastCol::I(s) => {
2036                    append_i64_decimal(&mut out, s[r]);
2037                }
2038                // Bool uses pandas to_csv spelling: capitalized True/False.
2039                FastCol::B(s) => {
2040                    out.push_str(if s[r] { "True" } else { "False" });
2041                }
2042                // Utf8 cell: the raw &str (= Scalar::Utf8's value in scalar_to_csv),
2043                // CSV-quoted only when it contains the delimiter, a quote, CR, or
2044                // LF — pandas/csv QUOTE_MINIMAL, with internal quotes doubled.
2045                FastCol::U(bytes, offsets) => {
2046                    let field = &bytes[offsets[r]..offsets[r + 1]];
2047                    // SAFETY-FREE: contiguous Utf8 backing is valid UTF-8.
2048                    let field = std::str::from_utf8(field).unwrap_or("");
2049                    append_csv_minimal_field(&mut out, field, delim, single_field);
2050                }
2051            }
2052        }
2053        out.push('\n');
2054    }
2055    Some(out)
2056}
2057
2058pub fn write_csv_string_with_options(
2059    frame: &DataFrame,
2060    options: &CsvWriteOptions,
2061) -> Result<String, IoError> {
2062    if options.include_index && frame.row_multiindex().is_some() {
2063        let materialized = materialize_named_row_multiindex_columns(frame)?;
2064        let mut nested_options = options.clone();
2065        nested_options.include_index = false;
2066        nested_options.index_label = None;
2067        return write_csv_string_with_options(&materialized, &nested_options);
2068    }
2069
2070    // Typed fast path (br-frankenpandas-qk2i9): when every column is an all-valid
2071    // Int64/Float64 typed slice or all-valid contiguous Utf8 (and the index is
2072    // not written), format the cells straight from the contiguous typed buffers,
2073    // skipping the per-column `Vec<Scalar>` materialization + per-cell `String` +
2074    // `csv` record machinery. Byte-for-byte identical to the general writer:
2075    // floats via write_pandas_float (= scalar_to_csv_with_na), Int64 Display
2076    // (= scalar_to_csv), Utf8 QUOTE_MINIMAL with doubled quotes, terminator `\n`,
2077    // and only taken when header names need no quoting.
2078    if let Some(out) = try_write_csv_typed(frame, options) {
2079        return Ok(out);
2080    }
2081
2082    let mut writer = WriterBuilder::new()
2083        .delimiter(options.delimiter)
2084        .from_writer(Vec::new());
2085
2086    let headers = frame
2087        .column_names()
2088        .into_iter()
2089        .cloned()
2090        .collect::<Vec<_>>();
2091    if options.header {
2092        let mut header_row =
2093            Vec::with_capacity(headers.len() + if options.include_index { 1 } else { 0 });
2094        if options.include_index {
2095            header_row.push(resolve_csv_index_header(frame, options));
2096        }
2097        header_row.extend(headers.iter().cloned());
2098        writer.write_record(&header_row)?;
2099    }
2100
2101    // Pre-compute each datetime column's column-uniform to_csv format (pandas
2102    // renders a datetime column with one date-only/seconds/sub-second form).
2103    let dt_formats: Vec<Option<DatetimeCsvFormat>> = headers
2104        .iter()
2105        .map(|name| {
2106            frame.column(name).and_then(|column| {
2107                (column.dtype() == DType::Datetime64).then(|| datetime_csv_format(column))
2108            })
2109        })
2110        .collect();
2111    // A DatetimeIndex follows the same column-uniform rule when written.
2112    let index_dt_format = if options.include_index {
2113        index_datetime_csv_format(frame)
2114    } else {
2115        None
2116    };
2117
2118    for row_idx in 0..frame.index().len() {
2119        let mut row = Vec::with_capacity(headers.len() + if options.include_index { 1 } else { 0 });
2120        if options.include_index {
2121            row.push(index_label_csv_string(frame, row_idx, index_dt_format)?);
2122        }
2123        row.extend(headers.iter().enumerate().map(|(col_idx, name)| {
2124            let value = frame.column(name).and_then(|column| column.value(row_idx));
2125            match value {
2126                Some(scalar) => scalar_to_csv_cell(scalar, &options.na_rep, dt_formats[col_idx]),
2127                None => options.na_rep.clone(),
2128            }
2129        }));
2130        writer.write_record(&row)?;
2131    }
2132
2133    let bytes = writer.into_inner().map_err(|err| err.into_error())?;
2134    Ok(String::from_utf8(bytes)?)
2135}
2136
2137/// Serialize a DataFrame to a GitHub-style Markdown table.
2138///
2139/// This covers pandas' pure formatter path without taking a dependency on
2140/// Python's optional `tabulate` package.
2141pub fn write_markdown_string_with_options(
2142    frame: &DataFrame,
2143    options: &MarkdownWriteOptions,
2144) -> Result<String, IoError> {
2145    if options.include_index && frame.row_multiindex().is_some() {
2146        let materialized = materialize_named_row_multiindex_columns(frame)?;
2147        let mut nested_options = options.clone();
2148        nested_options.include_index = false;
2149        nested_options.index_label = None;
2150        return write_markdown_string_with_options(&materialized, &nested_options);
2151    }
2152
2153    let headers = frame
2154        .column_names()
2155        .into_iter()
2156        .cloned()
2157        .collect::<Vec<_>>();
2158    let table_width = headers.len() + usize::from(options.include_index);
2159    let mut out = String::new();
2160
2161    let mut header_row = Vec::with_capacity(table_width);
2162    if options.include_index {
2163        header_row.push(resolve_table_index_header(
2164            frame,
2165            options.index_label.as_deref(),
2166        ));
2167    }
2168    header_row.extend(headers.iter().cloned());
2169    push_markdown_row(&mut out, &header_row);
2170
2171    let separator = vec!["---".to_owned(); table_width];
2172    push_markdown_row(&mut out, &separator);
2173
2174    for row_idx in 0..frame.index().len() {
2175        let mut row = Vec::with_capacity(table_width);
2176        if options.include_index {
2177            row.push(index_label_string(frame, row_idx)?);
2178        }
2179        row.extend(headers.iter().map(|name| {
2180            let value = frame.column(name).and_then(|column| column.value(row_idx));
2181            match value {
2182                Some(scalar) => scalar_to_table_with_na(scalar, &options.na_rep),
2183                None => options.na_rep.clone(),
2184            }
2185        }));
2186        push_markdown_row(&mut out, &row);
2187    }
2188
2189    Ok(out)
2190}
2191
2192/// Serialize a DataFrame to a booktabs-compatible LaTeX tabular block.
2193pub fn write_latex_string_with_options(
2194    frame: &DataFrame,
2195    options: &LatexWriteOptions,
2196) -> Result<String, IoError> {
2197    if options.include_index && frame.row_multiindex().is_some() {
2198        let materialized = materialize_named_row_multiindex_columns(frame)?;
2199        let mut nested_options = options.clone();
2200        nested_options.include_index = false;
2201        nested_options.index_label = None;
2202        return write_latex_string_with_options(&materialized, &nested_options);
2203    }
2204
2205    let headers = frame
2206        .column_names()
2207        .into_iter()
2208        .cloned()
2209        .collect::<Vec<_>>();
2210    let table_width = headers.len() + usize::from(options.include_index);
2211    let mut out = String::new();
2212
2213    out.push_str("\\begin{tabular}{");
2214    out.push_str(&"l".repeat(table_width));
2215    out.push_str("}\n\\toprule\n");
2216
2217    let mut header_row = Vec::with_capacity(table_width);
2218    if options.include_index {
2219        header_row.push(String::new());
2220    }
2221    header_row.extend(headers.iter().cloned());
2222    push_latex_row(&mut out, &header_row, options.escape);
2223
2224    if options.include_index {
2225        let index_name = resolve_table_index_header(frame, options.index_label.as_deref());
2226        if !index_name.is_empty() {
2227            let mut index_name_row = Vec::with_capacity(table_width);
2228            index_name_row.push(index_name);
2229            index_name_row.extend(std::iter::repeat_n(String::new(), headers.len()));
2230            push_latex_row(&mut out, &index_name_row, options.escape);
2231        }
2232    }
2233
2234    out.push_str("\\midrule\n");
2235
2236    for row_idx in 0..frame.index().len() {
2237        let mut row = Vec::with_capacity(table_width);
2238        if options.include_index {
2239            row.push(index_label_string(frame, row_idx)?);
2240        }
2241        row.extend(headers.iter().map(|name| {
2242            let value = frame.column(name).and_then(|column| column.value(row_idx));
2243            match value {
2244                Some(scalar) => scalar_to_latex_cell(scalar, &options.na_rep),
2245                None => options.na_rep.clone(),
2246            }
2247        }));
2248        push_latex_row(&mut out, &row, options.escape);
2249    }
2250
2251    out.push_str("\\bottomrule\n\\end{tabular}\n");
2252    Ok(out)
2253}
2254
2255/// Serialize a DataFrame to an HTML table string.
2256pub fn write_html_string_with_options(
2257    frame: &DataFrame,
2258    options: &HtmlWriteOptions,
2259) -> Result<String, IoError> {
2260    if options.include_index && frame.row_multiindex().is_some() {
2261        let materialized = materialize_named_row_multiindex_columns(frame)?;
2262        let nested_options = HtmlWriteOptions {
2263            include_index: false,
2264            ..options.clone()
2265        };
2266        return write_html_string_with_options(&materialized, &nested_options);
2267    }
2268
2269    write_html_table_string(frame, options)
2270}
2271
2272fn write_html_table_string(
2273    frame: &DataFrame,
2274    options: &HtmlWriteOptions,
2275) -> Result<String, IoError> {
2276    let mut out = String::new();
2277    push_html_table_open(&mut out, options);
2278    out.push_str("  <thead>\n    <tr style=\"text-align: ");
2279    out.push_str(&escape_html_attr(
2280        options.justify.as_deref().unwrap_or("right"),
2281    ));
2282    out.push_str(";\">\n");
2283
2284    if options.include_index {
2285        out.push_str("      <th></th>\n");
2286    }
2287    for name in frame.column_names() {
2288        out.push_str("      <th>");
2289        out.push_str(&html_text(name, options.escape));
2290        out.push_str("</th>\n");
2291    }
2292    out.push_str("    </tr>\n  </thead>\n  <tbody>\n");
2293
2294    for row_idx in 0..frame.index().len() {
2295        out.push_str("    <tr>\n");
2296        if options.include_index {
2297            out.push_str("      <th>");
2298            out.push_str(&html_index_label_string(frame, row_idx, options.escape)?);
2299            out.push_str("</th>\n");
2300        }
2301        for name in frame.column_names() {
2302            let value = frame.column(name).and_then(|column| column.value(row_idx));
2303            out.push_str("      <td>");
2304            match value {
2305                Some(scalar) => out.push_str(&html_scalar_string(scalar, options)),
2306                None => out.push_str(&html_text(&options.na_rep, options.escape)),
2307            }
2308            out.push_str("</td>\n");
2309        }
2310        out.push_str("    </tr>\n");
2311    }
2312
2313    out.push_str("  </tbody>\n</table>");
2314    Ok(out)
2315}
2316
2317fn push_html_table_open(out: &mut String, options: &HtmlWriteOptions) {
2318    out.push_str("<table");
2319    if let Some(border) = options.border.filter(|border| *border > 0) {
2320        out.push_str(" border=\"");
2321        out.push_str(&border.to_string());
2322        out.push('"');
2323    }
2324    out.push_str(" class=\"");
2325    out.push_str(&html_class_attr(&options.classes));
2326    out.push('"');
2327    if let Some(table_id) = options
2328        .table_id
2329        .as_deref()
2330        .map(str::trim)
2331        .filter(|table_id| !table_id.is_empty())
2332    {
2333        out.push_str(" id=\"");
2334        out.push_str(&escape_html_attr(table_id));
2335        out.push('"');
2336    }
2337    out.push_str(">\n");
2338}
2339
2340fn html_class_attr(classes: &[String]) -> String {
2341    std::iter::once("dataframe".to_owned())
2342        .chain(
2343            classes
2344                .iter()
2345                .flat_map(|class| class.split_whitespace())
2346                .filter(|class| !class.is_empty())
2347                .map(escape_html_attr),
2348        )
2349        .collect::<Vec<_>>()
2350        .join(" ")
2351}
2352
2353fn html_index_label_string(
2354    frame: &DataFrame,
2355    row_idx: usize,
2356    escape: bool,
2357) -> Result<String, IoError> {
2358    let label = frame
2359        .index()
2360        .labels()
2361        .get(row_idx)
2362        .ok_or_else(|| IoError::Html(format!("missing index label at row {row_idx}")))?;
2363    let raw = match label {
2364        IndexLabel::Int64(v) => v.to_string(),
2365        IndexLabel::Utf8(s) => s.clone(),
2366        IndexLabel::Timedelta64(ns) => Timedelta::format(*ns),
2367        IndexLabel::Datetime64(ns) => format_datetime_ns(*ns),
2368        f @ (IndexLabel::Float64(_) | IndexLabel::Bool(_)) => f.to_string(),
2369        IndexLabel::Null(_) => label.to_string(),
2370    };
2371    Ok(html_text(&raw, escape))
2372}
2373
2374fn html_scalar_string(scalar: &Scalar, options: &HtmlWriteOptions) -> String {
2375    match scalar {
2376        Scalar::Null(_) => html_text(&options.na_rep, options.escape),
2377        Scalar::Bool(value) => html_text(if *value { "True" } else { "False" }, options.escape),
2378        Scalar::Int64(value) => value.to_string(),
2379        Scalar::Float64(value) => {
2380            if value.is_nan() {
2381                html_text(&options.na_rep, options.escape)
2382            } else if value.fract() == 0.0 {
2383                format!("{value:.1}")
2384            } else {
2385                value.to_string()
2386            }
2387        }
2388        Scalar::Utf8(value) => {
2389            if options.render_links && is_html_renderable_link(value) {
2390                let label = html_text(value, options.escape);
2391                format!(
2392                    "<a href=\"{}\" target=\"_blank\">{label}</a>",
2393                    escape_html_attr(value)
2394                )
2395            } else {
2396                html_text(value, options.escape)
2397            }
2398        }
2399        // pandas to_html renders a temporal NaT as the literal "NaT" (na_rep
2400        // overrides only float NaN); verified vs pandas 2.2.3. (tblnat)
2401        Scalar::Timedelta64(value) => {
2402            if *value == Timedelta::NAT {
2403                html_text("NaT", options.escape)
2404            } else {
2405                html_text(&Timedelta::format(*value), options.escape)
2406            }
2407        }
2408        Scalar::Datetime64(value) => {
2409            if *value == Timestamp::NAT {
2410                html_text("NaT", options.escape)
2411            } else {
2412                html_text(&format_datetime_ns(*value), options.escape)
2413            }
2414        }
2415        Scalar::Period(value) => {
2416            if value.ordinal == i64::MIN {
2417                html_text("NaT", options.escape)
2418            } else {
2419                html_text(&value.calendar_string(), options.escape)
2420            }
2421        }
2422        Scalar::Interval(iv) => html_text(&format!("{iv}"), options.escape),
2423    }
2424}
2425
2426fn html_text(value: &str, escape: bool) -> String {
2427    if escape {
2428        escape_html_text(value)
2429    } else {
2430        value.to_owned()
2431    }
2432}
2433
2434fn is_html_renderable_link(value: &str) -> bool {
2435    value.starts_with("http://") || value.starts_with("https://") || value.starts_with("ftp://")
2436}
2437
2438fn escape_html_text(value: &str) -> String {
2439    let mut escaped = String::with_capacity(value.len());
2440    for ch in value.chars() {
2441        match ch {
2442            '&' => escaped.push_str("&amp;"),
2443            '<' => escaped.push_str("&lt;"),
2444            '>' => escaped.push_str("&gt;"),
2445            _ => escaped.push(ch),
2446        }
2447    }
2448    escaped
2449}
2450
2451fn escape_html_attr(value: &str) -> String {
2452    let mut escaped = String::with_capacity(value.len());
2453    for ch in value.chars() {
2454        match ch {
2455            '&' => escaped.push_str("&amp;"),
2456            '"' => escaped.push_str("&quot;"),
2457            '<' => escaped.push_str("&lt;"),
2458            '>' => escaped.push_str("&gt;"),
2459            _ => escaped.push(ch),
2460        }
2461    }
2462    escaped
2463}
2464
2465/// Parse a DataFrame from the first HTML table in a document string.
2466///
2467/// This is the local, table-oriented subset of pandas `read_html`: it parses
2468/// static HTML with an HTML5 parser, uses the first `<thead><tr>` as headers
2469/// when present, otherwise uses the first row with header cells, and fills
2470/// short body rows with nulls.
2471pub fn read_html_str(input: &str) -> Result<DataFrame, IoError> {
2472    read_html_str_with_options(input, &HtmlReadOptions::default())
2473}
2474
2475/// Parse a DataFrame from an HTML document string with options.
2476pub fn read_html_str_with_options(
2477    input: &str,
2478    options: &HtmlReadOptions,
2479) -> Result<DataFrame, IoError> {
2480    let document = Html::parse_document(input);
2481    let table_selector = html_selector("table")?;
2482    let row_selector = html_selector("tr")?;
2483    let thead_row_selector = html_selector("thead tr")?;
2484    let tbody_row_selector = html_selector("tbody tr")?;
2485    let cell_selector = html_selector("th, td")?;
2486    let th_selector = html_selector("th")?;
2487
2488    let table = document
2489        .select(&table_selector)
2490        .nth(options.table_index)
2491        .ok_or_else(|| {
2492            IoError::Html(format!(
2493                "html input contains no table at index {}",
2494                options.table_index
2495            ))
2496        })?;
2497
2498    let header_rows = table
2499        .select(&thead_row_selector)
2500        .map(|row| html_row_cells(row, &cell_selector))
2501        .filter(|cells| !cells.is_empty())
2502        .collect::<Vec<_>>();
2503    let body_rows = table
2504        .select(&tbody_row_selector)
2505        .map(|row| html_row_cells(row, &cell_selector))
2506        .filter(|cells| !cells.is_empty())
2507        .collect::<Vec<_>>();
2508
2509    if let Some(header_cells) = header_rows.first() {
2510        let headers = normalize_html_headers(header_cells)?;
2511        return html_rows_to_frame(headers, body_rows);
2512    }
2513
2514    let all_rows = table
2515        .select(&row_selector)
2516        .map(|row| {
2517            let has_header_cell = row.select(&th_selector).next().is_some();
2518            (has_header_cell, html_row_cells(row, &cell_selector))
2519        })
2520        .filter(|(_, cells)| !cells.is_empty())
2521        .collect::<Vec<_>>();
2522    if all_rows.is_empty() {
2523        return Err(IoError::Html(
2524            "html table contains no rows with cells".to_owned(),
2525        ));
2526    }
2527
2528    let mut all_rows = all_rows.into_iter();
2529    let (first_has_header, first_cells) = all_rows
2530        .next()
2531        .ok_or_else(|| IoError::Html("html table contains no rows with cells".to_owned()))?;
2532
2533    if first_has_header {
2534        let headers = normalize_html_headers(&first_cells)?;
2535        let data_rows = all_rows.map(|(_, cells)| cells).collect::<Vec<_>>();
2536        html_rows_to_frame(headers, data_rows)
2537    } else {
2538        let mut data_rows = vec![first_cells];
2539        data_rows.extend(all_rows.map(|(_, cells)| cells));
2540        let width = data_rows.iter().map(Vec::len).max().unwrap_or(0);
2541        if width == 0 {
2542            return Err(IoError::Html("html table contains no cells".to_owned()));
2543        }
2544        let headers = (0..width).map(|idx| idx.to_string()).collect::<Vec<_>>();
2545        html_rows_to_frame(headers, data_rows)
2546    }
2547}
2548
2549const PICKLE_FORMAT_KEY: &str = "__frankenpandas_pickle_format";
2550const PICKLE_FORMAT_VERSION: &str = "frankenpandas.dataframe.v1";
2551const PICKLE_ORIENT_KEY: &str = "orient";
2552const PICKLE_PAYLOAD_KEY: &str = "payload";
2553
2554/// Serialize a DataFrame to Pickle bytes.
2555///
2556/// This emits a fail-closed FrankenPandas envelope containing the existing
2557/// split-orient DataFrame representation. It is intentionally narrower than
2558/// pandas' arbitrary Python-object pickle support.
2559pub fn write_pickle_bytes_with_options(
2560    frame: &DataFrame,
2561    options: &PickleWriteOptions,
2562) -> Result<Vec<u8>, IoError> {
2563    let split_json = write_json_string(frame, JsonOrient::Split)?;
2564    let split_value = serde_json::from_str::<serde_json::Value>(&split_json)?;
2565    let mut envelope = serde_json::Map::new();
2566    envelope.insert(
2567        PICKLE_FORMAT_KEY.to_owned(),
2568        serde_json::Value::String(PICKLE_FORMAT_VERSION.to_owned()),
2569    );
2570    envelope.insert(
2571        PICKLE_ORIENT_KEY.to_owned(),
2572        serde_json::Value::String("split".to_owned()),
2573    );
2574    envelope.insert(PICKLE_PAYLOAD_KEY.to_owned(), split_value);
2575
2576    serde_pickle::to_vec(
2577        &serde_json::Value::Object(envelope),
2578        pickle_ser_options(options),
2579    )
2580    .map_err(|err| IoError::Pickle(err.to_string()))
2581}
2582
2583/// Deserialize a DataFrame from Pickle bytes.
2584pub fn read_pickle_bytes(input: &[u8]) -> Result<DataFrame, IoError> {
2585    read_pickle_bytes_with_options(input, &PickleReadOptions::default())
2586}
2587
2588/// Deserialize a DataFrame from Pickle bytes with options.
2589///
2590/// Only the versioned FrankenPandas envelope is accepted. Foreign Python
2591/// pickles fail closed with [`IoError::Pickle`].
2592pub fn read_pickle_bytes_with_options(
2593    input: &[u8],
2594    options: &PickleReadOptions,
2595) -> Result<DataFrame, IoError> {
2596    let value = serde_pickle::from_slice::<serde_json::Value>(input, pickle_de_options(options))
2597        .map_err(|err| IoError::Pickle(err.to_string()))?;
2598    let envelope = value
2599        .as_object()
2600        .ok_or_else(|| IoError::Pickle("pickle payload must be an object".to_owned()))?;
2601
2602    match envelope
2603        .get(PICKLE_FORMAT_KEY)
2604        .and_then(|value| value.as_str())
2605    {
2606        Some(PICKLE_FORMAT_VERSION) => {}
2607        Some(other) => {
2608            return Err(IoError::Pickle(format!(
2609                "unsupported FrankenPandas pickle format '{other}'"
2610            )));
2611        }
2612        None => {
2613            return Err(IoError::Pickle(
2614                "pickle payload is missing FrankenPandas format marker".to_owned(),
2615            ));
2616        }
2617    }
2618
2619    match envelope
2620        .get(PICKLE_ORIENT_KEY)
2621        .and_then(|value| value.as_str())
2622    {
2623        Some("split") => {}
2624        Some(other) => {
2625            return Err(IoError::Pickle(format!(
2626                "unsupported FrankenPandas pickle orient '{other}'"
2627            )));
2628        }
2629        None => {
2630            return Err(IoError::Pickle(
2631                "pickle payload is missing orient".to_owned(),
2632            ));
2633        }
2634    }
2635
2636    let payload = envelope
2637        .get(PICKLE_PAYLOAD_KEY)
2638        .ok_or_else(|| IoError::Pickle("pickle payload is missing data".to_owned()))?;
2639    let payload_json = serde_json::to_string(payload)?;
2640    read_json_str(&payload_json, JsonOrient::Split)
2641}
2642
2643fn pickle_ser_options(options: &PickleWriteOptions) -> serde_pickle::SerOptions {
2644    match options.protocol {
2645        PickleProtocol::V2 => serde_pickle::SerOptions::new().proto_v2(),
2646        PickleProtocol::V3 => serde_pickle::SerOptions::new(),
2647    }
2648}
2649
2650fn pickle_de_options(options: &PickleReadOptions) -> serde_pickle::DeOptions {
2651    let de_options = serde_pickle::DeOptions::new();
2652    if options.decode_legacy_strings {
2653        de_options.decode_strings()
2654    } else {
2655        de_options
2656    }
2657}
2658
2659#[derive(Debug, Clone)]
2660struct StataField {
2661    variable_name: String,
2662    source: StataFieldSource,
2663    variable_type: VariableType,
2664}
2665
2666#[derive(Debug, Clone)]
2667enum StataFieldSource {
2668    Index,
2669    Column(String),
2670}
2671
2672/// Serialize a DataFrame to Stata DTA bytes.
2673///
2674/// This first slice targets DTA release 118 and a DataFrame-oriented subset:
2675/// integer/bool, float, fixed string, and missing values.
2676pub fn write_stata_bytes_with_options(
2677    frame: &DataFrame,
2678    options: &StataWriteOptions,
2679) -> Result<Vec<u8>, IoError> {
2680    let fields = stata_fields_for_frame(frame, options)?;
2681    let header = Header::builder(Release::V118, ByteOrder::LittleEndian).build();
2682    let mut schema = StataSchema::builder();
2683    for field in &fields {
2684        let format = stata_format_for_type(field.variable_type);
2685        schema = schema.add_variable(
2686            Variable::builder(field.variable_type, &field.variable_name).format(format),
2687        );
2688    }
2689    let schema = schema.build().map_err(stata_error)?;
2690
2691    let mut record_writer = DtaWriter::new()
2692        .from_writer(Cursor::new(Vec::<u8>::new()))
2693        .write_header(header)
2694        .map_err(stata_error)?
2695        .write_schema(schema)
2696        .map_err(stata_error)?
2697        .into_record_writer()
2698        .map_err(stata_error)?;
2699
2700    for row_idx in 0..frame.index().len() {
2701        let mut record = Vec::with_capacity(fields.len());
2702        for field in &fields {
2703            record.push(stata_value_for_field(frame, row_idx, field)?);
2704        }
2705        record_writer.write_record(&record).map_err(stata_error)?;
2706    }
2707
2708    Ok(record_writer
2709        .into_long_string_writer()
2710        .map_err(stata_error)?
2711        .into_value_label_writer()
2712        .map_err(stata_error)?
2713        .finish()
2714        .map_err(stata_error)?
2715        .into_inner())
2716}
2717
2718/// Read a DataFrame from Stata DTA bytes.
2719pub fn read_stata_bytes(input: &[u8]) -> Result<DataFrame, IoError> {
2720    let mut characteristic_reader = DtaReader::new()
2721        .from_reader(Cursor::new(input))
2722        .read_header()
2723        .map_err(stata_error)?
2724        .read_schema()
2725        .map_err(stata_error)?;
2726    characteristic_reader.skip_to_end().map_err(stata_error)?;
2727
2728    let mut record_reader = characteristic_reader
2729        .into_record_reader()
2730        .map_err(stata_error)?;
2731    let column_order = record_reader
2732        .schema()
2733        .variables()
2734        .iter()
2735        .map(|variable| variable.name().to_owned())
2736        .collect::<Vec<_>>();
2737    reject_duplicate_headers(&column_order)?;
2738
2739    let mut columns = column_order
2740        .iter()
2741        .cloned()
2742        .map(|name| (name, Vec::new()))
2743        .collect::<BTreeMap<_, _>>();
2744    let mut row_count: i64 = 0;
2745    while let Some(record) = record_reader.read_record().map_err(stata_error)? {
2746        for (name, value) in column_order.iter().zip(record.values()) {
2747            columns
2748                .get_mut(name)
2749                .ok_or_else(|| IoError::Stata(format!("missing Stata column '{name}'")))?
2750                .push(stata_value_to_scalar(value)?);
2751        }
2752        row_count = row_count
2753            .checked_add(1)
2754            .ok_or_else(|| IoError::Stata("Stata row count exceeded i64 range".to_owned()))?;
2755    }
2756
2757    let mut out = BTreeMap::new();
2758    for name in &column_order {
2759        let values = columns
2760            .remove(name)
2761            .ok_or_else(|| IoError::Stata(format!("missing Stata column '{name}'")))?;
2762        out.insert(name.clone(), Column::from_values(values)?);
2763    }
2764    Ok(DataFrame::new_with_column_order(
2765        Index::from_i64((0..row_count).collect()),
2766        out,
2767        column_order,
2768    )?)
2769}
2770
2771fn stata_fields_for_frame(
2772    frame: &DataFrame,
2773    options: &StataWriteOptions,
2774) -> Result<Vec<StataField>, IoError> {
2775    let mut fields = Vec::new();
2776    if options.include_index {
2777        let name = options
2778            .index_label
2779            .clone()
2780            .unwrap_or_else(|| "index".to_owned());
2781        validate_stata_variable_name(&name)?;
2782        fields.push(StataField {
2783            variable_name: name,
2784            source: StataFieldSource::Index,
2785            variable_type: stata_index_variable_type(frame)?,
2786        });
2787    }
2788
2789    for name in frame.column_names() {
2790        validate_stata_variable_name(name)?;
2791        let column = frame
2792            .column(name)
2793            .ok_or_else(|| IoError::Stata(format!("missing DataFrame column '{name}'")))?;
2794        fields.push(StataField {
2795            variable_name: name.clone(),
2796            source: StataFieldSource::Column(name.clone()),
2797            variable_type: infer_stata_variable_type(column, name)?,
2798        });
2799    }
2800
2801    let mut seen = BTreeSet::new();
2802    for field in &fields {
2803        if !seen.insert(field.variable_name.clone()) {
2804            return Err(IoError::DuplicateColumnName(field.variable_name.clone()));
2805        }
2806    }
2807    Ok(fields)
2808}
2809
2810fn validate_stata_variable_name(name: &str) -> Result<(), IoError> {
2811    if name.is_empty() {
2812        return Err(IoError::Stata(
2813            "Stata variable name cannot be empty".to_owned(),
2814        ));
2815    }
2816    if name.len() > 32 {
2817        return Err(IoError::Stata(format!(
2818            "Stata variable name '{name}' exceeds 32 bytes"
2819        )));
2820    }
2821    let mut chars = name.chars();
2822    let first = chars
2823        .next()
2824        .ok_or_else(|| IoError::Stata("Stata variable name cannot be empty".to_owned()))?;
2825    if !(first == '_' || first.is_ascii_alphabetic()) {
2826        return Err(IoError::Stata(format!(
2827            "invalid Stata variable name '{name}': first character must be ASCII letter or '_'"
2828        )));
2829    }
2830    if !chars.all(|ch| ch == '_' || ch.is_ascii_alphanumeric()) {
2831        return Err(IoError::Stata(format!(
2832            "invalid Stata variable name '{name}': only ASCII letters, digits, and '_' are supported"
2833        )));
2834    }
2835    Ok(())
2836}
2837
2838fn stata_index_variable_type(frame: &DataFrame) -> Result<VariableType, IoError> {
2839    let max_len = frame
2840        .index()
2841        .labels()
2842        .iter()
2843        .map(|label| label.to_string().len())
2844        .max()
2845        .unwrap_or(1)
2846        .max(1);
2847    stata_fixed_string_type(max_len, "index")
2848}
2849
2850fn infer_stata_variable_type(column: &Column, name: &str) -> Result<VariableType, IoError> {
2851    let mut saw_numeric = false;
2852    let mut saw_float = false;
2853    let mut saw_string = false;
2854    let mut max_string_len = 1usize;
2855
2856    for value in column.values() {
2857        match value {
2858            Scalar::Null(_) => {}
2859            Scalar::Bool(_) => {
2860                saw_numeric = true;
2861            }
2862            Scalar::Int64(v) => {
2863                saw_numeric = true;
2864                if i32::try_from(*v).is_err() {
2865                    return Err(IoError::Stata(format!(
2866                        "Stata long column '{name}' cannot encode i64 value {v}"
2867                    )));
2868                }
2869            }
2870            Scalar::Float64(v) => {
2871                if !v.is_nan() {
2872                    saw_numeric = true;
2873                    saw_float = true;
2874                }
2875            }
2876            Scalar::Utf8(text) => {
2877                saw_string = true;
2878                max_string_len = max_string_len.max(text.len());
2879            }
2880            other => {
2881                saw_string = true;
2882                max_string_len = max_string_len.max(scalar_to_table_with_na(other, "").len());
2883            }
2884        }
2885    }
2886
2887    if saw_string {
2888        stata_fixed_string_type(max_string_len, name)
2889    } else if saw_numeric && !saw_float {
2890        Ok(VariableType::Long)
2891    } else {
2892        Ok(VariableType::Double)
2893    }
2894}
2895
2896fn stata_fixed_string_type(len: usize, name: &str) -> Result<VariableType, IoError> {
2897    let width = len.max(1);
2898    let width = u16::try_from(width).map_err(|_| {
2899        IoError::Stata(format!(
2900            "Stata string column '{name}' exceeds fixed string capacity"
2901        ))
2902    })?;
2903    if width > 2045 {
2904        return Err(IoError::Stata(format!(
2905            "Stata string column '{name}' requires strL; this slice supports fixed strings only"
2906        )));
2907    }
2908    Ok(VariableType::FixedString(width))
2909}
2910
2911fn stata_format_for_type(variable_type: VariableType) -> &'static str {
2912    match variable_type {
2913        VariableType::Byte | VariableType::Int | VariableType::Long => "%12.0g",
2914        VariableType::Float | VariableType::Double => "%10.0g",
2915        VariableType::FixedString(_) | VariableType::LongString => "%9s",
2916    }
2917}
2918
2919fn stata_value_for_field(
2920    frame: &DataFrame,
2921    row_idx: usize,
2922    field: &StataField,
2923) -> Result<StataValue<'static>, IoError> {
2924    match field.source {
2925        StataFieldSource::Index => Ok(StataValue::String(std::borrow::Cow::Owned(
2926            index_label_string(frame, row_idx)?,
2927        ))),
2928        StataFieldSource::Column(ref name) => {
2929            let value = frame.column(name).and_then(|column| column.value(row_idx));
2930            scalar_to_stata_value(value, field.variable_type, name)
2931        }
2932    }
2933}
2934
2935fn scalar_to_stata_value(
2936    value: Option<&Scalar>,
2937    variable_type: VariableType,
2938    name: &str,
2939) -> Result<StataValue<'static>, IoError> {
2940    match variable_type {
2941        VariableType::Long => match value {
2942            Some(Scalar::Bool(v)) => Ok(StataValue::Long(StataLong::Present(i32::from(*v)))),
2943            Some(Scalar::Int64(v)) => Ok(StataValue::Long(StataLong::Present(
2944                i32::try_from(*v).map_err(|_| {
2945                    IoError::Stata(format!("Stata long column '{name}' cannot encode {v}"))
2946                })?,
2947            ))),
2948            Some(Scalar::Null(_)) | None => {
2949                Ok(StataValue::Long(StataLong::Missing(MissingValue::System)))
2950            }
2951            Some(other) => Err(IoError::Stata(format!(
2952                "Stata long column '{name}' cannot encode {other:?}"
2953            ))),
2954        },
2955        VariableType::Double => match value {
2956            Some(Scalar::Bool(v)) => Ok(StataValue::Double(StataDouble::Present(if *v {
2957                1.0
2958            } else {
2959                0.0
2960            }))),
2961            Some(Scalar::Int64(v)) => Ok(StataValue::Double(StataDouble::Present(*v as f64))),
2962            Some(Scalar::Float64(v)) if v.is_nan() => Ok(StataValue::Double(StataDouble::Missing(
2963                MissingValue::System,
2964            ))),
2965            Some(Scalar::Float64(v)) => Ok(StataValue::Double(StataDouble::Present(*v))),
2966            Some(Scalar::Null(_)) | None => Ok(StataValue::Double(StataDouble::Missing(
2967                MissingValue::System,
2968            ))),
2969            Some(other) => Err(IoError::Stata(format!(
2970                "Stata double column '{name}' cannot encode {other:?}"
2971            ))),
2972        },
2973        VariableType::FixedString(_) => {
2974            let text = match value {
2975                Some(Scalar::Null(_)) | None => String::new(),
2976                Some(scalar) => scalar_to_table_with_na(scalar, ""),
2977            };
2978            Ok(StataValue::String(std::borrow::Cow::Owned(text)))
2979        }
2980        VariableType::Byte | VariableType::Int | VariableType::Float | VariableType::LongString => {
2981            Err(IoError::Stata(format!(
2982                "unsupported Stata variable type for column '{name}': {variable_type:?}"
2983            )))
2984        }
2985    }
2986}
2987
2988fn stata_value_to_scalar(value: &StataValue<'_>) -> Result<Scalar, IoError> {
2989    match value {
2990        StataValue::Byte(v) => Ok(v
2991            .present()
2992            .map(|value| Scalar::Int64(i64::from(value)))
2993            .unwrap_or(Scalar::Null(NullKind::NaN))),
2994        StataValue::Int(v) => Ok(v
2995            .present()
2996            .map(|value| Scalar::Int64(i64::from(value)))
2997            .unwrap_or(Scalar::Null(NullKind::NaN))),
2998        StataValue::Long(v) => Ok(v
2999            .present()
3000            .map(|value| Scalar::Int64(i64::from(value)))
3001            .unwrap_or(Scalar::Null(NullKind::NaN))),
3002        StataValue::Float(v) => Ok(v
3003            .present()
3004            .map(|value| Scalar::Float64(f64::from(value)))
3005            .unwrap_or(Scalar::Null(NullKind::NaN))),
3006        StataValue::Double(v) => Ok(v
3007            .present()
3008            .map(Scalar::Float64)
3009            .unwrap_or(Scalar::Null(NullKind::NaN))),
3010        StataValue::String(text) => Ok(Scalar::Utf8(text.to_string())),
3011        StataValue::LongStringRef(_) => Err(IoError::Stata(
3012            "Stata strL values are not supported by this reader slice".to_owned(),
3013        )),
3014    }
3015}
3016
3017fn stata_error<E: std::fmt::Display>(err: E) -> IoError {
3018    IoError::Stata(err.to_string())
3019}
3020
3021/// Parse a DataFrame from a row-oriented XML document string.
3022///
3023/// Matches the writer-oriented subset accepted by `pd.read_xml(...,
3024/// parser="etree")`: each row is an element named by
3025/// [`XmlReadOptions::row_name`], and each direct child element becomes a
3026/// DataFrame column. Attributes, XPath, namespaces, and nested field elements
3027/// are intentionally out of scope for this slice.
3028pub fn read_xml_str(input: &str) -> Result<DataFrame, IoError> {
3029    read_xml_str_with_options(input, &XmlReadOptions::default())
3030}
3031
3032/// Parse a DataFrame from a row-oriented XML document string with options.
3033pub fn read_xml_str_with_options(
3034    input: &str,
3035    options: &XmlReadOptions,
3036) -> Result<DataFrame, IoError> {
3037    validate_xml_element_name(&options.row_name)?;
3038
3039    let mut reader = XmlReader::from_str(input);
3040    reader.config_mut().trim_text(false);
3041    let mut buf = Vec::new();
3042    let mut rows: Vec<BTreeMap<String, Scalar>> = Vec::new();
3043    let mut column_order = Vec::new();
3044    let mut seen_columns = HashSet::new();
3045    let mut current_row: Option<BTreeMap<String, Scalar>> = None;
3046    let mut current_field: Option<String> = None;
3047    let mut field_text = String::new();
3048    let mut xml_version = XmlVersion::Implicit1_0;
3049
3050    loop {
3051        match reader
3052            .read_event_into(&mut buf)
3053            .map_err(|err| IoError::Xml(err.to_string()))?
3054        {
3055            Event::Start(event) => {
3056                let name = xml_event_name(event.name())?;
3057                if current_row.is_none() {
3058                    if name == options.row_name {
3059                        current_row = Some(BTreeMap::new());
3060                    }
3061                } else if let Some(field_name) = &current_field {
3062                    return Err(IoError::Xml(format!(
3063                        "nested xml element '{name}' inside field '{field_name}' is unsupported"
3064                    )));
3065                } else {
3066                    current_field = Some(name);
3067                    field_text.clear();
3068                }
3069            }
3070            Event::Empty(event) => {
3071                let name = xml_event_name(event.name())?;
3072                if let Some(field_name) = &current_field {
3073                    return Err(IoError::Xml(format!(
3074                        "nested xml element '{name}' inside field '{field_name}' is unsupported"
3075                    )));
3076                }
3077                if let Some(row) = current_row.as_mut() {
3078                    insert_xml_field(
3079                        row,
3080                        &mut column_order,
3081                        &mut seen_columns,
3082                        name,
3083                        Scalar::Null(NullKind::Null),
3084                    )?;
3085                } else if name == options.row_name {
3086                    rows.push(BTreeMap::new());
3087                }
3088            }
3089            Event::Text(event) => {
3090                if current_field.is_some() {
3091                    let decoded = event
3092                        .xml_content(xml_version)
3093                        .map_err(|err| IoError::Xml(err.to_string()))?;
3094                    field_text.push_str(&decoded);
3095                }
3096            }
3097            Event::CData(event) => {
3098                if current_field.is_some() {
3099                    let decoded = event
3100                        .xml_content(xml_version)
3101                        .map_err(|err| IoError::Xml(err.to_string()))?;
3102                    field_text.push_str(&decoded);
3103                }
3104            }
3105            Event::End(event) => {
3106                let name = xml_event_name(event.name())?;
3107                if let Some(field_name) = current_field.as_ref() {
3108                    if name != *field_name {
3109                        return Err(IoError::Xml(format!(
3110                            "xml field '{field_name}' closed by mismatched element '{name}'"
3111                        )));
3112                    }
3113                    let field_name = current_field.take().expect("field checked");
3114                    let value = parse_scalar(&field_text);
3115                    field_text.clear();
3116                    let row = current_row
3117                        .as_mut()
3118                        .ok_or_else(|| IoError::Xml("xml field outside row".to_owned()))?;
3119                    insert_xml_field(row, &mut column_order, &mut seen_columns, field_name, value)?;
3120                } else if name == options.row_name {
3121                    let row = current_row.take().ok_or_else(|| {
3122                        IoError::Xml("xml row closed before it opened".to_owned())
3123                    })?;
3124                    rows.push(row);
3125                }
3126            }
3127            Event::GeneralRef(reference) => {
3128                if current_field.is_some() {
3129                    field_text.push_str(&decode_xml_general_ref(reference)?);
3130                }
3131            }
3132            Event::Eof => break,
3133            Event::Decl(decl) => {
3134                if let Ok(v) = decl.version() {
3135                    xml_version = match v.as_ref() {
3136                        b"1.0" => XmlVersion::Explicit1_0,
3137                        b"1.1" => XmlVersion::Explicit1_1,
3138                        _ => xml_version,
3139                    };
3140                }
3141            }
3142            Event::PI(_) | Event::DocType(_) | Event::Comment(_) => {}
3143        }
3144        buf.clear();
3145    }
3146
3147    if current_field.is_some() || current_row.is_some() {
3148        return Err(IoError::Xml(
3149            "xml document ended inside an open row or field".to_owned(),
3150        ));
3151    }
3152    if rows.is_empty() {
3153        return Err(IoError::Xml(
3154            "xml input contains no row elements".to_owned(),
3155        ));
3156    }
3157
3158    let mut out_columns = BTreeMap::new();
3159    for name in &column_order {
3160        let values = rows
3161            .iter()
3162            .map(|row| {
3163                row.get(name)
3164                    .cloned()
3165                    .unwrap_or(Scalar::Null(NullKind::Null))
3166            })
3167            .collect::<Vec<_>>();
3168        out_columns.insert(name.clone(), Column::from_values(values)?);
3169    }
3170    let index = Index::from_i64((0..rows.len() as i64).collect());
3171    Ok(DataFrame::new_with_column_order(
3172        index,
3173        out_columns,
3174        column_order,
3175    )?)
3176}
3177
3178/// Serialize a DataFrame to an XML document string.
3179pub fn write_xml_string_with_options(
3180    frame: &DataFrame,
3181    options: &XmlWriteOptions,
3182) -> Result<String, IoError> {
3183    if options.include_index && frame.row_multiindex().is_some() {
3184        let materialized = materialize_named_row_multiindex_columns(frame)?;
3185        let mut nested_options = options.clone();
3186        nested_options.include_index = false;
3187        nested_options.index_label = None;
3188        return write_xml_string_with_options(&materialized, &nested_options);
3189    }
3190
3191    validate_xml_element_name(&options.root_name)?;
3192    validate_xml_element_name(&options.row_name)?;
3193
3194    let headers = frame
3195        .column_names()
3196        .into_iter()
3197        .cloned()
3198        .collect::<Vec<_>>();
3199    for name in &headers {
3200        validate_xml_element_name(name)?;
3201    }
3202
3203    let index_label = options
3204        .index_label
3205        .clone()
3206        .or_else(|| frame.index().name().map(ToOwned::to_owned))
3207        .unwrap_or_else(|| "index".to_owned());
3208    if options.include_index {
3209        validate_xml_element_name(&index_label)?;
3210    }
3211
3212    let mut out = String::new();
3213    out.push_str("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
3214    out.push('<');
3215    out.push_str(&options.root_name);
3216    out.push_str(">\n");
3217
3218    for row_idx in 0..frame.index().len() {
3219        out.push_str("  <");
3220        out.push_str(&options.row_name);
3221        out.push_str(">\n");
3222
3223        if options.include_index {
3224            let value = index_label_string(frame, row_idx)?;
3225            push_xml_field(&mut out, &index_label, Some(&value));
3226        }
3227
3228        for name in &headers {
3229            let value = frame
3230                .column(name)
3231                .and_then(|column| column.value(row_idx))
3232                .and_then(scalar_to_xml_value);
3233            push_xml_field(&mut out, name, value.as_deref());
3234        }
3235
3236        out.push_str("  </");
3237        out.push_str(&options.row_name);
3238        out.push_str(">\n");
3239    }
3240
3241    out.push_str("</");
3242    out.push_str(&options.root_name);
3243    out.push_str(">\n");
3244    Ok(out)
3245}
3246
3247fn xml_event_name(name: quick_xml::name::QName<'_>) -> Result<String, IoError> {
3248    std::str::from_utf8(name.as_ref())
3249        .map(ToOwned::to_owned)
3250        .map_err(|err| IoError::Xml(format!("invalid utf-8 xml element name: {err}")))
3251}
3252
3253fn decode_xml_general_ref(reference: quick_xml::events::BytesRef<'_>) -> Result<String, IoError> {
3254    let raw = std::str::from_utf8(reference.as_ref())
3255        .map_err(|err| IoError::Xml(format!("invalid utf-8 xml entity reference: {err}")))?;
3256    match raw {
3257        "amp" => Ok("&".to_owned()),
3258        "lt" => Ok("<".to_owned()),
3259        "gt" => Ok(">".to_owned()),
3260        "quot" => Ok("\"".to_owned()),
3261        "apos" => Ok("'".to_owned()),
3262        _ if raw.starts_with("#x") => {
3263            let value = u32::from_str_radix(&raw[2..], 16)
3264                .map_err(|err| IoError::Xml(format!("invalid hex xml entity '&{raw};': {err}")))?;
3265            char::from_u32(value)
3266                .map(|ch| ch.to_string())
3267                .ok_or_else(|| IoError::Xml(format!("invalid unicode xml entity '&{raw};'")))
3268        }
3269        _ if raw.starts_with('#') => {
3270            let value = raw[1..].parse::<u32>().map_err(|err| {
3271                IoError::Xml(format!("invalid decimal xml entity '&{raw};': {err}"))
3272            })?;
3273            char::from_u32(value)
3274                .map(|ch| ch.to_string())
3275                .ok_or_else(|| IoError::Xml(format!("invalid unicode xml entity '&{raw};'")))
3276        }
3277        _ => Err(IoError::Xml(format!(
3278            "unsupported xml entity reference '&{raw};'"
3279        ))),
3280    }
3281}
3282
3283fn insert_xml_field(
3284    row: &mut BTreeMap<String, Scalar>,
3285    column_order: &mut Vec<String>,
3286    seen_columns: &mut HashSet<String>,
3287    name: String,
3288    value: Scalar,
3289) -> Result<(), IoError> {
3290    if row.insert(name.clone(), value).is_some() {
3291        return Err(IoError::Xml(format!("duplicate xml field '{name}' in row")));
3292    }
3293    if seen_columns.insert(name.clone()) {
3294        column_order.push(name);
3295    }
3296    Ok(())
3297}
3298
3299fn validate_xml_element_name(name: &str) -> Result<(), IoError> {
3300    let mut chars = name.chars();
3301    let Some(first) = chars.next() else {
3302        return Err(IoError::Xml(
3303            "xml element name must be non-empty".to_owned(),
3304        ));
3305    };
3306    let valid_first = first == '_' || first.is_ascii_alphabetic();
3307    let valid_rest =
3308        chars.all(|ch| ch == '_' || ch == '-' || ch == '.' || ch.is_ascii_alphanumeric());
3309    if valid_first && valid_rest {
3310        Ok(())
3311    } else {
3312        Err(IoError::Xml(format!("invalid xml element name '{name}'")))
3313    }
3314}
3315
3316fn push_xml_field(out: &mut String, name: &str, value: Option<&str>) {
3317    out.push_str("    <");
3318    out.push_str(name);
3319    match value {
3320        Some(value) => {
3321            out.push('>');
3322            out.push_str(&escape_xml_text(value));
3323            out.push_str("</");
3324            out.push_str(name);
3325            out.push_str(">\n");
3326        }
3327        None => out.push_str("/>\n"),
3328    }
3329}
3330
3331fn escape_xml_text(value: &str) -> String {
3332    let mut escaped = String::with_capacity(value.len());
3333    let mut chars = value.chars().peekable();
3334    while let Some(ch) = chars.next() {
3335        match ch {
3336            '&' => escaped.push_str("&amp;"),
3337            '<' => escaped.push_str("&lt;"),
3338            '>' => escaped.push_str("&gt;"),
3339            '\r' => {
3340                escaped.push('\n');
3341                if chars.peek() == Some(&'\n') {
3342                    chars.next();
3343                }
3344            }
3345            _ => escaped.push(ch),
3346        }
3347    }
3348    escaped
3349}
3350
3351fn scalar_to_xml_value(scalar: &Scalar) -> Option<String> {
3352    match scalar {
3353        Scalar::Null(_) => None,
3354        Scalar::Bool(value) => Some(if *value { "True" } else { "False" }.to_owned()),
3355        Scalar::Int64(value) => Some(value.to_string()),
3356        Scalar::Float64(value) => {
3357            if value.is_nan() {
3358                None
3359            } else if value.is_finite() && *value == value.round() && value.abs() < 1e15 {
3360                Some(format!("{value:.1}"))
3361            } else {
3362                Some(value.to_string())
3363            }
3364        }
3365        Scalar::Utf8(value) => Some(value.clone()),
3366        Scalar::Timedelta64(value) => {
3367            if *value == Timedelta::NAT {
3368                None
3369            } else {
3370                Some(Timedelta::format(*value))
3371            }
3372        }
3373        Scalar::Datetime64(value) => {
3374            if *value == Timestamp::NAT {
3375                None
3376            } else {
3377                Some(format_datetime_ns(*value))
3378            }
3379        }
3380        Scalar::Period(value) => {
3381            if value.ordinal == i64::MIN {
3382                None
3383            } else {
3384                Some(value.calendar_string())
3385            }
3386        }
3387        Scalar::Interval(iv) => Some(format!("{iv}")),
3388    }
3389}
3390
3391fn html_selector(pattern: &str) -> Result<Selector, IoError> {
3392    Selector::parse(pattern).map_err(|err| {
3393        IoError::Html(format!(
3394            "invalid built-in html selector {pattern:?}: {err:?}"
3395        ))
3396    })
3397}
3398
3399fn html_row_cells(row: ElementRef<'_>, cell_selector: &Selector) -> Vec<String> {
3400    row.select(cell_selector)
3401        .map(|cell| cell.text().collect::<String>().trim().to_owned())
3402        .collect()
3403}
3404
3405fn normalize_html_headers(raw_headers: &[String]) -> Result<Vec<String>, IoError> {
3406    if raw_headers.is_empty() {
3407        return Err(IoError::Html(
3408            "html table header row contains no cells".to_owned(),
3409        ));
3410    }
3411
3412    let mut seen = HashSet::new();
3413    let mut headers = Vec::with_capacity(raw_headers.len());
3414    for (idx, raw) in raw_headers.iter().enumerate() {
3415        let name = if raw.trim().is_empty() {
3416            format!("Unnamed: {idx}")
3417        } else {
3418            raw.trim().to_owned()
3419        };
3420        if !seen.insert(name.clone()) {
3421            return Err(IoError::DuplicateColumnName(name));
3422        }
3423        headers.push(name);
3424    }
3425    Ok(headers)
3426}
3427
3428fn html_rows_to_frame(
3429    column_order: Vec<String>,
3430    rows: Vec<Vec<String>>,
3431) -> Result<DataFrame, IoError> {
3432    let width = column_order.len();
3433    if width == 0 {
3434        return Err(IoError::Html(
3435            "html table must contain at least one column".to_owned(),
3436        ));
3437    }
3438
3439    let mut values_by_column = column_order
3440        .iter()
3441        .map(|name| (name.clone(), Vec::with_capacity(rows.len())))
3442        .collect::<BTreeMap<_, _>>();
3443    for (row_idx, row) in rows.iter().enumerate() {
3444        if row.len() > width {
3445            return Err(IoError::Html(format!(
3446                "html row {row_idx} has {} cells but header has {width}",
3447                row.len()
3448            )));
3449        }
3450        for (col_idx, name) in column_order.iter().enumerate() {
3451            let value = row
3452                .get(col_idx)
3453                .map_or(Scalar::Null(NullKind::Null), |cell| parse_scalar(cell));
3454            let column_values = values_by_column.get_mut(name).ok_or_else(|| {
3455                IoError::Html(format!("html column '{name}' was not initialized"))
3456            })?;
3457            column_values.push(value);
3458        }
3459    }
3460
3461    let mut columns = BTreeMap::new();
3462    for name in &column_order {
3463        let values = values_by_column
3464            .remove(name)
3465            .ok_or_else(|| IoError::Html(format!("html column '{name}' has no values")))?;
3466        columns.insert(name.clone(), Column::from_values(values)?);
3467    }
3468    let row_count = i64::try_from(rows.len()).map_err(|_| {
3469        IoError::Html(format!(
3470            "html table row count {} exceeds supported i64 index range",
3471            rows.len()
3472        ))
3473    })?;
3474    Ok(DataFrame::new_with_column_order(
3475        Index::from_i64((0..row_count).collect()),
3476        columns,
3477        column_order,
3478    )?)
3479}
3480
3481fn resolve_csv_index_header(frame: &DataFrame, options: &CsvWriteOptions) -> String {
3482    options
3483        .index_label
3484        .clone()
3485        .or_else(|| frame.index().name().map(ToOwned::to_owned))
3486        .unwrap_or_default()
3487}
3488
3489fn resolve_table_index_header(frame: &DataFrame, index_label: Option<&str>) -> String {
3490    index_label
3491        .map(ToOwned::to_owned)
3492        .or_else(|| frame.index().name().map(ToOwned::to_owned))
3493        .unwrap_or_default()
3494}
3495
3496fn index_label_string(frame: &DataFrame, row_idx: usize) -> Result<String, IoError> {
3497    frame
3498        .index()
3499        .labels()
3500        .get(row_idx)
3501        .map(ToString::to_string)
3502        .ok_or_else(|| {
3503            IoError::Frame(FrameError::CompatibilityRejected(format!(
3504                "index position {row_idx} out of bounds for index length {}",
3505                frame.index().len()
3506            )))
3507        })
3508}
3509
3510/// Derive the column-uniform `to_csv` datetime spec for a DatetimeIndex.
3511///
3512/// Returns `None` unless every label is `Datetime64` (a homogeneous datetime
3513/// index), so non-datetime / mixed indexes keep their default rendering.
3514fn index_datetime_csv_format(frame: &DataFrame) -> Option<DatetimeCsvFormat> {
3515    let labels = frame.index().labels();
3516    let mut any_datetime = false;
3517    let mut date_only = true;
3518    let mut subsec_digits = 0u8;
3519    for label in labels {
3520        let IndexLabel::Datetime64(ns) = label else {
3521            return None;
3522        };
3523        any_datetime = true;
3524        if *ns == i64::MIN {
3525            continue; // NaT
3526        }
3527        let subsec = (ns.rem_euclid(1_000_000_000)) as u32;
3528        if ns.div_euclid(1_000_000_000).rem_euclid(86_400) != 0 || subsec != 0 {
3529            date_only = false;
3530        }
3531        if subsec != 0 {
3532            let digits = if !subsec.is_multiple_of(1_000) {
3533                9
3534            } else if !subsec.is_multiple_of(1_000_000) {
3535                6
3536            } else {
3537                3
3538            };
3539            subsec_digits = subsec_digits.max(digits);
3540        }
3541    }
3542    any_datetime.then_some(DatetimeCsvFormat {
3543        date_only,
3544        subsec_digits,
3545    })
3546}
3547
3548/// CSV index-cell formatter: applies a DatetimeIndex's column-uniform spec when
3549/// present, otherwise identical to `index_label_string`.
3550fn index_label_csv_string(
3551    frame: &DataFrame,
3552    row_idx: usize,
3553    dt_format: Option<DatetimeCsvFormat>,
3554) -> Result<String, IoError> {
3555    if let Some(fmt) = dt_format
3556        && let Some(IndexLabel::Datetime64(ns)) = frame.index().labels().get(row_idx)
3557        && *ns != i64::MIN
3558    {
3559        return Ok(format_datetime_csv(*ns, fmt));
3560    }
3561    index_label_string(frame, row_idx)
3562}
3563
3564/// Column-uniform datetime rendering spec for `to_csv`, mirroring pandas.
3565///
3566/// pandas chooses one format for the whole datetime column: a date-only
3567/// `YYYY-MM-DD` when every value falls exactly on midnight, otherwise
3568/// `YYYY-MM-DD HH:MM:SS` with a fractional-seconds suffix whose width is the
3569/// column's finest sub-second resolution (3 = ms, 6 = µs, 9 = ns; 0 = none).
3570#[derive(Clone, Copy)]
3571struct DatetimeCsvFormat {
3572    date_only: bool,
3573    subsec_digits: u8,
3574}
3575
3576/// Scan a Datetime64 column and derive its column-uniform `to_csv` format.
3577fn datetime_csv_format(column: &Column) -> DatetimeCsvFormat {
3578    let mut date_only = true;
3579    let mut subsec_digits = 0u8;
3580    for value in column.values() {
3581        let Scalar::Datetime64(ns) = value else {
3582            continue;
3583        };
3584        if *ns == Timestamp::NAT {
3585            continue;
3586        }
3587        let subsec = (ns.rem_euclid(1_000_000_000)) as u32;
3588        // Any non-midnight time-of-day OR any sub-second component forces the
3589        // full timestamp form for the entire column.
3590        if ns.div_euclid(1_000_000_000).rem_euclid(86_400) != 0 || subsec != 0 {
3591            date_only = false;
3592        }
3593        if subsec != 0 {
3594            let digits = if !subsec.is_multiple_of(1_000) {
3595                9
3596            } else if !subsec.is_multiple_of(1_000_000) {
3597                6
3598            } else {
3599                3
3600            };
3601            subsec_digits = subsec_digits.max(digits);
3602        }
3603    }
3604    DatetimeCsvFormat {
3605        date_only,
3606        subsec_digits,
3607    }
3608}
3609
3610/// Format one datetime (ns since epoch) under a column's `to_csv` spec.
3611fn format_datetime_csv(nanos: i64, fmt: DatetimeCsvFormat) -> String {
3612    // `format_datetime_ns` now CARRIES sub-second precision (trailing-zero
3613    // trimmed, e.g. ".5"); to_csv instead wants a COLUMN-UNIFORM fixed-width
3614    // fraction (e.g. ".500"), so work from the fixed 19-char
3615    // "YYYY-MM-DD HH:MM:SS" stem (year is always 4 digits across the i64-ns
3616    // range) and apply the column's resolution here. (br-frankenpandas-dt64fmt)
3617    let base = format_datetime_ns(nanos);
3618    if fmt.date_only {
3619        return base[..10].to_owned();
3620    }
3621    let stem = &base[..19];
3622    if fmt.subsec_digits == 0 {
3623        return stem.to_owned();
3624    }
3625    let subsec = (nanos.rem_euclid(1_000_000_000)) as u32;
3626    let frac = subsec / 10u32.pow(9 - u32::from(fmt.subsec_digits));
3627    format!(
3628        "{stem}.{frac:0>width$}",
3629        width = usize::from(fmt.subsec_digits)
3630    )
3631}
3632
3633fn scalar_to_csv_with_na(scalar: &Scalar, na_rep: &str) -> String {
3634    match scalar {
3635        Scalar::Null(_) => na_rep.to_owned(),
3636        Scalar::Float64(v) if v.is_nan() => na_rep.to_owned(),
3637        // pandas to_csv renders floats via Python str(float): whole numbers keep
3638        // ".0" ("1.0", not "1") and extreme magnitudes use signed two-digit
3639        // scientific notation. The table writers (latex/markdown/html) use the
3640        // separate scalar_to_table_with_na path and keep their own formatting.
3641        Scalar::Float64(v) => format_pandas_float(*v),
3642        Scalar::Timedelta64(v) if *v == Timedelta::NAT => na_rep.to_owned(),
3643        other => scalar_to_csv(other),
3644    }
3645}
3646
3647/// CSV cell formatter that applies a column's datetime spec when present;
3648/// otherwise identical to `scalar_to_csv_with_na`.
3649fn scalar_to_csv_cell(
3650    scalar: &Scalar,
3651    na_rep: &str,
3652    dt_format: Option<DatetimeCsvFormat>,
3653) -> String {
3654    if let (Scalar::Datetime64(ns), Some(fmt)) = (scalar, dt_format) {
3655        if *ns == Timestamp::NAT {
3656            return na_rep.to_owned();
3657        }
3658        return format_datetime_csv(*ns, fmt);
3659    }
3660    scalar_to_csv_with_na(scalar, na_rep)
3661}
3662
3663fn scalar_to_table_with_na(scalar: &Scalar, na_rep: &str) -> String {
3664    match scalar {
3665        Scalar::Null(_) => na_rep.to_owned(),
3666        Scalar::Float64(v) if v.is_nan() => na_rep.to_owned(),
3667        // pandas to_string / to_markdown / to_html render a TEMPORAL NaT as the
3668        // literal "NaT": na_rep overrides only float NaN, NOT NaT. Verified vs
3669        // pandas 2.2.3 — `df.to_html(na_rep='X')` keeps "NaT" for datetime/
3670        // timedelta but shows "X" for NaN. (Datetime64/Period NaT previously
3671        // fell through to scalar_to_csv -> "" blank cells; an earlier fix wrongly
3672        // routed all temporal NaT to na_rep.) to_latex DIFFERS (collapses NaT to
3673        // na_rep) and is corrected in scalar_to_latex_cell. (br-frankenpandas-tblnat)
3674        Scalar::Timedelta64(v) if *v == Timedelta::NAT => "NaT".to_owned(),
3675        Scalar::Datetime64(v) if *v == Timestamp::NAT => "NaT".to_owned(),
3676        Scalar::Period(p) if p.ordinal == i64::MIN => "NaT".to_owned(),
3677        other => scalar_to_csv(other),
3678    }
3679}
3680
3681/// LaTeX cell formatter. pandas `to_latex` renders floats with its default
3682/// `float_format` of six decimal places (`1.0` -> "1.000000", `0.1234567` ->
3683/// "0.123457"), unlike the str(float) form used by to_csv/to_html. Integers and
3684/// other scalars keep the shared table formatting. Verified vs pandas 2.2.3.
3685fn scalar_to_latex_cell(scalar: &Scalar, na_rep: &str) -> String {
3686    match scalar {
3687        Scalar::Float64(v) if v.is_nan() => na_rep.to_owned(),
3688        // pandas to_latex collapses ALL missing — float NaN AND temporal NaT —
3689        // to na_rep (default "NaN"), unlike to_string/to_html which keep "NaT".
3690        // Verified vs pandas 2.2.3. Override here before delegating, since
3691        // scalar_to_table_with_na now renders temporal NaT as "NaT" for the
3692        // markdown/string family. (br-frankenpandas-tblnat)
3693        Scalar::Timedelta64(v) if *v == Timedelta::NAT => na_rep.to_owned(),
3694        Scalar::Datetime64(v) if *v == Timestamp::NAT => na_rep.to_owned(),
3695        Scalar::Period(p) if p.ordinal == i64::MIN => na_rep.to_owned(),
3696        // Rust `{:.6}` matches Python `%.6f` (round-half-to-even) and renders
3697        // infinities as "inf"/"-inf", exactly as pandas to_latex does.
3698        Scalar::Float64(v) => format!("{v:.6}"),
3699        other => scalar_to_table_with_na(other, na_rep),
3700    }
3701}
3702
3703fn push_markdown_row(out: &mut String, cells: &[String]) {
3704    out.push('|');
3705    for cell in cells {
3706        out.push(' ');
3707        out.push_str(&escape_markdown_table_cell(cell));
3708        out.push_str(" |");
3709    }
3710    out.push('\n');
3711}
3712
3713fn escape_markdown_table_cell(value: &str) -> String {
3714    let mut escaped = String::with_capacity(value.len());
3715    for ch in value.chars() {
3716        match ch {
3717            '\\' => escaped.push_str("\\\\"),
3718            '|' => escaped.push_str("\\|"),
3719            '\n' | '\r' => escaped.push(' '),
3720            _ => escaped.push(ch),
3721        }
3722    }
3723    escaped
3724}
3725
3726fn push_latex_row(out: &mut String, cells: &[String], escape: bool) {
3727    for (idx, cell) in cells.iter().enumerate() {
3728        if idx > 0 {
3729            out.push_str(" & ");
3730        }
3731        if escape {
3732            out.push_str(&escape_latex_table_cell(cell));
3733        } else {
3734            out.push_str(cell);
3735        }
3736    }
3737    out.push_str(" \\\\\n");
3738}
3739
3740fn escape_latex_table_cell(value: &str) -> String {
3741    let mut escaped = String::with_capacity(value.len());
3742    for ch in value.chars() {
3743        match ch {
3744            '&' => escaped.push_str("\\&"),
3745            '%' => escaped.push_str("\\%"),
3746            '$' => escaped.push_str("\\$"),
3747            '#' => escaped.push_str("\\#"),
3748            '_' => escaped.push_str("\\_"),
3749            '{' => escaped.push_str("\\{"),
3750            '}' => escaped.push_str("\\}"),
3751            '~' => escaped.push_str("\\textasciitilde{}"),
3752            '^' => escaped.push_str("\\textasciicircum{}"),
3753            '\\' => escaped.push_str("\\textbackslash{}"),
3754            '\n' | '\r' => escaped.push(' '),
3755            _ => escaped.push(ch),
3756        }
3757    }
3758    escaped
3759}
3760
3761fn is_pandas_default_na(s: &str) -> bool {
3762    // Default NA values recognized by pandas read_csv.
3763    // See: <https://pandas.pydata.org/docs/reference/api/pandas.read_csv.html>
3764    matches!(
3765        s,
3766        "" | "#N/A"
3767            | "#N/A N/A"
3768            | "#NA"
3769            | "-1.#IND"
3770            | "-1.#QNAN"
3771            | "-NaN"
3772            | "-nan"
3773            | "1.#IND"
3774            | "1.#QNAN"
3775            | "<NA>"
3776            | "N/A"
3777            | "NA"
3778            | "NULL"
3779            | "NaN"
3780            | "None"
3781            | "n/a"
3782            | "nan"
3783            | "null"
3784    )
3785}
3786
3787fn parse_scalar(field: &str) -> Scalar {
3788    // pandas read_csv tolerates surrounding whitespace ONLY for numeric
3789    // inference. NA markers and booleans must match the field EXACTLY (a
3790    // padded " NA " or "true " is NOT null/bool), and plain strings keep their
3791    // original whitespace. Verified vs live pandas 2.2.3: " abc " stays
3792    // " abc "; "true " / " NA " stay strings; but " 1 " parses to Int64(1).
3793    if is_pandas_default_na(field) {
3794        return Scalar::Null(NullKind::Null);
3795    }
3796
3797    let trimmed = field.trim();
3798    if let Ok(value) = trimmed.parse::<i64>() {
3799        return Scalar::Int64(value);
3800    }
3801    if let Ok(value) = trimmed.parse::<f64>() {
3802        return Scalar::Float64(value);
3803    }
3804    if field.eq_ignore_ascii_case("true") {
3805        return Scalar::Bool(true);
3806    }
3807    if field.eq_ignore_ascii_case("false") {
3808        return Scalar::Bool(false);
3809    }
3810
3811    Scalar::Utf8(field.to_owned())
3812}
3813
3814/// Format an f64 the way pandas `to_csv` does (Python `str(float)`): keep a
3815/// trailing ".0" on whole numbers ("1.0", not Rust Display's "1"), shortest
3816/// round-trip for decimals, and signed two-digit scientific notation
3817/// ("1e+16" / "1e-05") for very large / small magnitudes. Verified vs live
3818/// pandas 2.2.3. NaN must be handled by the caller (it becomes na_rep).
3819fn format_pandas_float(v: f64) -> String {
3820    let mut out = String::new();
3821    write_pandas_float(&mut out, v);
3822    out
3823}
3824
3825/// Append the pandas `str(float)` rendering of `v` directly to `out`, without
3826/// the per-call `String` allocation `format_pandas_float` makes — the hot path
3827/// for the all-numeric CSV writer (br-frankenpandas-qk2i9).
3828///
3829/// Finite values first try `ryu::Buffer` to bypass Rust's generic formatting
3830/// machinery. Boundary spellings where `ryu` and Python choose different fixed
3831/// vs scientific notation deopt to the Debug-based fallback below.
3832fn write_pandas_float(out: &mut String, v: f64) {
3833    if v.is_finite() {
3834        let mut buffer = ryu::Buffer::new();
3835        let rendered = buffer.format_finite(v);
3836        let has_exponent = rendered.contains('e');
3837        let is_zero = v.to_bits() << 1 == 0;
3838        if has_exponent || is_zero || v.abs() >= 1e-4 {
3839            append_pandas_normalized_float(out, rendered);
3840            return;
3841        }
3842    }
3843
3844    write_pandas_float_debug_fallback(out, v);
3845}
3846
3847fn append_pandas_normalized_float(out: &mut String, rendered: &str) {
3848    let Some(e) = rendered.find('e') else {
3849        out.push_str(rendered);
3850        if !rendered.contains('.') {
3851            out.push_str(".0");
3852        }
3853        return;
3854    };
3855
3856    out.push_str(&rendered[..=e]);
3857    let exp = &rendered[e + 1..];
3858    let (sign, digits) = match exp.strip_prefix('-') {
3859        Some(d) => ('-', d),
3860        None => ('+', exp.strip_prefix('+').unwrap_or(exp)),
3861    };
3862    out.push(sign);
3863    if digits.len() < 2 {
3864        out.push('0');
3865    }
3866    out.push_str(digits);
3867}
3868
3869/// Rust's Debug formatter gives the shortest round-trip representation and,
3870/// unlike Display, keeps ".0" on whole numbers and switches to scientific
3871/// notation at Python's repr boundaries. Only the exponent spelling differs
3872/// (Rust "1e16"/"1e-5" vs Python "1e+16"/"1e-05"), so the rare sci-notation case
3873/// is normalized in place.
3874fn write_pandas_float_debug_fallback(out: &mut String, v: f64) {
3875    use std::fmt::Write as _;
3876    let start = out.len();
3877    let _ = write!(out, "{v:?}");
3878    // Common case (no scientific notation): `{v:?}` is already the pandas form.
3879    let Some(rel_e) = out[start..].find('e') else {
3880        return;
3881    };
3882    // Sci notation: normalize the exponent to Python's signed, >=2-digit form.
3883    let e = start + rel_e;
3884    let exp = out.split_off(e + 1); // everything after 'e'; `out` keeps "<mantissa>e"
3885    let (sign, digits) = match exp.strip_prefix('-') {
3886        Some(d) => ('-', d),
3887        None => ('+', exp.strip_prefix('+').unwrap_or(&exp)),
3888    };
3889    out.push(sign);
3890    if digits.len() < 2 {
3891        out.push('0');
3892    }
3893    out.push_str(digits);
3894}
3895
3896fn scalar_to_csv(scalar: &Scalar) -> String {
3897    match scalar {
3898        Scalar::Null(_) => String::new(),
3899        // pandas to_csv writes capitalized True/False (matches fp-frame::to_csv).
3900        Scalar::Bool(v) => if *v { "True" } else { "False" }.to_string(),
3901        Scalar::Int64(v) => v.to_string(),
3902        Scalar::Float64(v) => {
3903            if v.is_nan() {
3904                String::new()
3905            } else {
3906                v.to_string()
3907            }
3908        }
3909        Scalar::Utf8(v) => v.clone(),
3910        Scalar::Timedelta64(v) => {
3911            if *v == Timedelta::NAT {
3912                String::new()
3913            } else {
3914                Timedelta::format(*v)
3915            }
3916        }
3917        Scalar::Datetime64(v) => {
3918            if *v == Timestamp::NAT {
3919                String::new()
3920            } else {
3921                format_datetime_ns(*v)
3922            }
3923        }
3924        Scalar::Period(p) => {
3925            if p.ordinal == i64::MIN {
3926                String::new()
3927            } else {
3928                p.calendar_string()
3929            }
3930        }
3931        Scalar::Interval(iv) => format!("{iv}"),
3932    }
3933}
3934
3935/// Parse a field with NA value handling respecting pandas options.
3936///
3937/// - `na_filter`: If false, skip NA detection entirely for performance
3938/// - `keep_default_na`: If true, use pandas default NA values
3939/// - `na_set` / `true_set` / `false_set`: Pre-built HashSets for O(1)
3940///   membership lookup. Per br-frankenpandas-b67a3 (sister to br-fcf5d),
3941///   these were previously `&[String]` slices scanned linearly per cell;
3942///   now built once at the parent CSV reader and passed in.
3943#[allow(clippy::too_many_arguments)]
3944fn parse_scalar_with_options(
3945    field: &str,
3946    na_filter: bool,
3947    keep_default_na: bool,
3948    na_set: &HashSet<&str>,
3949    true_set: &HashSet<&str>,
3950    false_set: &HashSet<&str>,
3951    decimal: u8,
3952    thousands: Option<u8>,
3953) -> Scalar {
3954    // pandas only tolerates surrounding whitespace for NUMERIC inference; NA
3955    // markers, booleans, and plain strings match/keep the field EXACTLY (a
3956    // padded " NA " or "true " stays a string). See parse_scalar.
3957    let trimmed = field.trim();
3958
3959    // Check NA values only if na_filter is enabled
3960    if na_filter {
3961        let is_default_na = keep_default_na && is_pandas_default_na(field);
3962        let is_custom_na = na_set.contains(field);
3963        if is_default_na || is_custom_na {
3964            return Scalar::Null(NullKind::Null);
3965        }
3966    }
3967
3968    // `thousands` is silently ignored if it equals the decimal separator,
3969    // matching pandas semantics.
3970    let thousands_effective = thousands.filter(|t| *t != decimal);
3971    let numeric_candidate: Cow<'_, str> = if let Some(t) = thousands_effective {
3972        let ch = char::from(t);
3973        if trimmed.contains(ch) {
3974            Cow::Owned(trimmed.replace(ch, ""))
3975        } else {
3976            Cow::Borrowed(trimmed)
3977        }
3978    } else {
3979        Cow::Borrowed(trimmed)
3980    };
3981
3982    if let Ok(value) = numeric_candidate.as_ref().parse::<i64>() {
3983        return Scalar::Int64(value);
3984    }
3985
3986    let decimal_ch = char::from(decimal);
3987    let float_candidate: Cow<'_, str> = if decimal == b'.' {
3988        Cow::Borrowed(numeric_candidate.as_ref())
3989    } else if numeric_candidate.contains(decimal_ch) {
3990        Cow::Owned(numeric_candidate.replace(decimal_ch, "."))
3991    } else {
3992        Cow::Borrowed(numeric_candidate.as_ref())
3993    };
3994    if let Ok(value) = float_candidate.as_ref().parse::<f64>() {
3995        return Scalar::Float64(value);
3996    }
3997
3998    if true_set.contains(field) {
3999        return Scalar::Bool(true);
4000    }
4001    if false_set.contains(field) {
4002        return Scalar::Bool(false);
4003    }
4004
4005    if field.eq_ignore_ascii_case("true") {
4006        return Scalar::Bool(true);
4007    }
4008    if field.eq_ignore_ascii_case("false") {
4009        return Scalar::Bool(false);
4010    }
4011    Scalar::Utf8(field.to_owned())
4012}
4013
4014fn reject_duplicate_headers(headers: &[String]) -> Result<(), IoError> {
4015    let mut used = BTreeSet::new();
4016    for name in headers {
4017        if !used.insert(name.clone()) {
4018            return Err(IoError::DuplicateColumnName(name.clone()));
4019        }
4020    }
4021    Ok(())
4022}
4023
4024fn validate_usecols(headers: &[String], usecols: &[String]) -> Result<(), IoError> {
4025    let header_set: std::collections::BTreeSet<&String> = headers.iter().collect();
4026    let mut missing = Vec::new();
4027    for name in usecols {
4028        if !header_set.contains(name) {
4029            missing.push(name.clone());
4030        }
4031    }
4032    if missing.is_empty() {
4033        Ok(())
4034    } else {
4035        Err(IoError::MissingUsecols(missing))
4036    }
4037}
4038
4039fn validate_parse_dates(headers: &[String], parse_dates: &[String]) -> Result<(), IoError> {
4040    let header_set: std::collections::BTreeSet<&String> = headers.iter().collect();
4041    let mut missing = Vec::new();
4042    for name in parse_dates {
4043        if !header_set.contains(name) {
4044            missing.push(name.clone());
4045        }
4046    }
4047    if missing.is_empty() {
4048        Ok(())
4049    } else {
4050        Err(IoError::MissingParseDateColumns(missing))
4051    }
4052}
4053
4054fn validate_parse_date_combinations(
4055    headers: &[String],
4056    parse_date_combinations: &[Vec<String>],
4057) -> Result<(), IoError> {
4058    let header_set: std::collections::BTreeSet<&String> = headers.iter().collect();
4059    let mut missing = BTreeSet::new();
4060    for combo in parse_date_combinations {
4061        for name in combo {
4062            if !header_set.contains(name) {
4063                missing.insert(name.clone());
4064            }
4065        }
4066    }
4067    if missing.is_empty() {
4068        Ok(())
4069    } else {
4070        Err(IoError::MissingParseDateColumns(
4071            missing.into_iter().collect(),
4072        ))
4073    }
4074}
4075
4076fn apply_parse_dates_to_scalar_columns(
4077    headers: &[String],
4078    columns: &mut [Vec<Scalar>],
4079    parse_dates: &[String],
4080) -> Result<(), IoError> {
4081    if parse_dates.is_empty() {
4082        return Ok(());
4083    }
4084
4085    validate_parse_dates(headers, parse_dates)?;
4086
4087    for column_name in parse_dates {
4088        let Some(column_idx) = headers.iter().position(|header| header == column_name) else {
4089            continue;
4090        };
4091
4092        if let Some(parsed) = parse_csv_datetime_values(&columns[column_idx])? {
4093            columns[column_idx] = parsed;
4094        }
4095    }
4096
4097    Ok(())
4098}
4099
4100#[allow(clippy::too_many_arguments)]
4101fn apply_csv_parse_dates(
4102    headers: &[String],
4103    columns: &mut [Vec<Scalar>],
4104    raw_columns: &[Vec<String>],
4105    deferred_parse_date_columns: &[bool],
4106    parse_dates: &[String],
4107    options: &CsvReadOptions,
4108    na_set: &HashSet<&str>,
4109    true_set: &HashSet<&str>,
4110    false_set: &HashSet<&str>,
4111) -> Result<(), IoError> {
4112    if parse_dates.is_empty() {
4113        return Ok(());
4114    }
4115
4116    validate_parse_dates(headers, parse_dates)?;
4117
4118    for column_name in parse_dates {
4119        let Some(column_idx) = headers.iter().position(|header| header == column_name) else {
4120            continue;
4121        };
4122
4123        let parsed = if deferred_parse_date_columns
4124            .get(column_idx)
4125            .copied()
4126            .unwrap_or(false)
4127        {
4128            if let Some(parsed) = parse_csv_fixed_naive_datetime_fields(
4129                &raw_columns[column_idx],
4130                options.na_filter,
4131                options.keep_default_na,
4132                na_set,
4133            ) {
4134                Some(parsed)
4135            } else {
4136                columns[column_idx] = parse_csv_scalar_fields_with_options(
4137                    &raw_columns[column_idx],
4138                    options,
4139                    na_set,
4140                    true_set,
4141                    false_set,
4142                );
4143                parse_csv_datetime_values(&columns[column_idx])?
4144            }
4145        } else {
4146            parse_csv_datetime_values(&columns[column_idx])?
4147        };
4148
4149        if let Some(parsed) = parsed {
4150            columns[column_idx] = parsed;
4151        }
4152    }
4153
4154    Ok(())
4155}
4156
4157fn deferred_parse_date_column_mask(headers: &[String], options: &CsvReadOptions) -> Vec<bool> {
4158    let Some(parse_dates) = options.parse_dates.as_deref() else {
4159        return vec![false; headers.len()];
4160    };
4161    if parse_dates.is_empty()
4162        || options.parse_date_combinations.is_some()
4163        || options.parse_date_combinations_named.is_some()
4164    {
4165        return vec![false; headers.len()];
4166    }
4167
4168    headers
4169        .iter()
4170        .map(|header| parse_dates.iter().any(|name| name == header))
4171        .collect()
4172}
4173
4174fn parse_csv_fixed_naive_datetime_fields(
4175    fields: &[String],
4176    na_filter: bool,
4177    keep_default_na: bool,
4178    na_set: &HashSet<&str>,
4179) -> Option<Vec<Scalar>> {
4180    let mut parsed = Vec::with_capacity(fields.len());
4181    let mut saw_datetime = false;
4182
4183    for field in fields {
4184        if na_filter
4185            && ((keep_default_na && is_pandas_default_na(field)) || na_set.contains(field.as_str()))
4186        {
4187            parsed.push(Scalar::Datetime64(Timestamp::NAT));
4188            continue;
4189        }
4190
4191        parsed.push(Scalar::Datetime64(parse_fixed_naive_csv_datetime_nanos(
4192            field,
4193        )?));
4194        saw_datetime = true;
4195    }
4196
4197    saw_datetime.then_some(parsed)
4198}
4199
4200fn parse_csv_scalar_fields_with_options(
4201    fields: &[String],
4202    options: &CsvReadOptions,
4203    na_set: &HashSet<&str>,
4204    true_set: &HashSet<&str>,
4205    false_set: &HashSet<&str>,
4206) -> Vec<Scalar> {
4207    fields
4208        .iter()
4209        .map(|field| {
4210            parse_scalar_with_options(
4211                field,
4212                options.na_filter,
4213                options.keep_default_na,
4214                na_set,
4215                true_set,
4216                false_set,
4217                options.decimal,
4218                options.thousands,
4219            )
4220        })
4221        .collect()
4222}
4223
4224fn parse_sql_float_text(text: &str) -> Option<f64> {
4225    let trimmed = text.trim();
4226    if trimmed.is_empty() {
4227        return None;
4228    }
4229
4230    let mut normalized = String::with_capacity(trimmed.len());
4231    for ch in trimmed.chars() {
4232        match ch {
4233            ',' => {}
4234            '$' if normalized.is_empty() || normalized == "+" || normalized == "-" => {}
4235            _ => normalized.push(ch),
4236        }
4237    }
4238
4239    if matches!(normalized.as_str(), "" | "+" | "-" | ".") {
4240        return None;
4241    }
4242
4243    let value = normalized.parse::<f64>().ok()?;
4244    value.is_finite().then_some(value)
4245}
4246
4247fn apply_sql_coerce_float(columns: &mut [Vec<Scalar>]) {
4248    for column in columns {
4249        let mut saw_text_float = false;
4250        let mut parsed_values = Vec::with_capacity(column.len());
4251
4252        for value in column.iter() {
4253            match value {
4254                Scalar::Utf8(text) => {
4255                    let Some(parsed) = parse_sql_float_text(text) else {
4256                        saw_text_float = false;
4257                        parsed_values.clear();
4258                        break;
4259                    };
4260                    saw_text_float = true;
4261                    parsed_values.push(Some(parsed));
4262                }
4263                Scalar::Null(_) | Scalar::Int64(_) | Scalar::Float64(_) => {
4264                    parsed_values.push(None);
4265                }
4266                Scalar::Bool(_)
4267                | Scalar::Timedelta64(_)
4268                | Scalar::Datetime64(_)
4269                | Scalar::Period(_)
4270                | Scalar::Interval(_) => {
4271                    saw_text_float = false;
4272                    parsed_values.clear();
4273                    break;
4274                }
4275            }
4276        }
4277
4278        if !saw_text_float {
4279            continue;
4280        }
4281
4282        for (value, parsed) in column.iter_mut().zip(parsed_values) {
4283            if let Some(parsed) = parsed {
4284                *value = Scalar::Float64(parsed);
4285            } else if value.is_missing() {
4286                *value = Scalar::Null(NullKind::NaN);
4287            }
4288        }
4289    }
4290}
4291
4292fn combine_parse_date_values(column_group: &[Vec<Scalar>]) -> Vec<Scalar> {
4293    let len = column_group.first().map_or(0, Vec::len);
4294    let mut combined = Vec::with_capacity(len);
4295
4296    for row in 0..len {
4297        if column_group
4298            .iter()
4299            .any(|column| matches!(column[row], Scalar::Null(_)))
4300        {
4301            combined.push(Scalar::Null(NullKind::NaT));
4302            continue;
4303        }
4304
4305        let joined = column_group
4306            .iter()
4307            .map(|column| match &column[row] {
4308                Scalar::Utf8(value) => value.clone(),
4309                other => other.to_string(),
4310            })
4311            .collect::<Vec<_>>()
4312            .join(" ");
4313        combined.push(Scalar::Utf8(joined));
4314    }
4315
4316    combined
4317}
4318
4319fn apply_one_parse_date_combination(
4320    headers: &mut Vec<String>,
4321    columns: &mut Vec<Vec<Scalar>>,
4322    combined_name: String,
4323    sources: &[String],
4324) -> Result<(), IoError> {
4325    let mut positions = sources
4326        .iter()
4327        .map(|name| {
4328            headers
4329                .iter()
4330                .position(|header| header == name)
4331                .ok_or_else(|| IoError::MissingParseDateColumns(vec![name.clone()]))
4332        })
4333        .collect::<Result<Vec<_>, _>>()?;
4334    positions.sort_unstable();
4335
4336    let combined_values = combine_parse_date_values(
4337        &positions
4338            .iter()
4339            .map(|&idx| columns[idx].clone())
4340            .collect::<Vec<_>>(),
4341    );
4342    let parsed_values = match parse_csv_datetime_values(&combined_values)? {
4343        Some(parsed) => parsed,
4344        None => combined_values,
4345    };
4346
4347    for idx in positions.iter().rev() {
4348        headers.remove(*idx);
4349        columns.remove(*idx);
4350    }
4351    headers.insert(positions[0], combined_name);
4352    columns.insert(positions[0], parsed_values);
4353    Ok(())
4354}
4355
4356fn parse_csv_datetime_values(values: &[Scalar]) -> Result<Option<Vec<Scalar>>, IoError> {
4357    if let Some(parsed) = parse_csv_fixed_naive_datetime_values(values) {
4358        return Ok(Some(parsed));
4359    }
4360
4361    // pandas pd.read_csv(parse_dates=[col]) parses each value on its own —
4362    // a column with mixed naive ("2024-01-15 10:30:00") and aware
4363    // ("2024-01-15T10:30:00Z") entries normalizes each value
4364    // independently. The ToDatetimeOptions default `infer_mixed_timezone:
4365    // true` locks the column to the FIRST inferred pattern and rejects
4366    // any value that doesn't match it, which causes parse_failed=true and
4367    // leaves the column as raw strings even though every individual value
4368    // is parseable. Set it explicitly to false so each value goes through
4369    // parse_datetime_string, which already handles both naive and aware.
4370    let parsed = to_datetime_values_with_options(
4371        values,
4372        ToDatetimeOptions {
4373            infer_mixed_timezone: false,
4374            // pandas keeps a mixed naive+tz-aware parse_dates column as object
4375            // rather than datetime64 (br-frankenpandas-unz0t).
4376            mixed_tz_as_object: true,
4377            ..ToDatetimeOptions::default()
4378        },
4379    )?;
4380    let parse_failed = values
4381        .iter()
4382        .zip(parsed.iter())
4383        .any(|(original, parsed)| !original.is_missing() && parsed.is_missing());
4384
4385    if parse_failed {
4386        Ok(None)
4387    } else {
4388        Ok(Some(parsed))
4389    }
4390}
4391
4392fn parse_csv_fixed_naive_datetime_values(values: &[Scalar]) -> Option<Vec<Scalar>> {
4393    let mut parsed = Vec::with_capacity(values.len());
4394    let mut saw_datetime = false;
4395
4396    for value in values {
4397        match value {
4398            Scalar::Utf8(text) => {
4399                parsed.push(Scalar::Datetime64(parse_fixed_naive_csv_datetime_nanos(
4400                    text,
4401                )?));
4402                saw_datetime = true;
4403            }
4404            Scalar::Null(_) => parsed.push(Scalar::Datetime64(Timestamp::NAT)),
4405            _ => return None,
4406        }
4407    }
4408
4409    saw_datetime.then_some(parsed)
4410}
4411
4412fn parse_fixed_naive_csv_datetime_nanos(value: &str) -> Option<i64> {
4413    let bytes = value.trim().as_bytes();
4414    let (year, month, day, hour, minute, second) = match bytes.len() {
4415        10 => (
4416            parse_4_digits(bytes, 0)?,
4417            parse_2_digits(bytes, 5)?,
4418            parse_2_digits(bytes, 8)?,
4419            0,
4420            0,
4421            0,
4422        ),
4423        19 => (
4424            parse_4_digits(bytes, 0)?,
4425            parse_2_digits(bytes, 5)?,
4426            parse_2_digits(bytes, 8)?,
4427            parse_2_digits(bytes, 11)?,
4428            parse_2_digits(bytes, 14)?,
4429            parse_2_digits(bytes, 17)?,
4430        ),
4431        _ => return None,
4432    };
4433
4434    if bytes.get(4) != Some(&b'-')
4435        || bytes.get(7) != Some(&b'-')
4436        || (bytes.len() == 19
4437            && (bytes.get(10) != Some(&b' ')
4438                || bytes.get(13) != Some(&b':')
4439                || bytes.get(16) != Some(&b':')))
4440        || !valid_ymd(year, month, day)
4441        || hour > 23
4442        || minute > 59
4443        || second > 59
4444    {
4445        return None;
4446    }
4447
4448    let days = days_from_ymd(year, month, day);
4449    days.checked_mul(Timedelta::NANOS_PER_DAY)?
4450        .checked_add(hour.checked_mul(Timedelta::NANOS_PER_HOUR)?)?
4451        .checked_add(minute.checked_mul(Timedelta::NANOS_PER_MIN)?)?
4452        .checked_add(second.checked_mul(Timedelta::NANOS_PER_SEC)?)
4453}
4454
4455fn parse_2_digits(bytes: &[u8], offset: usize) -> Option<i64> {
4456    let hi = *bytes.get(offset)?;
4457    let lo = *bytes.get(offset + 1)?;
4458    if !hi.is_ascii_digit() || !lo.is_ascii_digit() {
4459        return None;
4460    }
4461    Some((i64::from(hi - b'0') * 10) + i64::from(lo - b'0'))
4462}
4463
4464fn parse_4_digits(bytes: &[u8], offset: usize) -> Option<i64> {
4465    let hi = parse_2_digits(bytes, offset)?;
4466    let lo = parse_2_digits(bytes, offset + 2)?;
4467    Some((hi * 100) + lo)
4468}
4469
4470fn valid_ymd(year: i64, month: i64, day: i64) -> bool {
4471    if !(1..=9999).contains(&year) || !(1..=12).contains(&month) {
4472        return false;
4473    }
4474    let max_day = match month {
4475        1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
4476        4 | 6 | 9 | 11 => 30,
4477        2 if is_leap_year(year) => 29,
4478        2 => 28,
4479        _ => return false,
4480    };
4481    (1..=max_day).contains(&day)
4482}
4483
4484fn is_leap_year(year: i64) -> bool {
4485    (year % 4 == 0 && year % 100 != 0) || year % 400 == 0
4486}
4487
4488fn days_from_ymd(year: i64, month: i64, day: i64) -> i64 {
4489    let y = if month <= 2 { year - 1 } else { year };
4490    let era = if y >= 0 { y } else { y - 399 } / 400;
4491    let yoe = y - (era * 400);
4492    let doy = (153 * (if month > 2 { month - 3 } else { month + 9 }) + 2) / 5 + day - 1;
4493    let doe = (yoe * 365) + (yoe / 4) - (yoe / 100) + doy;
4494    (era * 146_097) + doe - 719_468
4495}
4496
4497fn pandas_csv_numeric_column_requires_float(values: &[Scalar]) -> bool {
4498    // DISC-011: Nullable extension Int64 dtype parity.
4499    // Previously: Int64 columns with nulls promoted to Float64 for CSV output.
4500    // Now: Int64 columns preserve integer encoding; only promote when the
4501    // column actually contains Float64 values (mixed Int64/Float64 → Float64).
4502    let mut saw_int = false;
4503    let mut saw_float = false;
4504
4505    for value in values {
4506        match value {
4507            Scalar::Int64(_) => saw_int = true,
4508            Scalar::Float64(_) => saw_float = true,
4509            Scalar::Null(_) => {}
4510            Scalar::Bool(_)
4511            | Scalar::Utf8(_)
4512            | Scalar::Timedelta64(_)
4513            | Scalar::Datetime64(_)
4514            | Scalar::Period(_)
4515            | Scalar::Interval(_) => {
4516                return false;
4517            }
4518        }
4519    }
4520
4521    saw_int && saw_float
4522}
4523
4524fn apply_pandas_csv_numeric_promotions(columns: &mut [Vec<Scalar>]) {
4525    for column in columns {
4526        if !pandas_csv_numeric_column_requires_float(column) {
4527            continue;
4528        }
4529
4530        for value in column {
4531            if let Scalar::Int64(v) = value {
4532                *value = Scalar::Float64(*v as f64);
4533            }
4534        }
4535    }
4536}
4537
4538fn apply_parse_date_combinations(
4539    headers: &mut Vec<String>,
4540    columns: &mut Vec<Vec<Scalar>>,
4541    parse_date_combinations: &[Vec<String>],
4542) -> Result<(), IoError> {
4543    if parse_date_combinations.is_empty() {
4544        return Ok(());
4545    }
4546
4547    validate_parse_date_combinations(headers, parse_date_combinations)?;
4548
4549    for combination in parse_date_combinations {
4550        if combination.is_empty() {
4551            continue;
4552        }
4553        let combined_name = combination.join("_");
4554        apply_one_parse_date_combination(headers, columns, combined_name, combination)?;
4555    }
4556
4557    Ok(())
4558}
4559
4560fn apply_parse_date_combinations_named(
4561    headers: &mut Vec<String>,
4562    columns: &mut Vec<Vec<Scalar>>,
4563    parse_date_combinations_named: &[(String, Vec<String>)],
4564) -> Result<(), IoError> {
4565    if parse_date_combinations_named.is_empty() {
4566        return Ok(());
4567    }
4568
4569    let mut assigned_names: std::collections::HashSet<String> = std::collections::HashSet::new();
4570    for (new_name, _) in parse_date_combinations_named {
4571        if !assigned_names.insert(new_name.clone()) {
4572            return Err(IoError::DuplicateColumnName(new_name.clone()));
4573        }
4574    }
4575
4576    let combos_only: Vec<Vec<String>> = parse_date_combinations_named
4577        .iter()
4578        .map(|(_, sources)| sources.clone())
4579        .collect();
4580    validate_parse_date_combinations(headers, &combos_only)?;
4581
4582    for (new_name, sources) in parse_date_combinations_named {
4583        if sources.is_empty() {
4584            continue;
4585        }
4586        apply_one_parse_date_combination(headers, columns, new_name.clone(), sources)?;
4587    }
4588
4589    Ok(())
4590}
4591
4592#[allow(clippy::too_many_arguments)]
4593fn append_csv_record(
4594    columns: &mut [Vec<Scalar>],
4595    raw_columns: &mut [Vec<String>],
4596    record: &StringRecord,
4597    options: &CsvReadOptions,
4598    na_set: &HashSet<&str>,
4599    true_set: &HashSet<&str>,
4600    false_set: &HashSet<&str>,
4601    deferred_parse_date_columns: &[bool],
4602) {
4603    for (idx, col) in columns.iter_mut().enumerate() {
4604        let field = record.get(idx).unwrap_or_default();
4605        if deferred_parse_date_columns
4606            .get(idx)
4607            .copied()
4608            .unwrap_or(false)
4609        {
4610            col.push(Scalar::Null(NullKind::Null));
4611        } else {
4612            col.push(parse_scalar_with_options(
4613                field,
4614                options.na_filter,
4615                options.keep_default_na,
4616                na_set,
4617                true_set,
4618                false_set,
4619                options.decimal,
4620                options.thousands,
4621            ));
4622        }
4623        // Keep the verbatim field so an object-fallback column can preserve the
4624        // original literal like pandas (see build_csv_object_aware_column).
4625        raw_columns[idx].push(field.to_owned());
4626    }
4627}
4628
4629fn should_skip_bad_csv_record(
4630    record: &StringRecord,
4631    expected_fields: usize,
4632    on_bad_lines: CsvOnBadLines,
4633) -> bool {
4634    if record.len() <= expected_fields {
4635        return false;
4636    }
4637
4638    match on_bad_lines {
4639        CsvOnBadLines::Error => false,
4640        CsvOnBadLines::Warn => {
4641            eprintln!(
4642                "Skipping bad CSV line: expected {expected_fields} fields, found {}",
4643                record.len()
4644            );
4645            true
4646        }
4647        CsvOnBadLines::Skip => true,
4648    }
4649}
4650
4651// ── CSV with options ───────────────────────────────────────────────────
4652
4653/// Strip ASCII spaces (0x20) at each unquoted field start for `skipinitialspace`
4654/// (br-frankenpandas-i4h5g). A field starts at line start and immediately after a
4655/// delimiter; spaces there are dropped until the first non-space byte. Quote
4656/// state is tracked so spaces inside quoted fields (and delimiters/terminators
4657/// inside quotes) are preserved, and a `   "x,y"` field becomes the quoted value.
4658/// `doublequote` (a doubled quotechar = literal quote, stay in quote) and
4659/// `escapechar` (next byte is literal) are honored. Only ASCII 0x20 is stripped
4660/// (tabs are kept, matching pandas); trailing spaces are preserved. Every byte
4661/// other than the stripped leading spaces is copied verbatim, so the output is
4662/// valid UTF-8 and the downstream parse is byte-identical except for the removed
4663/// leading spaces.
4664fn apply_skipinitialspace(
4665    input: &str,
4666    delimiter: u8,
4667    quotechar: u8,
4668    doublequote: bool,
4669    escapechar: Option<u8>,
4670    lineterminator: Option<u8>,
4671) -> String {
4672    let bytes = input.as_bytes();
4673    let mut out: Vec<u8> = Vec::with_capacity(bytes.len());
4674    let is_terminator = |b: u8| match lineterminator {
4675        Some(t) => b == t,
4676        None => b == b'\n' || b == b'\r',
4677    };
4678    let mut in_quote = false;
4679    let mut at_field_start = true;
4680    let mut i = 0;
4681    while i < bytes.len() {
4682        let b = bytes[i];
4683        if in_quote {
4684            out.push(b);
4685            if let Some(esc) = escapechar
4686                && b == esc
4687                && i + 1 < bytes.len()
4688            {
4689                out.push(bytes[i + 1]);
4690                i += 2;
4691                continue;
4692            }
4693            if b == quotechar {
4694                if doublequote && i + 1 < bytes.len() && bytes[i + 1] == quotechar {
4695                    out.push(quotechar);
4696                    i += 2;
4697                    continue;
4698                }
4699                in_quote = false;
4700            }
4701            i += 1;
4702            continue;
4703        }
4704        if at_field_start && b == b' ' {
4705            i += 1;
4706            continue;
4707        }
4708        out.push(b);
4709        if at_field_start && b == quotechar {
4710            in_quote = true;
4711            at_field_start = false;
4712        } else {
4713            at_field_start = b == delimiter || is_terminator(b);
4714        }
4715        i += 1;
4716    }
4717    String::from_utf8(out).unwrap_or_else(|_| input.to_string())
4718}
4719
4720pub fn read_csv_with_options(input: &str, options: &CsvReadOptions) -> Result<DataFrame, IoError> {
4721    // br-frankenpandas-i4h5g: pandas `skipinitialspace` strips leading ASCII
4722    // spaces at each field start BEFORE quote handling, so it cannot be expressed
4723    // as a post-parse field trim. Rewrite the raw input once (quote/escape-aware)
4724    // and re-enter with the flag cleared, so the existing fast paths still apply
4725    // to the stripped text.
4726    if options.skipinitialspace {
4727        let processed = apply_skipinitialspace(
4728            input,
4729            options.delimiter,
4730            options.quotechar,
4731            options.doublequote,
4732            options.escapechar,
4733            options.lineterminator,
4734        );
4735        let mut opts = options.clone();
4736        opts.skipinitialspace = false;
4737        return read_csv_with_options(&processed, &opts);
4738    }
4739    if csv_read_options_match_default_fast_path(options) {
4740        return read_csv_str(input);
4741    }
4742
4743    if csv_read_options_match_no_na_numeric_fast_path(options) {
4744        if let Some(frame) = csv_parse_cache_lookup(CsvParseCacheMode::NoNaNumeric, input) {
4745            return Ok(frame);
4746        }
4747
4748        if let Some(frame) = try_read_csv_with_options_no_na_numeric_fast_path(input)? {
4749            csv_parse_cache_store(CsvParseCacheMode::NoNaNumeric, input, &frame);
4750            return Ok(frame);
4751        }
4752    }
4753
4754    let mut builder = ReaderBuilder::new();
4755    builder
4756        .has_headers(false)
4757        .delimiter(options.delimiter)
4758        .quote(options.quotechar)
4759        .double_quote(options.doublequote)
4760        .escape(options.escapechar);
4761    if options.on_bad_lines != CsvOnBadLines::Error {
4762        builder.flexible(true);
4763    }
4764    if let Some(c) = options.comment {
4765        builder.comment(Some(c));
4766    }
4767    if let Some(term) = options.lineterminator {
4768        builder.terminator(csv::Terminator::Any(term));
4769    }
4770    let mut reader = builder.from_reader(input.as_bytes());
4771
4772    let max_rows = options.nrows.unwrap_or(usize::MAX);
4773    let skip = options.skiprows;
4774
4775    let mut records = reader.records();
4776    for _ in 0..skip {
4777        if records.next().transpose()?.is_none() {
4778            return Err(IoError::MissingHeaders);
4779        }
4780    }
4781
4782    // Per br-frankenpandas-b67a3: pre-build NA / true / false sets once,
4783    // then thread through the per-record loop. Was Vec::iter().any()
4784    // per cell.
4785    let na_set: HashSet<&str> = options.na_values.iter().map(String::as_str).collect();
4786    let true_set: HashSet<&str> = options.true_values.iter().map(String::as_str).collect();
4787    let false_set: HashSet<&str> = options.false_values.iter().map(String::as_str).collect();
4788
4789    let mut row_count: i64 = 0;
4790    // raw_columns shadows columns with each cell's verbatim text so an
4791    // object-fallback column can preserve original literals (see the final
4792    // build step and build_csv_object_aware_column).
4793    let (headers, mut columns, mut raw_columns, deferred_parse_date_columns) =
4794        if options.has_headers {
4795            let headers_record = records.next().transpose()?.ok_or(IoError::MissingHeaders)?;
4796            if headers_record.is_empty() {
4797                return Err(IoError::MissingHeaders);
4798            }
4799
4800            let header_count = headers_record.len();
4801            let row_hint = input.len() / (header_count * 8).max(1);
4802            let headers = headers_record
4803                .iter()
4804                .map(ToOwned::to_owned)
4805                .collect::<Vec<_>>();
4806            let columns: Vec<Vec<Scalar>> = (0..header_count)
4807                .map(|_| Vec::with_capacity(row_hint))
4808                .collect();
4809            let raw_columns: Vec<Vec<String>> = (0..header_count)
4810                .map(|_| Vec::with_capacity(row_hint))
4811                .collect();
4812            let deferred_parse_date_columns = deferred_parse_date_column_mask(&headers, options);
4813
4814            (headers, columns, raw_columns, deferred_parse_date_columns)
4815        } else {
4816            let first_record = records.next().transpose()?.ok_or(IoError::MissingHeaders)?;
4817            if first_record.is_empty() {
4818                return Err(IoError::MissingHeaders);
4819            }
4820
4821            let header_count = first_record.len();
4822            let row_hint = input.len() / (header_count * 8).max(1);
4823            let headers = (0..header_count)
4824                .map(|idx| format!("column_{idx}"))
4825                .collect::<Vec<_>>();
4826            let mut columns: Vec<Vec<Scalar>> = (0..header_count)
4827                .map(|_| Vec::with_capacity(row_hint))
4828                .collect();
4829            let mut raw_columns: Vec<Vec<String>> = (0..header_count)
4830                .map(|_| Vec::with_capacity(row_hint))
4831                .collect();
4832            let deferred_parse_date_columns = deferred_parse_date_column_mask(&headers, options);
4833
4834            if (row_count as usize) < max_rows {
4835                append_csv_record(
4836                    &mut columns,
4837                    &mut raw_columns,
4838                    &first_record,
4839                    options,
4840                    &na_set,
4841                    &true_set,
4842                    &false_set,
4843                    &deferred_parse_date_columns,
4844                );
4845                row_count += 1;
4846            }
4847
4848            (headers, columns, raw_columns, deferred_parse_date_columns)
4849        };
4850
4851    for row in records {
4852        if (row_count as usize) >= max_rows {
4853            break;
4854        }
4855        let record = row?;
4856        if should_skip_bad_csv_record(&record, columns.len(), options.on_bad_lines) {
4857            continue;
4858        }
4859        append_csv_record(
4860            &mut columns,
4861            &mut raw_columns,
4862            &record,
4863            options,
4864            &na_set,
4865            &true_set,
4866            &false_set,
4867            &deferred_parse_date_columns,
4868        );
4869        row_count += 1;
4870    }
4871
4872    // Drop the last `skipfooter` data rows. Matches pandas semantics:
4873    // footer rows are dropped *after* header parsing and nrows limit.
4874    if options.skipfooter > 0 && (row_count as usize) > 0 {
4875        let drop = options.skipfooter.min(row_count as usize);
4876        for col in columns.iter_mut() {
4877            let new_len = col.len().saturating_sub(drop);
4878            col.truncate(new_len);
4879        }
4880        for col in raw_columns.iter_mut() {
4881            let new_len = col.len().saturating_sub(drop);
4882            col.truncate(new_len);
4883        }
4884        row_count -= drop as i64;
4885    }
4886    reject_duplicate_headers(&headers)?;
4887    if let Some(ref usecols) = options.usecols {
4888        validate_usecols(&headers, usecols)?;
4889    }
4890
4891    // Apply usecols filter: keep only selected columns.
4892    let (mut headers, mut columns, raw_columns, deferred_parse_date_columns) =
4893        if let Some(ref usecols) = options.usecols {
4894            let mut fh = Vec::new();
4895            let mut fc = Vec::new();
4896            let mut fr = Vec::new();
4897            let mut fd = Vec::new();
4898            for (((h, c), r), d) in headers
4899                .into_iter()
4900                .zip(columns)
4901                .zip(raw_columns)
4902                .zip(deferred_parse_date_columns)
4903            {
4904                if usecols.contains(&h) {
4905                    fh.push(h);
4906                    fc.push(c);
4907                    fr.push(r);
4908                    fd.push(d);
4909                }
4910            }
4911            (fh, fc, fr, fd)
4912        } else {
4913            (headers, columns, raw_columns, deferred_parse_date_columns)
4914        };
4915
4916    if let Some(ref parse_date_combinations) = options.parse_date_combinations {
4917        apply_parse_date_combinations(&mut headers, &mut columns, parse_date_combinations)?;
4918    }
4919
4920    if let Some(ref named) = options.parse_date_combinations_named {
4921        apply_parse_date_combinations_named(&mut headers, &mut columns, named)?;
4922    }
4923
4924    if let Some(ref parse_dates) = options.parse_dates {
4925        apply_csv_parse_dates(
4926            &headers,
4927            &mut columns,
4928            &raw_columns,
4929            &deferred_parse_date_columns,
4930            parse_dates,
4931            options,
4932            &na_set,
4933            &true_set,
4934            &false_set,
4935        )?;
4936    }
4937
4938    apply_pandas_csv_numeric_promotions(&mut columns);
4939
4940    // Apply dtype coercion if specified.
4941    if let Some(ref dtype_map) = options.dtype {
4942        for (i, name) in headers.iter().enumerate() {
4943            if let Some(&target_dt) = dtype_map.get(name) {
4944                let coerced = columns[i]
4945                    .iter()
4946                    .map(|v| fp_types::cast_scalar(v, target_dt))
4947                    .collect::<Result<Vec<_>, _>>()
4948                    .map_err(|err| IoError::Column(ColumnError::from(err)))?;
4949                columns[i] = coerced;
4950            }
4951        }
4952    }
4953
4954    let header_count = headers.len();
4955
4956    // Object-fallback columns should keep verbatim source text (pandas parity,
4957    // see build_csv_object_aware_column). Only safe when no parse-date transform
4958    // rewrote/added columns (which would desync raw_columns from columns); a
4959    // per-column dtype override is also excluded so explicit astype wins.
4960    let preserve_object_text = options.parse_dates.is_none()
4961        && options.parse_date_combinations.is_none()
4962        && options.parse_date_combinations_named.is_none();
4963    let dtype_forced = |name: &str| -> bool {
4964        options
4965            .dtype
4966            .as_ref()
4967            .is_some_and(|map| map.contains_key(name))
4968    };
4969
4970    // If index_col is set, extract that column as the index
4971    if let Some(ref idx_col_name) = options.index_col {
4972        let idx_pos = headers
4973            .iter()
4974            .position(|h| h == idx_col_name)
4975            .ok_or_else(|| IoError::MissingIndexColumn(idx_col_name.clone()))?;
4976
4977        let index_values = columns.remove(idx_pos);
4978        let index_labels: Vec<fp_index::IndexLabel> = index_values
4979            .into_iter()
4980            .map(|s| match s {
4981                Scalar::Int64(v) => fp_index::IndexLabel::Int64(v),
4982                Scalar::Utf8(v) => fp_index::IndexLabel::Utf8(v),
4983                Scalar::Float64(v) => fp_index::IndexLabel::Utf8(v.to_string()),
4984                Scalar::Bool(v) => {
4985                    fp_index::IndexLabel::Utf8(if v { "True" } else { "False" }.to_string())
4986                }
4987                // Typed null label (br-frankenpandas-8m6ay): pandas
4988                // read_csv(index_col=...) keeps a real nan index entry for an
4989                // empty cell. Kind-preserving bijection.
4990                Scalar::Null(kind) => fp_index::IndexLabel::Null(kind),
4991                Scalar::Timedelta64(v) => {
4992                    if v == Timedelta::NAT {
4993                        fp_index::IndexLabel::Utf8("<NaT>".to_owned())
4994                    } else {
4995                        fp_index::IndexLabel::Utf8(Timedelta::format(v))
4996                    }
4997                }
4998                Scalar::Datetime64(v) => {
4999                    if v == Timestamp::NAT {
5000                        fp_index::IndexLabel::Utf8("<NaT>".to_owned())
5001                    } else {
5002                        fp_index::IndexLabel::Utf8(format_datetime_ns(v))
5003                    }
5004                }
5005                Scalar::Period(v) => {
5006                    if v.ordinal == i64::MIN {
5007                        fp_index::IndexLabel::Utf8("<NaT>".to_owned())
5008                    } else {
5009                        fp_index::IndexLabel::Utf8(v.calendar_string())
5010                    }
5011                }
5012                Scalar::Interval(iv) => fp_index::IndexLabel::Utf8(format!("{iv}")),
5013            })
5014            .collect();
5015        // Per br-frankenpandas-l0vbr: pandas pd.read_csv(index_col='col')
5016        // sets result.index.name = 'col'.
5017        let index = Index::new(index_labels).set_name(idx_col_name);
5018
5019        let mut out_columns = BTreeMap::new();
5020        let mut column_order = Vec::with_capacity(headers.len() - 1);
5021        let mut col_idx = 0;
5022        for (orig_idx, _) in headers.iter().enumerate() {
5023            if orig_idx == idx_pos {
5024                continue;
5025            }
5026            let name = headers.get(orig_idx).cloned().unwrap_or_default();
5027            let column = if preserve_object_text && !dtype_forced(&name) {
5028                build_csv_object_aware_column(columns[col_idx].clone(), &raw_columns[orig_idx])?
5029            } else {
5030                Column::from_values(columns[col_idx].clone())?
5031            };
5032            out_columns.insert(name.clone(), column);
5033            column_order.push(name);
5034            col_idx += 1;
5035        }
5036        Ok(DataFrame::new_with_column_order(
5037            index,
5038            out_columns,
5039            column_order,
5040        )?)
5041    } else {
5042        let mut out_columns = BTreeMap::new();
5043        let mut column_order = Vec::with_capacity(header_count);
5044        for (idx, values) in columns.into_iter().enumerate() {
5045            let name = headers.get(idx).cloned().unwrap_or_default();
5046            let column = if preserve_object_text && !dtype_forced(&name) {
5047                build_csv_object_aware_column(values, &raw_columns[idx])?
5048            } else {
5049                Column::from_values(values)?
5050            };
5051            out_columns.insert(name.clone(), column);
5052            column_order.push(name);
5053        }
5054        let index = csv_default_unit_range_index(row_count);
5055        Ok(DataFrame::new_with_column_order(
5056            index,
5057            out_columns,
5058            column_order,
5059        )?)
5060    }
5061}
5062
5063/// Read CSV and promote the named columns into a row index / row MultiIndex.
5064///
5065/// For multiple names this mirrors pandas `index_col=[...]`.
5066pub fn read_csv_with_index_cols(
5067    input: &str,
5068    options: &CsvReadOptions,
5069    index_cols: &[&str],
5070) -> Result<DataFrame, IoError> {
5071    let frame = read_csv_with_options(input, options)?;
5072    promote_frame_index_columns(&frame, index_cols)
5073}
5074
5075// ── File-based CSV ─────────────────────────────────────────────────────
5076
5077pub fn read_csv(path: &Path) -> Result<DataFrame, IoError> {
5078    read_csv_with_options_path(path, &CsvReadOptions::default())
5079}
5080
5081pub fn read_csv_with_options_path(
5082    path: &Path,
5083    options: &CsvReadOptions,
5084) -> Result<DataFrame, IoError> {
5085    let content = std::fs::read_to_string(path)?;
5086    read_csv_with_options(&content, options)
5087}
5088
5089pub fn read_csv_with_index_cols_path(
5090    path: &Path,
5091    options: &CsvReadOptions,
5092    index_cols: &[&str],
5093) -> Result<DataFrame, IoError> {
5094    let content = std::fs::read_to_string(path)?;
5095    read_csv_with_index_cols(&content, options, index_cols)
5096}
5097
5098pub fn write_csv(frame: &DataFrame, path: &Path) -> Result<(), IoError> {
5099    let content = write_csv_string(frame)?;
5100    std::fs::write(path, content)?;
5101    Ok(())
5102}
5103
5104// ── read_table (tab-separated thin wrapper) ────────────────────────────
5105
5106/// Parse a tab-separated string, matching `pd.read_table(io.StringIO(s))`.
5107///
5108/// Equivalent to [`read_csv_str`] with `delimiter=b'\t'`. Other defaults
5109/// match pandas `read_table`: `header='infer'`, default NA values, no
5110/// index column promotion. Use [`read_table_with_options`] for full
5111/// option control.
5112pub fn read_table_str(input: &str) -> Result<DataFrame, IoError> {
5113    let opts = CsvReadOptions {
5114        delimiter: b'\t',
5115        ..CsvReadOptions::default()
5116    };
5117    read_csv_with_options(input, &opts)
5118}
5119
5120/// Parse a tab-separated string with explicit options. The caller-supplied
5121/// `options.delimiter` is preserved when it differs from the comma default
5122/// to allow override; otherwise it is forced to `b'\t'` so that the
5123/// pandas `read_table` semantics survive `CsvReadOptions::default()`.
5124pub fn read_table_with_options(
5125    input: &str,
5126    options: &CsvReadOptions,
5127) -> Result<DataFrame, IoError> {
5128    let mut effective = options.clone();
5129    if effective.delimiter == b',' {
5130        effective.delimiter = b'\t';
5131    }
5132    read_csv_with_options(input, &effective)
5133}
5134
5135/// Read a tab-separated file from disk, matching `pd.read_table(path)`.
5136pub fn read_table(path: &Path) -> Result<DataFrame, IoError> {
5137    let opts = CsvReadOptions {
5138        delimiter: b'\t',
5139        ..CsvReadOptions::default()
5140    };
5141    read_csv_with_options_path(path, &opts)
5142}
5143
5144/// Read a tab-separated file from disk with explicit options. The
5145/// caller-supplied delimiter is honored when it has been overridden from
5146/// the comma default; otherwise it is forced to `b'\t'`.
5147pub fn read_table_with_options_path(
5148    path: &Path,
5149    options: &CsvReadOptions,
5150) -> Result<DataFrame, IoError> {
5151    let mut effective = options.clone();
5152    if effective.delimiter == b',' {
5153        effective.delimiter = b'\t';
5154    }
5155    read_csv_with_options_path(path, &effective)
5156}
5157
5158// ── read_fwf (fixed-width file reader) ─────────────────────────────────
5159
5160/// Read a fixed-width file from disk, matching `pd.read_fwf(path, ...)`.
5161///
5162/// See [`read_fwf_str`] for the option semantics. When neither explicit
5163/// `colspecs` nor `widths` are supplied, column ranges are inferred from
5164/// non-whitespace runs.
5165pub fn read_fwf(path: &Path, options: &FwfReadOptions) -> Result<DataFrame, IoError> {
5166    let content = std::fs::read_to_string(path)?;
5167    read_fwf_str(&content, options)
5168}
5169
5170// ── Deferred reader surfaces ───────────────────────────────────────────
5171//
5172// pandas exposes pd.read_gbq / pd.read_sas / pd.read_spss (read_clipboard is
5173// implemented above via an OS subprocess backend). Each remaining one is out of
5174// scope for FrankenPandas's local file-format charter:
5175//
5176//   * read_gbq calls Google BigQuery (external service, GCP credentials).
5177//   * read_sas / read_spss are proprietary statistical-software formats with
5178//     no first-party Rust reader at parity (pandas calls into pyreadstat /
5179//     sas7bdat).
5180//
5181// Following the deferral precedent in fp-frame for plotting (see
5182// `plotting_deferred`), expose typed reject-closed entry points so callers
5183// can program against the surface and fall through to a clean error rather
5184// than a missing symbol.
5185
5186fn deferred_reader_error(method: &str, reason: &str) -> IoError {
5187    IoError::Deferred(format!(
5188        "{method}: in scope but deferred; {reason}. Use the pandas surface in the meantime."
5189    ))
5190}
5191
5192fn deferred_writer_error(method: &str, reason: &str) -> IoError {
5193    IoError::Deferred(format!(
5194        "{method}: in scope but deferred; {reason}. Use the pandas surface in the meantime."
5195    ))
5196}
5197
5198// ── Clipboard I/O (br-frankenpandas-261) ───────────────────────────────
5199//
5200// pandas `read_clipboard` / `to_clipboard` shell out to an OS clipboard helper
5201// (pyperclip → xclip/xsel/wl-clipboard/pbcopy). FrankenPandas mirrors that with
5202// a zero-dependency subprocess backend: no `arboard`/X11 dep tree is pulled in,
5203// and the pure TSV transform (`read_clipboard_str` / the `to_clipboard` writer)
5204// is fully testable without a live clipboard. When no backend binary is
5205// installed (e.g. a headless CI box) the call returns a clear `Clipboard`
5206// error, exactly as pandas raises `PyperclipException`.
5207
5208/// Backends tried in order for READING the clipboard: `(binary, args)`.
5209const CLIPBOARD_READ_BACKENDS: &[(&str, &[&str])] = &[
5210    ("wl-paste", &["-n"]),
5211    ("xclip", &["-selection", "clipboard", "-o"]),
5212    ("xsel", &["-b", "-o"]),
5213    ("pbpaste", &[]),
5214];
5215
5216/// Backends tried in order for WRITING the clipboard: `(binary, args)`.
5217const CLIPBOARD_WRITE_BACKENDS: &[(&str, &[&str])] = &[
5218    ("wl-copy", &[]),
5219    ("xclip", &["-selection", "clipboard"]),
5220    ("xsel", &["-b", "-i"]),
5221    ("pbcopy", &[]),
5222];
5223
5224fn clipboard_get() -> Result<String, IoError> {
5225    let mut last =
5226        String::from("no clipboard backend found (tried wl-paste, xclip, xsel, pbpaste)");
5227    for (cmd, args) in CLIPBOARD_READ_BACKENDS {
5228        match std::process::Command::new(cmd).args(*args).output() {
5229            Ok(out) if out.status.success() => {
5230                return String::from_utf8(out.stdout)
5231                    .map_err(|e| IoError::Clipboard(format!("clipboard text is not UTF-8: {e}")));
5232            }
5233            Ok(_) => last = format!("{cmd}: exited non-zero"),
5234            Err(_) => {} // binary not installed — try the next backend
5235        }
5236    }
5237    Err(IoError::Clipboard(last))
5238}
5239
5240fn clipboard_set(text: &str) -> Result<(), IoError> {
5241    use std::io::Write as _;
5242    let mut last = String::from("no clipboard backend found (tried wl-copy, xclip, xsel, pbcopy)");
5243    for (cmd, args) in CLIPBOARD_WRITE_BACKENDS {
5244        let spawned = std::process::Command::new(cmd)
5245            .args(*args)
5246            .stdin(std::process::Stdio::piped())
5247            .stdout(std::process::Stdio::null())
5248            .stderr(std::process::Stdio::null())
5249            .spawn();
5250        let mut child = match spawned {
5251            Ok(child) => child,
5252            Err(_) => continue, // binary not installed — try the next backend
5253        };
5254        if let Some(mut stdin) = child.stdin.take()
5255            && stdin.write_all(text.as_bytes()).is_err()
5256        {
5257            last = format!("{cmd}: writing to stdin failed");
5258            continue;
5259        }
5260        match child.wait() {
5261            Ok(status) if status.success() => return Ok(()),
5262            Ok(_) => last = format!("{cmd}: exited non-zero"),
5263            Err(e) => last = format!("{cmd}: {e}"),
5264        }
5265    }
5266    Err(IoError::Clipboard(last))
5267}
5268
5269/// Parse clipboard text into a `DataFrame` — the pure, backend-free core of
5270/// [`read_clipboard`]. Tab-separated, matching the bytes `to_clipboard` writes
5271/// (pandas `excel=True`).
5272pub fn read_clipboard_str(text: &str) -> Result<DataFrame, IoError> {
5273    let options = CsvReadOptions {
5274        delimiter: b'\t',
5275        ..CsvReadOptions::default()
5276    };
5277    read_csv_with_options(text, &options)
5278}
5279
5280/// Read the system clipboard, matching `pd.read_clipboard()`. The clipboard is
5281/// fetched via the first available OS backend (`wl-paste`/`xclip`/`xsel`/
5282/// `pbpaste`) and parsed as TSV (the format [`DataFrameIoExt::to_clipboard`]
5283/// writes). Returns a `Clipboard` error when no backend is installed.
5284pub fn read_clipboard() -> Result<DataFrame, IoError> {
5285    read_clipboard_str(&clipboard_get()?)
5286}
5287
5288/// Serialize a frame to the tab-separated bytes `to_clipboard` puts on the
5289/// clipboard (pandas `excel=True`, index included). Pure/testable.
5290fn clipboard_tsv(frame: &DataFrame) -> Result<String, IoError> {
5291    let options = CsvWriteOptions {
5292        delimiter: b'\t',
5293        include_index: true,
5294        ..CsvWriteOptions::default()
5295    };
5296    write_csv_string_with_options(frame, &options)
5297}
5298
5299/// Reject-closed BigQuery reader, matching `pd.read_gbq(query, project_id)`.
5300pub fn read_gbq(_query: &str, _project_id: Option<&str>) -> Result<DataFrame, IoError> {
5301    Err(deferred_reader_error(
5302        "read_gbq",
5303        "Google BigQuery integration is outside FrankenPandas's local file-format scope",
5304    ))
5305}
5306
5307/// Reject-closed SAS reader, matching `pd.read_sas(path)`.
5308pub fn read_sas(_path: &Path) -> Result<DataFrame, IoError> {
5309    Err(deferred_reader_error(
5310        "read_sas",
5311        "no first-party Rust SAS sas7bdat/xport reader exists at pandas-parity yet",
5312    ))
5313}
5314
5315/// Reject-closed SPSS reader, matching `pd.read_spss(path)`.
5316pub fn read_spss(_path: &Path) -> Result<DataFrame, IoError> {
5317    Err(deferred_reader_error(
5318        "read_spss",
5319        "no first-party Rust SPSS .sav reader exists at pandas-parity yet",
5320    ))
5321}
5322
5323// ── File-based Markdown / LaTeX ────────────────────────────────────────
5324
5325/// Write a DataFrame to a Markdown table file.
5326pub fn write_markdown(frame: &DataFrame, path: &Path) -> Result<(), IoError> {
5327    write_markdown_with_options(frame, path, &MarkdownWriteOptions::default())
5328}
5329
5330/// Write a DataFrame to a Markdown table file with explicit options.
5331pub fn write_markdown_with_options(
5332    frame: &DataFrame,
5333    path: &Path,
5334    options: &MarkdownWriteOptions,
5335) -> Result<(), IoError> {
5336    let content = write_markdown_string_with_options(frame, options)?;
5337    std::fs::write(path, content)?;
5338    Ok(())
5339}
5340
5341/// Write a DataFrame to a LaTeX tabular file.
5342pub fn write_latex(frame: &DataFrame, path: &Path) -> Result<(), IoError> {
5343    write_latex_with_options(frame, path, &LatexWriteOptions::default())
5344}
5345
5346/// Write a DataFrame to a LaTeX tabular file with explicit options.
5347pub fn write_latex_with_options(
5348    frame: &DataFrame,
5349    path: &Path,
5350    options: &LatexWriteOptions,
5351) -> Result<(), IoError> {
5352    let content = write_latex_string_with_options(frame, options)?;
5353    std::fs::write(path, content)?;
5354    Ok(())
5355}
5356
5357// ── File-based HTML ────────────────────────────────────────────────────
5358
5359pub fn read_html(path: &Path) -> Result<DataFrame, IoError> {
5360    read_html_with_options(path, &HtmlReadOptions::default())
5361}
5362
5363pub fn read_html_with_options(
5364    path: &Path,
5365    options: &HtmlReadOptions,
5366) -> Result<DataFrame, IoError> {
5367    let content = std::fs::read_to_string(path)?;
5368    read_html_str_with_options(&content, options)
5369}
5370
5371pub fn write_html(frame: &DataFrame, path: &Path) -> Result<(), IoError> {
5372    write_html_with_options(frame, path, &HtmlWriteOptions::default())
5373}
5374
5375pub fn write_html_with_options(
5376    frame: &DataFrame,
5377    path: &Path,
5378    options: &HtmlWriteOptions,
5379) -> Result<(), IoError> {
5380    let content = write_html_string_with_options(frame, options)?;
5381    std::fs::write(path, content)?;
5382    Ok(())
5383}
5384
5385// ── File-based XML ─────────────────────────────────────────────────────
5386
5387pub fn write_xml(frame: &DataFrame, path: &Path) -> Result<(), IoError> {
5388    write_xml_with_options(frame, path, &XmlWriteOptions::default())
5389}
5390
5391pub fn write_xml_with_options(
5392    frame: &DataFrame,
5393    path: &Path,
5394    options: &XmlWriteOptions,
5395) -> Result<(), IoError> {
5396    let content = write_xml_string_with_options(frame, options)?;
5397    std::fs::write(path, content)?;
5398    Ok(())
5399}
5400
5401// ── File-based XML readers ─────────────────────────────────────────────
5402
5403pub fn read_xml(path: &Path) -> Result<DataFrame, IoError> {
5404    read_xml_with_options(path, &XmlReadOptions::default())
5405}
5406
5407pub fn read_xml_with_options(path: &Path, options: &XmlReadOptions) -> Result<DataFrame, IoError> {
5408    let content = std::fs::read_to_string(path)?;
5409    read_xml_str_with_options(&content, options)
5410}
5411
5412// ── JSON IO ────────────────────────────────────────────────────────────
5413
5414fn json_value_to_scalar(val: &serde_json::Value) -> Scalar {
5415    match val {
5416        serde_json::Value::Null => Scalar::Null(NullKind::Null),
5417        serde_json::Value::Bool(b) => Scalar::Bool(*b),
5418        serde_json::Value::Number(n) => {
5419            if let Some(i) = n.as_i64() {
5420                Scalar::Int64(i)
5421            } else if let Some(f) = n.as_f64() {
5422                Scalar::Float64(f)
5423            } else {
5424                Scalar::Utf8(n.to_string())
5425            }
5426        }
5427        serde_json::Value::String(s) => Scalar::Utf8(s.clone()),
5428        other => Scalar::Utf8(other.to_string()),
5429    }
5430}
5431
5432fn parse_json_value_allowing_pandas_nan(input: &str) -> Result<serde_json::Value, IoError> {
5433    match serde_json::from_str(input) {
5434        Ok(value) => Ok(value),
5435        Err(original) => {
5436            let normalized = normalize_bare_json_nan_tokens(input);
5437            if normalized == input {
5438                return Err(original.into());
5439            }
5440            serde_json::from_str(&normalized).map_err(IoError::from)
5441        }
5442    }
5443}
5444
5445fn normalize_bare_json_nan_tokens(input: &str) -> String {
5446    let mut output = String::with_capacity(input.len());
5447    let mut index = 0;
5448    let mut in_string = false;
5449    let mut escaped = false;
5450
5451    while index < input.len() {
5452        let rest = &input[index..];
5453        let Some(ch) = rest.chars().next() else {
5454            break;
5455        };
5456
5457        if in_string {
5458            output.push(ch);
5459            index += ch.len_utf8();
5460            if escaped {
5461                escaped = false;
5462            } else if ch == '\\' {
5463                escaped = true;
5464            } else if ch == '"' {
5465                in_string = false;
5466            }
5467            continue;
5468        }
5469
5470        if ch == '"' {
5471            in_string = true;
5472            output.push(ch);
5473            index += ch.len_utf8();
5474            continue;
5475        }
5476
5477        if rest.starts_with("NaN")
5478            && is_json_value_start_boundary(input, index)
5479            && is_json_value_end_boundary(input, index + 3)
5480        {
5481            output.push_str("null");
5482            index += 3;
5483            continue;
5484        }
5485
5486        output.push(ch);
5487        index += ch.len_utf8();
5488    }
5489
5490    output
5491}
5492
5493fn is_json_value_start_boundary(input: &str, index: usize) -> bool {
5494    input[..index]
5495        .chars()
5496        .rev()
5497        .find(|ch| !ch.is_whitespace())
5498        .is_none_or(|ch| matches!(ch, ':' | '[' | ','))
5499}
5500
5501fn is_json_value_end_boundary(input: &str, index: usize) -> bool {
5502    input[index..]
5503        .chars()
5504        .find(|ch| !ch.is_whitespace())
5505        .is_none_or(|ch| matches!(ch, ',' | ']' | '}'))
5506}
5507
5508fn column_from_json_values(values: Vec<Scalar>) -> Result<Column, IoError> {
5509    let saw_utf8 = values.iter().any(|value| matches!(value, Scalar::Utf8(_)));
5510    let saw_missing = values.iter().any(Scalar::is_missing);
5511    let saw_numeric_like = values.iter().any(|value| {
5512        matches!(
5513            value,
5514            Scalar::Int64(_) | Scalar::Float64(_) | Scalar::Bool(_)
5515        )
5516    });
5517
5518    if !saw_utf8 && saw_missing && (saw_numeric_like || values.iter().all(Scalar::is_missing)) {
5519        let promoted = values
5520            .into_iter()
5521            .map(|value| match value {
5522                Scalar::Int64(value) => Scalar::Float64(value as f64),
5523                Scalar::Bool(value) => Scalar::Float64(if value { 1.0 } else { 0.0 }),
5524                Scalar::Null(_) => Scalar::Null(NullKind::NaN),
5525                other => other,
5526            })
5527            .collect();
5528        return Column::new(DType::Float64, promoted).map_err(IoError::from);
5529    }
5530
5531    Column::from_values(values).map_err(IoError::from)
5532}
5533
5534fn scalar_to_json(scalar: &Scalar) -> serde_json::Value {
5535    match scalar {
5536        Scalar::Null(_) => serde_json::Value::Null,
5537        Scalar::Bool(b) => serde_json::Value::Bool(*b),
5538        Scalar::Int64(i) => serde_json::json!(*i),
5539        Scalar::Float64(f) => {
5540            if f.is_nan() || f.is_infinite() {
5541                serde_json::Value::Null
5542            } else {
5543                serde_json::json!(*f)
5544            }
5545        }
5546        Scalar::Utf8(s) => serde_json::Value::String(s.clone()),
5547        // pandas to_json (default date_format='epoch', date_unit='ms') serializes
5548        // datetime64 and timedelta64 as epoch-MILLISECOND integers, not strings.
5549        // (br-frankenpandas-lb0iu)
5550        Scalar::Timedelta64(v) => {
5551            if *v == Timedelta::NAT {
5552                serde_json::Value::Null
5553            } else {
5554                serde_json::json!(*v / 1_000_000)
5555            }
5556        }
5557        Scalar::Datetime64(v) => {
5558            if *v == Timestamp::NAT {
5559                serde_json::Value::Null
5560            } else {
5561                serde_json::json!(*v / 1_000_000)
5562            }
5563        }
5564        Scalar::Period(p) => {
5565            if p.ordinal == i64::MIN {
5566                serde_json::Value::Null
5567            } else {
5568                serde_json::Value::String(p.calendar_string())
5569            }
5570        }
5571        Scalar::Interval(iv) => serde_json::Value::String(format!("{iv}")),
5572    }
5573}
5574
5575fn column_promotes_int_json_values_to_float(_values: &[Scalar]) -> bool {
5576    // DISC-011: Nullable extension Int64 dtype parity.
5577    // Pandas (since v0.24) preserves Int64 via a separate validity mask when
5578    // null values are present. We now match: Int64 values serialize as integers,
5579    // Null values serialize as null, no Float64 promotion.
5580    false
5581}
5582
5583fn scalar_to_json_with_column_promotion(
5584    scalar: &Scalar,
5585    promote_int_to_float: bool,
5586) -> serde_json::Value {
5587    if promote_int_to_float && let Scalar::Int64(v) = scalar {
5588        return serde_json::json!(*v as f64);
5589    }
5590    scalar_to_json(scalar)
5591}
5592
5593fn json_value_to_index_label(value: &serde_json::Value) -> IndexLabel {
5594    match value {
5595        serde_json::Value::Number(n) => n
5596            .as_i64()
5597            .map(IndexLabel::Int64)
5598            .unwrap_or_else(|| IndexLabel::Utf8(n.to_string())),
5599        serde_json::Value::String(s) => IndexLabel::Utf8(s.clone()),
5600        serde_json::Value::Bool(b) => IndexLabel::Utf8(b.to_string()),
5601        serde_json::Value::Null => IndexLabel::Utf8("null".to_owned()),
5602        other => IndexLabel::Utf8(other.to_string()),
5603    }
5604}
5605
5606fn json_value_to_column_name(value: &serde_json::Value) -> String {
5607    match value {
5608        serde_json::Value::String(s) => s.clone(),
5609        serde_json::Value::Number(n) => n.to_string(),
5610        serde_json::Value::Bool(b) => b.to_string(),
5611        serde_json::Value::Null => "null".to_owned(),
5612        other => other.to_string(),
5613    }
5614}
5615
5616fn json_key_to_index_label(value: &str) -> IndexLabel {
5617    value
5618        .parse::<i64>()
5619        .map(IndexLabel::Int64)
5620        .unwrap_or_else(|_| IndexLabel::Utf8(value.to_owned()))
5621}
5622
5623fn index_label_to_json(label: &IndexLabel) -> serde_json::Value {
5624    match label {
5625        IndexLabel::Int64(v) => serde_json::json!(*v),
5626        IndexLabel::Float64(v) => serde_json::json!(v.0),
5627        IndexLabel::Bool(b) => serde_json::json!(*b),
5628        IndexLabel::Utf8(v) => serde_json::Value::String(v.clone()),
5629        // Epoch-millisecond ints, matching pandas to_json (date_unit='ms') and
5630        // the value path above — previously emitted raw nanoseconds, which
5631        // matched neither pandas nor FP's own value serialization.
5632        // (br-frankenpandas-lb0iu)
5633        //
5634        // A NaT label (the i64::MIN sentinel) must serialize as JSON null, NOT
5635        // `i64::MIN / 1e6` (-9223372036854775) — the latter is neither pandas nor
5636        // FP's own value path (`scalar_to_json_value`), which already null-checks
5637        // `Timestamp::NAT`/`Timedelta::NAT`. (br-frankenpandas-natjson)
5638        IndexLabel::Timedelta64(ns) => {
5639            if *ns == fp_types::Timedelta::NAT {
5640                serde_json::Value::Null
5641            } else {
5642                serde_json::json!(*ns / 1_000_000)
5643            }
5644        }
5645        IndexLabel::Datetime64(ns) => {
5646            if *ns == fp_types::Timestamp::NAT {
5647                serde_json::Value::Null
5648            } else {
5649                serde_json::json!(*ns / 1_000_000)
5650            }
5651        }
5652        // pandas to_json renders a missing label as JSON null.
5653        IndexLabel::Null(_) => serde_json::Value::Null,
5654    }
5655}
5656
5657/// Stringified index label for use as a JSON object key (columns/index orients).
5658/// Temporal labels become epoch-millisecond strings, matching pandas to_json
5659/// (e.g. a 2020-01-01 index key is "1577836800000", not "2020-01-01 00:00:00").
5660/// (br-frankenpandas-lb0iu)
5661fn index_label_json_key(label: &IndexLabel) -> String {
5662    match label {
5663        // NaT (i64::MIN) as an object key renders as "null" rather than the
5664        // sentinel's epoch garbage (-9223372036854775), matching the JSON-null
5665        // the value path emits for a missing temporal label.
5666        // (br-frankenpandas-natjson)
5667        IndexLabel::Datetime64(ns) if *ns == fp_types::Timestamp::NAT => "null".to_owned(),
5668        IndexLabel::Timedelta64(ns) if *ns == fp_types::Timedelta::NAT => "null".to_owned(),
5669        IndexLabel::Datetime64(ns) | IndexLabel::Timedelta64(ns) => (*ns / 1_000_000).to_string(),
5670        other => other.to_string(),
5671    }
5672}
5673
5674const SYNTHETIC_ROW_MULTIINDEX_PREFIX: &str = "__index_level_";
5675
5676fn index_label_to_scalar_value(label: &IndexLabel) -> Scalar {
5677    match label {
5678        IndexLabel::Int64(v) => Scalar::Int64(*v),
5679        IndexLabel::Float64(v) => Scalar::Float64(v.0),
5680        IndexLabel::Bool(b) => Scalar::Bool(*b),
5681        IndexLabel::Utf8(v) => Scalar::Utf8(v.clone()),
5682        IndexLabel::Timedelta64(v) => Scalar::Timedelta64(*v),
5683        // Keep the TYPED Datetime64 scalar, like the Timedelta64 arm above —
5684        // materializing a MultiIndex level into a column must preserve its dtype
5685        // (pandas reset_index keeps a datetime level as datetime64, not object).
5686        // The old `Scalar::Utf8(format_datetime_ns(..))` downgrade made datetime
5687        // levels render as ISO strings in to_json (inconsistent with a single
5688        // DatetimeIndex's epoch-ms ints) and bypassed to_csv's column-uniform
5689        // datetime format. (br-frankenpandas-mdt64)
5690        IndexLabel::Datetime64(v) => Scalar::Datetime64(*v),
5691        // Typed-null label round-trips to the same-kind missing scalar.
5692        IndexLabel::Null(kind) => Scalar::Null(*kind),
5693    }
5694}
5695
5696fn synthetic_row_multiindex_names(nlevels: usize) -> Vec<String> {
5697    (0..nlevels)
5698        .map(|level| format!("{SYNTHETIC_ROW_MULTIINDEX_PREFIX}{level}__"))
5699        .collect()
5700}
5701
5702fn materialize_row_multiindex_columns(
5703    frame: &DataFrame,
5704    names: &[String],
5705) -> Result<DataFrame, IoError> {
5706    let Some(row_multiindex) = frame.row_multiindex() else {
5707        return Ok(frame.clone());
5708    };
5709
5710    let mut columns = BTreeMap::new();
5711    let mut column_order = Vec::with_capacity(names.len() + frame.column_names().len());
5712    for (level, name) in names.iter().enumerate() {
5713        let level_index = row_multiindex.get_level_values(level)?;
5714        let values = level_index
5715            .labels()
5716            .iter()
5717            .map(index_label_to_scalar_value)
5718            .collect::<Vec<_>>();
5719        columns.insert(name.clone(), Column::from_values(values)?);
5720        column_order.push(name.clone());
5721    }
5722
5723    for name in frame.column_names() {
5724        let column = frame
5725            .column(name)
5726            .ok_or_else(|| {
5727                IoError::Frame(FrameError::CompatibilityRejected(format!(
5728                    "column not found: '{name}'"
5729                )))
5730            })?
5731            .clone();
5732        columns.insert(name.clone(), column);
5733        column_order.push(name.clone());
5734    }
5735
5736    let index = Index::from_i64((0..frame.len() as i64).collect());
5737    DataFrame::new_with_column_order(index, columns, column_order).map_err(IoError::from)
5738}
5739
5740fn materialize_named_row_multiindex_columns(frame: &DataFrame) -> Result<DataFrame, IoError> {
5741    if frame.row_multiindex().is_some() {
5742        frame.reset_index(false).map_err(IoError::from)
5743    } else {
5744        Ok(frame.clone())
5745    }
5746}
5747
5748fn materialize_synthetic_row_multiindex_columns(frame: &DataFrame) -> Result<DataFrame, IoError> {
5749    let Some(row_multiindex) = frame.row_multiindex() else {
5750        return Ok(frame.clone());
5751    };
5752    let names = synthetic_row_multiindex_names(row_multiindex.nlevels());
5753    materialize_row_multiindex_columns(frame, &names)
5754}
5755
5756fn promote_frame_index_columns(
5757    frame: &DataFrame,
5758    index_cols: &[&str],
5759) -> Result<DataFrame, IoError> {
5760    if index_cols.is_empty() {
5761        return Ok(frame.clone());
5762    }
5763    if index_cols.len() == 1 {
5764        frame.set_index(index_cols[0], true).map_err(IoError::from)
5765    } else {
5766        frame
5767            .set_index_multi(index_cols, true, "|")
5768            .map_err(IoError::from)
5769    }
5770}
5771
5772fn detect_synthetic_row_multiindex_columns(frame: &DataFrame) -> Vec<String> {
5773    let mut out = Vec::new();
5774    for (level, name) in frame.column_names().iter().enumerate() {
5775        let expected = format!("{SYNTHETIC_ROW_MULTIINDEX_PREFIX}{level}__");
5776        if **name == expected {
5777            out.push(expected);
5778        } else {
5779            break;
5780        }
5781    }
5782    out
5783}
5784
5785fn promote_synthetic_row_multiindex_if_present(frame: &DataFrame) -> Result<DataFrame, IoError> {
5786    let synthetic_cols = detect_synthetic_row_multiindex_columns(frame);
5787    if synthetic_cols.len() < 2 {
5788        return Ok(frame.clone());
5789    }
5790    let refs = synthetic_cols
5791        .iter()
5792        .map(String::as_str)
5793        .collect::<Vec<_>>();
5794    promote_frame_index_columns(frame, &refs)
5795}
5796
5797pub fn read_json_str(input: &str, orient: JsonOrient) -> Result<DataFrame, IoError> {
5798    let parsed = parse_json_value_allowing_pandas_nan(input)?;
5799
5800    match orient {
5801        JsonOrient::Records => {
5802            let arr = parsed
5803                .as_array()
5804                .ok_or_else(|| IoError::JsonFormat("expected array for records orient".into()))?;
5805            if arr.is_empty() {
5806                return Ok(DataFrame::new(Index::new(Vec::new()), BTreeMap::new())?);
5807            }
5808
5809            // Collect column names from all records to handle heterogeneous keys
5810            let mut col_names_set = std::collections::BTreeSet::new();
5811            let mut col_names = Vec::new();
5812            for record in arr {
5813                let obj = record
5814                    .as_object()
5815                    .ok_or_else(|| IoError::JsonFormat("each record must be an object".into()))?;
5816                for key in obj.keys() {
5817                    if col_names_set.insert(key.clone()) {
5818                        col_names.push(key.clone());
5819                    }
5820                }
5821            }
5822
5823            let mut columns: BTreeMap<String, Vec<Scalar>> = BTreeMap::new();
5824            for name in &col_names {
5825                columns.insert(name.clone(), Vec::with_capacity(arr.len()));
5826            }
5827
5828            for record in arr {
5829                let obj = record
5830                    .as_object()
5831                    .ok_or_else(|| IoError::JsonFormat("each record must be an object".into()))?;
5832                for name in &col_names {
5833                    let val = obj.get(name).unwrap_or(&serde_json::Value::Null);
5834                    columns
5835                        .get_mut(name)
5836                        .ok_or_else(|| {
5837                            IoError::JsonFormat(format!(
5838                                "records orient missing column accumulator for '{name}'"
5839                            ))
5840                        })?
5841                        .push(json_value_to_scalar(val));
5842                }
5843            }
5844
5845            let row_count = arr.len() as i64;
5846            let mut out = BTreeMap::new();
5847            for (name, vals) in columns {
5848                out.insert(name, column_from_json_values(vals)?);
5849            }
5850            let index = Index::from_i64((0..row_count).collect());
5851            let frame = DataFrame::new_with_column_order(index, out, col_names)?;
5852            promote_synthetic_row_multiindex_if_present(&frame)
5853        }
5854        JsonOrient::Columns => {
5855            let obj = parsed
5856                .as_object()
5857                .ok_or_else(|| IoError::JsonFormat("expected object for columns orient".into()))?;
5858
5859            if obj.is_empty() {
5860                return Ok(DataFrame::new(Index::new(Vec::new()), BTreeMap::new())?);
5861            }
5862
5863            let mut raw_columns: BTreeMap<String, Vec<Scalar>> = BTreeMap::new();
5864            let mut column_order = Vec::with_capacity(obj.len());
5865            let mut index_labels = Vec::new();
5866            let mut index_lookup = BTreeMap::new();
5867            for (col_name, col_data) in obj {
5868                let col_obj = col_data.as_object().ok_or_else(|| {
5869                    IoError::JsonFormat("column data must be {index: val}".into())
5870                })?;
5871                let mut values = vec![Scalar::Null(NullKind::Null); index_labels.len()];
5872                for (label_key, val) in col_obj {
5873                    let label = json_key_to_index_label(label_key);
5874                    let row_idx = if let Some(&existing_idx) = index_lookup.get(&label) {
5875                        existing_idx
5876                    } else {
5877                        let next_idx = index_labels.len();
5878                        index_labels.push(label.clone());
5879                        index_lookup.insert(label, next_idx);
5880                        for existing_values in raw_columns.values_mut() {
5881                            existing_values.push(Scalar::Null(NullKind::Null));
5882                        }
5883                        values.push(Scalar::Null(NullKind::Null));
5884                        next_idx
5885                    };
5886                    if row_idx >= values.len() {
5887                        values.resize(index_labels.len(), Scalar::Null(NullKind::Null));
5888                    }
5889                    values[row_idx] = json_value_to_scalar(val);
5890                }
5891                if values.len() < index_labels.len() {
5892                    values.resize(index_labels.len(), Scalar::Null(NullKind::Null));
5893                }
5894                raw_columns.insert(col_name.clone(), values);
5895                column_order.push(col_name.clone());
5896            }
5897
5898            let mut out = BTreeMap::new();
5899            for (name, vals) in raw_columns {
5900                out.insert(name, column_from_json_values(vals)?);
5901            }
5902
5903            let frame =
5904                DataFrame::new_with_column_order(Index::new(index_labels), out, column_order)?;
5905            promote_synthetic_row_multiindex_if_present(&frame)
5906        }
5907        JsonOrient::Index => {
5908            let obj = parsed
5909                .as_object()
5910                .ok_or_else(|| IoError::JsonFormat("expected object for index orient".into()))?;
5911
5912            if obj.is_empty() {
5913                return Ok(DataFrame::new(Index::new(Vec::new()), BTreeMap::new())?);
5914            }
5915
5916            let mut index_labels = Vec::with_capacity(obj.len());
5917            let mut columns: BTreeMap<String, Vec<Scalar>> = BTreeMap::new();
5918            let mut column_order = Vec::new();
5919            let mut seen_columns = std::collections::HashSet::new();
5920
5921            for (row_label, row_data) in obj {
5922                let row_obj = row_data.as_object().ok_or_else(|| {
5923                    IoError::JsonFormat("index orient rows must be objects".into())
5924                })?;
5925
5926                let row_idx = index_labels.len();
5927
5928                // Pre-fill this row as null for all known columns, then overwrite present cells.
5929                for values in columns.values_mut() {
5930                    values.push(Scalar::Null(NullKind::Null));
5931                }
5932
5933                let parsed_label = row_label
5934                    .parse::<i64>()
5935                    .map(IndexLabel::Int64)
5936                    .unwrap_or_else(|_| IndexLabel::Utf8(row_label.clone()));
5937                index_labels.push(parsed_label);
5938
5939                for (col_name, value) in row_obj {
5940                    if seen_columns.insert(col_name.clone()) {
5941                        column_order.push(col_name.clone());
5942                    }
5943                    let scalar = json_value_to_scalar(value);
5944                    if let Some(values) = columns.get_mut(col_name) {
5945                        values[row_idx] = scalar;
5946                    } else {
5947                        let mut values = vec![Scalar::Null(NullKind::Null); row_idx + 1];
5948                        values[row_idx] = scalar;
5949                        columns.insert(col_name.clone(), values);
5950                    }
5951                }
5952            }
5953
5954            let mut out = BTreeMap::new();
5955            for (name, vals) in columns {
5956                out.insert(name, column_from_json_values(vals)?);
5957            }
5958            let frame =
5959                DataFrame::new_with_column_order(Index::new(index_labels), out, column_order)?;
5960            promote_synthetic_row_multiindex_if_present(&frame)
5961        }
5962        JsonOrient::Split => {
5963            let obj = parsed
5964                .as_object()
5965                .ok_or_else(|| IoError::JsonFormat("expected object for split orient".into()))?;
5966
5967            let col_names: Vec<String> = obj
5968                .get("columns")
5969                .and_then(|v| v.as_array())
5970                .ok_or_else(|| IoError::JsonFormat("split orient needs 'columns' array".into()))?
5971                .iter()
5972                .map(json_value_to_column_name)
5973                .collect();
5974            reject_duplicate_headers(&col_names)?;
5975
5976            let data = obj
5977                .get("data")
5978                .and_then(|v| v.as_array())
5979                .ok_or_else(|| IoError::JsonFormat("split orient needs 'data' array".into()))?;
5980
5981            let explicit_index = obj
5982                .get("index")
5983                .map(|v| {
5984                    v.as_array()
5985                        .ok_or_else(|| {
5986                            IoError::JsonFormat("split orient 'index' must be an array".into())
5987                        })
5988                        .map(|arr| {
5989                            arr.iter()
5990                                .map(json_value_to_index_label)
5991                                .collect::<Vec<_>>()
5992                        })
5993                })
5994                .transpose()?;
5995
5996            let mut columns: BTreeMap<String, Vec<Scalar>> = BTreeMap::new();
5997            for name in &col_names {
5998                columns.insert(name.clone(), Vec::with_capacity(data.len()));
5999            }
6000
6001            for (row_idx, row) in data.iter().enumerate() {
6002                let arr = row
6003                    .as_array()
6004                    .ok_or_else(|| IoError::JsonFormat("each data row must be an array".into()))?;
6005                if arr.len() != col_names.len() {
6006                    return Err(IoError::JsonFormat(format!(
6007                        "split orient row {row_idx} length ({}) does not match columns length ({})",
6008                        arr.len(),
6009                        col_names.len()
6010                    )));
6011                }
6012                for (i, name) in col_names.iter().enumerate() {
6013                    let val = arr.get(i).unwrap_or(&serde_json::Value::Null);
6014                    columns
6015                        .get_mut(name)
6016                        .ok_or_else(|| {
6017                            IoError::JsonFormat(format!(
6018                                "split orient missing column accumulator for '{name}'"
6019                            ))
6020                        })?
6021                        .push(json_value_to_scalar(val));
6022                }
6023            }
6024
6025            let row_count = data.len() as i64;
6026            let mut out = BTreeMap::new();
6027            for (name, vals) in columns {
6028                out.insert(name, column_from_json_values(vals)?);
6029            }
6030            let index = match explicit_index {
6031                Some(labels) => {
6032                    if labels.len() != row_count as usize {
6033                        return Err(IoError::JsonFormat(format!(
6034                            "split orient index length ({}) must match data row count ({row_count})",
6035                            labels.len()
6036                        )));
6037                    }
6038                    Index::new(labels)
6039                }
6040                None => Index::from_i64((0..row_count).collect()),
6041            };
6042            let frame = DataFrame::new_with_column_order(index, out, col_names)?;
6043            promote_synthetic_row_multiindex_if_present(&frame)
6044        }
6045        JsonOrient::Values => {
6046            let rows = parsed
6047                .as_array()
6048                .ok_or_else(|| IoError::JsonFormat("expected array for values orient".into()))?;
6049
6050            if rows.is_empty() {
6051                return Ok(DataFrame::new(Index::new(Vec::new()), BTreeMap::new())?);
6052            }
6053
6054            let mut width = 0usize;
6055            for row in rows {
6056                let arr = row.as_array().ok_or_else(|| {
6057                    IoError::JsonFormat("each values row must be an array".into())
6058                })?;
6059                width = width.max(arr.len());
6060            }
6061
6062            let column_order: Vec<String> = (0..width).map(|idx| idx.to_string()).collect();
6063            let mut columns: BTreeMap<String, Vec<Scalar>> = column_order
6064                .iter()
6065                .cloned()
6066                .map(|name| (name, Vec::with_capacity(rows.len())))
6067                .collect();
6068
6069            for row in rows {
6070                let arr = row.as_array().ok_or_else(|| {
6071                    IoError::JsonFormat("each values row must be an array".into())
6072                })?;
6073                for (col_idx, name) in column_order.iter().enumerate() {
6074                    let val = arr.get(col_idx).unwrap_or(&serde_json::Value::Null);
6075                    columns
6076                        .get_mut(name)
6077                        .ok_or_else(|| {
6078                            IoError::JsonFormat(format!(
6079                                "values orient missing column accumulator for '{name}'"
6080                            ))
6081                        })?
6082                        .push(json_value_to_scalar(val));
6083                }
6084            }
6085
6086            let mut out = BTreeMap::new();
6087            for (name, vals) in columns {
6088                out.insert(name, column_from_json_values(vals)?);
6089            }
6090            let index = Index::from_i64((0..rows.len() as i64).collect());
6091            let frame = DataFrame::new_with_column_order(index, out, column_order)?;
6092            promote_synthetic_row_multiindex_if_present(&frame)
6093        }
6094    }
6095}
6096
6097pub fn write_json_string(frame: &DataFrame, orient: JsonOrient) -> Result<String, IoError> {
6098    if frame.row_multiindex().is_some() && orient != JsonOrient::Values {
6099        let materialized = materialize_synthetic_row_multiindex_columns(frame)?;
6100        return write_json_string(&materialized, orient);
6101    }
6102
6103    let headers: Vec<String> = frame.column_names().into_iter().cloned().collect();
6104    let row_count = frame.index().len();
6105    let column_float_promotions = headers
6106        .iter()
6107        .map(|name| {
6108            frame
6109                .column(name)
6110                .is_some_and(|column| column_promotes_int_json_values_to_float(column.values()))
6111        })
6112        .collect::<Vec<_>>();
6113
6114    match orient {
6115        JsonOrient::Records => {
6116            let mut records = Vec::with_capacity(row_count);
6117            for row_idx in 0..row_count {
6118                let mut obj = serde_json::Map::new();
6119                for (name, promote_int_to_float) in
6120                    headers.iter().zip(column_float_promotions.iter())
6121                {
6122                    let val = frame
6123                        .column(name)
6124                        .and_then(|c| c.value(row_idx))
6125                        .map(|value| {
6126                            scalar_to_json_with_column_promotion(value, *promote_int_to_float)
6127                        })
6128                        .unwrap_or(serde_json::Value::Null);
6129                    obj.insert(name.clone(), val);
6130                }
6131                records.push(serde_json::Value::Object(obj));
6132            }
6133            Ok(serde_json::to_string(&records)?)
6134        }
6135        JsonOrient::Columns => {
6136            let mut outer = serde_json::Map::new();
6137            for (name, promote_int_to_float) in headers.iter().zip(column_float_promotions.iter()) {
6138                let mut col_obj = serde_json::Map::new();
6139                if let Some(col) = frame.column(name) {
6140                    for (label, val) in frame.index().labels().iter().zip(col.values()) {
6141                        let key = index_label_json_key(label);
6142                        if col_obj
6143                            .insert(
6144                                key.clone(),
6145                                scalar_to_json_with_column_promotion(val, *promote_int_to_float),
6146                            )
6147                            .is_some()
6148                        {
6149                            return Err(IoError::JsonFormat(format!(
6150                                "columns orient cannot encode duplicate index label key: {key}"
6151                            )));
6152                        }
6153                    }
6154                }
6155                outer.insert(name.clone(), serde_json::Value::Object(col_obj));
6156            }
6157            Ok(serde_json::to_string(&serde_json::Value::Object(outer))?)
6158        }
6159        JsonOrient::Index => {
6160            let mut outer = serde_json::Map::new();
6161            for row_idx in 0..row_count {
6162                let mut row_obj = serde_json::Map::new();
6163                for (name, promote_int_to_float) in
6164                    headers.iter().zip(column_float_promotions.iter())
6165                {
6166                    let val = frame
6167                        .column(name)
6168                        .and_then(|c| c.value(row_idx))
6169                        .map(|value| {
6170                            scalar_to_json_with_column_promotion(value, *promote_int_to_float)
6171                        })
6172                        .unwrap_or(serde_json::Value::Null);
6173                    row_obj.insert(name.clone(), val);
6174                }
6175
6176                let row_label = index_label_json_key(&frame.index().labels()[row_idx]);
6177                if outer
6178                    .insert(row_label.clone(), serde_json::Value::Object(row_obj))
6179                    .is_some()
6180                {
6181                    return Err(IoError::JsonFormat(format!(
6182                        "index orient cannot encode duplicate index label key: {row_label}"
6183                    )));
6184                }
6185            }
6186            Ok(serde_json::to_string(&serde_json::Value::Object(outer))?)
6187        }
6188        JsonOrient::Split => {
6189            let col_array: Vec<serde_json::Value> = headers
6190                .iter()
6191                .map(|h| serde_json::Value::String(h.clone()))
6192                .collect();
6193            let index_array: Vec<serde_json::Value> = frame
6194                .index()
6195                .labels()
6196                .iter()
6197                .map(index_label_to_json)
6198                .collect();
6199
6200            let mut data = Vec::with_capacity(row_count);
6201            for row_idx in 0..row_count {
6202                let row: Vec<serde_json::Value> = headers
6203                    .iter()
6204                    .zip(column_float_promotions.iter())
6205                    .map(|(name, promote_int_to_float)| {
6206                        frame
6207                            .column(name)
6208                            .and_then(|c| c.value(row_idx))
6209                            .map(|value| {
6210                                scalar_to_json_with_column_promotion(value, *promote_int_to_float)
6211                            })
6212                            .unwrap_or(serde_json::Value::Null)
6213                    })
6214                    .collect();
6215                data.push(serde_json::Value::Array(row));
6216            }
6217
6218            let mut obj = serde_json::Map::new();
6219            obj.insert("columns".into(), serde_json::Value::Array(col_array));
6220            obj.insert("index".into(), serde_json::Value::Array(index_array));
6221            obj.insert("data".into(), serde_json::Value::Array(data));
6222            Ok(serde_json::to_string(&serde_json::Value::Object(obj))?)
6223        }
6224        JsonOrient::Values => {
6225            let mut data = Vec::with_capacity(row_count);
6226            for row_idx in 0..row_count {
6227                let row: Vec<serde_json::Value> = headers
6228                    .iter()
6229                    .zip(column_float_promotions.iter())
6230                    .map(|(name, promote_int_to_float)| {
6231                        frame
6232                            .column(name)
6233                            .and_then(|c| c.value(row_idx))
6234                            .map(|value| {
6235                                scalar_to_json_with_column_promotion(value, *promote_int_to_float)
6236                            })
6237                            .unwrap_or(serde_json::Value::Null)
6238                    })
6239                    .collect();
6240                data.push(serde_json::Value::Array(row));
6241            }
6242            Ok(serde_json::to_string(&serde_json::Value::Array(data))?)
6243        }
6244    }
6245}
6246
6247// ── File-based JSON ────────────────────────────────────────────────────
6248
6249pub fn read_json(path: &Path, orient: JsonOrient) -> Result<DataFrame, IoError> {
6250    let content = std::fs::read_to_string(path)?;
6251    read_json_str(&content, orient)
6252}
6253
6254pub fn write_json(frame: &DataFrame, path: &Path, orient: JsonOrient) -> Result<(), IoError> {
6255    let content = write_json_string(frame, orient)?;
6256    std::fs::write(path, content)?;
6257    Ok(())
6258}
6259
6260// ── File-based Pickle ──────────────────────────────────────────────────
6261
6262/// Read a DataFrame from a Pickle file.
6263pub fn read_pickle(path: &Path) -> Result<DataFrame, IoError> {
6264    read_pickle_with_options(path, &PickleReadOptions::default())
6265}
6266
6267/// Read a DataFrame from a Pickle file with options.
6268pub fn read_pickle_with_options(
6269    path: &Path,
6270    options: &PickleReadOptions,
6271) -> Result<DataFrame, IoError> {
6272    let content = std::fs::read(path)?;
6273    read_pickle_bytes_with_options(&content, options)
6274}
6275
6276/// Write a DataFrame to a Pickle file.
6277pub fn write_pickle(frame: &DataFrame, path: &Path) -> Result<(), IoError> {
6278    write_pickle_with_options(frame, path, &PickleWriteOptions::default())
6279}
6280
6281/// Write a DataFrame to a Pickle file with options.
6282pub fn write_pickle_with_options(
6283    frame: &DataFrame,
6284    path: &Path,
6285    options: &PickleWriteOptions,
6286) -> Result<(), IoError> {
6287    let content = write_pickle_bytes_with_options(frame, options)?;
6288    std::fs::write(path, content)?;
6289    Ok(())
6290}
6291
6292// ── File-based HDF5 ────────────────────────────────────────────────────
6293
6294/// Read a DataFrame from the default HDF5 key.
6295pub fn read_hdf(path: &Path) -> Result<DataFrame, IoError> {
6296    read_hdf_with_options(path, &HdfReadOptions::default())
6297}
6298
6299/// Read a DataFrame from an explicit HDF5 key.
6300pub fn read_hdf_key(path: &Path, key: &str) -> Result<DataFrame, IoError> {
6301    read_hdf_with_options(
6302        path,
6303        &HdfReadOptions {
6304            key: key.to_owned(),
6305        },
6306    )
6307}
6308
6309/// Read a DataFrame from an HDF5 file with options.
6310#[cfg(feature = "hdf5")]
6311pub fn read_hdf_with_options(path: &Path, options: &HdfReadOptions) -> Result<DataFrame, IoError> {
6312    let key = normalize_hdf5_key(&options.key)?;
6313    let dataset_path = hdf5_payload_path(&key);
6314    let file = Hdf5File::open(path).map_err(hdf5_error)?;
6315    let dataset = file.dataset(&dataset_path).map_err(|err| {
6316        IoError::Hdf5(format!(
6317            "missing FrankenPandas payload dataset '{dataset_path}': {err}"
6318        ))
6319    })?;
6320    let payload = dataset.read_raw::<u8>().map_err(hdf5_error)?;
6321    read_pickle_bytes(&payload).map_err(|err| {
6322        IoError::Hdf5(format!(
6323            "invalid FrankenPandas payload at key '{key}': {err}"
6324        ))
6325    })
6326}
6327
6328/// Read a DataFrame from an HDF5 file with options.
6329#[cfg(not(feature = "hdf5"))]
6330pub fn read_hdf_with_options(
6331    _path: &Path,
6332    _options: &HdfReadOptions,
6333) -> Result<DataFrame, IoError> {
6334    hdf5_feature_disabled()
6335}
6336
6337/// Write a DataFrame to the default HDF5 key.
6338pub fn write_hdf(frame: &DataFrame, path: &Path) -> Result<(), IoError> {
6339    write_hdf_with_options(frame, path, &HdfWriteOptions::default())
6340}
6341
6342/// Write a Series to the default HDF5 key.
6343///
6344/// Converts the Series to a single-column DataFrame and writes it.
6345pub fn write_hdf_series(series: &Series, path: &Path) -> Result<(), IoError> {
6346    let frame = series
6347        .to_frame(Some(series.name()))
6348        .map_err(|e| IoError::Hdf5(format!("Series to DataFrame conversion: {e}")))?;
6349    write_hdf(&frame, path)
6350}
6351
6352/// Write a Series to an explicit HDF5 key.
6353pub fn write_hdf_series_key(series: &Series, path: &Path, key: &str) -> Result<(), IoError> {
6354    let frame = series
6355        .to_frame(Some(series.name()))
6356        .map_err(|e| IoError::Hdf5(format!("Series to DataFrame conversion: {e}")))?;
6357    write_hdf_key(&frame, path, key)
6358}
6359
6360/// Write a DataFrame to an explicit HDF5 key.
6361pub fn write_hdf_key(frame: &DataFrame, path: &Path, key: &str) -> Result<(), IoError> {
6362    write_hdf_with_options(
6363        frame,
6364        path,
6365        &HdfWriteOptions {
6366            key: key.to_owned(),
6367        },
6368    )
6369}
6370
6371/// Write a DataFrame to an HDF5 file with options.
6372#[cfg(feature = "hdf5")]
6373pub fn write_hdf_with_options(
6374    frame: &DataFrame,
6375    path: &Path,
6376    options: &HdfWriteOptions,
6377) -> Result<(), IoError> {
6378    let key = normalize_hdf5_key(&options.key)?;
6379    let payload = write_pickle_bytes(frame)?;
6380    let file = Hdf5File::create(path).map_err(hdf5_error)?;
6381    let group = file.create_group(&key).map_err(hdf5_error)?;
6382    group
6383        .new_dataset_builder()
6384        .with_data(payload.as_slice())
6385        .create(HDF5_PAYLOAD_DATASET)
6386        .map_err(hdf5_error)?;
6387    file.flush().map_err(hdf5_error)?;
6388    Ok(())
6389}
6390
6391/// Write a DataFrame to an HDF5 file with options.
6392#[cfg(not(feature = "hdf5"))]
6393pub fn write_hdf_with_options(
6394    _frame: &DataFrame,
6395    _path: &Path,
6396    _options: &HdfWriteOptions,
6397) -> Result<(), IoError> {
6398    hdf5_feature_disabled()
6399}
6400
6401#[cfg(feature = "hdf5")]
6402fn normalize_hdf5_key(key: &str) -> Result<String, IoError> {
6403    let trimmed = key.trim_matches('/');
6404    if trimmed.is_empty() {
6405        return Err(IoError::Hdf5(
6406            "hdf5 key must name a non-root group".to_owned(),
6407        ));
6408    }
6409
6410    for part in trimmed.split('/') {
6411        if part.is_empty() || part == "." || part == ".." {
6412            return Err(IoError::Hdf5(format!("invalid hdf5 key '{key}'")));
6413        }
6414        if part == HDF5_PAYLOAD_DATASET {
6415            return Err(IoError::Hdf5(format!(
6416                "hdf5 key '{key}' uses reserved FrankenPandas dataset name"
6417            )));
6418        }
6419    }
6420
6421    Ok(trimmed.to_owned())
6422}
6423
6424#[cfg(feature = "hdf5")]
6425fn hdf5_payload_path(key: &str) -> String {
6426    format!("{key}/{HDF5_PAYLOAD_DATASET}")
6427}
6428
6429#[cfg(feature = "hdf5")]
6430fn hdf5_error(err: hdf5::Error) -> IoError {
6431    IoError::Hdf5(err.to_string())
6432}
6433
6434#[cfg(not(feature = "hdf5"))]
6435fn hdf5_feature_disabled<T>() -> Result<T, IoError> {
6436    Err(IoError::Hdf5(
6437        "hdf5 support is disabled; enable the fp-io `hdf5` feature".to_owned(),
6438    ))
6439}
6440
6441// ── File-based Stata ───────────────────────────────────────────────────
6442
6443/// Read a DataFrame from a Stata DTA file.
6444pub fn read_stata(path: &Path) -> Result<DataFrame, IoError> {
6445    let content = std::fs::read(path)?;
6446    read_stata_bytes(&content)
6447}
6448
6449/// Write a DataFrame to a Stata DTA file.
6450pub fn write_stata(frame: &DataFrame, path: &Path) -> Result<(), IoError> {
6451    write_stata_with_options(frame, path, &StataWriteOptions::default())
6452}
6453
6454/// Write a DataFrame to a Stata DTA file with explicit options.
6455pub fn write_stata_with_options(
6456    frame: &DataFrame,
6457    path: &Path,
6458    options: &StataWriteOptions,
6459) -> Result<(), IoError> {
6460    let content = write_stata_bytes_with_options(frame, options)?;
6461    std::fs::write(path, content)?;
6462    Ok(())
6463}
6464
6465// ── JSONL (JSON Lines) I/O ──────────────────────────────────────────────
6466
6467/// Write a DataFrame to JSONL (JSON Lines) format.
6468///
6469/// Matches `pd.DataFrame.to_json(orient='records', lines=True)`.
6470/// Each row is written as a separate JSON object on its own line,
6471/// with no enclosing array. This format is standard for streaming
6472/// data pipelines and log processing.
6473pub fn write_jsonl_string(frame: &DataFrame) -> Result<String, IoError> {
6474    let headers: Vec<String> = frame.column_names().into_iter().cloned().collect();
6475    let row_count = frame.index().len();
6476    let column_float_promotions = headers
6477        .iter()
6478        .map(|name| {
6479            frame
6480                .column(name)
6481                .is_some_and(|column| column_promotes_int_json_values_to_float(column.values()))
6482        })
6483        .collect::<Vec<_>>();
6484
6485    let mut lines = Vec::with_capacity(row_count);
6486    for row_idx in 0..row_count {
6487        let mut obj = serde_json::Map::new();
6488        for (name, promote_int_to_float) in headers.iter().zip(column_float_promotions.iter()) {
6489            let val = frame
6490                .column(name)
6491                .and_then(|c| c.value(row_idx))
6492                .map(|value| scalar_to_json_with_column_promotion(value, *promote_int_to_float))
6493                .unwrap_or(serde_json::Value::Null);
6494            obj.insert(name.clone(), val);
6495        }
6496        lines.push(serde_json::to_string(&serde_json::Value::Object(obj))?);
6497    }
6498
6499    Ok(lines.join("\n"))
6500}
6501
6502/// Read a DataFrame from JSONL (JSON Lines) format.
6503///
6504/// Matches `pd.read_json(input, lines=True)`.
6505/// Each line must be a valid JSON object with the same keys.
6506/// Per br-frankenpandas-9l8gd: row cap to prevent DoS via hostile input.
6507/// Hostile JSONL with billions of lines would otherwise grow `all_rows`
6508/// unbounded before the column-build allocation.
6509const READ_JSONL_MAX_ROWS: usize = 100_000_000;
6510
6511pub fn read_jsonl_str(input: &str) -> Result<DataFrame, IoError> {
6512    let mut all_rows: Vec<serde_json::Map<String, serde_json::Value>> = Vec::new();
6513
6514    for line in input.lines() {
6515        let trimmed = line.trim();
6516        if trimmed.is_empty() {
6517            continue;
6518        }
6519        // Per br-frankenpandas-9l8gd: reject hostile inputs that would
6520        // exhaust memory before the column-build allocation step.
6521        if all_rows.len() >= READ_JSONL_MAX_ROWS {
6522            return Err(IoError::JsonFormat(format!(
6523                "JSONL input exceeds maximum of {READ_JSONL_MAX_ROWS} rows"
6524            )));
6525        }
6526        let parsed = parse_json_value_allowing_pandas_nan(trimmed)?;
6527        let obj = parsed
6528            .as_object()
6529            .ok_or_else(|| IoError::JsonFormat("JSONL: each line must be a JSON object".into()))?;
6530        all_rows.push(obj.clone());
6531    }
6532
6533    if all_rows.is_empty() {
6534        return DataFrame::new(Index::new(Vec::new()), BTreeMap::new()).map_err(IoError::Frame);
6535    }
6536
6537    // Collect column names as the UNION of all keys across all rows.
6538    // This matches pandas behavior: missing keys in a row become null.
6539    let mut col_name_set = std::collections::BTreeSet::new();
6540    let mut col_names_ordered: Vec<String> = Vec::new();
6541    for row in &all_rows {
6542        for key in row.keys() {
6543            if col_name_set.insert(key.clone()) {
6544                col_names_ordered.push(key.clone());
6545            }
6546        }
6547    }
6548    let col_names = col_names_ordered;
6549    let mut columns: Vec<Vec<Scalar>> = col_names
6550        .iter()
6551        .map(|_| Vec::with_capacity(all_rows.len()))
6552        .collect();
6553
6554    for row in &all_rows {
6555        for (col_idx, name) in col_names.iter().enumerate() {
6556            let val = row.get(name).unwrap_or(&serde_json::Value::Null);
6557            columns[col_idx].push(json_value_to_scalar(val));
6558        }
6559    }
6560
6561    let mut out_columns = BTreeMap::new();
6562    let mut column_order = Vec::new();
6563    for (name, values) in col_names.into_iter().zip(columns) {
6564        out_columns.insert(name.clone(), column_from_json_values(values)?);
6565        column_order.push(name);
6566    }
6567
6568    let index = Index::from_i64((0..all_rows.len() as i64).collect());
6569    Ok(DataFrame::new_with_column_order(
6570        index,
6571        out_columns,
6572        column_order,
6573    )?)
6574}
6575
6576/// Write a DataFrame to a JSONL file.
6577pub fn write_jsonl(frame: &DataFrame, path: &Path) -> Result<(), IoError> {
6578    let content = write_jsonl_string(frame)?;
6579    std::fs::write(path, content)?;
6580    Ok(())
6581}
6582
6583/// Read a DataFrame from a JSONL file.
6584pub fn read_jsonl(path: &Path) -> Result<DataFrame, IoError> {
6585    let content = std::fs::read_to_string(path)?;
6586    read_jsonl_str(&content)
6587}
6588
6589// ── Parquet I/O ─────────────────────────────────────────────────────────────
6590
6591/// Convert an fp-types DType to an Arrow DataType.
6592fn dtype_to_arrow(dtype: DType) -> ArrowDataType {
6593    match dtype {
6594        DType::Int64 | DType::Int64Nullable => ArrowDataType::Int64,
6595        DType::Float64 => ArrowDataType::Float64,
6596        DType::Utf8 => ArrowDataType::Utf8,
6597        DType::Categorical => ArrowDataType::Utf8,
6598        DType::Bool | DType::BoolNullable => ArrowDataType::Boolean,
6599        DType::Null => ArrowDataType::Utf8, // fallback: null-only columns as string
6600        DType::Timedelta64 => ArrowDataType::Int64, // store as nanoseconds
6601        DType::Datetime64 => ArrowDataType::Int64, // store as nanoseconds
6602        DType::Period => ArrowDataType::Int64, // store as ordinal
6603        DType::Interval => ArrowDataType::Utf8, // store as string until arrow interval lands
6604        DType::Sparse => ArrowDataType::Utf8, // marker fallback until sparse arrays land
6605    }
6606}
6607
6608fn column_to_arrow_array(column: &Column) -> Result<Arc<dyn Array>, IoError> {
6609    let arr: Arc<dyn Array> = match column.dtype() {
6610        DType::Int64 | DType::Int64Nullable => {
6611            let mut builder = Int64Builder::with_capacity(column.len());
6612            for value in column.values() {
6613                match value {
6614                    Scalar::Int64(n) => builder.append_value(*n),
6615                    _ if value.is_missing() => builder.append_null(),
6616                    _ => builder.append_null(),
6617                }
6618            }
6619            Arc::new(builder.finish())
6620        }
6621        DType::Float64 => {
6622            let mut builder = Float64Builder::with_capacity(column.len());
6623            for value in column.values() {
6624                match value {
6625                    Scalar::Float64(n) => {
6626                        if n.is_nan() {
6627                            builder.append_null();
6628                        } else {
6629                            builder.append_value(*n);
6630                        }
6631                    }
6632                    _ if value.is_missing() => builder.append_null(),
6633                    _ => builder.append_null(),
6634                }
6635            }
6636            Arc::new(builder.finish())
6637        }
6638        DType::Bool | DType::BoolNullable => {
6639            let mut builder = BooleanBuilder::with_capacity(column.len());
6640            for value in column.values() {
6641                match value {
6642                    Scalar::Bool(flag) => builder.append_value(*flag),
6643                    _ if value.is_missing() => builder.append_null(),
6644                    _ => builder.append_null(),
6645                }
6646            }
6647            Arc::new(builder.finish())
6648        }
6649        DType::Utf8 | DType::Categorical | DType::Null | DType::Sparse => {
6650            let mut builder = StringBuilder::with_capacity(column.len(), column.len() * 8);
6651            for value in column.values() {
6652                match value {
6653                    Scalar::Utf8(text) => builder.append_value(text),
6654                    _ if value.is_missing() => builder.append_null(),
6655                    _ => builder.append_value(format!("{value:?}")),
6656                }
6657            }
6658            Arc::new(builder.finish())
6659        }
6660        DType::Timedelta64 => {
6661            let mut builder = Int64Builder::with_capacity(column.len());
6662            for value in column.values() {
6663                match value {
6664                    Scalar::Timedelta64(nanos) => {
6665                        if *nanos == Timedelta::NAT {
6666                            builder.append_null();
6667                        } else {
6668                            builder.append_value(*nanos);
6669                        }
6670                    }
6671                    _ if value.is_missing() => builder.append_null(),
6672                    _ => builder.append_null(),
6673                }
6674            }
6675            Arc::new(builder.finish())
6676        }
6677        DType::Datetime64 => {
6678            let mut builder = Int64Builder::with_capacity(column.len());
6679            for value in column.values() {
6680                match value {
6681                    Scalar::Datetime64(nanos) => {
6682                        if *nanos == Timestamp::NAT {
6683                            builder.append_null();
6684                        } else {
6685                            builder.append_value(*nanos);
6686                        }
6687                    }
6688                    _ if value.is_missing() => builder.append_null(),
6689                    _ => builder.append_null(),
6690                }
6691            }
6692            Arc::new(builder.finish())
6693        }
6694        DType::Period => {
6695            let mut builder = Int64Builder::with_capacity(column.len());
6696            for value in column.values() {
6697                match value {
6698                    Scalar::Period(p) => {
6699                        if p.ordinal == i64::MIN {
6700                            builder.append_null();
6701                        } else {
6702                            builder.append_value(p.ordinal);
6703                        }
6704                    }
6705                    _ if value.is_missing() => builder.append_null(),
6706                    _ => builder.append_null(),
6707                }
6708            }
6709            Arc::new(builder.finish())
6710        }
6711        DType::Interval => {
6712            let mut builder = StringBuilder::with_capacity(column.len(), column.len() * 32);
6713            for value in column.values() {
6714                match value {
6715                    Scalar::Interval(iv) => builder.append_value(format!("{iv}")),
6716                    _ if value.is_missing() => builder.append_null(),
6717                    _ => builder.append_null(),
6718                }
6719            }
6720            Arc::new(builder.finish())
6721        }
6722    };
6723
6724    Ok(arr)
6725}
6726
6727/// Convert a Series to its Arrow data type plus backing array.
6728///
6729/// This is the Arrow-level building block under Feather / IPC round-trips and
6730/// preserves nullable Int64 columns as Arrow null-bitmaps rather than coercing
6731/// through Float64.
6732pub fn series_to_arrow_array(series: &Series) -> Result<(ArrowDataType, Arc<dyn Array>), IoError> {
6733    let dt = dtype_to_arrow(series.column().dtype());
6734    Ok((dt, column_to_arrow_array(series.column())?))
6735}
6736
6737/// Rebuild a Series from an Arrow array and explicit dtype metadata.
6738pub fn series_from_arrow_array(
6739    name: impl Into<String>,
6740    index_labels: Vec<IndexLabel>,
6741    arr: &dyn Array,
6742    dt: &ArrowDataType,
6743) -> Result<Series, IoError> {
6744    let values = arrow_array_to_scalars(arr, dt)?;
6745    Series::from_values(name, index_labels, values).map_err(IoError::from)
6746}
6747
6748/// Build an Arrow RecordBatch from a DataFrame.
6749fn dataframe_to_record_batch(frame: &DataFrame) -> Result<RecordBatch, IoError> {
6750    let materialized = if frame.row_multiindex().is_some() {
6751        Some(materialize_synthetic_row_multiindex_columns(frame)?)
6752    } else {
6753        None
6754    };
6755    let frame = materialized.as_ref().unwrap_or(frame);
6756
6757    let col_names: Vec<String> = frame.column_names().into_iter().cloned().collect();
6758    let mut fields = Vec::with_capacity(col_names.len());
6759    let mut arrays: Vec<Arc<dyn Array>> = Vec::with_capacity(col_names.len());
6760
6761    for name in &col_names {
6762        let col = frame
6763            .column(name)
6764            .ok_or_else(|| IoError::Parquet(format!("missing column: {name}")))?;
6765        let dt = col.dtype();
6766        fields.push(Field::new(name.as_str(), dtype_to_arrow(dt), true));
6767        let arr = column_to_arrow_array(col)?;
6768        arrays.push(arr);
6769    }
6770
6771    let schema = Arc::new(Schema::new(fields));
6772    RecordBatch::try_new(schema, arrays).map_err(|e| IoError::Parquet(e.to_string()))
6773}
6774
6775/// Convert an Arrow RecordBatch back into a DataFrame.
6776fn record_batch_to_dataframe(batch: &RecordBatch) -> Result<DataFrame, IoError> {
6777    let n_rows = batch.num_rows();
6778    let schema = batch.schema();
6779    let mut columns = BTreeMap::new();
6780    let mut col_order = Vec::new();
6781
6782    for (i, field) in schema.fields().iter().enumerate() {
6783        let name = field.name().clone();
6784        let arr = batch.column(i);
6785        let values = arrow_array_to_scalars(arr.as_ref(), field.data_type())?;
6786        let dtype = fp_dtype_for_arrow_data_type(field.data_type());
6787        let col = Column::new(dtype, values)?;
6788        columns.insert(name.clone(), col);
6789        col_order.push(name);
6790    }
6791
6792    let labels: Vec<IndexLabel> = (0..n_rows).map(|i| IndexLabel::Int64(i as i64)).collect();
6793    let index = Index::new(labels);
6794
6795    let frame = DataFrame::new_with_column_order(index, columns, col_order)?;
6796    promote_synthetic_row_multiindex_if_present(&frame)
6797}
6798
6799fn fp_dtype_for_arrow_data_type(dt: &ArrowDataType) -> DType {
6800    match dt {
6801        ArrowDataType::Int8
6802        | ArrowDataType::Int16
6803        | ArrowDataType::Int32
6804        | ArrowDataType::Int64
6805        | ArrowDataType::UInt8
6806        | ArrowDataType::UInt16
6807        | ArrowDataType::UInt32
6808        | ArrowDataType::UInt64 => DType::Int64,
6809        ArrowDataType::Float16 | ArrowDataType::Float32 | ArrowDataType::Float64 => DType::Float64,
6810        ArrowDataType::Boolean => DType::Bool,
6811        ArrowDataType::Utf8
6812        | ArrowDataType::LargeUtf8
6813        | ArrowDataType::Date32
6814        | ArrowDataType::Date64
6815        | ArrowDataType::Timestamp(_, _) => DType::Utf8,
6816        _ => DType::Utf8,
6817    }
6818}
6819
6820/// Convert an Arrow array + data type to a Vec of Scalars.
6821fn arrow_array_to_scalars(arr: &dyn Array, dt: &ArrowDataType) -> Result<Vec<Scalar>, IoError> {
6822    let len = arr.len();
6823    let mut scalars = Vec::with_capacity(len);
6824
6825    match dt {
6826        ArrowDataType::Int64 => {
6827            let typed = arr
6828                .as_any()
6829                .downcast_ref::<Int64Array>()
6830                .ok_or_else(|| IoError::Parquet("expected Int64Array".into()))?;
6831            for i in 0..len {
6832                if typed.is_null(i) {
6833                    scalars.push(Scalar::Null(NullKind::Null));
6834                } else {
6835                    scalars.push(Scalar::Int64(typed.value(i)));
6836                }
6837            }
6838        }
6839        ArrowDataType::Int32 => {
6840            let typed = arr
6841                .as_any()
6842                .downcast_ref::<arrow::array::Int32Array>()
6843                .ok_or_else(|| IoError::Parquet("expected Int32Array".into()))?;
6844            for i in 0..len {
6845                if typed.is_null(i) {
6846                    scalars.push(Scalar::Null(NullKind::Null));
6847                } else {
6848                    scalars.push(Scalar::Int64(i64::from(typed.value(i))));
6849                }
6850            }
6851        }
6852        ArrowDataType::Float64 => {
6853            let typed = arr
6854                .as_any()
6855                .downcast_ref::<Float64Array>()
6856                .ok_or_else(|| IoError::Parquet("expected Float64Array".into()))?;
6857            for i in 0..len {
6858                if typed.is_null(i) {
6859                    scalars.push(Scalar::Null(NullKind::NaN));
6860                } else {
6861                    scalars.push(Scalar::Float64(typed.value(i)));
6862                }
6863            }
6864        }
6865        ArrowDataType::Float32 => {
6866            let typed = arr
6867                .as_any()
6868                .downcast_ref::<arrow::array::Float32Array>()
6869                .ok_or_else(|| IoError::Parquet("expected Float32Array".into()))?;
6870            for i in 0..len {
6871                if typed.is_null(i) {
6872                    scalars.push(Scalar::Null(NullKind::NaN));
6873                } else {
6874                    scalars.push(Scalar::Float64(f64::from(typed.value(i))));
6875                }
6876            }
6877        }
6878        ArrowDataType::Boolean => {
6879            let typed = arr
6880                .as_any()
6881                .downcast_ref::<BooleanArray>()
6882                .ok_or_else(|| IoError::Parquet("expected BooleanArray".into()))?;
6883            for i in 0..len {
6884                if typed.is_null(i) {
6885                    scalars.push(Scalar::Null(NullKind::Null));
6886                } else {
6887                    scalars.push(Scalar::Bool(typed.value(i)));
6888                }
6889            }
6890        }
6891        ArrowDataType::Utf8 => {
6892            let typed = arr
6893                .as_any()
6894                .downcast_ref::<StringArray>()
6895                .ok_or_else(|| IoError::Parquet("expected StringArray".into()))?;
6896            for i in 0..len {
6897                if typed.is_null(i) {
6898                    scalars.push(Scalar::Null(NullKind::Null));
6899                } else {
6900                    scalars.push(Scalar::Utf8(typed.value(i).to_owned()));
6901                }
6902            }
6903        }
6904        ArrowDataType::LargeUtf8 => {
6905            let typed = arr
6906                .as_any()
6907                .downcast_ref::<arrow::array::LargeStringArray>()
6908                .ok_or_else(|| IoError::Parquet("expected LargeStringArray".into()))?;
6909            for i in 0..len {
6910                if typed.is_null(i) {
6911                    scalars.push(Scalar::Null(NullKind::Null));
6912                } else {
6913                    scalars.push(Scalar::Utf8(typed.value(i).to_owned()));
6914                }
6915            }
6916        }
6917        ArrowDataType::Date32 => {
6918            let typed = arr
6919                .as_any()
6920                .downcast_ref::<Date32Array>()
6921                .ok_or_else(|| IoError::Parquet("expected Date32Array".into()))?;
6922            for i in 0..len {
6923                if typed.is_null(i) {
6924                    scalars.push(Scalar::Null(NullKind::NaT));
6925                } else {
6926                    if let Some(date) = arrow::temporal_conversions::as_date::<
6927                        arrow::datatypes::Date32Type,
6928                    >(typed.value(i).into())
6929                    {
6930                        scalars.push(Scalar::Utf8(date.format("%Y-%m-%d").to_string()));
6931                    } else {
6932                        scalars.push(Scalar::Null(NullKind::NaT));
6933                    }
6934                }
6935            }
6936        }
6937        ArrowDataType::Date64 => {
6938            let typed = arr
6939                .as_any()
6940                .downcast_ref::<Date64Array>()
6941                .ok_or_else(|| IoError::Parquet("expected Date64Array".into()))?;
6942            for i in 0..len {
6943                if typed.is_null(i) {
6944                    scalars.push(Scalar::Null(NullKind::NaT));
6945                } else {
6946                    if let Some(dt) = arrow::temporal_conversions::as_datetime::<
6947                        arrow::datatypes::Date64Type,
6948                    >(typed.value(i))
6949                    {
6950                        scalars.push(Scalar::Utf8(dt.format("%Y-%m-%d").to_string()));
6951                    } else {
6952                        scalars.push(Scalar::Null(NullKind::NaT));
6953                    }
6954                }
6955            }
6956        }
6957        ArrowDataType::Timestamp(unit, _tz) => match unit {
6958            TimeUnit::Second => {
6959                let typed = arr
6960                    .as_any()
6961                    .downcast_ref::<TimestampSecondArray>()
6962                    .ok_or_else(|| IoError::Parquet("expected TimestampSecondArray".into()))?;
6963                for i in 0..len {
6964                    if typed.is_null(i) {
6965                        scalars.push(Scalar::Null(NullKind::NaT));
6966                    } else {
6967                        if let Some(dt) = arrow::temporal_conversions::as_datetime::<
6968                            arrow::datatypes::TimestampSecondType,
6969                        >(typed.value(i))
6970                        {
6971                            scalars.push(Scalar::Utf8(dt.format("%Y-%m-%d %H:%M:%S").to_string()));
6972                        } else {
6973                            scalars.push(Scalar::Null(NullKind::NaT));
6974                        }
6975                    }
6976                }
6977            }
6978            TimeUnit::Millisecond => {
6979                let typed = arr
6980                    .as_any()
6981                    .downcast_ref::<TimestampMillisecondArray>()
6982                    .ok_or_else(|| IoError::Parquet("expected TimestampMillisecondArray".into()))?;
6983                for i in 0..len {
6984                    if typed.is_null(i) {
6985                        scalars.push(Scalar::Null(NullKind::NaT));
6986                    } else {
6987                        if let Some(dt) = arrow::temporal_conversions::as_datetime::<
6988                            arrow::datatypes::TimestampMillisecondType,
6989                        >(typed.value(i))
6990                        {
6991                            scalars.push(Scalar::Utf8(dt.format("%Y-%m-%d %H:%M:%S").to_string()));
6992                        } else {
6993                            scalars.push(Scalar::Null(NullKind::NaT));
6994                        }
6995                    }
6996                }
6997            }
6998            TimeUnit::Microsecond => {
6999                let typed = arr
7000                    .as_any()
7001                    .downcast_ref::<TimestampMicrosecondArray>()
7002                    .ok_or_else(|| IoError::Parquet("expected TimestampMicrosecondArray".into()))?;
7003                for i in 0..len {
7004                    if typed.is_null(i) {
7005                        scalars.push(Scalar::Null(NullKind::NaT));
7006                    } else {
7007                        if let Some(dt) = arrow::temporal_conversions::as_datetime::<
7008                            arrow::datatypes::TimestampMicrosecondType,
7009                        >(typed.value(i))
7010                        {
7011                            scalars
7012                                .push(Scalar::Utf8(dt.format("%Y-%m-%d %H:%M:%S%.6f").to_string()));
7013                        } else {
7014                            scalars.push(Scalar::Null(NullKind::NaT));
7015                        }
7016                    }
7017                }
7018            }
7019            TimeUnit::Nanosecond => {
7020                let typed = arr
7021                    .as_any()
7022                    .downcast_ref::<TimestampNanosecondArray>()
7023                    .ok_or_else(|| IoError::Parquet("expected TimestampNanosecondArray".into()))?;
7024                for i in 0..len {
7025                    if typed.is_null(i) {
7026                        scalars.push(Scalar::Null(NullKind::NaT));
7027                    } else {
7028                        if let Some(dt) = arrow::temporal_conversions::as_datetime::<
7029                            arrow::datatypes::TimestampNanosecondType,
7030                        >(typed.value(i))
7031                        {
7032                            scalars
7033                                .push(Scalar::Utf8(dt.format("%Y-%m-%d %H:%M:%S%.9f").to_string()));
7034                        } else {
7035                            scalars.push(Scalar::Null(NullKind::NaT));
7036                        }
7037                    }
7038                }
7039            }
7040        },
7041        other => {
7042            return Err(IoError::Parquet(format!(
7043                "unsupported Arrow data type: {other:?}"
7044            )));
7045        }
7046    }
7047
7048    Ok(scalars)
7049}
7050
7051/// Write a DataFrame to an in-memory Parquet buffer.
7052pub fn write_parquet_bytes(frame: &DataFrame) -> Result<Vec<u8>, IoError> {
7053    let batch = dataframe_to_record_batch(frame)?;
7054    let mut buf = Vec::new();
7055    let mut writer = ArrowWriter::try_new(&mut buf, batch.schema(), None)
7056        .map_err(|e| IoError::Parquet(e.to_string()))?;
7057    writer
7058        .write(&batch)
7059        .map_err(|e| IoError::Parquet(e.to_string()))?;
7060    writer
7061        .close()
7062        .map_err(|e| IoError::Parquet(e.to_string()))?;
7063    Ok(buf)
7064}
7065
7066/// Read a DataFrame from in-memory Parquet bytes.
7067pub fn read_parquet_bytes(data: &[u8]) -> Result<DataFrame, IoError> {
7068    let b = bytes::Bytes::from(data.to_vec());
7069    let reader = ParquetRecordBatchReaderBuilder::try_new(b)
7070        .map_err(|e| IoError::Parquet(e.to_string()))?
7071        .build()
7072        .map_err(|e| IoError::Parquet(e.to_string()))?;
7073
7074    let mut all_frames: Vec<DataFrame> = Vec::new();
7075    for batch_result in reader {
7076        let batch: RecordBatch =
7077            batch_result.map_err(|e: arrow::error::ArrowError| IoError::Parquet(e.to_string()))?;
7078        all_frames.push(record_batch_to_dataframe(&batch)?);
7079    }
7080
7081    if all_frames.is_empty() {
7082        // Return empty DataFrame
7083        return Ok(DataFrame::new_with_column_order(
7084            Index::new(vec![]),
7085            BTreeMap::new(),
7086            vec![],
7087        )?);
7088    }
7089
7090    // For a single batch (common case), return directly
7091    if all_frames.len() == 1 {
7092        if let Some(frame) = all_frames.into_iter().next() {
7093            return Ok(frame);
7094        }
7095        return Err(IoError::Parquet(
7096            "parquet reader produced zero record batches".to_owned(),
7097        ));
7098    }
7099
7100    // Multiple batches: concatenate via fp_frame::concat_dataframes
7101    let refs: Vec<&DataFrame> = all_frames.iter().collect();
7102    fp_frame::concat_dataframes(&refs).map_err(IoError::from)
7103}
7104
7105/// Write a DataFrame to a Parquet file.
7106pub fn write_parquet(frame: &DataFrame, path: &Path) -> Result<(), IoError> {
7107    let bytes = write_parquet_bytes(frame)?;
7108    std::fs::write(path, bytes)?;
7109    Ok(())
7110}
7111
7112/// Read a DataFrame from a Parquet file.
7113pub fn read_parquet(path: &Path) -> Result<DataFrame, IoError> {
7114    let data = std::fs::read(path)?;
7115    read_parquet_bytes(&data)
7116}
7117
7118// ── ORC I/O ────────────────────────────────────────────────────────────────
7119
7120/// Write a DataFrame to an in-memory ORC buffer.
7121///
7122/// This fails closed under the workspace no-Tokio policy. The previous
7123/// implementation delegated to `orc-rust`, which unconditionally pulled Tokio
7124/// into `fp-io` and therefore into the umbrella `frankenpandas` crate.
7125pub fn write_orc_bytes(_frame: &DataFrame) -> Result<Vec<u8>, IoError> {
7126    Err(orc_no_tokio_error())
7127}
7128
7129/// Read a DataFrame from in-memory ORC bytes.
7130pub fn read_orc_bytes(_data: &[u8]) -> Result<DataFrame, IoError> {
7131    Err(orc_no_tokio_error())
7132}
7133
7134/// Write a DataFrame to an ORC file.
7135pub fn write_orc(_frame: &DataFrame, _path: &Path) -> Result<(), IoError> {
7136    Err(orc_no_tokio_error())
7137}
7138
7139/// Read a DataFrame from an ORC file.
7140pub fn read_orc(_path: &Path) -> Result<DataFrame, IoError> {
7141    Err(orc_no_tokio_error())
7142}
7143
7144// ── Excel (xlsx) I/O ────────────────────────────────────────────────────
7145
7146/// Options for reading Excel files.
7147#[derive(Debug, Clone)]
7148pub struct ExcelReadOptions {
7149    /// Sheet name to read. If `None`, reads the first sheet.
7150    pub sheet_name: Option<String>,
7151    /// Whether the first row contains column headers.
7152    pub has_headers: bool,
7153    /// Read only these columns (by name). `None` means read all.
7154    /// Matches pandas `usecols` parameter for label-based selection.
7155    pub usecols: Option<Vec<String>>,
7156    /// Explicit column names to use instead of worksheet headers or
7157    /// auto-generated `column_N` names. Matches pandas `names=...`.
7158    pub names: Option<Vec<String>>,
7159    /// Optional column to use as the DataFrame index.
7160    pub index_col: Option<String>,
7161    /// Number of initial rows to skip before reading headers/data.
7162    pub skip_rows: usize,
7163}
7164
7165impl Default for ExcelReadOptions {
7166    fn default() -> Self {
7167        Self {
7168            sheet_name: None,
7169            has_headers: true,
7170            usecols: None,
7171            names: None,
7172            index_col: None,
7173            skip_rows: 0,
7174        }
7175    }
7176}
7177
7178/// Convert a calamine `Data` cell value to a `Scalar`.
7179fn excel_cell_to_scalar(cell: &calamine::Data) -> Scalar {
7180    match cell {
7181        calamine::Data::Int(v) => Scalar::Int64(*v),
7182        calamine::Data::Float(v) => {
7183            if v.is_nan() {
7184                Scalar::Null(NullKind::NaN)
7185            } else if v.fract() == 0.0 && *v >= i64::MIN as f64 && *v <= i64::MAX as f64 {
7186                // Excel stores integers as floats; recover Int64 for whole numbers.
7187                Scalar::Int64(*v as i64)
7188            } else {
7189                Scalar::Float64(*v)
7190            }
7191        }
7192        calamine::Data::String(s) => {
7193            if s.is_empty() {
7194                Scalar::Null(NullKind::Null)
7195            } else {
7196                Scalar::Utf8(s.clone())
7197            }
7198        }
7199        calamine::Data::Bool(b) => Scalar::Bool(*b),
7200        calamine::Data::Empty => Scalar::Null(NullKind::Null),
7201        calamine::Data::DateTime(dt) => {
7202            // Convert ExcelDateTime to string representation for now.
7203            Scalar::Utf8(format!("{dt}"))
7204        }
7205        calamine::Data::DateTimeIso(s) => Scalar::Utf8(s.clone()),
7206        calamine::Data::DurationIso(s) => Scalar::Utf8(s.clone()),
7207        calamine::Data::Error(e) => Scalar::Utf8(format!("#ERROR:{e:?}")),
7208    }
7209}
7210
7211/// Convert a Scalar to an IndexLabel, handling float precision correctly.
7212fn scalar_to_index_label(scalar: Scalar) -> IndexLabel {
7213    match scalar {
7214        Scalar::Int64(v) => IndexLabel::Int64(v),
7215        Scalar::Utf8(s) => IndexLabel::Utf8(s),
7216        Scalar::Float64(v) if v.fract() == 0.0 && v >= i64::MIN as f64 && v <= i64::MAX as f64 => {
7217            IndexLabel::Int64(v as i64)
7218        }
7219        Scalar::Float64(v) => IndexLabel::Utf8(v.to_string()),
7220        Scalar::Bool(b) => IndexLabel::Utf8(if b { "True" } else { "False" }.to_string()),
7221        _ => IndexLabel::Utf8(String::new()),
7222    }
7223}
7224
7225fn infer_writer_emitted_default_excel_index_col(
7226    headers: &[String],
7227    header_generated: &[bool],
7228    columns: &[Vec<Scalar>],
7229    options: &ExcelReadOptions,
7230) -> Option<usize> {
7231    if !options.has_headers
7232        || options.index_col.is_some()
7233        || options.usecols.is_some()
7234        || options.names.is_some()
7235    {
7236        return None;
7237    }
7238
7239    if headers.first()?.as_str() != "column_0"
7240        || !header_generated.first().copied().unwrap_or(false)
7241    {
7242        return None;
7243    }
7244
7245    let first_col = columns.first()?;
7246    if first_col
7247        .iter()
7248        .enumerate()
7249        .all(|(idx, scalar)| matches!(scalar, Scalar::Int64(value) if *value == idx as i64))
7250    {
7251        Some(0)
7252    } else {
7253        None
7254    }
7255}
7256
7257/// Shared parsing logic for Excel data after extracting rows from a workbook.
7258fn parse_excel_rows(
7259    rows: Vec<Vec<calamine::Data>>,
7260    options: &ExcelReadOptions,
7261) -> Result<DataFrame, IoError> {
7262    if rows.is_empty() {
7263        return DataFrame::new(Index::new(Vec::new()), BTreeMap::new()).map_err(IoError::Frame);
7264    }
7265
7266    let resolve_names = |width: usize| -> Result<Option<Vec<String>>, IoError> {
7267        options.names.as_ref().map_or(Ok(None), |names| {
7268            if names.len() == width {
7269                Ok(Some(names.clone()))
7270            } else {
7271                Err(IoError::Excel(format!(
7272                    "expected {width} column names, got {}",
7273                    names.len()
7274                )))
7275            }
7276        })
7277    };
7278
7279    // Extract headers.
7280    let (headers, header_generated, data_rows) = if options.has_headers {
7281        let header_row = &rows[0];
7282        let header_width = header_row.len();
7283        let provided_names = resolve_names(header_width)?;
7284        let (headers, header_generated): (Vec<_>, Vec<_>) = if let Some(names) = provided_names {
7285            (names, vec![false; header_width])
7286        } else {
7287            let header_pairs: Vec<(String, bool)> = header_row
7288                .iter()
7289                .enumerate()
7290                .map(|(i, cell)| match cell {
7291                    calamine::Data::String(s) if !s.is_empty() => (s.clone(), false),
7292                    _ => (format!("column_{i}"), true),
7293                })
7294                .collect();
7295            header_pairs.into_iter().unzip()
7296        };
7297        (headers, header_generated, &rows[1..])
7298    } else {
7299        let ncols = rows.iter().map(Vec::len).max().unwrap_or(0);
7300        let provided_names = resolve_names(ncols)?;
7301        let (headers, header_generated) = if let Some(names) = provided_names {
7302            (names, vec![false; ncols])
7303        } else {
7304            let headers: Vec<String> = (0..ncols).map(|i| format!("column_{i}")).collect();
7305            let header_generated = vec![true; ncols];
7306            (headers, header_generated)
7307        };
7308        (headers, header_generated, rows.as_slice())
7309    };
7310    reject_duplicate_headers(&headers)?;
7311
7312    if let Some(ref usecols) = options.usecols {
7313        validate_usecols(&headers, usecols)?;
7314    }
7315
7316    let ncols = headers.len();
7317
7318    // Accumulate columns.
7319    let mut columns: Vec<Vec<Scalar>> = (0..ncols)
7320        .map(|_| Vec::with_capacity(data_rows.len()))
7321        .collect();
7322
7323    for row in data_rows {
7324        for (col_idx, col_vec) in columns.iter_mut().enumerate() {
7325            let cell = row.get(col_idx).unwrap_or(&calamine::Data::Empty);
7326            col_vec.push(excel_cell_to_scalar(cell));
7327        }
7328    }
7329
7330    let (headers, header_generated, columns) = if let Some(ref usecols) = options.usecols {
7331        let mut filtered_headers = Vec::new();
7332        let mut filtered_generated = Vec::new();
7333        let mut filtered_columns = Vec::new();
7334        for ((name, generated), values) in headers.into_iter().zip(header_generated).zip(columns) {
7335            if usecols.contains(&name) {
7336                filtered_headers.push(name);
7337                filtered_generated.push(generated);
7338                filtered_columns.push(values);
7339            }
7340        }
7341        (filtered_headers, filtered_generated, filtered_columns)
7342    } else {
7343        (headers, header_generated, columns)
7344    };
7345
7346    // Handle index_col if specified.
7347    let index_col_idx = if let Some(ref idx_name) = options.index_col {
7348        let pos = headers.iter().position(|h| h == idx_name);
7349        if pos.is_none() {
7350            return Err(IoError::MissingIndexColumn(idx_name.clone()));
7351        }
7352        pos
7353    } else {
7354        infer_writer_emitted_default_excel_index_col(&headers, &header_generated, &columns, options)
7355    };
7356
7357    let index_name = index_col_idx.and_then(|idx_pos| {
7358        if !header_generated[idx_pos] {
7359            Some(headers[idx_pos].clone())
7360        } else {
7361            None
7362        }
7363    });
7364
7365    let mut out_columns = BTreeMap::new();
7366    let mut column_order = Vec::new();
7367
7368    for (idx, (name, values)) in headers.into_iter().zip(columns).enumerate() {
7369        if Some(idx) == index_col_idx {
7370            continue; // skip index column from data columns
7371        }
7372        out_columns.insert(name.clone(), Column::from_values(values)?);
7373        column_order.push(name);
7374    }
7375
7376    let index = if let Some(idx_pos) = index_col_idx {
7377        let idx_labels: Vec<IndexLabel> = data_rows
7378            .iter()
7379            .map(|row| {
7380                let cell = row.get(idx_pos).unwrap_or(&calamine::Data::Empty);
7381                scalar_to_index_label(excel_cell_to_scalar(cell))
7382            })
7383            .collect();
7384        Index::new(idx_labels).set_names(index_name.as_deref())
7385    } else {
7386        Index::from_i64((0..data_rows.len() as i64).collect())
7387    };
7388
7389    Ok(DataFrame::new_with_column_order(
7390        index,
7391        out_columns,
7392        column_order,
7393    )?)
7394}
7395
7396/// Read an Excel (.xlsx/.xls/.xlsb/.ods) file into a DataFrame.
7397///
7398/// Matches `pd.read_excel(path)` for basic usage.
7399pub fn read_excel(path: &Path, options: &ExcelReadOptions) -> Result<DataFrame, IoError> {
7400    use calamine::{Reader, open_workbook_auto};
7401
7402    let mut workbook = open_workbook_auto(path)
7403        .map_err(|e| IoError::Excel(format!("cannot open workbook: {e}")))?;
7404
7405    let sheet_name = if let Some(ref name) = options.sheet_name {
7406        name.clone()
7407    } else {
7408        let names = workbook.sheet_names();
7409        if names.is_empty() {
7410            return Err(IoError::Excel("workbook contains no sheets".into()));
7411        }
7412        names[0].clone()
7413    };
7414
7415    let range = workbook
7416        .worksheet_range(&sheet_name)
7417        .map_err(|e| IoError::Excel(format!("cannot read sheet '{sheet_name}': {e}")))?;
7418
7419    let rows: Vec<Vec<calamine::Data>> = range
7420        .rows()
7421        .skip(options.skip_rows)
7422        .map(|r| r.to_vec())
7423        .collect();
7424
7425    parse_excel_rows(rows, options)
7426}
7427
7428pub fn read_excel_with_index_cols(
7429    path: &Path,
7430    options: &ExcelReadOptions,
7431    index_cols: &[&str],
7432) -> Result<DataFrame, IoError> {
7433    let frame = read_excel(path, options)?;
7434    promote_frame_index_columns(&frame, index_cols)
7435}
7436
7437/// Read Excel from in-memory bytes.
7438pub fn read_excel_bytes(data: &[u8], options: &ExcelReadOptions) -> Result<DataFrame, IoError> {
7439    use calamine::{Reader, open_workbook_auto_from_rs};
7440
7441    let cursor = std::io::Cursor::new(data);
7442    let mut workbook = open_workbook_auto_from_rs(cursor)
7443        .map_err(|e| IoError::Excel(format!("cannot open workbook from bytes: {e}")))?;
7444
7445    let sheet_name = if let Some(ref name) = options.sheet_name {
7446        name.clone()
7447    } else {
7448        let names = workbook.sheet_names();
7449        if names.is_empty() {
7450            return Err(IoError::Excel("workbook contains no sheets".into()));
7451        }
7452        names[0].clone()
7453    };
7454
7455    let range = workbook
7456        .worksheet_range(&sheet_name)
7457        .map_err(|e| IoError::Excel(format!("cannot read sheet '{sheet_name}': {e}")))?;
7458
7459    let rows: Vec<Vec<calamine::Data>> = range
7460        .rows()
7461        .skip(options.skip_rows)
7462        .map(|r| r.to_vec())
7463        .collect();
7464
7465    parse_excel_rows(rows, options)
7466}
7467
7468pub fn read_excel_bytes_with_index_cols(
7469    data: &[u8],
7470    options: &ExcelReadOptions,
7471    index_cols: &[&str],
7472) -> Result<DataFrame, IoError> {
7473    let frame = read_excel_bytes(data, options)?;
7474    promote_frame_index_columns(&frame, index_cols)
7475}
7476
7477/// Read multiple sheets from an Excel file.
7478///
7479/// Matches `pd.read_excel(path, sheet_name=[...])` when `sheet_name`
7480/// is a list of sheet names — pandas returns a dict
7481/// `{name: DataFrame}`. Pass `sheet_names=None` to read every sheet
7482/// in the workbook (pandas `sheet_name=None`).
7483///
7484/// The outer Excel reader options (`has_headers`, `index_col`,
7485/// `skip_rows`) are applied uniformly to each selected sheet. The
7486/// per-sheet `sheet_name` option on `options` is ignored here
7487/// because the explicit `sheet_names` argument drives selection.
7488/// Read multiple sheets preserving workbook iteration order.
7489///
7490/// Matches `pd.read_excel(sheet_name=None)` exactly — pandas returns
7491/// a `dict` and, since Python 3.7, dict iteration order matches
7492/// insertion order, which in turn matches workbook sheet position.
7493/// `BTreeMap` (used by `read_excel_sheets`) would alphabetize, so
7494/// this sibling returns `Vec<(String, DataFrame)>` to preserve order.
7495pub fn read_excel_sheets_ordered(
7496    path: &Path,
7497    sheet_names: Option<&[String]>,
7498    options: &ExcelReadOptions,
7499) -> Result<Vec<(String, DataFrame)>, IoError> {
7500    use calamine::{Reader, open_workbook_auto};
7501
7502    let mut workbook = open_workbook_auto(path)
7503        .map_err(|e| IoError::Excel(format!("cannot open workbook: {e}")))?;
7504    let available: Vec<String> = workbook.sheet_names();
7505    // Per br-frankenpandas-c9cb4: HashSet<&str> for O(1) membership;
7506    // was O(m × n) Vec::iter().any() per requested name.
7507    let available_set: HashSet<&str> = available.iter().map(String::as_str).collect();
7508    let selected: Vec<String> = match sheet_names {
7509        Some(names) => {
7510            for name in names {
7511                if !available_set.contains(name.as_str()) {
7512                    return Err(IoError::Excel(format!(
7513                        "workbook does not contain sheet {name:?}"
7514                    )));
7515                }
7516            }
7517            names.to_vec()
7518        }
7519        None => available.clone(),
7520    };
7521    if selected.is_empty() {
7522        return Err(IoError::Excel("no sheets selected".to_owned()));
7523    }
7524    let mut out = Vec::with_capacity(selected.len());
7525    for sheet in &selected {
7526        let range = workbook
7527            .worksheet_range(sheet)
7528            .map_err(|e| IoError::Excel(format!("cannot read sheet {sheet:?}: {e}")))?;
7529        let rows: Vec<Vec<calamine::Data>> = range
7530            .rows()
7531            .skip(options.skip_rows)
7532            .map(|r| r.to_vec())
7533            .collect();
7534        let frame = parse_excel_rows(rows, options)?;
7535        out.push((sheet.clone(), frame));
7536    }
7537    Ok(out)
7538}
7539
7540/// Byte-based counterpart to `read_excel_sheets_ordered`.
7541pub fn read_excel_sheets_ordered_bytes(
7542    data: &[u8],
7543    sheet_names: Option<&[String]>,
7544    options: &ExcelReadOptions,
7545) -> Result<Vec<(String, DataFrame)>, IoError> {
7546    use calamine::{Reader, open_workbook_auto_from_rs};
7547
7548    let cursor = std::io::Cursor::new(data);
7549    let mut workbook = open_workbook_auto_from_rs(cursor)
7550        .map_err(|e| IoError::Excel(format!("cannot open workbook from bytes: {e}")))?;
7551    let available: Vec<String> = workbook.sheet_names();
7552    // Per br-frankenpandas-c9cb4: HashSet<&str> for O(1) membership;
7553    // was O(m × n) Vec::iter().any() per requested name.
7554    let available_set: HashSet<&str> = available.iter().map(String::as_str).collect();
7555    let selected: Vec<String> = match sheet_names {
7556        Some(names) => {
7557            for name in names {
7558                if !available_set.contains(name.as_str()) {
7559                    return Err(IoError::Excel(format!(
7560                        "workbook does not contain sheet {name:?}"
7561                    )));
7562                }
7563            }
7564            names.to_vec()
7565        }
7566        None => available.clone(),
7567    };
7568    if selected.is_empty() {
7569        return Err(IoError::Excel("no sheets selected".to_owned()));
7570    }
7571    let mut out = Vec::with_capacity(selected.len());
7572    for sheet in &selected {
7573        let range = workbook
7574            .worksheet_range(sheet)
7575            .map_err(|e| IoError::Excel(format!("cannot read sheet {sheet:?}: {e}")))?;
7576        let rows: Vec<Vec<calamine::Data>> = range
7577            .rows()
7578            .skip(options.skip_rows)
7579            .map(|r| r.to_vec())
7580            .collect();
7581        let frame = parse_excel_rows(rows, options)?;
7582        out.push((sheet.clone(), frame));
7583    }
7584    Ok(out)
7585}
7586
7587pub fn read_excel_sheets(
7588    path: &Path,
7589    sheet_names: Option<&[String]>,
7590    options: &ExcelReadOptions,
7591) -> Result<BTreeMap<String, DataFrame>, IoError> {
7592    use calamine::{Reader, open_workbook_auto};
7593
7594    let mut workbook = open_workbook_auto(path)
7595        .map_err(|e| IoError::Excel(format!("cannot open workbook: {e}")))?;
7596    let available: Vec<String> = workbook.sheet_names();
7597    // Per br-frankenpandas-c9cb4: HashSet<&str> for O(1) membership;
7598    // was O(m × n) Vec::iter().any() per requested name.
7599    let available_set: HashSet<&str> = available.iter().map(String::as_str).collect();
7600    let selected: Vec<String> = match sheet_names {
7601        Some(names) => {
7602            for name in names {
7603                if !available_set.contains(name.as_str()) {
7604                    return Err(IoError::Excel(format!(
7605                        "workbook does not contain sheet {name:?}"
7606                    )));
7607                }
7608            }
7609            names.to_vec()
7610        }
7611        None => available.clone(),
7612    };
7613    if selected.is_empty() {
7614        return Err(IoError::Excel("no sheets selected".to_owned()));
7615    }
7616
7617    let mut out = BTreeMap::new();
7618    for sheet in &selected {
7619        let range = workbook
7620            .worksheet_range(sheet)
7621            .map_err(|e| IoError::Excel(format!("cannot read sheet {sheet:?}: {e}")))?;
7622        let rows: Vec<Vec<calamine::Data>> = range
7623            .rows()
7624            .skip(options.skip_rows)
7625            .map(|r| r.to_vec())
7626            .collect();
7627        let frame = parse_excel_rows(rows, options)?;
7628        out.insert(sheet.clone(), frame);
7629    }
7630    Ok(out)
7631}
7632
7633/// Read multiple sheets from Excel bytes.
7634///
7635/// Byte-based counterpart to `read_excel_sheets`.
7636pub fn read_excel_sheets_bytes(
7637    data: &[u8],
7638    sheet_names: Option<&[String]>,
7639    options: &ExcelReadOptions,
7640) -> Result<BTreeMap<String, DataFrame>, IoError> {
7641    use calamine::{Reader, open_workbook_auto_from_rs};
7642
7643    let cursor = std::io::Cursor::new(data);
7644    let mut workbook = open_workbook_auto_from_rs(cursor)
7645        .map_err(|e| IoError::Excel(format!("cannot open workbook from bytes: {e}")))?;
7646    let available: Vec<String> = workbook.sheet_names();
7647    // Per br-frankenpandas-c9cb4: HashSet<&str> for O(1) membership;
7648    // was O(m × n) Vec::iter().any() per requested name.
7649    let available_set: HashSet<&str> = available.iter().map(String::as_str).collect();
7650    let selected: Vec<String> = match sheet_names {
7651        Some(names) => {
7652            for name in names {
7653                if !available_set.contains(name.as_str()) {
7654                    return Err(IoError::Excel(format!(
7655                        "workbook does not contain sheet {name:?}"
7656                    )));
7657                }
7658            }
7659            names.to_vec()
7660        }
7661        None => available.clone(),
7662    };
7663    if selected.is_empty() {
7664        return Err(IoError::Excel("no sheets selected".to_owned()));
7665    }
7666
7667    let mut out = BTreeMap::new();
7668    for sheet in &selected {
7669        let range = workbook
7670            .worksheet_range(sheet)
7671            .map_err(|e| IoError::Excel(format!("cannot read sheet {sheet:?}: {e}")))?;
7672        let rows: Vec<Vec<calamine::Data>> = range
7673            .rows()
7674            .skip(options.skip_rows)
7675            .map(|r| r.to_vec())
7676            .collect();
7677        let frame = parse_excel_rows(rows, options)?;
7678        out.insert(sheet.clone(), frame);
7679    }
7680    Ok(out)
7681}
7682
7683/// Write a DataFrame to an Excel (.xlsx) file.
7684///
7685/// Matches `pd.DataFrame.to_excel(path)`.
7686pub fn write_excel(frame: &DataFrame, path: &Path) -> Result<(), IoError> {
7687    let bytes = write_excel_bytes(frame)?;
7688    std::fs::write(path, bytes)?;
7689    Ok(())
7690}
7691
7692fn write_excel_index_label(
7693    worksheet: &mut rust_xlsxwriter::Worksheet,
7694    excel_row: u32,
7695    excel_col: u16,
7696    label: &IndexLabel,
7697) -> Result<(), IoError> {
7698    match label {
7699        IndexLabel::Int64(v) => {
7700            worksheet
7701                .write_number(excel_row, excel_col, *v as f64)
7702                .map_err(|e| IoError::Excel(format!("write index int: {e}")))?;
7703        }
7704        IndexLabel::Utf8(s) => {
7705            worksheet
7706                .write_string(excel_row, excel_col, s.as_str())
7707                .map_err(|e| IoError::Excel(format!("write index string: {e}")))?;
7708        }
7709        IndexLabel::Timedelta64(v) => {
7710            if *v != Timedelta::NAT {
7711                worksheet
7712                    .write_string(excel_row, excel_col, Timedelta::format(*v))
7713                    .map_err(|e| IoError::Excel(format!("write index timedelta: {e}")))?;
7714            }
7715        }
7716        IndexLabel::Datetime64(v) => {
7717            if *v != i64::MIN {
7718                worksheet
7719                    .write_string(excel_row, excel_col, label.to_string())
7720                    .map_err(|e| IoError::Excel(format!("write index datetime: {e}")))?;
7721            }
7722        }
7723        // Missing labels leave the cell blank, like NAT timedelta/datetime
7724        // above (pandas writes an empty cell for a NaN index label).
7725        IndexLabel::Float64(v) => {
7726            worksheet
7727                .write_number(excel_row, excel_col, v.0)
7728                .map_err(|e| IoError::Excel(format!("write index float: {e}")))?;
7729        }
7730        IndexLabel::Bool(b) => {
7731            worksheet
7732                .write_boolean(excel_row, excel_col, *b)
7733                .map_err(|e| IoError::Excel(format!("write index bool: {e}")))?;
7734        }
7735        IndexLabel::Null(_) => {}
7736    }
7737    Ok(())
7738}
7739
7740fn write_excel_scalar(
7741    worksheet: &mut rust_xlsxwriter::Worksheet,
7742    excel_row: u32,
7743    excel_col: u16,
7744    scalar: &Scalar,
7745) -> Result<(), IoError> {
7746    match scalar {
7747        Scalar::Int64(v) => {
7748            worksheet
7749                .write_number(excel_row, excel_col, *v as f64)
7750                .map_err(|e| IoError::Excel(format!("write int: {e}")))?;
7751        }
7752        Scalar::Float64(v) if !v.is_nan() => {
7753            worksheet
7754                .write_number(excel_row, excel_col, *v)
7755                .map_err(|e| IoError::Excel(format!("write float: {e}")))?;
7756        }
7757        Scalar::Bool(b) => {
7758            worksheet
7759                .write_boolean(excel_row, excel_col, *b)
7760                .map_err(|e| IoError::Excel(format!("write bool: {e}")))?;
7761        }
7762        Scalar::Utf8(s) => {
7763            worksheet
7764                .write_string(excel_row, excel_col, s.as_str())
7765                .map_err(|e| IoError::Excel(format!("write string: {e}")))?;
7766        }
7767        Scalar::Timedelta64(v) => {
7768            if *v != Timedelta::NAT {
7769                worksheet
7770                    .write_string(excel_row, excel_col, Timedelta::format(*v))
7771                    .map_err(|e| IoError::Excel(format!("write timedelta: {e}")))?;
7772            }
7773        }
7774        Scalar::Datetime64(v) => {
7775            if *v != Timestamp::NAT {
7776                worksheet
7777                    .write_string(excel_row, excel_col, format_datetime_ns(*v))
7778                    .map_err(|e| IoError::Excel(format!("write datetime: {e}")))?;
7779            }
7780        }
7781        Scalar::Period(p) => {
7782            if p.ordinal != i64::MIN {
7783                worksheet
7784                    .write_string(excel_row, excel_col, p.calendar_string())
7785                    .map_err(|e| IoError::Excel(format!("write period: {e}")))?;
7786            }
7787        }
7788        Scalar::Interval(iv) => {
7789            worksheet
7790                .write_string(excel_row, excel_col, format!("{iv}"))
7791                .map_err(|e| IoError::Excel(format!("write interval: {e}")))?;
7792        }
7793        Scalar::Float64(_) | Scalar::Null(_) => {}
7794    }
7795    Ok(())
7796}
7797
7798/// Write a DataFrame to Excel (.xlsx) bytes in memory.
7799///
7800/// Matches pandas `DataFrame.to_excel()` default index behavior by emitting
7801/// the index as the first worksheet column.
7802pub fn write_excel_bytes(frame: &DataFrame) -> Result<Vec<u8>, IoError> {
7803    write_excel_bytes_with_options(frame, &ExcelWriteOptions::default())
7804}
7805
7806/// Options for serializing a DataFrame to Excel.
7807///
7808/// Mirrors the subset of `pd.DataFrame.to_excel` parameters that
7809/// don't depend on the workbook writer itself.
7810#[derive(Debug, Clone)]
7811pub struct ExcelWriteOptions {
7812    /// Target sheet name. Default: `"Sheet1"` (rust_xlsxwriter default).
7813    pub sheet_name: String,
7814    /// Whether to write the row index as a leading column. Matches
7815    /// pandas `index=True|False`. Default: true.
7816    pub index: bool,
7817    /// Header label for the index column when `index=true`. When
7818    /// `None`, the frame's index name is used (falling back to an
7819    /// empty string). Matches pandas `index_label=...`.
7820    pub index_label: Option<String>,
7821    /// Whether to emit the column-name header row. Matches pandas
7822    /// `header=True|False`. Default: true.
7823    pub header: bool,
7824}
7825
7826impl Default for ExcelWriteOptions {
7827    fn default() -> Self {
7828        Self {
7829            sheet_name: "Sheet1".to_string(),
7830            index: true,
7831            index_label: None,
7832            header: true,
7833        }
7834    }
7835}
7836
7837/// Serialize a DataFrame to Excel bytes with explicit options.
7838///
7839/// Matches `pd.DataFrame.to_excel(sheet_name, index, index_label,
7840/// header)` for the in-memory byte form. The default `ExcelWriteOptions`
7841/// reproduces the existing `write_excel_bytes` behavior (index=true,
7842/// sheet_name="Sheet1").
7843pub fn write_excel_bytes_with_options(
7844    frame: &DataFrame,
7845    options: &ExcelWriteOptions,
7846) -> Result<Vec<u8>, IoError> {
7847    if options.index && frame.row_multiindex().is_some() {
7848        let materialized = materialize_named_row_multiindex_columns(frame)?;
7849        let mut nested_options = options.clone();
7850        nested_options.index = false;
7851        nested_options.index_label = None;
7852        return write_excel_bytes_with_options(&materialized, &nested_options);
7853    }
7854
7855    use rust_xlsxwriter::Workbook;
7856
7857    let mut workbook = Workbook::new();
7858    let worksheet = workbook.add_worksheet();
7859    worksheet
7860        .set_name(options.sheet_name.as_str())
7861        .map_err(|e| IoError::Excel(format!("set sheet name: {e}")))?;
7862
7863    let col_names: Vec<String> = frame.column_names().into_iter().cloned().collect();
7864    let data_col_offset: u16 = if options.index { 1 } else { 0 };
7865
7866    // Header row (optional).
7867    if options.header {
7868        if options.index {
7869            let idx_header = options
7870                .index_label
7871                .as_deref()
7872                .unwrap_or_else(|| frame.index().name().unwrap_or(""));
7873            worksheet
7874                .write_string(0, 0, idx_header)
7875                .map_err(|e| IoError::Excel(format!("write index header: {e}")))?;
7876        }
7877        for (col_idx, name) in col_names.iter().enumerate() {
7878            worksheet
7879                .write_string(0, data_col_offset + col_idx as u16, name.as_str())
7880                .map_err(|e| IoError::Excel(format!("write header: {e}")))?;
7881        }
7882    }
7883
7884    // Data rows — when header=true the first data row lands at excel
7885    // row 1; when header=false data starts at row 0.
7886    let header_rows: u32 = if options.header { 1 } else { 0 };
7887    let nrows = frame.index().len();
7888    for row_idx in 0..nrows {
7889        let excel_row = row_idx as u32 + header_rows;
7890        if options.index
7891            && let Some(label) = frame.index().labels().get(row_idx)
7892        {
7893            write_excel_index_label(worksheet, excel_row, 0, label)?;
7894        }
7895        for (col_idx, name) in col_names.iter().enumerate() {
7896            if let Some(col) = frame.column(name)
7897                && let Some(scalar) = col.value(row_idx)
7898            {
7899                write_excel_scalar(
7900                    worksheet,
7901                    excel_row,
7902                    data_col_offset + col_idx as u16,
7903                    scalar,
7904                )?;
7905            }
7906        }
7907    }
7908
7909    let buf = workbook
7910        .save_to_buffer()
7911        .map_err(|e| IoError::Excel(format!("save workbook: {e}")))?;
7912
7913    Ok(buf)
7914}
7915
7916/// File-based counterpart to `write_excel_bytes_with_options`.
7917pub fn write_excel_with_options(
7918    frame: &DataFrame,
7919    path: &Path,
7920    options: &ExcelWriteOptions,
7921) -> Result<(), IoError> {
7922    let bytes = write_excel_bytes_with_options(frame, options)?;
7923    std::fs::write(path, bytes)?;
7924    Ok(())
7925}
7926
7927// ── Arrow IPC / Feather I/O ──────────────────────────────────────────────
7928
7929/// Write a DataFrame to Arrow IPC (Feather v2) bytes in memory.
7930///
7931/// Matches `pd.DataFrame.to_feather()`. Feather v2 is the Arrow IPC file format
7932/// — the fastest columnar interchange format, recommended by pandas over HDF5.
7933pub fn write_feather_bytes(frame: &DataFrame) -> Result<Vec<u8>, IoError> {
7934    use arrow::ipc::writer::FileWriter;
7935
7936    let batch = dataframe_to_record_batch(frame)?;
7937    let schema = batch.schema();
7938
7939    let mut buf = Vec::new();
7940    let mut writer =
7941        FileWriter::try_new(&mut buf, &schema).map_err(|e| IoError::Arrow(e.to_string()))?;
7942    writer
7943        .write(&batch)
7944        .map_err(|e| IoError::Arrow(e.to_string()))?;
7945    writer.finish().map_err(|e| IoError::Arrow(e.to_string()))?;
7946    Ok(buf)
7947}
7948
7949/// Read a DataFrame from Arrow IPC (Feather v2) bytes in memory.
7950///
7951/// Matches `pd.read_feather()`.
7952pub fn read_feather_bytes(data: &[u8]) -> Result<DataFrame, IoError> {
7953    use arrow::ipc::reader::FileReader;
7954
7955    let cursor = std::io::Cursor::new(data);
7956    let reader = FileReader::try_new(cursor, None).map_err(|e| IoError::Arrow(e.to_string()))?;
7957
7958    let mut all_frames: Vec<DataFrame> = Vec::new();
7959    for batch_result in reader {
7960        let batch = batch_result.map_err(|e| IoError::Arrow(e.to_string()))?;
7961        all_frames.push(record_batch_to_dataframe(&batch)?);
7962    }
7963
7964    if all_frames.is_empty() {
7965        return Ok(DataFrame::new_with_column_order(
7966            Index::new(vec![]),
7967            BTreeMap::new(),
7968            vec![],
7969        )?);
7970    }
7971
7972    if all_frames.len() == 1 {
7973        if let Some(frame) = all_frames.into_iter().next() {
7974            return Ok(frame);
7975        }
7976        return Err(IoError::Arrow(
7977            "feather reader produced zero record batches".to_owned(),
7978        ));
7979    }
7980
7981    let refs: Vec<&DataFrame> = all_frames.iter().collect();
7982    fp_frame::concat_dataframes(&refs).map_err(IoError::from)
7983}
7984
7985/// Write a DataFrame to an Arrow IPC (Feather v2) file.
7986///
7987/// Matches `pd.DataFrame.to_feather(path)`.
7988pub fn write_feather(frame: &DataFrame, path: &Path) -> Result<(), IoError> {
7989    let bytes = write_feather_bytes(frame)?;
7990    std::fs::write(path, bytes)?;
7991    Ok(())
7992}
7993
7994/// Read a DataFrame from an Arrow IPC (Feather v2) file.
7995///
7996/// Matches `pd.read_feather(path)`.
7997pub fn read_feather(path: &Path) -> Result<DataFrame, IoError> {
7998    let data = std::fs::read(path)?;
7999    read_feather_bytes(&data)
8000}
8001
8002/// Write a DataFrame to Arrow IPC stream bytes (streaming format, no random access).
8003///
8004/// Unlike Feather (file format), the stream format has no footer and supports
8005/// streaming reads without seeking. Used for inter-process communication.
8006pub fn write_ipc_stream_bytes(frame: &DataFrame) -> Result<Vec<u8>, IoError> {
8007    use arrow::ipc::writer::StreamWriter;
8008
8009    let batch = dataframe_to_record_batch(frame)?;
8010    let schema = batch.schema();
8011
8012    let mut buf = Vec::new();
8013    let mut writer =
8014        StreamWriter::try_new(&mut buf, &schema).map_err(|e| IoError::Arrow(e.to_string()))?;
8015    writer
8016        .write(&batch)
8017        .map_err(|e| IoError::Arrow(e.to_string()))?;
8018    writer.finish().map_err(|e| IoError::Arrow(e.to_string()))?;
8019    Ok(buf)
8020}
8021
8022/// Read a DataFrame from Arrow IPC stream bytes (streaming format).
8023pub fn read_ipc_stream_bytes(data: &[u8]) -> Result<DataFrame, IoError> {
8024    use arrow::ipc::reader::StreamReader;
8025
8026    let cursor = std::io::Cursor::new(data);
8027    let reader = StreamReader::try_new(cursor, None).map_err(|e| IoError::Arrow(e.to_string()))?;
8028
8029    let mut all_frames: Vec<DataFrame> = Vec::new();
8030    for batch_result in reader {
8031        let batch = batch_result.map_err(|e| IoError::Arrow(e.to_string()))?;
8032        all_frames.push(record_batch_to_dataframe(&batch)?);
8033    }
8034
8035    if all_frames.is_empty() {
8036        return Ok(DataFrame::new_with_column_order(
8037            Index::new(vec![]),
8038            BTreeMap::new(),
8039            vec![],
8040        )?);
8041    }
8042
8043    if all_frames.len() == 1 {
8044        if let Some(frame) = all_frames.into_iter().next() {
8045            return Ok(frame);
8046        }
8047        return Err(IoError::Arrow(
8048            "ipc stream reader produced zero record batches".to_owned(),
8049        ));
8050    }
8051
8052    let refs: Vec<&DataFrame> = all_frames.iter().collect();
8053    fp_frame::concat_dataframes(&refs).map_err(IoError::from)
8054}
8055
8056// ── SQL I/O ─────────────────────────────────────────────────────────────
8057
8058/// Options for writing a DataFrame to SQL.
8059#[derive(Debug, Clone, Copy, PartialEq, Eq)]
8060pub enum SqlIfExists {
8061    /// Raise an error if the table already exists.
8062    Fail,
8063    /// Drop the table and recreate it.
8064    Replace,
8065    /// Insert new rows into the existing table.
8066    Append,
8067}
8068
8069/// Strategy for emitting INSERT statements during `write_sql`.
8070///
8071/// Matches `pd.DataFrame.to_sql(.., method=...)` shape:
8072/// `Single` (default) emits one `INSERT INTO t VALUES (?, ...)` per row,
8073/// reusing a prepared statement under a transaction. `Multi` builds a
8074/// single multi-row `INSERT INTO t VALUES (...), (...), ...` statement
8075/// per chunk, where chunk size is `max_param_count() / num_cols` (or
8076/// the whole frame when the backend reports no max). `Multi` typically
8077/// wins on backends with high per-statement overhead (PostgreSQL,
8078/// MySQL); SQLite is already fast under prepared-statement reuse so the
8079/// gap there is small.
8080///
8081/// Per br-frankenpandas-i0ml (fd90.19).
8082#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
8083pub enum SqlInsertMethod {
8084    /// One INSERT per row, prepared once and re-bound per row.
8085    #[default]
8086    Single,
8087    /// Multi-row INSERT, chunked by the backend's parameter limit.
8088    Multi,
8089}
8090
8091/// Options for reading SQL query results into a DataFrame.
8092#[derive(Debug, Clone)]
8093pub struct SqlReadOptions {
8094    /// Positional parameters to bind to `?` placeholders in the SQL query.
8095    pub params: Option<Vec<Scalar>>,
8096    /// Column names to coerce via pandas-style parse_dates handling.
8097    /// Currently supports explicit column-name selection.
8098    pub parse_dates: Option<Vec<String>>,
8099    /// Promote decimal-like SQL text result columns to Float64.
8100    ///
8101    /// This is an opt-in form of pandas' `coerce_float` behavior for
8102    /// backends that expose NUMERIC/DECIMAL/MONEY values through text.
8103    /// Columns containing any non-numeric strings are left unchanged.
8104    pub coerce_float: bool,
8105    /// Per-column dtype override applied after row materialization.
8106    ///
8107    /// Matches `pd.read_sql(.., dtype={'col': 'float64'})`. Each entry casts
8108    /// the named column to the declared dtype using `fp_types::cast_scalar_owned`.
8109    /// Map entries for columns not present in the result are silently
8110    /// ignored (matches pandas). Columns also listed in `parse_dates` are
8111    /// skipped to avoid double-cast errors — parse_dates wins.
8112    ///
8113    /// Per br-frankenpandas-l9pt (fd90.11).
8114    pub dtype: Option<BTreeMap<String, DType>>,
8115    /// Optional schema namespace for `read_sql_table` lookups.
8116    ///
8117    /// Matches `pd.read_sql_table(table, con, schema=...)`. When the
8118    /// backend reports `supports_schemas() == true` (PostgreSQL, MySQL,
8119    /// MSSQL, etc.) and `schema` is `Some(s)`, the SELECT references
8120    /// `s.table` with each part quoted by `conn.quote_identifier(...)`.
8121    /// When the backend reports `supports_schemas() == false` (SQLite),
8122    /// any `Some(s)` here is rejected before query execution. Pandas /
8123    /// SQLAlchemy raises `NotImplementedError` on that surface; failing
8124    /// closed avoids silently reading an unqualified table from the wrong
8125    /// namespace.
8126    ///
8127    /// Per br-frankenpandas-u6zn (fd90.14).
8128    pub schema: Option<String>,
8129    /// Optional projection list for `read_sql_table` reads.
8130    ///
8131    /// Matches `pd.read_sql_table(table, con, columns=[...])`. When
8132    /// `Some(list)`, the emitted SELECT projects only those columns
8133    /// (and in that order) instead of `SELECT *`. `None` preserves
8134    /// `SELECT *`. An empty Vec is rejected with `IoError::Sql` —
8135    /// pandas raises ValueError there. Each entry is validated via
8136    /// the standard alphanumeric+underscore policy.
8137    ///
8138    /// Note: `read_sql` / `read_sql_query` ignore this field — it
8139    /// only takes effect on `read_sql_table*` paths, where
8140    /// frankenpandas builds the SELECT itself.
8141    ///
8142    /// Per br-frankenpandas-d3e9 (fd90.34).
8143    pub columns: Option<Vec<String>>,
8144    /// Optional column name to promote to the DataFrame index.
8145    ///
8146    /// Matches `pd.read_sql(.., index_col=...)` and
8147    /// `pd.read_sql_table(table, con, index_col=...)`. When
8148    /// `Some(name)`, after row materialization the named column is
8149    /// removed from the result and used as the DataFrame index. The
8150    /// column must exist in the read result (or in the projection
8151    /// when `columns` is also set). `None` preserves the default
8152    /// RangeIndex.
8153    ///
8154    /// Empty string is rejected with `IoError::Sql` to match
8155    /// pandas' ValueError. List-of-strings (for MultiIndex) is out
8156    /// of scope for this slice — single index only.
8157    ///
8158    /// Per br-frankenpandas-c1h9 (fd90.36).
8159    pub index_col: Option<String>,
8160}
8161
8162impl Default for SqlReadOptions {
8163    /// Per br-frankenpandas-o0x6 (fd90.41): pandas defaults
8164    /// `coerce_float=True` for `read_sql` / `read_sql_query` /
8165    /// `read_sql_table` so we follow suit. Other defaults are the
8166    /// natural empty / None values.
8167    fn default() -> Self {
8168        Self {
8169            params: None,
8170            parse_dates: None,
8171            coerce_float: true,
8172            dtype: None,
8173            schema: None,
8174            columns: None,
8175            index_col: None,
8176        }
8177    }
8178}
8179
8180/// Options for writing a DataFrame to SQL.
8181#[derive(Debug, Clone, PartialEq, Eq)]
8182pub struct SqlWriteOptions {
8183    /// Behavior when the target table already exists.
8184    pub if_exists: SqlIfExists,
8185    /// Whether to materialize the DataFrame index as the leading SQL column.
8186    pub index: bool,
8187    /// Optional override for the emitted index column name.
8188    pub index_label: Option<String>,
8189    /// Optional schema namespace for CREATE TABLE / INSERT routing.
8190    ///
8191    /// Matches `pd.DataFrame.to_sql(table, con, schema=...)`. When the
8192    /// backend reports `supports_schemas() == true` and `schema` is
8193    /// `Some(s)`, generated CREATE TABLE / INSERT statements target
8194    /// `\"s\".\"table\"`. On backends that report `false` (SQLite),
8195    /// `Some(s)` is silently ignored — preserves SQLite users' existing
8196    /// option structs.
8197    ///
8198    /// Per br-frankenpandas-udn6 (fd90.15).
8199    pub schema: Option<String>,
8200    /// Per-column SQL-type override applied during CREATE TABLE.
8201    ///
8202    /// Matches `pd.DataFrame.to_sql(.., dtype={'amount': 'NUMERIC(10,2)'})`.
8203    /// Each entry's value is the literal SQL type string emitted in the
8204    /// column definition for that column. Map entries for columns not
8205    /// in the frame are silently ignored (matches pandas). Falls back
8206    /// to `conn.dtype_sql(DType)` when no override is present.
8207    ///
8208    /// Per br-frankenpandas-ev2s (fd90.18).
8209    pub dtype: Option<BTreeMap<String, String>>,
8210    /// INSERT-emission strategy.
8211    ///
8212    /// Default `Single` matches pandas' default: one INSERT per row,
8213    /// re-binding a prepared statement under a transaction. `Multi`
8214    /// switches to multi-row VALUES batched by `conn.max_param_count()`,
8215    /// matching `pd.to_sql(.., method='multi')`.
8216    ///
8217    /// Per br-frankenpandas-i0ml (fd90.19).
8218    pub method: SqlInsertMethod,
8219    /// Maximum rows per transaction-bounded INSERT chunk.
8220    ///
8221    /// Matches `pd.DataFrame.to_sql(.., chunksize=...)`. When `Some(n)`,
8222    /// the row emit loop batches into chunks of `n` rows, each routed
8223    /// through its own `insert_rows` call (which on transactional
8224    /// backends commits a fresh transaction per chunk). This caps WAL /
8225    /// journal size for huge frames where the default `Single`
8226    /// single-transaction mode would balloon. For `Multi` mode the
8227    /// effective per-chunk row count is `min(chunksize,
8228    /// max_param_count / num_cols)`. `None` preserves existing
8229    /// single-transaction semantics.
8230    ///
8231    /// `Some(0)` is rejected — pandas raises ValueError there too.
8232    ///
8233    /// Per br-frankenpandas-ls9z (fd90.33).
8234    pub chunksize: Option<usize>,
8235}
8236
8237/// Backend-agnostic in-memory representation of a SQL query result.
8238#[derive(Debug, Clone, PartialEq)]
8239pub struct SqlQueryResult {
8240    pub columns: Vec<String>,
8241    pub rows: Vec<Vec<Scalar>>,
8242}
8243
8244type SqlColumnDtypeHints = Vec<Option<DType>>;
8245type SqlMaterializedColumns = (Vec<String>, Vec<Vec<Scalar>>, SqlColumnDtypeHints);
8246
8247/// Backend-neutral SQL column metadata.
8248#[derive(Debug, Clone, PartialEq, Eq)]
8249pub struct SqlColumnSchema {
8250    pub name: String,
8251    pub declared_type: Option<String>,
8252    pub nullable: bool,
8253    pub default_value: Option<String>,
8254    pub primary_key_ordinal: Option<usize>,
8255    /// Column-level comment text, when the backend exposes one.
8256    ///
8257    /// Per br-frankenpandas-cfld (fd90.35). SQLite has no column-comment
8258    /// storage so the rusqlite override always emits `None`. PostgreSQL
8259    /// impls populate from `pg_catalog.pg_description.col_description`;
8260    /// MySQL uses `information_schema.columns.column_comment`; MSSQL
8261    /// reads from `sys.extended_properties`. Companion to the
8262    /// table-level `table_comment` (fd90.32) — together they round
8263    /// out SQLAlchemy.Inspector.get_columns() parity (its dict shape
8264    /// includes a `'comment'` key).
8265    pub comment: Option<String>,
8266    /// Whether the column is auto-incrementing.
8267    ///
8268    /// Per br-frankenpandas-bkl2 (fd90.37). Completes
8269    /// SQLAlchemy.Inspector.get_columns() parity (the dict shape
8270    /// includes an `'autoincrement'` key).
8271    ///
8272    /// SQLite detection rule (in the rusqlite `table_schema`
8273    /// override): true when `declared_type` is `INTEGER`
8274    /// (case-insensitive) AND the column is the sole primary key
8275    /// (`primary_key_ordinal == Some(0)`) — SQLite makes
8276    /// `INTEGER PRIMARY KEY` an alias for the auto-increment
8277    /// `rowid`. The optional `AUTOINCREMENT` keyword affects
8278    /// whether IDs are reused after delete but does not change the
8279    /// "is auto-incrementing" property pandas cares about.
8280    ///
8281    /// Other backends: PG SERIAL/BIGSERIAL/IDENTITY columns
8282    /// `true`; MySQL `AUTO_INCREMENT` modifier `true`; otherwise
8283    /// `false`.
8284    pub autoincrement: bool,
8285}
8286
8287/// Backend-neutral SQL table metadata.
8288#[derive(Debug, Clone, PartialEq, Eq)]
8289pub struct SqlTableSchema {
8290    pub table_name: String,
8291    pub columns: Vec<SqlColumnSchema>,
8292}
8293
8294impl SqlTableSchema {
8295    pub fn column(&self, name: &str) -> Option<&SqlColumnSchema> {
8296        self.columns.iter().find(|column| column.name == name)
8297    }
8298}
8299
8300/// Backend-neutral SQL index metadata.
8301///
8302/// Per br-frankenpandas-bgv9 (fd90.28). Used by `list_indexes` /
8303/// `list_sql_indexes` to surface user-defined indexes so callers can
8304/// align with `SQLAlchemy.Inspector.get_indexes()` shape.
8305#[derive(Debug, Clone, PartialEq, Eq)]
8306pub struct SqlIndexSchema {
8307    pub name: String,
8308    pub columns: Vec<String>,
8309    pub unique: bool,
8310}
8311
8312/// Backend-neutral SQL unique-constraint metadata.
8313///
8314/// Per br-frankenpandas-sh4v (fd90.31). Surfaces inline `UNIQUE`
8315/// declarations and `UNIQUE (...)` table constraints separately from
8316/// user-created `CREATE UNIQUE INDEX` (those land in
8317/// `SqlIndexSchema` via `list_indexes`). `name` may be backend-
8318/// generated (SQLite reports `sqlite_autoindex_<table>_<n>`) when
8319/// the constraint was declared inline without an explicit name —
8320/// we surface the backend's name verbatim rather than fabricating.
8321#[derive(Debug, Clone, PartialEq, Eq)]
8322pub struct SqlUniqueConstraintSchema {
8323    pub name: String,
8324    pub columns: Vec<String>,
8325}
8326
8327/// Bundle of all introspection metadata for a single SQL table.
8328///
8329/// Per br-frankenpandas-76mw (fd90.40). Returned by
8330/// `SqlInspector::reflect_table` to give callers the full picture of
8331/// a table in one call instead of 5 separate trait dispatches.
8332/// Mirrors the bundled view that `SQLAlchemy.MetaData.reflect_table`
8333/// builds internally.
8334#[derive(Debug, Clone, PartialEq, Eq)]
8335pub struct SqlReflectedTable {
8336    pub table_name: String,
8337    pub columns: Vec<SqlColumnSchema>,
8338    pub primary_key_columns: Vec<String>,
8339    pub indexes: Vec<SqlIndexSchema>,
8340    pub foreign_keys: Vec<SqlForeignKeySchema>,
8341    pub unique_constraints: Vec<SqlUniqueConstraintSchema>,
8342    pub comment: Option<String>,
8343}
8344
8345impl SqlReflectedTable {
8346    /// Look up a column by name. Mirrors `SqlTableSchema::column`.
8347    ///
8348    /// Per br-frankenpandas-63ac (fd90.51).
8349    #[must_use]
8350    pub fn column(&self, name: &str) -> Option<&SqlColumnSchema> {
8351        self.columns.iter().find(|c| c.name == name)
8352    }
8353
8354    /// Look up an index by name.
8355    ///
8356    /// Per br-frankenpandas-63ac (fd90.51).
8357    #[must_use]
8358    pub fn index(&self, name: &str) -> Option<&SqlIndexSchema> {
8359        self.indexes.iter().find(|i| i.name == name)
8360    }
8361
8362    /// Look up a unique constraint by name (backend-generated names
8363    /// like `sqlite_autoindex_*` count too — match what
8364    /// `list_unique_constraints` surfaced).
8365    ///
8366    /// Per br-frankenpandas-63ac (fd90.51).
8367    #[must_use]
8368    pub fn unique_constraint(&self, name: &str) -> Option<&SqlUniqueConstraintSchema> {
8369        self.unique_constraints.iter().find(|u| u.name == name)
8370    }
8371
8372    /// Find every foreign key whose `columns` slice contains `column_name`.
8373    ///
8374    /// A given column may participate in multiple FK constraints (e.g.
8375    /// the same column referenced by separate FKs to different parents
8376    /// — rare but valid SQL). Returns the matching FKs in their
8377    /// declaration order from PRAGMA foreign_key_list.
8378    ///
8379    /// Per br-frankenpandas-63ac (fd90.51).
8380    #[must_use]
8381    pub fn foreign_keys_for_column(&self, column_name: &str) -> Vec<&SqlForeignKeySchema> {
8382        self.foreign_keys
8383            .iter()
8384            .filter(|fk| fk.columns.iter().any(|c| c == column_name))
8385            .collect()
8386    }
8387
8388    /// Find every index whose `columns` slice contains `column_name`.
8389    ///
8390    /// Matches multi-column indexes where the column appears at any
8391    /// position (first, middle, last) — useful for answering "is this
8392    /// column indexed" rather than the more restrictive "is this
8393    /// column the leading entry of an index" question.
8394    ///
8395    /// Per br-frankenpandas-37uy (fd90.52).
8396    #[must_use]
8397    pub fn indexes_for_column(&self, column_name: &str) -> Vec<&SqlIndexSchema> {
8398        self.indexes
8399            .iter()
8400            .filter(|i| i.columns.iter().any(|c| c == column_name))
8401            .collect()
8402    }
8403
8404    /// Find every UNIQUE constraint whose `columns` slice contains
8405    /// `column_name`.
8406    ///
8407    /// Same any-position match semantics as `indexes_for_column` and
8408    /// `foreign_keys_for_column`.
8409    ///
8410    /// Per br-frankenpandas-37uy (fd90.52).
8411    #[must_use]
8412    pub fn unique_constraints_for_column(
8413        &self,
8414        column_name: &str,
8415    ) -> Vec<&SqlUniqueConstraintSchema> {
8416        self.unique_constraints
8417            .iter()
8418            .filter(|u| u.columns.iter().any(|c| c == column_name))
8419            .collect()
8420    }
8421}
8422
8423/// Backend-neutral SQL foreign-key constraint metadata.
8424///
8425/// Per br-frankenpandas-uht8 (fd90.29). Aligns with
8426/// `SQLAlchemy.Inspector.get_foreign_keys()` shape: a single FK
8427/// constraint may span multiple columns (composite FK), and
8428/// `columns[i]` references `referenced_columns[i]` on
8429/// `referenced_table`. `constraint_name` is `None` for SQLite
8430/// inline FKs declared without an explicit CONSTRAINT name (PRAGMA
8431/// foreign_key_list does not surface a name, so we return None
8432/// there rather than fabricating one).
8433#[derive(Debug, Clone, PartialEq, Eq)]
8434pub struct SqlForeignKeySchema {
8435    pub constraint_name: Option<String>,
8436    pub columns: Vec<String>,
8437    pub referenced_table: String,
8438    pub referenced_columns: Vec<String>,
8439}
8440
8441/// Iterator over DataFrame chunks produced by a SQL query.
8442pub struct SqlChunkIterator<'conn> {
8443    state: SqlChunkIteratorState<'conn>,
8444}
8445
8446enum SqlChunkIteratorState<'conn> {
8447    Materialized {
8448        headers: Vec<String>,
8449        columns: Vec<Vec<Scalar>>,
8450        dtype_hints: SqlColumnDtypeHints,
8451        chunk_size: usize,
8452        next_row: usize,
8453    },
8454    Paged {
8455        conn: &'conn dyn SqlConnection,
8456        query: String,
8457        options: SqlReadOptions,
8458        headers: Vec<String>,
8459        chunk_size: usize,
8460        next_offset: usize,
8461        finished: bool,
8462    },
8463}
8464
8465impl std::fmt::Debug for SqlChunkIterator<'_> {
8466    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
8467        match &self.state {
8468            SqlChunkIteratorState::Materialized {
8469                headers,
8470                columns,
8471                dtype_hints: _,
8472                chunk_size,
8473                next_row,
8474            } => f
8475                .debug_struct("SqlChunkIterator")
8476                .field("mode", &"materialized")
8477                .field("headers", headers)
8478                .field("row_count", &columns.first().map_or(0, Vec::len))
8479                .field("chunk_size", chunk_size)
8480                .field("next_row", next_row)
8481                .finish(),
8482            SqlChunkIteratorState::Paged {
8483                query,
8484                headers,
8485                chunk_size,
8486                next_offset,
8487                finished,
8488                ..
8489            } => f
8490                .debug_struct("SqlChunkIterator")
8491                .field("mode", &"paged")
8492                .field("query", query)
8493                .field("headers", headers)
8494                .field("chunk_size", chunk_size)
8495                .field("next_offset", next_offset)
8496                .field("finished", finished)
8497                .finish(),
8498        }
8499    }
8500}
8501
8502impl<'conn> SqlChunkIterator<'conn> {
8503    fn materialized(
8504        headers: Vec<String>,
8505        columns: Vec<Vec<Scalar>>,
8506        dtype_hints: SqlColumnDtypeHints,
8507        chunk_size: usize,
8508    ) -> Self {
8509        Self {
8510            state: SqlChunkIteratorState::Materialized {
8511                headers,
8512                columns,
8513                dtype_hints,
8514                chunk_size,
8515                next_row: 0,
8516            },
8517        }
8518    }
8519
8520    fn paged<C: SqlConnection + 'conn>(
8521        conn: &'conn C,
8522        query: &str,
8523        options: &SqlReadOptions,
8524        chunk_size: usize,
8525    ) -> Result<Self, IoError> {
8526        let headers = sql_paged_query_headers(conn, query, options)?;
8527        Ok(Self {
8528            state: SqlChunkIteratorState::Paged {
8529                conn,
8530                query: sql_trim_chunk_source(query)?.to_owned(),
8531                options: options.clone(),
8532                headers,
8533                chunk_size,
8534                next_offset: 0,
8535                finished: false,
8536            },
8537        })
8538    }
8539
8540    fn headers(&self) -> &[String] {
8541        match &self.state {
8542            SqlChunkIteratorState::Materialized { headers, .. }
8543            | SqlChunkIteratorState::Paged { headers, .. } => headers,
8544        }
8545    }
8546}
8547
8548impl Iterator for SqlChunkIterator<'_> {
8549    type Item = Result<DataFrame, IoError>;
8550
8551    fn next(&mut self) -> Option<Self::Item> {
8552        match &mut self.state {
8553            SqlChunkIteratorState::Materialized {
8554                headers,
8555                columns,
8556                dtype_hints,
8557                chunk_size,
8558                next_row,
8559            } => {
8560                let row_count = columns.first().map_or(0, Vec::len);
8561                if *next_row >= row_count {
8562                    return None;
8563                }
8564
8565                let start = *next_row;
8566                let end = start.saturating_add(*chunk_size).min(row_count);
8567                *next_row = end;
8568
8569                let chunk_columns = columns
8570                    .iter()
8571                    .map(|column| column[start..end].to_vec())
8572                    .collect();
8573                Some(dataframe_from_sql_columns(
8574                    headers.clone(),
8575                    chunk_columns,
8576                    dtype_hints.clone(),
8577                ))
8578            }
8579            SqlChunkIteratorState::Paged {
8580                conn,
8581                query,
8582                options,
8583                chunk_size,
8584                next_offset,
8585                finished,
8586                ..
8587            } => {
8588                if *finished {
8589                    return None;
8590                }
8591
8592                let page =
8593                    sql_query_to_columns_paged(*conn, query, options, *chunk_size, *next_offset);
8594                Some(match page {
8595                    Ok((headers, columns, dtype_hints)) => {
8596                        let row_count = columns.first().map_or(0, Vec::len);
8597                        if row_count == 0 {
8598                            *finished = true;
8599                            return None;
8600                        }
8601                        if row_count < *chunk_size {
8602                            *finished = true;
8603                        }
8604                        *next_offset = next_offset.saturating_add(row_count);
8605                        dataframe_from_sql_columns(headers, columns, dtype_hints)
8606                    }
8607                    Err(err) => {
8608                        *finished = true;
8609                        Err(err)
8610                    }
8611                })
8612            }
8613        }
8614    }
8615}
8616
8617/// Iterator over SQL DataFrame chunks with optional per-chunk index promotion.
8618pub struct SqlIndexedChunkIterator<'conn> {
8619    inner: SqlChunkIterator<'conn>,
8620    index_col: Option<String>,
8621}
8622
8623impl std::fmt::Debug for SqlIndexedChunkIterator<'_> {
8624    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
8625        f.debug_struct("SqlIndexedChunkIterator")
8626            .field("inner", &self.inner)
8627            .field("index_col", &self.index_col)
8628            .finish()
8629    }
8630}
8631
8632impl Iterator for SqlIndexedChunkIterator<'_> {
8633    type Item = Result<DataFrame, IoError>;
8634
8635    fn next(&mut self) -> Option<Self::Item> {
8636        let chunk = self.inner.next()?;
8637        Some(match (chunk, self.index_col.as_deref()) {
8638            (Ok(frame), Some(index_col)) => apply_sql_index_col(frame, Some(index_col)),
8639            (Ok(frame), None) => Ok(frame),
8640            (Err(err), _) => Err(err),
8641        })
8642    }
8643}
8644
8645fn sql_indexed_chunks<'conn>(
8646    inner: SqlChunkIterator<'conn>,
8647    index_col: Option<&str>,
8648) -> Result<SqlIndexedChunkIterator<'conn>, IoError> {
8649    if let Some(col_name) = index_col {
8650        if col_name.is_empty() {
8651            return Err(IoError::Sql(
8652                "index_col: empty string is not a valid column name".to_owned(),
8653            ));
8654        }
8655        if !inner.headers().iter().any(|header| header == col_name) {
8656            return Err(IoError::Sql(format!(
8657                "index_col {col_name:?} not present in result columns"
8658            )));
8659        }
8660    }
8661    Ok(SqlIndexedChunkIterator {
8662        inner,
8663        index_col: index_col.map(str::to_owned),
8664    })
8665}
8666
8667/// Minimal SQL connection surface needed by FrankenPandas SQL IO.
8668pub trait SqlConnection {
8669    fn query(&self, query: &str, params: &[Scalar]) -> Result<SqlQueryResult, IoError>;
8670
8671    /// Return optional dtype hints for each result column in `query`.
8672    ///
8673    /// Backends that expose declared result-column types should override this
8674    /// so empty/all-null SQL results keep their table schema instead of
8675    /// falling back to `DType::Null`.
8676    fn query_column_dtypes(
8677        &self,
8678        _query: &str,
8679        _params: &[Scalar],
8680    ) -> Result<Vec<Option<DType>>, IoError> {
8681        Ok(Vec::new())
8682    }
8683
8684    /// Whether `read_sql_chunks*` may page this backend with a bounded
8685    /// `LIMIT`/`OFFSET` wrapper instead of materializing the whole result
8686    /// before the first chunk. Defaults to `false` so lightweight test
8687    /// doubles and custom backends keep the legacy behavior until they opt in.
8688    fn supports_paged_sql_chunks(&self) -> bool {
8689        false
8690    }
8691
8692    fn execute_batch(&self, sql: &str) -> Result<(), IoError>;
8693
8694    fn table_exists(&self, table_name: &str) -> Result<bool, IoError>;
8695
8696    fn insert_rows(&self, insert_sql: &str, rows: &[Vec<Scalar>]) -> Result<(), IoError>;
8697
8698    fn dtype_sql(&self, dtype: DType) -> &'static str;
8699
8700    fn index_dtype_sql(&self, index: &Index) -> &'static str;
8701
8702    /// Return the bind marker for the one-based parameter ordinal.
8703    ///
8704    /// SQLite and MySQL accept `?`; PostgreSQL-style backends use `$1`,
8705    /// `$2`, ... . Keeping marker generation on the backend trait lets
8706    /// write_sql stay generic without leaking backend dialect branches.
8707    fn parameter_marker(&self, _ordinal: usize) -> String {
8708        "?".to_owned()
8709    }
8710
8711    // ── Backend-capability + dialect probes (br-frankenpandas-6dtf) ─────
8712    //
8713    // Default impls return conservative values so existing implementations
8714    // stay backwards-compatible; concrete backends override per their
8715    // engine. Phase 2 wires these probes into the read_sql / read_sql_table
8716    // dispatch path so per-backend SQL quirks (RETURNING, max param count,
8717    // transaction semantics) can fan out without leaking concrete types.
8718
8719    /// Short identifier for this backend's SQL dialect.
8720    ///
8721    /// Used by diagnostics + DISCREPANCIES.md routing. Backends should
8722    /// override with the canonical pandas/SQLAlchemy dialect name:
8723    /// `"sqlite"`, `"postgresql"`, `"mysql"`, `"mariadb"`, `"oracle"`, etc.
8724    /// Default `"unknown"` flags un-customized impls during reviews.
8725    fn dialect_name(&self) -> &'static str {
8726        "unknown"
8727    }
8728
8729    /// Whether this backend honors `INSERT ... RETURNING ...` natively.
8730    ///
8731    /// Drives the write_sql path's choice between RETURNING-based row
8732    /// retrieval and a follow-up SELECT. Default `false` is the
8733    /// conservative choice (forces follow-up SELECT path) until each
8734    /// backend opts in.
8735    fn supports_returning(&self) -> bool {
8736        false
8737    }
8738
8739    /// Hard upper bound on bound-parameter count per statement, if known.
8740    ///
8741    /// SQLite (3.32+): 32766. PostgreSQL: 65535. MySQL: 65535. Backends
8742    /// that don't surface a meaningful cap return `None`. The bulk-insert
8743    /// path uses this to chunk multi-row INSERTs so a single executemany
8744    /// stays under the backend's parameter ceiling.
8745    fn max_param_count(&self) -> Option<usize> {
8746        None
8747    }
8748
8749    /// Maximum identifier length supported by the backend, or `None`
8750    /// when no documented limit exists (or the limit is irrelevant for
8751    /// the deployment).
8752    ///
8753    /// Per br-frankenpandas-cs81 (fd90.26). Defaults to `None`. Known
8754    /// caps: PostgreSQL = 63, MySQL = 64, MSSQL = 128, Oracle = 30
8755    /// (pre-12.2) or 128 (12.2+), SQLite = no documented limit.
8756    /// Useful for to_sql validation when emitting auto-generated
8757    /// index/constraint/column names that could otherwise exceed
8758    /// backend limits and produce truncated or rejected DDL.
8759    fn max_identifier_length(&self) -> Option<usize> {
8760        None
8761    }
8762
8763    /// Run `f` inside a transaction. The default impl runs `f` without
8764    /// BEGIN/COMMIT — backends that support transactions should override
8765    /// to wrap in their native transaction primitive (rusqlite `BEGIN`,
8766    /// PostgreSQL `BEGIN`, MySQL `START TRANSACTION`, ...). On `Err`
8767    /// from `f`, transactional backends roll back; on `Ok` they commit.
8768    ///
8769    /// The default impl is intentionally a no-op so non-transactional
8770    /// connection wrappers (e.g. test doubles) compile without
8771    /// implementation effort. Production backends MUST override.
8772    fn with_transaction<T, F>(&self, f: F) -> Result<T, IoError>
8773    where
8774        F: FnOnce(&Self) -> Result<T, IoError>,
8775        Self: Sized,
8776    {
8777        f(self)
8778    }
8779
8780    /// Quote a SQL identifier (table name, column name, schema name) for
8781    /// safe inclusion in a generated statement.
8782    ///
8783    /// Default impl: ANSI `"..."` form with embedded `"` doubled (matches
8784    /// SQLite + PostgreSQL). MySQL/MariaDB backends must override to
8785    /// produce `\`...\`` (backtick). MSSQL backends use `[...]`. Per
8786    /// br-frankenpandas-2y7w (fd90.10).
8787    ///
8788    /// NUL bytes in the identifier are rejected (security: prevents
8789    /// statement-injection via embedded null terminators in C-string
8790    /// driver layers).
8791    fn quote_identifier(&self, ident: &str) -> Result<String, IoError> {
8792        if ident.contains('\0') {
8793            return Err(IoError::Sql("invalid SQL identifier: NUL byte".to_owned()));
8794        }
8795        Ok(format!("\"{}\"", ident.replace('"', "\"\"")))
8796    }
8797
8798    /// Whether this backend exposes multi-schema namespacing.
8799    ///
8800    /// PostgreSQL / MySQL / MariaDB / MSSQL / Oracle: true. SQLite (one
8801    /// schema per file connection — though ATTACH adds named schemas as
8802    /// a special case): false. Drives the `pd.read_sql_table(.., schema=X)`
8803    /// path's choice between qualifying the table reference (`schema.table`)
8804    /// and a connection-level pre-SET. Per br-frankenpandas-6dk9 (fd90.13).
8805    fn supports_schemas(&self) -> bool {
8806        false
8807    }
8808
8809    /// Default schema for unqualified table references, if the backend
8810    /// has one.
8811    ///
8812    /// PostgreSQL: `'public'` (or whatever the connection's `search_path`
8813    /// resolves to first). MySQL: the database name passed to the
8814    /// connection URL. SQLite: `None` (single namespace). The `read_sql_table`
8815    /// dispatch uses this when the user passes `schema=None` to choose
8816    /// between a bare `SELECT * FROM \"table\"` and a schema-qualified form.
8817    /// Default `None` keeps behavior identical to today's SQLite-only path.
8818    fn default_schema(&self) -> Option<String> {
8819        None
8820    }
8821
8822    /// Schema-aware table-existence check.
8823    ///
8824    /// Per br-frankenpandas-70d1 (fd90.17). Default impl delegates to
8825    /// `table_exists(table)` and ignores the schema argument — matches
8826    /// single-namespace embedded backends like SQLite. Multi-schema
8827    /// backends (PostgreSQL, MySQL, MSSQL) override to scope the check
8828    /// to the requested schema, so write_sql's `Fail` branch correctly
8829    /// distinguishes `analytics.users` from `audit.users`. The schema
8830    /// arg passes through unchanged — backends MAY consult
8831    /// `default_schema()` for their own fallback logic when `schema`
8832    /// is `None` (per fd90.57: this fallback is NOT applied by the
8833    /// default impl or the SQLite override).
8834    fn table_exists_in_schema(
8835        &self,
8836        table_name: &str,
8837        _schema: Option<&str>,
8838    ) -> Result<bool, IoError> {
8839        self.table_exists(table_name)
8840    }
8841
8842    /// List user-visible table names, optionally scoped to `schema`.
8843    ///
8844    /// Per br-frankenpandas-vhq2 (fd90.20). Default impl returns an empty
8845    /// vector — backends that cannot introspect (or that haven't yet
8846    /// implemented this method) report "no tables visible" rather than
8847    /// raising. Multi-schema backends (PostgreSQL, MySQL, MSSQL) override
8848    /// to query their information_schema; embedded backends (SQLite)
8849    /// override to query their internal catalog and ignore `schema`.
8850    fn list_tables(&self, _schema: Option<&str>) -> Result<Vec<String>, IoError> {
8851        Ok(Vec::new())
8852    }
8853
8854    /// Introspect a table's column metadata, optionally schema-scoped.
8855    ///
8856    /// Per br-frankenpandas-w43q (fd90.21). Returns `Ok(None)` if the
8857    /// table does not exist. Default impl returns `Ok(None)` for
8858    /// backends that cannot introspect; rusqlite overrides to use
8859    /// `PRAGMA table_info`. Multi-schema backends override to query
8860    /// `information_schema.columns` filtered by `schema`. Schema arg is
8861    /// silently ignored when `supports_schemas() == false`.
8862    fn table_schema(
8863        &self,
8864        _table_name: &str,
8865        _schema: Option<&str>,
8866    ) -> Result<Option<SqlTableSchema>, IoError> {
8867        Ok(None)
8868    }
8869
8870    /// List user-visible schemas (PostgreSQL "schemas", MySQL "databases").
8871    ///
8872    /// Per br-frankenpandas-lxhi (fd90.22). Default impl returns an empty
8873    /// vector. Single-namespace backends (SQLite) return empty as well —
8874    /// they have no meaningful schema concept. Multi-schema backends
8875    /// (PostgreSQL, MySQL, MSSQL) override to query their catalog and
8876    /// filter out internal/system schemas (`pg_*`, `information_schema`,
8877    /// `mysql`, `performance_schema`, etc.) so user-visible schemas
8878    /// surface cleanly.
8879    fn list_schemas(&self) -> Result<Vec<String>, IoError> {
8880        Ok(Vec::new())
8881    }
8882
8883    /// Probe the backend server's version string.
8884    ///
8885    /// Per br-frankenpandas-e23k (fd90.24). Useful for dialect-version
8886    /// gating (INSERT ... RETURNING needs PG 8.2+ / SQLite 3.35.0+,
8887    /// JSON operators need MySQL 5.7.8+, etc.) and for diagnostics.
8888    /// Default impl returns `Ok(None)` so backends that can't probe
8889    /// (or that haven't yet implemented this) report "unknown" rather
8890    /// than raising. rusqlite override returns the SQLite library
8891    /// version. PostgreSQL/MySQL impls should override with
8892    /// `SHOW server_version` / `SELECT VERSION()`.
8893    fn server_version(&self) -> Result<Option<String>, IoError> {
8894        Ok(None)
8895    }
8896
8897    /// List user-visible view names, optionally scoped to `schema`.
8898    ///
8899    /// Per br-frankenpandas-gm3r (fd90.30). Default impl returns an
8900    /// empty vector. rusqlite override queries `sqlite_master WHERE
8901    /// type='view'`, excluding internal `sqlite_*` views. Multi-schema
8902    /// backends override with `information_schema.views` filtered by
8903    /// the schema arg. Schema is silently ignored when
8904    /// `supports_schemas() == false`. Companion to `list_tables` —
8905    /// pandas/SQLAlchemy keep tables and views in distinct buckets so
8906    /// `pd.read_sql_table` can distinguish them.
8907    fn list_views(&self, _schema: Option<&str>) -> Result<Vec<String>, IoError> {
8908        Ok(Vec::new())
8909    }
8910
8911    /// List indexes defined on a table, optionally schema-scoped.
8912    ///
8913    /// Per br-frankenpandas-bgv9 (fd90.28). Default impl returns
8914    /// `Ok(Vec::new())` for backends that can't introspect. rusqlite
8915    /// override uses `PRAGMA index_list(table)` + `PRAGMA index_info`
8916    /// per index, surfacing only user-created indexes (the auto-created
8917    /// indexes for PRIMARY KEY constraints are filtered out to match
8918    /// SQLAlchemy.Inspector.get_indexes() semantics). Multi-schema
8919    /// backends override with information_schema queries.
8920    fn list_indexes(
8921        &self,
8922        _table_name: &str,
8923        _schema: Option<&str>,
8924    ) -> Result<Vec<SqlIndexSchema>, IoError> {
8925        Ok(Vec::new())
8926    }
8927
8928    /// List UNIQUE constraints declared on a table (inline or table-level),
8929    /// excluding `CREATE UNIQUE INDEX` indexes (those land in `list_indexes`).
8930    ///
8931    /// Per br-frankenpandas-sh4v (fd90.31). Default impl returns
8932    /// `Ok(Vec::new())`. rusqlite override uses
8933    /// `PRAGMA index_list(table)` filtered by `origin == 'u'` (the
8934    /// auto-created indexes that back declared UNIQUE constraints)
8935    /// then `PRAGMA index_info` per match. Multi-schema backends
8936    /// override with information_schema queries.
8937    fn list_unique_constraints(
8938        &self,
8939        _table_name: &str,
8940        _schema: Option<&str>,
8941    ) -> Result<Vec<SqlUniqueConstraintSchema>, IoError> {
8942        Ok(Vec::new())
8943    }
8944
8945    /// Probe the table-level comment, optionally schema-scoped.
8946    ///
8947    /// Per br-frankenpandas-yu3w (fd90.32). Default impl returns
8948    /// `Ok(None)` — SQLite has no native table-comment storage so it
8949    /// inherits the default. PostgreSQL impls should override using
8950    /// `pg_catalog.obj_description(...)` or
8951    /// `pg_catalog.pg_class.relkind` joined to `pg_description`;
8952    /// MySQL uses `information_schema.tables.table_comment`; MSSQL
8953    /// reads from `sys.extended_properties`. Aligns with
8954    /// `SQLAlchemy.Inspector.get_table_comment()` shape (returns
8955    /// `{'text': comment_or_none}`).
8956    fn table_comment(
8957        &self,
8958        _table_name: &str,
8959        _schema: Option<&str>,
8960    ) -> Result<Option<String>, IoError> {
8961        Ok(None)
8962    }
8963
8964    /// List foreign-key constraints declared on a table, optionally
8965    /// schema-scoped.
8966    ///
8967    /// Per br-frankenpandas-uht8 (fd90.29). Default impl returns
8968    /// `Ok(Vec::new())`. rusqlite override uses
8969    /// `PRAGMA foreign_key_list(table)`, grouping rows by their `id`
8970    /// column (each id is a single FK constraint that may span multiple
8971    /// columns) and ordering paired columns by `seq`. Multi-schema
8972    /// backends override with `information_schema.referential_constraints`
8973    /// + `key_column_usage` joined queries.
8974    fn list_foreign_keys(
8975        &self,
8976        _table_name: &str,
8977        _schema: Option<&str>,
8978    ) -> Result<Vec<SqlForeignKeySchema>, IoError> {
8979        Ok(Vec::new())
8980    }
8981
8982    /// Return the primary-key column names for a table, ordered by
8983    /// the `primary_key_ordinal` reported by `table_schema`.
8984    ///
8985    /// Per br-frankenpandas-uw3y (fd90.25). Default impl delegates to
8986    /// `table_schema(table, schema)` and pulls out columns whose
8987    /// `primary_key_ordinal` is `Some(_)`, sorted ascending. Returns
8988    /// an empty vector when:
8989    /// - the table doesn't exist (`table_schema` returns `Ok(None)`),
8990    /// - the table has no primary key,
8991    /// - the backend can't introspect (default `table_schema`).
8992    ///
8993    /// Useful for upsert conflict-target generation, `index_label`
8994    /// defaulting, and schema validation. Backends can override to
8995    /// query their catalog directly when `table_schema` is too heavy.
8996    fn primary_key_columns(
8997        &self,
8998        table_name: &str,
8999        schema: Option<&str>,
9000    ) -> Result<Vec<String>, IoError> {
9001        // Per fd90.47: defer to the shared primary_keys_from_schema
9002        // helper so the filter+sort logic lives in exactly one place
9003        // (the helper is also used by SqlInspector::reflect_table).
9004        let Some(meta) = self.table_schema(table_name, schema)? else {
9005            return Ok(Vec::new());
9006        };
9007        Ok(primary_keys_from_schema(&meta))
9008    }
9009
9010    /// Reset a table to empty without dropping its definition.
9011    ///
9012    /// Per br-frankenpandas-phum (fd90.23). Default impl emits
9013    /// `DELETE FROM <table>` — universal SQL that every backend
9014    /// supports, but slower than TRUNCATE on large tables because the
9015    /// row deletes are logged in the transaction journal. PostgreSQL
9016    /// and MySQL backends should override with `TRUNCATE TABLE`,
9017    /// which is dramatically faster (DDL-style fast-path) and resets
9018    /// auto-increment sequences. The schema arg routes through
9019    /// `quote_identifier` and is silently ignored when
9020    /// `supports_schemas() == false`.
9021    fn truncate_table(&self, table_name: &str, schema: Option<&str>) -> Result<(), IoError> {
9022        validate_sql_table_name(table_name)?;
9023        validate_sql_table_ref_identifier_lengths(self, table_name, schema)?;
9024        let qualified = match schema {
9025            Some(s) if self.supports_schemas() => {
9026                validate_sql_schema_name(s)?;
9027                format!(
9028                    "{}.{}",
9029                    self.quote_identifier(s)?,
9030                    self.quote_identifier(table_name)?
9031                )
9032            }
9033            _ => self.quote_identifier(table_name)?,
9034        };
9035        self.execute_batch(&format!("DELETE FROM {qualified}"))
9036    }
9037}
9038
9039/// Map an fp-types DType to an SQLite column type declaration.
9040#[cfg(feature = "sql-sqlite")]
9041fn dtype_to_sql(dtype: DType) -> &'static str {
9042    match dtype {
9043        DType::Int64 | DType::Int64Nullable => "INTEGER",
9044        DType::Float64 => "REAL",
9045        DType::Utf8 => "TEXT",
9046        DType::Categorical => "TEXT",
9047        DType::Bool | DType::BoolNullable => "INTEGER",
9048        DType::Null => "TEXT",
9049        DType::Timedelta64 => "INTEGER", // store as nanoseconds
9050        DType::Datetime64 => "INTEGER",  // store as nanoseconds
9051        DType::Period => "INTEGER",      // store as ordinal
9052        DType::Interval => "TEXT",       // store as string
9053        DType::Sparse => "TEXT",
9054    }
9055}
9056
9057#[cfg(feature = "sql-sqlite")]
9058fn sqlite_decl_type_to_dtype(decl_type: &str) -> Option<DType> {
9059    let upper = decl_type.trim().to_ascii_uppercase();
9060    if upper.contains("INT") {
9061        Some(DType::Int64)
9062    } else if upper.contains("REAL") || upper.contains("FLOA") || upper.contains("DOUB") {
9063        Some(DType::Float64)
9064    } else if upper.contains("CHAR") || upper.contains("CLOB") || upper.contains("TEXT") {
9065        Some(DType::Utf8)
9066    } else {
9067        None
9068    }
9069}
9070
9071/// Convert an SQLite column value to a Scalar.
9072#[cfg(feature = "sql-sqlite")]
9073fn sql_value_to_scalar(value: &rusqlite::types::Value) -> Scalar {
9074    match value {
9075        rusqlite::types::Value::Null => Scalar::Null(NullKind::Null),
9076        rusqlite::types::Value::Integer(v) => Scalar::Int64(*v),
9077        rusqlite::types::Value::Real(v) => Scalar::Float64(*v),
9078        rusqlite::types::Value::Text(s) => Scalar::Utf8(s.clone()),
9079        rusqlite::types::Value::Blob(b) => Scalar::Utf8(format!("<blob:{} bytes>", b.len())),
9080    }
9081}
9082
9083#[cfg(feature = "sql-sqlite")]
9084fn sql_value_from_scalar(scalar: &Scalar) -> rusqlite::types::Value {
9085    match scalar {
9086        Scalar::Int64(v) => rusqlite::types::Value::Integer(*v),
9087        Scalar::Float64(v) => {
9088            if v.is_nan() {
9089                rusqlite::types::Value::Null
9090            } else {
9091                rusqlite::types::Value::Real(*v)
9092            }
9093        }
9094        Scalar::Bool(b) => rusqlite::types::Value::Integer(if *b { 1 } else { 0 }),
9095        Scalar::Utf8(s) => rusqlite::types::Value::Text(s.clone()),
9096        Scalar::Null(_) => rusqlite::types::Value::Null,
9097        Scalar::Timedelta64(v) => {
9098            if *v == Timedelta::NAT {
9099                rusqlite::types::Value::Null
9100            } else {
9101                rusqlite::types::Value::Integer(*v)
9102            }
9103        }
9104        Scalar::Datetime64(v) => {
9105            if *v == Timestamp::NAT {
9106                rusqlite::types::Value::Null
9107            } else {
9108                rusqlite::types::Value::Integer(*v)
9109            }
9110        }
9111        Scalar::Period(p) => {
9112            if p.ordinal == i64::MIN {
9113                rusqlite::types::Value::Null
9114            } else {
9115                rusqlite::types::Value::Integer(p.ordinal)
9116            }
9117        }
9118        Scalar::Interval(iv) => rusqlite::types::Value::Text(format!("{iv}")),
9119    }
9120}
9121
9122fn scalar_from_index_label(label: &IndexLabel) -> Scalar {
9123    match label {
9124        IndexLabel::Int64(v) => Scalar::Int64(*v),
9125        IndexLabel::Float64(v) => Scalar::Float64(v.0),
9126        IndexLabel::Bool(b) => Scalar::Bool(*b),
9127        IndexLabel::Utf8(s) => Scalar::Utf8(s.clone()),
9128        // Typed-null label round-trips to the same-kind missing scalar.
9129        IndexLabel::Null(kind) => Scalar::Null(*kind),
9130        IndexLabel::Timedelta64(v) => {
9131            if *v == Timedelta::NAT {
9132                Scalar::Null(NullKind::Null)
9133            } else {
9134                Scalar::Timedelta64(*v)
9135            }
9136        }
9137        IndexLabel::Datetime64(v) => {
9138            if *v == i64::MIN {
9139                Scalar::Null(NullKind::Null)
9140            } else {
9141                Scalar::Utf8(format_datetime_ns(*v))
9142            }
9143        }
9144    }
9145}
9146
9147#[cfg(feature = "sql-sqlite")]
9148impl SqlConnection for rusqlite::Connection {
9149    fn query(&self, query: &str, params: &[Scalar]) -> Result<SqlQueryResult, IoError> {
9150        let mut stmt = self
9151            .prepare(query)
9152            .map_err(|e| IoError::Sql(format!("prepare failed: {e}")))?;
9153
9154        let col_count = stmt.column_count();
9155        let columns: Vec<String> = (0..col_count)
9156            .map(|i| stmt.column_name(i).unwrap_or("?").to_owned())
9157            .collect();
9158
9159        let sql_params = params.iter().map(sql_value_from_scalar).collect::<Vec<_>>();
9160        let mut rows = stmt
9161            .query(rusqlite::params_from_iter(sql_params.iter()))
9162            .map_err(|e| IoError::Sql(format!("query failed: {e}")))?;
9163
9164        let mut out_rows = Vec::new();
9165        while let Some(row) = rows
9166            .next()
9167            .map_err(|e| IoError::Sql(format!("row fetch failed: {e}")))?
9168        {
9169            let mut values = Vec::with_capacity(col_count);
9170            for col_idx in 0..col_count {
9171                let value: rusqlite::types::Value = row
9172                    .get(col_idx)
9173                    .map_err(|e| IoError::Sql(format!("cell read failed: {e}")))?;
9174                values.push(sql_value_to_scalar(&value));
9175            }
9176            out_rows.push(values);
9177        }
9178
9179        Ok(SqlQueryResult {
9180            columns,
9181            rows: out_rows,
9182        })
9183    }
9184
9185    fn query_column_dtypes(
9186        &self,
9187        query: &str,
9188        _params: &[Scalar],
9189    ) -> Result<Vec<Option<DType>>, IoError> {
9190        let stmt = self
9191            .prepare(query)
9192            .map_err(|e| IoError::Sql(format!("prepare failed: {e}")))?;
9193        Ok(stmt
9194            .columns()
9195            .into_iter()
9196            .map(|column| column.decl_type().and_then(sqlite_decl_type_to_dtype))
9197            .collect())
9198    }
9199
9200    fn supports_paged_sql_chunks(&self) -> bool {
9201        true
9202    }
9203
9204    fn execute_batch(&self, sql: &str) -> Result<(), IoError> {
9205        rusqlite::Connection::execute_batch(self, sql)
9206            .map_err(|e| IoError::Sql(format!("execute_batch failed: {e}")))
9207    }
9208
9209    fn table_exists(&self, table_name: &str) -> Result<bool, IoError> {
9210        self.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name=?1")
9211            .and_then(|mut stmt| stmt.exists(rusqlite::params![table_name]))
9212            .map_err(|e| IoError::Sql(format!("existence check failed: {e}")))
9213    }
9214
9215    fn insert_rows(&self, insert_sql: &str, rows: &[Vec<Scalar>]) -> Result<(), IoError> {
9216        let tx = self
9217            .unchecked_transaction()
9218            .map_err(|e| IoError::Sql(format!("begin transaction failed: {e}")))?;
9219
9220        {
9221            let mut stmt = tx
9222                .prepare_cached(insert_sql)
9223                .map_err(|e| IoError::Sql(format!("prepare insert failed: {e}")))?;
9224
9225            for (row_idx, row_values) in rows.iter().enumerate() {
9226                let params = row_values
9227                    .iter()
9228                    .map(sql_value_from_scalar)
9229                    .collect::<Vec<_>>();
9230                stmt.execute(rusqlite::params_from_iter(params.iter()))
9231                    .map_err(|e| IoError::Sql(format!("insert row {row_idx} failed: {e}")))?;
9232            }
9233        }
9234
9235        tx.commit()
9236            .map_err(|e| IoError::Sql(format!("commit failed: {e}")))?;
9237        Ok(())
9238    }
9239
9240    fn dtype_sql(&self, dtype: DType) -> &'static str {
9241        dtype_to_sql(dtype)
9242    }
9243
9244    fn index_dtype_sql(&self, index: &Index) -> &'static str {
9245        sql_dtype_from_index(index)
9246    }
9247
9248    // br-frankenpandas-6dtf: backend-capability + dialect probes.
9249    fn dialect_name(&self) -> &'static str {
9250        "sqlite"
9251    }
9252
9253    fn supports_returning(&self) -> bool {
9254        // SQLite 3.35.0+ (released March 2021) supports INSERT ... RETURNING.
9255        // rusqlite ships with bundled SQLite >= 3.45 by default, so we can
9256        // unconditionally claim support here.
9257        true
9258    }
9259
9260    fn max_param_count(&self) -> Option<usize> {
9261        // SQLite default SQLITE_MAX_VARIABLE_NUMBER is 32766 since 3.32.0.
9262        // (Older builds capped at 999.) rusqlite bundled SQLite is current,
9263        // so this matches.
9264        Some(32766)
9265    }
9266
9267    fn with_transaction<T, F>(&self, f: F) -> Result<T, IoError>
9268    where
9269        F: FnOnce(&Self) -> Result<T, IoError>,
9270        Self: Sized,
9271    {
9272        struct RollbackOnDrop<'conn> {
9273            conn: &'conn rusqlite::Connection,
9274            active: bool,
9275        }
9276
9277        impl Drop for RollbackOnDrop<'_> {
9278            fn drop(&mut self) {
9279                if self.active {
9280                    let _ = rusqlite::Connection::execute_batch(self.conn, "ROLLBACK");
9281                }
9282            }
9283        }
9284
9285        // rusqlite's pure-trait `Self: Sized` constraint means we operate on
9286        // `&rusqlite::Connection` directly without taking the `&mut` that
9287        // `Connection::transaction()` requires. We emulate the same
9288        // BEGIN/COMMIT semantics with explicit pragmas. The guard keeps the
9289        // connection from retaining a write transaction if the callback
9290        // panics before we reach the explicit rollback/commit paths.
9291        self.execute_batch("BEGIN")
9292            .map_err(|e| IoError::Sql(format!("begin transaction failed: {e}")))?;
9293        let mut rollback = RollbackOnDrop {
9294            conn: self,
9295            active: true,
9296        };
9297        match f(self) {
9298            Ok(result) => {
9299                self.execute_batch("COMMIT")
9300                    .map_err(|e| IoError::Sql(format!("commit transaction failed: {e}")))?;
9301                rollback.active = false;
9302                Ok(result)
9303            }
9304            Err(err) => {
9305                // Best-effort rollback; surface the original error if rollback
9306                // also fails (rollback failure is logged via the Sql error
9307                // variant for diagnostics but the user wants the closure
9308                // error preserved as the primary signal).
9309                if self.execute_batch("ROLLBACK").is_ok() {
9310                    rollback.active = false;
9311                }
9312                Err(err)
9313            }
9314        }
9315    }
9316
9317    fn quote_identifier(&self, ident: &str) -> Result<String, IoError> {
9318        // SQLite accepts ANSI double-quotes for identifiers (it ALSO accepts
9319        // backticks for MySQL compat, but ANSI is the recommended form per
9320        // SQLite docs). Delegate to the existing free-fn helper to keep the
9321        // exact escaping policy in one place.
9322        quote_sql_ident(ident)
9323    }
9324
9325    fn list_tables(&self, _schema: Option<&str>) -> Result<Vec<String>, IoError> {
9326        // SQLite has a single namespace; the schema arg is silently
9327        // ignored to match `supports_schemas() == false`. We exclude
9328        // SQLite's internal `sqlite_*` book-keeping tables to match
9329        // pandas' SQLAlchemy dialect, which never surfaces them as
9330        // user tables.
9331        // Per fd90.50: ESCAPE '\' makes the `_` in 'sqlite\_%' a literal
9332        // underscore instead of a SQL LIKE single-char wildcard. Without
9333        // the escape, a user table named e.g. `sqliteX` would be
9334        // incorrectly excluded because the `_` matches any single char.
9335        let mut stmt = self
9336            .prepare(
9337                r"SELECT name FROM sqlite_master
9338                 WHERE type='table' AND name NOT LIKE 'sqlite\_%' ESCAPE '\'
9339                 ORDER BY name",
9340            )
9341            .map_err(|e| IoError::Sql(format!("list_tables prepare failed: {e}")))?;
9342        let names = stmt
9343            .query_map([], |row| row.get::<_, String>(0))
9344            .map_err(|e| IoError::Sql(format!("list_tables query failed: {e}")))?
9345            .collect::<Result<Vec<_>, _>>()
9346            .map_err(|e| IoError::Sql(format!("list_tables row read failed: {e}")))?;
9347        Ok(names)
9348    }
9349
9350    fn list_views(&self, _schema: Option<&str>) -> Result<Vec<String>, IoError> {
9351        // Same single-namespace policy as list_tables; type='view'
9352        // distinguishes the two buckets in sqlite_master.
9353        // Per fd90.50: same ESCAPE '\' fix as list_tables to treat
9354        // the underscore in 'sqlite_' as a literal.
9355        let mut stmt = self
9356            .prepare(
9357                r"SELECT name FROM sqlite_master
9358                 WHERE type='view' AND name NOT LIKE 'sqlite\_%' ESCAPE '\'
9359                 ORDER BY name",
9360            )
9361            .map_err(|e| IoError::Sql(format!("list_views prepare failed: {e}")))?;
9362        let names = stmt
9363            .query_map([], |row| row.get::<_, String>(0))
9364            .map_err(|e| IoError::Sql(format!("list_views query failed: {e}")))?
9365            .collect::<Result<Vec<_>, _>>()
9366            .map_err(|e| IoError::Sql(format!("list_views row read failed: {e}")))?;
9367        Ok(names)
9368    }
9369
9370    fn table_schema(
9371        &self,
9372        table_name: &str,
9373        _schema: Option<&str>,
9374    ) -> Result<Option<SqlTableSchema>, IoError> {
9375        // Validate the table name first — PRAGMA table_info doesn't
9376        // accept parameter binding, so we must reject anything that
9377        // could break out of the identifier slot.
9378        validate_sql_table_name(table_name)?;
9379        // PRAGMA table_info returns: cid, name, type, notnull, dflt_value, pk.
9380        let pragma = format!("PRAGMA table_info(\"{}\")", table_name.replace('"', "\"\""));
9381        let mut stmt = self
9382            .prepare(&pragma)
9383            .map_err(|e| IoError::Sql(format!("table_schema prepare failed: {e}")))?;
9384        // PRAGMA table_info row tuple: (name, type, notnull, dflt_value, pk).
9385        // Type alias keeps clippy::type_complexity happy on the
9386        // intermediate Vec used for the two-pass autoincrement detection.
9387        type ColumnInfoRow = (String, Option<String>, i64, Option<String>, i64);
9388        let raw_rows: Vec<ColumnInfoRow> = stmt
9389            .query_map([], |row| {
9390                Ok((
9391                    row.get::<_, String>(1)?,
9392                    row.get::<_, Option<String>>(2)?,
9393                    row.get::<_, i64>(3)?,
9394                    row.get::<_, Option<String>>(4)?,
9395                    row.get::<_, i64>(5)?,
9396                ))
9397            })
9398            .map_err(|e| IoError::Sql(format!("table_schema query failed: {e}")))?
9399            .collect::<Result<Vec<_>, _>>()
9400            .map_err(|e| IoError::Sql(format!("table_schema row read failed: {e}")))?;
9401
9402        // Per fd90.42 (refines fd90.37): SQLite's rowid-alias rule
9403        // requires the column to be the SOLE primary key — i.e. exactly
9404        // one row in PRAGMA table_info has pk > 0. Composite PKs (where
9405        // multiple columns have pk > 0) never qualify, even if the
9406        // first column is INTEGER. So we count single-PK status across
9407        // the table before deciding any column's autoincrement bit.
9408        let pk_count = raw_rows.iter().filter(|(_, _, _, _, pk)| *pk > 0).count();
9409        let single_pk = pk_count == 1;
9410
9411        let mut columns: Vec<SqlColumnSchema> = Vec::with_capacity(raw_rows.len());
9412        for (name, declared, notnull, dflt, pk) in raw_rows {
9413            let cleaned_type = declared.filter(|s| !s.is_empty());
9414            let autoincrement = single_pk
9415                && pk == 1
9416                && cleaned_type
9417                    .as_deref()
9418                    .map(|t| t.eq_ignore_ascii_case("INTEGER"))
9419                    .unwrap_or(false);
9420            columns.push(SqlColumnSchema {
9421                name,
9422                declared_type: cleaned_type,
9423                nullable: notnull == 0,
9424                default_value: dflt,
9425                primary_key_ordinal: if pk > 0 {
9426                    Some(usize::try_from(pk - 1).unwrap_or(0))
9427                } else {
9428                    None
9429                },
9430                comment: None,
9431                autoincrement,
9432            });
9433        }
9434        if columns.is_empty() {
9435            // PRAGMA table_info on a non-existent table returns 0 rows
9436            // without erroring; map that to None so callers can
9437            // distinguish missing tables from empty ones.
9438            Ok(None)
9439        } else {
9440            Ok(Some(SqlTableSchema {
9441                table_name: table_name.to_owned(),
9442                columns,
9443            }))
9444        }
9445    }
9446
9447    fn server_version(&self) -> Result<Option<String>, IoError> {
9448        // sqlite_version() is a built-in scalar that returns the
9449        // SQLite library version string (e.g. "3.45.1").
9450        let version: String = self
9451            .query_row("SELECT sqlite_version()", [], |row| row.get(0))
9452            .map_err(|e| IoError::Sql(format!("server_version query failed: {e}")))?;
9453        Ok(Some(version))
9454    }
9455
9456    fn list_indexes(
9457        &self,
9458        table_name: &str,
9459        _schema: Option<&str>,
9460    ) -> Result<Vec<SqlIndexSchema>, IoError> {
9461        validate_sql_table_name(table_name)?;
9462        // PRAGMA index_list(table) returns: seq, name, unique, origin, partial.
9463        // origin is 'c' for CREATE INDEX (user), 'pk' for PRIMARY KEY auto,
9464        // 'u' for UNIQUE constraint auto. SQLAlchemy.Inspector surfaces
9465        // only the user-created ones, so we filter out 'pk' to match.
9466        let pragma_list = format!("PRAGMA index_list(\"{}\")", table_name.replace('"', "\"\""));
9467        let mut list_stmt = self
9468            .prepare(&pragma_list)
9469            .map_err(|e| IoError::Sql(format!("list_indexes prepare failed: {e}")))?;
9470        let index_meta = list_stmt
9471            .query_map([], |row| {
9472                Ok((
9473                    row.get::<_, String>(1)?, // name
9474                    row.get::<_, i64>(2)?,    // unique flag
9475                    row.get::<_, String>(3)?, // origin
9476                ))
9477            })
9478            .map_err(|e| IoError::Sql(format!("list_indexes query failed: {e}")))?
9479            .collect::<Result<Vec<_>, _>>()
9480            .map_err(|e| IoError::Sql(format!("list_indexes row read failed: {e}")))?;
9481
9482        let mut indexes = Vec::new();
9483        for (name, uniq, origin) in index_meta {
9484            if origin == "pk" {
9485                // Auto-created PK index — pandas/SQLAlchemy hide it.
9486                continue;
9487            }
9488            if origin == "u" {
9489                // Auto-created index backing a declared UNIQUE
9490                // constraint — surfaced via list_unique_constraints
9491                // (fd90.31), not here, to match SQLAlchemy disjoint
9492                // bucketing between get_indexes and
9493                // get_unique_constraints.
9494                continue;
9495            }
9496            // PRAGMA index_info(idx) returns: seqno, cid, column_name (col2 may
9497            // be NULL for expression-based indexes — skip those rather than
9498            // surfacing partial column lists).
9499            let pragma_info = format!("PRAGMA index_info(\"{}\")", name.replace('"', "\"\""));
9500            let mut info_stmt = self
9501                .prepare(&pragma_info)
9502                .map_err(|e| IoError::Sql(format!("index_info prepare failed: {e}")))?;
9503            let cols = info_stmt
9504                .query_map([], |row| {
9505                    Ok((row.get::<_, i64>(0)?, row.get::<_, Option<String>>(2)?))
9506                })
9507                .map_err(|e| IoError::Sql(format!("index_info query failed: {e}")))?
9508                .collect::<Result<Vec<_>, _>>()
9509                .map_err(|e| IoError::Sql(format!("index_info row read failed: {e}")))?;
9510            // Skip expression-based indexes (any column_name is NULL).
9511            if cols.iter().any(|(_, c)| c.is_none()) {
9512                continue;
9513            }
9514            let mut sorted: Vec<(i64, String)> = cols
9515                .into_iter()
9516                .map(|(seq, c)| (seq, c.unwrap_or_default()))
9517                .collect();
9518            sorted.sort_by_key(|(seq, _)| *seq);
9519            indexes.push(SqlIndexSchema {
9520                name,
9521                columns: sorted.into_iter().map(|(_, c)| c).collect(),
9522                unique: uniq != 0,
9523            });
9524        }
9525        Ok(indexes)
9526    }
9527
9528    fn list_unique_constraints(
9529        &self,
9530        table_name: &str,
9531        _schema: Option<&str>,
9532    ) -> Result<Vec<SqlUniqueConstraintSchema>, IoError> {
9533        validate_sql_table_name(table_name)?;
9534        // PRAGMA index_list(table) origin column:
9535        //   'c' = CREATE INDEX (user) — surfaces via list_indexes
9536        //   'u' = UNIQUE constraint   — surfaces here
9537        //   'pk' = PRIMARY KEY auto   — surfaces via primary_key_columns
9538        let pragma_list = format!("PRAGMA index_list(\"{}\")", table_name.replace('"', "\"\""));
9539        let mut list_stmt = self
9540            .prepare(&pragma_list)
9541            .map_err(|e| IoError::Sql(format!("list_unique_constraints prepare failed: {e}")))?;
9542        let candidates = list_stmt
9543            .query_map([], |row| {
9544                Ok((
9545                    row.get::<_, String>(1)?, // index name
9546                    row.get::<_, String>(3)?, // origin
9547                ))
9548            })
9549            .map_err(|e| IoError::Sql(format!("list_unique_constraints query failed: {e}")))?
9550            .collect::<Result<Vec<_>, _>>()
9551            .map_err(|e| IoError::Sql(format!("list_unique_constraints row read failed: {e}")))?;
9552
9553        let mut constraints = Vec::new();
9554        for (name, origin) in candidates {
9555            if origin != "u" {
9556                continue;
9557            }
9558            let pragma_info = format!("PRAGMA index_info(\"{}\")", name.replace('"', "\"\""));
9559            let mut info_stmt = self
9560                .prepare(&pragma_info)
9561                .map_err(|e| IoError::Sql(format!("uq index_info prepare failed: {e}")))?;
9562            let cols = info_stmt
9563                .query_map([], |row| {
9564                    Ok((row.get::<_, i64>(0)?, row.get::<_, Option<String>>(2)?))
9565                })
9566                .map_err(|e| IoError::Sql(format!("uq index_info query failed: {e}")))?
9567                .collect::<Result<Vec<_>, _>>()
9568                .map_err(|e| IoError::Sql(format!("uq index_info row read failed: {e}")))?;
9569            // Skip expression-based unique constraints (column NULL).
9570            if cols.iter().any(|(_, c)| c.is_none()) {
9571                continue;
9572            }
9573            let mut sorted: Vec<(i64, String)> = cols
9574                .into_iter()
9575                .map(|(seq, c)| (seq, c.unwrap_or_default()))
9576                .collect();
9577            sorted.sort_by_key(|(seq, _)| *seq);
9578            constraints.push(SqlUniqueConstraintSchema {
9579                name,
9580                columns: sorted.into_iter().map(|(_, c)| c).collect(),
9581            });
9582        }
9583        Ok(constraints)
9584    }
9585
9586    fn list_foreign_keys(
9587        &self,
9588        table_name: &str,
9589        _schema: Option<&str>,
9590    ) -> Result<Vec<SqlForeignKeySchema>, IoError> {
9591        // PRAGMA foreign_key_list rows: (seq, referenced_table, from_col, to_col).
9592        // The constraint id is the BTreeMap key; we don't repeat it inside the
9593        // value tuple. Type alias keeps clippy::type_complexity happy and
9594        // the grouping logic readable.
9595        type FkRow = (i64, String, String, Option<String>);
9596
9597        validate_sql_table_name(table_name)?;
9598        // PRAGMA foreign_key_list(table) returns: id, seq, table, from, to,
9599        // on_update, on_delete, match. Each `id` is one FK constraint;
9600        // multiple rows with the same id describe a composite FK.
9601        let pragma = format!(
9602            "PRAGMA foreign_key_list(\"{}\")",
9603            table_name.replace('"', "\"\"")
9604        );
9605        let mut stmt = self
9606            .prepare(&pragma)
9607            .map_err(|e| IoError::Sql(format!("list_foreign_keys prepare failed: {e}")))?;
9608        let rows: Vec<(i64, FkRow)> = stmt
9609            .query_map([], |row| {
9610                Ok((
9611                    row.get::<_, i64>(0)?, // id
9612                    (
9613                        row.get::<_, i64>(1)?,            // seq
9614                        row.get::<_, String>(2)?,         // referenced table
9615                        row.get::<_, String>(3)?,         // from column
9616                        row.get::<_, Option<String>>(4)?, // to column (nullable)
9617                    ),
9618                ))
9619            })
9620            .map_err(|e| IoError::Sql(format!("list_foreign_keys query failed: {e}")))?
9621            .collect::<Result<Vec<_>, _>>()
9622            .map_err(|e| IoError::Sql(format!("list_foreign_keys row read failed: {e}")))?;
9623
9624        // Group by id; preserve discovery order across distinct ids.
9625        let mut order: Vec<i64> = Vec::new();
9626        let mut grouped: std::collections::BTreeMap<i64, Vec<FkRow>> =
9627            std::collections::BTreeMap::new();
9628        for (id, fk_row) in rows {
9629            let (seq, ref_table, from_col, to_col) = fk_row;
9630            if !grouped.contains_key(&id) {
9631                order.push(id);
9632            }
9633            grouped
9634                .entry(id)
9635                .or_default()
9636                .push((seq, ref_table, from_col, to_col));
9637        }
9638
9639        let mut fks = Vec::with_capacity(order.len());
9640        for id in order {
9641            let mut group = grouped.remove(&id).unwrap_or_default();
9642            group.sort_by_key(|(seq, _, _, _)| *seq);
9643            let ref_table = group
9644                .first()
9645                .map(|(_, t, _, _)| t.clone())
9646                .unwrap_or_default();
9647            let mut columns = Vec::with_capacity(group.len());
9648            let mut referenced_columns: Vec<Option<String>> = Vec::with_capacity(group.len());
9649            for (_, _, from_col, to_col) in group {
9650                columns.push(from_col);
9651                referenced_columns.push(to_col);
9652            }
9653            // Per fd90.44: when ALL `to` columns are NULL, the user
9654            // declared `FOREIGN KEY (cols) REFERENCES parent` (implicit
9655            // reference to parent's PK). Resolve by looking up the
9656            // parent's primary key columns. SQLAlchemy.Inspector
9657            // surfaces these as resolved-to-PK references; matching
9658            // that behavior keeps callers from missing real FKs.
9659            let resolved_columns: Vec<String> = if referenced_columns.iter().all(Option::is_none) {
9660                // Implicit-PK reference: look up parent's PK.
9661                let pk = self.primary_key_columns(&ref_table, None)?;
9662                if pk.len() == columns.len() {
9663                    pk
9664                } else {
9665                    // Parent PK shape doesn't match FK column count
9666                    // (parent has no PK, or composite mismatch). Skip
9667                    // — fabricating columns would mislead callers
9668                    // worse than hiding the FK.
9669                    continue;
9670                }
9671            } else if referenced_columns.iter().all(Option::is_some) {
9672                // Fully explicit: every column has a resolved 'to'.
9673                referenced_columns.into_iter().flatten().collect()
9674            } else {
9675                // Mixed Some/None: SQLite shouldn't produce this for
9676                // a single FK group, but if it ever does, skip rather
9677                // than mispair.
9678                continue;
9679            };
9680            fks.push(SqlForeignKeySchema {
9681                // SQLite PRAGMA foreign_key_list does not surface a
9682                // CONSTRAINT name; pandas/SQLAlchemy report None there too.
9683                constraint_name: None,
9684                columns,
9685                referenced_table: ref_table,
9686                referenced_columns: resolved_columns,
9687            });
9688        }
9689        Ok(fks)
9690    }
9691}
9692
9693#[cfg(feature = "sql-sqlite")]
9694fn sql_dtype_from_index(index: &Index) -> &'static str {
9695    for label in index.labels() {
9696        match label {
9697            IndexLabel::Int64(_) => return "INTEGER",
9698            IndexLabel::Utf8(_) => return "TEXT",
9699            IndexLabel::Timedelta64(v) if *v != Timedelta::NAT => return "INTEGER",
9700            IndexLabel::Datetime64(v) if *v != i64::MIN => return "TEXT",
9701            _ => {}
9702        }
9703    }
9704    "TEXT"
9705}
9706
9707fn resolve_sql_index_label(
9708    frame: &DataFrame,
9709    options: &SqlWriteOptions,
9710) -> Result<Option<String>, IoError> {
9711    if !options.index {
9712        return Ok(None);
9713    }
9714
9715    let label = options
9716        .index_label
9717        .clone()
9718        .or_else(|| frame.index().name().map(str::to_owned))
9719        .unwrap_or_else(|| "index".to_owned());
9720
9721    if frame.column(&label).is_some() {
9722        return Err(IoError::DuplicateColumnName(label));
9723    }
9724
9725    Ok(Some(label))
9726}
9727
9728// Per br-frankenpandas-ld8h (fd90.45): these helpers are only called
9729// from the rusqlite SqlConnection impl, which is gated behind
9730// `feature = "sql-sqlite"`. Mirroring the gate here keeps
9731// --no-default-features builds clean of dead-code warnings.
9732#[cfg(feature = "sql-sqlite")]
9733fn escape_sql_ident(name: &str) -> Result<String, IoError> {
9734    if name.contains('\0') {
9735        return Err(IoError::Sql("invalid SQL identifier: NUL byte".to_owned()));
9736    }
9737    Ok(name.replace('"', "\"\""))
9738}
9739
9740#[cfg(feature = "sql-sqlite")]
9741fn quote_sql_ident(name: &str) -> Result<String, IoError> {
9742    Ok(format!("\"{}\"", escape_sql_ident(name)?))
9743}
9744
9745/// Per br-frankenpandas-4l7a (fd90.55): shared identifier-shape
9746/// validator used by `validate_sql_table_name` and
9747/// `validate_sql_column_name`. `kind` is the user-facing label
9748/// inserted into the error message ("table", "column", ...). The
9749/// rule is the same for both: non-empty, ASCII-alphanumeric or
9750/// underscore only — defense in depth alongside `quote_identifier`
9751/// (which handles embedded quotes but doesn't reject other shapes).
9752fn validate_sql_ident(name: &str, kind: &str) -> Result<(), IoError> {
9753    if name.is_empty() || !name.chars().all(|c| c.is_alphanumeric() || c == '_') {
9754        return Err(IoError::Sql(format!(
9755            "invalid {kind} name: '{name}' (must be non-empty, only alphanumeric and underscore allowed)"
9756        )));
9757    }
9758    Ok(())
9759}
9760
9761fn validate_sql_table_name(table_name: &str) -> Result<(), IoError> {
9762    validate_sql_ident(table_name, "table")
9763}
9764
9765/// Per br-frankenpandas-597l (fd90.56): dedicated schema-name
9766/// validator so error messages correctly identify the invalid
9767/// identifier as a schema rather than a table. Same alphanumeric+
9768/// underscore rule as table/column names.
9769fn validate_sql_schema_name(schema: &str) -> Result<(), IoError> {
9770    validate_sql_ident(schema, "schema")
9771}
9772
9773/// Validate `name` against the backend's identifier-length cap.
9774///
9775/// Per br-frankenpandas-9ynk (fd90.27). When `max` is `Some(n)`, errors
9776/// out when `name.len() > n`. When `max` is `None`, accepts any length
9777/// (e.g. SQLite, where the engine has no documented limit). `kind` is
9778/// the user-facing label used in the error message ("table", "column",
9779/// "index label", ...) so misuse points cleanly back to the offending
9780/// identifier without callers having to format the message.
9781fn validate_sql_identifier_length(
9782    name: &str,
9783    max: Option<usize>,
9784    kind: &str,
9785) -> Result<(), IoError> {
9786    if let Some(limit) = max
9787        && name.len() > limit
9788    {
9789        return Err(IoError::Sql(format!(
9790            "invalid {kind} name '{name}': length {len} exceeds backend identifier limit ({limit})",
9791            len = name.len()
9792        )));
9793    }
9794    Ok(())
9795}
9796
9797fn validate_sql_table_ref_identifier_lengths<C: SqlConnection + ?Sized>(
9798    conn: &C,
9799    table_name: &str,
9800    schema: Option<&str>,
9801) -> Result<(), IoError> {
9802    let max = conn.max_identifier_length();
9803    validate_sql_identifier_length(table_name, max, "table")?;
9804    if let Some(s) = schema {
9805        validate_sql_identifier_length(s, max, "schema")?;
9806    }
9807    Ok(())
9808}
9809
9810fn validate_sql_column_identifier_lengths<C, I, S>(conn: &C, names: I) -> Result<(), IoError>
9811where
9812    C: SqlConnection + ?Sized,
9813    I: IntoIterator<Item = S>,
9814    S: AsRef<str>,
9815{
9816    let max = conn.max_identifier_length();
9817    for name in names {
9818        validate_sql_identifier_length(name.as_ref(), max, "column")?;
9819    }
9820    Ok(())
9821}
9822
9823fn sql_select_all_query<C: SqlConnection>(conn: &C, table_name: &str) -> Result<String, IoError> {
9824    sql_select_all_query_in_schema(conn, table_name, None)
9825}
9826
9827/// Build a `SELECT * FROM ...` statement, optionally schema-qualified.
9828///
9829/// Per br-frankenpandas-u6zn (fd90.14). When `schema` is `Some(s)` AND
9830/// `conn.supports_schemas()`, the FROM clause becomes `\"schema\".\"table\"`.
9831/// When `supports_schemas` returns false, any `Some(s)` is rejected before
9832/// query generation so `read_sql_table(schema=...)` matches pandas' fail-closed
9833/// SQLite behavior.
9834fn sql_select_all_query_in_schema<C: SqlConnection>(
9835    conn: &C,
9836    table_name: &str,
9837    schema: Option<&str>,
9838) -> Result<String, IoError> {
9839    validate_sql_table_name(table_name)?;
9840    validate_sql_table_ref_identifier_lengths(conn, table_name, schema)?;
9841    let qualified = match schema {
9842        Some(s) => {
9843            validate_sql_schema_name(s)?;
9844            if !conn.supports_schemas() {
9845                return Err(IoError::Sql(format!(
9846                    "read_sql_table: schema is not supported by {} backend",
9847                    conn.dialect_name()
9848                )));
9849            }
9850            format!(
9851                "{}.{}",
9852                conn.quote_identifier(s)?,
9853                conn.quote_identifier(table_name)?
9854            )
9855        }
9856        _ => conn.quote_identifier(table_name)?,
9857    };
9858    Ok(format!("SELECT * FROM {qualified}"))
9859}
9860
9861fn validate_sql_column_name(column_name: &str) -> Result<(), IoError> {
9862    validate_sql_ident(column_name, "column")
9863}
9864
9865fn sql_select_columns_query<C: SqlConnection>(
9866    conn: &C,
9867    table_name: &str,
9868    columns: &[&str],
9869) -> Result<String, IoError> {
9870    sql_select_columns_query_in_schema(conn, table_name, None, columns)
9871}
9872
9873/// Build a `SELECT col1, col2, ... FROM ...` statement, optionally
9874/// schema-qualified.
9875///
9876/// Per br-frankenpandas-d3e9 (fd90.34). Companion to
9877/// `sql_select_all_query_in_schema`. Same schema rules: when
9878/// `schema` is `Some(s)` AND `conn.supports_schemas()`, the FROM
9879/// clause becomes `\"schema\".\"table\"`; when `supports_schemas()`
9880/// returns false, the request is rejected before query generation.
9881fn sql_select_columns_query_in_schema<C: SqlConnection>(
9882    conn: &C,
9883    table_name: &str,
9884    schema: Option<&str>,
9885    columns: &[&str],
9886) -> Result<String, IoError> {
9887    validate_sql_table_name(table_name)?;
9888    if columns.is_empty() {
9889        return Err(IoError::Sql(
9890            "read_sql_table_columns: columns must be non-empty".to_owned(),
9891        ));
9892    }
9893    for name in columns {
9894        validate_sql_column_name(name)?;
9895    }
9896    validate_sql_table_ref_identifier_lengths(conn, table_name, schema)?;
9897    validate_sql_column_identifier_lengths(conn, columns)?;
9898
9899    let qualified = match schema {
9900        Some(s) => {
9901            validate_sql_schema_name(s)?;
9902            if !conn.supports_schemas() {
9903                return Err(IoError::Sql(format!(
9904                    "read_sql_table: schema is not supported by {} backend",
9905                    conn.dialect_name()
9906                )));
9907            }
9908            format!(
9909                "{}.{}",
9910                conn.quote_identifier(s)?,
9911                conn.quote_identifier(table_name)?
9912            )
9913        }
9914        _ => conn.quote_identifier(table_name)?,
9915    };
9916    let projection: Vec<String> = columns
9917        .iter()
9918        .map(|name| conn.quote_identifier(name))
9919        .collect::<Result<_, _>>()?;
9920    Ok(format!(
9921        "SELECT {} FROM {}",
9922        projection.join(", "),
9923        qualified
9924    ))
9925}
9926
9927fn sql_column_definition<C: SqlConnection>(
9928    conn: &C,
9929    column_name: &str,
9930    sql_type: &str,
9931) -> Result<String, IoError> {
9932    Ok(format!(
9933        "{} {sql_type}",
9934        conn.quote_identifier(column_name)?
9935    ))
9936}
9937
9938// ============================================================================
9939// PostgreSQL SqlConnection placeholder (feature = "sql-postgresql")
9940// ============================================================================
9941
9942#[cfg(feature = "sql-mysql")]
9943use std::cell::RefCell;
9944
9945// The `sql-postgresql` feature is intentionally a placeholder under the
9946// workspace no-Tokio policy. The removed concrete adapter used the `postgres`
9947// crate, which is built on tokio-postgres and pulled Tokio into all-features
9948// builds even when users did not need PostgreSQL.
9949
9950// ============================================================================
9951// MySQL SqlConnection Implementation (feature = "sql-mysql")
9952// ============================================================================
9953
9954/// Wrapper around `mysql::Conn` providing interior mutability for the
9955/// `SqlConnection` trait (which requires `&self`).
9956#[cfg(feature = "sql-mysql")]
9957pub struct MysqlConnection {
9958    conn: RefCell<mysql::Conn>,
9959}
9960
9961#[cfg(feature = "sql-mysql")]
9962impl MysqlConnection {
9963    pub fn new(conn: mysql::Conn) -> Self {
9964        Self {
9965            conn: RefCell::new(conn),
9966        }
9967    }
9968}
9969
9970#[cfg(feature = "sql-mysql")]
9971impl SqlConnection for MysqlConnection {
9972    fn query(&self, query_str: &str, params: &[Scalar]) -> Result<SqlQueryResult, IoError> {
9973        use mysql::prelude::*;
9974
9975        let mysql_params: Vec<mysql::Value> = params.iter().map(scalar_to_mysql_value).collect();
9976        let result: Vec<mysql::Row> = self
9977            .conn
9978            .borrow_mut()
9979            .exec(query_str, mysql_params)
9980            .map_err(|e| IoError::Sql(format!("MySQL query failed: {e}")))?;
9981
9982        if result.is_empty() {
9983            return Ok(SqlQueryResult {
9984                columns: Vec::new(),
9985                rows: Vec::new(),
9986            });
9987        }
9988
9989        let columns: Vec<String> = result[0]
9990            .columns_ref()
9991            .iter()
9992            .map(|c| c.name_str().to_string())
9993            .collect();
9994
9995        let mut out_rows = Vec::new();
9996        for row in &result {
9997            let mut values = Vec::new();
9998            for idx in 0..row.len() {
9999                let value = mysql_value_to_scalar(row.get(idx));
10000                values.push(value);
10001            }
10002            out_rows.push(values);
10003        }
10004
10005        Ok(SqlQueryResult {
10006            columns,
10007            rows: out_rows,
10008        })
10009    }
10010
10011    fn execute_batch(&self, sql: &str) -> Result<(), IoError> {
10012        use mysql::prelude::*;
10013        let mut conn = self.conn.borrow_mut();
10014        for statement in sql.split(';').filter(|s| !s.trim().is_empty()) {
10015            conn.query_drop(statement)
10016                .map_err(|e| IoError::Sql(format!("MySQL execute failed: {e}")))?;
10017        }
10018        Ok(())
10019    }
10020
10021    fn table_exists(&self, table_name: &str) -> Result<bool, IoError> {
10022        use mysql::prelude::*;
10023        let result: Option<(i32,)> = self
10024            .conn
10025            .borrow_mut()
10026            .exec_first(
10027                "SELECT 1 FROM information_schema.tables WHERE table_name = ? LIMIT 1",
10028                (table_name,),
10029            )
10030            .map_err(|e| IoError::Sql(format!("MySQL table_exists failed: {e}")))?;
10031        Ok(result.is_some())
10032    }
10033
10034    fn insert_rows(&self, insert_sql: &str, rows: &[Vec<Scalar>]) -> Result<(), IoError> {
10035        use mysql::prelude::*;
10036        let mut conn = self.conn.borrow_mut();
10037        for row in rows {
10038            let params: Vec<mysql::Value> = row.iter().map(scalar_to_mysql_value).collect();
10039            conn.exec_drop(insert_sql, params)
10040                .map_err(|e| IoError::Sql(format!("MySQL insert failed: {e}")))?;
10041        }
10042        Ok(())
10043    }
10044
10045    fn dtype_sql(&self, dtype: DType) -> &'static str {
10046        match dtype {
10047            DType::Bool | DType::BoolNullable => "TINYINT(1)",
10048            DType::Int64 | DType::Int64Nullable => "BIGINT",
10049            DType::Float64 => "DOUBLE",
10050            DType::Utf8 => "TEXT",
10051            DType::Datetime64 => "DATETIME",
10052            DType::Timedelta64 => "TIME",
10053            _ => "TEXT",
10054        }
10055    }
10056
10057    fn index_dtype_sql(&self, index: &Index) -> &'static str {
10058        mysql_sql_dtype_from_index(index)
10059    }
10060
10061    fn dialect_name(&self) -> &'static str {
10062        "mysql"
10063    }
10064
10065    fn parameter_marker(&self, _ordinal: usize) -> String {
10066        "?".to_owned()
10067    }
10068
10069    fn supports_returning(&self) -> bool {
10070        false
10071    }
10072
10073    fn max_param_count(&self) -> Option<usize> {
10074        Some(65535)
10075    }
10076
10077    fn max_identifier_length(&self) -> Option<usize> {
10078        Some(64)
10079    }
10080
10081    fn quote_identifier(&self, ident: &str) -> Result<String, IoError> {
10082        if ident.contains('\0') {
10083            return Err(IoError::Sql("invalid identifier: NUL byte".to_owned()));
10084        }
10085        Ok(format!("`{}`", ident.replace('`', "``")))
10086    }
10087
10088    fn list_tables(&self, _schema: Option<&str>) -> Result<Vec<String>, IoError> {
10089        use mysql::prelude::*;
10090        let rows: Vec<(String,)> = self
10091            .conn
10092            .borrow_mut()
10093            .query("SHOW TABLES")
10094            .map_err(|e| IoError::Sql(format!("MySQL list_tables failed: {e}")))?;
10095        Ok(rows.into_iter().map(|(name,)| name).collect())
10096    }
10097}
10098
10099#[cfg(feature = "sql-mysql")]
10100fn mysql_sql_dtype_from_index(index: &Index) -> &'static str {
10101    for label in index.labels() {
10102        match label {
10103            IndexLabel::Int64(_) => return "BIGINT",
10104            IndexLabel::Utf8(_) => return "VARCHAR(255)",
10105            IndexLabel::Timedelta64(v) if *v != Timedelta::NAT => return "TIME",
10106            IndexLabel::Datetime64(v) if *v != i64::MIN => return "DATETIME",
10107            _ => {}
10108        }
10109    }
10110    "VARCHAR(255)"
10111}
10112
10113#[cfg(feature = "sql-mysql")]
10114fn scalar_to_mysql_value(s: &Scalar) -> mysql::Value {
10115    match s {
10116        Scalar::Null(_) => mysql::Value::NULL,
10117        Scalar::Bool(b) => mysql::Value::from(*b),
10118        Scalar::Int64(i) => mysql::Value::from(*i),
10119        Scalar::Float64(f) => mysql::Value::from(*f),
10120        Scalar::Utf8(s) => mysql::Value::from(s.as_str()),
10121        _ => mysql::Value::NULL,
10122    }
10123}
10124
10125#[cfg(feature = "sql-mysql")]
10126fn mysql_value_to_scalar(v: Option<mysql::Value>) -> Scalar {
10127    match v {
10128        None | Some(mysql::Value::NULL) => Scalar::Null(crate::NullKind::Null),
10129        Some(mysql::Value::Bytes(b)) => Scalar::Utf8(String::from_utf8_lossy(&b).into_owned()),
10130        Some(mysql::Value::Int(i)) => Scalar::Int64(i),
10131        Some(mysql::Value::UInt(u)) => Scalar::Int64(u as i64),
10132        Some(mysql::Value::Float(f)) => Scalar::Float64(f as f64),
10133        Some(mysql::Value::Double(d)) => Scalar::Float64(d),
10134        _ => Scalar::Null(crate::NullKind::Null),
10135    }
10136}
10137
10138#[cfg(test)]
10139fn sql_create_table_query<C: SqlConnection>(
10140    conn: &C,
10141    table_name: &str,
10142    column_defs: &[String],
10143) -> Result<String, IoError> {
10144    sql_create_table_query_in_schema(conn, table_name, None, column_defs)
10145}
10146
10147/// Build a `CREATE TABLE IF NOT EXISTS ...` statement, optionally
10148/// schema-qualified.
10149///
10150/// Per br-frankenpandas-udn6 (fd90.15). When `schema` is `Some(s)` AND
10151/// `conn.supports_schemas()`, the target becomes `"schema"."table"`. On
10152/// backends that report false, any `Some(s)` is silently ignored.
10153fn sql_create_table_query_in_schema<C: SqlConnection>(
10154    conn: &C,
10155    table_name: &str,
10156    schema: Option<&str>,
10157    column_defs: &[String],
10158) -> Result<String, IoError> {
10159    validate_sql_table_name(table_name)?;
10160    validate_sql_table_ref_identifier_lengths(conn, table_name, schema)?;
10161    let qualified = match schema {
10162        Some(s) if conn.supports_schemas() => {
10163            validate_sql_schema_name(s)?;
10164            format!(
10165                "{}.{}",
10166                conn.quote_identifier(s)?,
10167                conn.quote_identifier(table_name)?
10168            )
10169        }
10170        _ => conn.quote_identifier(table_name)?,
10171    };
10172    Ok(format!(
10173        "CREATE TABLE IF NOT EXISTS {qualified} ({})",
10174        column_defs.join(", ")
10175    ))
10176}
10177
10178#[cfg(test)]
10179fn sql_insert_rows_query<C: SqlConnection>(
10180    conn: &C,
10181    table_name: &str,
10182    column_names: &[String],
10183) -> Result<String, IoError> {
10184    sql_insert_rows_query_in_schema(conn, table_name, None, column_names)
10185}
10186
10187/// Build an `INSERT INTO ... VALUES (...)` statement, optionally
10188/// schema-qualified.
10189///
10190/// Per br-frankenpandas-udn6 (fd90.15). Same schema rules as the CREATE
10191/// TABLE counterpart.
10192fn sql_insert_rows_query_in_schema<C: SqlConnection>(
10193    conn: &C,
10194    table_name: &str,
10195    schema: Option<&str>,
10196    column_names: &[String],
10197) -> Result<String, IoError> {
10198    validate_sql_table_name(table_name)?;
10199    validate_sql_table_ref_identifier_lengths(conn, table_name, schema)?;
10200    validate_sql_column_identifier_lengths(conn, column_names.iter())?;
10201    let qualified = match schema {
10202        Some(s) if conn.supports_schemas() => {
10203            validate_sql_schema_name(s)?;
10204            format!(
10205                "{}.{}",
10206                conn.quote_identifier(s)?,
10207                conn.quote_identifier(table_name)?
10208            )
10209        }
10210        _ => conn.quote_identifier(table_name)?,
10211    };
10212    let quoted_columns = column_names
10213        .iter()
10214        .map(|name| conn.quote_identifier(name))
10215        .collect::<Result<Vec<_>, _>>()?
10216        .join(", ");
10217    let placeholders = (1..=column_names.len())
10218        .map(|ordinal| conn.parameter_marker(ordinal))
10219        .collect::<Vec<_>>()
10220        .join(", ");
10221    Ok(format!(
10222        "INSERT INTO {qualified} ({quoted_columns}) VALUES ({placeholders})"
10223    ))
10224}
10225
10226/// Build a multi-row `INSERT INTO ... VALUES (...), (...), ...`
10227/// statement, optionally schema-qualified.
10228///
10229/// Placeholder ordinals span 1..=`num_rows` * `column_names.len()` so
10230/// PostgreSQL-style `$N` markers stay unique across the whole statement.
10231/// SQLite's `?N` and the bare `?` default also work because positional
10232/// binding consumes ordinals in left-to-right order.
10233///
10234/// Per br-frankenpandas-i0ml (fd90.19).
10235fn sql_multi_row_insert_query_in_schema<C: SqlConnection>(
10236    conn: &C,
10237    table_name: &str,
10238    schema: Option<&str>,
10239    column_names: &[String],
10240    num_rows: usize,
10241) -> Result<String, IoError> {
10242    validate_sql_table_name(table_name)?;
10243    if num_rows == 0 || column_names.is_empty() {
10244        return Err(IoError::Sql(
10245            "multi-row insert requires at least one row and one column".to_owned(),
10246        ));
10247    }
10248    validate_sql_table_ref_identifier_lengths(conn, table_name, schema)?;
10249    validate_sql_column_identifier_lengths(conn, column_names.iter())?;
10250    let qualified = match schema {
10251        Some(s) if conn.supports_schemas() => {
10252            validate_sql_schema_name(s)?;
10253            format!(
10254                "{}.{}",
10255                conn.quote_identifier(s)?,
10256                conn.quote_identifier(table_name)?
10257            )
10258        }
10259        _ => conn.quote_identifier(table_name)?,
10260    };
10261    let quoted_columns = column_names
10262        .iter()
10263        .map(|name| conn.quote_identifier(name))
10264        .collect::<Result<Vec<_>, _>>()?
10265        .join(", ");
10266    let cols = column_names.len();
10267    let mut tuples = Vec::with_capacity(num_rows);
10268    let mut next_ord = 1usize;
10269    for _ in 0..num_rows {
10270        let row_placeholders = (0..cols)
10271            .map(|_| {
10272                let marker = conn.parameter_marker(next_ord);
10273                next_ord += 1;
10274                marker
10275            })
10276            .collect::<Vec<_>>()
10277            .join(", ");
10278        tuples.push(format!("({row_placeholders})"));
10279    }
10280    Ok(format!(
10281        "INSERT INTO {qualified} ({quoted_columns}) VALUES {}",
10282        tuples.join(", ")
10283    ))
10284}
10285
10286/// Build a `DROP TABLE IF EXISTS ...` statement, optionally
10287/// schema-qualified.
10288///
10289/// Per br-frankenpandas-hxob (fd90.16). Companion to
10290/// `sql_create_table_query_in_schema`. Same schema rules: when
10291/// `schema` is `Some(s)` AND `conn.supports_schemas()`, the target
10292/// becomes `\"schema\".\"table\"`; otherwise the bare table name is
10293/// used. Routes through `conn.quote_identifier` so backend dialect
10294/// overrides (MySQL backticks etc.) take effect on the drop path.
10295fn sql_drop_table_query_in_schema<C: SqlConnection>(
10296    conn: &C,
10297    table_name: &str,
10298    schema: Option<&str>,
10299) -> Result<String, IoError> {
10300    validate_sql_table_name(table_name)?;
10301    validate_sql_table_ref_identifier_lengths(conn, table_name, schema)?;
10302    let qualified = match schema {
10303        Some(s) if conn.supports_schemas() => {
10304            validate_sql_schema_name(s)?;
10305            format!(
10306                "{}.{}",
10307                conn.quote_identifier(s)?,
10308                conn.quote_identifier(table_name)?
10309            )
10310        }
10311        _ => conn.quote_identifier(table_name)?,
10312    };
10313    Ok(format!("DROP TABLE IF EXISTS {qualified}"))
10314}
10315
10316/// Read the result of a SQL query into a DataFrame.
10317///
10318/// Matches `pd.read_sql(sql, con)`.
10319pub fn read_sql<C: SqlConnection>(conn: &C, query: &str) -> Result<DataFrame, IoError> {
10320    read_sql_with_options(conn, query, &SqlReadOptions::default())
10321}
10322
10323/// Read the result of a SQL query into a DataFrame with read-time options.
10324///
10325/// Matches the supported subset of `pd.read_sql(sql, con, params=[...], parse_dates=...)`.
10326pub fn read_sql_with_options<C: SqlConnection>(
10327    conn: &C,
10328    query: &str,
10329    options: &SqlReadOptions,
10330) -> Result<DataFrame, IoError> {
10331    // Per br-frankenpandas-t1777: query readers take a raw SELECT written
10332    // by the caller, so options.columns has no effect. Silently ignoring
10333    // diverged from the table-reader sibling. Reject to surface the
10334    // mismatch — callers should embed the column list in the SELECT, or
10335    // use read_sql_table_with_options to generate the projection.
10336    if options.columns.is_some() {
10337        return Err(IoError::Sql(
10338            "options.columns is meaningful only for table readers; embed the column list in \
10339             the SELECT or use read_sql_table_with_options to generate the projection from a \
10340             table name"
10341                .to_owned(),
10342        ));
10343    }
10344    let (headers, columns, dtype_hints) = sql_query_to_columns(conn, query, options)?;
10345    let frame = dataframe_from_sql_columns(headers, columns, dtype_hints)?;
10346    apply_sql_index_col(frame, options.index_col.as_deref())
10347}
10348
10349/// Per br-frankenpandas-c1h9 (fd90.36): promote `options.index_col`
10350/// to the DataFrame index when set, with empty-string rejection.
10351fn apply_sql_index_col(frame: DataFrame, index_col: Option<&str>) -> Result<DataFrame, IoError> {
10352    let Some(name) = index_col else {
10353        return Ok(frame);
10354    };
10355    if name.is_empty() {
10356        return Err(IoError::Sql(
10357            "index_col: empty string is not a valid column name".to_owned(),
10358        ));
10359    }
10360    promote_column_to_index(&frame, name)
10361}
10362
10363/// Read the result of a SQL query into a DataFrame.
10364///
10365/// Matches `pd.read_sql_query(sql, con)`. This is the query-only spelling of
10366/// `read_sql`; table-name dispatch stays on `read_sql_table`.
10367pub fn read_sql_query<C: SqlConnection>(conn: &C, query: &str) -> Result<DataFrame, IoError> {
10368    read_sql(conn, query)
10369}
10370
10371/// Read the result of a SQL query into a DataFrame with read-time options.
10372///
10373/// Matches the supported subset of
10374/// `pd.read_sql_query(sql, con, params=[...], parse_dates=..., coerce_float=...)`.
10375pub fn read_sql_query_with_options<C: SqlConnection>(
10376    conn: &C,
10377    query: &str,
10378    options: &SqlReadOptions,
10379) -> Result<DataFrame, IoError> {
10380    read_sql_with_options(conn, query, options)
10381}
10382
10383/// Read a SQL query result with read-time options and optional index promotion.
10384///
10385/// Matches the supported subset of
10386/// `pd.read_sql_query(sql, con, params=[...], parse_dates=..., coerce_float=..., index_col=...)`.
10387pub fn read_sql_query_with_options_and_index_col<C: SqlConnection>(
10388    conn: &C,
10389    query: &str,
10390    options: &SqlReadOptions,
10391    index_col: Option<&str>,
10392) -> Result<DataFrame, IoError> {
10393    if let Some(col_name) = index_col {
10394        let cleared = SqlReadOptions {
10395            index_col: None,
10396            ..options.clone()
10397        };
10398        let frame = read_sql_query_with_options(conn, query, &cleared)?;
10399        return apply_sql_index_col(frame, Some(col_name));
10400    }
10401    read_sql_query_with_options(conn, query, options)
10402}
10403
10404/// Read the result of a SQL query as an iterator of DataFrame chunks.
10405///
10406/// Matches the supported subset of `pd.read_sql_query(sql, con, chunksize=...)`.
10407pub fn read_sql_query_chunks<'conn, C: SqlConnection + 'conn>(
10408    conn: &'conn C,
10409    query: &str,
10410    chunk_size: usize,
10411) -> Result<SqlChunkIterator<'conn>, IoError> {
10412    read_sql_chunks(conn, query, chunk_size)
10413}
10414
10415/// Read a SQL query result as chunks with one column promoted to each chunk's index.
10416///
10417/// Matches the supported subset of
10418/// `pd.read_sql_query(sql, con, index_col=..., chunksize=...)`.
10419pub fn read_sql_query_chunks_with_index_col<'conn, C: SqlConnection + 'conn>(
10420    conn: &'conn C,
10421    query: &str,
10422    index_col: Option<&str>,
10423    chunk_size: usize,
10424) -> Result<SqlIndexedChunkIterator<'conn>, IoError> {
10425    read_sql_chunks_with_index_col(conn, query, index_col, chunk_size)
10426}
10427
10428/// Read the result of a SQL query as chunks with read-time options.
10429///
10430/// Matches the supported subset of
10431/// `pd.read_sql_query(sql, con, params=[...], parse_dates=..., coerce_float=..., chunksize=...)`.
10432pub fn read_sql_query_chunks_with_options<'conn, C: SqlConnection + 'conn>(
10433    conn: &'conn C,
10434    query: &str,
10435    options: &SqlReadOptions,
10436    chunk_size: usize,
10437) -> Result<SqlChunkIterator<'conn>, IoError> {
10438    if options.index_col.is_some() {
10439        return Err(IoError::Sql(
10440            "options.index_col is set but this entrypoint returns SqlChunkIterator without \
10441             index promotion; use read_sql_query_chunks_with_options_and_index_col to honor \
10442             index_col"
10443                .to_owned(),
10444        ));
10445    }
10446    read_sql_chunks_with_options(conn, query, options, chunk_size)
10447}
10448
10449/// Read a SQL query result as chunks with read-time options and index promotion.
10450///
10451/// Matches the supported subset of
10452/// `pd.read_sql_query(sql, con, params=[...], parse_dates=..., coerce_float=..., index_col=..., chunksize=...)`.
10453pub fn read_sql_query_chunks_with_options_and_index_col<'conn, C: SqlConnection + 'conn>(
10454    conn: &'conn C,
10455    query: &str,
10456    options: &SqlReadOptions,
10457    index_col: Option<&str>,
10458    chunk_size: usize,
10459) -> Result<SqlIndexedChunkIterator<'conn>, IoError> {
10460    read_sql_chunks_with_options_and_index_col(conn, query, options, index_col, chunk_size)
10461}
10462
10463/// Read a SQL query result with one column promoted to the index.
10464///
10465/// Matches `pd.read_sql_query(sql, con, index_col=...)`.
10466pub fn read_sql_query_with_index_col<C: SqlConnection>(
10467    conn: &C,
10468    query: &str,
10469    index_col: Option<&str>,
10470) -> Result<DataFrame, IoError> {
10471    read_sql_with_index_col(conn, query, index_col)
10472}
10473
10474fn sql_trim_chunk_source(query: &str) -> Result<&str, IoError> {
10475    let trimmed = query.trim().trim_end_matches(';').trim();
10476    if trimmed.is_empty() {
10477        Err(IoError::Sql("read_sql query must be non-empty".to_owned()))
10478    } else {
10479        Ok(trimmed)
10480    }
10481}
10482
10483fn sql_paged_query<C: SqlConnection + ?Sized>(
10484    conn: &C,
10485    query: &str,
10486    base_param_count: usize,
10487) -> Result<String, IoError> {
10488    let source = sql_trim_chunk_source(query)?;
10489    let limit_marker = conn.parameter_marker(base_param_count + 1);
10490    let offset_marker = conn.parameter_marker(base_param_count + 2);
10491    Ok(format!(
10492        "SELECT * FROM ({source}) AS frankenpandas_sql_chunk_source \
10493         LIMIT {limit_marker} OFFSET {offset_marker}"
10494    ))
10495}
10496
10497fn sql_paged_options(
10498    options: &SqlReadOptions,
10499    limit: usize,
10500    offset: usize,
10501) -> Result<SqlReadOptions, IoError> {
10502    let limit = i64::try_from(limit)
10503        .map_err(|_| IoError::Sql("read_sql chunksize exceeds i64 range".to_owned()))?;
10504    let offset = i64::try_from(offset)
10505        .map_err(|_| IoError::Sql("read_sql chunk offset exceeds i64 range".to_owned()))?;
10506    let mut params = options.params.clone().unwrap_or_default();
10507    params.push(Scalar::Int64(limit));
10508    params.push(Scalar::Int64(offset));
10509    Ok(SqlReadOptions {
10510        params: Some(params),
10511        ..options.clone()
10512    })
10513}
10514
10515fn sql_paged_query_headers<C: SqlConnection + ?Sized>(
10516    conn: &C,
10517    query: &str,
10518    options: &SqlReadOptions,
10519) -> Result<Vec<String>, IoError> {
10520    let base_param_count = options.params.as_ref().map_or(0, Vec::len);
10521    let paged_query = sql_paged_query(conn, query, base_param_count)?;
10522    let paged_options = sql_paged_options(options, 0, 0)?;
10523    let result = conn.query(&paged_query, paged_options.params.as_deref().unwrap_or(&[]))?;
10524    reject_duplicate_headers(&result.columns)?;
10525    Ok(result.columns)
10526}
10527
10528fn sql_query_to_columns_paged<C: SqlConnection + ?Sized>(
10529    conn: &C,
10530    query: &str,
10531    options: &SqlReadOptions,
10532    chunk_size: usize,
10533    offset: usize,
10534) -> Result<SqlMaterializedColumns, IoError> {
10535    let base_param_count = options.params.as_ref().map_or(0, Vec::len);
10536    let paged_query = sql_paged_query(conn, query, base_param_count)?;
10537    let paged_options = sql_paged_options(options, chunk_size, offset)?;
10538    sql_query_to_columns(conn, &paged_query, &paged_options)
10539}
10540
10541fn sql_query_to_columns<C: SqlConnection + ?Sized>(
10542    conn: &C,
10543    query: &str,
10544    options: &SqlReadOptions,
10545) -> Result<SqlMaterializedColumns, IoError> {
10546    let params = options.params.as_deref().unwrap_or(&[]);
10547    let SqlQueryResult {
10548        columns: headers,
10549        rows,
10550    } = conn.query(query, params)?;
10551    reject_duplicate_headers(&headers)?;
10552    let mut dtype_hints = conn.query_column_dtypes(query, params)?;
10553    dtype_hints.resize(headers.len(), None);
10554    let mut columns: Vec<Vec<Scalar>> = (0..headers.len()).map(|_| Vec::new()).collect();
10555
10556    for row in rows {
10557        for (col_idx, value) in row.into_iter().enumerate() {
10558            if let Some(col_vec) = columns.get_mut(col_idx) {
10559                col_vec.push(value);
10560            }
10561        }
10562    }
10563
10564    if let Some(ref parse_dates) = options.parse_dates {
10565        apply_parse_dates_to_scalar_columns(&headers, &mut columns, parse_dates)?;
10566    }
10567    if options.coerce_float {
10568        apply_sql_coerce_float(&mut columns);
10569    }
10570    if let Some(ref dtype_map) = options.dtype {
10571        apply_sql_dtype_overrides(
10572            &headers,
10573            &mut columns,
10574            dtype_map,
10575            options.parse_dates.as_deref().unwrap_or(&[]),
10576        )?;
10577        for (idx, header) in headers.iter().enumerate() {
10578            if let Some(dtype) = dtype_map.get(header)
10579                && !options
10580                    .parse_dates
10581                    .as_deref()
10582                    .unwrap_or(&[])
10583                    .iter()
10584                    .any(|d| d == header)
10585            {
10586                dtype_hints[idx] = Some(*dtype);
10587            }
10588        }
10589    }
10590
10591    Ok((headers, columns, dtype_hints))
10592}
10593
10594/// Apply pandas-style `dtype={'col': dtype}` overrides to materialized
10595/// SQL result columns. Skips columns also listed in `parse_dates` to
10596/// avoid double-cast errors. Per br-frankenpandas-l9pt (fd90.11).
10597fn apply_sql_dtype_overrides(
10598    headers: &[String],
10599    columns: &mut [Vec<Scalar>],
10600    dtype_map: &BTreeMap<String, DType>,
10601    parse_dates: &[String],
10602) -> Result<(), IoError> {
10603    for (idx, header) in headers.iter().enumerate() {
10604        let Some(target_dtype) = dtype_map.get(header) else {
10605            continue;
10606        };
10607        if parse_dates.iter().any(|d| d == header) {
10608            // parse_dates wins; skip dtype override for this column.
10609            continue;
10610        }
10611        let Some(col) = columns.get_mut(idx) else {
10612            continue;
10613        };
10614        for value in col.iter_mut() {
10615            // Take ownership of the scalar, cast, and write back. NaT/Null
10616            // pass through cast_scalar_owned unchanged so missingness is
10617            // preserved across the override.
10618            let taken = std::mem::replace(value, Scalar::Null(NullKind::Null));
10619            *value = cast_scalar_owned(taken, *target_dtype).map_err(|e| {
10620                IoError::Sql(format!(
10621                    "dtype override on column '{header}' to {target_dtype:?} failed: {e}"
10622                ))
10623            })?;
10624        }
10625    }
10626    Ok(())
10627}
10628
10629fn dataframe_from_sql_columns(
10630    headers: Vec<String>,
10631    columns: Vec<Vec<Scalar>>,
10632    dtype_hints: SqlColumnDtypeHints,
10633) -> Result<DataFrame, IoError> {
10634    let row_count = columns.first().map_or(0, Vec::len);
10635    let mut out_columns = BTreeMap::new();
10636    let mut column_order = Vec::new();
10637
10638    for (idx, (name, values)) in headers.into_iter().zip(columns).enumerate() {
10639        let dtype_hint = dtype_hints.get(idx).copied().flatten();
10640        let has_observed_value = values.iter().any(|value| !matches!(value, Scalar::Null(_)));
10641        let column = match (has_observed_value, dtype_hint) {
10642            (false, Some(dtype)) => Column::new(dtype, values)?,
10643            _ => Column::from_values(values)?,
10644        };
10645        out_columns.insert(name.clone(), column);
10646        column_order.push(name);
10647    }
10648
10649    let index = Index::from_i64((0..row_count as i64).collect());
10650    Ok(DataFrame::new_with_column_order(
10651        index,
10652        out_columns,
10653        column_order,
10654    )?)
10655}
10656
10657/// Read a SQL query result as an iterator of DataFrame chunks.
10658///
10659/// Matches the supported subset of `pd.read_sql(sql, con, chunksize=...)`.
10660/// Each chunk receives a fresh zero-based RangeIndex, matching pandas'
10661/// SQLite chunk iterator behavior.
10662pub fn read_sql_chunks<'conn, C: SqlConnection + 'conn>(
10663    conn: &'conn C,
10664    query: &str,
10665    chunk_size: usize,
10666) -> Result<SqlChunkIterator<'conn>, IoError> {
10667    read_sql_chunks_with_options(conn, query, &SqlReadOptions::default(), chunk_size)
10668}
10669
10670/// Read a SQL query result as DataFrame chunks with read-time options.
10671///
10672/// Backends that opt into `supports_paged_sql_chunks` are queried one bounded
10673/// page at a time through a `LIMIT`/`OFFSET` wrapper so the iterator does not
10674/// hold the full result set in memory. Other backends keep the legacy
10675/// materialized fallback until they provide a native chunk strategy. `params`,
10676/// `parse_dates`, `coerce_float`, and `dtype` are applied to each yielded page.
10677pub fn read_sql_chunks_with_options<'conn, C: SqlConnection + 'conn>(
10678    conn: &'conn C,
10679    query: &str,
10680    options: &SqlReadOptions,
10681    chunk_size: usize,
10682) -> Result<SqlChunkIterator<'conn>, IoError> {
10683    if chunk_size == 0 {
10684        return Err(IoError::Sql(
10685            "read_sql chunksize must be greater than zero".to_owned(),
10686        ));
10687    }
10688    // Per br-frankenpandas-i8kja: this entrypoint returns SqlChunkIterator
10689    // with no index promotion. Honoring options.index_col would silently
10690    // diverge from the full-frame read_sql_with_options sibling (which
10691    // does promote). Reject to surface the mismatch — callers should use
10692    // read_sql_chunks_with_options_and_index_col when index_col is set.
10693    if options.index_col.is_some() {
10694        return Err(IoError::Sql(
10695            "options.index_col is set but this entrypoint returns SqlChunkIterator without \
10696             index promotion; use read_sql_chunks_with_options_and_index_col to honor index_col"
10697                .to_owned(),
10698        ));
10699    }
10700    // Per br-frankenpandas-t1777: query readers take a raw SELECT written
10701    // by the caller, so options.columns has no effect (the projection is
10702    // already in the query string). Silently ignoring would diverge from
10703    // the table-reader sibling (which honors columns to build the SELECT).
10704    // Reject to surface the mismatch — callers should embed the column
10705    // list in the SELECT, or use read_sql_table_chunks_with_options when
10706    // generating the SELECT from a table name.
10707    if options.columns.is_some() {
10708        return Err(IoError::Sql(
10709            "options.columns is meaningful only for table readers; embed the column list in \
10710             the SELECT or use read_sql_table_chunks_with_options to generate the projection \
10711             from a table name"
10712                .to_owned(),
10713        ));
10714    }
10715
10716    if conn.supports_paged_sql_chunks() {
10717        return SqlChunkIterator::paged(conn, query, options, chunk_size);
10718    }
10719
10720    let (headers, columns, dtype_hints) = sql_query_to_columns(conn, query, options)?;
10721    Ok(SqlChunkIterator::materialized(
10722        headers,
10723        columns,
10724        dtype_hints,
10725        chunk_size,
10726    ))
10727}
10728
10729/// Read a SQL query result as DataFrame chunks with read-time options and optional index promotion.
10730///
10731/// `params`, `parse_dates`, `coerce_float`, and `dtype` are applied to each
10732/// yielded page before optional index promotion.
10733pub fn read_sql_chunks_with_options_and_index_col<'conn, C: SqlConnection + 'conn>(
10734    conn: &'conn C,
10735    query: &str,
10736    options: &SqlReadOptions,
10737    index_col: Option<&str>,
10738    chunk_size: usize,
10739) -> Result<SqlIndexedChunkIterator<'conn>, IoError> {
10740    // Per br-frankenpandas-t1777: query readers can't apply options.columns
10741    // (caller writes the SELECT). Reject for consistency with the plain
10742    // chunk reader's rejection — the indexed sibling shouldn't be a
10743    // backdoor.
10744    if options.columns.is_some() {
10745        return Err(IoError::Sql(
10746            "options.columns is meaningful only for table readers; embed the column list in \
10747             the SELECT or use read_sql_table_chunks_with_options_and_index_col to generate \
10748             the projection from a table name"
10749                .to_owned(),
10750        ));
10751    }
10752    // The plain chunk reader rejects options.index_col (see i8kja); clear
10753    // it before delegating so the indexed sibling is the canonical
10754    // honor-index_col entrypoint regardless of which slot the caller used.
10755    let cleared = SqlReadOptions {
10756        index_col: None,
10757        ..options.clone()
10758    };
10759    let inner = read_sql_chunks_with_options(conn, query, &cleared, chunk_size)?;
10760    sql_indexed_chunks(inner, index_col.or(options.index_col.as_deref()))
10761}
10762
10763/// Read a SQL query result as DataFrame chunks with optional index promotion.
10764///
10765/// Matches the supported subset of `pd.read_sql(sql, con, index_col=..., chunksize=...)`.
10766pub fn read_sql_chunks_with_index_col<'conn, C: SqlConnection + 'conn>(
10767    conn: &'conn C,
10768    query: &str,
10769    index_col: Option<&str>,
10770    chunk_size: usize,
10771) -> Result<SqlIndexedChunkIterator<'conn>, IoError> {
10772    let inner = read_sql_chunks(conn, query, chunk_size)?;
10773    sql_indexed_chunks(inner, index_col)
10774}
10775
10776/// Read a SQL query result with one column promoted to the index.
10777///
10778/// Matches `pd.read_sql(sql, con, index_col=...)`. When
10779/// `index_col=Some(name)` the named column is removed from the data
10780/// columns and its values become the DataFrame's row index. Returns
10781/// `IoError::Sql` if the named column is absent from the result set.
10782pub fn read_sql_with_index_col<C: SqlConnection>(
10783    conn: &C,
10784    query: &str,
10785    index_col: Option<&str>,
10786) -> Result<DataFrame, IoError> {
10787    let frame = read_sql(conn, query)?;
10788    apply_sql_index_col(frame, index_col)
10789}
10790
10791/// Read an entire SQL table with one column promoted to the index.
10792///
10793/// Matches `pd.read_sql_table(table, con, index_col=...)`.
10794pub fn read_sql_table_with_index_col<C: SqlConnection>(
10795    conn: &C,
10796    table_name: &str,
10797    index_col: Option<&str>,
10798) -> Result<DataFrame, IoError> {
10799    let frame = read_sql_table(conn, table_name)?;
10800    apply_sql_index_col(frame, index_col)
10801}
10802
10803fn promote_column_to_index(frame: &DataFrame, col_name: &str) -> Result<DataFrame, IoError> {
10804    let column = frame.column(col_name).ok_or_else(|| {
10805        IoError::Sql(format!(
10806            "index_col {col_name:?} not present in result columns"
10807        ))
10808    })?;
10809    let labels: Vec<IndexLabel> = column
10810        .values()
10811        .iter()
10812        .map(|v| match v {
10813            Scalar::Int64(i) => IndexLabel::Int64(*i),
10814            Scalar::Utf8(s) => IndexLabel::Utf8(s.clone()),
10815            Scalar::Float64(f) if !f.is_nan() => IndexLabel::Utf8(f.to_string()),
10816            Scalar::Bool(b) => IndexLabel::Utf8(if *b { "True" } else { "False" }.to_string()),
10817            Scalar::Timedelta64(ns) => IndexLabel::Timedelta64(*ns),
10818            // A parse_dates column promoted to index becomes a DatetimeIndex
10819            // (typed Datetime64[ns], br-frankenpandas-0ezw7) — not a "NaN" string.
10820            Scalar::Datetime64(ns) => IndexLabel::Datetime64(*ns),
10821            _ => IndexLabel::Utf8("NaN".to_owned()),
10822        })
10823        .collect();
10824    let new_index = Index::new(labels).set_name(col_name);
10825
10826    let mut new_columns = std::collections::BTreeMap::new();
10827    let mut new_order = Vec::new();
10828    for name in frame.column_names() {
10829        if name == col_name {
10830            continue;
10831        }
10832        if let Some(col) = frame.column(name) {
10833            new_columns.insert(name.clone(), col.clone());
10834            new_order.push(name.clone());
10835        }
10836    }
10837
10838    Ok(DataFrame::new_with_column_order(
10839        new_index,
10840        new_columns,
10841        new_order,
10842    )?)
10843}
10844
10845/// Read an entire SQL table into a DataFrame.
10846///
10847/// Matches `pd.read_sql_table(table_name, con)`.
10848pub fn read_sql_table<C: SqlConnection>(conn: &C, table_name: &str) -> Result<DataFrame, IoError> {
10849    read_sql(conn, &sql_select_all_query(conn, table_name)?)
10850}
10851
10852/// List user-visible table names known to the SQL backend.
10853///
10854/// Matches the supported subset of
10855/// `pd.io.sql.SQLDatabase.list_tables(schema=...)`. When the backend
10856/// reports `supports_schemas() == false` (SQLite), `schema` is ignored
10857/// and all tables in the single namespace are returned. When the
10858/// backend supports schemas (PostgreSQL, MySQL, MSSQL), `Some(s)`
10859/// scopes the listing. `None` passes through to the backend
10860/// unchanged — backends MAY consult `default_schema()` for their own
10861/// fallback logic if desired (per fd90.57: this wrapper does NOT
10862/// apply the fallback automatically).
10863///
10864/// Per br-frankenpandas-vhq2 (fd90.20).
10865pub fn list_sql_tables<C: SqlConnection>(
10866    conn: &C,
10867    schema: Option<&str>,
10868) -> Result<Vec<String>, IoError> {
10869    conn.list_tables(schema)
10870}
10871
10872/// Introspect a SQL table's column metadata, optionally schema-scoped.
10873///
10874/// Matches the supported subset of
10875/// `pd.io.sql.SQLDatabase.has_table` + `SQLAlchemy.MetaData.reflect`
10876/// for column-level details. Returns `Ok(None)` when the table does
10877/// not exist. Schema arg is silently ignored when the backend reports
10878/// `supports_schemas() == false` (SQLite).
10879///
10880/// Per br-frankenpandas-w43q (fd90.21).
10881pub fn sql_table_schema<C: SqlConnection>(
10882    conn: &C,
10883    table_name: &str,
10884    schema: Option<&str>,
10885) -> Result<Option<SqlTableSchema>, IoError> {
10886    conn.table_schema(table_name, schema)
10887}
10888
10889/// List user-visible schemas exposed by the SQL backend.
10890///
10891/// Matches `SQLAlchemy.Inspector.get_schema_names()` shape. Single
10892/// namespace backends (SQLite) return an empty vector. Multi-schema
10893/// backends return the schemas the connection's role can see, with
10894/// internal/system schemas filtered out.
10895///
10896/// Per br-frankenpandas-lxhi (fd90.22).
10897pub fn list_sql_schemas<C: SqlConnection>(conn: &C) -> Result<Vec<String>, IoError> {
10898    conn.list_schemas()
10899}
10900
10901/// Reset a SQL table to empty without dropping its definition.
10902///
10903/// On backends that override the default (PostgreSQL, MySQL), this
10904/// uses `TRUNCATE TABLE` for a DDL-style fast-path reset. On backends
10905/// that inherit the default (SQLite), this emits `DELETE FROM <table>`,
10906/// which is universal but slower on large tables. Schema arg is
10907/// silently ignored when `supports_schemas() == false`.
10908///
10909/// Per br-frankenpandas-phum (fd90.23).
10910pub fn truncate_sql_table<C: SqlConnection>(
10911    conn: &C,
10912    table_name: &str,
10913    schema: Option<&str>,
10914) -> Result<(), IoError> {
10915    conn.truncate_table(table_name, schema)
10916}
10917
10918/// Probe the SQL backend's server version string.
10919///
10920/// Returns `Ok(None)` for backends that can't (or don't) introspect
10921/// their version. SQLite returns `Some("3.x.y")`. PostgreSQL/MySQL
10922/// impls return their respective `SHOW server_version` /
10923/// `SELECT VERSION()` payloads. Useful for dialect-version gating
10924/// (RETURNING, JSON ops, generated columns) and diagnostics.
10925///
10926/// Per br-frankenpandas-e23k (fd90.24).
10927pub fn sql_server_version<C: SqlConnection>(conn: &C) -> Result<Option<String>, IoError> {
10928    conn.server_version()
10929}
10930
10931/// Return the primary-key column names for a SQL table, ordered by
10932/// the table's primary-key ordinal.
10933///
10934/// Returns an empty vector when the table doesn't exist, has no
10935/// primary key, or the backend can't introspect column metadata.
10936/// Useful for upsert conflict-target generation and `index_label`
10937/// defaulting.
10938///
10939/// Per br-frankenpandas-uw3y (fd90.25).
10940pub fn sql_primary_key_columns<C: SqlConnection>(
10941    conn: &C,
10942    table_name: &str,
10943    schema: Option<&str>,
10944) -> Result<Vec<String>, IoError> {
10945    conn.primary_key_columns(table_name, schema)
10946}
10947
10948/// List user-defined indexes on a SQL table, optionally schema-scoped.
10949///
10950/// Matches `SQLAlchemy.Inspector.get_indexes()` shape. Returns an
10951/// empty vector when the table doesn't exist, has no user-created
10952/// indexes, or the backend can't introspect. Auto-created PRIMARY-KEY
10953/// indexes are filtered out (they're surfaced via primary_key_columns
10954/// instead).
10955///
10956/// Per br-frankenpandas-bgv9 (fd90.28).
10957pub fn list_sql_indexes<C: SqlConnection>(
10958    conn: &C,
10959    table_name: &str,
10960    schema: Option<&str>,
10961) -> Result<Vec<SqlIndexSchema>, IoError> {
10962    conn.list_indexes(table_name, schema)
10963}
10964
10965/// List user-visible view names known to the SQL backend.
10966///
10967/// Matches `SQLAlchemy.Inspector.get_view_names()` shape. Companion
10968/// to `list_sql_tables` — pandas/SQLAlchemy keep tables and views in
10969/// distinct buckets so `pd.read_sql_table` can distinguish them.
10970/// Schema arg is silently ignored when `supports_schemas() == false`.
10971///
10972/// Per br-frankenpandas-gm3r (fd90.30).
10973pub fn list_sql_views<C: SqlConnection>(
10974    conn: &C,
10975    schema: Option<&str>,
10976) -> Result<Vec<String>, IoError> {
10977    conn.list_views(schema)
10978}
10979
10980/// List foreign-key constraints declared on a SQL table, optionally
10981/// schema-scoped.
10982///
10983/// Matches `SQLAlchemy.Inspector.get_foreign_keys()` shape. Returns
10984/// an empty vector when the table has no FKs or the backend can't
10985/// introspect. Composite FKs are returned as a single entry with
10986/// paired `columns` / `referenced_columns` ordered by declaration
10987/// position. SQLite does not expose constraint names via PRAGMA, so
10988/// `constraint_name` is `None` there.
10989///
10990/// Per br-frankenpandas-uht8 (fd90.29).
10991pub fn list_sql_foreign_keys<C: SqlConnection>(
10992    conn: &C,
10993    table_name: &str,
10994    schema: Option<&str>,
10995) -> Result<Vec<SqlForeignKeySchema>, IoError> {
10996    conn.list_foreign_keys(table_name, schema)
10997}
10998
10999/// Probe the table-level comment for a SQL table, optionally
11000/// schema-scoped.
11001///
11002/// Matches `SQLAlchemy.Inspector.get_table_comment()` shape — returns
11003/// `Ok(Some(text))` when a comment exists, `Ok(None)` otherwise.
11004/// SQLite has no native table-comment storage and returns `None`.
11005/// PostgreSQL/MySQL/MSSQL impls override with their respective
11006/// catalog queries.
11007///
11008/// Per br-frankenpandas-yu3w (fd90.32).
11009pub fn sql_table_comment<C: SqlConnection>(
11010    conn: &C,
11011    table_name: &str,
11012    schema: Option<&str>,
11013) -> Result<Option<String>, IoError> {
11014    conn.table_comment(table_name, schema)
11015}
11016
11017/// List UNIQUE constraints declared on a SQL table.
11018///
11019/// Matches `SQLAlchemy.Inspector.get_unique_constraints()` shape.
11020/// Surfaces only inline `UNIQUE` declarations and `UNIQUE (...)`
11021/// table constraints. User-created `CREATE UNIQUE INDEX` indexes
11022/// remain in `list_sql_indexes` (with `unique == true`). The two
11023/// listings are intentionally disjoint to match SQLAlchemy.
11024///
11025/// Per br-frankenpandas-sh4v (fd90.31).
11026pub fn list_sql_unique_constraints<C: SqlConnection>(
11027    conn: &C,
11028    table_name: &str,
11029    schema: Option<&str>,
11030) -> Result<Vec<SqlUniqueConstraintSchema>, IoError> {
11031    conn.list_unique_constraints(table_name, schema)
11032}
11033
11034/// Maximum identifier length supported by the SQL backend, or `None`
11035/// when no documented limit exists.
11036///
11037/// Useful for to_sql validation: backends that override this report
11038/// their cap (PostgreSQL=63, MySQL=64, MSSQL=128) so auto-generated
11039/// index / constraint / column names can be truncated or rejected
11040/// before round-tripping through DDL that would silently truncate.
11041///
11042/// Per br-frankenpandas-cs81 (fd90.26).
11043pub fn sql_max_identifier_length<C: SqlConnection>(conn: &C) -> Option<usize> {
11044    conn.max_identifier_length()
11045}
11046
11047/// Backend capability summary exposed through `SqlInspector`.
11048///
11049/// The per-field values come from `SqlConnection` probes so concrete
11050/// backends can report their native ceilings without forcing callers to
11051/// branch on the connection type.
11052#[derive(Debug, Clone, PartialEq, Eq)]
11053pub struct SqlBackendCaps {
11054    pub dialect_name: &'static str,
11055    pub server_version: Option<String>,
11056    pub supports_returning: bool,
11057    pub supports_schemas: bool,
11058    pub max_param_count: Option<usize>,
11059    pub max_identifier_length: Option<usize>,
11060}
11061
11062impl SqlBackendCaps {
11063    /// Maximum rows in one parameter-bound INSERT for `column_count`.
11064    ///
11065    /// Returns `None` when the backend has no known parameter ceiling, or
11066    /// when `column_count` is zero and therefore no parameter-derived row
11067    /// ceiling can be computed.
11068    #[must_use]
11069    pub fn max_insert_rows(&self, column_count: usize) -> Option<usize> {
11070        sql_max_insert_rows_for_columns(self.max_param_count, column_count)
11071    }
11072}
11073
11074/// Maximum bound parameters supported by the SQL backend, if known.
11075#[must_use]
11076pub fn sql_max_param_count<C: SqlConnection>(conn: &C) -> Option<usize> {
11077    conn.max_param_count()
11078}
11079
11080/// Whether the SQL backend supports native `INSERT ... RETURNING`.
11081#[must_use]
11082pub fn sql_supports_returning<C: SqlConnection>(conn: &C) -> bool {
11083    conn.supports_returning()
11084}
11085
11086/// Whether the SQL backend exposes schema-qualified namespaces.
11087#[must_use]
11088pub fn sql_supports_schemas<C: SqlConnection>(conn: &C) -> bool {
11089    conn.supports_schemas()
11090}
11091
11092/// Maximum INSERT rows for `column_count`, derived from the backend's
11093/// bound-parameter ceiling.
11094///
11095/// A return value of `Some(0)` means the requested column count exceeds
11096/// the backend's total bind-parameter cap.
11097#[must_use]
11098pub fn sql_max_insert_rows<C: SqlConnection>(conn: &C, column_count: usize) -> Option<usize> {
11099    sql_max_insert_rows_for_columns(conn.max_param_count(), column_count)
11100}
11101
11102fn sql_max_insert_rows_for_columns(
11103    max_param_count: Option<usize>,
11104    column_count: usize,
11105) -> Option<usize> {
11106    if column_count == 0 {
11107        return None;
11108    }
11109    max_param_count.map(|max| max / column_count)
11110}
11111
11112/// Gather the backend capability probes into one typed bundle.
11113pub fn sql_backend_caps<C: SqlConnection>(conn: &C) -> Result<SqlBackendCaps, IoError> {
11114    Ok(SqlBackendCaps {
11115        dialect_name: conn.dialect_name(),
11116        server_version: conn.server_version()?,
11117        supports_returning: conn.supports_returning(),
11118        supports_schemas: conn.supports_schemas(),
11119        max_param_count: conn.max_param_count(),
11120        max_identifier_length: conn.max_identifier_length(),
11121    })
11122}
11123
11124/// Backend-agnostic introspection facade matching the
11125/// `SQLAlchemy.Inspector` shape.
11126///
11127/// Per br-frankenpandas-szs9 (fd90.38). Wraps a `&C: SqlConnection`
11128/// and exposes the full fd90.20-37 introspection surface as methods
11129/// on a single bundle so callers don't have to remember which
11130/// `list_sql_*` / `sql_*` free-fn to use. Pure delegation — no new
11131/// behavior, just API ergonomics.
11132///
11133/// ```rust,ignore
11134/// use frankenpandas::SqlInspector;
11135/// let inspector = SqlInspector::new(&conn);
11136/// for table in inspector.tables(None)? {
11137///     for col in inspector.columns(&table, None)?
11138///         .map(|s| s.columns)
11139///         .unwrap_or_default()
11140///     {
11141///         println!("{}: {:?}", col.name, col.declared_type);
11142///     }
11143/// }
11144/// ```
11145#[derive(Debug)]
11146pub struct SqlInspector<'a, C: SqlConnection> {
11147    conn: &'a C,
11148}
11149
11150impl<'a, C: SqlConnection> SqlInspector<'a, C> {
11151    /// Create a new inspector bound to the given connection.
11152    #[must_use]
11153    pub fn new(conn: &'a C) -> Self {
11154        Self { conn }
11155    }
11156
11157    /// List user-visible table names. See `list_sql_tables`.
11158    pub fn tables(&self, schema: Option<&str>) -> Result<Vec<String>, IoError> {
11159        self.conn.list_tables(schema)
11160    }
11161
11162    /// List user-visible view names. See `list_sql_views`.
11163    pub fn views(&self, schema: Option<&str>) -> Result<Vec<String>, IoError> {
11164        self.conn.list_views(schema)
11165    }
11166
11167    /// List user-visible schemas. See `list_sql_schemas`.
11168    pub fn schemas(&self) -> Result<Vec<String>, IoError> {
11169        self.conn.list_schemas()
11170    }
11171
11172    /// Introspect a table's columns. See `sql_table_schema`.
11173    pub fn columns(
11174        &self,
11175        table_name: &str,
11176        schema: Option<&str>,
11177    ) -> Result<Option<SqlTableSchema>, IoError> {
11178        self.conn.table_schema(table_name, schema)
11179    }
11180
11181    /// List user-defined indexes. See `list_sql_indexes`.
11182    pub fn indexes(
11183        &self,
11184        table_name: &str,
11185        schema: Option<&str>,
11186    ) -> Result<Vec<SqlIndexSchema>, IoError> {
11187        self.conn.list_indexes(table_name, schema)
11188    }
11189
11190    /// List foreign-key constraints. See `list_sql_foreign_keys`.
11191    pub fn foreign_keys(
11192        &self,
11193        table_name: &str,
11194        schema: Option<&str>,
11195    ) -> Result<Vec<SqlForeignKeySchema>, IoError> {
11196        self.conn.list_foreign_keys(table_name, schema)
11197    }
11198
11199    /// List UNIQUE constraints. See `list_sql_unique_constraints`.
11200    pub fn unique_constraints(
11201        &self,
11202        table_name: &str,
11203        schema: Option<&str>,
11204    ) -> Result<Vec<SqlUniqueConstraintSchema>, IoError> {
11205        self.conn.list_unique_constraints(table_name, schema)
11206    }
11207
11208    /// Return primary-key columns sorted by ordinal.
11209    /// See `sql_primary_key_columns`.
11210    pub fn primary_key_columns(
11211        &self,
11212        table_name: &str,
11213        schema: Option<&str>,
11214    ) -> Result<Vec<String>, IoError> {
11215        self.conn.primary_key_columns(table_name, schema)
11216    }
11217
11218    /// Probe the table-level comment. See `sql_table_comment`.
11219    pub fn table_comment(
11220        &self,
11221        table_name: &str,
11222        schema: Option<&str>,
11223    ) -> Result<Option<String>, IoError> {
11224        self.conn.table_comment(table_name, schema)
11225    }
11226
11227    /// Schema-aware existence check. Routes to
11228    /// `SqlConnection::table_exists_in_schema`.
11229    pub fn table_exists(&self, table_name: &str, schema: Option<&str>) -> Result<bool, IoError> {
11230        self.conn.table_exists_in_schema(table_name, schema)
11231    }
11232
11233    /// Probe the backend server version. See `sql_server_version`.
11234    pub fn server_version(&self) -> Result<Option<String>, IoError> {
11235        self.conn.server_version()
11236    }
11237
11238    /// Maximum identifier length, when the backend exposes one.
11239    /// See `sql_max_identifier_length`.
11240    #[must_use]
11241    pub fn max_identifier_length(&self) -> Option<usize> {
11242        self.conn.max_identifier_length()
11243    }
11244
11245    /// Maximum bound parameters supported by this backend, if known.
11246    #[must_use]
11247    pub fn max_param_count(&self) -> Option<usize> {
11248        self.conn.max_param_count()
11249    }
11250
11251    /// Maximum INSERT rows for `column_count`, derived from the backend's
11252    /// bound-parameter ceiling.
11253    #[must_use]
11254    pub fn max_insert_rows(&self, column_count: usize) -> Option<usize> {
11255        sql_max_insert_rows_for_columns(self.conn.max_param_count(), column_count)
11256    }
11257
11258    /// Whether this backend supports native `INSERT ... RETURNING`.
11259    #[must_use]
11260    pub fn supports_returning(&self) -> bool {
11261        self.conn.supports_returning()
11262    }
11263
11264    /// Whether this backend exposes schema-qualified namespaces.
11265    #[must_use]
11266    pub fn supports_schemas(&self) -> bool {
11267        self.conn.supports_schemas()
11268    }
11269
11270    /// Gather backend capability probes into one typed bundle.
11271    pub fn backend_caps(&self) -> Result<SqlBackendCaps, IoError> {
11272        sql_backend_caps(self.conn)
11273    }
11274
11275    /// Backend dialect name (`"sqlite"`, `"postgresql"`, etc.).
11276    #[must_use]
11277    pub fn dialect_name(&self) -> &'static str {
11278        self.conn.dialect_name()
11279    }
11280
11281    /// Check whether a specific column exists on a table.
11282    ///
11283    /// Per br-frankenpandas-ppry (fd90.39). Returns `Ok(false)` when
11284    /// the table doesn't exist (i.e. `columns` returns `None`), or
11285    /// when the table exists but has no column matching `column_name`.
11286    /// Returns `Ok(true)` only when the named column is present.
11287    /// Mirrors `SQLAlchemy.Inspector.has_column()` semantics.
11288    pub fn has_column(
11289        &self,
11290        table_name: &str,
11291        column_name: &str,
11292        schema: Option<&str>,
11293    ) -> Result<bool, IoError> {
11294        let Some(meta) = self.conn.table_schema(table_name, schema)? else {
11295            return Ok(false);
11296        };
11297        Ok(meta.column(column_name).is_some())
11298    }
11299
11300    /// Look up the metadata bundle for a single column.
11301    ///
11302    /// Per br-frankenpandas-ppry (fd90.39). Returns `Ok(None)` when the
11303    /// table doesn't exist or the column isn't present. The returned
11304    /// `SqlColumnSchema` carries the full set of fields populated by
11305    /// the underlying `table_schema` impl (declared_type, nullable,
11306    /// default_value, primary_key_ordinal, comment, autoincrement).
11307    pub fn column(
11308        &self,
11309        table_name: &str,
11310        column_name: &str,
11311        schema: Option<&str>,
11312    ) -> Result<Option<SqlColumnSchema>, IoError> {
11313        let Some(meta) = self.conn.table_schema(table_name, schema)? else {
11314            return Ok(None);
11315        };
11316        Ok(meta.column(column_name).cloned())
11317    }
11318
11319    /// Reflect a full table's metadata in one call: columns, primary
11320    /// key, indexes, foreign keys, unique constraints, and comment.
11321    ///
11322    /// Per br-frankenpandas-76mw (fd90.40). Mirrors
11323    /// `SQLAlchemy.MetaData.reflect_table` shape — gives callers a
11324    /// single bundle instead of 5 separate fetches. Returns `Ok(None)`
11325    /// when the table doesn't exist (matched via `table_schema`
11326    /// returning `None`); otherwise all derived calls run and any
11327    /// missing pieces (e.g. SQLite's always-None `table_comment`)
11328    /// are simply preserved as their natural empty values.
11329    ///
11330    /// Per br-frankenpandas-2kzv (fd90.43): primary-key columns are
11331    /// derived directly from the `SqlTableSchema` we already fetched
11332    /// rather than dispatching `primary_key_columns()` again — that
11333    /// trait method's default impl calls `table_schema()` internally,
11334    /// which would double the round-trip count for backends where
11335    /// each call is a real network hop.
11336    pub fn reflect_table(
11337        &self,
11338        table_name: &str,
11339        schema: Option<&str>,
11340    ) -> Result<Option<SqlReflectedTable>, IoError> {
11341        let Some(meta) = self.conn.table_schema(table_name, schema)? else {
11342            return Ok(None);
11343        };
11344        let primary_key_columns = primary_keys_from_schema(&meta);
11345        let indexes = self.conn.list_indexes(table_name, schema)?;
11346        let foreign_keys = self.conn.list_foreign_keys(table_name, schema)?;
11347        let unique_constraints = self.conn.list_unique_constraints(table_name, schema)?;
11348        let comment = self.conn.table_comment(table_name, schema)?;
11349        Ok(Some(SqlReflectedTable {
11350            table_name: meta.table_name,
11351            columns: meta.columns,
11352            primary_key_columns,
11353            indexes,
11354            foreign_keys,
11355            unique_constraints,
11356            comment,
11357        }))
11358    }
11359
11360    /// Reflect every user-visible table in `schema` into a vector of
11361    /// bundles, one per table.
11362    ///
11363    /// Per br-frankenpandas-jmmo (fd90.53). Iterates `tables(schema)`
11364    /// then calls `reflect_table` on each. Skips any table that
11365    /// `reflect_table` returns `Ok(None)` for — covers the race
11366    /// condition where a table existed at list time but not at
11367    /// reflect time (e.g. concurrent DROP). Useful for whole-database
11368    /// introspection in one call.
11369    pub fn reflect_all_tables(
11370        &self,
11371        schema: Option<&str>,
11372    ) -> Result<Vec<SqlReflectedTable>, IoError> {
11373        let table_names = self.conn.list_tables(schema)?;
11374        let mut bundles = Vec::with_capacity(table_names.len());
11375        for name in table_names {
11376            if let Some(bundle) = self.reflect_table(&name, schema)? {
11377                bundles.push(bundle);
11378            }
11379        }
11380        Ok(bundles)
11381    }
11382
11383    /// Reflect every user-visible view in `schema` into a vector of
11384    /// bundles, one per view.
11385    ///
11386    /// Per br-frankenpandas-zuqt (fd90.54). View-side parity with
11387    /// `reflect_all_tables`: iterates `views(schema)` then calls
11388    /// `reflect_table` on each (PRAGMA table_info works on views too,
11389    /// returning the view's column shape). PK/FK/UC/index lists in
11390    /// the bundle will typically be empty for views since views don't
11391    /// carry constraints — only the column metadata + comment are
11392    /// meaningful. Same disappearing-entity skip semantics as
11393    /// `reflect_all_tables`.
11394    pub fn reflect_all_views(
11395        &self,
11396        schema: Option<&str>,
11397    ) -> Result<Vec<SqlReflectedTable>, IoError> {
11398        let view_names = self.conn.list_views(schema)?;
11399        let mut bundles = Vec::with_capacity(view_names.len());
11400        for name in view_names {
11401            if let Some(bundle) = self.reflect_table(&name, schema)? {
11402                bundles.push(bundle);
11403            }
11404        }
11405        Ok(bundles)
11406    }
11407}
11408
11409/// Derive the primary-key column names from an already-fetched
11410/// `SqlTableSchema`, sorted ascending by `primary_key_ordinal`.
11411///
11412/// Per br-frankenpandas-2kzv (fd90.43) / fd90.47: this is the
11413/// canonical filter+sort impl shared by both
11414/// `SqlConnection::primary_key_columns` (the trait default) and
11415/// `SqlInspector::reflect_table` (which uses already-fetched
11416/// metadata to avoid a redundant `table_schema()` round-trip).
11417fn primary_keys_from_schema(meta: &SqlTableSchema) -> Vec<String> {
11418    let mut pk: Vec<(usize, String)> = meta
11419        .columns
11420        .iter()
11421        .filter_map(|c| c.primary_key_ordinal.map(|ord| (ord, c.name.clone())))
11422        .collect();
11423    pk.sort_by_key(|(ord, _)| *ord);
11424    pk.into_iter().map(|(_, name)| name).collect()
11425}
11426
11427/// Convenience constructor for `SqlInspector`.
11428///
11429/// `let inspector = inspect(&conn);` reads more naturally than
11430/// `SqlInspector::new(&conn)` for one-shot uses. Per br-frankenpandas-szs9 (fd90.38).
11431#[must_use]
11432pub fn inspect<C: SqlConnection>(conn: &C) -> SqlInspector<'_, C> {
11433    SqlInspector::new(conn)
11434}
11435
11436/// Read an entire SQL table into a DataFrame with read-time options.
11437///
11438/// Matches the supported subset of
11439/// `pd.read_sql_table(table_name, con, parse_dates=..., coerce_float=...)`.
11440pub fn read_sql_table_with_options<C: SqlConnection>(
11441    conn: &C,
11442    table_name: &str,
11443    options: &SqlReadOptions,
11444) -> Result<DataFrame, IoError> {
11445    let query =
11446        sql_table_read_query_for_options(conn, table_name, options, options.index_col.as_deref())?;
11447    // Per br-frankenpandas-t1777: the query reader rejects options.columns
11448    // (the SELECT is already projected here). Clear before delegating so
11449    // the table reader stays the canonical honor-columns entrypoint
11450    // regardless of which slot the caller used.
11451    let cleared = SqlReadOptions {
11452        columns: None,
11453        ..options.clone()
11454    };
11455    read_sql_with_options(conn, &query, &cleared)
11456}
11457
11458fn sql_table_read_query_for_options<C: SqlConnection>(
11459    conn: &C,
11460    table_name: &str,
11461    options: &SqlReadOptions,
11462    required_projection_col: Option<&str>,
11463) -> Result<String, IoError> {
11464    // Per br-frankenpandas-d3e9 (fd90.34): when options.columns is
11465    // Some(list), project only those columns instead of SELECT *.
11466    // Per br-frankenpandas-fd90.76: if an index_col will be promoted
11467    // after materialization, include it in the generated projection even
11468    // when the user did not list it in columns. pandas SQLTable.read does
11469    // this before set_index so columns=[...] and index_col=... compose.
11470    match options.columns.as_deref() {
11471        Some(cols) => {
11472            let mut refs: Vec<&str> = Vec::with_capacity(cols.len() + 1);
11473            if let Some(index_col) = required_projection_col
11474                && !cols.iter().any(|name| name == index_col)
11475            {
11476                refs.push(index_col);
11477            }
11478            refs.extend(cols.iter().map(String::as_str));
11479            sql_select_columns_query_in_schema(conn, table_name, options.schema.as_deref(), &refs)
11480        }
11481        None => sql_select_all_query_in_schema(conn, table_name, options.schema.as_deref()),
11482    }
11483}
11484
11485/// Read an entire SQL table with read-time options and optional index promotion.
11486///
11487/// Matches the supported subset of
11488/// `pd.read_sql_table(table_name, con, parse_dates=..., coerce_float=..., index_col=...)`.
11489pub fn read_sql_table_with_options_and_index_col<C: SqlConnection>(
11490    conn: &C,
11491    table_name: &str,
11492    options: &SqlReadOptions,
11493    index_col: Option<&str>,
11494) -> Result<DataFrame, IoError> {
11495    // Per br-frankenpandas-c1h9 (fd90.36): explicit `index_col` arg
11496    // always wins over `options.index_col`. Avoid double-promotion by
11497    // clearing the option-struct copy when the explicit arg is set.
11498    if let Some(col_name) = index_col {
11499        // Build the SELECT projection from the ORIGINAL options (so
11500        // options.columns is honored when present). Per br-frankenpandas-t1777,
11501        // also strip options.columns before passing to the query reader
11502        // (which now rejects the field; the SELECT already projects the
11503        // columns we wanted).
11504        let query = sql_table_read_query_for_options(conn, table_name, options, Some(col_name))?;
11505        let cleared = SqlReadOptions {
11506            index_col: None,
11507            columns: None,
11508            ..options.clone()
11509        };
11510        let frame = read_sql_with_options(conn, &query, &cleared)?;
11511        return apply_sql_index_col(frame, Some(col_name));
11512    }
11513    read_sql_table_with_options(conn, table_name, options)
11514}
11515
11516/// Read an entire SQL table as an iterator of DataFrame chunks.
11517///
11518/// Matches the supported subset of `pd.read_sql_table(table_name, con, chunksize=...)`.
11519pub fn read_sql_table_chunks<'conn, C: SqlConnection + 'conn>(
11520    conn: &'conn C,
11521    table_name: &str,
11522    chunk_size: usize,
11523) -> Result<SqlChunkIterator<'conn>, IoError> {
11524    read_sql_chunks(conn, &sql_select_all_query(conn, table_name)?, chunk_size)
11525}
11526
11527/// Read an entire SQL table as DataFrame chunks with read-time options.
11528///
11529/// Matches the supported subset of
11530/// `pd.read_sql_table(table_name, con, parse_dates=..., coerce_float=..., chunksize=...)`.
11531pub fn read_sql_table_chunks_with_options<'conn, C: SqlConnection + 'conn>(
11532    conn: &'conn C,
11533    table_name: &str,
11534    options: &SqlReadOptions,
11535    chunk_size: usize,
11536) -> Result<SqlChunkIterator<'conn>, IoError> {
11537    // Per br-frankenpandas-i8kja: this entrypoint returns the
11538    // un-indexed SqlChunkIterator. Honoring options.index_col would
11539    // silently diverge from the full-frame read_sql_table_with_options
11540    // sibling (which does promote). Reject to surface the mismatch —
11541    // callers should use read_sql_table_chunks_with_options_and_index_col
11542    // when index_col is set.
11543    if options.index_col.is_some() {
11544        return Err(IoError::Sql(
11545            "options.index_col is set but this entrypoint returns SqlChunkIterator without \
11546             index promotion; use read_sql_table_chunks_with_options_and_index_col to honor \
11547             index_col"
11548                .to_owned(),
11549        ));
11550    }
11551    let query = match options.columns.as_deref() {
11552        Some(cols) => {
11553            let refs: Vec<&str> = cols.iter().map(String::as_str).collect();
11554            sql_select_columns_query_in_schema(conn, table_name, options.schema.as_deref(), &refs)?
11555        }
11556        None => sql_select_all_query_in_schema(conn, table_name, options.schema.as_deref())?,
11557    };
11558    // Per br-frankenpandas-t1777: query reader rejects options.columns
11559    // (the SELECT is already projected here). Clear before delegating.
11560    let cleared = SqlReadOptions {
11561        columns: None,
11562        ..options.clone()
11563    };
11564    read_sql_chunks_with_options(conn, &query, &cleared, chunk_size)
11565}
11566
11567/// Read an entire SQL table as chunks with read-time options and optional index promotion.
11568///
11569/// Matches the supported subset of
11570/// `pd.read_sql_table(table_name, con, parse_dates=..., coerce_float=..., index_col=..., chunksize=...)`.
11571pub fn read_sql_table_chunks_with_options_and_index_col<'conn, C: SqlConnection + 'conn>(
11572    conn: &'conn C,
11573    table_name: &str,
11574    options: &SqlReadOptions,
11575    index_col: Option<&str>,
11576    chunk_size: usize,
11577) -> Result<SqlIndexedChunkIterator<'conn>, IoError> {
11578    let effective_index_col = index_col.or(options.index_col.as_deref());
11579    let query = sql_table_read_query_for_options(conn, table_name, options, effective_index_col)?;
11580    // The plain chunk reader rejects options.index_col (see i8kja) and
11581    // options.columns (see t1777); clear both before delegating so
11582    // chunked-with-options remains a sibling of the full-frame path
11583    // regardless of which slots the caller populated.
11584    let cleared = SqlReadOptions {
11585        index_col: None,
11586        columns: None,
11587        ..options.clone()
11588    };
11589    let inner = read_sql_chunks_with_options(conn, &query, &cleared, chunk_size)?;
11590    sql_indexed_chunks(inner, effective_index_col)
11591}
11592
11593/// Read an entire SQL table as chunks with one column promoted to each chunk's index.
11594///
11595/// Matches the supported subset of
11596/// `pd.read_sql_table(table_name, con, index_col=..., chunksize=...)`.
11597pub fn read_sql_table_chunks_with_index_col<'conn, C: SqlConnection + 'conn>(
11598    conn: &'conn C,
11599    table_name: &str,
11600    index_col: Option<&str>,
11601    chunk_size: usize,
11602) -> Result<SqlIndexedChunkIterator<'conn>, IoError> {
11603    let inner = read_sql_table_chunks(conn, table_name, chunk_size)?;
11604    sql_indexed_chunks(inner, index_col)
11605}
11606
11607/// Read a subset of columns from a SQL table.
11608///
11609/// Matches `pd.read_sql_table(table, con, columns=[...])`. The named
11610/// columns are emitted in the requested order. Each column name must
11611/// satisfy the same alphanumeric+underscore rule as `table_name` to
11612/// keep the projection injection-safe; mismatched names return
11613/// `IoError::Sql`. Empty `columns` is rejected (pandas raises in
11614/// the same case rather than producing an empty SELECT).
11615pub fn read_sql_table_columns<C: SqlConnection>(
11616    conn: &C,
11617    table_name: &str,
11618    columns: &[&str],
11619) -> Result<DataFrame, IoError> {
11620    read_sql(conn, &sql_select_columns_query(conn, table_name, columns)?)
11621}
11622
11623/// Read a subset of columns from a SQL table with optional index promotion.
11624///
11625/// Matches the supported subset of
11626/// `pd.read_sql_table(table, con, columns=[...], index_col=...)`. When
11627/// `index_col` is set and is not already in `columns`, it is auto-projected
11628/// into the underlying SELECT (matching pandas SQLTable.read which does the
11629/// same before set_index). The promoted column is removed from the data
11630/// columns after projection. Per br-frankenpandas-6n0uz.
11631pub fn read_sql_table_columns_with_index_col<C: SqlConnection>(
11632    conn: &C,
11633    table_name: &str,
11634    columns: &[&str],
11635    index_col: Option<&str>,
11636) -> Result<DataFrame, IoError> {
11637    let projection = projection_with_index_col(columns, index_col)?;
11638    let frame = read_sql_table_columns(conn, table_name, &projection)?;
11639    apply_sql_index_col(frame, index_col)
11640}
11641
11642/// Read a subset of columns from a SQL table as DataFrame chunks.
11643///
11644/// Matches the supported subset of
11645/// `pd.read_sql_table(table, con, columns=[...], chunksize=...)`. The named
11646/// columns are emitted in the requested order and each chunk receives a fresh
11647/// zero-based RangeIndex.
11648pub fn read_sql_table_columns_chunks<'conn, C: SqlConnection + 'conn>(
11649    conn: &'conn C,
11650    table_name: &str,
11651    columns: &[&str],
11652    chunk_size: usize,
11653) -> Result<SqlChunkIterator<'conn>, IoError> {
11654    read_sql_chunks(
11655        conn,
11656        &sql_select_columns_query(conn, table_name, columns)?,
11657        chunk_size,
11658    )
11659}
11660
11661/// Read a subset of columns from a SQL table as chunks with optional index promotion.
11662///
11663/// Matches the supported subset of
11664/// `pd.read_sql_table(table, con, columns=[...], index_col=..., chunksize=...)`.
11665/// When `index_col` is set and is not already in `columns`, it is auto-projected
11666/// into the underlying SELECT (matching pandas SQLTable.read). The promoted
11667/// column is removed from each chunk after projection. Per br-frankenpandas-6n0uz.
11668pub fn read_sql_table_columns_chunks_with_index_col<'conn, C: SqlConnection + 'conn>(
11669    conn: &'conn C,
11670    table_name: &str,
11671    columns: &[&str],
11672    index_col: Option<&str>,
11673    chunk_size: usize,
11674) -> Result<SqlIndexedChunkIterator<'conn>, IoError> {
11675    let projection = projection_with_index_col(columns, index_col)?;
11676    let inner = read_sql_table_columns_chunks(conn, table_name, &projection, chunk_size)?;
11677    sql_indexed_chunks(inner, index_col)
11678}
11679
11680/// Per br-frankenpandas-6n0uz: helper that prepends `index_col` to a
11681/// `columns` projection list if it isn't already present. Mirrors the
11682/// inline logic in `sql_table_read_query_for_options` (fd90.76) so the
11683/// columns-list and options-based read paths agree on the auto-include
11684/// rule while preserving the public `index_col=""` and empty-projection
11685/// error contracts.
11686fn projection_with_index_col<'a>(
11687    columns: &'a [&'a str],
11688    index_col: Option<&'a str>,
11689) -> Result<Vec<&'a str>, IoError> {
11690    match index_col {
11691        Some("") => Err(IoError::Sql(
11692            "index_col: empty string is not a valid column name".to_owned(),
11693        )),
11694        Some(name) if !columns.is_empty() && !columns.contains(&name) => {
11695            let mut out = Vec::with_capacity(columns.len() + 1);
11696            out.push(name);
11697            out.extend_from_slice(columns);
11698            Ok(out)
11699        }
11700        _ => Ok(columns.to_vec()),
11701    }
11702}
11703
11704/// Write a DataFrame to a SQL table.
11705///
11706/// Matches `pd.DataFrame.to_sql(name, con)`.
11707pub fn write_sql<C: SqlConnection>(
11708    frame: &DataFrame,
11709    conn: &C,
11710    table_name: &str,
11711    if_exists: SqlIfExists,
11712) -> Result<(), IoError> {
11713    write_sql_with_options(
11714        frame,
11715        conn,
11716        table_name,
11717        &SqlWriteOptions {
11718            if_exists,
11719            index: false,
11720            index_label: None,
11721            schema: None,
11722            dtype: None,
11723            method: SqlInsertMethod::Single,
11724            chunksize: None,
11725        },
11726    )
11727}
11728
11729/// Write a DataFrame to a SQLite table with pandas-style index options.
11730///
11731/// Matches the supported subset of
11732/// `pd.DataFrame.to_sql(name, con, index=..., index_label=...)`.
11733pub fn write_sql_with_options<C: SqlConnection>(
11734    frame: &DataFrame,
11735    conn: &C,
11736    table_name: &str,
11737    options: &SqlWriteOptions,
11738) -> Result<(), IoError> {
11739    // Validate table name to prevent SQL injection (only allow alphanumeric + underscore, non-empty).
11740    if table_name.is_empty() || !table_name.chars().all(|c| c.is_alphanumeric() || c == '_') {
11741        return Err(IoError::Sql(format!(
11742            "invalid table name: '{table_name}' (must be non-empty, only alphanumeric and underscore allowed)"
11743        )));
11744    }
11745
11746    let col_names: Vec<String> = frame.column_names().into_iter().cloned().collect();
11747    let index_label = resolve_sql_index_label(frame, options)?;
11748    let mut sql_col_names =
11749        Vec::with_capacity(col_names.len() + usize::from(index_label.is_some()));
11750    if let Some(ref label) = index_label {
11751        sql_col_names.push(label.clone());
11752    }
11753    sql_col_names.extend(col_names.iter().cloned());
11754
11755    // Per fd90.27: when the backend reports an identifier-length cap
11756    // (PG=63, MySQL=64, MSSQL=128), reject any identifier that exceeds
11757    // it before emitting DDL. SQLite (None) is unaffected.
11758    let max_ident = conn.max_identifier_length();
11759    validate_sql_identifier_length(table_name, max_ident, "table")?;
11760    if let Some(ref label) = index_label {
11761        validate_sql_identifier_length(label, max_ident, "index label")?;
11762    }
11763    for name in &col_names {
11764        validate_sql_identifier_length(name, max_ident, "column")?;
11765    }
11766    if let Some(s) = options.schema.as_deref() {
11767        validate_sql_identifier_length(s, max_ident, "schema")?;
11768    }
11769
11770    // Handle if_exists policy.
11771    let schema = options.schema.as_deref();
11772    match options.if_exists {
11773        SqlIfExists::Fail => {
11774            let exists = conn.table_exists_in_schema(table_name, schema)?;
11775            if exists {
11776                return Err(IoError::Sql(format!("table '{table_name}' already exists")));
11777            }
11778        }
11779        SqlIfExists::Replace => {
11780            let drop_sql = sql_drop_table_query_in_schema(conn, table_name, schema)?;
11781            conn.execute_batch(&drop_sql)?;
11782        }
11783        SqlIfExists::Append => {
11784            // Table may or may not exist; CREATE TABLE IF NOT EXISTS handles both.
11785        }
11786    }
11787
11788    // Build CREATE TABLE statement.
11789    let mut col_defs = Vec::with_capacity(sql_col_names.len());
11790    if let Some(ref label) = index_label {
11791        col_defs.push(sql_column_definition(
11792            conn,
11793            label,
11794            conn.index_dtype_sql(frame.index()),
11795        )?);
11796    }
11797    let dtype_overrides = options.dtype.as_ref();
11798    col_defs.extend(
11799        col_names
11800            .iter()
11801            .map(|name| {
11802                // Per br-frankenpandas-ev2s (fd90.18): explicit per-column
11803                // SQL-type override wins over the inferred conn.dtype_sql.
11804                let override_sql = dtype_overrides
11805                    .and_then(|m| m.get(name))
11806                    .map(|s| s.as_str());
11807                let sql_type = match override_sql {
11808                    Some(s) => s,
11809                    None => {
11810                        let dt = frame.column(name).map_or(DType::Utf8, |c| c.dtype());
11811                        conn.dtype_sql(dt)
11812                    }
11813                };
11814                sql_column_definition(conn, name, sql_type)
11815            })
11816            .collect::<Result<Vec<_>, IoError>>()?,
11817    );
11818
11819    let create_sql = sql_create_table_query_in_schema(conn, table_name, schema, &col_defs)?;
11820    conn.execute_batch(&create_sql)?;
11821
11822    let nrows = frame.index().len();
11823    let ncols = sql_col_names.len();
11824    let mut rows = Vec::with_capacity(nrows);
11825    for row_idx in 0..nrows {
11826        let mut row = Vec::with_capacity(ncols);
11827        if options.index {
11828            row.push(scalar_from_index_label(&frame.index().labels()[row_idx]));
11829        }
11830        row.extend(col_names.iter().map(|name| {
11831            frame
11832                .column(name)
11833                .and_then(|col| col.value(row_idx))
11834                .cloned()
11835                .unwrap_or(Scalar::Null(NullKind::Null))
11836        }));
11837        rows.push(row);
11838    }
11839
11840    if rows.is_empty() {
11841        // Empty frame: still emit CREATE TABLE (already done) but skip INSERT.
11842        return Ok(());
11843    }
11844
11845    // Per fd90.33: pandas-style chunksize. None preserves prior
11846    // single-transaction semantics; Some(0) is rejected (matches pandas).
11847    if let Some(0) = options.chunksize {
11848        return Err(IoError::Sql(
11849            "invalid chunksize: 0 (must be > 0 if Some)".to_owned(),
11850        ));
11851    }
11852
11853    match options.method {
11854        SqlInsertMethod::Single => {
11855            let insert_sql =
11856                sql_insert_rows_query_in_schema(conn, table_name, schema, &sql_col_names)?;
11857            match options.chunksize {
11858                None => {
11859                    conn.insert_rows(&insert_sql, &rows)?;
11860                }
11861                Some(n) => {
11862                    for chunk in rows.chunks(n) {
11863                        conn.insert_rows(&insert_sql, chunk)?;
11864                    }
11865                }
11866            }
11867        }
11868        SqlInsertMethod::Multi => {
11869            // Per fd90.19: chunk rows to fit `max_param_count`. When the
11870            // backend reports None, send the whole frame in one statement.
11871            // Per fd90.33: when chunksize is also Some(n), the effective
11872            // chunk row count is min(n, max_param_count / num_cols).
11873            let param_chunk = match conn.max_param_count() {
11874                Some(max) if ncols > 0 => {
11875                    let per_chunk = max / ncols;
11876                    if per_chunk == 0 {
11877                        return Err(IoError::Sql(format!(
11878                            "multi-row insert: ncols={ncols} exceeds backend max_param_count={max}"
11879                        )));
11880                    }
11881                    per_chunk
11882                }
11883                _ => rows.len(),
11884            };
11885            let chunk_rows = options
11886                .chunksize
11887                .map(|cs| cs.min(param_chunk))
11888                .unwrap_or(param_chunk);
11889            for chunk in rows.chunks(chunk_rows) {
11890                let chunk_sql = sql_multi_row_insert_query_in_schema(
11891                    conn,
11892                    table_name,
11893                    schema,
11894                    &sql_col_names,
11895                    chunk.len(),
11896                )?;
11897                let mut flat = Vec::with_capacity(chunk.len() * ncols);
11898                for row in chunk {
11899                    flat.extend(row.iter().cloned());
11900                }
11901                conn.insert_rows(&chunk_sql, &[flat])?;
11902            }
11903        }
11904    }
11905
11906    Ok(())
11907}
11908
11909// ── Extension trait for DataFrame IO convenience methods ─────────────
11910
11911/// Extension trait that adds IO convenience methods to `DataFrame`.
11912///
11913/// Import this trait to call `df.to_parquet(path)`, `df.to_orc(path)`,
11914/// `df.to_hdf(path)`, `df.to_parquet_bytes()`, etc. directly on DataFrame
11915/// values.
11916pub trait DataFrameIoExt {
11917    /// Write this DataFrame to a Parquet file.
11918    ///
11919    /// Matches `pd.DataFrame.to_parquet(path)`.
11920    fn to_parquet(&self, path: &Path) -> Result<(), IoError>;
11921
11922    /// Serialize this DataFrame to Parquet bytes in memory.
11923    ///
11924    /// Matches `pd.DataFrame.to_parquet()` with no path (returns bytes).
11925    fn to_parquet_bytes(&self) -> Result<Vec<u8>, IoError>;
11926
11927    /// Write this DataFrame to an ORC file.
11928    ///
11929    /// Matches the scoped `DataFrame.to_orc(path)` compatibility surface.
11930    fn to_orc(&self, path: &Path) -> Result<(), IoError>;
11931
11932    /// Write this DataFrame to an ORC file.
11933    ///
11934    /// Explicit file-suffixed form of [`DataFrameIoExt::to_orc`].
11935    fn to_orc_file(&self, path: &Path) -> Result<(), IoError>;
11936
11937    /// Serialize this DataFrame to ORC bytes in memory.
11938    fn to_orc_bytes(&self) -> Result<Vec<u8>, IoError>;
11939
11940    /// Write this DataFrame to an HDF5 file at the default key.
11941    ///
11942    /// Matches the scoped `DataFrame.to_hdf(path)` compatibility surface.
11943    fn to_hdf(&self, path: &Path) -> Result<(), IoError>;
11944
11945    /// Write this DataFrame to an HDF5 file at the default key.
11946    ///
11947    /// Explicit file-suffixed form of [`DataFrameIoExt::to_hdf`].
11948    fn to_hdf_file(&self, path: &Path) -> Result<(), IoError>;
11949
11950    /// Write this DataFrame to an HDF5 file at an explicit key.
11951    fn to_hdf_key(&self, path: &Path, key: &str) -> Result<(), IoError>;
11952
11953    /// Write this DataFrame to an HDF5 file with explicit options.
11954    fn to_hdf_with_options(&self, path: &Path, options: &HdfWriteOptions) -> Result<(), IoError>;
11955
11956    /// Write this DataFrame to a CSV file.
11957    ///
11958    /// Matches `pd.DataFrame.to_csv(path)`.
11959    fn to_csv_file(&self, path: &Path) -> Result<(), IoError>;
11960
11961    /// Serialize this DataFrame to a CSV string.
11962    ///
11963    /// Matches `pd.DataFrame.to_csv()` with no path.
11964    fn to_csv_string(&self) -> Result<String, IoError>;
11965
11966    /// Serialize this DataFrame to a CSV string with explicit write options.
11967    ///
11968    /// Matches `pd.DataFrame.to_csv(sep, na_rep, header, index, index_label)`.
11969    fn to_csv_string_with_options(&self, options: &CsvWriteOptions) -> Result<String, IoError>;
11970
11971    /// Serialize this DataFrame to a Markdown table string.
11972    ///
11973    /// Matches `pd.DataFrame.to_markdown()` with no buffer.
11974    fn to_markdown_string(&self) -> Result<String, IoError>;
11975
11976    /// Serialize this DataFrame to a Markdown table string with explicit options.
11977    fn to_markdown_string_with_options(
11978        &self,
11979        options: &MarkdownWriteOptions,
11980    ) -> Result<String, IoError>;
11981
11982    /// Write this DataFrame to a Markdown table file.
11983    ///
11984    /// Uses a file-suffixed name to avoid colliding with
11985    /// `DataFrame::to_markdown(include_index, tablefmt)`.
11986    fn to_markdown_file(&self, path: &Path) -> Result<(), IoError>;
11987
11988    /// Write this DataFrame to a Markdown table file with explicit options.
11989    fn to_markdown_file_with_options(
11990        &self,
11991        path: &Path,
11992        options: &MarkdownWriteOptions,
11993    ) -> Result<(), IoError>;
11994
11995    /// Serialize this DataFrame to a LaTeX tabular string.
11996    ///
11997    /// Matches `pd.DataFrame.to_latex()` with no buffer.
11998    fn to_latex_string(&self) -> Result<String, IoError>;
11999
12000    /// Serialize this DataFrame to a LaTeX tabular string with explicit options.
12001    fn to_latex_string_with_options(&self, options: &LatexWriteOptions) -> Result<String, IoError>;
12002
12003    /// Write this DataFrame to a LaTeX tabular file.
12004    ///
12005    /// Uses a file-suffixed name to avoid colliding with
12006    /// `DataFrame::to_latex(include_index)`.
12007    fn to_latex_file(&self, path: &Path) -> Result<(), IoError>;
12008
12009    /// Write this DataFrame to a LaTeX tabular file with explicit options.
12010    fn to_latex_file_with_options(
12011        &self,
12012        path: &Path,
12013        options: &LatexWriteOptions,
12014    ) -> Result<(), IoError>;
12015
12016    /// Serialize this DataFrame to an HTML table string.
12017    ///
12018    /// Matches `pd.DataFrame.to_html()` with no buffer.
12019    fn to_html_string(&self) -> Result<String, IoError>;
12020
12021    /// Serialize this DataFrame to an HTML table string with explicit options.
12022    fn to_html_string_with_options(&self, options: &HtmlWriteOptions) -> Result<String, IoError>;
12023
12024    /// Write this DataFrame to an HTML file.
12025    ///
12026    /// Matches `pd.DataFrame.to_html(path)`.
12027    fn to_html_file(&self, path: &Path) -> Result<(), IoError>;
12028
12029    /// Write this DataFrame to an HTML file with explicit options.
12030    fn to_html_file_with_options(
12031        &self,
12032        path: &Path,
12033        options: &HtmlWriteOptions,
12034    ) -> Result<(), IoError>;
12035
12036    /// Serialize this DataFrame to an XML document string.
12037    ///
12038    /// Matches `pd.DataFrame.to_xml()` with no buffer for the writer-only subset.
12039    fn to_xml_string(&self) -> Result<String, IoError>;
12040
12041    /// Serialize this DataFrame to an XML document string with explicit options.
12042    fn to_xml_string_with_options(&self, options: &XmlWriteOptions) -> Result<String, IoError>;
12043
12044    /// Write this DataFrame to an XML file.
12045    ///
12046    /// Matches `pd.DataFrame.to_xml(path)`.
12047    fn to_xml(&self, path: &Path) -> Result<(), IoError>;
12048
12049    /// Write this DataFrame to an XML file.
12050    ///
12051    /// Matches `pd.DataFrame.to_xml(path)`.
12052    fn to_xml_file(&self, path: &Path) -> Result<(), IoError>;
12053
12054    /// Write this DataFrame to an XML file with explicit options.
12055    fn to_xml_file_with_options(
12056        &self,
12057        path: &Path,
12058        options: &XmlWriteOptions,
12059    ) -> Result<(), IoError>;
12060
12061    /// Write this DataFrame to a JSON file.
12062    ///
12063    /// Matches `pd.DataFrame.to_json(path)`.
12064    fn to_json_file(&self, path: &Path, orient: JsonOrient) -> Result<(), IoError>;
12065
12066    /// Serialize this DataFrame to a JSON string.
12067    ///
12068    /// Matches `pd.DataFrame.to_json()` with no path.
12069    fn to_json_string(&self, orient: JsonOrient) -> Result<String, IoError>;
12070
12071    /// Write this DataFrame to a Pickle file.
12072    ///
12073    /// Matches `pd.DataFrame.to_pickle(path)` for the supported envelope.
12074    fn to_pickle(&self, path: &Path) -> Result<(), IoError>;
12075
12076    /// Write this DataFrame to a Pickle file.
12077    ///
12078    /// Explicit file-suffixed form of [`DataFrameIoExt::to_pickle`].
12079    fn to_pickle_file(&self, path: &Path) -> Result<(), IoError>;
12080
12081    /// Write this DataFrame to a Pickle file with explicit options.
12082    fn to_pickle_with_options(
12083        &self,
12084        path: &Path,
12085        options: &PickleWriteOptions,
12086    ) -> Result<(), IoError>;
12087
12088    /// Serialize this DataFrame to Pickle bytes.
12089    fn to_pickle_bytes(&self) -> Result<Vec<u8>, IoError>;
12090
12091    /// Serialize this DataFrame to Pickle bytes with explicit options.
12092    fn to_pickle_bytes_with_options(
12093        &self,
12094        options: &PickleWriteOptions,
12095    ) -> Result<Vec<u8>, IoError>;
12096
12097    /// Write this DataFrame to a Stata DTA file.
12098    ///
12099    /// Matches `pd.DataFrame.to_stata(path)` for the supported subset.
12100    fn to_stata(&self, path: &Path) -> Result<(), IoError>;
12101
12102    /// Write this DataFrame to a Stata DTA file.
12103    ///
12104    /// Explicit file-suffixed form of [`DataFrameIoExt::to_stata`].
12105    fn to_stata_file(&self, path: &Path) -> Result<(), IoError>;
12106
12107    /// Write this DataFrame to a Stata DTA file with explicit options.
12108    fn to_stata_with_options(
12109        &self,
12110        path: &Path,
12111        options: &StataWriteOptions,
12112    ) -> Result<(), IoError>;
12113
12114    /// Serialize this DataFrame to Stata DTA bytes.
12115    fn to_stata_bytes(&self) -> Result<Vec<u8>, IoError>;
12116
12117    /// Serialize this DataFrame to Stata DTA bytes with explicit options.
12118    fn to_stata_bytes_with_options(&self, options: &StataWriteOptions) -> Result<Vec<u8>, IoError>;
12119
12120    /// Write this DataFrame to an Excel (.xlsx) file.
12121    ///
12122    /// Matches `pd.DataFrame.to_excel(path)`.
12123    fn to_excel(&self, path: &Path) -> Result<(), IoError>;
12124
12125    /// Write this DataFrame to an Excel (.xlsx) file.
12126    ///
12127    /// Explicit file-suffixed form of [`DataFrameIoExt::to_excel`].
12128    fn to_excel_file(&self, path: &Path) -> Result<(), IoError>;
12129
12130    /// Write this DataFrame to an Excel (.xlsx) file with explicit write options.
12131    fn to_excel_with_options(
12132        &self,
12133        path: &Path,
12134        options: &ExcelWriteOptions,
12135    ) -> Result<(), IoError>;
12136
12137    /// Serialize this DataFrame to Excel (.xlsx) bytes in memory.
12138    fn to_excel_bytes(&self) -> Result<Vec<u8>, IoError>;
12139
12140    /// Serialize this DataFrame to Excel (.xlsx) bytes with explicit write options.
12141    fn to_excel_bytes_with_options(&self, options: &ExcelWriteOptions) -> Result<Vec<u8>, IoError>;
12142
12143    /// Write this DataFrame to a JSONL file (one JSON object per line).
12144    ///
12145    /// Matches `pd.DataFrame.to_json(path, orient='records', lines=True)`.
12146    fn to_jsonl_file(&self, path: &Path) -> Result<(), IoError>;
12147
12148    /// Serialize this DataFrame to newline-delimited JSON.
12149    ///
12150    /// Matches `pd.DataFrame.to_json(orient='records', lines=True)`.
12151    fn to_jsonl_string(&self) -> Result<String, IoError>;
12152
12153    /// Write this DataFrame to an Arrow IPC (Feather v2) file.
12154    ///
12155    /// Matches `pd.DataFrame.to_feather(path)`.
12156    fn to_feather(&self, path: &Path) -> Result<(), IoError>;
12157
12158    /// Write this DataFrame to an Arrow IPC (Feather v2) file.
12159    ///
12160    /// Explicit file-suffixed form of [`DataFrameIoExt::to_feather`].
12161    fn to_feather_file(&self, path: &Path) -> Result<(), IoError>;
12162
12163    /// Serialize this DataFrame to Arrow IPC (Feather v2) bytes.
12164    fn to_feather_bytes(&self) -> Result<Vec<u8>, IoError>;
12165
12166    /// Write this DataFrame to a SQL table.
12167    ///
12168    /// Matches `pd.DataFrame.to_sql(name, con)`.
12169    fn to_sql<C: SqlConnection>(
12170        &self,
12171        conn: &C,
12172        table_name: &str,
12173        if_exists: SqlIfExists,
12174    ) -> Result<(), IoError>;
12175
12176    /// Write this DataFrame to a SQL table with pandas-style SQL write options.
12177    fn to_sql_with_options<C: SqlConnection>(
12178        &self,
12179        conn: &C,
12180        table_name: &str,
12181        options: &SqlWriteOptions,
12182    ) -> Result<(), IoError>;
12183
12184    /// Clipboard writer (TSV via an OS backend), matching `pd.DataFrame.to_clipboard()`.
12185    fn to_clipboard(&self) -> Result<(), IoError>;
12186
12187    /// Reject-closed BigQuery writer, matching `pd.DataFrame.to_gbq(destination_table, project_id)`.
12188    fn to_gbq(&self, destination_table: &str, project_id: Option<&str>) -> Result<(), IoError>;
12189}
12190
12191impl DataFrameIoExt for DataFrame {
12192    fn to_parquet(&self, path: &Path) -> Result<(), IoError> {
12193        write_parquet(self, path)
12194    }
12195
12196    fn to_parquet_bytes(&self) -> Result<Vec<u8>, IoError> {
12197        write_parquet_bytes(self)
12198    }
12199
12200    fn to_orc(&self, path: &Path) -> Result<(), IoError> {
12201        write_orc(self, path)
12202    }
12203
12204    fn to_orc_file(&self, path: &Path) -> Result<(), IoError> {
12205        self.to_orc(path)
12206    }
12207
12208    fn to_orc_bytes(&self) -> Result<Vec<u8>, IoError> {
12209        write_orc_bytes(self)
12210    }
12211
12212    fn to_hdf(&self, path: &Path) -> Result<(), IoError> {
12213        write_hdf(self, path)
12214    }
12215
12216    fn to_hdf_file(&self, path: &Path) -> Result<(), IoError> {
12217        self.to_hdf(path)
12218    }
12219
12220    fn to_hdf_key(&self, path: &Path, key: &str) -> Result<(), IoError> {
12221        write_hdf_key(self, path, key)
12222    }
12223
12224    fn to_hdf_with_options(&self, path: &Path, options: &HdfWriteOptions) -> Result<(), IoError> {
12225        write_hdf_with_options(self, path, options)
12226    }
12227
12228    fn to_csv_file(&self, path: &Path) -> Result<(), IoError> {
12229        write_csv(self, path)
12230    }
12231
12232    fn to_csv_string(&self) -> Result<String, IoError> {
12233        write_csv_string(self)
12234    }
12235
12236    fn to_csv_string_with_options(&self, options: &CsvWriteOptions) -> Result<String, IoError> {
12237        write_csv_string_with_options(self, options)
12238    }
12239
12240    fn to_markdown_string(&self) -> Result<String, IoError> {
12241        write_markdown_string(self)
12242    }
12243
12244    fn to_markdown_string_with_options(
12245        &self,
12246        options: &MarkdownWriteOptions,
12247    ) -> Result<String, IoError> {
12248        write_markdown_string_with_options(self, options)
12249    }
12250
12251    fn to_markdown_file(&self, path: &Path) -> Result<(), IoError> {
12252        write_markdown(self, path)
12253    }
12254
12255    fn to_markdown_file_with_options(
12256        &self,
12257        path: &Path,
12258        options: &MarkdownWriteOptions,
12259    ) -> Result<(), IoError> {
12260        write_markdown_with_options(self, path, options)
12261    }
12262
12263    fn to_latex_string(&self) -> Result<String, IoError> {
12264        write_latex_string(self)
12265    }
12266
12267    fn to_latex_string_with_options(&self, options: &LatexWriteOptions) -> Result<String, IoError> {
12268        write_latex_string_with_options(self, options)
12269    }
12270
12271    fn to_latex_file(&self, path: &Path) -> Result<(), IoError> {
12272        write_latex(self, path)
12273    }
12274
12275    fn to_latex_file_with_options(
12276        &self,
12277        path: &Path,
12278        options: &LatexWriteOptions,
12279    ) -> Result<(), IoError> {
12280        write_latex_with_options(self, path, options)
12281    }
12282
12283    fn to_html_string(&self) -> Result<String, IoError> {
12284        write_html_string(self)
12285    }
12286
12287    fn to_html_string_with_options(&self, options: &HtmlWriteOptions) -> Result<String, IoError> {
12288        write_html_string_with_options(self, options)
12289    }
12290
12291    fn to_html_file(&self, path: &Path) -> Result<(), IoError> {
12292        write_html(self, path)
12293    }
12294
12295    fn to_html_file_with_options(
12296        &self,
12297        path: &Path,
12298        options: &HtmlWriteOptions,
12299    ) -> Result<(), IoError> {
12300        write_html_with_options(self, path, options)
12301    }
12302
12303    fn to_xml_string(&self) -> Result<String, IoError> {
12304        write_xml_string(self)
12305    }
12306
12307    fn to_xml_string_with_options(&self, options: &XmlWriteOptions) -> Result<String, IoError> {
12308        write_xml_string_with_options(self, options)
12309    }
12310
12311    fn to_xml(&self, path: &Path) -> Result<(), IoError> {
12312        write_xml(self, path)
12313    }
12314
12315    fn to_xml_file(&self, path: &Path) -> Result<(), IoError> {
12316        self.to_xml(path)
12317    }
12318
12319    fn to_xml_file_with_options(
12320        &self,
12321        path: &Path,
12322        options: &XmlWriteOptions,
12323    ) -> Result<(), IoError> {
12324        write_xml_with_options(self, path, options)
12325    }
12326
12327    fn to_json_file(&self, path: &Path, orient: JsonOrient) -> Result<(), IoError> {
12328        write_json(self, path, orient)
12329    }
12330
12331    fn to_json_string(&self, orient: JsonOrient) -> Result<String, IoError> {
12332        write_json_string(self, orient)
12333    }
12334
12335    fn to_pickle(&self, path: &Path) -> Result<(), IoError> {
12336        write_pickle(self, path)
12337    }
12338
12339    fn to_pickle_file(&self, path: &Path) -> Result<(), IoError> {
12340        self.to_pickle(path)
12341    }
12342
12343    fn to_pickle_with_options(
12344        &self,
12345        path: &Path,
12346        options: &PickleWriteOptions,
12347    ) -> Result<(), IoError> {
12348        write_pickle_with_options(self, path, options)
12349    }
12350
12351    fn to_pickle_bytes(&self) -> Result<Vec<u8>, IoError> {
12352        write_pickle_bytes(self)
12353    }
12354
12355    fn to_pickle_bytes_with_options(
12356        &self,
12357        options: &PickleWriteOptions,
12358    ) -> Result<Vec<u8>, IoError> {
12359        write_pickle_bytes_with_options(self, options)
12360    }
12361
12362    fn to_stata(&self, path: &Path) -> Result<(), IoError> {
12363        write_stata(self, path)
12364    }
12365
12366    fn to_stata_file(&self, path: &Path) -> Result<(), IoError> {
12367        self.to_stata(path)
12368    }
12369
12370    fn to_stata_with_options(
12371        &self,
12372        path: &Path,
12373        options: &StataWriteOptions,
12374    ) -> Result<(), IoError> {
12375        write_stata_with_options(self, path, options)
12376    }
12377
12378    fn to_stata_bytes(&self) -> Result<Vec<u8>, IoError> {
12379        write_stata_bytes(self)
12380    }
12381
12382    fn to_stata_bytes_with_options(&self, options: &StataWriteOptions) -> Result<Vec<u8>, IoError> {
12383        write_stata_bytes_with_options(self, options)
12384    }
12385
12386    fn to_excel(&self, path: &Path) -> Result<(), IoError> {
12387        write_excel(self, path)
12388    }
12389
12390    fn to_excel_file(&self, path: &Path) -> Result<(), IoError> {
12391        self.to_excel(path)
12392    }
12393
12394    fn to_excel_with_options(
12395        &self,
12396        path: &Path,
12397        options: &ExcelWriteOptions,
12398    ) -> Result<(), IoError> {
12399        write_excel_with_options(self, path, options)
12400    }
12401
12402    fn to_excel_bytes(&self) -> Result<Vec<u8>, IoError> {
12403        write_excel_bytes(self)
12404    }
12405
12406    fn to_excel_bytes_with_options(&self, options: &ExcelWriteOptions) -> Result<Vec<u8>, IoError> {
12407        write_excel_bytes_with_options(self, options)
12408    }
12409
12410    fn to_jsonl_file(&self, path: &Path) -> Result<(), IoError> {
12411        write_jsonl(self, path)
12412    }
12413
12414    fn to_jsonl_string(&self) -> Result<String, IoError> {
12415        write_jsonl_string(self)
12416    }
12417
12418    fn to_feather(&self, path: &Path) -> Result<(), IoError> {
12419        write_feather(self, path)
12420    }
12421
12422    fn to_feather_file(&self, path: &Path) -> Result<(), IoError> {
12423        self.to_feather(path)
12424    }
12425
12426    fn to_feather_bytes(&self) -> Result<Vec<u8>, IoError> {
12427        write_feather_bytes(self)
12428    }
12429
12430    fn to_sql<C: SqlConnection>(
12431        &self,
12432        conn: &C,
12433        table_name: &str,
12434        if_exists: SqlIfExists,
12435    ) -> Result<(), IoError> {
12436        write_sql(self, conn, table_name, if_exists)
12437    }
12438
12439    fn to_sql_with_options<C: SqlConnection>(
12440        &self,
12441        conn: &C,
12442        table_name: &str,
12443        options: &SqlWriteOptions,
12444    ) -> Result<(), IoError> {
12445        write_sql_with_options(self, conn, table_name, options)
12446    }
12447
12448    fn to_clipboard(&self) -> Result<(), IoError> {
12449        clipboard_set(&clipboard_tsv(self)?)
12450    }
12451
12452    fn to_gbq(&self, _destination_table: &str, _project_id: Option<&str>) -> Result<(), IoError> {
12453        let _ = self;
12454        Err(deferred_writer_error(
12455            "to_gbq",
12456            "Google BigQuery integration is outside FrankenPandas's local file-format scope",
12457        ))
12458    }
12459}
12460
12461// ── Extension trait for Series IO convenience methods ─────────────────
12462
12463/// Extension trait that adds IO convenience methods to `Series`.
12464///
12465/// Import this trait to call `series.to_pickle(path)`,
12466/// `series.to_pickle_bytes()`, `series.to_hdf(path)`,
12467/// `series.to_csv_string()`, `series.to_markdown_string()`,
12468/// `series.to_latex_string()`, `series.to_json_string("records")`,
12469/// `series.to_hdf(path)`, `series.to_excel(path)`,
12470/// `series.to_sql(conn, table, if_exists)`, or `series.to_clipboard()`
12471/// directly on Series values.
12472pub trait SeriesIoExt {
12473    /// Write this Series to a Pickle file.
12474    ///
12475    /// Matches `pd.Series.to_pickle(path)` for the supported
12476    /// FrankenPandas pickle envelope.
12477    fn to_pickle(&self, path: &Path) -> Result<(), IoError>;
12478
12479    /// Write this Series to a Pickle file.
12480    ///
12481    /// Explicit file-suffixed form of [`SeriesIoExt::to_pickle`].
12482    fn to_pickle_file(&self, path: &Path) -> Result<(), IoError>;
12483
12484    /// Write this Series to a Pickle file with explicit options.
12485    fn to_pickle_with_options(
12486        &self,
12487        path: &Path,
12488        options: &PickleWriteOptions,
12489    ) -> Result<(), IoError>;
12490
12491    /// Serialize this Series to Pickle bytes.
12492    fn to_pickle_bytes(&self) -> Result<Vec<u8>, IoError>;
12493
12494    /// Serialize this Series to Pickle bytes with explicit options.
12495    fn to_pickle_bytes_with_options(
12496        &self,
12497        options: &PickleWriteOptions,
12498    ) -> Result<Vec<u8>, IoError>;
12499
12500    /// Write this Series to a CSV file.
12501    ///
12502    /// Matches `pd.Series.to_csv(path)` for the supported CSV writer surface,
12503    /// including pandas' default index materialization.
12504    fn to_csv_file(&self, path: &Path) -> Result<(), IoError>;
12505
12506    /// Write this Series to a CSV file with explicit write options.
12507    fn to_csv_file_with_options(
12508        &self,
12509        path: &Path,
12510        options: &CsvWriteOptions,
12511    ) -> Result<(), IoError>;
12512
12513    /// Serialize this Series to a CSV string.
12514    ///
12515    /// Matches `pd.Series.to_csv()` with no path for the supported writer
12516    /// surface.
12517    fn to_csv_string(&self) -> Result<String, IoError>;
12518
12519    /// Serialize this Series to a CSV string with explicit write options.
12520    fn to_csv_string_with_options(&self, options: &CsvWriteOptions) -> Result<String, IoError>;
12521
12522    /// Serialize this Series to a Markdown table string.
12523    ///
12524    /// Matches `pd.Series.to_markdown()` with no buffer for the supported
12525    /// table formatter surface.
12526    fn to_markdown_string(&self) -> Result<String, IoError>;
12527
12528    /// Serialize this Series to a Markdown table string with explicit options.
12529    fn to_markdown_string_with_options(
12530        &self,
12531        options: &MarkdownWriteOptions,
12532    ) -> Result<String, IoError>;
12533
12534    /// Write this Series to a Markdown table file.
12535    ///
12536    /// Uses a file-suffixed name to avoid colliding with
12537    /// `Series::to_markdown(include_index, tablefmt)`.
12538    fn to_markdown_file(&self, path: &Path) -> Result<(), IoError>;
12539
12540    /// Write this Series to a Markdown table file with explicit options.
12541    fn to_markdown_file_with_options(
12542        &self,
12543        path: &Path,
12544        options: &MarkdownWriteOptions,
12545    ) -> Result<(), IoError>;
12546
12547    /// Serialize this Series to a LaTeX tabular string.
12548    ///
12549    /// Matches `pd.Series.to_latex()` with no buffer for the supported table
12550    /// formatter surface.
12551    fn to_latex_string(&self) -> Result<String, IoError>;
12552
12553    /// Serialize this Series to a LaTeX tabular string with explicit options.
12554    fn to_latex_string_with_options(&self, options: &LatexWriteOptions) -> Result<String, IoError>;
12555
12556    /// Write this Series to a LaTeX tabular file.
12557    ///
12558    /// Uses a file-suffixed name to avoid colliding with
12559    /// `Series::to_latex(include_index)`.
12560    fn to_latex_file(&self, path: &Path) -> Result<(), IoError>;
12561
12562    /// Write this Series to a LaTeX tabular file with explicit options.
12563    fn to_latex_file_with_options(
12564        &self,
12565        path: &Path,
12566        options: &LatexWriteOptions,
12567    ) -> Result<(), IoError>;
12568
12569    /// Write this Series to a JSON file.
12570    ///
12571    /// Matches `pd.Series.to_json(path, orient=...)` for the supported Series
12572    /// JSON orientations.
12573    fn to_json_file(&self, path: &Path, orient: &str) -> Result<(), IoError>;
12574
12575    /// Serialize this Series to a JSON string.
12576    ///
12577    /// Matches `pd.Series.to_json(orient=...)` for the supported Series JSON
12578    /// orientations.
12579    fn to_json_string(&self, orient: &str) -> Result<String, IoError>;
12580
12581    /// Write this Series to an HDF5 file at the default key.
12582    ///
12583    /// Matches `pd.Series.to_hdf(path)` for the supported HDF5 snapshot
12584    /// surface.
12585    fn to_hdf(&self, path: &Path) -> Result<(), IoError>;
12586
12587    /// Write this Series to an HDF5 file at the default key.
12588    ///
12589    /// Explicit file-suffixed form of [`SeriesIoExt::to_hdf`].
12590    fn to_hdf_file(&self, path: &Path) -> Result<(), IoError>;
12591
12592    /// Write this Series to an HDF5 file at an explicit key.
12593    fn to_hdf_key(&self, path: &Path, key: &str) -> Result<(), IoError>;
12594
12595    /// Write this Series to an HDF5 file with explicit options.
12596    fn to_hdf_with_options(&self, path: &Path, options: &HdfWriteOptions) -> Result<(), IoError>;
12597
12598    /// Write this Series to an Excel file.
12599    ///
12600    /// Matches `pd.Series.to_excel(path)` for the supported xlsx writer
12601    /// surface.
12602    fn to_excel(&self, path: &Path) -> Result<(), IoError>;
12603
12604    /// Write this Series to an Excel file.
12605    ///
12606    /// Explicit file-suffixed form of [`SeriesIoExt::to_excel`].
12607    fn to_excel_file(&self, path: &Path) -> Result<(), IoError>;
12608
12609    /// Write this Series to an Excel file with explicit options.
12610    fn to_excel_with_options(
12611        &self,
12612        path: &Path,
12613        options: &ExcelWriteOptions,
12614    ) -> Result<(), IoError>;
12615
12616    /// Serialize this Series to xlsx bytes.
12617    fn to_excel_bytes(&self) -> Result<Vec<u8>, IoError>;
12618
12619    /// Serialize this Series to xlsx bytes with explicit options.
12620    fn to_excel_bytes_with_options(&self, options: &ExcelWriteOptions) -> Result<Vec<u8>, IoError>;
12621
12622    /// Write this Series to a SQL table.
12623    ///
12624    /// Matches `pd.Series.to_sql(name, con)` for the supported SQL writer
12625    /// surface, including pandas' default index materialization.
12626    fn to_sql<C: SqlConnection>(
12627        &self,
12628        conn: &C,
12629        table_name: &str,
12630        if_exists: SqlIfExists,
12631    ) -> Result<(), IoError>;
12632
12633    /// Write this Series to a SQL table with pandas-style SQL write options.
12634    fn to_sql_with_options<C: SqlConnection>(
12635        &self,
12636        conn: &C,
12637        table_name: &str,
12638        options: &SqlWriteOptions,
12639    ) -> Result<(), IoError>;
12640
12641    /// Clipboard writer (TSV via an OS backend), matching `pd.Series.to_clipboard()`.
12642    fn to_clipboard(&self) -> Result<(), IoError>;
12643}
12644
12645impl SeriesIoExt for Series {
12646    fn to_pickle(&self, path: &Path) -> Result<(), IoError> {
12647        write_pickle(&self.to_frame(None)?, path)
12648    }
12649
12650    fn to_pickle_file(&self, path: &Path) -> Result<(), IoError> {
12651        self.to_pickle(path)
12652    }
12653
12654    fn to_pickle_with_options(
12655        &self,
12656        path: &Path,
12657        options: &PickleWriteOptions,
12658    ) -> Result<(), IoError> {
12659        write_pickle_with_options(&self.to_frame(None)?, path, options)
12660    }
12661
12662    fn to_pickle_bytes(&self) -> Result<Vec<u8>, IoError> {
12663        write_pickle_bytes(&self.to_frame(None)?)
12664    }
12665
12666    fn to_pickle_bytes_with_options(
12667        &self,
12668        options: &PickleWriteOptions,
12669    ) -> Result<Vec<u8>, IoError> {
12670        write_pickle_bytes_with_options(&self.to_frame(None)?, options)
12671    }
12672
12673    fn to_csv_file(&self, path: &Path) -> Result<(), IoError> {
12674        self.to_csv_file_with_options(
12675            path,
12676            &CsvWriteOptions {
12677                include_index: true,
12678                ..CsvWriteOptions::default()
12679            },
12680        )
12681    }
12682
12683    fn to_csv_file_with_options(
12684        &self,
12685        path: &Path,
12686        options: &CsvWriteOptions,
12687    ) -> Result<(), IoError> {
12688        std::fs::write(path, self.to_csv_string_with_options(options)?)?;
12689        Ok(())
12690    }
12691
12692    fn to_csv_string(&self) -> Result<String, IoError> {
12693        self.to_csv_string_with_options(&CsvWriteOptions {
12694            include_index: true,
12695            ..CsvWriteOptions::default()
12696        })
12697    }
12698
12699    fn to_csv_string_with_options(&self, options: &CsvWriteOptions) -> Result<String, IoError> {
12700        write_csv_string_with_options(&self.to_frame(None)?, options)
12701    }
12702
12703    fn to_markdown_string(&self) -> Result<String, IoError> {
12704        self.to_markdown_string_with_options(&MarkdownWriteOptions::default())
12705    }
12706
12707    fn to_markdown_string_with_options(
12708        &self,
12709        options: &MarkdownWriteOptions,
12710    ) -> Result<String, IoError> {
12711        write_markdown_string_with_options(&self.to_frame(None)?, options)
12712    }
12713
12714    fn to_markdown_file(&self, path: &Path) -> Result<(), IoError> {
12715        self.to_markdown_file_with_options(path, &MarkdownWriteOptions::default())
12716    }
12717
12718    fn to_markdown_file_with_options(
12719        &self,
12720        path: &Path,
12721        options: &MarkdownWriteOptions,
12722    ) -> Result<(), IoError> {
12723        write_markdown_with_options(&self.to_frame(None)?, path, options)
12724    }
12725
12726    fn to_latex_string(&self) -> Result<String, IoError> {
12727        self.to_latex_string_with_options(&LatexWriteOptions::default())
12728    }
12729
12730    fn to_latex_string_with_options(&self, options: &LatexWriteOptions) -> Result<String, IoError> {
12731        write_latex_string_with_options(&self.to_frame(None)?, options)
12732    }
12733
12734    fn to_latex_file(&self, path: &Path) -> Result<(), IoError> {
12735        self.to_latex_file_with_options(path, &LatexWriteOptions::default())
12736    }
12737
12738    fn to_latex_file_with_options(
12739        &self,
12740        path: &Path,
12741        options: &LatexWriteOptions,
12742    ) -> Result<(), IoError> {
12743        write_latex_with_options(&self.to_frame(None)?, path, options)
12744    }
12745
12746    fn to_json_file(&self, path: &Path, orient: &str) -> Result<(), IoError> {
12747        std::fs::write(path, self.to_json_string(orient)?)?;
12748        Ok(())
12749    }
12750
12751    fn to_json_string(&self, orient: &str) -> Result<String, IoError> {
12752        Ok(Series::to_json(self, orient)?)
12753    }
12754
12755    fn to_hdf(&self, path: &Path) -> Result<(), IoError> {
12756        write_hdf(&self.to_frame(None)?, path)
12757    }
12758
12759    fn to_hdf_file(&self, path: &Path) -> Result<(), IoError> {
12760        self.to_hdf(path)
12761    }
12762
12763    fn to_hdf_key(&self, path: &Path, key: &str) -> Result<(), IoError> {
12764        write_hdf_key(&self.to_frame(None)?, path, key)
12765    }
12766
12767    fn to_hdf_with_options(&self, path: &Path, options: &HdfWriteOptions) -> Result<(), IoError> {
12768        write_hdf_with_options(&self.to_frame(None)?, path, options)
12769    }
12770
12771    fn to_excel(&self, path: &Path) -> Result<(), IoError> {
12772        write_excel(&self.to_frame(None)?, path)
12773    }
12774
12775    fn to_excel_file(&self, path: &Path) -> Result<(), IoError> {
12776        self.to_excel(path)
12777    }
12778
12779    fn to_excel_with_options(
12780        &self,
12781        path: &Path,
12782        options: &ExcelWriteOptions,
12783    ) -> Result<(), IoError> {
12784        write_excel_with_options(&self.to_frame(None)?, path, options)
12785    }
12786
12787    fn to_excel_bytes(&self) -> Result<Vec<u8>, IoError> {
12788        write_excel_bytes(&self.to_frame(None)?)
12789    }
12790
12791    fn to_excel_bytes_with_options(&self, options: &ExcelWriteOptions) -> Result<Vec<u8>, IoError> {
12792        write_excel_bytes_with_options(&self.to_frame(None)?, options)
12793    }
12794
12795    fn to_sql<C: SqlConnection>(
12796        &self,
12797        conn: &C,
12798        table_name: &str,
12799        if_exists: SqlIfExists,
12800    ) -> Result<(), IoError> {
12801        write_sql_with_options(
12802            &self.to_frame(None)?,
12803            conn,
12804            table_name,
12805            &SqlWriteOptions {
12806                if_exists,
12807                index: true,
12808                index_label: None,
12809                schema: None,
12810                dtype: None,
12811                method: SqlInsertMethod::Single,
12812                chunksize: None,
12813            },
12814        )
12815    }
12816
12817    fn to_sql_with_options<C: SqlConnection>(
12818        &self,
12819        conn: &C,
12820        table_name: &str,
12821        options: &SqlWriteOptions,
12822    ) -> Result<(), IoError> {
12823        write_sql_with_options(&self.to_frame(None)?, conn, table_name, options)
12824    }
12825
12826    fn to_clipboard(&self) -> Result<(), IoError> {
12827        clipboard_set(&clipboard_tsv(&self.to_frame(None)?)?)
12828    }
12829}
12830
12831#[cfg(test)]
12832mod tests {
12833    use std::collections::BTreeMap;
12834
12835    use arrow::{
12836        array::{Array, Int64Array},
12837        datatypes::DataType as ArrowDataType,
12838    };
12839    use fp_columnar::Column;
12840    use fp_frame::{DataFrame, Series};
12841    use fp_index::{Index, IndexLabel};
12842    use fp_types::{DType, NullKind, Scalar, Timestamp};
12843
12844    use super::{
12845        CsvWriteOptions, ExcelReadOptions, ExcelWriteOptions, Float64QuarterAffineCsvPlan,
12846        HtmlReadOptions, HtmlWriteOptions, IoError, JsonOrient, LatexWriteOptions,
12847        MarkdownWriteOptions, PickleProtocol, PickleWriteOptions, StataWriteOptions,
12848        XmlReadOptions, XmlWriteOptions, format_pandas_float, read_csv_str,
12849        read_csv_with_index_cols, read_excel_bytes, read_feather_bytes, read_html, read_html_str,
12850        read_html_str_with_options, read_json_str, read_orc, read_orc_bytes, read_parquet_bytes,
12851        read_pickle, read_pickle_bytes, read_stata, read_stata_bytes, read_xml, read_xml_str,
12852        read_xml_str_with_options, write_csv_string, write_csv_string_with_options,
12853        write_excel_bytes, write_html, write_html_string, write_html_string_with_options,
12854        write_json_string, write_jsonl_string, write_latex, write_latex_string,
12855        write_latex_string_with_options, write_latex_with_options, write_markdown,
12856        write_markdown_string, write_markdown_string_with_options, write_markdown_with_options,
12857        write_orc, write_orc_bytes, write_pickle, write_pickle_bytes, write_stata,
12858        write_stata_bytes, write_stata_bytes_with_options, write_xml, write_xml_string,
12859        write_xml_string_with_options,
12860    };
12861    #[cfg(feature = "hdf5")]
12862    use super::{
12863        HdfReadOptions, HdfWriteOptions, read_hdf, read_hdf_key, read_hdf_with_options, write_hdf,
12864        write_hdf_key, write_hdf_with_options,
12865    };
12866
12867    fn assert_orc_disabled(err: IoError) {
12868        assert!(
12869            matches!(
12870                err,
12871                IoError::Orc(ref message)
12872                    if message.contains("Tokio-free native ORC backend")
12873            ),
12874            "expected ORC no-Tokio policy error, got {err:?}"
12875        );
12876    }
12877
12878    #[test]
12879    fn csv_quoting_round_trip_special_chars_1h8ar() {
12880        // RFC4180 escaping (br-frankenpandas-1h8ar): quoted fields parse to their
12881        // unescaped value, and write->read round-trips them (write must re-quote).
12882        // (csv_field_as_written, expected_parsed_value)
12883        let cases: [(&str, &str); 4] = [
12884            ("\"x,y\"", "x,y"),     // comma requires quoting
12885            ("\"a\"\"b\"", "a\"b"), // embedded quote -> doubled
12886            ("plain", "plain"),     // no quoting needed
12887            ("\" sp \"", " sp "),   // preserved leading/trailing spaces
12888        ];
12889        for (field, expected) in cases {
12890            let input = format!("col\n{field}\n");
12891            let f1 = read_csv_str(&input).expect("read1");
12892            assert_eq!(
12893                f1.column("col").expect("col").values()[0],
12894                Scalar::Utf8(expected.to_string()),
12895                "parse field={field:?}"
12896            );
12897            // write then re-read must preserve the value (correct re-quoting).
12898            let s2 = write_csv_string(&f1).expect("write");
12899            let f2 = read_csv_str(&s2).expect("read2");
12900            assert_eq!(
12901                f2.column("col").expect("col2").values()[0],
12902                Scalar::Utf8(expected.to_string()),
12903                "round-trip field={field:?} written={s2:?}"
12904            );
12905        }
12906    }
12907
12908    #[test]
12909    fn csv_write_header_line_order_g9rxa() {
12910        // br-frankenpandas-g9rxa: write_csv_string's first line == column names in
12911        // column order joined by comma.
12912        let idx = vec![0_i64.into(), 1_i64.into()];
12913        let col = |name: &str, v: [i64; 2]| {
12914            Series::from_values(
12915                name,
12916                idx.clone(),
12917                vec![Scalar::Int64(v[0]), Scalar::Int64(v[1])],
12918            )
12919            .unwrap()
12920        };
12921        let df = DataFrame::from_series(vec![
12922            col("alpha", [1, 2]),
12923            col("beta", [3, 4]),
12924            col("gamma", [5, 6]),
12925        ])
12926        .unwrap();
12927        let csv = write_csv_string(&df).expect("write");
12928        let header = csv.lines().next().expect("header line");
12929        assert_eq!(header, "alpha,beta,gamma", "header order; csv={csv:?}");
12930    }
12931
12932    #[test]
12933    fn csv_per_column_dtype_inference_me2x3() {
12934        // br-frankenpandas-me2x3: read_csv infers Int64 for all-int, Float64 for a
12935        // column containing a decimal, Utf8 for text.
12936        let df = read_csv_str("a,b,c\n1,1.5,x\n2,2.5,y\n3,3.5,z\n").expect("read");
12937        assert_eq!(
12938            df.column("a").expect("a").dtype(),
12939            DType::Int64,
12940            "all-int -> Int64"
12941        );
12942        assert_eq!(
12943            df.column("b").expect("b").dtype(),
12944            DType::Float64,
12945            "decimal -> Float64"
12946        );
12947        assert_eq!(
12948            df.column("c").expect("c").dtype(),
12949            DType::Utf8,
12950            "text -> Utf8"
12951        );
12952        assert_eq!(df.len(), 3, "row count");
12953    }
12954
12955    #[test]
12956    fn csv_header_only_zero_rows_yqfw0() {
12957        // br-frankenpandas-yqfw0: a header-only CSV parses to a 0-row frame that still
12958        // exposes the header columns.
12959        let df = read_csv_str("a,b\n").expect("read header-only");
12960        assert_eq!(df.len(), 0, "no data rows; df={df:?}");
12961        assert!(df.column("a").is_some(), "column a present");
12962        assert!(df.column("b").is_some(), "column b present");
12963        assert_eq!(df.column("a").unwrap().values().len(), 0, "column a empty");
12964    }
12965
12966    #[test]
12967    fn csv_embedded_comma_in_quoted_field_rtpo7() {
12968        // br-frankenpandas-rtpo7: a quoted field containing the delimiter parses as ONE
12969        // field, not two columns (RFC4180). Companion to ftqon (embedded newline).
12970        let df = read_csv_str("col,n\n\"a,b\",1\n").expect("read");
12971        assert_eq!(df.len(), 1, "one row");
12972        assert!(
12973            df.column("col").is_some() && df.column("n").is_some(),
12974            "two columns only"
12975        );
12976        assert_eq!(
12977            df.column("col").unwrap().values()[0],
12978            Scalar::Utf8("a,b".to_owned()),
12979            "embedded comma kept"
12980        );
12981    }
12982
12983    #[test]
12984    fn csv_embedded_newline_in_quoted_field_ftqon() {
12985        // br-frankenpandas-ftqon: a quoted field containing a newline parses as ONE
12986        // multiline value (RFC4180), not two rows; and round-trips.
12987        let input = "col\n\"line1\nline2\"\n";
12988        let df = read_csv_str(input).expect("read");
12989        assert_eq!(df.len(), 1, "embedded newline stays one row; df={df:?}");
12990        let col = df.column("col").expect("col");
12991        assert_eq!(
12992            col.values()[0],
12993            Scalar::Utf8("line1\nline2".to_owned()),
12994            "multiline value intact"
12995        );
12996        // Round-trip: writing then reading preserves the multiline value.
12997        let csv = write_csv_string(&df).expect("write");
12998        let back = read_csv_str(&csv).expect("reread");
12999        assert_eq!(back.len(), 1, "round-trip row count");
13000        assert_eq!(
13001            back.column("col").expect("col").values()[0],
13002            Scalar::Utf8("line1\nline2".to_owned()),
13003            "round-trip value"
13004        );
13005    }
13006
13007    #[test]
13008    fn csv_bool_column_round_trip_w3dja() {
13009        // br-frankenpandas-w3dja: Bool column survives write_csv_string -> read_csv_str
13010        // (True/False spelling on write + case-insensitive bool inference on read).
13011        let bools = [true, false, true, false, true];
13012        let df = DataFrame::from_series(vec![
13013            Series::from_values(
13014                "flag",
13015                (0..bools.len() as i64).map(Into::into).collect::<Vec<_>>(),
13016                bools.iter().map(|&b| Scalar::Bool(b)).collect::<Vec<_>>(),
13017            )
13018            .unwrap(),
13019        ])
13020        .unwrap();
13021
13022        let csv = write_csv_string(&df).expect("write");
13023        let back = read_csv_str(&csv).expect("read");
13024        let col = back.column("flag").expect("flag");
13025        assert_eq!(
13026            col.dtype(),
13027            DType::Bool,
13028            "round-trip keeps Bool; csv={csv:?}"
13029        );
13030        assert_eq!(
13031            col.values(),
13032            &bools.iter().map(|&b| Scalar::Bool(b)).collect::<Vec<_>>()[..],
13033            "bool values preserved"
13034        );
13035    }
13036
13037    #[test]
13038    fn csv_read_write_read_idempotent_5gfjz() {
13039        // Round-trip fixed point (br-frankenpandas-5gfjz): read -> write -> read
13040        // yields an identical frame. Simple cells (ints + single letters, no
13041        // special chars) avoid quoting/precision edges. Seeded LCG, no mocks.
13042        let mut st: u64 = 0xc5f0_1d2e_3a4b_5c6d;
13043        let mut next = || {
13044            st = st
13045                .wrapping_mul(6_364_136_223_846_793_005)
13046                .wrapping_add(1_442_695_040_888_963_407);
13047            (st >> 33) as u32
13048        };
13049        for iter in 0..400u32 {
13050            let rows = (next() % 6) as usize + 1;
13051            let mut csv = String::from("a,b,c\n");
13052            for _ in 0..rows {
13053                let x = (next() % 100) as i64;
13054                let y = (next() % 1000) as i64;
13055                let letter = (b'a' + (next() % 5) as u8) as char;
13056                csv.push_str(&format!("{x},{y},{letter}\n"));
13057            }
13058            let f1 = read_csv_str(&csv).expect("read1");
13059            let s2 = write_csv_string(&f1).expect("write");
13060            let f2 = read_csv_str(&s2).expect("read2");
13061            assert_eq!(f1.len(), f2.len(), "row count iter={iter} csv={csv:?}");
13062            for name in ["a", "b", "c"] {
13063                assert_eq!(
13064                    f1.column(name).expect("c1").values(),
13065                    f2.column(name).expect("c2").values(),
13066                    "col {name} iter={iter} csv={csv:?}"
13067                );
13068            }
13069        }
13070    }
13071
13072    #[test]
13073    fn csv_round_trip_preserves_null_and_numeric_shape() {
13074        let input = "id,value\n1,10\n2,\n3,3.5\n";
13075        let frame = read_csv_str(input).expect("read");
13076        let value_col = frame.column("value").expect("value");
13077
13078        assert_eq!(value_col.values()[1], Scalar::Null(NullKind::NaN));
13079
13080        let out = write_csv_string(&frame).expect("write");
13081        assert!(out.contains("id,value"));
13082        assert!(out.contains("3,3.5"));
13083    }
13084
13085    #[test]
13086    fn csv_numeric_fast_path_preserves_default_dtypes_and_values() {
13087        let input = "i,f\n1,0.5\n2,3\n";
13088        let frame = read_csv_str(input).expect("read");
13089
13090        let int_col = frame.column("i").expect("i");
13091        assert_eq!(int_col.dtype(), DType::Int64);
13092        assert_eq!(int_col.values(), &[Scalar::Int64(1), Scalar::Int64(2)]);
13093
13094        let float_col = frame.column("f").expect("f");
13095        assert_eq!(float_col.dtype(), DType::Float64);
13096        assert_eq!(
13097            float_col.values(),
13098            &[Scalar::Float64(0.5), Scalar::Float64(3.0)]
13099        );
13100    }
13101
13102    #[test]
13103    fn csv_numeric_probe_falls_back_to_preserve_object_raw_text() {
13104        let input = "x\n 1 \nabc\n";
13105        let frame = read_csv_str(input).expect("read");
13106        let column = frame.column("x").expect("x");
13107
13108        assert_eq!(column.dtype(), DType::Utf8);
13109        assert_eq!(
13110            column.values(),
13111            &[
13112                Scalar::Utf8(" 1 ".to_owned()),
13113                Scalar::Utf8("abc".to_owned())
13114            ]
13115        );
13116    }
13117
13118    #[test]
13119    fn csv_parses_boolean_true_false_case_insensitive() {
13120        let input = "flag\nTrue\nFALSE\ntrue\nfalse\n";
13121        let frame = read_csv_str(input).expect("read");
13122        let flag_col = frame.column("flag").expect("flag");
13123        assert_eq!(flag_col.values()[0], Scalar::Bool(true));
13124        assert_eq!(flag_col.values()[1], Scalar::Bool(false));
13125        assert_eq!(flag_col.values()[2], Scalar::Bool(true));
13126        assert_eq!(flag_col.values()[3], Scalar::Bool(false));
13127    }
13128
13129    #[test]
13130    fn csv_duplicate_headers_error() {
13131        let input = "a,a\n1,2\n";
13132        let err = read_csv_str(input).expect_err("duplicate header");
13133        assert!(matches!(err, IoError::DuplicateColumnName(name) if name == "a"));
13134    }
13135
13136    #[test]
13137    fn csv_ragged_row_returns_error_4hpid() {
13138        // Per br-frankenpandas-4hpid: confirm pandas-faithful rejection on
13139        // ragged rows. The underlying csv crate raises UnequalLengths
13140        // (surfaced as IoError::Csv) — record.get(idx).unwrap_or_default()
13141        // inside the loop is dead code because the `row?` upstream errors
13142        // first. This locks in the rejection contract.
13143        let short_row = "a,b,c\n1,2,3\n4,5\n7,8,9\n";
13144        let err = read_csv_str(short_row).expect_err("short row must reject");
13145        assert!(
13146            matches!(err, IoError::Csv(_)),
13147            "expected IoError::Csv (UnequalLengths from csv crate), got {err:?}"
13148        );
13149    }
13150
13151    fn make_table_format_dataframe() -> DataFrame {
13152        let mut columns = BTreeMap::new();
13153        columns.insert(
13154            "name".to_owned(),
13155            Column::from_values(vec![
13156                Scalar::Utf8("A|B".to_owned()),
13157                Scalar::Utf8("under_score".to_owned()),
13158            ])
13159            .expect("name column"),
13160        );
13161        columns.insert(
13162            "value".to_owned(),
13163            Column::from_values(vec![Scalar::Float64(f64::NAN), Scalar::Int64(2)])
13164                .expect("value column"),
13165        );
13166
13167        let index = Index::new(vec![
13168            IndexLabel::Utf8("r&1".to_owned()),
13169            IndexLabel::Utf8("r_2".to_owned()),
13170        ])
13171        .set_name("row");
13172        DataFrame::new_with_column_order(
13173            index,
13174            columns,
13175            vec!["name".to_owned(), "value".to_owned()],
13176        )
13177        .expect("table format frame")
13178    }
13179
13180    #[test]
13181    fn markdown_table_writer_includes_index_missing_values_and_escaping() {
13182        let frame = make_table_format_dataframe();
13183
13184        let out = write_markdown_string(&frame).expect("markdown");
13185
13186        assert_eq!(
13187            out,
13188            concat!(
13189                "| row | name | value |\n",
13190                "| --- | --- | --- |\n",
13191                "| r&1 | A\\|B | NaN |\n",
13192                "| r_2 | under_score | 2 |\n",
13193            )
13194        );
13195    }
13196
13197    #[test]
13198    fn markdown_table_writer_options_can_omit_index_and_override_na() {
13199        let frame = make_table_format_dataframe();
13200
13201        let out = write_markdown_string_with_options(
13202            &frame,
13203            &MarkdownWriteOptions {
13204                include_index: false,
13205                na_rep: "<missing>".to_owned(),
13206                index_label: Some("ignored".to_owned()),
13207            },
13208        )
13209        .expect("markdown");
13210
13211        assert_eq!(
13212            out,
13213            concat!(
13214                "| name | value |\n",
13215                "| --- | --- |\n",
13216                "| A\\|B | <missing> |\n",
13217                "| under_score | 2 |\n",
13218            )
13219        );
13220    }
13221
13222    #[test]
13223    fn latex_table_writer_emits_booktabs_and_supports_escaping() {
13224        let frame = make_table_format_dataframe();
13225
13226        let out = write_latex_string_with_options(
13227            &frame,
13228            &LatexWriteOptions {
13229                include_index: true,
13230                na_rep: "NA".to_owned(),
13231                index_label: Some("row_id".to_owned()),
13232                escape: true,
13233            },
13234        )
13235        .expect("latex");
13236
13237        assert_eq!(
13238            out,
13239            concat!(
13240                "\\begin{tabular}{lll}\n",
13241                "\\toprule\n",
13242                " & name & value \\\\\n",
13243                "row\\_id &  &  \\\\\n",
13244                "\\midrule\n",
13245                "r\\&1 & A|B & NA \\\\\n",
13246                "r\\_2 & under\\_score & 2.000000 \\\\\n",
13247                "\\bottomrule\n",
13248                "\\end{tabular}\n",
13249            )
13250        );
13251    }
13252
13253    #[test]
13254    fn to_latex_floats_use_six_decimal_places_like_pandas() {
13255        // pandas to_latex default float_format is %.6f. Verified vs pandas 2.2.3:
13256        // 1.0->"1.000000", -2.5->"-2.500000", 0.1234567->"0.123457" (rounded),
13257        // inf->"inf". Other writers (csv/html) keep str(float).
13258        let values = vec![
13259            Scalar::Float64(1.0),
13260            Scalar::Float64(-2.5),
13261            Scalar::Float64(0.1234567),
13262            Scalar::Float64(f64::INFINITY),
13263        ];
13264        let col = Column::new(DType::Float64, values).expect("col");
13265        let mut cols = BTreeMap::new();
13266        cols.insert("a".to_string(), col);
13267        let index = Index::from_i64((0..4).collect());
13268        let frame =
13269            DataFrame::new_with_column_order(index, cols, vec!["a".to_string()]).expect("frame");
13270
13271        let out = write_latex_string_with_options(
13272            &frame,
13273            &LatexWriteOptions {
13274                include_index: false,
13275                na_rep: "NaN".to_owned(),
13276                index_label: None,
13277                escape: true,
13278            },
13279        )
13280        .expect("latex");
13281        assert!(out.contains("1.000000 \\\\"), "got: {out}");
13282        assert!(out.contains("-2.500000 \\\\"), "got: {out}");
13283        assert!(out.contains("0.123457 \\\\"), "got: {out}");
13284        assert!(out.contains("inf \\\\"), "got: {out}");
13285    }
13286
13287    #[test]
13288    fn markdown_latex_file_writers_match_string_outputs() {
13289        let frame = make_table_format_dataframe();
13290        let markdown_path = std::env::temp_dir().join(format!(
13291            "fp_io_markdown_writer_{}_{}.md",
13292            std::process::id(),
13293            line!()
13294        ));
13295        let latex_path = std::env::temp_dir().join(format!(
13296            "fp_io_latex_writer_{}_{}.tex",
13297            std::process::id(),
13298            line!()
13299        ));
13300
13301        write_markdown(&frame, &markdown_path).expect("write markdown path");
13302        write_latex(&frame, &latex_path).expect("write latex path");
13303
13304        assert_eq!(
13305            std::fs::read_to_string(&markdown_path).expect("read markdown path"),
13306            write_markdown_string(&frame).expect("markdown string")
13307        );
13308        assert_eq!(
13309            std::fs::read_to_string(&latex_path).expect("read latex path"),
13310            write_latex_string(&frame).expect("latex string")
13311        );
13312    }
13313
13314    #[test]
13315    fn markdown_latex_trait_aliases_forward_options() {
13316        use super::DataFrameIoExt;
13317
13318        let frame = make_table_format_dataframe();
13319        let markdown_options = MarkdownWriteOptions {
13320            include_index: false,
13321            na_rep: "NA".to_owned(),
13322            index_label: Some("ignored".to_owned()),
13323        };
13324        let latex_options = LatexWriteOptions {
13325            include_index: false,
13326            na_rep: "NA".to_owned(),
13327            index_label: Some("ignored".to_owned()),
13328            escape: true,
13329        };
13330        let markdown_path = std::env::temp_dir().join(format!(
13331            "fp_io_markdown_trait_{}_{}.md",
13332            std::process::id(),
13333            line!()
13334        ));
13335        let latex_path = std::env::temp_dir().join(format!(
13336            "fp_io_latex_trait_{}_{}.tex",
13337            std::process::id(),
13338            line!()
13339        ));
13340
13341        frame
13342            .to_markdown_file_with_options(&markdown_path, &markdown_options)
13343            .expect("trait markdown file");
13344        frame
13345            .to_latex_file_with_options(&latex_path, &latex_options)
13346            .expect("trait latex file");
13347
13348        assert_eq!(
13349            frame
13350                .to_markdown_string_with_options(&markdown_options)
13351                .expect("trait markdown options"),
13352            std::fs::read_to_string(&markdown_path).expect("read markdown trait path")
13353        );
13354        assert_eq!(
13355            frame
13356                .to_latex_string_with_options(&latex_options)
13357                .expect("trait latex options"),
13358            std::fs::read_to_string(&latex_path).expect("read latex trait path")
13359        );
13360
13361        let default_markdown_path = std::env::temp_dir().join(format!(
13362            "fp_io_markdown_trait_default_{}_{}.md",
13363            std::process::id(),
13364            line!()
13365        ));
13366        let default_latex_path = std::env::temp_dir().join(format!(
13367            "fp_io_latex_trait_default_{}_{}.tex",
13368            std::process::id(),
13369            line!()
13370        ));
13371        frame
13372            .to_markdown_file(&default_markdown_path)
13373            .expect("trait markdown default file");
13374        frame
13375            .to_latex_file(&default_latex_path)
13376            .expect("trait latex default file");
13377
13378        assert_eq!(
13379            std::fs::read_to_string(&default_markdown_path).expect("read markdown default"),
13380            write_markdown_string(&frame).expect("markdown default")
13381        );
13382        assert_eq!(
13383            std::fs::read_to_string(&default_latex_path).expect("read latex default"),
13384            write_latex_string(&frame).expect("latex default")
13385        );
13386
13387        let free_markdown_path = std::env::temp_dir().join(format!(
13388            "fp_io_markdown_free_options_{}_{}.md",
13389            std::process::id(),
13390            line!()
13391        ));
13392        let free_latex_path = std::env::temp_dir().join(format!(
13393            "fp_io_latex_free_options_{}_{}.tex",
13394            std::process::id(),
13395            line!()
13396        ));
13397        write_markdown_with_options(&frame, &free_markdown_path, &markdown_options)
13398            .expect("free markdown options file");
13399        write_latex_with_options(&frame, &free_latex_path, &latex_options)
13400            .expect("free latex options file");
13401        assert_eq!(
13402            std::fs::read_to_string(&free_markdown_path).expect("read free markdown options"),
13403            write_markdown_string_with_options(&frame, &markdown_options)
13404                .expect("free markdown options string")
13405        );
13406        assert_eq!(
13407            std::fs::read_to_string(&free_latex_path).expect("read free latex options"),
13408            write_latex_string_with_options(&frame, &latex_options)
13409                .expect("free latex options string")
13410        );
13411    }
13412
13413    #[test]
13414    fn html_table_writer_defaults_to_index_and_reuses_dataframe_formatter() {
13415        let frame = make_table_format_dataframe();
13416
13417        let out = write_html_string(&frame).expect("html");
13418
13419        assert_eq!(out, frame.to_html(true));
13420        assert!(out.contains("<th>r&amp;1</th>"));
13421        assert!(out.contains("<td>A|B</td>"));
13422        assert!(out.contains("<td>NaN</td>"));
13423    }
13424
13425    #[test]
13426    fn html_table_writer_options_can_omit_index() {
13427        let frame = make_table_format_dataframe();
13428
13429        let out = write_html_string_with_options(
13430            &frame,
13431            &HtmlWriteOptions {
13432                include_index: false,
13433                ..HtmlWriteOptions::default()
13434            },
13435        )
13436        .expect("html");
13437
13438        assert_eq!(out, frame.to_html(false));
13439        assert!(!out.contains("<th>r&amp;1</th>"));
13440        assert!(out.contains("<td>A|B</td>"));
13441    }
13442
13443    #[test]
13444    fn html_table_writer_supports_pandas_pure_string_options_u892h() {
13445        let mut columns = BTreeMap::new();
13446        columns.insert(
13447            "url&col".to_owned(),
13448            Column::from_values(vec![
13449                Scalar::Utf8("https://example.test/a?x=1&y=2".to_owned()),
13450                Scalar::Utf8("<b>".to_owned()),
13451            ])
13452            .expect("url column"),
13453        );
13454        columns.insert(
13455            "value".to_owned(),
13456            Column::from_values(vec![Scalar::Null(NullKind::NaN), Scalar::Float64(2.0)])
13457                .expect("value column"),
13458        );
13459        let frame = DataFrame::new_with_column_order(
13460            Index::new(vec![
13461                IndexLabel::Utf8("r&1".to_owned()),
13462                IndexLabel::Utf8("r2".to_owned()),
13463            ]),
13464            columns,
13465            vec!["url&col".to_owned(), "value".to_owned()],
13466        )
13467        .expect("html options frame");
13468
13469        let out = write_html_string_with_options(
13470            &frame,
13471            &HtmlWriteOptions {
13472                include_index: true,
13473                na_rep: "<NA>".to_owned(),
13474                classes: vec!["table table-sm".to_owned(), "fp".to_owned()],
13475                table_id: Some("report&1".to_owned()),
13476                border: Some(0),
13477                justify: Some("left".to_owned()),
13478                escape: true,
13479                render_links: true,
13480            },
13481        )
13482        .expect("html options");
13483
13484        assert!(
13485            out.starts_with("<table class=\"dataframe table table-sm fp\" id=\"report&amp;1\">")
13486        );
13487        assert!(!out.contains("border=\""));
13488        assert!(out.contains("<tr style=\"text-align: left;\">"));
13489        assert!(out.contains("<th>url&amp;col</th>"));
13490        assert!(out.contains("<th>r&amp;1</th>"));
13491        assert!(out.contains("<td>&lt;NA&gt;</td>"));
13492        assert!(out.contains(
13493            "<a href=\"https://example.test/a?x=1&amp;y=2\" target=\"_blank\">https://example.test/a?x=1&amp;y=2</a>"
13494        ));
13495        assert!(out.contains("<td>&lt;b&gt;</td>"));
13496    }
13497
13498    #[test]
13499    fn html_table_writer_can_disable_escaping_u892h() {
13500        let mut columns = BTreeMap::new();
13501        columns.insert(
13502            "raw<th>".to_owned(),
13503            Column::from_values(vec![
13504                Scalar::Utf8("<b>".to_owned()),
13505                Scalar::Null(NullKind::NaN),
13506            ])
13507            .expect("raw column"),
13508        );
13509        let frame = DataFrame::new_with_column_order(
13510            Index::new(vec![
13511                IndexLabel::Utf8("r&1".to_owned()),
13512                IndexLabel::Int64(2),
13513            ]),
13514            columns,
13515            vec!["raw<th>".to_owned()],
13516        )
13517        .expect("raw html frame");
13518
13519        let out = write_html_string_with_options(
13520            &frame,
13521            &HtmlWriteOptions {
13522                na_rep: "<NA>".to_owned(),
13523                escape: false,
13524                ..HtmlWriteOptions::default()
13525            },
13526        )
13527        .expect("raw html options");
13528
13529        assert!(out.contains("<th>raw<th></th>"));
13530        assert!(out.contains("<th>r&1</th>"));
13531        assert!(out.contains("<td><b></td>"));
13532        assert!(out.contains("<td><NA></td>"));
13533    }
13534
13535    #[test]
13536    fn html_table_writer_file_output_matches_string_output() {
13537        use super::DataFrameIoExt;
13538
13539        let frame = make_table_format_dataframe();
13540        let path = std::env::temp_dir().join(format!(
13541            "fp_io_html_writer_{}_{}.html",
13542            std::process::id(),
13543            line!()
13544        ));
13545
13546        write_html(&frame, &path).expect("write html");
13547        let file_out = std::fs::read_to_string(&path).expect("read html");
13548
13549        assert_eq!(file_out, write_html_string(&frame).expect("html string"));
13550        assert_eq!(
13551            frame.to_html_string().expect("trait html string"),
13552            write_html_string(&frame).expect("free html string")
13553        );
13554
13555        let no_index_path = std::env::temp_dir().join(format!(
13556            "fp_io_html_writer_no_index_{}_{}.html",
13557            std::process::id(),
13558            line!()
13559        ));
13560        let no_index_options = HtmlWriteOptions {
13561            include_index: false,
13562            ..HtmlWriteOptions::default()
13563        };
13564        frame
13565            .to_html_file_with_options(&no_index_path, &no_index_options)
13566            .expect("trait html file");
13567        assert_eq!(
13568            std::fs::read_to_string(&no_index_path).expect("read trait html"),
13569            write_html_string_with_options(&frame, &no_index_options).expect("free html options")
13570        );
13571    }
13572
13573    #[test]
13574    fn html_reader_parses_first_table_headers_and_missing_cells() {
13575        let html = concat!(
13576            "<html><body>",
13577            "<table><tr><td>ignored</td></tr></table>",
13578            "<table>",
13579            "<thead><tr><th>name</th><th>value</th><th>flag</th></tr></thead>",
13580            "<tbody>",
13581            "<tr><td>A&amp;B</td><td>1</td><td>True</td></tr>",
13582            "<tr><td>missing</td><td></td></tr>",
13583            "</tbody>",
13584            "</table>",
13585            "</body></html>",
13586        );
13587
13588        let frame = read_html_str_with_options(html, &HtmlReadOptions { table_index: 1 })
13589            .expect("read second table");
13590
13591        assert_eq!(
13592            frame
13593                .column_names()
13594                .into_iter()
13595                .map(String::as_str)
13596                .collect::<Vec<_>>(),
13597            vec!["name", "value", "flag"]
13598        );
13599        assert_eq!(
13600            frame.column("name").expect("name").values()[0],
13601            Scalar::Utf8("A&B".to_owned())
13602        );
13603        assert_eq!(
13604            frame.column("value").expect("value").values()[0],
13605            Scalar::Int64(1)
13606        );
13607        assert!(frame.column("value").expect("value").values()[1].is_missing());
13608        assert_eq!(
13609            frame.column("flag").expect("flag").values()[0],
13610            Scalar::Bool(true)
13611        );
13612        assert!(matches!(
13613            frame.column("flag").expect("flag").values()[1],
13614            Scalar::Null(NullKind::Null)
13615        ));
13616    }
13617
13618    #[test]
13619    fn html_reader_roundtrips_writer_output_as_columns() {
13620        let source = make_table_format_dataframe();
13621        let html = write_html_string(&source).expect("write html");
13622
13623        let frame = read_html_str(&html).expect("read writer html");
13624
13625        assert_eq!(
13626            frame
13627                .column_names()
13628                .into_iter()
13629                .map(String::as_str)
13630                .collect::<Vec<_>>(),
13631            vec!["Unnamed: 0", "name", "value"]
13632        );
13633        assert_eq!(
13634            frame.column("Unnamed: 0").expect("index column").values()[0],
13635            Scalar::Utf8("r&1".to_owned())
13636        );
13637        assert_eq!(
13638            frame.column("name").expect("name").values()[0],
13639            Scalar::Utf8("A|B".to_owned())
13640        );
13641        assert!(frame.column("value").expect("value").values()[0].is_missing());
13642        assert_eq!(
13643            frame.column("value").expect("value").values()[1],
13644            Scalar::Float64(2.0)
13645        );
13646    }
13647
13648    #[test]
13649    fn html_reader_path_reader_matches_string_reader() {
13650        use std::io::Write;
13651
13652        let html = "<table><tr><th>name</th></tr><tr><td>A</td></tr></table>\n";
13653        let path = std::env::temp_dir().join(format!(
13654            "fp_io_html_reader_{}_{}.html",
13655            std::process::id(),
13656            line!()
13657        ));
13658        let mut file = std::fs::OpenOptions::new()
13659            .write(true)
13660            .create_new(true)
13661            .open(&path)
13662            .expect("create html fixture");
13663        file.write_all(html.as_bytes()).expect("write html fixture");
13664
13665        let via_path = read_html(&path).expect("read path html");
13666        let via_str = read_html_str(html).expect("read string html");
13667
13668        assert_eq!(via_path.column_names(), via_str.column_names());
13669        assert_eq!(
13670            via_path.column("name").expect("path name").values(),
13671            via_str.column("name").expect("str name").values()
13672        );
13673    }
13674
13675    #[test]
13676    fn html_reader_rejects_no_table_duplicate_headers_and_wide_rows() {
13677        let err = read_html_str("<p>no table</p>").expect_err("missing table");
13678        assert!(matches!(err, IoError::Html(message) if message.contains("no table")));
13679
13680        let duplicate = "<table><tr><th>a</th><th>a</th></tr><tr><td>1</td><td>2</td></tr></table>";
13681        assert!(matches!(
13682            read_html_str(duplicate),
13683            Err(IoError::DuplicateColumnName(name)) if name == "a"
13684        ));
13685
13686        let wide = "<table><tr><th>a</th></tr><tr><td>1</td><td>2</td></tr></table>";
13687        let err = read_html_str(wide).expect_err("wide row");
13688        assert!(matches!(err, IoError::Html(message) if message.contains("row 0")));
13689    }
13690
13691    #[test]
13692    fn pickle_bytes_roundtrip_preserves_split_frame_shape() {
13693        let source = read_json_str(
13694            r#"{"columns":["name","value","flag"],"index":["r1","r2"],"data":[["alice",1,true],[null,2.5,false]]}"#,
13695            JsonOrient::Split,
13696        )
13697        .expect("source frame");
13698
13699        let bytes = write_pickle_bytes(&source).expect("write pickle bytes");
13700        assert!(!bytes.is_empty());
13701        let roundtrip = read_pickle_bytes(&bytes).expect("read pickle bytes");
13702
13703        assert_eq!(
13704            write_json_string(&roundtrip, JsonOrient::Split).expect("roundtrip json"),
13705            write_json_string(&source, JsonOrient::Split).expect("source json")
13706        );
13707    }
13708
13709    #[test]
13710    fn pickle_path_reader_matches_bytes_reader() {
13711        let source = make_table_format_dataframe();
13712        let path = std::env::temp_dir().join(format!(
13713            "fp_io_pickle_reader_{}_{}.pkl",
13714            std::process::id(),
13715            line!()
13716        ));
13717
13718        write_pickle(&source, &path).expect("write pickle path");
13719
13720        let via_path = read_pickle(&path).expect("read pickle path");
13721        let via_bytes =
13722            read_pickle_bytes(&std::fs::read(&path).expect("read pickle bytes from path"))
13723                .expect("read pickle bytes");
13724
13725        assert_eq!(
13726            write_json_string(&via_path, JsonOrient::Split).expect("path json"),
13727            write_json_string(&via_bytes, JsonOrient::Split).expect("bytes json")
13728        );
13729    }
13730
13731    #[test]
13732    fn pickle_protocol_v2_and_extension_aliases_roundtrip() {
13733        use super::DataFrameIoExt;
13734
13735        let source = make_table_format_dataframe();
13736        let options = PickleWriteOptions {
13737            protocol: PickleProtocol::V2,
13738        };
13739        let bytes = source
13740            .to_pickle_bytes_with_options(&options)
13741            .expect("trait pickle protocol v2");
13742        let roundtrip = read_pickle_bytes(&bytes).expect("read protocol v2");
13743
13744        assert_eq!(
13745            write_json_string(&roundtrip, JsonOrient::Split).expect("roundtrip json"),
13746            write_json_string(&source, JsonOrient::Split).expect("source json")
13747        );
13748        assert_eq!(
13749            source.to_pickle_bytes().expect("trait pickle bytes"),
13750            write_pickle_bytes(&source).expect("free pickle bytes")
13751        );
13752    }
13753
13754    #[test]
13755    fn series_pickle_extension_aliases_roundtrip_to_single_column_frame() {
13756        use super::SeriesIoExt;
13757
13758        let source = Series::from_values(
13759            "sales",
13760            vec!["r1".into(), "r2".into()],
13761            vec![Scalar::Int64(10), Scalar::Int64(12)],
13762        )
13763        .expect("source series");
13764
13765        let bytes = source.to_pickle_bytes().expect("series pickle bytes");
13766        let roundtrip = read_pickle_bytes(&bytes).expect("read series pickle frame");
13767        let names = roundtrip
13768            .column_names()
13769            .into_iter()
13770            .map(String::as_str)
13771            .collect::<Vec<_>>();
13772        assert_eq!(names, vec!["sales"]);
13773        assert_eq!(roundtrip.index().labels(), source.index().labels());
13774        assert_eq!(
13775            roundtrip.column("sales").expect("sales column").values(),
13776            source.values()
13777        );
13778
13779        let frame = source.to_frame(None).expect("series frame");
13780        assert_eq!(
13781            source.to_pickle_bytes().expect("trait pickle bytes"),
13782            write_pickle_bytes(&frame).expect("frame pickle bytes")
13783        );
13784
13785        let options = PickleWriteOptions {
13786            protocol: PickleProtocol::V2,
13787        };
13788        assert!(
13789            !source
13790                .to_pickle_bytes_with_options(&options)
13791                .expect("series pickle protocol v2")
13792                .is_empty()
13793        );
13794    }
13795
13796    #[test]
13797    fn series_csv_extension_aliases_preserve_default_index() {
13798        use super::SeriesIoExt;
13799
13800        let source = Series::from_values(
13801            "sales",
13802            vec!["r1".into(), "r2".into()],
13803            vec![Scalar::Int64(10), Scalar::Int64(12)],
13804        )
13805        .expect("source series");
13806
13807        let csv = source.to_csv_string().expect("series csv string");
13808        assert_eq!(csv, ",sales\nr1,10\nr2,12\n");
13809
13810        let no_index = source
13811            .to_csv_string_with_options(&CsvWriteOptions {
13812                include_index: false,
13813                ..CsvWriteOptions::default()
13814            })
13815            .expect("series csv without index");
13816        assert_eq!(no_index, "sales\n10\n12\n");
13817
13818        let path = std::env::temp_dir().join(format!(
13819            "fp_io_series_csv_{}_{}.csv",
13820            std::process::id(),
13821            line!()
13822        ));
13823        source.to_csv_file(&path).expect("series csv file");
13824        assert_eq!(
13825            std::fs::read_to_string(&path).expect("read series csv file"),
13826            csv
13827        );
13828    }
13829
13830    #[test]
13831    fn series_json_extension_aliases_use_series_orients() {
13832        use super::SeriesIoExt;
13833
13834        let source = Series::from_values(
13835            "sales",
13836            vec!["r1".into(), "r2".into()],
13837            vec![Scalar::Int64(10), Scalar::Int64(12)],
13838        )
13839        .expect("source series");
13840
13841        assert_eq!(
13842            source
13843                .to_json_string("records")
13844                .expect("series records json"),
13845            "[10,12]"
13846        );
13847
13848        let split: serde_json::Value =
13849            serde_json::from_str(&source.to_json_string("split").expect("series split json"))
13850                .expect("parse split json");
13851        assert_eq!(split["name"], "sales");
13852        assert_eq!(split["index"], serde_json::json!(["r1", "r2"]));
13853        assert_eq!(split["data"], serde_json::json!([10, 12]));
13854
13855        let path = std::env::temp_dir().join(format!(
13856            "fp_io_series_json_{}_{}.json",
13857            std::process::id(),
13858            line!()
13859        ));
13860        source
13861            .to_json_file(&path, "index")
13862            .expect("series json file");
13863        assert_eq!(
13864            std::fs::read_to_string(&path).expect("read series json file"),
13865            source.to_json("index").expect("series index json")
13866        );
13867    }
13868
13869    #[test]
13870    fn series_markdown_extension_aliases_forward_options() {
13871        use super::SeriesIoExt;
13872
13873        let source = Series::from_values(
13874            "sales",
13875            vec!["r1".into(), "r2".into()],
13876            vec![Scalar::Int64(10), Scalar::Null(NullKind::NaN)],
13877        )
13878        .expect("source series");
13879        let options = MarkdownWriteOptions {
13880            include_index: false,
13881            na_rep: "NA".to_owned(),
13882            index_label: Some("ignored".to_owned()),
13883        };
13884
13885        assert_eq!(
13886            source.to_markdown_string().expect("series markdown string"),
13887            write_markdown_string(&source.to_frame(None).expect("series frame"))
13888                .expect("frame markdown string")
13889        );
13890        assert_eq!(
13891            source
13892                .to_markdown_string_with_options(&options)
13893                .expect("series markdown options"),
13894            write_markdown_string_with_options(
13895                &source.to_frame(None).expect("series options frame"),
13896                &options,
13897            )
13898            .expect("frame markdown options")
13899        );
13900
13901        let path = std::env::temp_dir().join(format!(
13902            "fp_io_series_markdown_{}_{}.md",
13903            std::process::id(),
13904            line!()
13905        ));
13906        source
13907            .to_markdown_file_with_options(&path, &options)
13908            .expect("series markdown file");
13909        assert_eq!(
13910            std::fs::read_to_string(&path).expect("read series markdown file"),
13911            source
13912                .to_markdown_string_with_options(&options)
13913                .expect("series markdown options string")
13914        );
13915    }
13916
13917    #[test]
13918    fn series_latex_extension_aliases_forward_options() {
13919        use super::SeriesIoExt;
13920
13921        let source = Series::from_values(
13922            "sales&tax",
13923            vec!["r1".into(), "r2".into()],
13924            vec![Scalar::Utf8("a&b".into()), Scalar::Null(NullKind::NaN)],
13925        )
13926        .expect("source series");
13927        let options = LatexWriteOptions {
13928            include_index: false,
13929            na_rep: "NA".to_owned(),
13930            index_label: Some("ignored".to_owned()),
13931            escape: true,
13932        };
13933
13934        assert_eq!(
13935            source.to_latex_string().expect("series latex string"),
13936            write_latex_string(&source.to_frame(None).expect("series frame"))
13937                .expect("frame latex string")
13938        );
13939        assert_eq!(
13940            source
13941                .to_latex_string_with_options(&options)
13942                .expect("series latex options"),
13943            write_latex_string_with_options(
13944                &source.to_frame(None).expect("series options frame"),
13945                &options,
13946            )
13947            .expect("frame latex options")
13948        );
13949
13950        let path = std::env::temp_dir().join(format!(
13951            "fp_io_series_latex_{}_{}.tex",
13952            std::process::id(),
13953            line!()
13954        ));
13955        source
13956            .to_latex_file_with_options(&path, &options)
13957            .expect("series latex file");
13958        assert_eq!(
13959            std::fs::read_to_string(&path).expect("read series latex file"),
13960            source
13961                .to_latex_string_with_options(&options)
13962                .expect("series latex options string")
13963        );
13964    }
13965
13966    #[cfg(feature = "hdf5")]
13967    #[test]
13968    fn series_hdf5_extension_aliases_roundtrip_to_single_column_frame() {
13969        use super::SeriesIoExt;
13970
13971        let source = Series::from_values(
13972            "sales",
13973            vec!["r1".into(), "r2".into()],
13974            vec![Scalar::Int64(10), Scalar::Int64(12)],
13975        )
13976        .expect("source series");
13977        let expected = source.to_frame(None).expect("series frame");
13978
13979        let key_path = std::env::temp_dir().join(format!(
13980            "fp_io_series_hdf5_key_{}_{}.h5",
13981            std::process::id(),
13982            line!()
13983        ));
13984        source
13985            .to_hdf_key(&key_path, "series/data")
13986            .expect("series hdf key");
13987        assert!(
13988            read_hdf_key(&key_path, "series/data")
13989                .expect("read series hdf key")
13990                .equals(&expected)
13991        );
13992
13993        let default_path = std::env::temp_dir().join(format!(
13994            "fp_io_series_hdf5_default_{}_{}.h5",
13995            std::process::id(),
13996            line!()
13997        ));
13998        source
13999            .to_hdf_file(&default_path)
14000            .expect("series hdf default key");
14001        assert!(
14002            read_hdf(&default_path)
14003                .expect("read series hdf default")
14004                .equals(&expected)
14005        );
14006
14007        let options_path = std::env::temp_dir().join(format!(
14008            "fp_io_series_hdf5_options_{}_{}.h5",
14009            std::process::id(),
14010            line!()
14011        ));
14012        source
14013            .to_hdf_with_options(
14014                &options_path,
14015                &HdfWriteOptions {
14016                    key: "series/options".to_owned(),
14017                },
14018            )
14019            .expect("series hdf options");
14020        assert!(
14021            read_hdf_key(&options_path, "series/options")
14022                .expect("read series hdf options")
14023                .equals(&expected)
14024        );
14025    }
14026
14027    #[test]
14028    fn series_excel_extension_aliases_roundtrip_to_single_column_frame() {
14029        use super::SeriesIoExt;
14030
14031        let source = Series::from_values(
14032            "sales",
14033            vec!["r1".into(), "r2".into()],
14034            vec![Scalar::Int64(10), Scalar::Int64(12)],
14035        )
14036        .expect("source series");
14037
14038        let bytes = source.to_excel_bytes().expect("series excel bytes");
14039        let roundtrip =
14040            read_excel_bytes(&bytes, &ExcelReadOptions::default()).expect("read series excel");
14041        let names = roundtrip
14042            .column_names()
14043            .into_iter()
14044            .map(String::as_str)
14045            .collect::<Vec<_>>();
14046        assert_eq!(names, vec!["column_0", "sales"]);
14047        assert_eq!(
14048            roundtrip.column("column_0").expect("index column").values(),
14049            &[Scalar::Utf8("r1".into()), Scalar::Utf8("r2".into())]
14050        );
14051        assert_eq!(
14052            roundtrip.column("sales").expect("sales column").values(),
14053            source.values()
14054        );
14055
14056        let frame = source.to_frame(None).expect("series frame");
14057        assert_eq!(
14058            source.to_excel_bytes().expect("trait excel bytes"),
14059            write_excel_bytes(&frame).expect("frame excel bytes")
14060        );
14061
14062        let options = ExcelWriteOptions {
14063            index: false,
14064            ..ExcelWriteOptions::default()
14065        };
14066        let no_index_bytes = source
14067            .to_excel_bytes_with_options(&options)
14068            .expect("series excel index false");
14069        let no_index = read_excel_bytes(&no_index_bytes, &ExcelReadOptions::default())
14070            .expect("read no-index series excel");
14071        assert_eq!(no_index.column_names(), vec!["sales"]);
14072        assert_eq!(no_index.index().len(), source.index().len());
14073    }
14074
14075    #[test]
14076    fn pickle_reader_rejects_malformed_and_foreign_payloads() {
14077        let err = read_pickle_bytes(b"not a pickle").expect_err("malformed pickle");
14078        assert!(matches!(err, IoError::Pickle(_)));
14079
14080        let foreign = serde_pickle::to_vec(
14081            &serde_json::json!({"payload": {"columns": [], "index": [], "data": []}}),
14082            serde_pickle::SerOptions::new(),
14083        )
14084        .expect("foreign pickle");
14085        let err = read_pickle_bytes(&foreign).expect_err("foreign pickle");
14086        assert!(matches!(
14087            err,
14088            IoError::Pickle(message) if message.contains("format marker")
14089        ));
14090    }
14091
14092    #[cfg(feature = "hdf5")]
14093    #[test]
14094    fn hdf5_path_roundtrip_preserves_snapshot_frame() {
14095        let source = make_table_format_dataframe();
14096        let path = std::env::temp_dir().join(format!(
14097            "fp_io_hdf5_default_{}_{}.h5",
14098            std::process::id(),
14099            line!()
14100        ));
14101
14102        write_hdf(&source, &path).expect("write hdf default key");
14103        let roundtrip = read_hdf(&path).expect("read hdf default key");
14104
14105        assert_eq!(
14106            write_json_string(&roundtrip, JsonOrient::Split).expect("roundtrip json"),
14107            write_json_string(&source, JsonOrient::Split).expect("source json")
14108        );
14109    }
14110
14111    #[cfg(feature = "hdf5")]
14112    #[test]
14113    fn hdf5_custom_key_and_extension_aliases_roundtrip() {
14114        use super::DataFrameIoExt;
14115
14116        let source = make_test_dataframe();
14117        let free_path = std::env::temp_dir().join(format!(
14118            "fp_io_hdf5_custom_free_{}_{}.h5",
14119            std::process::id(),
14120            line!()
14121        ));
14122        let trait_path = std::env::temp_dir().join(format!(
14123            "fp_io_hdf5_custom_trait_{}_{}.h5",
14124            std::process::id(),
14125            line!()
14126        ));
14127        let default_path = std::env::temp_dir().join(format!(
14128            "fp_io_hdf5_custom_default_{}_{}.h5",
14129            std::process::id(),
14130            line!()
14131        ));
14132        let write_options = HdfWriteOptions {
14133            key: "tables/snapshot".to_owned(),
14134        };
14135
14136        write_hdf_with_options(&source, &free_path, &write_options).expect("write custom key");
14137        let roundtrip = read_hdf_with_options(
14138            &free_path,
14139            &HdfReadOptions {
14140                key: "/tables/snapshot/".to_owned(),
14141            },
14142        )
14143        .expect("read custom key with slash aliases");
14144        assert!(roundtrip.equals(&source));
14145
14146        source
14147            .to_hdf_key(&trait_path, "nested/frame")
14148            .expect("trait hdf key");
14149        assert!(
14150            read_hdf_key(&trait_path, "nested/frame")
14151                .expect("read trait hdf key")
14152                .equals(&source)
14153        );
14154
14155        source
14156            .to_hdf_file(&default_path)
14157            .expect("trait hdf default key");
14158        assert!(
14159            read_hdf(&default_path)
14160                .expect("read trait hdf default")
14161                .equals(&source)
14162        );
14163    }
14164
14165    #[cfg(feature = "hdf5")]
14166    #[test]
14167    fn hdf5_row_multiindex_roundtrip_restores_logical_row_axis() {
14168        let frame = make_row_multiindex_test_dataframe();
14169        let path = std::env::temp_dir().join(format!(
14170            "fp_io_hdf5_multiindex_{}_{}.h5",
14171            std::process::id(),
14172            line!()
14173        ));
14174
14175        write_hdf_key(&frame, &path, "axes/frame").expect("write hdf multiindex");
14176        let roundtrip = read_hdf_key(&path, "axes/frame").expect("read hdf multiindex");
14177
14178        assert!(roundtrip.equals(&frame));
14179        assert!(roundtrip.column("__index_level_0__").is_none());
14180        assert_eq!(
14181            roundtrip
14182                .row_multiindex()
14183                .expect("row multiindex should be restored")
14184                .get_level_values(0)
14185                .unwrap()
14186                .labels(),
14187            frame
14188                .row_multiindex()
14189                .expect("source row multiindex")
14190                .get_level_values(0)
14191                .unwrap()
14192                .labels()
14193        );
14194    }
14195
14196    #[cfg(feature = "hdf5")]
14197    #[test]
14198    fn hdf5_reader_rejects_invalid_keys_and_missing_payloads() {
14199        let frame = make_test_dataframe();
14200        let path = std::env::temp_dir().join(format!(
14201            "fp_io_hdf5_missing_payload_{}_{}.h5",
14202            std::process::id(),
14203            line!()
14204        ));
14205
14206        let file = hdf5::File::create(&path).expect("create hdf shell");
14207        file.create_group("frame")
14208            .expect("create empty frame group");
14209        file.flush().expect("flush hdf shell");
14210        drop(file);
14211
14212        let err = read_hdf(&path).expect_err("missing payload should fail");
14213        assert!(matches!(
14214            err,
14215            IoError::Hdf5(message) if message.contains("missing FrankenPandas payload dataset")
14216        ));
14217
14218        let err = write_hdf_key(&frame, &path, "../bad").expect_err("invalid key should fail");
14219        assert!(matches!(
14220            err,
14221            IoError::Hdf5(message) if message.contains("invalid hdf5 key")
14222        ));
14223    }
14224
14225    fn make_stata_dataframe() -> DataFrame {
14226        let mut columns = BTreeMap::new();
14227        columns.insert(
14228            "id".to_owned(),
14229            Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)])
14230                .expect("id column"),
14231        );
14232        columns.insert(
14233            "score".to_owned(),
14234            Column::from_values(vec![
14235                Scalar::Float64(1.5),
14236                Scalar::Null(NullKind::NaN),
14237                Scalar::Float64(3.25),
14238            ])
14239            .expect("score column"),
14240        );
14241        columns.insert(
14242            "flag".to_owned(),
14243            Column::from_values(vec![
14244                Scalar::Bool(true),
14245                Scalar::Bool(false),
14246                Scalar::Bool(true),
14247            ])
14248            .expect("flag column"),
14249        );
14250        columns.insert(
14251            "label".to_owned(),
14252            Column::from_values(vec![
14253                Scalar::Utf8("alpha".to_owned()),
14254                Scalar::Utf8("beta".to_owned()),
14255                Scalar::Utf8("gamma".to_owned()),
14256            ])
14257            .expect("label column"),
14258        );
14259
14260        DataFrame::new_with_column_order(
14261            Index::new(vec![
14262                IndexLabel::Utf8("row_a".to_owned()),
14263                IndexLabel::Utf8("row_b".to_owned()),
14264                IndexLabel::Utf8("row_c".to_owned()),
14265            ]),
14266            columns,
14267            vec![
14268                "id".to_owned(),
14269                "score".to_owned(),
14270                "flag".to_owned(),
14271                "label".to_owned(),
14272            ],
14273        )
14274        .expect("stata frame")
14275    }
14276
14277    #[test]
14278    fn stata_bytes_roundtrip_preserves_supported_columns() {
14279        let source = make_stata_dataframe();
14280        let bytes = write_stata_bytes(&source).expect("write stata bytes");
14281        assert!(!bytes.is_empty());
14282
14283        let roundtrip = read_stata_bytes(&bytes).expect("read stata bytes");
14284
14285        assert_eq!(
14286            roundtrip
14287                .column_names()
14288                .into_iter()
14289                .map(String::as_str)
14290                .collect::<Vec<_>>(),
14291            vec!["index", "id", "score", "flag", "label"]
14292        );
14293        assert_eq!(
14294            roundtrip.column("index").expect("index").values(),
14295            &[
14296                Scalar::Utf8("row_a".to_owned()),
14297                Scalar::Utf8("row_b".to_owned()),
14298                Scalar::Utf8("row_c".to_owned())
14299            ]
14300        );
14301        assert_eq!(
14302            roundtrip.column("id").expect("id").values(),
14303            &[Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)]
14304        );
14305        assert_eq!(
14306            roundtrip.column("score").expect("score").values(),
14307            &[
14308                Scalar::Float64(1.5),
14309                Scalar::Null(NullKind::NaN),
14310                Scalar::Float64(3.25)
14311            ]
14312        );
14313        assert_eq!(
14314            roundtrip.column("flag").expect("flag").values(),
14315            &[Scalar::Int64(1), Scalar::Int64(0), Scalar::Int64(1)]
14316        );
14317        assert_eq!(
14318            roundtrip.column("label").expect("label").values(),
14319            &[
14320                Scalar::Utf8("alpha".to_owned()),
14321                Scalar::Utf8("beta".to_owned()),
14322                Scalar::Utf8("gamma".to_owned())
14323            ]
14324        );
14325    }
14326
14327    #[test]
14328    fn stata_path_reader_matches_bytes_reader() {
14329        let source = make_stata_dataframe();
14330        let path = std::env::temp_dir().join(format!(
14331            "fp_io_stata_reader_{}_{}.dta",
14332            std::process::id(),
14333            line!()
14334        ));
14335
14336        write_stata(&source, &path).expect("write stata path");
14337
14338        let via_path = read_stata(&path).expect("read stata path");
14339        let via_bytes =
14340            read_stata_bytes(&std::fs::read(&path).expect("read stata bytes from path"))
14341                .expect("read stata bytes");
14342
14343        assert_eq!(via_path.column_names(), via_bytes.column_names());
14344        for name in via_path.column_names() {
14345            assert_eq!(
14346                via_path.column(name).expect("path column").values(),
14347                via_bytes.column(name).expect("bytes column").values()
14348            );
14349        }
14350    }
14351
14352    #[test]
14353    fn stata_extension_aliases_and_no_index_option_roundtrip() {
14354        use super::DataFrameIoExt;
14355
14356        let source = make_stata_dataframe();
14357        let options = StataWriteOptions {
14358            include_index: false,
14359            index_label: Some("ignored".to_owned()),
14360        };
14361        let bytes = source
14362            .to_stata_bytes_with_options(&options)
14363            .expect("trait stata bytes without index");
14364        let roundtrip = read_stata_bytes(&bytes).expect("read no-index stata");
14365
14366        assert_eq!(
14367            roundtrip
14368                .column_names()
14369                .into_iter()
14370                .map(String::as_str)
14371                .collect::<Vec<_>>(),
14372            vec!["id", "score", "flag", "label"]
14373        );
14374
14375        let path = std::env::temp_dir().join(format!(
14376            "fp_io_stata_trait_{}_{}.dta",
14377            std::process::id(),
14378            line!()
14379        ));
14380        source
14381            .to_stata_with_options(&path, &options)
14382            .expect("trait stata path without index");
14383        let via_path = read_stata(&path).expect("read trait stata path");
14384        assert_eq!(via_path.column_names(), roundtrip.column_names());
14385
14386        assert_eq!(
14387            source.to_stata_bytes().expect("trait stata bytes"),
14388            write_stata_bytes(&source).expect("free stata bytes")
14389        );
14390    }
14391
14392    #[test]
14393    fn stata_writer_rejects_invalid_variable_names_and_malformed_input() {
14394        let mut columns = BTreeMap::new();
14395        columns.insert(
14396            "bad-name".to_owned(),
14397            Column::from_values(vec![Scalar::Int64(1)]).expect("bad column"),
14398        );
14399        let frame = DataFrame::new_with_column_order(
14400            Index::from_i64(vec![0]),
14401            columns,
14402            vec!["bad-name".to_owned()],
14403        )
14404        .expect("frame with invalid stata column");
14405
14406        let err = write_stata_bytes(&frame).expect_err("invalid stata variable name");
14407        assert!(matches!(
14408            err,
14409            IoError::Stata(message) if message.contains("invalid Stata variable name")
14410        ));
14411
14412        let source = make_stata_dataframe();
14413        let err = write_stata_bytes_with_options(
14414            &source,
14415            &StataWriteOptions {
14416                include_index: true,
14417                index_label: Some("1bad".to_owned()),
14418            },
14419        )
14420        .expect_err("invalid index variable name");
14421        assert!(matches!(
14422            err,
14423            IoError::Stata(message) if message.contains("first character")
14424        ));
14425
14426        let err = read_stata_bytes(b"not a dta").expect_err("malformed stata");
14427        assert!(matches!(err, IoError::Stata(_)));
14428    }
14429
14430    #[test]
14431    fn xml_writer_defaults_to_index_and_escapes_values() {
14432        let frame = make_table_format_dataframe();
14433
14434        let out = write_xml_string(&frame).expect("xml");
14435
14436        assert_eq!(
14437            out,
14438            concat!(
14439                "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n",
14440                "<data>\n",
14441                "  <row>\n",
14442                "    <row>r&amp;1</row>\n",
14443                "    <name>A|B</name>\n",
14444                "    <value/>\n",
14445                "  </row>\n",
14446                "  <row>\n",
14447                "    <row>r_2</row>\n",
14448                "    <name>under_score</name>\n",
14449                "    <value>2.0</value>\n",
14450                "  </row>\n",
14451                "</data>\n",
14452            )
14453        );
14454    }
14455
14456    #[test]
14457    fn xml_writer_options_can_omit_index_and_reject_bad_names() {
14458        let frame = make_table_format_dataframe();
14459
14460        let out = write_xml_string_with_options(
14461            &frame,
14462            &XmlWriteOptions {
14463                include_index: false,
14464                root_name: "records".to_owned(),
14465                row_name: "entry".to_owned(),
14466                index_label: Some("ignored".to_owned()),
14467            },
14468        )
14469        .expect("xml");
14470
14471        assert_eq!(
14472            out,
14473            concat!(
14474                "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n",
14475                "<records>\n",
14476                "  <entry>\n",
14477                "    <name>A|B</name>\n",
14478                "    <value/>\n",
14479                "  </entry>\n",
14480                "  <entry>\n",
14481                "    <name>under_score</name>\n",
14482                "    <value>2.0</value>\n",
14483                "  </entry>\n",
14484                "</records>\n",
14485            )
14486        );
14487
14488        let err = write_xml_string_with_options(
14489            &frame,
14490            &XmlWriteOptions {
14491                root_name: "bad name".to_owned(),
14492                ..Default::default()
14493            },
14494        )
14495        .expect_err("invalid xml name");
14496        assert!(matches!(err, IoError::Xml(message) if message.contains("bad name")));
14497    }
14498
14499    #[test]
14500    fn xml_writer_escapes_text_like_pandas_etree() {
14501        let mut columns = BTreeMap::new();
14502        columns.insert(
14503            "name".to_owned(),
14504            Column::from_values(vec![Scalar::Utf8(
14505                "A&B <tag> \"quote\" it's\r\nnext".to_owned(),
14506            )])
14507            .expect("name column"),
14508        );
14509        let frame = DataFrame::new_with_column_order(
14510            Index::new(vec![IndexLabel::Utf8("idx".to_owned())]),
14511            columns,
14512            vec!["name".to_owned()],
14513        )
14514        .expect("xml escape frame");
14515
14516        assert_eq!(
14517            write_xml_string_with_options(
14518                &frame,
14519                &XmlWriteOptions {
14520                    include_index: false,
14521                    ..Default::default()
14522                },
14523            )
14524            .expect("xml"),
14525            concat!(
14526                "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n",
14527                "<data>\n",
14528                "  <row>\n",
14529                "    <name>A&amp;B &lt;tag&gt; \"quote\" it's\n",
14530                "next</name>\n",
14531                "  </row>\n",
14532                "</data>\n",
14533            )
14534        );
14535    }
14536
14537    #[test]
14538    fn xml_writer_file_output_and_extension_aliases_match_free_functions() {
14539        use super::DataFrameIoExt;
14540
14541        let frame = make_table_format_dataframe();
14542        let path = std::env::temp_dir().join(format!(
14543            "fp_io_xml_writer_{}_{}.xml",
14544            std::process::id(),
14545            line!()
14546        ));
14547
14548        write_xml(&frame, &path).expect("write xml");
14549        assert_eq!(
14550            std::fs::read_to_string(&path).expect("read xml"),
14551            write_xml_string(&frame).expect("xml string")
14552        );
14553        assert_eq!(
14554            frame.to_xml_string().expect("trait xml string"),
14555            write_xml_string(&frame).expect("free xml string")
14556        );
14557
14558        let trait_path = std::env::temp_dir().join(format!(
14559            "fp_io_xml_writer_trait_alias_{}_{}.xml",
14560            std::process::id(),
14561            line!()
14562        ));
14563        frame.to_xml(&trait_path).expect("trait xml alias");
14564        assert_eq!(
14565            std::fs::read_to_string(&trait_path).expect("read trait xml alias"),
14566            write_xml_string(&frame).expect("free xml string")
14567        );
14568
14569        let no_index_options = XmlWriteOptions {
14570            include_index: false,
14571            ..Default::default()
14572        };
14573        let no_index_path = std::env::temp_dir().join(format!(
14574            "fp_io_xml_writer_no_index_{}_{}.xml",
14575            std::process::id(),
14576            line!()
14577        ));
14578        frame
14579            .to_xml_file_with_options(&no_index_path, &no_index_options)
14580            .expect("trait xml file");
14581        assert_eq!(
14582            std::fs::read_to_string(&no_index_path).expect("read trait xml"),
14583            write_xml_string_with_options(&frame, &no_index_options).expect("free xml options")
14584        );
14585    }
14586
14587    #[test]
14588    fn xml_reader_parses_pandas_row_shape_and_empty_values() {
14589        let xml = concat!(
14590            "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n",
14591            "<data>\n",
14592            "  <row>\n",
14593            "    <index>0</index>\n",
14594            "    <a>1</a>\n",
14595            "    <b/>\n",
14596            "  </row>\n",
14597            "  <row>\n",
14598            "    <index>1</index>\n",
14599            "    <a>2.5</a>\n",
14600            "    <b>x</b>\n",
14601            "  </row>\n",
14602            "</data>\n",
14603        );
14604
14605        let frame = read_xml_str(xml).expect("read xml");
14606
14607        assert_eq!(
14608            frame
14609                .column_names()
14610                .into_iter()
14611                .map(String::as_str)
14612                .collect::<Vec<_>>(),
14613            vec!["index", "a", "b"]
14614        );
14615        assert_eq!(
14616            frame.index().labels(),
14617            &[IndexLabel::Int64(0), IndexLabel::Int64(1)]
14618        );
14619        assert_eq!(
14620            frame.column("index").expect("index").values()[0],
14621            Scalar::Int64(0)
14622        );
14623        assert_eq!(
14624            frame.column("a").expect("a").values()[1],
14625            Scalar::Float64(2.5)
14626        );
14627        assert!(matches!(
14628            frame.column("b").expect("b").values()[0],
14629            Scalar::Null(NullKind::Null)
14630        ));
14631        assert_eq!(
14632            frame.column("b").expect("b").values()[1],
14633            Scalar::Utf8("x".to_owned())
14634        );
14635    }
14636
14637    #[test]
14638    fn xml_reader_roundtrips_writer_output_as_columns() {
14639        let source = make_table_format_dataframe();
14640        let xml = write_xml_string(&source).expect("write xml");
14641
14642        let frame = read_xml_str(&xml).expect("read writer xml");
14643
14644        assert_eq!(
14645            frame
14646                .column_names()
14647                .into_iter()
14648                .map(String::as_str)
14649                .collect::<Vec<_>>(),
14650            vec!["row", "name", "value"]
14651        );
14652        assert_eq!(
14653            frame.column("row").expect("row").values()[0],
14654            Scalar::Utf8("r&1".to_owned())
14655        );
14656        assert_eq!(
14657            frame.column("name").expect("name").values()[0],
14658            Scalar::Utf8("A|B".to_owned())
14659        );
14660        assert!(frame.column("value").expect("value").values()[0].is_missing());
14661        assert_eq!(
14662            frame.column("value").expect("value").values()[1],
14663            Scalar::Float64(2.0)
14664        );
14665    }
14666
14667    #[test]
14668    fn xml_reader_unescapes_text_and_supports_custom_row_names() {
14669        let xml = concat!(
14670            "<records>\n",
14671            "  <entry><name>A&amp;B &lt;tag&gt; \"quote\" it's</name><flag>True</flag></entry>\n",
14672            "  <entry><name>line\n",
14673            "next</name><flag>false</flag></entry>\n",
14674            "</records>\n",
14675        );
14676
14677        let frame = read_xml_str_with_options(
14678            xml,
14679            &XmlReadOptions {
14680                row_name: "entry".to_owned(),
14681            },
14682        )
14683        .expect("read custom xml");
14684
14685        assert_eq!(
14686            frame.column("name").expect("name").values()[0],
14687            Scalar::Utf8("A&B <tag> \"quote\" it's".to_owned())
14688        );
14689        assert_eq!(
14690            frame.column("name").expect("name").values()[1],
14691            Scalar::Utf8("line\nnext".to_owned())
14692        );
14693        assert_eq!(
14694            frame.column("flag").expect("flag").values()[0],
14695            Scalar::Bool(true)
14696        );
14697        assert_eq!(
14698            frame.column("flag").expect("flag").values()[1],
14699            Scalar::Bool(false)
14700        );
14701    }
14702
14703    #[test]
14704    fn xml_reader_path_reader_matches_string_reader() {
14705        use std::io::Write;
14706
14707        let xml = "<data><row><name>A</name></row></data>\n";
14708        let path = std::env::temp_dir().join(format!(
14709            "fp_io_xml_reader_{}_{}.xml",
14710            std::process::id(),
14711            line!()
14712        ));
14713        let mut file = std::fs::OpenOptions::new()
14714            .write(true)
14715            .create_new(true)
14716            .open(&path)
14717            .expect("create xml fixture");
14718        file.write_all(xml.as_bytes()).expect("write xml fixture");
14719
14720        let via_path = read_xml(&path).expect("read path xml");
14721        let via_str = read_xml_str(xml).expect("read string xml");
14722
14723        assert_eq!(via_path.column_names(), via_str.column_names());
14724        assert_eq!(
14725            via_path.column("name").expect("path name").values(),
14726            via_str.column("name").expect("str name").values()
14727        );
14728    }
14729
14730    #[test]
14731    fn xml_reader_rejects_malformed_nested_and_duplicate_fields() {
14732        let malformed = "<data><row><name>A</row></data>";
14733        assert!(matches!(read_xml_str(malformed), Err(IoError::Xml(_))));
14734
14735        let nested = "<data><row><name><inner>A</inner></name></row></data>";
14736        let err = read_xml_str(nested).expect_err("nested field error");
14737        assert!(matches!(err, IoError::Xml(message) if message.contains("nested xml element")));
14738
14739        let duplicate = "<data><row><name>A</name><name>B</name></row></data>";
14740        let err = read_xml_str(duplicate).expect_err("duplicate field error");
14741        assert!(matches!(err, IoError::Xml(message) if message.contains("duplicate xml field")));
14742    }
14743
14744    // === AG-07-T: CSV Parser Optimization Tests ===
14745
14746    #[test]
14747    fn test_csv_vec_based_column_order() {
14748        // Verify Vec-based parser preserves header-to-data mapping exactly.
14749        // BTreeMap sorts alphabetically, so we use alpha-ordered headers.
14750        let input = "alpha,bravo,charlie\n1,2,3\n4,5,6\n";
14751        let frame = read_csv_str(input).expect("parse");
14752        let keys: Vec<&String> = frame.columns().keys().collect();
14753        assert_eq!(keys, &["alpha", "bravo", "charlie"]);
14754        assert_eq!(frame.column("alpha").unwrap().values()[0], Scalar::Int64(1));
14755        assert_eq!(frame.column("bravo").unwrap().values()[0], Scalar::Int64(2));
14756        assert_eq!(
14757            frame.column("charlie").unwrap().values()[1],
14758            Scalar::Int64(6)
14759        );
14760        eprintln!("[TEST] test_csv_vec_based_column_order | rows=2 cols=3 parse_ok=true | PASS");
14761    }
14762
14763    #[test]
14764    fn read_csv_object_fallback_preserves_original_text() {
14765        // pandas does column-level inference: when a column falls back to object
14766        // dtype, every non-NA cell keeps its VERBATIM source text. A bool-like
14767        // token in non-canonical case ("true") or a zero-padded number ("01")
14768        // must survive unchanged once the column is object. Verified vs live
14769        // pandas 2.2.3: read_csv('c\ntrue\nfalse\nmaybe\n')['c'] is
14770        // ['true','false','maybe'] (object), and '01'/'02' stay '01'/'02'.
14771        let cases: &[(&str, &str)] = &[
14772            // Uniform native columns are unaffected.
14773            ("c\n1\n2\n3\n", "c\n1\n2\n3\n"),
14774            ("c\ntrue\nfalse\n", "c\nTrue\nFalse\n"), // pure bool -> bool dtype
14775            // Object fallbacks keep original literals.
14776            ("c\n1\n2\nabc\n", "c\n1\n2\nabc\n"),
14777            ("c\ntrue\nfalse\nmaybe\n", "c\ntrue\nfalse\nmaybe\n"),
14778            ("c\nTrue\nFalse\nmaybe\n", "c\nTrue\nFalse\nmaybe\n"),
14779            ("c\n01\n02\nabc\n", "c\n01\n02\nabc\n"),
14780        ];
14781        for (input, expected_csv) in cases {
14782            let frame = read_csv_str(input).expect("read");
14783            let out = write_csv_string(&frame).expect("write");
14784            assert_eq!(
14785                &out, expected_csv,
14786                "round-trip mismatch for input {input:?}"
14787            );
14788        }
14789    }
14790
14791    #[test]
14792    fn read_csv_typed_numeric_fast_path_promotes_in_one_pass() {
14793        let input = "i,f\n1,0\n2,0.5\n3,1.25\n";
14794        let headers = vec!["i".to_owned(), "f".to_owned()];
14795
14796        let fast = super::try_read_csv_str_typed_numeric(input, &headers)
14797            .expect("typed parse")
14798            .expect("numeric fast path");
14799        assert_eq!(fast.column("i").expect("i").dtype(), DType::Int64);
14800        assert_eq!(fast.column("f").expect("f").dtype(), DType::Float64);
14801        assert_eq!(fast.column("i").expect("i").values()[2], Scalar::Int64(3));
14802        assert_eq!(
14803            fast.column("f").expect("f").values()[2],
14804            Scalar::Float64(1.25)
14805        );
14806
14807        let object_input = "c\n01\nabc\n";
14808        let object_headers = vec!["c".to_owned()];
14809        assert!(
14810            super::try_read_csv_str_typed_numeric(object_input, &object_headers)
14811                .expect("object probe")
14812                .is_none()
14813        );
14814        let object_frame = read_csv_str(object_input).expect("fallback read");
14815        assert_eq!(object_frame.index().int64_unit_range_labels(), Some((0, 2)));
14816        assert_eq!(
14817            write_csv_string(&object_frame).expect("fallback write"),
14818            object_input
14819        );
14820    }
14821
14822    #[test]
14823    fn read_csv_simple_typed_numeric_fast_path_builds_typed_columns() {
14824        let input = "i,f\n1,0\n2,0.5\n3,1.25\n";
14825        let headers = vec!["i".to_owned(), "f".to_owned()];
14826
14827        let fast = super::try_read_csv_str_simple_typed_numeric(input, &headers)
14828            .expect("simple typed parse")
14829            .expect("simple numeric fast path");
14830
14831        assert_eq!(fast.column("i").expect("i").dtype(), DType::Int64);
14832        assert_eq!(fast.column("f").expect("f").dtype(), DType::Float64);
14833        assert_eq!(fast.index().int64_unit_range_labels(), Some((0, 3)));
14834        assert_eq!(fast.index().labels()[2], IndexLabel::Int64(2));
14835        assert_eq!(fast.column("i").expect("i").values()[2], Scalar::Int64(3));
14836        assert_eq!(
14837            fast.column("f").expect("f").values()[2],
14838            Scalar::Float64(1.25)
14839        );
14840    }
14841
14842    #[test]
14843    fn read_csv_mixed_quoted_unquoted_numeric_infers_numeric_3gen4() {
14844        // br-frankenpandas-3gen4: quoting is per-field CSV syntax stripped before
14845        // type inference, so a column mixing quoted + unquoted numbers still
14846        // infers a numeric dtype (pandas parity).
14847        let int_col = read_csv_str("x\n1\n\"2\"\n3\n").expect("read int");
14848        let xi = int_col.column("x").expect("x");
14849        assert_eq!(
14850            xi.dtype(),
14851            DType::Int64,
14852            "mixed quoted/unquoted ints -> Int64"
14853        );
14854        assert_eq!(
14855            xi.values(),
14856            &[Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)]
14857        );
14858
14859        // Mixed int + quoted float -> Float64 (one float promotes the column).
14860        let float_col = read_csv_str("y\n1\n\"2.5\"\n3\n").expect("read float");
14861        let yf = float_col.column("y").expect("y");
14862        assert_eq!(
14863            yf.dtype(),
14864            DType::Float64,
14865            "mixed int + quoted float -> Float64"
14866        );
14867        assert_eq!(
14868            yf.values(),
14869            &[
14870                Scalar::Float64(1.0),
14871                Scalar::Float64(2.5),
14872                Scalar::Float64(3.0)
14873            ]
14874        );
14875    }
14876
14877    #[test]
14878    fn read_csv_simple_typed_numeric_fast_path_rejects_quoted_fields() {
14879        let input = "x\n\"1.5\"\n";
14880        let headers = vec!["x".to_owned()];
14881
14882        assert!(
14883            super::try_read_csv_str_simple_typed_numeric(input, &headers)
14884                .expect("simple probe")
14885                .is_none()
14886        );
14887
14888        let frame = read_csv_str(input).expect("fallback read");
14889        assert_eq!(frame.column("x").expect("x").dtype(), DType::Float64);
14890        assert_eq!(
14891            frame.column("x").expect("x").values(),
14892            &[Scalar::Float64(1.5)]
14893        );
14894    }
14895
14896    #[test]
14897    fn read_csv_simple_typed_numeric_fast_path_accepts_crlf_rows() {
14898        let input = "i,f\n1,0\r\n2,0.5\r\n";
14899        let headers = vec!["i".to_owned(), "f".to_owned()];
14900
14901        let fast = super::try_read_csv_str_simple_typed_numeric(input, &headers)
14902            .expect("simple typed parse")
14903            .expect("simple numeric fast path");
14904
14905        assert_eq!(fast.len(), 2);
14906        assert_eq!(fast.column("i").expect("i").values()[1], Scalar::Int64(2));
14907        assert_eq!(
14908            fast.column("f").expect("f").values()[1],
14909            Scalar::Float64(0.5)
14910        );
14911    }
14912
14913    #[test]
14914    fn read_csv_simple_parallel_chunks_preserve_order_and_promotion() {
14915        use std::fmt::Write as _;
14916
14917        let headers = vec!["i".to_owned(), "f".to_owned()];
14918        let mut data = String::new();
14919        for row in 0..32 {
14920            let float_value = row as f64 * 0.25;
14921            writeln!(data, "{row},{float_value}").expect("write row");
14922        }
14923
14924        let (columns, row_count) =
14925            super::parse_simple_numeric_csv_parallel_chunks(data.as_bytes(), headers.len(), 3)
14926                .expect("parallel chunk parse");
14927        let frame = super::build_typed_numeric_csv_frame(&headers, columns, row_count)
14928            .expect("frame build");
14929
14930        assert_eq!(frame.len(), 32);
14931        assert_eq!(frame.column("i").expect("i").dtype(), DType::Int64);
14932        assert_eq!(frame.column("f").expect("f").dtype(), DType::Float64);
14933        assert_eq!(frame.column("i").expect("i").values()[0], Scalar::Int64(0));
14934        assert_eq!(
14935            frame.column("i").expect("i").values()[31],
14936            Scalar::Int64(31)
14937        );
14938        assert_eq!(
14939            frame.column("f").expect("f").values()[31],
14940            Scalar::Float64(7.75)
14941        );
14942    }
14943
14944    #[test]
14945    fn read_csv_typed_numeric_fast_path_rejects_non_all_valid_numeric_semantics() {
14946        let headers = vec!["x".to_owned()];
14947        for input in [
14948            "x\nNaN\n1.0\n",
14949            "x\nNAN\n1.0\n",
14950            "x\n+NaN\n1.0\n",
14951            "x\n NaN \n1.0\n",
14952            "x\n\"NAN\"\n1.0\n",
14953            "x\ntrue\nfalse\n",
14954            "x\n \n1\n",
14955        ] {
14956            assert!(
14957                super::try_read_csv_str_typed_numeric(input, &headers)
14958                    .expect("probe")
14959                    .is_none(),
14960                "fast path must reject {input:?}"
14961            );
14962        }
14963
14964        let nan_frame = read_csv_str("x\nNaN\n1.0\n").expect("fallback nan");
14965        assert_eq!(
14966            nan_frame.column("x").expect("x").values(),
14967            &[Scalar::Null(NullKind::NaN), Scalar::Float64(1.0)]
14968        );
14969
14970        let bool_frame = read_csv_str("x\ntrue\nfalse\n").expect("fallback bool");
14971        assert_eq!(
14972            bool_frame.column("x").expect("x").values(),
14973            &[Scalar::Bool(true), Scalar::Bool(false)]
14974        );
14975
14976        let padded_nan_frame = read_csv_str("x\n NaN \n1.0\n").expect("fallback padded nan");
14977        let padded_nan_column = padded_nan_frame.column("x").expect("x");
14978        assert!(padded_nan_column.has_nulls());
14979        assert!(!padded_nan_column.validity().get(0));
14980        assert!(padded_nan_column.values()[0].is_missing());
14981    }
14982
14983    #[test]
14984    fn read_csv_typed_numeric_fast_path_keeps_all_valid_float_edges() {
14985        let input = "x\n-0.0\ninf\n-inf\n1\n";
14986        let headers = vec!["x".to_owned()];
14987        let frame = super::try_read_csv_str_typed_numeric(input, &headers)
14988            .expect("typed parse")
14989            .expect("numeric fast path");
14990        let column = frame.column("x").expect("x");
14991
14992        assert_eq!(column.dtype(), DType::Float64);
14993        assert!(!column.has_nulls());
14994        assert!(column.validity().all());
14995        let values = column.values();
14996        assert_eq!(
14997            values,
14998            &[
14999                Scalar::Float64(-0.0),
15000                Scalar::Float64(f64::INFINITY),
15001                Scalar::Float64(f64::NEG_INFINITY),
15002                Scalar::Float64(1.0)
15003            ]
15004        );
15005        let negative_zero_bits = match values[0] {
15006            Scalar::Float64(value) => Some(value.to_bits()),
15007            _ => None,
15008        };
15009        assert_eq!(negative_zero_bits, Some((-0.0f64).to_bits()));
15010    }
15011
15012    #[test]
15013    fn read_csv_typed_numeric_fast_path_preserves_ragged_row_errors() {
15014        let long_row = "a,b\n1,2,3\n";
15015        let err = read_csv_str(long_row).expect_err("long row must reject");
15016        assert!(matches!(err, IoError::Csv(_)), "got {err:?}");
15017    }
15018
15019    #[test]
15020    fn to_csv_datetime_is_column_uniform_like_pandas() {
15021        // pandas to_csv renders a datetime column with ONE format: date-only
15022        // when all values are midnight, else YYYY-MM-DD HH:MM:SS with a
15023        // sub-second suffix sized to the column's finest resolution. Verified
15024        // vs live pandas 2.2.3. (Previously format_datetime_ns dropped the
15025        // sub-second component and always wrote 00:00:00.)
15026        fn dt_frame(nanos: &[i64]) -> DataFrame {
15027            let values: Vec<Scalar> = nanos.iter().map(|&n| Scalar::Datetime64(n)).collect();
15028            let col = Column::new(DType::Datetime64, values).expect("col");
15029            let mut cols = BTreeMap::new();
15030            cols.insert("d".to_string(), col);
15031            let index = Index::from_i64((0..nanos.len() as i64).collect());
15032            DataFrame::new_with_column_order(index, cols, vec!["d".to_string()]).expect("frame")
15033        }
15034        const MIDNIGHT_JAN1: i64 = 1_577_836_800_000_000_000; // 2020-01-01 00:00:00Z
15035        const MIDNIGHT_JAN2: i64 = 1_577_923_200_000_000_000; // 2020-01-02 00:00:00Z
15036        const JAN2_0300: i64 = 1_577_934_000_000_000_000; // 2020-01-02 03:00:00Z
15037        const JAN1_HALF: i64 = 1_577_836_800_500_000_000; // 2020-01-01 00:00:00.5Z
15038
15039        // All midnight -> date only.
15040        assert_eq!(
15041            write_csv_string(&dt_frame(&[MIDNIGHT_JAN1, MIDNIGHT_JAN2])).expect("w"),
15042            "d\n2020-01-01\n2020-01-02\n"
15043        );
15044        // Sub-second present -> whole column gets .fff (millis), incl. .000.
15045        assert_eq!(
15046            write_csv_string(&dt_frame(&[JAN1_HALF, MIDNIGHT_JAN1])).expect("w"),
15047            "d\n2020-01-01 00:00:00.500\n2020-01-01 00:00:00.000\n"
15048        );
15049        // Time present, no sub-second -> HH:MM:SS for all (midnight -> 00:00:00).
15050        assert_eq!(
15051            write_csv_string(&dt_frame(&[JAN2_0300, MIDNIGHT_JAN1])).expect("w"),
15052            "d\n2020-01-02 03:00:00\n2020-01-01 00:00:00\n"
15053        );
15054        // NaT in an otherwise date-only column -> date only, NaT -> quoted "".
15055        assert_eq!(
15056            write_csv_string(&dt_frame(&[MIDNIGHT_JAN1, i64::MIN])).expect("w"),
15057            "d\n2020-01-01\n\"\"\n"
15058        );
15059    }
15060
15061    #[test]
15062    fn to_csv_datetime_index_is_column_uniform_like_pandas() {
15063        use super::{CsvWriteOptions, write_csv_string_with_options};
15064        // A DatetimeIndex written with index=True follows the same column-
15065        // uniform rule as a datetime column. Verified vs live pandas 2.2.3.
15066        fn dt_index_frame(nanos: &[i64]) -> DataFrame {
15067            let labels: Vec<IndexLabel> =
15068                nanos.iter().map(|&n| IndexLabel::Datetime64(n)).collect();
15069            let index = Index::new(labels);
15070            let values: Vec<Scalar> = (0..nanos.len() as i64).map(Scalar::Int64).collect();
15071            let col = Column::new(DType::Int64, values).expect("col");
15072            let mut cols = BTreeMap::new();
15073            cols.insert("v".to_string(), col);
15074            DataFrame::new_with_column_order(index, cols, vec!["v".to_string()]).expect("frame")
15075        }
15076        let opts = CsvWriteOptions {
15077            include_index: true,
15078            ..Default::default()
15079        };
15080        // All midnight -> date only.
15081        assert_eq!(
15082            write_csv_string_with_options(
15083                &dt_index_frame(&[1_577_836_800_000_000_000, 1_577_923_200_000_000_000]),
15084                &opts
15085            )
15086            .expect("w"),
15087            ",v\n2020-01-01,0\n2020-01-02,1\n"
15088        );
15089        // Sub-second (ms) -> .fff on every label.
15090        assert_eq!(
15091            write_csv_string_with_options(
15092                &dt_index_frame(&[1_577_836_800_500_000_000, 1_577_836_800_250_000_000]),
15093                &opts
15094            )
15095            .expect("w"),
15096            ",v\n2020-01-01 00:00:00.500,0\n2020-01-01 00:00:00.250,1\n"
15097        );
15098    }
15099
15100    #[test]
15101    fn to_json_nat_index_label_is_null_not_sentinel_epoch_natjson() {
15102        use super::{JsonOrient, write_json_string};
15103        // A DatetimeIndex containing NaT (the i64::MIN sentinel): the index label
15104        // must serialize as JSON null, NOT i64::MIN/1e6 (-9223372036854775).
15105        let labels = vec![
15106            IndexLabel::Datetime64(1_577_836_800_000_000_000), // 2020-01-01
15107            IndexLabel::Datetime64(i64::MIN),                  // NaT
15108        ];
15109        let index = Index::new(labels);
15110        let col = Column::new(DType::Int64, vec![Scalar::Int64(7), Scalar::Int64(9)]).expect("col");
15111        let mut cols = BTreeMap::new();
15112        cols.insert("v".to_string(), col);
15113        let frame =
15114            DataFrame::new_with_column_order(index, cols, vec!["v".to_string()]).expect("frame");
15115
15116        // The garbage sentinel epoch must never appear in any orient.
15117        for orient in [
15118            JsonOrient::Split,
15119            JsonOrient::Records,
15120            JsonOrient::Columns,
15121            JsonOrient::Index,
15122        ] {
15123            let out = write_json_string(&frame, orient).expect("json");
15124            assert!(
15125                !out.contains("-9223372036854775"),
15126                "orient {orient:?} leaked the NaT sentinel epoch: {out}"
15127            );
15128        }
15129        // Split orient lists the index as values -> NaT becomes literal null.
15130        let split = write_json_string(&frame, JsonOrient::Split).expect("json");
15131        assert!(
15132            split.contains("null"),
15133            "NaT index label should be null in split orient: {split}"
15134        );
15135    }
15136
15137    #[test]
15138    fn index_label_to_scalar_value_preserves_temporal_dtype_mdt64() {
15139        // Materializing a MultiIndex level into a column must keep the level's
15140        // dtype: a Datetime64 label stays a typed Datetime64 scalar (like the
15141        // Timedelta64 arm), NOT a downgraded Utf8 string — otherwise a datetime
15142        // level becomes an object column (pandas keeps datetime64) and serializes
15143        // inconsistently with a single DatetimeIndex.
15144        assert_eq!(
15145            super::index_label_to_scalar_value(&IndexLabel::Datetime64(1_577_836_800_000_000_000)),
15146            Scalar::Datetime64(1_577_836_800_000_000_000)
15147        );
15148        assert_eq!(
15149            super::index_label_to_scalar_value(&IndexLabel::Timedelta64(86_400_000_000_000)),
15150            Scalar::Timedelta64(86_400_000_000_000)
15151        );
15152        // NaT sentinel stays the typed Datetime64 NaT (downstream writers map it
15153        // to na_rep / null), not the "NaT" literal a Utf8 downgrade produced.
15154        assert_eq!(
15155            super::index_label_to_scalar_value(&IndexLabel::Datetime64(i64::MIN)),
15156            Scalar::Datetime64(i64::MIN)
15157        );
15158    }
15159
15160    #[test]
15161    fn table_writers_render_temporal_nat_dtype_aware_tblnat() {
15162        // Verified vs pandas 2.2.3:
15163        //   to_string/to_markdown/to_html: temporal NaT -> "NaT", float NaN -> na_rep.
15164        //   to_latex:                       temporal NaT -> na_rep, float NaN -> na_rep.
15165        let na = "NaN";
15166        // markdown/string family (scalar_to_table_with_na): NaT literal, NaN -> na_rep.
15167        assert_eq!(
15168            super::scalar_to_table_with_na(&Scalar::Float64(f64::NAN), na),
15169            na
15170        );
15171        assert_eq!(
15172            super::scalar_to_table_with_na(&Scalar::Timedelta64(i64::MIN), na),
15173            "NaT"
15174        );
15175        assert_eq!(
15176            super::scalar_to_table_with_na(&Scalar::Datetime64(i64::MIN), na),
15177            "NaT"
15178        );
15179        assert_eq!(
15180            super::scalar_to_table_with_na(
15181                &Scalar::Period(fp_types::Period::new(i64::MIN, fp_types::PeriodFreq::Daily)),
15182                na
15183            ),
15184            "NaT"
15185        );
15186        // latex (scalar_to_latex_cell): ALL missing collapse to na_rep.
15187        assert_eq!(
15188            super::scalar_to_latex_cell(&Scalar::Float64(f64::NAN), na),
15189            na
15190        );
15191        assert_eq!(
15192            super::scalar_to_latex_cell(&Scalar::Timedelta64(i64::MIN), na),
15193            na
15194        );
15195        assert_eq!(
15196            super::scalar_to_latex_cell(&Scalar::Datetime64(i64::MIN), na),
15197            na
15198        );
15199        assert_eq!(
15200            super::scalar_to_latex_cell(
15201                &Scalar::Period(fp_types::Period::new(i64::MIN, fp_types::PeriodFreq::Daily)),
15202                na
15203            ),
15204            na
15205        );
15206        // A non-NaT datetime still renders normally (sanity).
15207        assert_eq!(
15208            super::scalar_to_table_with_na(&Scalar::Datetime64(1_577_836_800_000_000_000), na),
15209            "2020-01-01 00:00:00"
15210        );
15211    }
15212
15213    #[test]
15214    fn format_pandas_float_matches_python_str_float_at_boundaries() {
15215        // to_csv float cells use Python str(float): fixed notation for decimal
15216        // exponents in [-4, 16), scientific (signed 2-digit exp) outside. Each
15217        // expectation verified vs live pandas 2.2.3 `DataFrame({'v':[x]}).to_csv`.
15218        let cases: &[(f64, &str)] = &[
15219            (0.1, "0.1"),
15220            (1.0 / 3.0, "0.3333333333333333"),
15221            (1e16, "1e+16"),
15222            (1e-5, "1e-05"),
15223            (1e-4, "0.0001"),
15224            (123_456_789_012_345.6, "123456789012345.6"),
15225            (1e21, "1e+21"),
15226            (1e-7, "1e-07"),
15227            (-0.0, "-0.0"),
15228            // 9999999999999999.0 rounds to 1e16 in f64.
15229            (9_999_999_999_999_999.0, "1e+16"),
15230            (2.5e-8, "2.5e-08"),
15231            (1e17, "1e+17"),
15232            (0.00012345, "0.00012345"),
15233        ];
15234        for &(v, expected) in cases {
15235            assert_eq!(
15236                super::format_pandas_float(v),
15237                expected,
15238                "format_pandas_float({v:?})"
15239            );
15240        }
15241    }
15242
15243    #[test]
15244    fn skipinitialspace_preprocessor_strips_leading_field_spaces_i4h5g() {
15245        let f = |s: &str| super::apply_skipinitialspace(s, b',', b'"', true, None, None);
15246        // Leading spaces at every field start (first field + header + after
15247        // delimiter) stripped; trailing spaces kept; verified vs pandas 2.2.3.
15248        assert_eq!(f(" a,  b\n  x,  y  \n"), "a,b\nx,y  \n");
15249        // Space before a quoted field is stripped, the quote is then honored, and
15250        // spaces INSIDE the quotes are preserved.
15251        assert_eq!(f("a,b\nx,  \"  q,q  \"\n"), "a,b\nx,\"  q,q  \"\n");
15252        // Tabs are not stripped (only ASCII 0x20).
15253        assert_eq!(f("a,b\nx,\t y\n"), "a,b\nx,\t y\n");
15254        // An all-space field collapses to empty.
15255        assert_eq!(f("a,   ,b\n"), "a,,b\n");
15256        // Doubled quotes inside a quoted field stay intact.
15257        assert_eq!(f("a\n  \"x\"\"y\"\n"), "a\n\"x\"\"y\"\n");
15258    }
15259
15260    #[test]
15261    fn read_csv_skipinitialspace_strips_field_leading_spaces_i4h5g() {
15262        use super::{CsvReadOptions, read_csv_with_options, write_csv_string};
15263        let opts = CsvReadOptions {
15264            skipinitialspace: true,
15265            ..Default::default()
15266        };
15267        // Object columns: leading spaces at each field start are dropped.
15268        let frame = read_csv_with_options("k,v\n  aa,bb\n cc,  dd\n", &opts).expect("read");
15269        assert_eq!(
15270            write_csv_string(&frame).expect("write"),
15271            "k,v\naa,bb\ncc,dd\n"
15272        );
15273        // Default (skipinitialspace=false) keeps the leading spaces.
15274        let frame_def =
15275            read_csv_with_options("k,v\n  aa,bb\n", &CsvReadOptions::default()).expect("read");
15276        assert_eq!(
15277            write_csv_string(&frame_def).expect("write"),
15278            "k,v\n  aa,bb\n"
15279        );
15280    }
15281
15282    #[test]
15283    fn read_csv_with_options_object_fallback_preserves_text() {
15284        use super::{CsvReadOptions, read_csv_with_options};
15285        // Same pandas object-fallback rule on the options reader (custom
15286        // delimiter / na_values etc.): non-canonical bool casing and zero-padded
15287        // numbers survive once the column is object. Verified vs pandas 2.2.3.
15288        let tsv = CsvReadOptions {
15289            delimiter: b'\t',
15290            ..Default::default()
15291        };
15292        let frame = read_csv_with_options("c\ntrue\nfalse\nmaybe\n", &tsv).expect("read");
15293        assert_eq!(frame.index().int64_unit_range_labels(), Some((0, 3)));
15294        let out = write_csv_string(&frame).expect("write");
15295        assert_eq!(out, "c\ntrue\nfalse\nmaybe\n");
15296
15297        let frame2 = read_csv_with_options("c\n01\n02\nabc\n", &tsv).expect("read");
15298        let out2 = write_csv_string(&frame2).expect("write");
15299        assert_eq!(out2, "c\n01\n02\nabc\n");
15300
15301        // Pure-bool column still infers bool dtype (writes True/False).
15302        let frame3 = read_csv_with_options("c\ntrue\nfalse\n", &tsv).expect("read");
15303        let out3 = write_csv_string(&frame3).expect("write");
15304        assert_eq!(out3, "c\nTrue\nFalse\n");
15305
15306        // Custom na_values: an NA cell in an object column stays missing while
15307        // the surrounding original literals are preserved.
15308        let na_opts = CsvReadOptions {
15309            delimiter: b'\t',
15310            na_values: vec!["MISSING".to_string()],
15311            ..Default::default()
15312        };
15313        let frame4 = read_csv_with_options("c\ntrue\nMISSING\nmaybe\n", &na_opts).expect("read");
15314        let out4 = write_csv_string(&frame4).expect("write");
15315        // The lone empty NaN field in a single-column object frame is quoted "".
15316        assert_eq!(out4, "c\ntrue\n\"\"\nmaybe\n");
15317    }
15318
15319    #[test]
15320    fn to_csv_float_format_matches_pandas_str() {
15321        // pandas to_csv writes floats via Python str(float): whole numbers keep
15322        // ".0", decimals use the shortest round-trip, and extreme magnitudes use
15323        // signed two-digit scientific notation. Verified vs live pandas 2.2.3.
15324        let cases: &[(f64, &str)] = &[
15325            (0.0, "0.0"),
15326            (-0.0, "-0.0"),
15327            (1.0, "1.0"),
15328            (100.0, "100.0"),
15329            (0.1, "0.1"),
15330            (1.0 / 3.0, "0.3333333333333333"),
15331            (9999999999999999.0, "1e+16"),
15332            (1e16, "1e+16"),
15333            (1e20, "1e+20"),
15334            (0.0001, "0.0001"),
15335            (1e-5, "1e-05"),
15336            (1e-7, "1e-07"),
15337            (f64::MIN_POSITIVE / 2.0, "1.1125369292536007e-308"),
15338            (f64::INFINITY, "inf"),
15339            (f64::NEG_INFINITY, "-inf"),
15340        ];
15341        for (v, expected) in cases {
15342            assert_eq!(
15343                &format_pandas_float(*v),
15344                expected,
15345                "format_pandas_float({v})"
15346            );
15347        }
15348
15349        let col = Column::from_f64_values(vec![1.0, f64::NAN, 3.0]);
15350        let mut cols = BTreeMap::new();
15351        cols.insert("x".to_owned(), col);
15352        let frame = DataFrame::new_with_column_order(
15353            Index::from_i64((0..3).collect()),
15354            cols,
15355            vec!["x".to_owned()],
15356        )
15357        .expect("frame");
15358        let out = write_csv_string_with_options(
15359            &frame,
15360            &CsvWriteOptions {
15361                include_index: false,
15362                na_rep: "NA".to_owned(),
15363                ..Default::default()
15364            },
15365        )
15366        .expect("write");
15367        assert_eq!(out, "x\n1.0\nNA\n3.0\n");
15368    }
15369
15370    #[test]
15371    fn to_csv_quarter_affine_float_plan_matches_pandas_str_uza0481() {
15372        let values = (0..128)
15373            .map(|row| (row as f64 * 1.25) + 2.0)
15374            .collect::<Vec<_>>();
15375        let plan = Float64QuarterAffineCsvPlan::for_slice(&values).expect("quarter plan");
15376        let expected_cells = values
15377            .iter()
15378            .copied()
15379            .map(format_pandas_float)
15380            .collect::<Vec<_>>();
15381        let mut fast_cells = Vec::with_capacity(values.len());
15382        for row in 0..values.len() {
15383            let mut out = String::new();
15384            assert!(plan.append_row(&mut out, row));
15385            fast_cells.push(out);
15386        }
15387        assert_eq!(fast_cells, expected_cells);
15388
15389        let col = Column::from_f64_values(values);
15390        let mut cols = BTreeMap::new();
15391        cols.insert("x".to_owned(), col);
15392        let frame = DataFrame::new_with_column_order(
15393            Index::from_i64((0..128).collect()),
15394            cols,
15395            vec!["x".to_owned()],
15396        )
15397        .expect("frame");
15398        let out = write_csv_string_with_options(
15399            &frame,
15400            &CsvWriteOptions {
15401                include_index: false,
15402                ..Default::default()
15403            },
15404        )
15405        .expect("write");
15406        let mut expected = String::from("x\n");
15407        for cell in expected_cells {
15408            expected.push_str(&cell);
15409            expected.push('\n');
15410        }
15411        assert_eq!(out, expected);
15412    }
15413
15414    #[test]
15415    fn quarter_affine_float_plan_rejects_fallback_boundaries_uza0481() {
15416        let rejected: &[&[f64]] = &[
15417            &[-0.0, 1.25, 2.5],
15418            &[-1.25, 0.0, 1.25],
15419            &[0.0, f64::NAN, 2.5],
15420            &[0.0, f64::INFINITY, 2.5],
15421            &[0.1, 1.35, 2.6],
15422            &[0.0, 1.25, 2.75],
15423            &[1e16, 1e16 + 1.25],
15424        ];
15425        for values in rejected {
15426            assert!(
15427                Float64QuarterAffineCsvPlan::for_slice(values).is_none(),
15428                "unexpected quarter plan for {values:?}"
15429            );
15430        }
15431    }
15432
15433    #[test]
15434    fn to_csv_single_column_nan_quotes_empty_and_keeps_float_repr() {
15435        // The lone empty NaN field is already quoted as "" by the csv writer so
15436        // read_csv doesn't drop it (NOT a blank line). The real fix here is the
15437        // float repr: 1.0/3.0 must stay "1.0"/"3.0", not collapse to "1"/"3".
15438        let frame = read_csv_str("x\n1.0\nNaN\n3.0\n").expect("read");
15439        assert!(frame.column("x").unwrap().values()[1].is_missing());
15440        let out = write_csv_string(&frame).expect("write");
15441        assert_eq!(out, "x\n1.0\n\"\"\n3.0\n");
15442    }
15443
15444    #[test]
15445    fn to_csv_typed_single_empty_string_field_is_quoted_like_pandas() {
15446        // Oracle pandas 2.2.3 (csv QUOTE_MINIMAL): a SOLE empty field per record is
15447        // quoted "" so read_csv round-trips '' instead of a blank line -> NaN. An
15448        // all-valid contiguous Utf8 single column takes the typed fast path
15449        // (try_write_csv_typed), which previously emitted the empty cell bare.
15450        // DataFrame({'a':['','x','y']}).to_csv(index=False) -> 'a\n""\nx\ny\n'
15451        let col = Column::from_utf8_contiguous(b"xy".to_vec(), vec![0, 0, 1, 2]);
15452        // Sanity: this column is the all-valid contiguous Utf8 the typed path needs.
15453        assert!(col.as_utf8_contiguous().is_some());
15454        assert_eq!(col.value(0), Some(&Scalar::Utf8(String::new())));
15455        let mut columns = BTreeMap::new();
15456        columns.insert("a".to_string(), col);
15457        let frame = DataFrame::new_with_column_order(
15458            Index::new(vec![
15459                IndexLabel::Int64(0),
15460                IndexLabel::Int64(1),
15461                IndexLabel::Int64(2),
15462            ]),
15463            columns,
15464            vec!["a".to_string()],
15465        )
15466        .unwrap();
15467        assert_eq!(write_csv_string(&frame).expect("write"), "a\n\"\"\nx\ny\n");
15468
15469        // Empty header for a sole column is quoted too (DataFrame({'':['a','b']})).
15470        let named = frame.rename_columns(&[("a", "")]).expect("rename");
15471        assert_eq!(
15472            write_csv_string(&named).expect("write2"),
15473            "\"\"\n\"\"\nx\ny\n"
15474        );
15475    }
15476
15477    #[test]
15478    fn to_csv_typed_multi_column_empty_string_stays_bare_like_pandas() {
15479        // With >1 field per record an empty field is NOT quoted (no blank-line
15480        // ambiguity): DataFrame({'a':['','x'],'b':['y','']}).to_csv(index=False)
15481        // -> 'a,b\n,y\nx,\n'.
15482        let mut columns = BTreeMap::new();
15483        columns.insert(
15484            "a".to_string(),
15485            Column::from_utf8_contiguous(b"x".to_vec(), vec![0, 0, 1]),
15486        );
15487        columns.insert(
15488            "b".to_string(),
15489            Column::from_utf8_contiguous(b"y".to_vec(), vec![0, 1, 1]),
15490        );
15491        let frame = DataFrame::new_with_column_order(
15492            Index::new(vec![IndexLabel::Int64(0), IndexLabel::Int64(1)]),
15493            columns,
15494            vec!["a".to_string(), "b".to_string()],
15495        )
15496        .unwrap();
15497        assert_eq!(write_csv_string(&frame).expect("write"), "a,b\n,y\nx,\n");
15498    }
15499
15500    #[test]
15501    fn to_csv_typed_mixed_columns_quote_alt_delimiter_property_7q396() {
15502        // Code-first property guard (br-frankenpandas-fp-io-csv-typed-writer-quote-property-7q396):
15503        // all-valid typed Int64/Float64 plus contiguous Utf8 must stay byte-exact
15504        // under QUOTE_MINIMAL when the delimiter changes and Utf8 cells contain
15505        // delimiter, quote, and newline characters.
15506        let mut columns = BTreeMap::new();
15507        columns.insert("i".to_string(), Column::from_i64_values(vec![-1, 0, 42, 7]));
15508        columns.insert(
15509            "f".to_string(),
15510            Column::from_f64_values(vec![1.0, 2.5, -0.0, 3.25]),
15511        );
15512
15513        let text = b"plainsemi;colonquote\"meline\nbreak".to_vec();
15514        let offsets = vec![0, 5, 15, 23, 33];
15515        let utf8 = Column::from_utf8_contiguous(text, offsets);
15516        assert!(utf8.as_utf8_contiguous().is_some());
15517        columns.insert("s".to_string(), utf8);
15518
15519        let frame = DataFrame::new_with_column_order(
15520            Index::new((0..4).map(IndexLabel::Int64).collect()),
15521            columns,
15522            vec!["i".to_string(), "f".to_string(), "s".to_string()],
15523        )
15524        .unwrap();
15525        let out = write_csv_string_with_options(
15526            &frame,
15527            &CsvWriteOptions {
15528                delimiter: b';',
15529                include_index: false,
15530                ..CsvWriteOptions::default()
15531            },
15532        )
15533        .expect("typed csv write");
15534
15535        assert_eq!(
15536            out,
15537            "i;f;s\n-1;1.0;plain\n0;2.5;\"semi;colon\"\n42;-0.0;\"quote\"\"me\"\n7;3.25;\"line\nbreak\"\n"
15538        );
15539    }
15540
15541    #[test]
15542    fn to_csv_typed_headerless_keeps_fast_path_for_quoted_column_name_up3yf() {
15543        // br-frankenpandas-fp-io-csv-headerless-quoted-name-typed-fast-pat-up3yf:
15544        // a quoted column name is unobservable when header=false, so it must not
15545        // force the all-valid typed writer off the fast path.
15546        let mut columns = BTreeMap::new();
15547        columns.insert(
15548            "needs,quote".to_string(),
15549            Column::from_i64_values(vec![1, 2]),
15550        );
15551        let frame = DataFrame::new_with_column_order(
15552            Index::new(vec![IndexLabel::Int64(0), IndexLabel::Int64(1)]),
15553            columns,
15554            vec!["needs,quote".to_string()],
15555        )
15556        .unwrap();
15557        let options = CsvWriteOptions {
15558            header: false,
15559            include_index: false,
15560            ..CsvWriteOptions::default()
15561        };
15562
15563        assert_eq!(
15564            super::try_write_csv_typed(&frame, &options).as_deref(),
15565            Some("1\n2\n")
15566        );
15567        assert_eq!(
15568            write_csv_string_with_options(&frame, &options).expect("write"),
15569            "1\n2\n"
15570        );
15571    }
15572
15573    #[test]
15574    fn to_csv_typed_quotes_header_names_without_fallback_ay42b() {
15575        // br-frankenpandas-fp-io-csv-typed-quoted-header-fast-path-4d9vn-ay42b:
15576        // emitted headers use the same QUOTE_MINIMAL rules as data cells, so
15577        // typed columns with quoted names can still bypass the generic writer.
15578        let mut columns = BTreeMap::new();
15579        columns.insert(
15580            "comma,name".to_string(),
15581            Column::from_i64_values(vec![1, 2]),
15582        );
15583        columns.insert(
15584            "quote\"name".to_string(),
15585            Column::from_f64_values(vec![1.0, 2.5]),
15586        );
15587        columns.insert(
15588            "line\nname".to_string(),
15589            Column::from_utf8_contiguous(b"xy".to_vec(), vec![0, 1, 2]),
15590        );
15591        let frame = DataFrame::new_with_column_order(
15592            Index::new(vec![IndexLabel::Int64(0), IndexLabel::Int64(1)]),
15593            columns,
15594            vec![
15595                "comma,name".to_string(),
15596                "quote\"name".to_string(),
15597                "line\nname".to_string(),
15598            ],
15599        )
15600        .unwrap();
15601        let expected = "\"comma,name\",\"quote\"\"name\",\"line\nname\"\n1,1.0,x\n2,2.5,y\n";
15602
15603        assert_eq!(
15604            super::try_write_csv_typed(&frame, &CsvWriteOptions::default()).as_deref(),
15605            Some(expected)
15606        );
15607        assert_eq!(write_csv_string(&frame).expect("write"), expected);
15608    }
15609
15610    #[test]
15611    fn to_csv_typed_emits_int64_index_without_fallback_a2uli() {
15612        // br-frankenpandas-fp-io-csv-typed-int64-index-fast-path-8m6qd-a2uli:
15613        // a simple Int64 index can be emitted directly without forcing typed
15614        // columns through per-cell Scalar materialization.
15615        let mut columns = BTreeMap::new();
15616        columns.insert("a".to_string(), Column::from_i64_values(vec![1, 2]));
15617        columns.insert("b".to_string(), Column::from_f64_values(vec![1.0, 2.5]));
15618        let frame = DataFrame::new_with_column_order(
15619            Index::from_i64(vec![10, 20]).set_name("row,id"),
15620            columns,
15621            vec!["a".to_string(), "b".to_string()],
15622        )
15623        .unwrap();
15624        let options = CsvWriteOptions {
15625            include_index: true,
15626            ..CsvWriteOptions::default()
15627        };
15628        let expected = "\"row,id\",a,b\n10,1,1.0\n20,2,2.5\n";
15629
15630        assert_eq!(
15631            super::try_write_csv_typed(&frame, &options).as_deref(),
15632            Some(expected)
15633        );
15634        assert_eq!(
15635            write_csv_string_with_options(&frame, &options).expect("write"),
15636            expected
15637        );
15638    }
15639
15640    #[test]
15641    fn to_csv_typed_int64_manual_decimal_boundaries_cnw1j() {
15642        // br-frankenpandas-fp-io-csv-int64-manual-decimal-emitter-5p8kx-cnw1j:
15643        // the stack decimal emitter must preserve Display bytes for every i64,
15644        // including the unsigned_abs corner at i64::MIN.
15645        let mut columns = BTreeMap::new();
15646        columns.insert(
15647            "v".to_string(),
15648            Column::from_i64_values(vec![i64::MIN, 0, i64::MAX]),
15649        );
15650        let frame = DataFrame::new_with_column_order(
15651            Index::from_i64(vec![-1, 0, 1]),
15652            columns,
15653            vec!["v".to_string()],
15654        )
15655        .unwrap();
15656        let options = CsvWriteOptions {
15657            include_index: true,
15658            index_label: Some("i".to_string()),
15659            ..CsvWriteOptions::default()
15660        };
15661        let expected = "i,v\n-1,-9223372036854775808\n0,0\n1,9223372036854775807\n";
15662
15663        assert_eq!(
15664            super::try_write_csv_typed(&frame, &options).as_deref(),
15665            Some(expected)
15666        );
15667        assert_eq!(
15668            write_csv_string_with_options(&frame, &options).expect("write"),
15669            expected
15670        );
15671    }
15672
15673    #[test]
15674    fn to_csv_typed_bool_column_stays_on_fast_path_48fwr() {
15675        // br-frankenpandas-fp-io-csv-typed-bool-column-fast-path-2k7hm-48fwr:
15676        // all-valid Bool columns have a typed backing and should emit pandas
15677        // True/False spelling without Scalar materialization.
15678        let mut columns = BTreeMap::new();
15679        columns.insert(
15680            "flag".to_string(),
15681            Column::from_bool_values(vec![true, false, true]),
15682        );
15683        columns.insert("value".to_string(), Column::from_i64_values(vec![7, 8, 9]));
15684        let frame = DataFrame::new_with_column_order(
15685            Index::from_i64(vec![100, 101, 102]),
15686            columns,
15687            vec!["flag".to_string(), "value".to_string()],
15688        )
15689        .unwrap();
15690        let options = CsvWriteOptions {
15691            include_index: true,
15692            index_label: Some("row".to_string()),
15693            ..CsvWriteOptions::default()
15694        };
15695        let expected = "row,flag,value\n100,True,7\n101,False,8\n102,True,9\n";
15696
15697        assert_eq!(
15698            super::try_write_csv_typed(&frame, &options).as_deref(),
15699            Some(expected)
15700        );
15701        assert_eq!(
15702            write_csv_string_with_options(&frame, &options).expect("write"),
15703            expected
15704        );
15705    }
15706
15707    #[test]
15708    fn test_csv_capacity_hint_reasonable() {
15709        // Generate a ~1MB CSV and verify it parses correctly.
15710        // The capacity hint (input.len / (cols*8)) should avoid excessive reallocs.
15711        let mut csv = String::with_capacity(1_100_000);
15712        csv.push_str("a,b,c,d,e\n");
15713        let target_rows = 50_000; // ~20 bytes/row * 50k ≈ 1MB
15714        for i in 0..target_rows {
15715            csv.push_str(&format!("{},{},{},{},{}\n", i, i * 2, i * 3, i * 4, i * 5));
15716        }
15717        assert!(csv.len() > 500_000, "CSV should be large");
15718
15719        let frame = read_csv_str(&csv).expect("parse large CSV");
15720        assert_eq!(frame.index().len(), target_rows);
15721        assert_eq!(frame.columns().len(), 5);
15722        // Spot-check last row
15723        assert_eq!(
15724            frame.column("a").unwrap().values()[target_rows - 1],
15725            Scalar::Int64((target_rows - 1) as i64)
15726        );
15727        eprintln!(
15728            "[TEST] test_csv_capacity_hint_reasonable | rows={target_rows} cols=5 parse_ok=true | PASS"
15729        );
15730    }
15731
15732    #[test]
15733    fn test_csv_empty_columns() {
15734        // CSV with headers but no data rows -> empty DataFrame with correct column names.
15735        let input = "x,y,z\n";
15736        let frame = read_csv_str(input).expect("parse");
15737        assert_eq!(frame.index().len(), 0);
15738        let keys: Vec<&String> = frame.columns().keys().collect();
15739        assert_eq!(keys, &["x", "y", "z"]);
15740        for col in frame.columns().values() {
15741            assert!(col.is_empty());
15742        }
15743        eprintln!("[TEST] test_csv_empty_columns | rows=0 cols=3 parse_ok=true | PASS");
15744    }
15745
15746    #[test]
15747    fn test_csv_comment_skips_lines() {
15748        let input = "# header comment\nname,age\n# inline comment\nalice,30\nbob,25\n";
15749        let options = CsvReadOptions {
15750            comment: Some(b'#'),
15751            ..CsvReadOptions::default()
15752        };
15753        let frame = read_csv_with_options(input, &options).expect("parse");
15754        assert_eq!(frame.index().len(), 2);
15755        let names: Vec<&String> = frame.column_names().into_iter().collect();
15756        assert_eq!(names, vec!["name", "age"]);
15757        assert_eq!(
15758            frame.column("name").unwrap().values()[0],
15759            Scalar::Utf8("alice".to_string())
15760        );
15761        assert_eq!(frame.column("age").unwrap().values()[1], Scalar::Int64(25));
15762    }
15763
15764    #[test]
15765    fn test_csv_comment_none_preserves_comment_lines() {
15766        // Without comment set, a leading "#"-line should become part of parsing
15767        // (and fail as duplicate/missing-headers or be treated as data).
15768        let input = "name,age\nalice,30\n";
15769        let frame = read_csv_with_options(input, &CsvReadOptions::default()).expect("parse");
15770        assert_eq!(frame.index().len(), 1);
15771    }
15772
15773    #[test]
15774    fn read_csv_with_default_options_matches_read_csv_str() {
15775        for input in [
15776            "i,f,s\n1,2.5,abc\n3,4.0,def\n",
15777            "flag\ntrue\nfalse\nmaybe\n",
15778        ] {
15779            let expected = read_csv_str(input).expect("default read");
15780            let actual =
15781                read_csv_with_options(input, &CsvReadOptions::default()).expect("options read");
15782
15783            assert_eq!(actual.index().len(), expected.index().len());
15784            assert_eq!(actual.column_names(), expected.column_names());
15785            for name in expected.column_names() {
15786                let expected_col = expected.column(name).expect("expected column");
15787                let actual_col = actual.column(name).expect("actual column");
15788                assert_eq!(actual_col.dtype(), expected_col.dtype());
15789                assert_eq!(actual_col.values(), expected_col.values());
15790            }
15791        }
15792    }
15793
15794    #[test]
15795    fn read_csv_str_cache_reuses_exact_successful_input() {
15796        let input = "x,y\n1,2.5\n3,4.5\n";
15797
15798        let first = read_csv_str(input).expect("first parse");
15799        let second = read_csv_str(input).expect("cached parse");
15800
15801        assert_eq!(second.index().len(), first.index().len());
15802        assert_eq!(second.column_names(), first.column_names());
15803        for name in first.column_names() {
15804            let first_col = first.column(name).expect("first column");
15805            let second_col = second.column(name).expect("second column");
15806            assert_eq!(second_col.dtype(), first_col.dtype());
15807            assert_eq!(second_col.values(), first_col.values());
15808        }
15809    }
15810
15811    #[test]
15812    fn read_csv_str_cache_is_content_addressed() {
15813        let mut input = String::from("x\n1\n2\n");
15814        let first = read_csv_str(&input).expect("first parse");
15815        assert_eq!(first.column("x").unwrap().values()[0], Scalar::Int64(1));
15816
15817        input.clear();
15818        input.push_str("x\n9\n10\n");
15819        let second = read_csv_str(&input).expect("changed-content parse");
15820
15821        assert_eq!(second.index().len(), 2);
15822        assert_eq!(second.column("x").unwrap().values()[0], Scalar::Int64(9));
15823        assert_eq!(second.column("x").unwrap().values()[1], Scalar::Int64(10));
15824    }
15825
15826    #[test]
15827    fn read_csv_no_na_cache_reuses_exact_successful_input() {
15828        let options = CsvReadOptions {
15829            na_filter: false,
15830            ..CsvReadOptions::default()
15831        };
15832        let input = "x,y\n1,2.5\n3,4.5\n";
15833
15834        let first = read_csv_with_options(input, &options).expect("first no-na parse");
15835        let second = read_csv_with_options(input, &options).expect("cached no-na parse");
15836
15837        assert_eq!(second.index().len(), first.index().len());
15838        assert_eq!(second.column_names(), first.column_names());
15839        for name in first.column_names() {
15840            let first_col = first.column(name).expect("first column");
15841            let second_col = second.column(name).expect("second column");
15842            assert_eq!(second_col.dtype(), first_col.dtype());
15843            assert_eq!(second_col.values(), first_col.values());
15844        }
15845    }
15846
15847    #[test]
15848    fn csv_parse_cache_keeps_default_and_no_na_modes_separate() {
15849        let input = "mode_sep_a,mode_sep_b\n11,12.5\n13,14.5\n";
15850        let no_na_options = CsvReadOptions {
15851            na_filter: false,
15852            ..CsvReadOptions::default()
15853        };
15854
15855        let no_na_frame = read_csv_with_options(input, &no_na_options).expect("no-na parse");
15856        assert!(super::csv_parse_cache_lookup(super::CsvParseCacheMode::Default, input).is_none());
15857        assert!(
15858            super::csv_parse_cache_lookup(super::CsvParseCacheMode::NoNaNumeric, input).is_some()
15859        );
15860
15861        let default_frame = read_csv_str(input).expect("default parse");
15862        let default_cached =
15863            super::csv_parse_cache_lookup(super::CsvParseCacheMode::Default, input)
15864                .expect("default cache entry");
15865        let no_na_cached =
15866            super::csv_parse_cache_lookup(super::CsvParseCacheMode::NoNaNumeric, input)
15867                .expect("no-na cache entry");
15868
15869        assert_eq!(default_cached.column_names(), default_frame.column_names());
15870        assert_eq!(no_na_cached.column_names(), no_na_frame.column_names());
15871        assert_eq!(
15872            default_cached.column("mode_sep_b").unwrap().values(),
15873            default_frame.column("mode_sep_b").unwrap().values()
15874        );
15875        assert_eq!(
15876            no_na_cached.column("mode_sep_b").unwrap().values(),
15877            no_na_frame.column("mode_sep_b").unwrap().values()
15878        );
15879    }
15880
15881    #[test]
15882    fn csv_default_options_fast_path_excludes_behavioral_options() {
15883        assert!(super::csv_read_options_match_default_fast_path(
15884            &CsvReadOptions::default()
15885        ));
15886
15887        for options in [
15888            CsvReadOptions {
15889                delimiter: b'\t',
15890                ..CsvReadOptions::default()
15891            },
15892            CsvReadOptions {
15893                na_filter: false,
15894                ..CsvReadOptions::default()
15895            },
15896            CsvReadOptions {
15897                nrows: Some(1),
15898                ..CsvReadOptions::default()
15899            },
15900            CsvReadOptions {
15901                comment: Some(b'#'),
15902                ..CsvReadOptions::default()
15903            },
15904            CsvReadOptions {
15905                thousands: Some(b','),
15906                ..CsvReadOptions::default()
15907            },
15908        ] {
15909            assert!(!super::csv_read_options_match_default_fast_path(&options));
15910        }
15911    }
15912
15913    #[test]
15914    fn read_csv_no_na_filter_numeric_fast_path_preserves_numeric_columns() {
15915        let options = CsvReadOptions {
15916            na_filter: false,
15917            ..CsvReadOptions::default()
15918        };
15919        assert!(super::csv_read_options_match_no_na_numeric_fast_path(
15920            &options
15921        ));
15922
15923        let frame = read_csv_with_options("i,f\n1,2.5\n3,4\n", &options).expect("parse");
15924        assert_eq!(frame.len(), 2);
15925        assert_eq!(frame.column("i").expect("i").dtype(), DType::Int64);
15926        assert_eq!(frame.column("f").expect("f").dtype(), DType::Float64);
15927        assert_eq!(frame.column("i").expect("i").values()[1], Scalar::Int64(3));
15928        assert_eq!(
15929            frame.column("f").expect("f").values()[0],
15930            Scalar::Float64(2.5)
15931        );
15932    }
15933
15934    #[test]
15935    fn read_csv_no_na_filter_fast_path_falls_back_for_empty_field() {
15936        let options = CsvReadOptions {
15937            na_filter: false,
15938            ..CsvReadOptions::default()
15939        };
15940        let frame = read_csv_with_options("x,y\n1,\n2,3\n", &options).expect("parse");
15941        let y = frame.column("y").expect("y");
15942
15943        assert_eq!(y.dtype(), DType::Utf8);
15944        assert_eq!(y.values()[0], Scalar::Utf8(String::new()));
15945        assert_eq!(y.values()[1], Scalar::Utf8("3".to_owned()));
15946    }
15947
15948    #[test]
15949    fn test_csv_comment_custom_char() {
15950        let input = "% this is ignored\nname,age\nalice,30\n";
15951        let options = CsvReadOptions {
15952            comment: Some(b'%'),
15953            ..CsvReadOptions::default()
15954        };
15955        let frame = read_csv_with_options(input, &options).expect("parse");
15956        assert_eq!(frame.index().len(), 1);
15957        assert_eq!(
15958            frame.column("name").unwrap().values()[0],
15959            Scalar::Utf8("alice".to_string())
15960        );
15961    }
15962
15963    #[test]
15964    fn test_csv_thousands_strips_int_separator() {
15965        let input = "amount\n\"1,234,567\"\n\"42\"\n";
15966        let options = CsvReadOptions {
15967            thousands: Some(b','),
15968            ..CsvReadOptions::default()
15969        };
15970        let frame = read_csv_with_options(input, &options).expect("parse");
15971        assert_eq!(
15972            frame.column("amount").unwrap().values()[0],
15973            Scalar::Int64(1234567)
15974        );
15975        assert_eq!(
15976            frame.column("amount").unwrap().values()[1],
15977            Scalar::Int64(42)
15978        );
15979    }
15980
15981    #[test]
15982    fn test_csv_thousands_strips_float_with_custom_decimal() {
15983        // European convention: '.' as thousands, ',' as decimal.
15984        let input = "price\n\"1.234,56\"\n";
15985        let options = CsvReadOptions {
15986            thousands: Some(b'.'),
15987            decimal: b',',
15988            ..CsvReadOptions::default()
15989        };
15990        let frame = read_csv_with_options(input, &options).expect("parse");
15991        let v = frame.column("price").unwrap().values()[0].clone();
15992        assert!(matches!(v, Scalar::Float64(_)), "expected Float64");
15993        let Scalar::Float64(f) = v else { return };
15994        assert!((f - 1234.56).abs() < 1e-9);
15995    }
15996
15997    #[test]
15998    fn test_csv_thousands_none_keeps_separator_as_string() {
15999        // Without thousands set, "1,234" in a single field stays Utf8.
16000        let input = "amount\n\"1,234\"\n";
16001        let frame = read_csv_with_options(input, &CsvReadOptions::default()).expect("parse");
16002        assert_eq!(
16003            frame.column("amount").unwrap().values()[0],
16004            Scalar::Utf8("1,234".to_string())
16005        );
16006    }
16007
16008    #[test]
16009    fn test_csv_thousands_equal_to_decimal_is_ignored() {
16010        // pandas silently ignores thousands if it equals decimal.
16011        let input = "v\n\"1.234\"\n";
16012        let options = CsvReadOptions {
16013            thousands: Some(b'.'),
16014            decimal: b'.',
16015            ..CsvReadOptions::default()
16016        };
16017        let frame = read_csv_with_options(input, &options).expect("parse");
16018        let v = frame.column("v").unwrap().values()[0].clone();
16019        // thousands ignored → "1.234" parses as float 1.234
16020        assert!(matches!(v, Scalar::Float64(_)), "expected Float64");
16021        let Scalar::Float64(f) = v else { return };
16022        assert!((f - 1.234).abs() < 1e-9);
16023    }
16024
16025    #[test]
16026    fn test_csv_thousands_does_not_affect_non_numeric() {
16027        let input = "name\n\"a,b\"\n";
16028        let options = CsvReadOptions {
16029            thousands: Some(b','),
16030            ..CsvReadOptions::default()
16031        };
16032        let frame = read_csv_with_options(input, &options).expect("parse");
16033        assert_eq!(
16034            frame.column("name").unwrap().values()[0],
16035            Scalar::Utf8("a,b".to_string())
16036        );
16037    }
16038
16039    #[test]
16040    fn test_csv_quotechar_custom_single_quote() {
16041        let input = "name,remark\n'alice','loves, cats'\n";
16042        let options = CsvReadOptions {
16043            quotechar: b'\'',
16044            ..CsvReadOptions::default()
16045        };
16046        let frame = read_csv_with_options(input, &options).expect("parse");
16047        assert_eq!(
16048            frame.column("name").unwrap().values()[0],
16049            Scalar::Utf8("alice".to_string())
16050        );
16051        assert_eq!(
16052            frame.column("remark").unwrap().values()[0],
16053            Scalar::Utf8("loves, cats".to_string())
16054        );
16055    }
16056
16057    #[test]
16058    fn test_csv_doublequote_true_collapses_doubled_quotes() {
16059        // The field is `she said ""hi""` with doubled inner quotes.
16060        let input = "text\n\"she said \"\"hi\"\"\"\n";
16061        let frame = read_csv_with_options(input, &CsvReadOptions::default()).expect("parse");
16062        assert_eq!(
16063            frame.column("text").unwrap().values()[0],
16064            Scalar::Utf8("she said \"hi\"".to_string())
16065        );
16066    }
16067
16068    #[test]
16069    fn test_csv_doublequote_false_requires_escapechar() {
16070        // With doublequote=false and escapechar=\, \" escapes the quote.
16071        let input = "text\n\"hi\\\"there\"\n";
16072        let options = CsvReadOptions {
16073            doublequote: false,
16074            escapechar: Some(b'\\'),
16075            ..CsvReadOptions::default()
16076        };
16077        let frame = read_csv_with_options(input, &options).expect("parse");
16078        assert_eq!(
16079            frame.column("text").unwrap().values()[0],
16080            Scalar::Utf8("hi\"there".to_string())
16081        );
16082    }
16083
16084    #[test]
16085    fn test_csv_lineterminator_semicolon() {
16086        // Single-byte record separator '|'. No newlines in the data.
16087        let input = "a,b|1,x|2,y|3,z";
16088        let options = CsvReadOptions {
16089            lineterminator: Some(b'|'),
16090            ..CsvReadOptions::default()
16091        };
16092        let frame = read_csv_with_options(input, &options).expect("parse");
16093        assert_eq!(frame.index().len(), 3);
16094        assert_eq!(frame.column_names(), vec!["a", "b"]);
16095        assert_eq!(frame.column("a").unwrap().values()[2], Scalar::Int64(3));
16096    }
16097
16098    #[test]
16099    fn test_csv_lineterminator_default_none_accepts_crlf() {
16100        let input = "a,b\r\n1,x\r\n2,y\r\n";
16101        let frame = read_csv_with_options(input, &CsvReadOptions::default()).expect("parse");
16102        assert_eq!(frame.index().len(), 2);
16103    }
16104
16105    #[test]
16106    fn test_csv_lineterminator_interacts_with_skipfooter() {
16107        let input = "a|1|2|3|4|FOOTER";
16108        let options = CsvReadOptions {
16109            lineterminator: Some(b'|'),
16110            skipfooter: 1,
16111            ..CsvReadOptions::default()
16112        };
16113        let frame = read_csv_with_options(input, &options).expect("parse");
16114        // 5 data rows after header, footer drops 1 → 4 rows.
16115        assert_eq!(frame.index().len(), 4);
16116    }
16117
16118    #[test]
16119    fn test_csv_skipfooter_drops_trailing_rows() {
16120        let input = "a,b\n1,x\n2,y\n3,z\nTOTAL,summary\n";
16121        let options = CsvReadOptions {
16122            skipfooter: 1,
16123            ..CsvReadOptions::default()
16124        };
16125        let frame = read_csv_with_options(input, &options).expect("parse");
16126        assert_eq!(frame.index().len(), 3);
16127        assert_eq!(frame.column("a").unwrap().values()[2], Scalar::Int64(3));
16128    }
16129
16130    #[test]
16131    fn test_csv_skipfooter_zero_is_noop() {
16132        let input = "a,b\n1,x\n2,y\n";
16133        let frame_default =
16134            read_csv_with_options(input, &CsvReadOptions::default()).expect("parse");
16135        let options = CsvReadOptions {
16136            skipfooter: 0,
16137            ..CsvReadOptions::default()
16138        };
16139        let frame_zero = read_csv_with_options(input, &options).expect("parse");
16140        assert_eq!(frame_default.index().len(), frame_zero.index().len());
16141    }
16142
16143    #[test]
16144    fn test_csv_skipfooter_larger_than_data_clears_rows() {
16145        let input = "a,b\n1,x\n2,y\n";
16146        let options = CsvReadOptions {
16147            skipfooter: 10,
16148            ..CsvReadOptions::default()
16149        };
16150        let frame = read_csv_with_options(input, &options).expect("parse");
16151        assert_eq!(frame.index().len(), 0);
16152        // Columns and headers are still preserved.
16153        assert_eq!(frame.column_names().len(), 2);
16154    }
16155
16156    #[test]
16157    fn test_csv_skipfooter_with_nrows() {
16158        // nrows caps read to 4, then skipfooter drops last 1 → 3 rows.
16159        let input = "a\n1\n2\n3\n4\n5\n";
16160        let options = CsvReadOptions {
16161            nrows: Some(4),
16162            skipfooter: 1,
16163            ..CsvReadOptions::default()
16164        };
16165        let frame = read_csv_with_options(input, &options).expect("parse");
16166        assert_eq!(frame.index().len(), 3);
16167    }
16168
16169    #[test]
16170    fn test_csv_escapechar_none_default_keeps_backslash_literal() {
16171        // Without escapechar set, backslash is just a normal character.
16172        let input = "text\n\"foo\\bar\"\n";
16173        let frame = read_csv_with_options(input, &CsvReadOptions::default()).expect("parse");
16174        assert_eq!(
16175            frame.column("text").unwrap().values()[0],
16176            Scalar::Utf8("foo\\bar".to_string())
16177        );
16178    }
16179
16180    #[test]
16181    fn test_csv_single_column() {
16182        // CSV with one column, many rows -> correct parsing.
16183        let mut csv = String::from("value\n");
16184        for i in 0..500 {
16185            csv.push_str(&format!("{}\n", i));
16186        }
16187        let frame = read_csv_str(&csv).expect("parse");
16188        assert_eq!(frame.index().len(), 500);
16189        assert_eq!(frame.columns().len(), 1);
16190        assert_eq!(
16191            frame.column("value").unwrap().values()[499],
16192            Scalar::Int64(499)
16193        );
16194        eprintln!("[TEST] test_csv_single_column | rows=500 cols=1 parse_ok=true | PASS");
16195    }
16196
16197    #[test]
16198    fn test_csv_many_columns() {
16199        // CSV with 100+ columns -> all columns present, correct values.
16200        let col_count = 120;
16201        let headers: Vec<String> = (0..col_count).map(|i| format!("c{i:03}")).collect();
16202        let mut csv = headers.join(",");
16203        csv.push('\n');
16204        // 3 data rows
16205        for row in 0..3 {
16206            let vals: Vec<String> = (0..col_count)
16207                .map(|c| format!("{}", row * 1000 + c))
16208                .collect();
16209            csv.push_str(&vals.join(","));
16210            csv.push('\n');
16211        }
16212        let frame = read_csv_str(&csv).expect("parse");
16213        assert_eq!(frame.columns().len(), col_count);
16214        assert_eq!(frame.index().len(), 3);
16215        // Spot-check: c000 row 0 = 0, c119 row 2 = 2119
16216        assert_eq!(frame.column("c000").unwrap().values()[0], Scalar::Int64(0));
16217        assert_eq!(
16218            frame.column("c119").unwrap().values()[2],
16219            Scalar::Int64(2119)
16220        );
16221        eprintln!("[TEST] test_csv_many_columns | rows=3 cols={col_count} parse_ok=true | PASS");
16222    }
16223
16224    #[test]
16225    fn test_csv_mixed_dtypes() {
16226        // Columns with uniform int/float/string/bool/null -> correct type inference.
16227        let input = "ints,floats,strings,bools,nulls\n\
16228                     1,1.5,hello,true,\n\
16229                     2,2.7,world,false,\n\
16230                     3,3.14,foo,true,\n";
16231        let frame = read_csv_str(input).expect("parse");
16232
16233        let ints = frame.column("ints").unwrap();
16234        assert_eq!(ints.values()[0], Scalar::Int64(1));
16235
16236        let floats = frame.column("floats").unwrap();
16237        assert_eq!(floats.values()[1], Scalar::Float64(2.7));
16238
16239        let strings = frame.column("strings").unwrap();
16240        assert_eq!(strings.values()[2], Scalar::Utf8("foo".to_owned()));
16241
16242        let bools = frame.column("bools").unwrap();
16243        assert_eq!(bools.values()[0], Scalar::Bool(true));
16244        assert_eq!(bools.values()[1], Scalar::Bool(false));
16245
16246        // "nulls" column is all empty -> all null/NaN
16247        let nulls = frame.column("nulls").unwrap();
16248        for v in nulls.values() {
16249            assert!(v.is_missing(), "null column values should be missing");
16250        }
16251        eprintln!(
16252            "[TEST] test_csv_mixed_dtypes | rows=3 cols=5 parse_ok=true | dtype_per_col=[int64,float64,utf8,bool,null] | PASS"
16253        );
16254    }
16255
16256    #[test]
16257    fn test_csv_unicode_headers() {
16258        // CSV with unicode header names -> correct column names.
16259        let input = "名前,Größe,café\nAlice,170,latte\nBob,180,espresso\n";
16260        let frame = read_csv_str(input).expect("parse");
16261        assert!(frame.column("名前").is_some());
16262        assert!(frame.column("Größe").is_some());
16263        assert!(frame.column("café").is_some());
16264        assert_eq!(
16265            frame.column("名前").unwrap().values()[0],
16266            Scalar::Utf8("Alice".to_owned())
16267        );
16268        eprintln!("[TEST] test_csv_unicode_headers | rows=2 cols=3 parse_ok=true | PASS");
16269    }
16270
16271    #[test]
16272    fn test_csv_quoted_fields() {
16273        // CSV with quoted fields containing commas and newlines -> correct parsing.
16274        let input =
16275            "name,address\n\"Smith, John\",\"123 Main St\nApt 4\"\nJane,\"456 Oak, Suite 1\"\n";
16276        let frame = read_csv_str(input).expect("parse");
16277        assert_eq!(frame.index().len(), 2);
16278        assert_eq!(
16279            frame.column("name").unwrap().values()[0],
16280            Scalar::Utf8("Smith, John".to_owned())
16281        );
16282        // Quoted field with embedded newline
16283        let addr0 = &frame.column("address").unwrap().values()[0];
16284        assert!(
16285            matches!(addr0, Scalar::Utf8(s) if s.contains('\n')),
16286            "expected Utf8 containing embedded newline, got {addr0:?}"
16287        );
16288        eprintln!("[TEST] test_csv_quoted_fields | rows=2 cols=2 parse_ok=true | PASS");
16289    }
16290
16291    #[test]
16292    fn test_csv_trailing_newline() {
16293        // CSV with/without trailing newline -> identical DataFrame.
16294        let with = "a,b\n1,2\n3,4\n";
16295        let without = "a,b\n1,2\n3,4";
16296        let f1 = read_csv_str(with).expect("with newline");
16297        let f2 = read_csv_str(without).expect("without newline");
16298
16299        assert_eq!(f1.index().len(), f2.index().len());
16300        assert_eq!(f1.columns().len(), f2.columns().len());
16301        for key in f1.columns().keys() {
16302            let c1 = f1.column(key).unwrap();
16303            let c2 = f2.column(key).unwrap();
16304            assert_eq!(c1.values(), c2.values(), "column {key} mismatch");
16305        }
16306        eprintln!("[TEST] test_csv_trailing_newline | rows=2 cols=2 parse_ok=true | PASS");
16307    }
16308
16309    #[test]
16310    fn test_csv_round_trip_unchanged() {
16311        // read_csv_str then write_csv_string produces semantically equivalent output.
16312        let input = "id,name,score\n1,Alice,95.5\n2,Bob,87\n3,,100\n";
16313        let frame = read_csv_str(input).expect("read");
16314        let output = write_csv_string(&frame).expect("write");
16315        // Re-parse the output and compare
16316        let frame2 = read_csv_str(&output).expect("re-read");
16317        assert_eq!(frame.index().len(), frame2.index().len());
16318        for key in frame.columns().keys() {
16319            let c1 = frame.column(key).unwrap();
16320            let c2 = frame2.column(key).unwrap();
16321            assert!(
16322                c1.semantic_eq(c2),
16323                "column {key} not semantically equal after round-trip"
16324            );
16325        }
16326        eprintln!("[TEST] test_csv_round_trip_unchanged | rows=3 cols=3 parse_ok=true | PASS");
16327    }
16328
16329    #[test]
16330    fn test_write_csv_options_custom_delimiter() {
16331        let input = "a,b\n1,x\n2,y\n";
16332        let frame = read_csv_str(input).expect("read");
16333        let output = write_csv_string_with_options(
16334            &frame,
16335            &CsvWriteOptions {
16336                delimiter: b';',
16337                ..CsvWriteOptions::default()
16338            },
16339        )
16340        .expect("write");
16341        assert!(output.starts_with("a;b\n"));
16342        assert!(output.contains("1;x\n"));
16343        assert!(output.contains("2;y\n"));
16344    }
16345
16346    #[test]
16347    fn test_write_csv_options_na_rep_replaces_nulls() {
16348        let input = "id,name\n1,Alice\n2,\n";
16349        let frame = read_csv_str(input).expect("read");
16350        let output = write_csv_string_with_options(
16351            &frame,
16352            &CsvWriteOptions {
16353                na_rep: "NA".to_string(),
16354                ..CsvWriteOptions::default()
16355            },
16356        )
16357        .expect("write");
16358        // Second data row's name should render as NA, not empty.
16359        assert!(output.contains("2,NA\n"));
16360        assert!(!output.contains("2,\n"));
16361    }
16362
16363    #[test]
16364    fn test_write_csv_options_header_false_omits_header_row() {
16365        let input = "a,b\n1,2\n";
16366        let frame = read_csv_str(input).expect("read");
16367        let output = write_csv_string_with_options(
16368            &frame,
16369            &CsvWriteOptions {
16370                header: false,
16371                ..CsvWriteOptions::default()
16372            },
16373        )
16374        .expect("write");
16375        assert_eq!(output, "1,2\n");
16376    }
16377
16378    #[test]
16379    fn test_write_csv_options_include_index_and_index_label() {
16380        let input = "a,b\n1,2\n3,4\n";
16381        let frame = read_csv_str(input).expect("read");
16382        let output = write_csv_string_with_options(
16383            &frame,
16384            &CsvWriteOptions {
16385                include_index: true,
16386                index_label: Some("row_id".to_string()),
16387                ..CsvWriteOptions::default()
16388            },
16389        )
16390        .expect("write");
16391
16392        assert_eq!(output, "row_id,a,b\n0,1,2\n1,3,4\n");
16393    }
16394
16395    #[test]
16396    fn test_write_csv_options_include_index_uses_named_index_when_label_omitted() {
16397        let mut cols = std::collections::BTreeMap::new();
16398        cols.insert(
16399            "a".to_string(),
16400            Column::from_values(vec![Scalar::Int64(10), Scalar::Int64(20)]).unwrap(),
16401        );
16402        let frame = DataFrame::new_with_column_order(
16403            Index::from_i64(vec![100, 200]).set_name("sample_id"),
16404            cols,
16405            vec!["a".to_string()],
16406        )
16407        .unwrap();
16408
16409        let output = write_csv_string_with_options(
16410            &frame,
16411            &CsvWriteOptions {
16412                include_index: true,
16413                ..CsvWriteOptions::default()
16414            },
16415        )
16416        .expect("write");
16417
16418        assert_eq!(output, "sample_id,a\n100,10\n200,20\n");
16419    }
16420
16421    #[test]
16422    fn test_write_csv_options_include_index_label_overrides_index_name() {
16423        let mut cols = std::collections::BTreeMap::new();
16424        cols.insert(
16425            "a".to_string(),
16426            Column::from_values(vec![Scalar::Int64(10), Scalar::Int64(20)]).unwrap(),
16427        );
16428        let frame = DataFrame::new_with_column_order(
16429            Index::from_i64(vec![100, 200]).set_name("sample_id"),
16430            cols,
16431            vec!["a".to_string()],
16432        )
16433        .unwrap();
16434
16435        let output = write_csv_string_with_options(
16436            &frame,
16437            &CsvWriteOptions {
16438                include_index: true,
16439                index_label: Some("row".to_string()),
16440                ..CsvWriteOptions::default()
16441            },
16442        )
16443        .expect("write");
16444
16445        assert_eq!(output, "row,a\n100,10\n200,20\n");
16446    }
16447
16448    #[test]
16449    fn test_csv_multiindex_roundtrip_with_explicit_index_cols() {
16450        let frame = make_row_multiindex_test_dataframe();
16451        let csv = write_csv_string_with_options(
16452            &frame,
16453            &CsvWriteOptions {
16454                include_index: true,
16455                ..CsvWriteOptions::default()
16456            },
16457        )
16458        .expect("write");
16459
16460        let roundtrip = read_csv_with_index_cols(
16461            &csv,
16462            &CsvReadOptions::default(),
16463            &["region", "product", "year"],
16464        )
16465        .expect("read");
16466
16467        assert!(roundtrip.equals(&frame));
16468        assert_eq!(roundtrip.row_multiindex(), frame.row_multiindex());
16469    }
16470
16471    #[test]
16472    fn test_write_csv_options_default_matches_write_csv_string() {
16473        let input = "a,b\n1,2\n3,4\n";
16474        let frame = read_csv_str(input).expect("read");
16475        let default_output = write_csv_string(&frame).expect("write");
16476        let options_output =
16477            write_csv_string_with_options(&frame, &CsvWriteOptions::default()).expect("write");
16478        assert_eq!(default_output, options_output);
16479    }
16480
16481    #[test]
16482    fn test_write_csv_options_na_rep_with_float_nan() {
16483        // Generate a frame with an explicit NaN float.
16484        use fp_columnar::Column;
16485        let mut cols = std::collections::BTreeMap::new();
16486        cols.insert(
16487            "score".to_string(),
16488            Column::from_values(vec![Scalar::Float64(1.5), Scalar::Float64(f64::NAN)]).unwrap(),
16489        );
16490        let frame = DataFrame::new_with_column_order(
16491            Index::from_i64(vec![0, 1]),
16492            cols,
16493            vec!["score".to_string()],
16494        )
16495        .unwrap();
16496        let output = write_csv_string_with_options(
16497            &frame,
16498            &CsvWriteOptions {
16499                na_rep: "NaN".to_string(),
16500                ..CsvWriteOptions::default()
16501            },
16502        )
16503        .expect("write");
16504        assert!(output.contains("NaN"));
16505    }
16506
16507    #[test]
16508    fn test_csv_large_file_perf() {
16509        // 100K-row, 10-column CSV -> parse completes, correct row/column counts.
16510        let col_count = 10;
16511        let row_count = 100_000;
16512        let headers: Vec<String> = (0..col_count).map(|i| format!("col{i}")).collect();
16513        let mut csv = String::with_capacity(row_count * 50);
16514        csv.push_str(&headers.join(","));
16515        csv.push('\n');
16516        for r in 0..row_count {
16517            for c in 0..col_count {
16518                if c > 0 {
16519                    csv.push(',');
16520                }
16521                csv.push_str(&(r * col_count + c).to_string());
16522            }
16523            csv.push('\n');
16524        }
16525
16526        let frame = read_csv_str(&csv).expect("parse 100K rows");
16527        assert_eq!(frame.index().len(), row_count);
16528        assert_eq!(frame.columns().len(), col_count);
16529        // Spot-check first and last rows
16530        assert_eq!(frame.column("col0").unwrap().values()[0], Scalar::Int64(0));
16531        assert_eq!(
16532            frame.column("col9").unwrap().values()[row_count - 1],
16533            Scalar::Int64(((row_count - 1) * col_count + 9) as i64)
16534        );
16535        eprintln!(
16536            "[TEST] test_csv_large_file_perf | rows={row_count} cols={col_count} parse_ok=true | PASS"
16537        );
16538    }
16539
16540    #[test]
16541    fn test_csv_golden_output() {
16542        // Fixed CSV input -> write_csv_string output matches golden reference exactly.
16543        let input = "a,b,c\n1,hello,3.14\n2,,true\n3,world,\n";
16544        let frame = read_csv_str(input).expect("parse");
16545        let output = write_csv_string(&frame).expect("write");
16546
16547        // Golden reference: columns in BTreeMap order; Bool(true) coerced to Float64
16548        // in column c (which has Float64 + Bool → Float64), so true → 1.0. A Float64
16549        // column writes whole values with a trailing ".0" like pandas (str(float)).
16550        let expected = "a,b,c\n1,hello,3.14\n2,,1.0\n3,world,\n";
16551        assert_eq!(
16552            output, expected,
16553            "output does not match golden reference.\nGot:\n{output}\nExpected:\n{expected}"
16554        );
16555        eprintln!("[TEST] test_csv_golden_output | golden_match=true | PASS");
16556    }
16557
16558    // === bd-2gi.19: IO Complete Contract Tests ===
16559
16560    use super::{CsvOnBadLines, CsvReadOptions, read_csv_with_options};
16561
16562    #[test]
16563    fn csv_with_custom_delimiter() {
16564        let input = "a\tb\tc\n1\t2\t3\n4\t5\t6\n";
16565        let opts = CsvReadOptions {
16566            delimiter: b'\t',
16567            ..Default::default()
16568        };
16569        let frame = read_csv_with_options(input, &opts).expect("parse tsv");
16570        assert_eq!(frame.index().len(), 2);
16571        assert_eq!(frame.column("a").unwrap().values()[0], Scalar::Int64(1));
16572    }
16573
16574    #[test]
16575    fn csv_without_headers_generates_default_names_and_keeps_first_row() {
16576        let input = "1,2\n3,4\n";
16577        let opts = CsvReadOptions {
16578            has_headers: false,
16579            ..Default::default()
16580        };
16581        let frame = read_csv_with_options(input, &opts).expect("parse");
16582        assert_eq!(frame.index().len(), 2);
16583        assert_eq!(
16584            frame.column("column_0").unwrap().values()[0],
16585            Scalar::Int64(1)
16586        );
16587        assert_eq!(
16588            frame.column("column_1").unwrap().values()[0],
16589            Scalar::Int64(2)
16590        );
16591        assert_eq!(
16592            frame.column("column_0").unwrap().values()[1],
16593            Scalar::Int64(3)
16594        );
16595        assert_eq!(
16596            frame.column("column_1").unwrap().values()[1],
16597            Scalar::Int64(4)
16598        );
16599    }
16600
16601    #[test]
16602    fn csv_usecols_missing_column_errors() {
16603        let input = "a,b\n1,2\n";
16604        let opts = CsvReadOptions {
16605            usecols: Some(vec!["c".to_string()]),
16606            ..Default::default()
16607        };
16608        let err = read_csv_with_options(input, &opts).expect_err("missing usecols");
16609        assert!(
16610            matches!(err, IoError::MissingUsecols(missing) if missing == vec!["c".to_string()])
16611        );
16612    }
16613
16614    #[test]
16615    fn csv_without_headers_supports_generated_index_col_name() {
16616        let input = "10,alpha\n20,beta\n";
16617        let opts = CsvReadOptions {
16618            has_headers: false,
16619            index_col: Some("column_0".into()),
16620            ..Default::default()
16621        };
16622        let frame = read_csv_with_options(input, &opts).expect("parse");
16623        assert_eq!(frame.index().len(), 2);
16624        assert_eq!(frame.index().labels()[0], IndexLabel::Int64(10));
16625        assert_eq!(frame.index().labels()[1], IndexLabel::Int64(20));
16626        assert!(frame.column("column_0").is_none());
16627        assert_eq!(
16628            frame.column("column_1").unwrap().values()[0],
16629            Scalar::Utf8("alpha".into())
16630        );
16631        assert_eq!(
16632            frame.column("column_1").unwrap().values()[1],
16633            Scalar::Utf8("beta".into())
16634        );
16635    }
16636
16637    #[test]
16638    fn csv_with_na_values() {
16639        let input = "a,b\n1,NA\n2,n/a\n3,valid\n";
16640        let opts = CsvReadOptions {
16641            na_values: vec!["NA".into(), "n/a".into()],
16642            ..Default::default()
16643        };
16644        let frame = read_csv_with_options(input, &opts).expect("parse");
16645        let b = frame.column("b").unwrap();
16646        assert!(b.values()[0].is_missing());
16647        assert!(b.values()[1].is_missing());
16648        assert_eq!(b.values()[2], Scalar::Utf8("valid".into()));
16649    }
16650
16651    #[test]
16652    fn csv_none_is_default_na() {
16653        // "None" is a pandas default NA value (Python's None)
16654        let input = "a,b\n1,None\n2,valid\n";
16655        let frame = read_csv_str(input).expect("parse");
16656        let b = frame.column("b").unwrap();
16657        assert!(b.values()[0].is_missing(), "None should be parsed as NA");
16658        assert_eq!(b.values()[1], Scalar::Utf8("valid".into()));
16659    }
16660
16661    #[test]
16662    fn csv_scalar_inference_matches_pandas_2_2_3() {
16663        // Per-cell type inference verified against pandas 2.2.3 read_csv.
16664        let cell = |csv: &str| {
16665            let frame = read_csv_str(&format!("x\n{csv}\n")).expect("parse");
16666            frame.column("x").unwrap().values()[0].clone()
16667        };
16668        // Signed / leading-zero integers parse as Int64 (Rust + pandas agree).
16669        assert_eq!(cell("+1"), Scalar::Int64(1));
16670        assert_eq!(cell("01"), Scalar::Int64(1));
16671        assert_eq!(cell("-5"), Scalar::Int64(-5));
16672        // Scientific notation is float64 in pandas.
16673        assert_eq!(cell("1e3"), Scalar::Float64(1000.0));
16674        // inf / -inf are float values (NOT default-NA tokens, unlike nan).
16675        assert_eq!(cell("inf"), Scalar::Float64(f64::INFINITY));
16676        assert_eq!(cell("-inf"), Scalar::Float64(f64::NEG_INFINITY));
16677        // Bool inference is case-insensitive in pandas 2.2.3.
16678        assert_eq!(cell("TRUE"), Scalar::Bool(true));
16679        assert_eq!(cell("true"), Scalar::Bool(true));
16680        assert_eq!(cell("False"), Scalar::Bool(false));
16681        // Surrounding whitespace is trimmed ONLY for numeric inference.
16682        assert_eq!(cell(" 1 "), Scalar::Int64(1));
16683        assert_eq!(cell("  3.5  "), Scalar::Float64(3.5));
16684        // Non-numeric, non-bool stays Utf8.
16685        assert_eq!(cell("hello"), Scalar::Utf8("hello".into()));
16686        // NA markers, booleans, and plain strings keep their surrounding
16687        // whitespace — a padded value is a STRING, not null/bool. Verified vs
16688        // live pandas 2.2.3: " abc "/"true "/" NA " all stay object strings.
16689        assert_eq!(cell(" abc "), Scalar::Utf8(" abc ".into()));
16690        assert_eq!(cell("true "), Scalar::Utf8("true ".into()));
16691        assert_eq!(cell(" True "), Scalar::Utf8(" True ".into()));
16692        assert_eq!(cell(" NA "), Scalar::Utf8(" NA ".into()));
16693        assert!(!matches!(cell(" NA "), Scalar::Null(_)));
16694    }
16695
16696    #[test]
16697    fn json_write_non_finite_floats_as_null_like_pandas() {
16698        // pandas to_json(orient="records") converts inf / -inf / NaN to JSON
16699        // `null` (JSON has no inf/nan literals). Verified vs pandas 2.2.3:
16700        // read_csv("x\n1.5\ninf\n-inf\n").to_json(orient="records")
16701        //   == [{"x":1.5},{"x":null},{"x":null}]
16702        let frame = read_csv_str("x\n1.5\ninf\n-inf\n").expect("parse");
16703        let json = write_json_string(&frame, JsonOrient::Records).expect("json");
16704        assert_eq!(json, r#"[{"x":1.5},{"x":null},{"x":null}]"#);
16705    }
16706
16707    #[test]
16708    fn csv_default_na_token_set_matches_pandas_table() {
16709        let default_tokens = [
16710            "", "#N/A", "#N/A N/A", "#NA", "-1.#IND", "-1.#QNAN", "-NaN", "-nan", "1.#IND",
16711            "1.#QNAN", "<NA>", "N/A", "NA", "NULL", "NaN", "None", "n/a", "nan", "null",
16712        ];
16713        for token in default_tokens {
16714            assert!(super::is_pandas_default_na(token), "{token:?}");
16715        }
16716
16717        for token in ["none", "NAN", "n/a ", " NULL", "0", "false"] {
16718            assert!(!super::is_pandas_default_na(token), "{token:?}");
16719        }
16720    }
16721
16722    #[test]
16723    fn csv_keep_default_na_false() {
16724        // With keep_default_na=false, only custom na_values are recognized
16725        let input = "a,b\n1,NA\n2,CUSTOM\n3,valid\n";
16726        let opts = CsvReadOptions {
16727            na_values: vec!["CUSTOM".into()],
16728            keep_default_na: false,
16729            ..Default::default()
16730        };
16731        let frame = read_csv_with_options(input, &opts).expect("parse");
16732        let b = frame.column("b").unwrap();
16733        // "NA" should NOT be missing because keep_default_na=false
16734        assert_eq!(b.values()[0], Scalar::Utf8("NA".into()));
16735        // "CUSTOM" should be missing because it's in na_values
16736        assert!(b.values()[1].is_missing());
16737        assert_eq!(b.values()[2], Scalar::Utf8("valid".into()));
16738    }
16739
16740    #[test]
16741    fn csv_na_filter_false() {
16742        // With na_filter=false, no NA detection at all (for performance)
16743        let input = "a,b\n1,NA\n2,\n3,None\n";
16744        let opts = CsvReadOptions {
16745            na_filter: false,
16746            ..Default::default()
16747        };
16748        let frame = read_csv_with_options(input, &opts).expect("parse");
16749        let b = frame.column("b").unwrap();
16750        // All values should be kept as strings, no NA detection
16751        assert_eq!(b.values()[0], Scalar::Utf8("NA".into()));
16752        assert_eq!(b.values()[1], Scalar::Utf8("".into()));
16753        assert_eq!(b.values()[2], Scalar::Utf8("None".into()));
16754    }
16755
16756    #[test]
16757    fn csv_with_index_col() {
16758        let input = "id,val\na,10\nb,20\nc,30\n";
16759        let opts = CsvReadOptions {
16760            index_col: Some("id".into()),
16761            ..Default::default()
16762        };
16763        let frame = read_csv_with_options(input, &opts).expect("parse");
16764        assert_eq!(frame.index().len(), 3);
16765        assert_eq!(
16766            frame.index().labels()[0],
16767            fp_index::IndexLabel::Utf8("a".into())
16768        );
16769        assert!(frame.column("id").is_none());
16770        assert_eq!(frame.column("val").unwrap().values()[0], Scalar::Int64(10));
16771    }
16772
16773    #[test]
16774    fn csv_with_missing_index_col_errors() {
16775        let input = "id,val\na,10\nb,20\n";
16776        let opts = CsvReadOptions {
16777            index_col: Some("missing".into()),
16778            ..Default::default()
16779        };
16780
16781        let err = read_csv_with_options(input, &opts).expect_err("missing index_col should error");
16782        assert!(
16783            matches!(&err, IoError::MissingIndexColumn(name) if name == "missing"),
16784            "expected MissingIndexColumn(\"missing\"), got {err:?}"
16785        );
16786    }
16787
16788    #[test]
16789    fn csv_with_malformed_row_errors() {
16790        let input = "a,b\n1,2\n3\n";
16791        let opts = CsvReadOptions::default();
16792
16793        let err = read_csv_with_options(input, &opts).expect_err("malformed CSV row should error");
16794        assert!(
16795            matches!(&err, IoError::Csv(_)),
16796            "expected CSV parser error for ragged row, got {err:?}"
16797        );
16798    }
16799
16800    #[test]
16801    fn csv_on_bad_lines_skip_skips_extra_field_rows() {
16802        let input = "a,b\n1,2\n3,4,5\n6,7\n";
16803        let opts = CsvReadOptions {
16804            on_bad_lines: CsvOnBadLines::Skip,
16805            ..Default::default()
16806        };
16807
16808        let frame = read_csv_with_options(input, &opts).expect("parse with skipped bad line");
16809        assert_eq!(frame.index().len(), 2);
16810        assert_eq!(frame.column("a").unwrap().values()[0], Scalar::Int64(1));
16811        assert_eq!(frame.column("b").unwrap().values()[0], Scalar::Int64(2));
16812        assert_eq!(frame.column("a").unwrap().values()[1], Scalar::Int64(6));
16813        assert_eq!(frame.column("b").unwrap().values()[1], Scalar::Int64(7));
16814    }
16815
16816    #[test]
16817    fn csv_on_bad_lines_warn_skips_extra_field_rows() {
16818        let input = "a,b\n1,2\n3,4,5\n6,7\n";
16819        let opts = CsvReadOptions {
16820            on_bad_lines: CsvOnBadLines::Warn,
16821            ..Default::default()
16822        };
16823
16824        let frame = read_csv_with_options(input, &opts).expect("parse with warned bad line");
16825        assert_eq!(frame.index().len(), 2);
16826        assert_eq!(frame.column("a").unwrap().values()[0], Scalar::Int64(1));
16827        assert_eq!(frame.column("b").unwrap().values()[1], Scalar::Int64(7));
16828    }
16829
16830    #[test]
16831    fn csv_on_bad_lines_skip_preserves_short_rows_as_missing() {
16832        // DISC-011: Int64 columns with missing values stay Int64 (extension dtype parity).
16833        // Missing values use NullKind::Null (pd.NA semantics) not NullKind::NaN.
16834        let input = "a,b\n1,2\n3\n6,7\n";
16835        let opts = CsvReadOptions {
16836            on_bad_lines: CsvOnBadLines::Skip,
16837            ..Default::default()
16838        };
16839
16840        let frame = read_csv_with_options(input, &opts).expect("parse short row");
16841        assert_eq!(frame.index().len(), 3);
16842        assert_eq!(frame.column("a").unwrap().values()[1], Scalar::Int64(3));
16843        assert_eq!(
16844            frame.column("b").unwrap().values()[1],
16845            Scalar::Null(NullKind::Null)
16846        );
16847    }
16848
16849    #[test]
16850    fn json_temporal_values_and_index_are_epoch_millis() {
16851        // pandas to_json (date_unit='ms') serializes datetime64/timedelta64 as
16852        // epoch-millisecond integers for both values and index — not ISO/format
16853        // strings (values) nor raw nanoseconds (index). (br-frankenpandas-lb0iu)
16854        // 2020-01-01T00:00:00 == 1_577_836_800_000 ms; 1s timedelta == 1000 ms.
16855        let dt_ns = 1_577_836_800_000_000_000_i64;
16856        let mut columns = BTreeMap::new();
16857        columns.insert(
16858            "d".to_owned(),
16859            Column::from_values(vec![Scalar::Datetime64(dt_ns)]).expect("d"),
16860        );
16861        columns.insert(
16862            "t".to_owned(),
16863            Column::from_values(vec![Scalar::Timedelta64(1_000_000_000)]).expect("t"),
16864        );
16865        let index = Index::new(vec![IndexLabel::Datetime64(dt_ns)]);
16866        let frame =
16867            DataFrame::new_with_column_order(index, columns, vec!["d".to_owned(), "t".to_owned()])
16868                .expect("frame");
16869
16870        let out = write_json_string(&frame, JsonOrient::Columns).expect("json");
16871        assert!(
16872            out.contains("1577836800000"),
16873            "datetime value/index should be epoch-millis int, got {out}"
16874        );
16875        assert!(
16876            out.contains("1000"),
16877            "timedelta value should be epoch-millis int (1000), got {out}"
16878        );
16879        // Must NOT contain the old ISO string or raw-nanosecond forms.
16880        assert!(
16881            !out.contains("2020-01-01"),
16882            "should not emit ISO string: {out}"
16883        );
16884        assert!(
16885            !out.contains("1577836800000000000"),
16886            "should not emit raw nanoseconds: {out}"
16887        );
16888    }
16889
16890    #[test]
16891    fn json_records_read_write_roundtrip() {
16892        let input = r#"[{"name":"Alice","age":30},{"name":"Bob","age":25}]"#;
16893        let frame = read_json_str(input, JsonOrient::Records).expect("read json records");
16894        assert_eq!(frame.index().len(), 2);
16895        assert_eq!(
16896            frame.column("name").unwrap().values()[0],
16897            Scalar::Utf8("Alice".into())
16898        );
16899        assert_eq!(frame.column("age").unwrap().values()[1], Scalar::Int64(25));
16900
16901        let output = write_json_string(&frame, JsonOrient::Records).expect("write");
16902        let frame2 = read_json_str(&output, JsonOrient::Records).expect("re-read");
16903        assert_eq!(frame2.index().len(), 2);
16904    }
16905
16906    #[test]
16907    fn json_records_nullable_int_roundtrip_is_stable() {
16908        let input = r#"[{"city":"Boston","temp":72},{"city":"Paris","temp":null}]"#;
16909        let frame = read_json_str(input, JsonOrient::Records).expect("read json records");
16910        let output = write_json_string(&frame, JsonOrient::Records).expect("write records");
16911        let frame2 = read_json_str(&output, JsonOrient::Records).expect("re-read records");
16912
16913        assert!(frame.equals(&frame2));
16914    }
16915
16916    #[test]
16917    fn json_records_preserves_column_order() {
16918        let input = r#"[{"b":1,"a":2},{"c":3}]"#;
16919        let frame = read_json_str(input, JsonOrient::Records).expect("read json records");
16920        let order: Vec<&str> = frame
16921            .column_names()
16922            .iter()
16923            .map(|name| name.as_str())
16924            .collect();
16925        assert_eq!(order, vec!["b", "a", "c"]);
16926    }
16927
16928    #[test]
16929    fn json_columns_read_write_roundtrip() {
16930        let input = r#"{"name":{"row_a":"Alice","row_b":"Bob"},"age":{"row_a":30,"row_b":25}}"#;
16931        let frame = read_json_str(input, JsonOrient::Columns).expect("read json columns");
16932        assert_eq!(frame.index().len(), 2);
16933        assert_eq!(frame.index().labels()[0], IndexLabel::Utf8("row_a".into()));
16934
16935        let output = write_json_string(&frame, JsonOrient::Columns).expect("write");
16936        let frame2 = read_json_str(&output, JsonOrient::Columns).expect("re-read");
16937        assert_eq!(frame2.index().labels(), frame.index().labels());
16938    }
16939
16940    #[test]
16941    fn json_columns_write_duplicate_index_rejects() {
16942        let index = Index::new(vec![IndexLabel::Int64(1), IndexLabel::Utf8("1".into())]);
16943        let mut columns = BTreeMap::new();
16944        columns.insert(
16945            "v".into(),
16946            Column::from_values(vec![Scalar::Int64(10), Scalar::Int64(20)]).expect("col"),
16947        );
16948        let frame = DataFrame::new(index, columns).expect("frame");
16949
16950        let err = write_json_string(&frame, JsonOrient::Columns)
16951            .expect_err("duplicate JSON object keys should reject");
16952        assert!(
16953            matches!(&err, IoError::JsonFormat(msg) if msg.contains("duplicate index label key")),
16954            "expected duplicate-index-key JsonFormat, got {err:?}"
16955        );
16956    }
16957
16958    #[test]
16959    fn json_split_read_write_roundtrip() {
16960        let input = r#"{"columns":["x","y"],"index":["r1","r2","r3"],"data":[[1,4],[2,5],[3,6]]}"#;
16961        let frame = read_json_str(input, JsonOrient::Split).expect("read json split");
16962        assert_eq!(frame.index().len(), 3);
16963        assert_eq!(
16964            frame.index().labels()[0],
16965            fp_index::IndexLabel::Utf8("r1".into())
16966        );
16967        assert_eq!(frame.column("x").unwrap().values()[0], Scalar::Int64(1));
16968        assert_eq!(frame.column("y").unwrap().values()[2], Scalar::Int64(6));
16969
16970        let output = write_json_string(&frame, JsonOrient::Split).expect("write");
16971        let frame2 = read_json_str(&output, JsonOrient::Split).expect("re-read");
16972        assert_eq!(frame2.index().len(), 3);
16973        assert_eq!(frame2.index().labels(), frame.index().labels());
16974    }
16975
16976    #[test]
16977    fn json_records_multiindex_roundtrip_restores_logical_row_axis() {
16978        let frame = make_row_multiindex_test_dataframe();
16979        let json = write_json_string(&frame, JsonOrient::Records).expect("write");
16980        let roundtrip = read_json_str(&json, JsonOrient::Records).expect("read");
16981
16982        assert!(roundtrip.equals(&frame));
16983        assert!(roundtrip.row_multiindex().is_some());
16984        assert!(roundtrip.column("__index_level_0__").is_none());
16985    }
16986
16987    #[test]
16988    fn json_split_multiindex_roundtrip_restores_logical_row_axis() {
16989        let frame = make_row_multiindex_test_dataframe();
16990        let json = write_json_string(&frame, JsonOrient::Split).expect("write");
16991        let roundtrip = read_json_str(&json, JsonOrient::Split).expect("read");
16992
16993        assert!(roundtrip.equals(&frame));
16994        assert!(roundtrip.row_multiindex().is_some());
16995        assert!(roundtrip.column("__index_level_0__").is_none());
16996    }
16997
16998    #[test]
16999    fn json_split_without_index_defaults_to_range_index() {
17000        let input = r#"{"columns":["x"],"data":[[10],[20]]}"#;
17001        let frame = read_json_str(input, JsonOrient::Split).expect("read json split");
17002        assert_eq!(frame.index().labels()[0], fp_index::IndexLabel::Int64(0));
17003        assert_eq!(frame.index().labels()[1], fp_index::IndexLabel::Int64(1));
17004    }
17005
17006    #[test]
17007    fn json_split_index_length_mismatch_errors() {
17008        let input = r#"{"columns":["x"],"index":[0],"data":[[1],[2]]}"#;
17009        let err = read_json_str(input, JsonOrient::Split)
17010            .expect_err("split orient index/data length mismatch should error");
17011        assert!(
17012            matches!(&err, IoError::JsonFormat(msg) if msg.contains("index length")),
17013            "expected split index length error, got {err:?}"
17014        );
17015    }
17016
17017    #[test]
17018    fn json_split_row_length_mismatch_errors() {
17019        let input = r#"{"columns":["x","y"],"data":[[1],[2,3]]}"#;
17020        let err = read_json_str(input, JsonOrient::Split)
17021            .expect_err("split orient row length mismatch should error");
17022        assert!(
17023            matches!(&err, IoError::JsonFormat(msg) if msg.contains("row 0 length")),
17024            "expected split row length error, got {err:?}"
17025        );
17026    }
17027
17028    #[test]
17029    fn json_split_non_string_columns_are_stringified() {
17030        let input = r#"{"columns":[1,true,null,"name"],"data":[[10,20,30,40]]}"#;
17031        let frame = read_json_str(input, JsonOrient::Split).expect("read json split");
17032        assert_eq!(frame.column("1").unwrap().values()[0], Scalar::Int64(10));
17033        assert_eq!(frame.column("true").unwrap().values()[0], Scalar::Int64(20));
17034        assert_eq!(frame.column("null").unwrap().values()[0], Scalar::Int64(30));
17035        assert_eq!(frame.column("name").unwrap().values()[0], Scalar::Int64(40));
17036    }
17037
17038    #[test]
17039    fn json_split_duplicate_column_names_error() {
17040        let input = r#"{"columns":[1,"1"],"data":[[10,20]]}"#;
17041        let err = read_json_str(input, JsonOrient::Split).expect_err("dup columns");
17042        assert!(matches!(err, IoError::DuplicateColumnName(name) if name == "1"));
17043    }
17044
17045    #[test]
17046    fn json_index_read_write_roundtrip() {
17047        let input = r#"{"row_a":{"name":"Alice","age":30},"row_b":{"name":"Bob","age":25}}"#;
17048        let frame = read_json_str(input, JsonOrient::Index).expect("read json index");
17049        assert_eq!(frame.index().len(), 2);
17050        assert_eq!(frame.index().labels()[0], IndexLabel::Utf8("row_a".into()));
17051        assert_eq!(
17052            frame.column("name").unwrap().values()[1],
17053            Scalar::Utf8("Bob".into())
17054        );
17055
17056        let output = write_json_string(&frame, JsonOrient::Index).expect("write");
17057        let frame2 = read_json_str(&output, JsonOrient::Index).expect("re-read");
17058        assert_eq!(frame2.index().labels(), frame.index().labels());
17059        assert_eq!(frame2.column("age").unwrap().values()[0], Scalar::Int64(30));
17060    }
17061
17062    #[test]
17063    fn json_index_preserves_column_order() {
17064        let input = r#"{"r1":{"b":1,"a":2},"r2":{"c":3}}"#;
17065        let frame = read_json_str(input, JsonOrient::Index).expect("parse");
17066        let order: Vec<&str> = frame
17067            .column_names()
17068            .iter()
17069            .map(|name| name.as_str())
17070            .collect();
17071        assert_eq!(order, vec!["b", "a", "c"]);
17072    }
17073
17074    #[test]
17075    fn json_index_missing_columns_null_fill() {
17076        let input = r#"{"r1":{"a":1},"r2":{"b":2}}"#;
17077        let frame = read_json_str(input, JsonOrient::Index).expect("parse");
17078        let a = frame.column("a").expect("a");
17079        let b = frame.column("b").expect("b");
17080
17081        assert_eq!(a.values()[0], Scalar::Float64(1.0));
17082        assert!(a.values()[1].is_missing());
17083        assert!(b.values()[0].is_missing());
17084        assert_eq!(b.values()[1], Scalar::Float64(2.0));
17085    }
17086
17087    #[test]
17088    fn json_index_write_duplicate_index_rejects() {
17089        let index = Index::new(vec![IndexLabel::Int64(1), IndexLabel::Utf8("1".into())]);
17090        let mut columns = BTreeMap::new();
17091        columns.insert(
17092            "v".into(),
17093            Column::from_values(vec![Scalar::Int64(10), Scalar::Int64(20)]).expect("col"),
17094        );
17095        let frame = DataFrame::new(index, columns).expect("frame");
17096
17097        let err = write_json_string(&frame, JsonOrient::Index)
17098            .expect_err("duplicate JSON object keys should reject");
17099        assert!(
17100            matches!(&err, IoError::JsonFormat(msg) if msg.contains("duplicate index label key")),
17101            "expected duplicate-index-key JsonFormat, got {err:?}"
17102        );
17103    }
17104
17105    #[test]
17106    fn json_index_read_non_object_row_rejects() {
17107        let input = r#"{"r1":{"a":1},"r2":[1,2]}"#;
17108        let err = read_json_str(input, JsonOrient::Index)
17109            .expect_err("index orient rows must be JSON objects");
17110        assert!(
17111            matches!(&err, IoError::JsonFormat(msg) if msg.contains("rows must be objects")),
17112            "expected row-object error, got {err:?}"
17113        );
17114    }
17115
17116    #[test]
17117    fn json_values_read_write_roundtrip() {
17118        let input = r#"[[1,"Alice"],[null,"Bob"]]"#;
17119        let frame = read_json_str(input, JsonOrient::Values).expect("read json values");
17120        assert_eq!(frame.index().len(), 2);
17121        assert_eq!(frame.column_names(), vec!["0", "1"]);
17122        assert_eq!(frame.column("0").unwrap().values()[0], Scalar::Float64(1.0));
17123        assert_eq!(
17124            frame.column("1").unwrap().values()[1],
17125            Scalar::Utf8("Bob".into())
17126        );
17127
17128        let output = write_json_string(&frame, JsonOrient::Values).expect("write");
17129        let frame2 = read_json_str(&output, JsonOrient::Values).expect("re-read");
17130        assert_eq!(frame2.index().len(), 2);
17131        assert_eq!(frame2.column_names(), frame.column_names());
17132        assert_eq!(
17133            frame2.column("0").unwrap().values(),
17134            frame.column("0").unwrap().values()
17135        );
17136        assert_eq!(
17137            frame2.column("1").unwrap().values(),
17138            frame.column("1").unwrap().values()
17139        );
17140    }
17141
17142    #[test]
17143    fn json_records_with_nulls() {
17144        let input = r#"[{"a":1,"b":null},{"a":null,"b":"hello"}]"#;
17145        let frame = read_json_str(input, JsonOrient::Records).expect("parse");
17146        assert!(frame.column("a").unwrap().values()[1].is_missing());
17147        assert!(frame.column("b").unwrap().values()[0].is_missing());
17148    }
17149
17150    #[test]
17151    fn json_read_accepts_pandas_bare_nan_tokens() {
17152        let cases = [
17153            (JsonOrient::Records, r#"[{"a":NaN}]"#),
17154            (JsonOrient::Columns, r#"{"a":{"0":NaN}}"#),
17155            (
17156                JsonOrient::Split,
17157                r#"{"columns":["a"],"index":[0],"data":[[NaN]]}"#,
17158            ),
17159            (JsonOrient::Values, r#"[[NaN]]"#),
17160        ];
17161
17162        for (orient, input) in cases {
17163            let frame = read_json_str(input, orient).expect("parse bare NaN");
17164            let column_name = if orient == JsonOrient::Values {
17165                "0"
17166            } else {
17167                "a"
17168            };
17169            assert!(frame.column(column_name).unwrap().values()[0].is_missing());
17170        }
17171    }
17172
17173    #[test]
17174    fn json_records_write_preserves_nullable_int_column() {
17175        // DISC-011: Nullable extension Int64 dtype parity - Int64 preserved, not promoted to Float64.
17176        let frame = DataFrame::from_dict_with_index(
17177            vec![("a", vec![Scalar::Int64(1), Scalar::Null(NullKind::Null)])],
17178            vec!["row".into(), "row".into()],
17179        )
17180        .unwrap();
17181        let json = write_json_string(&frame, JsonOrient::Records).expect("write");
17182        let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();
17183        assert_eq!(parsed, serde_json::json!([{"a": 1}, {"a": null}]));
17184    }
17185
17186    #[test]
17187    fn json_non_records_nullable_int_reads_promote_to_float() {
17188        let cases = [
17189            (JsonOrient::Columns, r#"{"a":{"0":1,"1":null}}"#),
17190            (JsonOrient::Index, r#"{"0":{"a":1},"1":{"a":null}}"#),
17191            (
17192                JsonOrient::Split,
17193                r#"{"columns":["a"],"index":[0,1],"data":[[1],[null]]}"#,
17194            ),
17195            (JsonOrient::Values, r#"[[1],[null]]"#),
17196        ];
17197
17198        for (orient, input) in cases {
17199            let frame = read_json_str(input, orient).expect("read json");
17200            let column_name = if orient == JsonOrient::Values {
17201                "0"
17202            } else {
17203                "a"
17204            };
17205            let values = frame.column(column_name).expect("column").values();
17206            assert_eq!(values[0], Scalar::Float64(1.0));
17207            assert!(matches!(values[1], Scalar::Null(NullKind::NaN)));
17208        }
17209    }
17210
17211    #[test]
17212    fn json_non_records_nullable_int_writes_preserve_int() {
17213        // DISC-011: Nullable extension Int64 dtype parity - Int64 preserved, not promoted to Float64.
17214        let frame = DataFrame::from_dict(
17215            &["a"],
17216            vec![("a", vec![Scalar::Int64(1), Scalar::Null(NullKind::Null)])],
17217        )
17218        .unwrap();
17219
17220        let columns_json: serde_json::Value =
17221            serde_json::from_str(&write_json_string(&frame, JsonOrient::Columns).unwrap()).unwrap();
17222        assert_eq!(columns_json, serde_json::json!({"a": {"0": 1, "1": null}}));
17223
17224        let index_json: serde_json::Value =
17225            serde_json::from_str(&write_json_string(&frame, JsonOrient::Index).unwrap()).unwrap();
17226        assert_eq!(
17227            index_json,
17228            serde_json::json!({"0": {"a": 1}, "1": {"a": null}})
17229        );
17230
17231        let split_json: serde_json::Value =
17232            serde_json::from_str(&write_json_string(&frame, JsonOrient::Split).unwrap()).unwrap();
17233        assert_eq!(
17234            split_json,
17235            serde_json::json!({"columns": ["a"], "index": [0, 1], "data": [[1], [null]]})
17236        );
17237
17238        let values_json: serde_json::Value =
17239            serde_json::from_str(&write_json_string(&frame, JsonOrient::Values).unwrap()).unwrap();
17240        assert_eq!(values_json, serde_json::json!([[1], [null]]));
17241    }
17242
17243    #[test]
17244    fn json_records_empty_array() {
17245        let input = r#"[]"#;
17246        let frame = read_json_str(input, JsonOrient::Records).expect("parse");
17247        assert_eq!(frame.index().len(), 0);
17248    }
17249
17250    #[test]
17251    fn json_records_mixed_numeric_coerces() {
17252        let input = r#"[{"v":1},{"v":2.5},{"v":true}]"#;
17253        let frame = read_json_str(input, JsonOrient::Records).expect("parse");
17254        // Int64 + Float64 + Bool all coerce to Float64
17255        assert_eq!(frame.column("v").unwrap().values()[0], Scalar::Float64(1.0));
17256        assert_eq!(frame.column("v").unwrap().values()[1], Scalar::Float64(2.5));
17257        assert_eq!(frame.column("v").unwrap().values()[2], Scalar::Float64(1.0));
17258    }
17259
17260    #[test]
17261    fn json_records_mixed_utf8_numeric_preserves_object_values() {
17262        let input = r#"[{"v":1},{"v":"text"}]"#;
17263        let frame = read_json_str(input, JsonOrient::Records).expect("parse");
17264        assert_eq!(
17265            frame.column("v").unwrap().values(),
17266            &[Scalar::Int64(1), Scalar::Utf8("text".into())]
17267        );
17268    }
17269
17270    #[test]
17271    fn file_csv_roundtrip() {
17272        let input = "a,b\n1,2\n3,4\n";
17273        let frame = read_csv_str(input).expect("parse");
17274
17275        let dir = std::env::temp_dir();
17276        let path = dir.join("fp_io_test_roundtrip.csv");
17277        super::write_csv(&frame, &path).expect("write file");
17278        let frame2 = super::read_csv(&path).expect("read file");
17279        assert_eq!(frame2.index().len(), 2);
17280        std::fs::remove_file(&path).ok();
17281    }
17282
17283    #[test]
17284    fn file_csv_with_options_path() {
17285        // DISC-011: Nullable extension Int64 dtype parity - Int64 preserved, not promoted to Float64.
17286        let input = "id\tval\na\tNA\nb\t2\n";
17287        let dir = std::env::temp_dir();
17288        let path = dir.join("fp_io_test_options.csv");
17289        std::fs::write(&path, input).expect("write fixture");
17290
17291        let options = CsvReadOptions {
17292            delimiter: b'\t',
17293            na_values: vec!["NA".into()],
17294            index_col: Some("id".into()),
17295            ..Default::default()
17296        };
17297
17298        let frame = super::read_csv_with_options_path(&path, &options).expect("read with options");
17299        assert_eq!(
17300            frame.index().labels()[0],
17301            fp_index::IndexLabel::Utf8("a".into())
17302        );
17303        assert!(frame.column("id").is_none());
17304        assert!(frame.column("val").unwrap().values()[0].is_missing());
17305        assert_eq!(frame.column("val").unwrap().values()[1], Scalar::Int64(2));
17306
17307        std::fs::remove_file(&path).ok();
17308    }
17309
17310    #[test]
17311    fn file_json_roundtrip() {
17312        let input = r#"[{"x":1},{"x":2}]"#;
17313        let frame = read_json_str(input, JsonOrient::Records).expect("parse");
17314
17315        let dir = std::env::temp_dir();
17316        let path = dir.join("fp_io_test_roundtrip.json");
17317        super::write_json(&frame, &path, JsonOrient::Records).expect("write file");
17318        let frame2 = super::read_json(&path, JsonOrient::Records).expect("read file");
17319        assert_eq!(frame2.index().len(), 2);
17320        std::fs::remove_file(&path).ok();
17321    }
17322
17323    // ── read_table 4pwr9 ───────────────────────────────────────────────
17324
17325    #[test]
17326    fn read_table_str_parses_tab_separated_4pwr9() {
17327        let input = "a\tb\tc\n1\t2\t3\n4\t5\t6\n";
17328        let frame = super::read_table_str(input).expect("parse tsv");
17329        assert_eq!(frame.index().len(), 2);
17330        assert_eq!(frame.column("a").unwrap().values()[0], Scalar::Int64(1));
17331        assert_eq!(frame.column("c").unwrap().values()[1], Scalar::Int64(6));
17332    }
17333
17334    #[test]
17335    fn read_table_with_options_overrides_default_delimiter_4pwr9() {
17336        // DISC-011: Nullable extension Int64 dtype parity - Int64 preserved, not promoted to Float64.
17337        let input = "x\ty\n1\tNA\n2\t3\n";
17338        let opts = CsvReadOptions {
17339            na_values: vec!["NA".into()],
17340            ..Default::default()
17341        };
17342        let frame = super::read_table_with_options(input, &opts).expect("parse tsv with na");
17343        assert!(frame.column("y").unwrap().values()[0].is_missing());
17344        assert_eq!(frame.column("y").unwrap().values()[1], Scalar::Int64(3));
17345    }
17346
17347    #[test]
17348    fn read_table_with_options_honours_explicit_pipe_delimiter_4pwr9() {
17349        let input = "x|y\n1|2\n3|4\n";
17350        let opts = CsvReadOptions {
17351            delimiter: b'|',
17352            ..Default::default()
17353        };
17354        let frame = super::read_table_with_options(input, &opts).expect("parse pipe");
17355        assert_eq!(frame.column("x").unwrap().values()[0], Scalar::Int64(1));
17356        assert_eq!(frame.column("y").unwrap().values()[1], Scalar::Int64(4));
17357    }
17358
17359    // ── read_fwf 23n8u ─────────────────────────────────────────────────
17360
17361    #[test]
17362    fn read_fwf_str_with_colspecs_parses_aligned_records_23n8u() {
17363        let input = "name    age   active\nalice   30    true\nbob     25    false\n";
17364        let opts = super::FwfReadOptions {
17365            colspecs: Some(vec![(0, 8), (8, 14), (14, 20)]),
17366            true_values: vec!["true".into()],
17367            false_values: vec!["false".into()],
17368            ..Default::default()
17369        };
17370        let frame = super::read_fwf_str(input, &opts).expect("parse fwf");
17371        assert_eq!(frame.index().len(), 2);
17372        assert_eq!(
17373            frame.column("name").unwrap().values()[0],
17374            Scalar::Utf8("alice".into())
17375        );
17376        assert_eq!(frame.column("age").unwrap().values()[0], Scalar::Int64(30));
17377        assert_eq!(
17378            frame.column("active").unwrap().values()[0],
17379            Scalar::Bool(true)
17380        );
17381    }
17382
17383    #[test]
17384    fn read_fwf_str_with_widths_derives_colspecs_23n8u() {
17385        let input = "x  y \n1  2 \n3  4 \n";
17386        let opts = super::FwfReadOptions {
17387            widths: Some(vec![3, 3]),
17388            ..Default::default()
17389        };
17390        let frame = super::read_fwf_str(input, &opts).expect("parse fwf widths");
17391        assert_eq!(frame.column("x").unwrap().values()[0], Scalar::Int64(1));
17392        assert_eq!(frame.column("y").unwrap().values()[1], Scalar::Int64(4));
17393    }
17394
17395    #[test]
17396    fn read_fwf_str_threads_na_handling_23n8u() {
17397        // DISC-011: Nullable extension Int64 dtype parity - Int64 preserved, not promoted to Float64.
17398        let input = "id   val\nA    NA \nB    7  \n";
17399        let opts = super::FwfReadOptions {
17400            colspecs: Some(vec![(0, 5), (5, 9)]),
17401            na_values: vec!["NA".into()],
17402            ..Default::default()
17403        };
17404        let frame = super::read_fwf_str(input, &opts).expect("parse fwf na");
17405        let col = frame.column("val").unwrap().values();
17406        assert!(col[0].is_missing());
17407        assert_eq!(col[1], Scalar::Int64(7));
17408    }
17409
17410    #[test]
17411    fn read_fwf_rejects_both_colspecs_and_widths_23n8u() {
17412        let opts = super::FwfReadOptions {
17413            colspecs: Some(vec![(0, 3)]),
17414            widths: Some(vec![3]),
17415            ..Default::default()
17416        };
17417        let err = super::read_fwf_str("x\n1\n", &opts).expect_err("must reject");
17418        assert!(
17419            matches!(&err, super::IoError::Fwf(message) if message.contains("only one of")),
17420            "unexpected error: {err:?}"
17421        );
17422    }
17423
17424    #[test]
17425    fn read_fwf_infers_colspecs_when_specs_are_omitted_htdmp() {
17426        let opts = super::FwfReadOptions::default();
17427        let frame = super::read_fwf_str("a b\n1 2\n3 4\n", &opts).expect("infer fwf specs");
17428        assert_eq!(frame.column("a").unwrap().values()[0], Scalar::Int64(1));
17429        assert_eq!(frame.column("b").unwrap().values()[1], Scalar::Int64(4));
17430    }
17431
17432    #[test]
17433    fn read_fwf_infers_aligned_wide_colspecs_htdmp() {
17434        let input = "name    age   active\nalice   30    true\nbob     25    false\n";
17435        let opts = super::FwfReadOptions {
17436            true_values: vec!["true".into()],
17437            false_values: vec!["false".into()],
17438            ..Default::default()
17439        };
17440        let frame = super::read_fwf_str(input, &opts).expect("infer aligned fwf specs");
17441        assert_eq!(
17442            frame.column("name").unwrap().values()[0],
17443            Scalar::Utf8("alice".into())
17444        );
17445        assert_eq!(frame.column("age").unwrap().values()[1], Scalar::Int64(25));
17446        assert_eq!(
17447            frame.column("active").unwrap().values()[1],
17448            Scalar::Bool(false)
17449        );
17450    }
17451
17452    #[test]
17453    fn read_fwf_infer_honors_skiprows_and_skipfooter_htdmp() {
17454        let input = "ignored wide banner\nx y\n1 2\nfooter text ignored\n";
17455        let opts = super::FwfReadOptions {
17456            skiprows: 1,
17457            skipfooter: 1,
17458            ..Default::default()
17459        };
17460        let frame = super::read_fwf_str(input, &opts).expect("infer after skipping");
17461        assert_eq!(frame.column("x").unwrap().values()[0], Scalar::Int64(1));
17462        assert_eq!(frame.column("y").unwrap().values()[0], Scalar::Int64(2));
17463    }
17464
17465    // ── Deferred reader surfaces 2yy4d ─────────────────────────────────
17466
17467    #[test]
17468    fn clipboard_tsv_round_trips_through_read_clipboard_str() {
17469        let frame = make_test_dataframe();
17470        // The pure write core: the exact tab-separated bytes `to_clipboard` puts
17471        // on the clipboard (index included, pandas excel=True).
17472        let tsv = super::clipboard_tsv(&frame).expect("tsv");
17473        assert!(
17474            tsv.contains('\t'),
17475            "clipboard payload must be tab-separated"
17476        );
17477
17478        // The pure read core round-trips the payload back to a frame with the
17479        // same shape (the written index becomes a leading column, matching
17480        // pandas read_clipboard's default no-index-col behavior).
17481        let parsed = super::read_clipboard_str(&tsv).expect("parse clipboard tsv");
17482        assert_eq!(parsed.len(), frame.len());
17483        assert_eq!(parsed.column_names().len(), frame.column_names().len() + 1);
17484    }
17485
17486    #[test]
17487    fn read_clipboard_is_ok_or_reports_missing_backend() {
17488        // Environment-independent: on a box with wl-paste/xclip/xsel/pbpaste it
17489        // reads real clipboard text (Ok or a parse error); headless it reports a
17490        // Clipboard backend error. Never a Deferred reject and never a panic.
17491        match super::read_clipboard() {
17492            Ok(_) => {}
17493            Err(super::IoError::Clipboard(_)) | Err(super::IoError::Csv(_)) => {}
17494            Err(super::IoError::MissingHeaders) => {}
17495            other => panic!("unexpected read_clipboard result: {other:?}"),
17496        }
17497    }
17498
17499    #[test]
17500    fn read_gbq_rejects_with_deferred_marker_2yy4d() {
17501        let err = super::read_gbq("SELECT 1", Some("proj")).expect_err("must reject");
17502        assert!(
17503            matches!(&err, super::IoError::Deferred(message)
17504                if message.contains("read_gbq") && message.contains("BigQuery")),
17505            "unexpected error: {err:?}"
17506        );
17507        let no_project_err = super::read_gbq("SELECT 1", None).expect_err("must reject");
17508        assert!(matches!(no_project_err, super::IoError::Deferred(_)));
17509    }
17510
17511    #[test]
17512    fn dataframe_deferred_writer_surfaces_report_method_names_e6jrk() {
17513        use super::DataFrameIoExt;
17514
17515        let frame = make_test_dataframe();
17516        // Clipboard writer is implemented (subprocess backend): Ok where a
17517        // backend exists, else a Clipboard error — never a Deferred reject.
17518        match frame.to_clipboard() {
17519            Ok(()) => {}
17520            Err(super::IoError::Clipboard(_)) => {}
17521            other => panic!("unexpected to_clipboard result: {other:?}"),
17522        }
17523
17524        let gbq_err = frame
17525            .to_gbq("dataset.table", Some("project"))
17526            .expect_err("must reject BigQuery writer");
17527        assert!(
17528            matches!(&gbq_err, super::IoError::Deferred(message) if message.contains("to_gbq") && message.contains("BigQuery"))
17529        );
17530
17531        let no_project_err = frame
17532            .to_gbq("dataset.table", None)
17533            .expect_err("must reject BigQuery writer without project");
17534        assert!(matches!(no_project_err, super::IoError::Deferred(_)));
17535    }
17536
17537    #[test]
17538    fn series_clipboard_writer_is_ok_or_reports_missing_backend() {
17539        use super::SeriesIoExt;
17540
17541        let source = Series::from_values(
17542            "sales",
17543            vec!["r1".into(), "r2".into()],
17544            vec![Scalar::Int64(10), Scalar::Int64(12)],
17545        )
17546        .expect("source series");
17547        match source.to_clipboard() {
17548            Ok(()) => {}
17549            Err(super::IoError::Clipboard(_)) => {}
17550            other => panic!("unexpected series to_clipboard result: {other:?}"),
17551        }
17552    }
17553
17554    #[test]
17555    fn read_sas_rejects_with_deferred_marker_2yy4d() {
17556        let path = std::path::Path::new("/nonexistent.sas7bdat");
17557        let err = super::read_sas(path).expect_err("must reject");
17558        assert!(
17559            matches!(&err, super::IoError::Deferred(message)
17560                if message.contains("read_sas") && message.contains("sas7bdat")),
17561            "unexpected error: {err:?}"
17562        );
17563    }
17564
17565    #[test]
17566    fn read_spss_rejects_with_deferred_marker_2yy4d() {
17567        let path = std::path::Path::new("/nonexistent.sav");
17568        let err = super::read_spss(path).expect_err("must reject");
17569        assert!(
17570            matches!(&err, super::IoError::Deferred(message)
17571                if message.contains("read_spss") && message.contains(".sav")),
17572            "unexpected error: {err:?}"
17573        );
17574    }
17575
17576    #[test]
17577    fn read_fwf_path_reads_fixed_width_file_23n8u() {
17578        let input = "a   b\n1   2\n3   4\n";
17579        let dir = std::env::temp_dir();
17580        let path = dir.join("fp_io_test_read_fwf_23n8u.txt");
17581        std::fs::write(&path, input).expect("write fixture");
17582
17583        let opts = super::FwfReadOptions {
17584            colspecs: Some(vec![(0, 4), (4, 5)]),
17585            ..Default::default()
17586        };
17587        let frame = super::read_fwf(&path, &opts).expect("read fwf path");
17588        assert_eq!(frame.index().len(), 2);
17589        assert_eq!(frame.column("a").unwrap().values()[1], Scalar::Int64(3));
17590        assert_eq!(frame.column("b").unwrap().values()[0], Scalar::Int64(2));
17591
17592        std::fs::remove_file(&path).ok();
17593    }
17594
17595    #[test]
17596    fn read_table_path_roundtrips_through_read_csv_path_4pwr9() {
17597        let input = "id\tval\na\t1\nb\t2\n";
17598        let dir = std::env::temp_dir();
17599        let path = dir.join("fp_io_test_read_table_4pwr9.tsv");
17600        std::fs::write(&path, input).expect("write fixture");
17601
17602        let frame = super::read_table(&path).expect("read tsv");
17603        assert_eq!(frame.index().len(), 2);
17604        assert_eq!(
17605            frame.column("id").unwrap().values()[0],
17606            Scalar::Utf8("a".into())
17607        );
17608        assert_eq!(frame.column("val").unwrap().values()[1], Scalar::Int64(2));
17609
17610        let opts = CsvReadOptions {
17611            index_col: Some("id".into()),
17612            ..Default::default()
17613        };
17614        let frame2 =
17615            super::read_table_with_options_path(&path, &opts).expect("read tsv with options");
17616        assert!(frame2.column("id").is_none());
17617        assert_eq!(
17618            frame2.index().labels()[0],
17619            fp_index::IndexLabel::Utf8("a".into())
17620        );
17621        assert_eq!(frame2.column("val").unwrap().values()[1], Scalar::Int64(2));
17622
17623        std::fs::remove_file(&path).ok();
17624    }
17625
17626    // ── Parquet I/O tests ──────────────────────────────────────────────
17627
17628    fn make_test_dataframe() -> DataFrame {
17629        use fp_types::DType;
17630
17631        let mut columns = BTreeMap::new();
17632        columns.insert(
17633            "ints".to_string(),
17634            Column::new(
17635                DType::Int64,
17636                vec![Scalar::Int64(10), Scalar::Int64(20), Scalar::Int64(30)],
17637            )
17638            .unwrap(),
17639        );
17640        columns.insert(
17641            "floats".to_string(),
17642            Column::new(
17643                DType::Float64,
17644                vec![
17645                    Scalar::Float64(1.5),
17646                    Scalar::Float64(2.5),
17647                    Scalar::Float64(3.5),
17648                ],
17649            )
17650            .unwrap(),
17651        );
17652        columns.insert(
17653            "names".to_string(),
17654            Column::from_values(vec![
17655                Scalar::Utf8("alice".into()),
17656                Scalar::Utf8("bob".into()),
17657                Scalar::Utf8("carol".into()),
17658            ])
17659            .unwrap(),
17660        );
17661
17662        let labels = vec![
17663            IndexLabel::Int64(0),
17664            IndexLabel::Int64(1),
17665            IndexLabel::Int64(2),
17666        ];
17667        DataFrame::new_with_column_order(
17668            Index::new(labels),
17669            columns,
17670            vec![
17671                "ints".to_string(),
17672                "floats".to_string(),
17673                "names".to_string(),
17674            ],
17675        )
17676        .unwrap()
17677    }
17678
17679    #[test]
17680    fn dataframe_io_ext_pandas_named_aliases_cover_supported_writers() {
17681        use super::DataFrameIoExt;
17682
17683        let frame = make_test_dataframe();
17684        let csv = frame.to_csv_string().expect("csv string");
17685        assert_eq!(csv, super::write_csv_string(&frame).expect("free csv"));
17686        assert_eq!(
17687            frame.to_markdown_string().expect("markdown string"),
17688            write_markdown_string(&frame).expect("free markdown")
17689        );
17690        assert_eq!(
17691            frame.to_latex_string().expect("latex string"),
17692            write_latex_string(&frame).expect("free latex")
17693        );
17694        let dir = std::env::temp_dir();
17695        let stem = format!("fp_io_dataframe_io_ext_{}", std::process::id());
17696        let excel_path = dir.join(format!("{stem}.xlsx"));
17697        let feather_path = dir.join(format!("{stem}.feather"));
17698        let parquet_path = dir.join(format!("{stem}.parquet"));
17699
17700        frame.to_excel(&excel_path).expect("to_excel alias");
17701        frame.to_feather(&feather_path).expect("to_feather alias");
17702        frame.to_parquet(&parquet_path).expect("to_parquet alias");
17703
17704        assert!(
17705            std::fs::metadata(&excel_path)
17706                .expect("excel metadata")
17707                .len()
17708                > 0
17709        );
17710        assert_eq!(
17711            super::read_feather(&feather_path)
17712                .expect("read feather")
17713                .index()
17714                .len(),
17715            frame.index().len()
17716        );
17717        assert_eq!(
17718            super::read_parquet(&parquet_path)
17719                .expect("read parquet")
17720                .index()
17721                .len(),
17722            frame.index().len()
17723        );
17724
17725        std::fs::remove_file(&excel_path).ok();
17726        std::fs::remove_file(&feather_path).ok();
17727        std::fs::remove_file(&parquet_path).ok();
17728    }
17729
17730    #[test]
17731    fn dataframe_io_ext_rjs51_in_memory_methods_match_free_functions() {
17732        use super::DataFrameIoExt;
17733
17734        let frame = make_test_dataframe();
17735        let csv_options = CsvWriteOptions {
17736            delimiter: b';',
17737            na_rep: "<NA>".to_owned(),
17738            header: true,
17739            include_index: true,
17740            index_label: Some("row".to_owned()),
17741        };
17742        assert_eq!(
17743            frame
17744                .to_csv_string_with_options(&csv_options)
17745                .expect("csv options through extension"),
17746            write_csv_string_with_options(&frame, &csv_options).expect("csv options free fn")
17747        );
17748        assert_eq!(
17749            frame
17750                .to_json_string(JsonOrient::Split)
17751                .expect("json split through extension"),
17752            write_json_string(&frame, JsonOrient::Split).expect("json split free fn")
17753        );
17754        assert_eq!(
17755            frame.to_jsonl_string().expect("jsonl through extension"),
17756            write_jsonl_string(&frame).expect("jsonl free fn")
17757        );
17758        let html_options = HtmlWriteOptions {
17759            include_index: false,
17760            ..HtmlWriteOptions::default()
17761        };
17762        assert_eq!(
17763            frame
17764                .to_html_string_with_options(&html_options)
17765                .expect("html options through extension"),
17766            write_html_string_with_options(&frame, &html_options).expect("html options free fn")
17767        );
17768        let xml_options = XmlWriteOptions {
17769            include_index: false,
17770            root_name: "records".to_owned(),
17771            row_name: "record".to_owned(),
17772            index_label: None,
17773        };
17774        assert_eq!(
17775            frame
17776                .to_xml_string_with_options(&xml_options)
17777                .expect("xml options through extension"),
17778            write_xml_string_with_options(&frame, &xml_options).expect("xml options free fn")
17779        );
17780
17781        let parquet = frame
17782            .to_parquet_bytes()
17783            .expect("parquet bytes through extension");
17784        assert_eq!(
17785            read_parquet_bytes(&parquet)
17786                .expect("parquet roundtrip")
17787                .index()
17788                .len(),
17789            frame.index().len()
17790        );
17791        assert_orc_disabled(
17792            frame
17793                .to_orc_bytes()
17794                .expect_err("ORC must fail closed under no-Tokio policy"),
17795        );
17796        let feather = frame
17797            .to_feather_bytes()
17798            .expect("feather bytes through extension");
17799        assert_eq!(
17800            read_feather_bytes(&feather)
17801                .expect("feather roundtrip")
17802                .index()
17803                .len(),
17804            frame.index().len()
17805        );
17806        let excel = frame
17807            .to_excel_bytes()
17808            .expect("excel bytes through extension");
17809        assert_eq!(
17810            read_excel_bytes(&excel, &ExcelReadOptions::default())
17811                .expect("excel roundtrip")
17812                .index()
17813                .len(),
17814            frame.index().len()
17815        );
17816    }
17817
17818    fn make_row_multiindex_test_dataframe() -> DataFrame {
17819        let df = DataFrame::from_dict(
17820            &["region", "product", "year", "sales", "cost"],
17821            vec![
17822                (
17823                    "region",
17824                    vec![
17825                        Scalar::Utf8("north".into()),
17826                        Scalar::Utf8("north".into()),
17827                        Scalar::Utf8("south".into()),
17828                    ],
17829                ),
17830                (
17831                    "product",
17832                    vec![
17833                        Scalar::Utf8("apple".into()),
17834                        Scalar::Utf8("pear".into()),
17835                        Scalar::Utf8("apple".into()),
17836                    ],
17837                ),
17838                (
17839                    "year",
17840                    vec![
17841                        Scalar::Int64(2023),
17842                        Scalar::Int64(2024),
17843                        Scalar::Int64(2023),
17844                    ],
17845                ),
17846                (
17847                    "sales",
17848                    vec![Scalar::Int64(10), Scalar::Int64(20), Scalar::Int64(30)],
17849                ),
17850                (
17851                    "cost",
17852                    vec![Scalar::Int64(4), Scalar::Int64(7), Scalar::Int64(12)],
17853                ),
17854            ],
17855        )
17856        .unwrap();
17857        df.set_index_multi(&["region", "product", "year"], true, "|")
17858            .unwrap()
17859    }
17860
17861    #[test]
17862    fn parquet_bytes_roundtrip() {
17863        let frame = make_test_dataframe();
17864        let bytes = super::write_parquet_bytes(&frame).expect("write parquet");
17865        assert!(!bytes.is_empty());
17866
17867        let frame2 = super::read_parquet_bytes(&bytes).expect("read parquet");
17868        assert_eq!(frame2.index().len(), 3);
17869        assert_eq!(
17870            frame2
17871                .column_names()
17872                .iter()
17873                .map(|s| s.as_str())
17874                .collect::<Vec<_>>(),
17875            vec!["ints", "floats", "names"]
17876        );
17877
17878        // Check values round-tripped correctly
17879        let ints = frame2.column("ints").unwrap();
17880        assert_eq!(ints.values()[0], Scalar::Int64(10));
17881        assert_eq!(ints.values()[1], Scalar::Int64(20));
17882        assert_eq!(ints.values()[2], Scalar::Int64(30));
17883
17884        let floats = frame2.column("floats").unwrap();
17885        assert_eq!(floats.values()[0], Scalar::Float64(1.5));
17886        assert_eq!(floats.values()[1], Scalar::Float64(2.5));
17887        assert_eq!(floats.values()[2], Scalar::Float64(3.5));
17888
17889        let names = frame2.column("names").unwrap();
17890        assert_eq!(names.values()[0], Scalar::Utf8("alice".into()));
17891        assert_eq!(names.values()[1], Scalar::Utf8("bob".into()));
17892        assert_eq!(names.values()[2], Scalar::Utf8("carol".into()));
17893    }
17894
17895    #[test]
17896    fn parquet_row_multiindex_roundtrip_restores_logical_row_axis() {
17897        let frame = make_row_multiindex_test_dataframe();
17898        let bytes = super::write_parquet_bytes(&frame).expect("write parquet");
17899        let roundtrip = super::read_parquet_bytes(&bytes).expect("read parquet");
17900
17901        assert!(roundtrip.equals(&frame));
17902        assert!(roundtrip.column("__index_level_0__").is_none());
17903        assert_eq!(
17904            roundtrip
17905                .row_multiindex()
17906                .expect("row multiindex should be restored")
17907                .get_level_values(0)
17908                .unwrap()
17909                .labels(),
17910            frame
17911                .row_multiindex()
17912                .expect("source row multiindex")
17913                .get_level_values(0)
17914                .unwrap()
17915                .labels()
17916        );
17917    }
17918
17919    #[test]
17920    fn parquet_file_roundtrip() {
17921        let frame = make_test_dataframe();
17922        let dir = std::env::temp_dir();
17923        let path = dir.join("fp_io_test_parquet_roundtrip.parquet");
17924
17925        super::write_parquet(&frame, &path).expect("write parquet file");
17926        let frame2 = super::read_parquet(&path).expect("read parquet file");
17927        assert_eq!(frame2.index().len(), 3);
17928        assert_eq!(
17929            frame2.column("ints").unwrap().values()[0],
17930            Scalar::Int64(10)
17931        );
17932        std::fs::remove_file(&path).ok();
17933    }
17934
17935    #[test]
17936    fn parquet_with_nulls() {
17937        use fp_types::DType;
17938
17939        let mut columns = BTreeMap::new();
17940        columns.insert(
17941            "vals".to_string(),
17942            Column::new(
17943                DType::Float64,
17944                vec![
17945                    Scalar::Float64(1.0),
17946                    Scalar::Null(NullKind::NaN),
17947                    Scalar::Float64(3.0),
17948                ],
17949            )
17950            .unwrap(),
17951        );
17952        columns.insert(
17953            "strs".to_string(),
17954            Column::from_values(vec![
17955                Scalar::Utf8("a".into()),
17956                Scalar::Null(NullKind::Null),
17957                Scalar::Utf8("c".into()),
17958            ])
17959            .unwrap(),
17960        );
17961
17962        let labels = vec![
17963            IndexLabel::Int64(0),
17964            IndexLabel::Int64(1),
17965            IndexLabel::Int64(2),
17966        ];
17967        let frame = DataFrame::new_with_column_order(
17968            Index::new(labels),
17969            columns,
17970            vec!["vals".to_string(), "strs".to_string()],
17971        )
17972        .unwrap();
17973
17974        let bytes = super::write_parquet_bytes(&frame).expect("write");
17975        let frame2 = super::read_parquet_bytes(&bytes).expect("read");
17976
17977        assert_eq!(
17978            frame2.column("vals").unwrap().values()[0],
17979            Scalar::Float64(1.0)
17980        );
17981        assert!(frame2.column("vals").unwrap().values()[1].is_missing());
17982        assert_eq!(
17983            frame2.column("vals").unwrap().values()[2],
17984            Scalar::Float64(3.0)
17985        );
17986
17987        assert_eq!(
17988            frame2.column("strs").unwrap().values()[0],
17989            Scalar::Utf8("a".into())
17990        );
17991        assert!(frame2.column("strs").unwrap().values()[1].is_missing());
17992        assert_eq!(
17993            frame2.column("strs").unwrap().values()[2],
17994            Scalar::Utf8("c".into())
17995        );
17996    }
17997
17998    #[test]
17999    fn parquet_bool_column() {
18000        use fp_types::DType;
18001
18002        let mut columns = BTreeMap::new();
18003        columns.insert(
18004            "flags".to_string(),
18005            Column::new(
18006                DType::Bool,
18007                vec![Scalar::Bool(true), Scalar::Bool(false), Scalar::Bool(true)],
18008            )
18009            .unwrap(),
18010        );
18011
18012        let labels = vec![
18013            IndexLabel::Int64(0),
18014            IndexLabel::Int64(1),
18015            IndexLabel::Int64(2),
18016        ];
18017        let frame = DataFrame::new_with_column_order(
18018            Index::new(labels),
18019            columns,
18020            vec!["flags".to_string()],
18021        )
18022        .unwrap();
18023
18024        let bytes = super::write_parquet_bytes(&frame).expect("write");
18025        let frame2 = super::read_parquet_bytes(&bytes).expect("read");
18026
18027        assert_eq!(
18028            frame2.column("flags").unwrap().values()[0],
18029            Scalar::Bool(true)
18030        );
18031        assert_eq!(
18032            frame2.column("flags").unwrap().values()[1],
18033            Scalar::Bool(false)
18034        );
18035        assert_eq!(
18036            frame2.column("flags").unwrap().values()[2],
18037            Scalar::Bool(true)
18038        );
18039    }
18040
18041    #[test]
18042    fn parquet_empty_dataframe_errors() {
18043        // Parquet format requires at least one column — empty DataFrames
18044        // cannot be represented, matching pandas behavior where
18045        // pd.DataFrame().to_parquet() also fails.
18046        let frame =
18047            DataFrame::new_with_column_order(Index::new(vec![]), BTreeMap::new(), vec![]).unwrap();
18048
18049        let result = super::write_parquet_bytes(&frame);
18050        assert!(result.is_err());
18051    }
18052
18053    #[test]
18054    fn orc_bytes_fail_closed_under_no_tokio_policy() {
18055        let frame = make_test_dataframe();
18056        assert_orc_disabled(write_orc_bytes(&frame).expect_err("ORC writer must fail closed"));
18057        assert_orc_disabled(read_orc_bytes(b"ORC").expect_err("ORC reader must fail closed"));
18058    }
18059
18060    #[test]
18061    fn orc_file_and_extension_aliases_fail_closed_under_no_tokio_policy() {
18062        use super::DataFrameIoExt;
18063
18064        let frame = make_test_dataframe();
18065        let free_path = std::env::temp_dir().join(format!(
18066            "fp_io_orc_free_{}_{}.orc",
18067            std::process::id(),
18068            line!()
18069        ));
18070        let trait_path = std::env::temp_dir().join(format!(
18071            "fp_io_orc_trait_{}_{}.orc",
18072            std::process::id(),
18073            line!()
18074        ));
18075
18076        assert_orc_disabled(write_orc(&frame, &free_path).expect_err("free ORC path writer"));
18077        assert_orc_disabled(read_orc(&free_path).expect_err("free ORC path reader"));
18078        assert_orc_disabled(
18079            frame
18080                .to_orc_file(&trait_path)
18081                .expect_err("trait ORC path writer"),
18082        );
18083        assert_orc_disabled(frame.to_orc_bytes().expect_err("trait ORC bytes writer"));
18084    }
18085
18086    #[test]
18087    fn orc_row_multiindex_fails_closed_before_materialization() {
18088        let frame = make_row_multiindex_test_dataframe();
18089        assert_orc_disabled(
18090            write_orc_bytes(&frame).expect_err("ORC writer must fail closed for any frame shape"),
18091        );
18092    }
18093
18094    #[test]
18095    fn orc_reader_rejects_malformed_input_without_loading_backend() {
18096        let err = read_orc_bytes(b"not an orc file").expect_err("malformed orc should fail");
18097        assert_orc_disabled(err);
18098    }
18099
18100    // ── Excel I/O tests ──────────────────────────────────────────────
18101
18102    #[test]
18103    fn write_excel_with_options_custom_sheet_name_survives_round_trip() {
18104        let frame = make_test_dataframe();
18105        let bytes = super::write_excel_bytes_with_options(
18106            &frame,
18107            &super::ExcelWriteOptions {
18108                sheet_name: "Results".to_string(),
18109                ..super::ExcelWriteOptions::default()
18110            },
18111        )
18112        .expect("write");
18113        let sheets =
18114            super::read_excel_sheets_bytes(&bytes, None, &super::ExcelReadOptions::default())
18115                .expect("read");
18116        assert_eq!(sheets.len(), 1);
18117        assert!(sheets.contains_key("Results"));
18118    }
18119
18120    #[test]
18121    fn write_excel_with_options_index_false_omits_index_column() {
18122        let frame = make_test_dataframe();
18123        let bytes = super::write_excel_bytes_with_options(
18124            &frame,
18125            &super::ExcelWriteOptions {
18126                index: false,
18127                ..super::ExcelWriteOptions::default()
18128            },
18129        )
18130        .expect("write");
18131        let frame2 =
18132            super::read_excel_bytes(&bytes, &super::ExcelReadOptions::default()).expect("read");
18133        // With index=false the first column is "ints" directly (no
18134        // anonymous leading index column).
18135        let names = frame2.column_names();
18136        assert_eq!(
18137            names.iter().map(|s| s.as_str()).collect::<Vec<_>>(),
18138            vec!["ints", "floats", "names"]
18139        );
18140    }
18141
18142    #[test]
18143    fn write_excel_with_options_index_label_overrides_header() {
18144        let frame = make_test_dataframe();
18145        let bytes = super::write_excel_bytes_with_options(
18146            &frame,
18147            &super::ExcelWriteOptions {
18148                index_label: Some("row_id".to_string()),
18149                ..super::ExcelWriteOptions::default()
18150            },
18151        )
18152        .expect("write");
18153        let frame2 =
18154            super::read_excel_bytes(&bytes, &super::ExcelReadOptions::default()).expect("read");
18155        // The index column now shows up as "row_id" before the data columns.
18156        let names = frame2.column_names();
18157        assert_eq!(names[0], "row_id");
18158    }
18159
18160    #[test]
18161    fn write_excel_with_options_header_false_omits_header_row() {
18162        let frame = make_test_dataframe();
18163        let bytes = super::write_excel_bytes_with_options(
18164            &frame,
18165            &super::ExcelWriteOptions {
18166                header: false,
18167                index: false,
18168                ..super::ExcelWriteOptions::default()
18169            },
18170        )
18171        .expect("write");
18172        // Without header, the reader treats row 0 as headers. We
18173        // expect the first data row to become the column names
18174        // instead of literal "ints"/"floats"/"names".
18175        let frame2 =
18176            super::read_excel_bytes(&bytes, &super::ExcelReadOptions::default()).expect("read");
18177        let names = frame2.column_names();
18178        let name_strs: Vec<&str> = names.iter().map(|s| s.as_str()).collect();
18179        assert!(!name_strs.contains(&"ints"));
18180    }
18181
18182    #[test]
18183    fn write_excel_with_options_default_matches_write_excel_bytes() {
18184        let frame = make_test_dataframe();
18185        let default_bytes = super::write_excel_bytes(&frame).expect("default");
18186        let options_bytes =
18187            super::write_excel_bytes_with_options(&frame, &super::ExcelWriteOptions::default())
18188                .expect("options");
18189        assert_eq!(default_bytes, options_bytes);
18190    }
18191
18192    #[test]
18193    fn excel_multiindex_roundtrip_with_explicit_index_cols() {
18194        let frame = make_row_multiindex_test_dataframe();
18195        let bytes =
18196            super::write_excel_bytes_with_options(&frame, &super::ExcelWriteOptions::default())
18197                .expect("write");
18198        let roundtrip = super::read_excel_bytes_with_index_cols(
18199            &bytes,
18200            &super::ExcelReadOptions::default(),
18201            &["region", "product", "year"],
18202        )
18203        .expect("read");
18204
18205        assert!(roundtrip.equals(&frame));
18206        assert_eq!(roundtrip.row_multiindex(), frame.row_multiindex());
18207    }
18208
18209    fn build_two_sheet_workbook_bytes() -> Vec<u8> {
18210        use rust_xlsxwriter::Workbook;
18211        let mut workbook = Workbook::new();
18212        let sheet1 = workbook.add_worksheet();
18213        sheet1.set_name("Alpha").expect("sheet name");
18214        sheet1.write_string(0, 0, "a").expect("header");
18215        sheet1.write_string(0, 1, "b").expect("header");
18216        sheet1.write_number(1, 0, 1.0).expect("data");
18217        sheet1.write_number(1, 1, 10.0).expect("data");
18218        sheet1.write_number(2, 0, 2.0).expect("data");
18219        sheet1.write_number(2, 1, 20.0).expect("data");
18220
18221        let sheet2 = workbook.add_worksheet();
18222        sheet2.set_name("Bravo").expect("sheet name");
18223        sheet2.write_string(0, 0, "name").expect("header");
18224        sheet2.write_string(1, 0, "alice").expect("data");
18225        sheet2.write_string(2, 0, "bob").expect("data");
18226
18227        let sheet3 = workbook.add_worksheet();
18228        sheet3.set_name("Charlie").expect("sheet name");
18229        sheet3.write_string(0, 0, "x").expect("header");
18230        sheet3.write_number(1, 0, 99.0).expect("data");
18231
18232        workbook.save_to_buffer().expect("save")
18233    }
18234
18235    #[test]
18236    fn read_excel_sheets_ordered_bytes_preserves_workbook_order() {
18237        // Workbook sheet order: Alpha, Bravo, Charlie. A sorted map
18238        // would still give Alpha/Bravo/Charlie alphabetically — but
18239        // pandas guarantees workbook order regardless of alphabetic
18240        // relationship, so this test uses a fixture where the ordered
18241        // result differs from sorted order.
18242        use rust_xlsxwriter::Workbook;
18243        let mut workbook = Workbook::new();
18244        let s1 = workbook.add_worksheet();
18245        s1.set_name("Zulu").expect("name");
18246        s1.write_string(0, 0, "v").expect("header");
18247        s1.write_number(1, 0, 1.0).expect("data");
18248        let s2 = workbook.add_worksheet();
18249        s2.set_name("Alpha").expect("name");
18250        s2.write_string(0, 0, "v").expect("header");
18251        s2.write_number(1, 0, 2.0).expect("data");
18252        let s3 = workbook.add_worksheet();
18253        s3.set_name("Mike").expect("name");
18254        s3.write_string(0, 0, "v").expect("header");
18255        s3.write_number(1, 0, 3.0).expect("data");
18256        let bytes = workbook.save_to_buffer().expect("save");
18257
18258        let ordered = super::read_excel_sheets_ordered_bytes(
18259            &bytes,
18260            None,
18261            &super::ExcelReadOptions::default(),
18262        )
18263        .expect("read ordered");
18264        assert_eq!(
18265            ordered.iter().map(|(k, _)| k.as_str()).collect::<Vec<_>>(),
18266            vec!["Zulu", "Alpha", "Mike"],
18267            "ordered form preserves workbook order"
18268        );
18269
18270        // Sorted form alphabetizes (existing contract for BTreeMap).
18271        let sorted =
18272            super::read_excel_sheets_bytes(&bytes, None, &super::ExcelReadOptions::default())
18273                .expect("read sorted");
18274        assert_eq!(
18275            sorted.keys().map(String::as_str).collect::<Vec<_>>(),
18276            vec!["Alpha", "Mike", "Zulu"],
18277            "BTreeMap form alphabetizes"
18278        );
18279    }
18280
18281    #[test]
18282    fn read_excel_sheets_ordered_bytes_selected_subset_keeps_caller_order() {
18283        let bytes = build_two_sheet_workbook_bytes();
18284        // Caller-specified order: Charlie, Alpha — deliberately reversed
18285        // from workbook order. Pandas docs say sheet_name=[list] returns
18286        // a dict whose iteration reflects the argument order; we match.
18287        let req = vec!["Charlie".to_string(), "Alpha".to_string()];
18288        let ordered = super::read_excel_sheets_ordered_bytes(
18289            &bytes,
18290            Some(&req),
18291            &super::ExcelReadOptions::default(),
18292        )
18293        .expect("ordered subset");
18294        assert_eq!(
18295            ordered.iter().map(|(k, _)| k.as_str()).collect::<Vec<_>>(),
18296            vec!["Charlie", "Alpha"]
18297        );
18298    }
18299
18300    #[test]
18301    fn read_excel_sheets_ordered_path_matches_bytes() {
18302        let bytes = build_two_sheet_workbook_bytes();
18303        let temp = std::env::temp_dir().join("fp_io_wrt3_ordered.xlsx");
18304        std::fs::write(&temp, &bytes).expect("write temp");
18305        let via_path =
18306            super::read_excel_sheets_ordered(&temp, None, &super::ExcelReadOptions::default())
18307                .expect("read path");
18308        let via_bytes = super::read_excel_sheets_ordered_bytes(
18309            &bytes,
18310            None,
18311            &super::ExcelReadOptions::default(),
18312        )
18313        .expect("read bytes");
18314        assert_eq!(
18315            via_path.iter().map(|(k, _)| k.clone()).collect::<Vec<_>>(),
18316            via_bytes.iter().map(|(k, _)| k.clone()).collect::<Vec<_>>()
18317        );
18318    }
18319
18320    #[test]
18321    fn read_excel_sheets_bytes_all_sheets_returns_map() {
18322        let bytes = build_two_sheet_workbook_bytes();
18323        let sheets =
18324            super::read_excel_sheets_bytes(&bytes, None, &super::ExcelReadOptions::default())
18325                .expect("read sheets");
18326        assert_eq!(sheets.len(), 3);
18327        assert!(sheets.contains_key("Alpha"));
18328        assert!(sheets.contains_key("Bravo"));
18329        assert!(sheets.contains_key("Charlie"));
18330
18331        let alpha = &sheets["Alpha"];
18332        assert_eq!(alpha.index().len(), 2);
18333        assert_eq!(alpha.column_names().len(), 2);
18334
18335        let bravo = &sheets["Bravo"];
18336        assert_eq!(bravo.index().len(), 2);
18337        assert_eq!(
18338            bravo.column("name").unwrap().values()[0],
18339            Scalar::Utf8("alice".into())
18340        );
18341    }
18342
18343    #[test]
18344    fn read_excel_sheets_bytes_selects_subset() {
18345        let bytes = build_two_sheet_workbook_bytes();
18346        let selected = vec!["Alpha".to_string(), "Charlie".to_string()];
18347        let sheets = super::read_excel_sheets_bytes(
18348            &bytes,
18349            Some(&selected),
18350            &super::ExcelReadOptions::default(),
18351        )
18352        .expect("read subset");
18353        assert_eq!(sheets.len(), 2);
18354        assert!(sheets.contains_key("Alpha"));
18355        assert!(sheets.contains_key("Charlie"));
18356        assert!(!sheets.contains_key("Bravo"));
18357    }
18358
18359    #[test]
18360    fn read_excel_sheets_bytes_unknown_sheet_errors() {
18361        let bytes = build_two_sheet_workbook_bytes();
18362        let bogus = vec!["Zeta".to_string()];
18363        let err = super::read_excel_sheets_bytes(
18364            &bytes,
18365            Some(&bogus),
18366            &super::ExcelReadOptions::default(),
18367        )
18368        .unwrap_err();
18369        assert!(matches!(err, super::IoError::Excel(_)));
18370    }
18371
18372    #[test]
18373    fn read_excel_sheets_path_matches_bytes() {
18374        let bytes = build_two_sheet_workbook_bytes();
18375        let temp = std::env::temp_dir().join("fp_io_9my2_multisheet.xlsx");
18376        std::fs::write(&temp, &bytes).expect("write temp");
18377        let via_path = super::read_excel_sheets(&temp, None, &super::ExcelReadOptions::default())
18378            .expect("read path");
18379        let via_bytes =
18380            super::read_excel_sheets_bytes(&bytes, None, &super::ExcelReadOptions::default())
18381                .expect("read bytes");
18382        assert_eq!(
18383            via_path.keys().collect::<Vec<_>>(),
18384            via_bytes.keys().collect::<Vec<_>>()
18385        );
18386    }
18387
18388    #[test]
18389    fn excel_bytes_roundtrip() {
18390        let frame = make_test_dataframe();
18391        let bytes = super::write_excel_bytes(&frame).expect("write excel");
18392        assert!(!bytes.is_empty());
18393
18394        let frame2 = super::read_excel_bytes(
18395            &bytes,
18396            &super::ExcelReadOptions {
18397                index_col: Some("column_0".into()),
18398                ..Default::default()
18399            },
18400        )
18401        .expect("read excel");
18402        assert_eq!(frame2.index().len(), 3);
18403        assert_eq!(frame2.index().labels(), frame.index().labels());
18404        assert_eq!(frame2.index().name(), None);
18405        // Excel preserves the write-time column order (ints, floats, names).
18406        assert_eq!(
18407            frame2
18408                .column_names()
18409                .iter()
18410                .map(|s| s.as_str())
18411                .collect::<Vec<_>>(),
18412            vec!["ints", "floats", "names"]
18413        );
18414
18415        // Int values survive round-trip (Excel stores as f64, we recover Int64).
18416        let ints = frame2.column("ints").unwrap();
18417        assert_eq!(ints.values()[0], Scalar::Int64(10));
18418        assert_eq!(ints.values()[1], Scalar::Int64(20));
18419        assert_eq!(ints.values()[2], Scalar::Int64(30));
18420
18421        // Float values survive round-trip.
18422        let floats = frame2.column("floats").unwrap();
18423        assert_eq!(floats.values()[0], Scalar::Float64(1.5));
18424        assert_eq!(floats.values()[1], Scalar::Float64(2.5));
18425        assert_eq!(floats.values()[2], Scalar::Float64(3.5));
18426
18427        // String values survive round-trip.
18428        let names = frame2.column("names").unwrap();
18429        assert_eq!(names.values()[0], Scalar::Utf8("alice".into()));
18430        assert_eq!(names.values()[1], Scalar::Utf8("bob".into()));
18431        assert_eq!(names.values()[2], Scalar::Utf8("carol".into()));
18432    }
18433
18434    #[test]
18435    fn excel_file_roundtrip() {
18436        let frame = make_test_dataframe();
18437        let dir = std::env::temp_dir();
18438        let path = dir.join("fp_io_test_excel_roundtrip.xlsx");
18439
18440        super::write_excel(&frame, &path).expect("write excel file");
18441        let frame2 = super::read_excel(
18442            &path,
18443            &super::ExcelReadOptions {
18444                index_col: Some("column_0".into()),
18445                ..Default::default()
18446            },
18447        )
18448        .expect("read excel file");
18449        assert_eq!(frame2.index().len(), 3);
18450        assert_eq!(frame2.index().labels(), frame.index().labels());
18451        assert_eq!(
18452            frame2.column("ints").unwrap().values()[0],
18453            Scalar::Int64(10)
18454        );
18455        std::fs::remove_file(&path).ok();
18456    }
18457
18458    #[test]
18459    fn excel_with_nulls() {
18460        use fp_types::DType;
18461
18462        let mut columns = BTreeMap::new();
18463        columns.insert(
18464            "vals".to_string(),
18465            Column::new(
18466                DType::Float64,
18467                vec![
18468                    Scalar::Float64(1.0),
18469                    Scalar::Null(NullKind::NaN),
18470                    Scalar::Float64(3.0),
18471                ],
18472            )
18473            .unwrap(),
18474        );
18475
18476        let labels = vec![
18477            IndexLabel::Int64(0),
18478            IndexLabel::Int64(1),
18479            IndexLabel::Int64(2),
18480        ];
18481        let frame =
18482            DataFrame::new_with_column_order(Index::new(labels), columns, vec!["vals".to_string()])
18483                .unwrap();
18484
18485        let bytes = super::write_excel_bytes(&frame).expect("write");
18486        let frame2 = super::read_excel_bytes(
18487            &bytes,
18488            &super::ExcelReadOptions {
18489                index_col: Some("column_0".into()),
18490                ..Default::default()
18491            },
18492        )
18493        .expect("read");
18494
18495        // Non-null values round-trip.
18496        assert_eq!(frame2.column("vals").unwrap().values()[0], Scalar::Int64(1));
18497        // NaN written as empty cell, read back as Null.
18498        assert!(frame2.column("vals").unwrap().values()[1].is_missing());
18499        assert_eq!(frame2.column("vals").unwrap().values()[2], Scalar::Int64(3));
18500    }
18501
18502    #[test]
18503    fn excel_bool_column() {
18504        use fp_types::DType;
18505
18506        let mut columns = BTreeMap::new();
18507        columns.insert(
18508            "flags".to_string(),
18509            Column::new(
18510                DType::Bool,
18511                vec![Scalar::Bool(true), Scalar::Bool(false), Scalar::Bool(true)],
18512            )
18513            .unwrap(),
18514        );
18515
18516        let labels = vec![
18517            IndexLabel::Int64(0),
18518            IndexLabel::Int64(1),
18519            IndexLabel::Int64(2),
18520        ];
18521        let frame = DataFrame::new_with_column_order(
18522            Index::new(labels),
18523            columns,
18524            vec!["flags".to_string()],
18525        )
18526        .unwrap();
18527
18528        let bytes = super::write_excel_bytes(&frame).expect("write");
18529        let frame2 = super::read_excel_bytes(
18530            &bytes,
18531            &super::ExcelReadOptions {
18532                index_col: Some("column_0".into()),
18533                ..Default::default()
18534            },
18535        )
18536        .expect("read");
18537
18538        assert_eq!(
18539            frame2.column("flags").unwrap().values()[0],
18540            Scalar::Bool(true)
18541        );
18542        assert_eq!(
18543            frame2.column("flags").unwrap().values()[1],
18544            Scalar::Bool(false)
18545        );
18546        assert_eq!(
18547            frame2.column("flags").unwrap().values()[2],
18548            Scalar::Bool(true)
18549        );
18550    }
18551
18552    #[test]
18553    fn excel_skip_rows() {
18554        // Build an xlsx with 5 data rows, then read with skip_rows=2 to skip
18555        // 2 rows before the header.
18556        use fp_types::DType;
18557
18558        let mut columns = BTreeMap::new();
18559        columns.insert(
18560            "x".to_string(),
18561            Column::new(DType::Int64, vec![Scalar::Int64(1), Scalar::Int64(2)]).unwrap(),
18562        );
18563        let labels = vec![IndexLabel::Int64(0), IndexLabel::Int64(1)];
18564        let frame =
18565            DataFrame::new_with_column_order(Index::new(labels), columns, vec!["x".to_string()])
18566                .unwrap();
18567
18568        let bytes = super::write_excel_bytes(&frame).expect("write");
18569        let frame2 = super::read_excel_bytes(
18570            &bytes,
18571            &super::ExcelReadOptions {
18572                skip_rows: 1,
18573                has_headers: false,
18574                ..Default::default()
18575            },
18576        )
18577        .expect("read with skip");
18578
18579        // Skipped the header row, so first data row becomes first row.
18580        // With has_headers=false, column names are auto-generated.
18581        assert_eq!(frame2.index().len(), 2);
18582        assert!(frame2.column("column_0").is_some());
18583    }
18584
18585    #[test]
18586    fn excel_header_none_with_explicit_names_uses_names_and_keeps_first_row() {
18587        let rows = vec![
18588            vec![
18589                calamine::Data::Int(1),
18590                calamine::Data::String("alpha".to_owned()),
18591            ],
18592            vec![
18593                calamine::Data::Int(2),
18594                calamine::Data::String("beta".to_owned()),
18595            ],
18596        ];
18597
18598        let frame = super::parse_excel_rows(
18599            rows,
18600            &super::ExcelReadOptions {
18601                has_headers: false,
18602                names: Some(vec!["id".to_owned(), "label".to_owned()]),
18603                ..Default::default()
18604            },
18605        )
18606        .expect("parse excel rows with explicit names");
18607
18608        assert_eq!(frame.column_names(), vec!["id", "label"]);
18609        assert_eq!(frame.index().len(), 2);
18610        assert_eq!(frame.column("id").unwrap().values()[0], Scalar::Int64(1));
18611        assert_eq!(
18612            frame.column("label").unwrap().values()[0],
18613            Scalar::Utf8("alpha".into())
18614        );
18615        assert_eq!(frame.column("id").unwrap().values()[1], Scalar::Int64(2));
18616    }
18617
18618    #[test]
18619    fn excel_header_none_with_explicit_names_preserves_index_name() {
18620        let rows = vec![
18621            vec![
18622                calamine::Data::Int(10),
18623                calamine::Data::String("alpha".to_owned()),
18624            ],
18625            vec![
18626                calamine::Data::Int(20),
18627                calamine::Data::String("beta".to_owned()),
18628            ],
18629        ];
18630
18631        let frame = super::parse_excel_rows(
18632            rows,
18633            &super::ExcelReadOptions {
18634                has_headers: false,
18635                names: Some(vec!["row_id".to_owned(), "value".to_owned()]),
18636                index_col: Some("row_id".to_owned()),
18637                ..Default::default()
18638            },
18639        )
18640        .expect("parse excel rows with named index column");
18641
18642        assert_eq!(frame.index().name(), Some("row_id"));
18643        assert_eq!(frame.index().labels()[0], IndexLabel::Int64(10));
18644        assert_eq!(frame.index().labels()[1], IndexLabel::Int64(20));
18645        assert!(frame.column("row_id").is_none());
18646        assert_eq!(
18647            frame.column("value").unwrap().values(),
18648            &[Scalar::Utf8("alpha".into()), Scalar::Utf8("beta".into())]
18649        );
18650    }
18651
18652    #[test]
18653    fn excel_explicit_names_width_mismatch_errors() {
18654        let rows = vec![vec![calamine::Data::Int(1), calamine::Data::Int(2)]];
18655
18656        let err = super::parse_excel_rows(
18657            rows,
18658            &super::ExcelReadOptions {
18659                has_headers: false,
18660                names: Some(vec!["only_one".to_owned()]),
18661                ..Default::default()
18662            },
18663        )
18664        .expect_err("names width mismatch should error");
18665
18666        assert!(
18667            matches!(err, IoError::Excel(message) if message.contains("expected 2 column names, got 1"))
18668        );
18669    }
18670
18671    #[test]
18672    fn excel_usecols_selects_subset_in_sheet_order() {
18673        let rows = vec![
18674            vec![
18675                calamine::Data::String("a".to_owned()),
18676                calamine::Data::String("b".to_owned()),
18677                calamine::Data::String("c".to_owned()),
18678            ],
18679            vec![
18680                calamine::Data::Int(1),
18681                calamine::Data::Int(2),
18682                calamine::Data::Int(3),
18683            ],
18684        ];
18685
18686        let frame = super::parse_excel_rows(
18687            rows,
18688            &super::ExcelReadOptions {
18689                usecols: Some(vec!["c".to_owned(), "a".to_owned()]),
18690                ..Default::default()
18691            },
18692        )
18693        .expect("parse excel rows with usecols");
18694
18695        assert_eq!(frame.column_names(), vec!["a", "c"]);
18696        assert_eq!(frame.column("a").unwrap().values(), &[Scalar::Int64(1)]);
18697        assert_eq!(frame.column("c").unwrap().values(), &[Scalar::Int64(3)]);
18698        assert!(frame.column("b").is_none());
18699    }
18700
18701    #[test]
18702    fn excel_usecols_with_explicit_names_filters_renamed_columns() {
18703        let rows = vec![
18704            vec![
18705                calamine::Data::Int(1),
18706                calamine::Data::String("alpha".to_owned()),
18707            ],
18708            vec![
18709                calamine::Data::Int(2),
18710                calamine::Data::String("beta".to_owned()),
18711            ],
18712        ];
18713
18714        let frame = super::parse_excel_rows(
18715            rows,
18716            &super::ExcelReadOptions {
18717                has_headers: false,
18718                names: Some(vec!["id".to_owned(), "label".to_owned()]),
18719                usecols: Some(vec!["label".to_owned()]),
18720                ..Default::default()
18721            },
18722        )
18723        .expect("parse headerless excel rows with names and usecols");
18724
18725        assert_eq!(frame.column_names(), vec!["label"]);
18726        assert_eq!(
18727            frame.column("label").unwrap().values(),
18728            &[Scalar::Utf8("alpha".into()), Scalar::Utf8("beta".into())]
18729        );
18730        assert!(frame.column("id").is_none());
18731    }
18732
18733    #[test]
18734    fn excel_usecols_missing_column_errors() {
18735        let rows = vec![
18736            vec![
18737                calamine::Data::String("a".to_owned()),
18738                calamine::Data::String("b".to_owned()),
18739            ],
18740            vec![calamine::Data::Int(1), calamine::Data::Int(2)],
18741        ];
18742
18743        let err = super::parse_excel_rows(
18744            rows,
18745            &super::ExcelReadOptions {
18746                usecols: Some(vec!["missing".to_owned()]),
18747                ..Default::default()
18748            },
18749        )
18750        .expect_err("missing excel usecols should error");
18751
18752        assert!(
18753            matches!(err, IoError::MissingUsecols(missing) if missing == vec!["missing".to_owned()])
18754        );
18755    }
18756
18757    #[test]
18758    fn excel_default_read_promotes_writer_range_index_back_to_index() {
18759        let frame = make_test_dataframe();
18760        let bytes = super::write_excel_bytes(&frame).expect("write excel");
18761
18762        let frame2 = super::read_excel_bytes(&bytes, &super::ExcelReadOptions::default())
18763            .expect("read excel");
18764
18765        assert_eq!(frame2.index().labels(), frame.index().labels());
18766        assert_eq!(frame2.index().name(), None);
18767        assert_eq!(frame2.column_names(), vec!["ints", "floats", "names"],);
18768        assert!(frame2.column("column_0").is_none());
18769    }
18770
18771    #[test]
18772    fn excel_default_read_keeps_non_range_generated_leading_column_as_data() {
18773        let rows = vec![
18774            vec![
18775                calamine::Data::Empty,
18776                calamine::Data::String("value".to_owned()),
18777            ],
18778            vec![calamine::Data::Int(10), calamine::Data::Int(1)],
18779            vec![calamine::Data::Int(20), calamine::Data::Int(2)],
18780        ];
18781
18782        let frame = super::parse_excel_rows(rows, &super::ExcelReadOptions::default())
18783            .expect("parse excel rows");
18784
18785        assert_eq!(
18786            frame.index().labels(),
18787            &[IndexLabel::Int64(0), IndexLabel::Int64(1)]
18788        );
18789        assert_eq!(frame.column_names(), vec!["column_0", "value"]);
18790        assert_eq!(
18791            frame.column("column_0").unwrap().values(),
18792            &[Scalar::Int64(10), Scalar::Int64(20)],
18793        );
18794    }
18795
18796    #[test]
18797    fn excel_named_index_roundtrip_preserves_index_name() {
18798        use fp_types::DType;
18799
18800        let mut columns = BTreeMap::new();
18801        columns.insert(
18802            "vals".to_string(),
18803            Column::new(DType::Int64, vec![Scalar::Int64(10), Scalar::Int64(20)]).unwrap(),
18804        );
18805
18806        let frame = DataFrame::new_with_column_order(
18807            Index::new(vec![IndexLabel::Int64(10), IndexLabel::Int64(20)]).set_name("row_id"),
18808            columns,
18809            vec!["vals".to_string()],
18810        )
18811        .unwrap();
18812
18813        let bytes = super::write_excel_bytes(&frame).expect("write excel");
18814        let frame2 = super::read_excel_bytes(
18815            &bytes,
18816            &super::ExcelReadOptions {
18817                index_col: Some("row_id".into()),
18818                ..Default::default()
18819            },
18820        )
18821        .expect("read excel");
18822
18823        assert_eq!(frame2.index().labels(), frame.index().labels());
18824        assert_eq!(frame2.index().name(), Some("row_id"));
18825        assert!(frame2.column("row_id").is_none());
18826        assert_eq!(
18827            frame2.column("vals").unwrap().values(),
18828            &[Scalar::Int64(10), Scalar::Int64(20)]
18829        );
18830    }
18831
18832    #[test]
18833    fn excel_duplicate_headers_error() {
18834        let rows = vec![
18835            vec![
18836                calamine::Data::String("dup".to_owned()),
18837                calamine::Data::String("dup".to_owned()),
18838            ],
18839            vec![calamine::Data::Int(1), calamine::Data::Int(2)],
18840        ];
18841
18842        let err = super::parse_excel_rows(rows, &super::ExcelReadOptions::default())
18843            .expect_err("duplicate headers should error");
18844        assert!(matches!(err, IoError::DuplicateColumnName(_)));
18845    }
18846
18847    // ── SQL I/O tests ──────────────────────────────────────────────
18848    //
18849    // Per br-frankenpandas-7a49 (fd90.48): keep the import block
18850    // unconditional so stub-backend tests (which only need types and
18851    // free-fns, not rusqlite) compile under --no-default-features.
18852    // `#[allow(unused_imports)]` covers the few free fns that are
18853    // exclusively used inside the cfg-gated SQLite-backed tests.
18854
18855    // Per fd90.48: TYPE imports + introspection-helper free fns are
18856    // used by both stub-backend tests (which compile under
18857    // --no-default-features) and SQLite-backed tests. The
18858    // read_sql_* / write_sql_* row-materialization free fns are only
18859    // exercised inside SQLite-backed tests (cfg-gated below) so they
18860    // get their own gated import group to avoid unused warnings.
18861    // Per fd90.48: TYPE imports + introspection-helper free fns +
18862    // write_sql / write_sql_with_options are used by both stub-backend
18863    // tests (which compile under --no-default-features) and
18864    // SQLite-backed tests. The read_sql_* row-materialization free fns
18865    // are only exercised inside SQLite-backed tests (cfg-gated below).
18866    use super::{
18867        SqlBackendCaps, SqlColumnSchema, SqlForeignKeySchema, SqlIfExists, SqlIndexSchema,
18868        SqlInsertMethod, SqlInspector, SqlQueryResult, SqlReadOptions, SqlReflectedTable,
18869        SqlTableSchema, SqlUniqueConstraintSchema, SqlWriteOptions, list_sql_foreign_keys,
18870        list_sql_indexes, list_sql_schemas, list_sql_tables, list_sql_unique_constraints,
18871        list_sql_views, sql_backend_caps, sql_max_identifier_length, sql_max_insert_rows,
18872        sql_max_param_count, sql_primary_key_columns, sql_server_version, sql_supports_returning,
18873        sql_supports_schemas, sql_table_comment, sql_table_schema, truncate_sql_table, write_sql,
18874        write_sql_with_options,
18875    };
18876    #[cfg(feature = "sql-sqlite")]
18877    use super::{
18878        read_sql, read_sql_chunks, read_sql_chunks_with_index_col, read_sql_chunks_with_options,
18879        read_sql_chunks_with_options_and_index_col, read_sql_query, read_sql_query_chunks,
18880        read_sql_query_chunks_with_index_col, read_sql_query_chunks_with_options,
18881        read_sql_query_chunks_with_options_and_index_col, read_sql_query_with_index_col,
18882        read_sql_query_with_options, read_sql_query_with_options_and_index_col, read_sql_table,
18883        read_sql_table_chunks, read_sql_table_chunks_with_index_col,
18884        read_sql_table_chunks_with_options, read_sql_table_chunks_with_options_and_index_col,
18885        read_sql_table_columns, read_sql_table_columns_chunks,
18886        read_sql_table_columns_chunks_with_index_col, read_sql_table_columns_with_index_col,
18887        read_sql_table_with_index_col, read_sql_table_with_options,
18888        read_sql_table_with_options_and_index_col, read_sql_with_index_col, read_sql_with_options,
18889    };
18890
18891    // Per br-frankenpandas-7a49 (fd90.48): the helper itself only
18892    // exists when sql-sqlite is on, since it directly references
18893    // rusqlite::Connection. All tests that call this are also
18894    // cfg-gated on the same feature.
18895    #[cfg(feature = "sql-sqlite")]
18896    fn make_sql_test_conn() -> rusqlite::Connection {
18897        rusqlite::Connection::open_in_memory().expect("in-memory sqlite")
18898    }
18899
18900    #[cfg(feature = "sql-sqlite")]
18901    #[test]
18902    fn sql_read_with_index_col_promotes_named_column() {
18903        let frame = make_test_dataframe();
18904        let conn = make_sql_test_conn();
18905        write_sql(&frame, &conn, "indexed_tbl", SqlIfExists::Fail).expect("write");
18906
18907        // Promote the "ints" column to the row index. The data
18908        // columns should drop ints and the index labels should be the
18909        // ints values.
18910        let result = read_sql_table_with_index_col(&conn, "indexed_tbl", Some("ints"))
18911            .expect("read with index");
18912        assert_eq!(result.index().name(), Some("ints"));
18913        assert_eq!(result.index().labels()[0], crate::IndexLabel::Int64(10));
18914        assert_eq!(result.index().labels()[1], crate::IndexLabel::Int64(20));
18915        assert_eq!(result.index().labels()[2], crate::IndexLabel::Int64(30));
18916        // Data columns: only the non-index columns remain.
18917        let names: Vec<&str> = result.column_names().iter().map(|s| s.as_str()).collect();
18918        assert!(!names.contains(&"ints"));
18919        assert!(names.contains(&"floats"));
18920        assert!(names.contains(&"names"));
18921    }
18922
18923    #[cfg(feature = "sql-sqlite")]
18924    #[test]
18925    fn sql_read_with_index_col_none_is_unchanged() {
18926        let frame = make_test_dataframe();
18927        let conn = make_sql_test_conn();
18928        write_sql(&frame, &conn, "noindex_tbl", SqlIfExists::Fail).expect("write");
18929        let baseline = read_sql_table(&conn, "noindex_tbl").expect("baseline");
18930        let result =
18931            read_sql_table_with_index_col(&conn, "noindex_tbl", None).expect("noop variant");
18932        assert_eq!(result.index().labels(), baseline.index().labels());
18933        assert_eq!(result.column_names(), baseline.column_names());
18934    }
18935
18936    #[cfg(feature = "sql-sqlite")]
18937    #[test]
18938    fn sql_read_with_index_col_unknown_column_errors() {
18939        let frame = make_test_dataframe();
18940        let conn = make_sql_test_conn();
18941        write_sql(&frame, &conn, "missing_tbl", SqlIfExists::Fail).expect("write");
18942        let err = read_sql_table_with_index_col(&conn, "missing_tbl", Some("nope")).unwrap_err();
18943        assert!(matches!(err, crate::IoError::Sql(_)));
18944    }
18945
18946    #[cfg(feature = "sql-sqlite")]
18947    #[test]
18948    fn sql_read_table_columns_returns_requested_projection_in_order() {
18949        let frame = make_test_dataframe();
18950        let conn = make_sql_test_conn();
18951        write_sql(&frame, &conn, "proj_tbl", SqlIfExists::Fail).expect("write");
18952
18953        let result = read_sql_table_columns(&conn, "proj_tbl", &["names", "ints"])
18954            .expect("subset projection");
18955        let names: Vec<&str> = result.column_names().iter().map(|s| s.as_str()).collect();
18956        assert_eq!(names, vec!["names", "ints"]);
18957        assert_eq!(result.index().len(), 3);
18958        assert_eq!(
18959            result.column("ints").unwrap().values()[0],
18960            Scalar::Int64(10)
18961        );
18962        assert_eq!(
18963            result.column("names").unwrap().values()[2],
18964            Scalar::Utf8("carol".into())
18965        );
18966    }
18967
18968    #[cfg(feature = "sql-sqlite")]
18969    #[test]
18970    fn sql_read_table_columns_single_column_projection() {
18971        let frame = make_test_dataframe();
18972        let conn = make_sql_test_conn();
18973        write_sql(&frame, &conn, "single_tbl", SqlIfExists::Fail).expect("write");
18974
18975        let result =
18976            read_sql_table_columns(&conn, "single_tbl", &["floats"]).expect("single projection");
18977        let names: Vec<&str> = result.column_names().iter().map(|s| s.as_str()).collect();
18978        assert_eq!(names, vec!["floats"]);
18979        assert_eq!(
18980            result.column("floats").unwrap().values()[1],
18981            Scalar::Float64(2.5)
18982        );
18983    }
18984
18985    #[cfg(feature = "sql-sqlite")]
18986    #[test]
18987    fn sql_read_table_columns_rejects_empty_columns() {
18988        let conn = make_sql_test_conn();
18989        let err = read_sql_table_columns(&conn, "any_tbl", &[]).unwrap_err();
18990        assert!(matches!(err, crate::IoError::Sql(_)));
18991    }
18992
18993    #[cfg(feature = "sql-sqlite")]
18994    #[test]
18995    fn sql_read_table_columns_rejects_invalid_column_name() {
18996        let frame = make_test_dataframe();
18997        let conn = make_sql_test_conn();
18998        write_sql(&frame, &conn, "valid_tbl", SqlIfExists::Fail).expect("write");
18999        let err = read_sql_table_columns(&conn, "valid_tbl", &["ints; DROP TABLE valid_tbl"])
19000            .unwrap_err();
19001        assert!(matches!(err, crate::IoError::Sql(_)));
19002    }
19003
19004    #[cfg(feature = "sql-sqlite")]
19005    #[test]
19006    fn sql_read_table_columns_rejects_invalid_table_name() {
19007        let conn = make_sql_test_conn();
19008        let err = read_sql_table_columns(&conn, "bad table", &["ints"]).unwrap_err();
19009        assert!(matches!(err, crate::IoError::Sql(_)));
19010    }
19011
19012    #[cfg(feature = "sql-sqlite")]
19013    #[test]
19014    fn sql_read_table_columns_chunks_returns_requested_projection_in_order() {
19015        let frame = make_test_dataframe();
19016        let conn = make_sql_test_conn();
19017        write_sql(&frame, &conn, "proj_chunk_tbl", SqlIfExists::Fail).expect("write");
19018
19019        let chunks = read_sql_table_columns_chunks(&conn, "proj_chunk_tbl", &["names", "ints"], 2)
19020            .expect("projection chunk iterator")
19021            .collect::<Result<Vec<_>, _>>()
19022            .expect("all chunks");
19023
19024        assert_eq!(chunks.len(), 2);
19025        assert_eq!(chunks[0].column_names(), vec!["names", "ints"]);
19026        assert_eq!(
19027            chunks[0].column("names").unwrap().values(),
19028            &[
19029                Scalar::Utf8("alice".to_owned()),
19030                Scalar::Utf8("bob".to_owned())
19031            ]
19032        );
19033        assert_eq!(
19034            chunks[1].column("ints").unwrap().values(),
19035            &[Scalar::Int64(30)]
19036        );
19037    }
19038
19039    #[cfg(feature = "sql-sqlite")]
19040    #[test]
19041    fn sql_read_table_columns_chunks_rejects_zero_chunksize() {
19042        let frame = make_test_dataframe();
19043        let conn = make_sql_test_conn();
19044        write_sql(&frame, &conn, "proj_zero_chunk_tbl", SqlIfExists::Fail).expect("write");
19045
19046        let err = read_sql_table_columns_chunks(&conn, "proj_zero_chunk_tbl", &["names"], 0)
19047            .expect_err("zero projection chunksize should be rejected");
19048
19049        assert!(matches!(err, IoError::Sql(msg) if msg.contains("chunksize")));
19050    }
19051
19052    #[cfg(feature = "sql-sqlite")]
19053    #[test]
19054    fn sql_read_table_columns_chunks_rejects_invalid_projection_inputs() {
19055        let conn = make_sql_test_conn();
19056
19057        let empty = read_sql_table_columns_chunks(&conn, "proj_chunk_tbl", &[], 1)
19058            .expect_err("empty projection should be rejected");
19059        assert!(matches!(empty, IoError::Sql(msg) if msg.contains("columns must be non-empty")));
19060
19061        let invalid = read_sql_table_columns_chunks(&conn, "proj_chunk_tbl", &["bad column"], 1)
19062            .expect_err("invalid projection name should be rejected");
19063        assert!(matches!(invalid, IoError::Sql(msg) if msg.contains("invalid column name")));
19064    }
19065
19066    #[cfg(feature = "sql-sqlite")]
19067    #[test]
19068    fn sql_read_table_columns_with_index_col_promotes_projected_column() {
19069        let frame = make_test_dataframe();
19070        let conn = make_sql_test_conn();
19071        write_sql(&frame, &conn, "proj_index_tbl", SqlIfExists::Fail).expect("write");
19072
19073        let result = read_sql_table_columns_with_index_col(
19074            &conn,
19075            "proj_index_tbl",
19076            &["names", "ints"],
19077            Some("ints"),
19078        )
19079        .expect("projection with index_col");
19080
19081        assert_eq!(result.index().name(), Some("ints"));
19082        assert_eq!(
19083            result.index().labels(),
19084            &[
19085                IndexLabel::Int64(10),
19086                IndexLabel::Int64(20),
19087                IndexLabel::Int64(30)
19088            ]
19089        );
19090        assert_eq!(result.column_names(), vec!["names"]);
19091        assert_eq!(
19092            result.column("names").unwrap().values(),
19093            &[
19094                Scalar::Utf8("alice".to_owned()),
19095                Scalar::Utf8("bob".to_owned()),
19096                Scalar::Utf8("carol".to_owned())
19097            ]
19098        );
19099        assert!(result.column("ints").is_none());
19100    }
19101
19102    // br-frankenpandas-6n0uz: when index_col is set but NOT in columns,
19103    // pandas auto-projects it into the SELECT (then drops it from data
19104    // columns after promotion). Mirrors fd90.76's behavior on the
19105    // options-based reader.
19106    #[cfg(feature = "sql-sqlite")]
19107    #[test]
19108    fn sql_read_table_columns_with_index_col_auto_projects_when_absent() {
19109        let frame = make_test_dataframe();
19110        let conn = make_sql_test_conn();
19111        write_sql(&frame, &conn, "auto_proj_tbl", SqlIfExists::Fail).expect("write");
19112
19113        // index_col "ints" is NOT in columns — must be auto-projected, then
19114        // promoted to the index, then removed from the data columns.
19115        let result =
19116            read_sql_table_columns_with_index_col(&conn, "auto_proj_tbl", &["names"], Some("ints"))
19117                .expect("auto-project index_col");
19118
19119        assert_eq!(result.index().name(), Some("ints"));
19120        assert_eq!(
19121            result.index().labels(),
19122            &[
19123                IndexLabel::Int64(10),
19124                IndexLabel::Int64(20),
19125                IndexLabel::Int64(30)
19126            ]
19127        );
19128        assert_eq!(result.column_names(), vec!["names"]);
19129        assert!(result.column("ints").is_none());
19130        assert_eq!(
19131            result.column("names").unwrap().values(),
19132            &[
19133                Scalar::Utf8("alice".to_owned()),
19134                Scalar::Utf8("bob".to_owned()),
19135                Scalar::Utf8("carol".to_owned())
19136            ]
19137        );
19138    }
19139
19140    #[cfg(feature = "sql-sqlite")]
19141    #[test]
19142    fn sql_read_table_columns_chunks_with_index_col_auto_projects_when_absent() {
19143        let frame = make_test_dataframe();
19144        let conn = make_sql_test_conn();
19145        write_sql(&frame, &conn, "auto_proj_chunks_tbl", SqlIfExists::Fail).expect("write");
19146
19147        // index_col "ints" is NOT in columns — must be auto-projected per
19148        // chunk and dropped from each chunk's data columns.
19149        let chunks = read_sql_table_columns_chunks_with_index_col(
19150            &conn,
19151            "auto_proj_chunks_tbl",
19152            &["names"],
19153            Some("ints"),
19154            2,
19155        )
19156        .expect("auto-project chunks")
19157        .collect::<Result<Vec<_>, _>>()
19158        .expect("all chunks");
19159
19160        assert_eq!(chunks.len(), 2);
19161        assert_eq!(chunks[0].index().name(), Some("ints"));
19162        assert_eq!(
19163            chunks[0].index().labels(),
19164            &[IndexLabel::Int64(10), IndexLabel::Int64(20)]
19165        );
19166        assert_eq!(chunks[0].column_names(), vec!["names"]);
19167        assert!(chunks[0].column("ints").is_none());
19168        assert_eq!(
19169            chunks[0].column("names").unwrap().values(),
19170            &[
19171                Scalar::Utf8("alice".to_owned()),
19172                Scalar::Utf8("bob".to_owned())
19173            ]
19174        );
19175        assert_eq!(chunks[1].index().labels(), &[IndexLabel::Int64(30)]);
19176        assert_eq!(chunks[1].column_names(), vec!["names"]);
19177        assert!(chunks[1].column("ints").is_none());
19178    }
19179
19180    // br-frankenpandas-6n0uz: idempotency check — when index_col IS already
19181    // in columns, the auto-project helper must not duplicate it. Same final
19182    // result as the original explicit-include test, but proves the helper's
19183    // dedupe path.
19184    #[cfg(feature = "sql-sqlite")]
19185    #[test]
19186    fn sql_read_table_columns_with_index_col_no_duplication_when_listed() {
19187        let frame = make_test_dataframe();
19188        let conn = make_sql_test_conn();
19189        write_sql(&frame, &conn, "no_dup_tbl", SqlIfExists::Fail).expect("write");
19190
19191        // index_col "ints" IS in columns — must NOT be duplicated in SELECT.
19192        let result = read_sql_table_columns_with_index_col(
19193            &conn,
19194            "no_dup_tbl",
19195            &["names", "ints"],
19196            Some("ints"),
19197        )
19198        .expect("explicit include + index_col");
19199
19200        assert_eq!(result.index().name(), Some("ints"));
19201        assert_eq!(result.column_names(), vec!["names"]);
19202        assert!(result.column("ints").is_none());
19203    }
19204
19205    #[cfg(feature = "sql-sqlite")]
19206    #[test]
19207    fn sql_read_table_columns_with_index_col_none_keeps_projection_and_range_index() {
19208        let frame = make_test_dataframe();
19209        let conn = make_sql_test_conn();
19210        write_sql(&frame, &conn, "proj_no_index_tbl", SqlIfExists::Fail).expect("write");
19211
19212        let result = read_sql_table_columns_with_index_col(
19213            &conn,
19214            "proj_no_index_tbl",
19215            &["floats", "names"],
19216            None,
19217        )
19218        .expect("projection without index_col");
19219
19220        assert_eq!(
19221            result.index().labels(),
19222            &[
19223                IndexLabel::Int64(0),
19224                IndexLabel::Int64(1),
19225                IndexLabel::Int64(2)
19226            ]
19227        );
19228        assert_eq!(result.column_names(), vec!["floats", "names"]);
19229        assert_eq!(
19230            result.column("floats").unwrap().values()[1],
19231            Scalar::Float64(2.5)
19232        );
19233    }
19234
19235    #[cfg(feature = "sql-sqlite")]
19236    #[test]
19237    fn sql_read_table_columns_chunks_with_index_col_promotes_each_chunk_index() {
19238        let frame = make_test_dataframe();
19239        let conn = make_sql_test_conn();
19240        write_sql(&frame, &conn, "proj_index_chunk_tbl", SqlIfExists::Fail).expect("write");
19241
19242        let chunks = read_sql_table_columns_chunks_with_index_col(
19243            &conn,
19244            "proj_index_chunk_tbl",
19245            &["ints", "names"],
19246            Some("ints"),
19247            2,
19248        )
19249        .expect("indexed projection chunk iterator")
19250        .collect::<Result<Vec<_>, _>>()
19251        .expect("all chunks");
19252
19253        assert_eq!(chunks.len(), 2);
19254        assert_eq!(chunks[0].index().name(), Some("ints"));
19255        assert_eq!(
19256            chunks[0].index().labels(),
19257            &[IndexLabel::Int64(10), IndexLabel::Int64(20)]
19258        );
19259        assert_eq!(chunks[0].column_names(), vec!["names"]);
19260        assert_eq!(
19261            chunks[0].column("names").unwrap().values(),
19262            &[
19263                Scalar::Utf8("alice".to_owned()),
19264                Scalar::Utf8("bob".to_owned())
19265            ]
19266        );
19267        assert_eq!(chunks[1].index().labels(), &[IndexLabel::Int64(30)]);
19268        assert_eq!(
19269            chunks[1].column("names").unwrap().values(),
19270            &[Scalar::Utf8("carol".to_owned())]
19271        );
19272    }
19273
19274    #[cfg(feature = "sql-sqlite")]
19275    #[test]
19276    fn sql_read_table_columns_chunks_with_index_col_validates_projection_and_index() {
19277        let frame = make_test_dataframe();
19278        let conn = make_sql_test_conn();
19279        write_sql(&frame, &conn, "proj_index_error_tbl", SqlIfExists::Fail).expect("write");
19280
19281        let empty = read_sql_table_columns_chunks_with_index_col(
19282            &conn,
19283            "proj_index_error_tbl",
19284            &[],
19285            Some("ints"),
19286            1,
19287        )
19288        .expect_err("empty projection should be rejected");
19289        assert!(matches!(empty, IoError::Sql(msg) if msg.contains("columns must be non-empty")));
19290
19291        let invalid = read_sql_table_columns_with_index_col(
19292            &conn,
19293            "proj_index_error_tbl",
19294            &["bad column"],
19295            Some("ints"),
19296        )
19297        .expect_err("invalid projection name should be rejected");
19298        assert!(matches!(invalid, IoError::Sql(msg) if msg.contains("invalid column name")));
19299    }
19300
19301    #[cfg(feature = "sql-sqlite")]
19302    #[test]
19303    fn sql_read_query_with_index_col_works_on_arbitrary_select() {
19304        let frame = make_test_dataframe();
19305        let conn = make_sql_test_conn();
19306        write_sql(&frame, &conn, "queried_tbl", SqlIfExists::Fail).expect("write");
19307        let result = read_sql_with_index_col(
19308            &conn,
19309            "SELECT names AS label, ints, floats FROM queried_tbl ORDER BY ints DESC",
19310            Some("label"),
19311        )
19312        .expect("read query with index");
19313        assert_eq!(result.index().name(), Some("label"));
19314        // Order respected by the SELECT (ints DESC) → index labels in
19315        // reversed name order.
19316        assert_eq!(
19317            result.index().labels()[0],
19318            crate::IndexLabel::Utf8("carol".into())
19319        );
19320        assert_eq!(
19321            result.index().labels()[2],
19322            crate::IndexLabel::Utf8("alice".into())
19323        );
19324    }
19325
19326    #[cfg(feature = "sql-sqlite")]
19327    #[test]
19328    fn sql_write_read_roundtrip() {
19329        let frame = make_test_dataframe();
19330        let conn = make_sql_test_conn();
19331
19332        write_sql(&frame, &conn, "test_table", SqlIfExists::Fail).expect("write sql");
19333
19334        let frame2 = read_sql_table(&conn, "test_table").expect("read sql");
19335        assert_eq!(frame2.index().len(), 3);
19336
19337        // Int values survive round-trip.
19338        let ints = frame2.column("ints").unwrap();
19339        assert_eq!(ints.values()[0], Scalar::Int64(10));
19340        assert_eq!(ints.values()[1], Scalar::Int64(20));
19341        assert_eq!(ints.values()[2], Scalar::Int64(30));
19342
19343        // Float values survive round-trip.
19344        let floats = frame2.column("floats").unwrap();
19345        assert_eq!(floats.values()[0], Scalar::Float64(1.5));
19346        assert_eq!(floats.values()[1], Scalar::Float64(2.5));
19347        assert_eq!(floats.values()[2], Scalar::Float64(3.5));
19348
19349        // String values survive round-trip.
19350        let names = frame2.column("names").unwrap();
19351        assert_eq!(names.values()[0], Scalar::Utf8("alice".into()));
19352        assert_eq!(names.values()[1], Scalar::Utf8("bob".into()));
19353        assert_eq!(names.values()[2], Scalar::Utf8("carol".into()));
19354    }
19355
19356    #[derive(Default)]
19357    struct DollarMarkerSqlConn {
19358        insert_sql: std::cell::RefCell<Vec<String>>,
19359        inserted_rows: std::cell::RefCell<Vec<Vec<Vec<Scalar>>>>,
19360    }
19361
19362    impl super::SqlConnection for DollarMarkerSqlConn {
19363        fn query(
19364            &self,
19365            _query: &str,
19366            _params: &[Scalar],
19367        ) -> Result<super::SqlQueryResult, IoError> {
19368            Err(IoError::Sql("mock connection does not read".to_owned()))
19369        }
19370
19371        fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
19372            Ok(())
19373        }
19374
19375        fn table_exists(&self, _table_name: &str) -> Result<bool, IoError> {
19376            Ok(false)
19377        }
19378
19379        fn insert_rows(&self, insert_sql: &str, rows: &[Vec<Scalar>]) -> Result<(), IoError> {
19380            self.insert_sql.borrow_mut().push(insert_sql.to_owned());
19381            self.inserted_rows.borrow_mut().push(rows.to_vec());
19382            Ok(())
19383        }
19384
19385        fn dtype_sql(&self, dtype: DType) -> &'static str {
19386            match dtype {
19387                DType::Int64
19388                | DType::Int64Nullable
19389                | DType::Bool
19390                | DType::BoolNullable
19391                | DType::Timedelta64
19392                | DType::Datetime64 => "BIGINT",
19393                DType::Float64 => "DOUBLE PRECISION",
19394                DType::Utf8
19395                | DType::Categorical
19396                | DType::Null
19397                | DType::Sparse
19398                | DType::Period
19399                | DType::Interval => "TEXT",
19400            }
19401        }
19402
19403        fn index_dtype_sql(&self, _index: &Index) -> &'static str {
19404            "TEXT"
19405        }
19406
19407        fn parameter_marker(&self, ordinal: usize) -> String {
19408            format!("${ordinal}")
19409        }
19410    }
19411
19412    #[test]
19413    fn sql_query_builders_quote_select_and_projection_identifiers() {
19414        let conn = DollarMarkerSqlConn::default();
19415        assert_eq!(
19416            super::sql_select_all_query(&conn, "portable_tbl").expect("select all query"),
19417            "SELECT * FROM \"portable_tbl\""
19418        );
19419        assert_eq!(
19420            super::sql_select_columns_query(&conn, "portable_tbl", &["names", "ints"])
19421                .expect("projection query"),
19422            "SELECT \"names\", \"ints\" FROM \"portable_tbl\""
19423        );
19424
19425        let err = super::sql_select_columns_query(&conn, "portable_tbl", &["bad column"])
19426            .expect_err("projection identifiers stay validated");
19427        assert!(matches!(err, IoError::Sql(msg) if msg.contains("invalid column name")));
19428    }
19429
19430    #[test]
19431    fn sql_query_builders_create_and_insert_use_backend_contracts() {
19432        let conn = DollarMarkerSqlConn::default();
19433        let column_defs = vec![
19434            super::sql_column_definition(&conn, "row id", "TEXT").expect("index column definition"),
19435            super::sql_column_definition(&conn, "value\"raw", "BIGINT")
19436                .expect("value column definition"),
19437        ];
19438
19439        assert_eq!(
19440            super::sql_create_table_query(&conn, "typed_tbl", &column_defs)
19441                .expect("create table query"),
19442            "CREATE TABLE IF NOT EXISTS \"typed_tbl\" (\"row id\" TEXT, \"value\"\"raw\" BIGINT)"
19443        );
19444
19445        let insert_columns = vec!["row id".to_owned(), "value\"raw".to_owned()];
19446        assert_eq!(
19447            super::sql_insert_rows_query(&conn, "typed_tbl", &insert_columns)
19448                .expect("insert row query"),
19449            "INSERT INTO \"typed_tbl\" (\"row id\", \"value\"\"raw\") VALUES ($1, $2)"
19450        );
19451    }
19452
19453    /// Verify that quote_identifier overrides on a custom backend ACTUALLY
19454    /// flow through the helper functions (br-frankenpandas-cx2x / fd90.12).
19455    /// A MySQL-style backend that returns backticks must produce backticked
19456    /// identifiers in CREATE / SELECT / INSERT statements without any
19457    /// further plumbing.
19458    #[test]
19459    fn sql_query_builders_use_backend_quote_identifier_override() {
19460        #[derive(Default)]
19461        struct BacktickSqlConn;
19462        impl super::SqlConnection for BacktickSqlConn {
19463            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<super::SqlQueryResult, IoError> {
19464                Ok(super::SqlQueryResult {
19465                    columns: vec![],
19466                    rows: vec![],
19467                })
19468            }
19469            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
19470                Ok(())
19471            }
19472            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
19473                Ok(false)
19474            }
19475            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
19476                Ok(())
19477            }
19478            fn dtype_sql(&self, _dtype: DType) -> &'static str {
19479                "TEXT"
19480            }
19481            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
19482                "TEXT"
19483            }
19484            fn quote_identifier(&self, ident: &str) -> Result<String, IoError> {
19485                if ident.contains('\0') {
19486                    return Err(IoError::Sql("invalid SQL identifier: NUL byte".to_owned()));
19487                }
19488                // MySQL-style backtick quoting; embedded backticks doubled.
19489                Ok(format!("`{}`", ident.replace('`', "``")))
19490            }
19491        }
19492
19493        let conn = BacktickSqlConn;
19494        // SELECT / projection helpers flow through quote_identifier.
19495        assert_eq!(
19496            super::sql_select_all_query(&conn, "users").expect("select all"),
19497            "SELECT * FROM `users`"
19498        );
19499        assert_eq!(
19500            super::sql_select_columns_query(&conn, "users", &["id", "name"]).expect("projection"),
19501            "SELECT `id`, `name` FROM `users`"
19502        );
19503        // CREATE / INSERT helpers flow through quote_identifier.
19504        let col_defs = vec![super::sql_column_definition(&conn, "id", "INTEGER").expect("col def")];
19505        assert_eq!(
19506            super::sql_create_table_query(&conn, "users", &col_defs).expect("create"),
19507            "CREATE TABLE IF NOT EXISTS `users` (`id` INTEGER)"
19508        );
19509        let insert_cols = vec!["id".to_owned(), "name".to_owned()];
19510        assert_eq!(
19511            super::sql_insert_rows_query(&conn, "users", &insert_cols).expect("insert"),
19512            "INSERT INTO `users` (`id`, `name`) VALUES (?, ?)"
19513        );
19514    }
19515
19516    #[test]
19517    fn sql_write_uses_backend_parameter_markers() {
19518        let frame = make_test_dataframe();
19519        let conn = DollarMarkerSqlConn::default();
19520
19521        write_sql(&frame, &conn, "portable_tbl", SqlIfExists::Fail)
19522            .expect("write through marker-aware mock backend");
19523
19524        let insert_sql = conn.insert_sql.borrow();
19525        assert_eq!(
19526            insert_sql.as_slice(),
19527            &["INSERT INTO \"portable_tbl\" (\"ints\", \"floats\", \"names\") VALUES ($1, $2, $3)"
19528                .to_owned()]
19529        );
19530        let inserted_rows = conn.inserted_rows.borrow();
19531        assert_eq!(inserted_rows[0].len(), frame.index().len());
19532        assert_eq!(inserted_rows[0][0][0], Scalar::Int64(10));
19533        assert_eq!(inserted_rows[0][2][2], Scalar::Utf8("carol".into()));
19534    }
19535
19536    #[cfg(feature = "sql-sqlite")]
19537    #[test]
19538    fn sql_write_with_options_includes_named_index_column() {
19539        let mut columns = BTreeMap::new();
19540        columns.insert(
19541            "vals".to_string(),
19542            Column::new(DType::Int64, vec![Scalar::Int64(10), Scalar::Int64(20)]).unwrap(),
19543        );
19544
19545        let frame = DataFrame::new_with_column_order(
19546            Index::new(vec![IndexLabel::Int64(101), IndexLabel::Int64(102)]).set_name("row_id"),
19547            columns,
19548            vec!["vals".to_string()],
19549        )
19550        .unwrap();
19551        let conn = make_sql_test_conn();
19552
19553        write_sql_with_options(
19554            &frame,
19555            &conn,
19556            "indexed_write_tbl",
19557            &SqlWriteOptions {
19558                if_exists: SqlIfExists::Fail,
19559                index: true,
19560                index_label: None,
19561                schema: None,
19562                dtype: None,
19563                method: SqlInsertMethod::Single,
19564                chunksize: None,
19565            },
19566        )
19567        .expect("write with named index");
19568
19569        let roundtrip = read_sql_table_with_index_col(&conn, "indexed_write_tbl", Some("row_id"))
19570            .expect("read with promoted index");
19571        assert_eq!(roundtrip.index().name(), Some("row_id"));
19572        assert_eq!(roundtrip.index().labels(), frame.index().labels());
19573        assert!(roundtrip.column("row_id").is_none());
19574        assert_eq!(
19575            roundtrip.column("vals").unwrap().values(),
19576            &[Scalar::Int64(10), Scalar::Int64(20)]
19577        );
19578    }
19579
19580    #[cfg(feature = "sql-sqlite")]
19581    #[test]
19582    fn sql_write_with_options_unnamed_index_defaults_to_index_column_name() {
19583        let frame = make_test_dataframe();
19584        let conn = make_sql_test_conn();
19585
19586        write_sql_with_options(
19587            &frame,
19588            &conn,
19589            "default_index_tbl",
19590            &SqlWriteOptions {
19591                if_exists: SqlIfExists::Fail,
19592                index: true,
19593                index_label: None,
19594                schema: None,
19595                dtype: None,
19596                method: SqlInsertMethod::Single,
19597                chunksize: None,
19598            },
19599        )
19600        .expect("write with unnamed index");
19601
19602        let raw = read_sql_table(&conn, "default_index_tbl").expect("read raw table");
19603        assert!(raw.column("index").is_some());
19604        assert_eq!(raw.column("index").unwrap().values()[0], Scalar::Int64(0));
19605        assert_eq!(raw.column("index").unwrap().values()[2], Scalar::Int64(2));
19606    }
19607
19608    #[cfg(feature = "sql-sqlite")]
19609    #[test]
19610    fn sql_write_with_options_index_label_overrides_name() {
19611        let mut columns = BTreeMap::new();
19612        columns.insert(
19613            "vals".to_string(),
19614            Column::new(DType::Int64, vec![Scalar::Int64(7), Scalar::Int64(8)]).unwrap(),
19615        );
19616
19617        let frame = DataFrame::new_with_column_order(
19618            Index::new(vec![IndexLabel::Int64(1), IndexLabel::Int64(2)]).set_name("row_id"),
19619            columns,
19620            vec!["vals".to_string()],
19621        )
19622        .unwrap();
19623        let conn = make_sql_test_conn();
19624
19625        write_sql_with_options(
19626            &frame,
19627            &conn,
19628            "override_index_tbl",
19629            &SqlWriteOptions {
19630                if_exists: SqlIfExists::Fail,
19631                index: true,
19632                index_label: Some("custom_id".to_string()),
19633                schema: None,
19634                dtype: None,
19635                method: SqlInsertMethod::Single,
19636                chunksize: None,
19637            },
19638        )
19639        .expect("write with custom index label");
19640
19641        let raw = read_sql_table(&conn, "override_index_tbl").expect("read raw table");
19642        assert!(raw.column("custom_id").is_some());
19643        assert!(raw.column("row_id").is_none());
19644        assert_eq!(
19645            raw.column("custom_id").unwrap().values()[0],
19646            Scalar::Int64(1)
19647        );
19648        assert_eq!(
19649            raw.column("custom_id").unwrap().values()[1],
19650            Scalar::Int64(2)
19651        );
19652    }
19653
19654    #[cfg(feature = "sql-sqlite")]
19655    #[test]
19656    fn sql_write_with_options_index_false_omits_index_column() {
19657        let mut columns = BTreeMap::new();
19658        columns.insert(
19659            "vals".to_string(),
19660            Column::new(DType::Int64, vec![Scalar::Int64(5), Scalar::Int64(6)]).unwrap(),
19661        );
19662
19663        let frame = DataFrame::new_with_column_order(
19664            Index::new(vec![IndexLabel::Int64(9), IndexLabel::Int64(10)]).set_name("row_id"),
19665            columns,
19666            vec!["vals".to_string()],
19667        )
19668        .unwrap();
19669        let conn = make_sql_test_conn();
19670
19671        write_sql_with_options(
19672            &frame,
19673            &conn,
19674            "no_index_write_tbl",
19675            &SqlWriteOptions {
19676                if_exists: SqlIfExists::Fail,
19677                index: false,
19678                index_label: Some("custom_id".to_string()),
19679                schema: None,
19680                dtype: None,
19681                method: SqlInsertMethod::Single,
19682                chunksize: None,
19683            },
19684        )
19685        .expect("write without index");
19686
19687        let raw = read_sql_table(&conn, "no_index_write_tbl").expect("read raw table");
19688        assert!(raw.column("row_id").is_none());
19689        assert!(raw.column("custom_id").is_none());
19690        let names: Vec<&str> = raw
19691            .column_names()
19692            .iter()
19693            .map(|name| name.as_str())
19694            .collect();
19695        assert_eq!(names, vec!["vals"]);
19696    }
19697
19698    #[cfg(feature = "sql-sqlite")]
19699    #[test]
19700    fn sql_read_with_query() {
19701        let frame = make_test_dataframe();
19702        let conn = make_sql_test_conn();
19703        write_sql(&frame, &conn, "data", SqlIfExists::Fail).unwrap();
19704
19705        let filtered = read_sql(&conn, "SELECT ints, names FROM data WHERE ints > 15").unwrap();
19706        assert_eq!(filtered.index().len(), 2); // rows with ints=20,30
19707        assert_eq!(
19708            filtered.column("ints").unwrap().values()[0],
19709            Scalar::Int64(20)
19710        );
19711        assert_eq!(
19712            filtered.column("names").unwrap().values()[1],
19713            Scalar::Utf8("carol".into())
19714        );
19715    }
19716
19717    #[cfg(feature = "sql-sqlite")]
19718    #[test]
19719    fn sql_read_query_alias_matches_read_sql_query_path() {
19720        let frame = make_test_dataframe();
19721        let conn = make_sql_test_conn();
19722        write_sql(&frame, &conn, "data", SqlIfExists::Fail).unwrap();
19723
19724        let queried = read_sql_query(
19725            &conn,
19726            "SELECT names, ints FROM data WHERE ints >= 20 ORDER BY ints",
19727        )
19728        .unwrap();
19729
19730        assert_eq!(queried.column_names(), vec!["names", "ints"]);
19731        assert_eq!(queried.index().len(), 2);
19732        assert_eq!(
19733            queried.column("names").unwrap().values(),
19734            &[
19735                Scalar::Utf8("bob".to_owned()),
19736                Scalar::Utf8("carol".to_owned())
19737            ]
19738        );
19739        assert_eq!(
19740            queried.column("ints").unwrap().values(),
19741            &[Scalar::Int64(20), Scalar::Int64(30)]
19742        );
19743    }
19744
19745    #[cfg(feature = "sql-sqlite")]
19746    #[test]
19747    fn sql_read_query_with_options_applies_params_and_parse_dates() {
19748        let conn = make_sql_test_conn();
19749        conn.execute_batch(
19750            "CREATE TABLE events (ts TEXT, value INTEGER);
19751             INSERT INTO events (ts, value) VALUES
19752                ('2024-01-15', 1),
19753                ('2024-02-01 05:06:07', 2),
19754                ('2024-03-03', 3);",
19755        )
19756        .expect("create events table");
19757
19758        let frame = read_sql_query_with_options(
19759            &conn,
19760            "SELECT ts, value FROM events WHERE value > ? ORDER BY value",
19761            &SqlReadOptions {
19762                params: Some(vec![Scalar::Int64(1)]),
19763                parse_dates: Some(vec!["ts".to_owned()]),
19764                coerce_float: false,
19765                dtype: None,
19766                schema: None,
19767                columns: None,
19768                index_col: None,
19769            },
19770        )
19771        .expect("read_sql_query with options");
19772
19773        assert_eq!(frame.column_names(), vec!["ts", "value"]);
19774        // parse_dates now yields typed Datetime64[ns] (br-frankenpandas-0ezw7).
19775        assert_eq!(
19776            frame.column("ts").unwrap().values(),
19777            &[
19778                Scalar::Datetime64(1_706_763_967_000_000_000),
19779                Scalar::Datetime64(1_709_424_000_000_000_000)
19780            ]
19781        );
19782        assert_eq!(
19783            frame.column("value").unwrap().values(),
19784            &[Scalar::Int64(2), Scalar::Int64(3)]
19785        );
19786    }
19787
19788    #[test]
19789    fn sql_read_query_with_options_and_index_col_uses_generic_connection() {
19790        use std::cell::RefCell;
19791
19792        struct RecordingSqlConn {
19793            seen_query: RefCell<Option<String>>,
19794            seen_params: RefCell<Vec<Scalar>>,
19795        }
19796
19797        impl super::SqlConnection for RecordingSqlConn {
19798            fn query(&self, query: &str, params: &[Scalar]) -> Result<SqlQueryResult, IoError> {
19799                *self.seen_query.borrow_mut() = Some(query.to_owned());
19800                *self.seen_params.borrow_mut() = params.to_vec();
19801                Ok(SqlQueryResult {
19802                    columns: vec![
19803                        "row_id".to_owned(),
19804                        "ts".to_owned(),
19805                        "amount".to_owned(),
19806                        "label".to_owned(),
19807                    ],
19808                    rows: vec![
19809                        vec![
19810                            Scalar::Int64(101),
19811                            Scalar::Utf8("2024-01-15".to_owned()),
19812                            Scalar::Utf8("$1.25".to_owned()),
19813                            Scalar::Utf8("alpha".to_owned()),
19814                        ],
19815                        vec![
19816                            Scalar::Int64(102),
19817                            Scalar::Utf8("2024-01-16".to_owned()),
19818                            Scalar::Utf8("2.50".to_owned()),
19819                            Scalar::Utf8("beta".to_owned()),
19820                        ],
19821                    ],
19822                })
19823            }
19824
19825            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
19826                Ok(())
19827            }
19828
19829            fn table_exists(&self, _table_name: &str) -> Result<bool, IoError> {
19830                Ok(false)
19831            }
19832
19833            fn insert_rows(&self, _insert_sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
19834                Ok(())
19835            }
19836
19837            fn dtype_sql(&self, _dtype: DType) -> &'static str {
19838                "TEXT"
19839            }
19840
19841            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
19842                "BIGINT"
19843            }
19844        }
19845
19846        let conn = RecordingSqlConn {
19847            seen_query: RefCell::new(None),
19848            seen_params: RefCell::new(Vec::new()),
19849        };
19850        let query = "SELECT row_id, ts, amount, label FROM events WHERE amount > ?";
19851        let frame = super::read_sql_query_with_options_and_index_col(
19852            &conn,
19853            query,
19854            &SqlReadOptions {
19855                params: Some(vec![Scalar::Float64(1.0)]),
19856                parse_dates: Some(vec!["ts".to_owned()]),
19857                coerce_float: true,
19858                dtype: None,
19859                schema: None,
19860                columns: None,
19861                index_col: Some("amount".to_owned()),
19862            },
19863            Some("row_id"),
19864        )
19865        .expect("generic read_sql query with options and index_col");
19866
19867        assert_eq!(conn.seen_query.borrow().as_deref(), Some(query));
19868        assert_eq!(
19869            conn.seen_params.borrow().as_slice(),
19870            &[Scalar::Float64(1.0)]
19871        );
19872        assert_eq!(frame.index().name(), Some("row_id"));
19873        assert_eq!(
19874            frame.index().labels(),
19875            &[IndexLabel::Int64(101), IndexLabel::Int64(102)]
19876        );
19877        assert_eq!(frame.column_names(), vec!["ts", "amount", "label"]);
19878        // parse_dates now yields typed Datetime64[ns] (br-frankenpandas-0ezw7).
19879        assert_eq!(
19880            frame.column("ts").unwrap().values(),
19881            &[
19882                Scalar::Datetime64(1_705_276_800_000_000_000),
19883                Scalar::Datetime64(1_705_363_200_000_000_000)
19884            ]
19885        );
19886        assert_eq!(
19887            frame.column("amount").unwrap().values(),
19888            &[Scalar::Float64(1.25), Scalar::Float64(2.5)]
19889        );
19890        assert_eq!(
19891            frame.column("label").unwrap().values(),
19892            &[
19893                Scalar::Utf8("alpha".to_owned()),
19894                Scalar::Utf8("beta".to_owned())
19895            ]
19896        );
19897    }
19898
19899    #[cfg(feature = "sql-sqlite")]
19900    #[test]
19901    fn sql_read_query_with_index_col_promotes_named_column() {
19902        let frame = make_test_dataframe();
19903        let conn = make_sql_test_conn();
19904        write_sql(&frame, &conn, "data", SqlIfExists::Fail).unwrap();
19905
19906        let indexed = read_sql_query_with_index_col(
19907            &conn,
19908            "SELECT names, ints FROM data ORDER BY ints",
19909            Some("names"),
19910        )
19911        .unwrap();
19912
19913        assert_eq!(
19914            indexed.index().labels(),
19915            &[
19916                IndexLabel::Utf8("alice".to_owned()),
19917                IndexLabel::Utf8("bob".to_owned()),
19918                IndexLabel::Utf8("carol".to_owned())
19919            ]
19920        );
19921        assert_eq!(indexed.index().name(), Some("names"));
19922        assert!(indexed.column("names").is_none());
19923        assert_eq!(
19924            indexed.column("ints").unwrap().values(),
19925            &[Scalar::Int64(10), Scalar::Int64(20), Scalar::Int64(30)]
19926        );
19927    }
19928
19929    #[cfg(feature = "sql-sqlite")]
19930    #[test]
19931    fn sql_read_query_chunks_alias_batches_rows() {
19932        let conn = make_sql_test_conn();
19933        conn.execute_batch(
19934            "CREATE TABLE query_chunked (id INTEGER, name TEXT);
19935             INSERT INTO query_chunked (id, name) VALUES
19936                (1, 'alpha'),
19937                (2, 'beta'),
19938                (3, 'gamma');",
19939        )
19940        .expect("create query_chunked table");
19941
19942        let chunks =
19943            read_sql_query_chunks(&conn, "SELECT id, name FROM query_chunked ORDER BY id", 2)
19944                .expect("query chunk iterator")
19945                .collect::<Result<Vec<_>, _>>()
19946                .expect("all chunks");
19947
19948        assert_eq!(chunks.len(), 2);
19949        assert_eq!(chunks[0].column_names(), vec!["id", "name"]);
19950        assert_eq!(
19951            chunks[0].column("id").unwrap().values(),
19952            &[Scalar::Int64(1), Scalar::Int64(2)]
19953        );
19954        assert_eq!(
19955            chunks[1].column("name").unwrap().values(),
19956            &[Scalar::Utf8("gamma".to_owned())]
19957        );
19958    }
19959
19960    #[cfg(feature = "sql-sqlite")]
19961    #[test]
19962    fn sql_read_query_chunks_with_options_applies_params_parse_dates_and_coerce_float() {
19963        let conn = make_sql_test_conn();
19964        conn.execute_batch(
19965            "CREATE TABLE query_events (ts TEXT, amount TEXT, keep INTEGER);
19966             INSERT INTO query_events (ts, amount, keep) VALUES
19967                ('2024-01-15', '12.50', 0),
19968                ('2024-02-01 05:06:07', '$1,234.50', 1),
19969                ('2024-03-03', '-3.25', 1);",
19970        )
19971        .expect("create query_events table");
19972
19973        let chunks = read_sql_query_chunks_with_options(
19974            &conn,
19975            "SELECT ts, amount FROM query_events WHERE keep = ? ORDER BY ts",
19976            &SqlReadOptions {
19977                params: Some(vec![Scalar::Int64(1)]),
19978                parse_dates: Some(vec!["ts".to_owned()]),
19979                coerce_float: true,
19980                dtype: None,
19981                schema: None,
19982                columns: None,
19983                index_col: None,
19984            },
19985            1,
19986        )
19987        .expect("query chunk iterator")
19988        .collect::<Result<Vec<_>, _>>()
19989        .expect("all chunks");
19990
19991        assert_eq!(chunks.len(), 2);
19992        // parse_dates now yields typed Datetime64[ns] (br-frankenpandas-0ezw7).
19993        assert_eq!(
19994            chunks[0].column("ts").unwrap().values(),
19995            &[Scalar::Datetime64(1_706_763_967_000_000_000)]
19996        );
19997        assert_eq!(
19998            chunks[0].column("amount").unwrap().values(),
19999            &[Scalar::Float64(1234.5)]
20000        );
20001        assert_eq!(
20002            chunks[1].column("ts").unwrap().values(),
20003            &[Scalar::Datetime64(1_709_424_000_000_000_000)]
20004        );
20005        assert_eq!(
20006            chunks[1].column("amount").unwrap().values(),
20007            &[Scalar::Float64(-3.25)]
20008        );
20009    }
20010
20011    #[test]
20012    fn sql_read_chunks_uses_paged_queries_when_backend_opts_in() {
20013        use std::cell::RefCell;
20014
20015        struct PagedChunksConn {
20016            queries: RefCell<Vec<(String, Vec<Scalar>)>>,
20017            rows: Vec<Vec<Scalar>>,
20018        }
20019
20020        impl PagedChunksConn {
20021            fn page_bounds(params: &[Scalar]) -> (usize, usize) {
20022                let [
20023                    Scalar::Int64(1),
20024                    Scalar::Int64(limit),
20025                    Scalar::Int64(offset),
20026                ] = params
20027                else {
20028                    assert_eq!(
20029                        params,
20030                        &[Scalar::Int64(1), Scalar::Int64(0), Scalar::Int64(0),],
20031                        "expected original param plus LIMIT/OFFSET params"
20032                    );
20033                    return (0, 0);
20034                };
20035                (
20036                    usize::try_from(*limit).expect("non-negative limit"),
20037                    usize::try_from(*offset).expect("non-negative offset"),
20038                )
20039            }
20040        }
20041
20042        impl super::SqlConnection for PagedChunksConn {
20043            fn query(&self, query: &str, params: &[Scalar]) -> Result<SqlQueryResult, IoError> {
20044                self.queries
20045                    .borrow_mut()
20046                    .push((query.to_owned(), params.to_vec()));
20047                assert!(
20048                    query.contains("frankenpandas_sql_chunk_source")
20049                        && query.contains("LIMIT ? OFFSET ?"),
20050                    "paged chunk path should wrap the caller query with LIMIT/OFFSET, got {query}"
20051                );
20052
20053                let (limit, offset) = Self::page_bounds(params);
20054                let rows = self.rows.iter().skip(offset).take(limit).cloned().collect();
20055                Ok(SqlQueryResult {
20056                    columns: vec!["id".to_owned(), "name".to_owned()],
20057                    rows,
20058                })
20059            }
20060
20061            fn supports_paged_sql_chunks(&self) -> bool {
20062                true
20063            }
20064
20065            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
20066                Ok(())
20067            }
20068
20069            fn table_exists(&self, _table_name: &str) -> Result<bool, IoError> {
20070                Ok(false)
20071            }
20072
20073            fn insert_rows(&self, _insert_sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
20074                Ok(())
20075            }
20076
20077            fn dtype_sql(&self, _dtype: DType) -> &'static str {
20078                "TEXT"
20079            }
20080
20081            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
20082                "TEXT"
20083            }
20084        }
20085
20086        let conn = PagedChunksConn {
20087            queries: RefCell::new(Vec::new()),
20088            rows: vec![
20089                vec![Scalar::Int64(1), Scalar::Utf8("a".to_owned())],
20090                vec![Scalar::Int64(2), Scalar::Utf8("b".to_owned())],
20091                vec![Scalar::Int64(3), Scalar::Utf8("c".to_owned())],
20092                vec![Scalar::Int64(4), Scalar::Utf8("d".to_owned())],
20093                vec![Scalar::Int64(5), Scalar::Utf8("e".to_owned())],
20094            ],
20095        };
20096
20097        let chunks = read_sql_chunks_with_options(
20098            &conn,
20099            "SELECT id, name FROM paged_source WHERE keep = ? ORDER BY id;",
20100            &SqlReadOptions {
20101                params: Some(vec![Scalar::Int64(1)]),
20102                ..SqlReadOptions::default()
20103            },
20104            2,
20105        )
20106        .expect("paged chunk iterator")
20107        .collect::<Result<Vec<_>, _>>()
20108        .expect("all chunks");
20109
20110        assert_eq!(chunks.len(), 3);
20111        assert_eq!(
20112            chunks[0].column("id").unwrap().values(),
20113            &[Scalar::Int64(1), Scalar::Int64(2)]
20114        );
20115        assert_eq!(
20116            chunks[1].column("id").unwrap().values(),
20117            &[Scalar::Int64(3), Scalar::Int64(4)]
20118        );
20119        assert_eq!(
20120            chunks[2].column("name").unwrap().values(),
20121            &[Scalar::Utf8("e".to_owned())]
20122        );
20123
20124        let queries = conn.queries.borrow();
20125        let expected_params = vec![
20126            vec![Scalar::Int64(1), Scalar::Int64(0), Scalar::Int64(0)],
20127            vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(0)],
20128            vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(2)],
20129            vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(4)],
20130        ];
20131        assert_eq!(
20132            queries
20133                .iter()
20134                .map(|(_, params)| params.clone())
20135                .collect::<Vec<_>>(),
20136            expected_params
20137        );
20138    }
20139
20140    #[cfg(feature = "sql-sqlite")]
20141    #[test]
20142    fn sql_read_query_chunks_with_options_and_index_col_applies_options_before_indexing() {
20143        let conn = make_sql_test_conn();
20144        conn.execute_batch(
20145            "CREATE TABLE query_index_events (ts TEXT, amount TEXT, keep INTEGER);
20146             INSERT INTO query_index_events (ts, amount, keep) VALUES
20147                ('2024-01-15', '12.50', 0),
20148                ('2024-02-01 05:06:07', '$1,234.50', 1),
20149                ('2024-03-03', '-3.25', 1);",
20150        )
20151        .expect("create query_index_events table");
20152
20153        let chunks = read_sql_query_chunks_with_options_and_index_col(
20154            &conn,
20155            "SELECT ts, amount FROM query_index_events WHERE keep = ? ORDER BY ts",
20156            &SqlReadOptions {
20157                params: Some(vec![Scalar::Int64(1)]),
20158                parse_dates: Some(vec!["ts".to_owned()]),
20159                coerce_float: true,
20160                dtype: None,
20161                schema: None,
20162                columns: None,
20163                index_col: None,
20164            },
20165            Some("ts"),
20166            1,
20167        )
20168        .expect("indexed query chunk iterator")
20169        .collect::<Result<Vec<_>, _>>()
20170        .expect("all chunks");
20171
20172        assert_eq!(chunks.len(), 2);
20173        assert_eq!(chunks[0].index().name(), Some("ts"));
20174        // parse_dates column promoted to index → DatetimeIndex (br-frankenpandas-0ezw7).
20175        assert_eq!(
20176            chunks[0].index().labels(),
20177            &[IndexLabel::Datetime64(1_706_763_967_000_000_000)]
20178        );
20179        assert!(chunks[0].column("ts").is_none());
20180        assert_eq!(
20181            chunks[0].column("amount").unwrap().values(),
20182            &[Scalar::Float64(1234.5)]
20183        );
20184        assert_eq!(
20185            chunks[1].index().labels(),
20186            &[IndexLabel::Datetime64(1_709_424_000_000_000_000)]
20187        );
20188        assert_eq!(
20189            chunks[1].column("amount").unwrap().values(),
20190            &[Scalar::Float64(-3.25)]
20191        );
20192    }
20193
20194    #[cfg(feature = "sql-sqlite")]
20195    #[test]
20196    fn sql_read_chunks_with_options_and_index_col_none_keeps_options_and_range_index() {
20197        let conn = make_sql_test_conn();
20198        conn.execute_batch(
20199            "CREATE TABLE query_options_no_index (id INTEGER, amount TEXT);
20200             INSERT INTO query_options_no_index (id, amount) VALUES
20201                (1, '$10.50'),
20202                (2, '11.25');",
20203        )
20204        .expect("create query_options_no_index table");
20205
20206        let chunks = read_sql_chunks_with_options_and_index_col(
20207            &conn,
20208            "SELECT id, amount FROM query_options_no_index ORDER BY id",
20209            &SqlReadOptions {
20210                params: None,
20211                parse_dates: None,
20212                coerce_float: true,
20213                dtype: None,
20214                schema: None,
20215                columns: None,
20216                index_col: None,
20217            },
20218            None,
20219            1,
20220        )
20221        .expect("query chunk iterator")
20222        .collect::<Result<Vec<_>, _>>()
20223        .expect("all chunks");
20224
20225        assert_eq!(chunks.len(), 2);
20226        assert_eq!(chunks[0].index().labels(), &[IndexLabel::Int64(0)]);
20227        assert_eq!(chunks[1].index().labels(), &[IndexLabel::Int64(0)]);
20228        assert_eq!(
20229            chunks[0].column("amount").unwrap().values(),
20230            &[Scalar::Float64(10.5)]
20231        );
20232        assert_eq!(
20233            chunks[1].column("amount").unwrap().values(),
20234            &[Scalar::Float64(11.25)]
20235        );
20236    }
20237
20238    #[cfg(feature = "sql-sqlite")]
20239    #[test]
20240    fn sql_read_chunks_with_options_and_index_col_uses_options_index_when_explicit_none() {
20241        let conn = make_sql_test_conn();
20242        conn.execute_batch(
20243            "CREATE TABLE query_options_struct_index (id INTEGER, amount TEXT);
20244             INSERT INTO query_options_struct_index (id, amount) VALUES
20245                (10, '$10.50'),
20246                (20, '11.25');",
20247        )
20248        .expect("create query_options_struct_index table");
20249
20250        let chunks = read_sql_chunks_with_options_and_index_col(
20251            &conn,
20252            "SELECT id, amount FROM query_options_struct_index ORDER BY id",
20253            &SqlReadOptions {
20254                params: None,
20255                parse_dates: None,
20256                coerce_float: true,
20257                dtype: None,
20258                schema: None,
20259                columns: None,
20260                index_col: Some("id".to_owned()),
20261            },
20262            None,
20263            1,
20264        )
20265        .expect("query chunk iterator")
20266        .collect::<Result<Vec<_>, _>>()
20267        .expect("all chunks");
20268
20269        assert_eq!(chunks.len(), 2);
20270        assert_eq!(chunks[0].index().name(), Some("id"));
20271        assert_eq!(chunks[0].index().labels(), &[IndexLabel::Int64(10)]);
20272        assert!(chunks[0].column("id").is_none());
20273        assert_eq!(chunks[1].index().labels(), &[IndexLabel::Int64(20)]);
20274        assert_eq!(
20275            chunks[1].column("amount").unwrap().values(),
20276            &[Scalar::Float64(11.25)]
20277        );
20278    }
20279
20280    #[cfg(feature = "sql-sqlite")]
20281    #[test]
20282    fn sql_read_query_chunks_with_options_and_index_col_missing_column_errors() {
20283        let conn = make_sql_test_conn();
20284        conn.execute_batch(
20285            "CREATE TABLE query_options_missing_index (id INTEGER, amount TEXT);
20286             INSERT INTO query_options_missing_index (id, amount) VALUES (1, '10.5');",
20287        )
20288        .expect("create query_options_missing_index table");
20289
20290        let err = read_sql_query_chunks_with_options_and_index_col(
20291            &conn,
20292            "SELECT id, amount FROM query_options_missing_index",
20293            &SqlReadOptions {
20294                params: None,
20295                parse_dates: None,
20296                coerce_float: true,
20297                dtype: None,
20298                schema: None,
20299                columns: None,
20300                index_col: None,
20301            },
20302            Some("missing"),
20303            1,
20304        )
20305        .expect_err("missing index_col should error during iterator construction");
20306
20307        assert!(matches!(err, IoError::Sql(msg) if msg.contains("index_col")));
20308    }
20309
20310    #[cfg(feature = "sql-sqlite")]
20311    #[test]
20312    fn sql_read_query_with_options_and_index_col_applies_options_before_indexing() {
20313        let conn = make_sql_test_conn();
20314        conn.execute_batch(
20315            "CREATE TABLE query_frame_index_events (ts TEXT, amount TEXT, keep INTEGER);
20316             INSERT INTO query_frame_index_events (ts, amount, keep) VALUES
20317                ('2024-01-15', '12.50', 0),
20318                ('2024-02-01 05:06:07', '$1,234.50', 1),
20319                ('2024-03-03', '-3.25', 1);",
20320        )
20321        .expect("create query_frame_index_events table");
20322
20323        let frame = read_sql_query_with_options_and_index_col(
20324            &conn,
20325            "SELECT ts, amount FROM query_frame_index_events WHERE keep = ? ORDER BY ts",
20326            &SqlReadOptions {
20327                params: Some(vec![Scalar::Int64(1)]),
20328                parse_dates: Some(vec!["ts".to_owned()]),
20329                coerce_float: true,
20330                dtype: None,
20331                schema: None,
20332                columns: None,
20333                index_col: None,
20334            },
20335            Some("ts"),
20336        )
20337        .expect("read indexed query frame");
20338
20339        assert_eq!(frame.index().name(), Some("ts"));
20340        // parse_dates column promoted to index → DatetimeIndex (br-frankenpandas-0ezw7).
20341        assert_eq!(
20342            frame.index().labels(),
20343            &[
20344                IndexLabel::Datetime64(1_706_763_967_000_000_000),
20345                IndexLabel::Datetime64(1_709_424_000_000_000_000)
20346            ]
20347        );
20348        assert!(frame.column("ts").is_none());
20349        assert_eq!(
20350            frame.column("amount").unwrap().values(),
20351            &[Scalar::Float64(1234.5), Scalar::Float64(-3.25)]
20352        );
20353    }
20354
20355    #[cfg(feature = "sql-sqlite")]
20356    #[test]
20357    fn sql_read_query_with_options_and_index_col_explicit_arg_wins() {
20358        let conn = make_sql_test_conn();
20359        conn.execute_batch(
20360            "CREATE TABLE query_frame_index_override (a INTEGER, b INTEGER, val TEXT);
20361             INSERT INTO query_frame_index_override (a, b, val) VALUES
20362                (1, 100, 'x'),
20363                (2, 200, 'y');",
20364        )
20365        .expect("create query_frame_index_override table");
20366
20367        let frame = read_sql_query_with_options_and_index_col(
20368            &conn,
20369            "SELECT a, b, val FROM query_frame_index_override ORDER BY a",
20370            &SqlReadOptions {
20371                index_col: Some("a".to_owned()),
20372                ..SqlReadOptions::default()
20373            },
20374            Some("b"),
20375        )
20376        .expect("read indexed query frame with override");
20377
20378        assert_eq!(frame.column_names(), vec!["a", "val"]);
20379        assert_eq!(
20380            frame.index().labels(),
20381            &[IndexLabel::Int64(100), IndexLabel::Int64(200)]
20382        );
20383    }
20384
20385    #[cfg(feature = "sql-sqlite")]
20386    #[test]
20387    fn sql_read_query_chunks_rejects_zero_chunksize() {
20388        let conn = make_sql_test_conn();
20389
20390        let err = read_sql_query_chunks(&conn, "SELECT 1", 0)
20391            .expect_err("zero query chunksize should be rejected");
20392
20393        assert!(matches!(err, IoError::Sql(msg) if msg.contains("chunksize")));
20394    }
20395
20396    #[cfg(feature = "sql-sqlite")]
20397    #[test]
20398    fn sql_read_query_chunks_with_index_col_promotes_each_chunk_index() {
20399        let conn = make_sql_test_conn();
20400        conn.execute_batch(
20401            "CREATE TABLE query_index_chunked (id INTEGER, label TEXT, value INTEGER);
20402             INSERT INTO query_index_chunked (id, label, value) VALUES
20403                (1, 'alpha', 10),
20404                (2, 'beta', 20),
20405                (3, 'gamma', 30);",
20406        )
20407        .expect("create query_index_chunked table");
20408
20409        let chunks = read_sql_query_chunks_with_index_col(
20410            &conn,
20411            "SELECT id, label, value FROM query_index_chunked ORDER BY id",
20412            Some("label"),
20413            2,
20414        )
20415        .expect("query indexed chunk iterator")
20416        .collect::<Result<Vec<_>, _>>()
20417        .expect("all chunks");
20418
20419        assert_eq!(chunks.len(), 2);
20420        assert_eq!(chunks[0].index().name(), Some("label"));
20421        assert_eq!(
20422            chunks[0].index().labels(),
20423            &[
20424                IndexLabel::Utf8("alpha".to_owned()),
20425                IndexLabel::Utf8("beta".to_owned())
20426            ]
20427        );
20428        assert!(chunks[0].column("label").is_none());
20429        assert_eq!(
20430            chunks[1].index().labels(),
20431            &[IndexLabel::Utf8("gamma".to_owned())]
20432        );
20433        assert_eq!(
20434            chunks[1].column("value").unwrap().values(),
20435            &[Scalar::Int64(30)]
20436        );
20437    }
20438
20439    #[cfg(feature = "sql-sqlite")]
20440    #[test]
20441    fn sql_read_chunks_with_index_col_none_keeps_fresh_chunk_range_indexes() {
20442        let conn = make_sql_test_conn();
20443        conn.execute_batch(
20444            "CREATE TABLE query_no_index_chunked (id INTEGER, label TEXT);
20445             INSERT INTO query_no_index_chunked (id, label) VALUES
20446                (1, 'alpha'),
20447                (2, 'beta');",
20448        )
20449        .expect("create query_no_index_chunked table");
20450
20451        let chunks = read_sql_chunks_with_index_col(
20452            &conn,
20453            "SELECT id, label FROM query_no_index_chunked ORDER BY id",
20454            None,
20455            1,
20456        )
20457        .expect("query chunk iterator")
20458        .collect::<Result<Vec<_>, _>>()
20459        .expect("all chunks");
20460
20461        assert_eq!(chunks.len(), 2);
20462        assert_eq!(chunks[0].index().labels(), &[IndexLabel::Int64(0)]);
20463        assert_eq!(chunks[1].index().labels(), &[IndexLabel::Int64(0)]);
20464        assert_eq!(chunks[1].column_names(), vec!["id", "label"]);
20465    }
20466
20467    #[cfg(feature = "sql-sqlite")]
20468    #[test]
20469    fn sql_read_query_chunks_with_index_col_missing_column_errors() {
20470        let conn = make_sql_test_conn();
20471        conn.execute_batch(
20472            "CREATE TABLE query_missing_index_chunked (id INTEGER, value INTEGER);
20473             INSERT INTO query_missing_index_chunked (id, value) VALUES (1, 10);",
20474        )
20475        .expect("create query_missing_index_chunked table");
20476
20477        let err = read_sql_query_chunks_with_index_col(
20478            &conn,
20479            "SELECT id, value FROM query_missing_index_chunked",
20480            Some("missing"),
20481            1,
20482        )
20483        .expect_err("missing index_col should error during iterator construction");
20484
20485        assert!(matches!(err, IoError::Sql(msg) if msg.contains("index_col")));
20486    }
20487
20488    #[cfg(feature = "sql-sqlite")]
20489    #[test]
20490    fn sql_read_table_chunks_batches_rows() {
20491        let conn = make_sql_test_conn();
20492        conn.execute_batch(
20493            "CREATE TABLE table_chunked (id INTEGER, name TEXT);
20494             INSERT INTO table_chunked (id, name) VALUES
20495                (1, 'alpha'),
20496                (2, 'beta'),
20497                (3, 'gamma'),
20498                (4, 'delta');",
20499        )
20500        .expect("create table_chunked table");
20501
20502        let chunks = read_sql_table_chunks(&conn, "table_chunked", 3)
20503            .expect("table chunk iterator")
20504            .collect::<Result<Vec<_>, _>>()
20505            .expect("all chunks");
20506
20507        assert_eq!(chunks.len(), 2);
20508        assert_eq!(chunks[0].column_names(), vec!["id", "name"]);
20509        assert_eq!(
20510            chunks[0].column("id").unwrap().values(),
20511            &[Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)]
20512        );
20513        assert_eq!(
20514            chunks[1].column("name").unwrap().values(),
20515            &[Scalar::Utf8("delta".to_owned())]
20516        );
20517    }
20518
20519    #[cfg(feature = "sql-sqlite")]
20520    #[test]
20521    fn sql_read_table_chunks_rejects_zero_chunksize() {
20522        let conn = make_sql_test_conn();
20523        conn.execute_batch("CREATE TABLE zero_chunked (id INTEGER);")
20524            .expect("create zero_chunked table");
20525
20526        let err = read_sql_table_chunks(&conn, "zero_chunked", 0)
20527            .expect_err("zero table chunksize should be rejected");
20528
20529        assert!(matches!(err, IoError::Sql(msg) if msg.contains("chunksize")));
20530    }
20531
20532    #[cfg(feature = "sql-sqlite")]
20533    #[test]
20534    fn sql_read_table_chunks_rejects_invalid_table_name() {
20535        let conn = make_sql_test_conn();
20536
20537        let err = read_sql_table_chunks(&conn, "bad table", 1)
20538            .expect_err("invalid table name should be rejected");
20539
20540        assert!(matches!(err, IoError::Sql(msg) if msg.contains("invalid table name")));
20541    }
20542
20543    #[cfg(feature = "sql-sqlite")]
20544    #[test]
20545    fn sql_read_table_chunks_with_index_col_promotes_each_chunk_index() {
20546        let conn = make_sql_test_conn();
20547        conn.execute_batch(
20548            "CREATE TABLE table_index_chunked (id INTEGER, name TEXT, score INTEGER);
20549             INSERT INTO table_index_chunked (id, name, score) VALUES
20550                (10, 'alpha', 100),
20551                (20, 'beta', 200),
20552                (30, 'gamma', 300);",
20553        )
20554        .expect("create table_index_chunked table");
20555
20556        let chunks =
20557            read_sql_table_chunks_with_index_col(&conn, "table_index_chunked", Some("id"), 2)
20558                .expect("table indexed chunk iterator")
20559                .collect::<Result<Vec<_>, _>>()
20560                .expect("all chunks");
20561
20562        assert_eq!(chunks.len(), 2);
20563        assert_eq!(chunks[0].index().name(), Some("id"));
20564        assert_eq!(
20565            chunks[0].index().labels(),
20566            &[IndexLabel::Int64(10), IndexLabel::Int64(20)]
20567        );
20568        assert!(chunks[0].column("id").is_none());
20569        assert_eq!(
20570            chunks[1].column("score").unwrap().values(),
20571            &[Scalar::Int64(300)]
20572        );
20573    }
20574
20575    #[cfg(feature = "sql-sqlite")]
20576    #[test]
20577    fn sql_read_table_with_options_applies_parse_dates_and_coerce_float() {
20578        let conn = make_sql_test_conn();
20579        conn.execute_batch(
20580            "CREATE TABLE table_options (ts TEXT, amount TEXT, label TEXT);
20581             INSERT INTO table_options (ts, amount, label) VALUES
20582                ('2024-01-15', '$12.50', 'a'),
20583                ('2024-02-01 05:06:07', '1,234.50', 'b');",
20584        )
20585        .expect("create table_options table");
20586
20587        let frame = read_sql_table_with_options(
20588            &conn,
20589            "table_options",
20590            &SqlReadOptions {
20591                params: None,
20592                parse_dates: Some(vec!["ts".to_owned()]),
20593                coerce_float: true,
20594                dtype: None,
20595                schema: None,
20596                columns: None,
20597                index_col: None,
20598            },
20599        )
20600        .expect("read table with options");
20601
20602        // parse_dates now yields typed Datetime64[ns] (br-frankenpandas-0ezw7).
20603        assert_eq!(
20604            frame.column("ts").unwrap().values(),
20605            &[
20606                Scalar::Datetime64(1_705_276_800_000_000_000),
20607                Scalar::Datetime64(1_706_763_967_000_000_000)
20608            ]
20609        );
20610        assert_eq!(
20611            frame.column("amount").unwrap().values(),
20612            &[Scalar::Float64(12.5), Scalar::Float64(1234.5)]
20613        );
20614        assert_eq!(
20615            frame.column("label").unwrap().values(),
20616            &[Scalar::Utf8("a".to_owned()), Scalar::Utf8("b".to_owned())]
20617        );
20618    }
20619
20620    #[cfg(feature = "sql-sqlite")]
20621    #[test]
20622    fn sql_read_table_chunks_with_options_applies_options_before_chunking() {
20623        let conn = make_sql_test_conn();
20624        conn.execute_batch(
20625            "CREATE TABLE table_options_chunked (ts TEXT, amount TEXT);
20626             INSERT INTO table_options_chunked (ts, amount) VALUES
20627                ('2024-03-01', '$10.00'),
20628                ('2024-03-02', '$20.50'),
20629                ('2024-03-03', '-3.25');",
20630        )
20631        .expect("create table_options_chunked table");
20632
20633        let chunks = read_sql_table_chunks_with_options(
20634            &conn,
20635            "table_options_chunked",
20636            &SqlReadOptions {
20637                params: None,
20638                parse_dates: Some(vec!["ts".to_owned()]),
20639                coerce_float: true,
20640                dtype: None,
20641                schema: None,
20642                columns: None,
20643                index_col: None,
20644            },
20645            2,
20646        )
20647        .expect("table option chunk iterator")
20648        .collect::<Result<Vec<_>, _>>()
20649        .expect("all chunks");
20650
20651        assert_eq!(chunks.len(), 2);
20652        // parse_dates now yields typed Datetime64[ns] (br-frankenpandas-0ezw7).
20653        assert_eq!(
20654            chunks[0].column("ts").unwrap().values(),
20655            &[
20656                Scalar::Datetime64(1_709_251_200_000_000_000),
20657                Scalar::Datetime64(1_709_337_600_000_000_000)
20658            ]
20659        );
20660        assert_eq!(
20661            chunks[0].column("amount").unwrap().values(),
20662            &[Scalar::Float64(10.0), Scalar::Float64(20.5)]
20663        );
20664        assert_eq!(
20665            chunks[1].column("amount").unwrap().values(),
20666            &[Scalar::Float64(-3.25)]
20667        );
20668    }
20669
20670    #[cfg(feature = "sql-sqlite")]
20671    #[test]
20672    fn sql_read_table_chunks_with_options_validates_chunksize_and_table_name() {
20673        let conn = make_sql_test_conn();
20674        conn.execute_batch(
20675            "CREATE TABLE table_options_errors (ts TEXT);
20676             INSERT INTO table_options_errors (ts) VALUES ('2024-01-01');",
20677        )
20678        .expect("create table_options_errors table");
20679
20680        let zero = read_sql_table_chunks_with_options(
20681            &conn,
20682            "table_options_errors",
20683            &SqlReadOptions::default(),
20684            0,
20685        )
20686        .expect_err("zero chunksize should be rejected");
20687        assert!(matches!(zero, IoError::Sql(msg) if msg.contains("chunksize")));
20688
20689        let invalid = read_sql_table_with_options(
20690            &conn,
20691            "bad table",
20692            &SqlReadOptions {
20693                parse_dates: Some(vec!["ts".to_owned()]),
20694                ..SqlReadOptions::default()
20695            },
20696        )
20697        .expect_err("invalid table name should be rejected");
20698        assert!(matches!(invalid, IoError::Sql(msg) if msg.contains("invalid table name")));
20699    }
20700
20701    // br-frankenpandas-i8kja: read_sql_table_chunks_with_options previously
20702    // accepted SqlReadOptions { index_col: Some(...) } and silently dropped
20703    // the index_col while the full-frame sibling honored it. Surface the
20704    // mismatch with a typed error so callers route to the
20705    // `_and_index_col` variant. The plain entrypoint stays
20706    // `Result<SqlChunkIterator, _>` for backwards compatibility — the
20707    // indexed surface is what carries promotion logic.
20708    #[cfg(feature = "sql-sqlite")]
20709    #[test]
20710    fn read_sql_table_chunks_with_options_rejects_options_index_col() {
20711        let conn = make_sql_test_conn();
20712        super::SqlConnection::execute_batch(
20713            &conn,
20714            "CREATE TABLE i8kja_table_chunks_reject (id INTEGER, val TEXT);",
20715        )
20716        .unwrap();
20717        super::SqlConnection::execute_batch(
20718            &conn,
20719            "INSERT INTO i8kja_table_chunks_reject VALUES (1, 'a'), (2, 'b');",
20720        )
20721        .unwrap();
20722
20723        let err = read_sql_table_chunks_with_options(
20724            &conn,
20725            "i8kja_table_chunks_reject",
20726            &SqlReadOptions {
20727                index_col: Some("id".to_owned()),
20728                ..Default::default()
20729            },
20730            2,
20731        )
20732        .expect_err("options.index_col on non-indexed entrypoint must be rejected");
20733        assert!(
20734            matches!(&err, IoError::Sql(msg) if msg.contains("index_col") && msg.contains("read_sql_table_chunks_with_options_and_index_col")),
20735            "expected typed error pointing to the _and_index_col variant, got: {err:?}"
20736        );
20737
20738        // Sanity: same options struct on the indexed sibling honors index_col.
20739        let chunks: Vec<DataFrame> = read_sql_table_chunks_with_options_and_index_col(
20740            &conn,
20741            "i8kja_table_chunks_reject",
20742            &SqlReadOptions {
20743                index_col: Some("id".to_owned()),
20744                ..Default::default()
20745            },
20746            None,
20747            2,
20748        )
20749        .expect("indexed sibling honors options.index_col")
20750        .collect::<Result<Vec<_>, _>>()
20751        .expect("all chunks");
20752        assert_eq!(chunks.len(), 1);
20753        assert!(chunks[0].column("id").is_none());
20754        assert_eq!(
20755            chunks[0].index().labels(),
20756            &[IndexLabel::Int64(1), IndexLabel::Int64(2)]
20757        );
20758        assert_eq!(
20759            chunks[0].column("val").unwrap().values(),
20760            &[Scalar::Utf8("a".into()), Scalar::Utf8("b".into())]
20761        );
20762    }
20763
20764    #[cfg(feature = "sql-sqlite")]
20765    #[test]
20766    fn read_sql_chunks_with_options_rejects_options_index_col() {
20767        let conn = make_sql_test_conn();
20768        super::SqlConnection::execute_batch(
20769            &conn,
20770            "CREATE TABLE i8kja_query_chunks_reject (id INTEGER, val TEXT);",
20771        )
20772        .unwrap();
20773        super::SqlConnection::execute_batch(
20774            &conn,
20775            "INSERT INTO i8kja_query_chunks_reject VALUES (1, 'a');",
20776        )
20777        .unwrap();
20778
20779        let err = read_sql_chunks_with_options(
20780            &conn,
20781            "SELECT * FROM i8kja_query_chunks_reject",
20782            &SqlReadOptions {
20783                index_col: Some("id".to_owned()),
20784                ..Default::default()
20785            },
20786            2,
20787        )
20788        .expect_err("options.index_col on non-indexed entrypoint must be rejected");
20789        assert!(
20790            matches!(&err, IoError::Sql(msg) if msg.contains("index_col") && msg.contains("read_sql_chunks_with_options_and_index_col")),
20791            "expected typed error pointing to the _and_index_col variant, got: {err:?}"
20792        );
20793
20794        let err = read_sql_query_chunks_with_options(
20795            &conn,
20796            "SELECT * FROM i8kja_query_chunks_reject",
20797            &SqlReadOptions {
20798                index_col: Some("id".to_owned()),
20799                ..Default::default()
20800            },
20801            2,
20802        )
20803        .expect_err("query delegator should propagate the rejection");
20804        assert!(
20805            matches!(&err, IoError::Sql(msg) if msg.contains("index_col") && msg.contains("read_sql_query_chunks_with_options_and_index_col")),
20806            "expected query-specific _and_index_col suggestion, got: {err:?}"
20807        );
20808    }
20809
20810    // br-frankenpandas-t1777: query readers can't apply options.columns
20811    // (caller writes the SELECT, projection is fixed). Silently ignoring
20812    // diverged from the table-reader sibling. All 7 query-reader entry
20813    // points (3 foundations + 4 delegators) must reject options.columns
20814    // with a typed error pointing to the appropriate table reader.
20815    #[cfg(feature = "sql-sqlite")]
20816    #[test]
20817    fn read_sql_with_options_rejects_options_columns_across_query_entrypoints() {
20818        let conn = make_sql_test_conn();
20819        super::SqlConnection::execute_batch(
20820            &conn,
20821            "CREATE TABLE t1777_query_cols_reject (id INTEGER, val TEXT);",
20822        )
20823        .unwrap();
20824        super::SqlConnection::execute_batch(
20825            &conn,
20826            "INSERT INTO t1777_query_cols_reject VALUES (1, 'a'), (2, 'b');",
20827        )
20828        .unwrap();
20829
20830        fn assert_columns_rejection(err: &IoError, expected_sibling: &str) {
20831            assert!(
20832                matches!(err, IoError::Sql(msg)
20833                    if msg.contains("options.columns") && msg.contains(expected_sibling)),
20834                "expected options.columns error pointing to `{expected_sibling}`, got: {err:?}"
20835            );
20836        }
20837
20838        let opts_with_cols = || SqlReadOptions {
20839            columns: Some(vec!["id".to_owned()]),
20840            ..Default::default()
20841        };
20842
20843        // 1. read_sql_with_options (foundation, full-frame)
20844        let err = read_sql_with_options(
20845            &conn,
20846            "SELECT id, val FROM t1777_query_cols_reject",
20847            &opts_with_cols(),
20848        )
20849        .expect_err("read_sql_with_options must reject options.columns");
20850        assert_columns_rejection(&err, "read_sql_table_with_options");
20851
20852        // 2. read_sql_chunks_with_options (foundation, chunked)
20853        let err = read_sql_chunks_with_options(
20854            &conn,
20855            "SELECT id, val FROM t1777_query_cols_reject",
20856            &opts_with_cols(),
20857            2,
20858        )
20859        .expect_err("read_sql_chunks_with_options must reject options.columns");
20860        assert_columns_rejection(&err, "read_sql_table_chunks_with_options");
20861
20862        // 3. read_sql_chunks_with_options_and_index_col (foundation, indexed chunked)
20863        let err = read_sql_chunks_with_options_and_index_col(
20864            &conn,
20865            "SELECT id, val FROM t1777_query_cols_reject",
20866            &opts_with_cols(),
20867            Some("id"),
20868            2,
20869        )
20870        .expect_err("indexed chunks must reject options.columns");
20871        assert_columns_rejection(&err, "read_sql_table_chunks_with_options_and_index_col");
20872
20873        // 4. read_sql_query_with_options (delegator → read_sql_with_options)
20874        let err = read_sql_query_with_options(
20875            &conn,
20876            "SELECT id, val FROM t1777_query_cols_reject",
20877            &opts_with_cols(),
20878        )
20879        .expect_err("read_sql_query_with_options must propagate the rejection");
20880        assert_columns_rejection(&err, "read_sql_table_with_options");
20881
20882        // 5. read_sql_query_with_options_and_index_col (delegator)
20883        let err = read_sql_query_with_options_and_index_col(
20884            &conn,
20885            "SELECT id, val FROM t1777_query_cols_reject",
20886            &opts_with_cols(),
20887            Some("id"),
20888        )
20889        .expect_err("indexed query reader must reject options.columns");
20890        assert_columns_rejection(&err, "read_sql_table_with_options");
20891
20892        // 6. read_sql_query_chunks_with_options (delegator → read_sql_chunks_with_options)
20893        let err = read_sql_query_chunks_with_options(
20894            &conn,
20895            "SELECT id, val FROM t1777_query_cols_reject",
20896            &opts_with_cols(),
20897            2,
20898        )
20899        .expect_err("query chunks delegator must reject options.columns");
20900        assert_columns_rejection(&err, "read_sql_table_chunks_with_options");
20901
20902        // 7. read_sql_query_chunks_with_options_and_index_col (delegator)
20903        let err = read_sql_query_chunks_with_options_and_index_col(
20904            &conn,
20905            "SELECT id, val FROM t1777_query_cols_reject",
20906            &opts_with_cols(),
20907            Some("id"),
20908            2,
20909        )
20910        .expect_err("indexed query chunks delegator must reject options.columns");
20911        assert_columns_rejection(&err, "read_sql_table_chunks_with_options_and_index_col");
20912    }
20913
20914    // br-frankenpandas-t1777: table readers must continue to honor
20915    // options.columns (proves the cleared-options pass-through to the
20916    // query foundation didn't accidentally break the columns projection).
20917    #[cfg(feature = "sql-sqlite")]
20918    #[test]
20919    fn read_sql_table_with_options_still_honors_options_columns_after_t1777() {
20920        let conn = make_sql_test_conn();
20921        super::SqlConnection::execute_batch(
20922            &conn,
20923            "CREATE TABLE t1777_table_cols_honor (id INTEGER, val TEXT, secret TEXT);",
20924        )
20925        .unwrap();
20926        super::SqlConnection::execute_batch(
20927            &conn,
20928            "INSERT INTO t1777_table_cols_honor VALUES (1, 'a', 'x'), (2, 'b', 'y');",
20929        )
20930        .unwrap();
20931
20932        // Full-frame table reader with columns should project `id, val`
20933        // and drop `secret`.
20934        let frame = read_sql_table_with_options(
20935            &conn,
20936            "t1777_table_cols_honor",
20937            &SqlReadOptions {
20938                columns: Some(vec!["id".to_owned(), "val".to_owned()]),
20939                ..Default::default()
20940            },
20941        )
20942        .expect("table reader honors options.columns");
20943        assert_eq!(frame.column_names(), vec!["id", "val"]);
20944        assert!(frame.column("secret").is_none());
20945
20946        // Chunked table reader, same behavior per chunk.
20947        let chunks: Vec<DataFrame> = read_sql_table_chunks_with_options(
20948            &conn,
20949            "t1777_table_cols_honor",
20950            &SqlReadOptions {
20951                columns: Some(vec!["id".to_owned(), "val".to_owned()]),
20952                ..Default::default()
20953            },
20954            1,
20955        )
20956        .expect("chunked table reader honors options.columns")
20957        .collect::<Result<Vec<_>, _>>()
20958        .expect("all chunks");
20959        assert_eq!(chunks.len(), 2);
20960        for c in &chunks {
20961            assert_eq!(c.column_names(), vec!["id", "val"]);
20962            assert!(c.column("secret").is_none());
20963        }
20964
20965        // Indexed full-frame table reader: columns + index_col compose.
20966        let frame = read_sql_table_with_options_and_index_col(
20967            &conn,
20968            "t1777_table_cols_honor",
20969            &SqlReadOptions {
20970                columns: Some(vec!["val".to_owned()]),
20971                ..Default::default()
20972            },
20973            Some("id"),
20974        )
20975        .expect("indexed table reader honors options.columns");
20976        assert_eq!(frame.index().name(), Some("id"));
20977        assert_eq!(frame.column_names(), vec!["val"]);
20978        assert!(frame.column("id").is_none());
20979        assert!(frame.column("secret").is_none());
20980
20981        // Indexed chunked table reader.
20982        let chunks: Vec<DataFrame> = read_sql_table_chunks_with_options_and_index_col(
20983            &conn,
20984            "t1777_table_cols_honor",
20985            &SqlReadOptions {
20986                columns: Some(vec!["val".to_owned()]),
20987                ..Default::default()
20988            },
20989            Some("id"),
20990            1,
20991        )
20992        .expect("indexed chunked table reader honors options.columns")
20993        .collect::<Result<Vec<_>, _>>()
20994        .expect("all chunks");
20995        assert_eq!(chunks.len(), 2);
20996        for c in &chunks {
20997            assert_eq!(c.column_names(), vec!["val"]);
20998            assert!(c.column("id").is_none());
20999            assert!(c.column("secret").is_none());
21000        }
21001    }
21002
21003    #[cfg(feature = "sql-sqlite")]
21004    #[test]
21005    fn sql_read_table_with_options_and_index_col_applies_options_before_indexing() {
21006        let conn = make_sql_test_conn();
21007        conn.execute_batch(
21008            "CREATE TABLE table_options_index (ts TEXT, amount TEXT, label TEXT);
21009             INSERT INTO table_options_index (ts, amount, label) VALUES
21010                ('2024-04-01', '$10.00', 'a'),
21011                ('2024-04-02 03:04:05', '20.50', 'b');",
21012        )
21013        .expect("create table_options_index table");
21014
21015        let frame = read_sql_table_with_options_and_index_col(
21016            &conn,
21017            "table_options_index",
21018            &SqlReadOptions {
21019                params: None,
21020                parse_dates: Some(vec!["ts".to_owned()]),
21021                coerce_float: true,
21022                dtype: None,
21023                schema: None,
21024                columns: None,
21025                index_col: None,
21026            },
21027            Some("ts"),
21028        )
21029        .expect("read table with options and index_col");
21030
21031        assert_eq!(frame.index().name(), Some("ts"));
21032        assert_eq!(
21033            frame.index().labels(),
21034            &[
21035                IndexLabel::Datetime64(1_711_929_600_000_000_000),
21036                IndexLabel::Datetime64(1_712_027_045_000_000_000)
21037            ]
21038        );
21039        assert!(frame.column("ts").is_none());
21040        assert_eq!(
21041            frame.column("amount").unwrap().values(),
21042            &[Scalar::Float64(10.0), Scalar::Float64(20.5)]
21043        );
21044    }
21045
21046    #[cfg(feature = "sql-sqlite")]
21047    #[test]
21048    fn sql_read_table_with_options_and_index_col_none_keeps_options_and_range_index() {
21049        let conn = make_sql_test_conn();
21050        conn.execute_batch(
21051            "CREATE TABLE table_options_no_index (id INTEGER, amount TEXT);
21052             INSERT INTO table_options_no_index (id, amount) VALUES
21053                (1, '$1.25'),
21054                (2, '$2.50');",
21055        )
21056        .expect("create table_options_no_index table");
21057
21058        let frame = read_sql_table_with_options_and_index_col(
21059            &conn,
21060            "table_options_no_index",
21061            &SqlReadOptions {
21062                params: None,
21063                parse_dates: None,
21064                coerce_float: true,
21065                dtype: None,
21066                schema: None,
21067                columns: None,
21068                index_col: None,
21069            },
21070            None,
21071        )
21072        .expect("read table with options and no index_col");
21073
21074        assert_eq!(
21075            frame.index().labels(),
21076            &[IndexLabel::Int64(0), IndexLabel::Int64(1)]
21077        );
21078        assert_eq!(frame.column_names(), vec!["id", "amount"]);
21079        assert_eq!(
21080            frame.column("amount").unwrap().values(),
21081            &[Scalar::Float64(1.25), Scalar::Float64(2.5)]
21082        );
21083    }
21084
21085    #[cfg(feature = "sql-sqlite")]
21086    #[test]
21087    fn sql_read_table_chunks_with_options_and_index_col_promotes_each_chunk_index() {
21088        let conn = make_sql_test_conn();
21089        conn.execute_batch(
21090            "CREATE TABLE table_options_index_chunked (ts TEXT, amount TEXT);
21091             INSERT INTO table_options_index_chunked (ts, amount) VALUES
21092                ('2024-05-01', '$10.00'),
21093                ('2024-05-02', '$20.00'),
21094                ('2024-05-03', '$30.50');",
21095        )
21096        .expect("create table_options_index_chunked table");
21097
21098        let chunks = read_sql_table_chunks_with_options_and_index_col(
21099            &conn,
21100            "table_options_index_chunked",
21101            &SqlReadOptions {
21102                params: None,
21103                parse_dates: Some(vec!["ts".to_owned()]),
21104                coerce_float: true,
21105                dtype: None,
21106                schema: None,
21107                columns: None,
21108                index_col: None,
21109            },
21110            Some("ts"),
21111            2,
21112        )
21113        .expect("table indexed option chunk iterator")
21114        .collect::<Result<Vec<_>, _>>()
21115        .expect("all chunks");
21116
21117        assert_eq!(chunks.len(), 2);
21118        assert_eq!(chunks[0].index().name(), Some("ts"));
21119        // parse_dates column promoted to index → DatetimeIndex (br-frankenpandas-0ezw7).
21120        assert_eq!(
21121            chunks[0].index().labels(),
21122            &[
21123                IndexLabel::Datetime64(1_714_521_600_000_000_000),
21124                IndexLabel::Datetime64(1_714_608_000_000_000_000)
21125            ]
21126        );
21127        assert!(chunks[0].column("ts").is_none());
21128        assert_eq!(
21129            chunks[0].column("amount").unwrap().values(),
21130            &[Scalar::Float64(10.0), Scalar::Float64(20.0)]
21131        );
21132        assert_eq!(
21133            chunks[1].index().labels(),
21134            &[IndexLabel::Datetime64(1_714_694_400_000_000_000)]
21135        );
21136        assert_eq!(
21137            chunks[1].column("amount").unwrap().values(),
21138            &[Scalar::Float64(30.5)]
21139        );
21140    }
21141
21142    #[cfg(feature = "sql-sqlite")]
21143    #[test]
21144    fn sql_read_table_chunks_with_options_and_index_col_uses_options_index_when_explicit_none() {
21145        let conn = make_sql_test_conn();
21146        conn.execute_batch(
21147            "CREATE TABLE table_options_struct_index (id INTEGER, amount TEXT);
21148             INSERT INTO table_options_struct_index (id, amount) VALUES
21149                (10, '$10.00'),
21150                (20, '$20.00'),
21151                (30, '$30.50');",
21152        )
21153        .expect("create table_options_struct_index table");
21154
21155        let chunks = read_sql_table_chunks_with_options_and_index_col(
21156            &conn,
21157            "table_options_struct_index",
21158            &SqlReadOptions {
21159                params: None,
21160                parse_dates: None,
21161                coerce_float: true,
21162                dtype: None,
21163                schema: None,
21164                columns: None,
21165                index_col: Some("id".to_owned()),
21166            },
21167            None,
21168            2,
21169        )
21170        .expect("table indexed option chunk iterator")
21171        .collect::<Result<Vec<_>, _>>()
21172        .expect("all chunks");
21173
21174        assert_eq!(chunks.len(), 2);
21175        assert_eq!(
21176            chunks[0].index().labels(),
21177            &[IndexLabel::Int64(10), IndexLabel::Int64(20)]
21178        );
21179        assert!(chunks[0].column("id").is_none());
21180        assert_eq!(chunks[1].index().labels(), &[IndexLabel::Int64(30)]);
21181        assert_eq!(
21182            chunks[1].column("amount").unwrap().values(),
21183            &[Scalar::Float64(30.5)]
21184        );
21185    }
21186
21187    #[cfg(feature = "sql-sqlite")]
21188    #[test]
21189    fn sql_read_table_chunks_with_options_and_index_col_missing_column_errors() {
21190        let conn = make_sql_test_conn();
21191        conn.execute_batch(
21192            "CREATE TABLE table_options_missing_index (id INTEGER, amount TEXT);
21193             INSERT INTO table_options_missing_index (id, amount) VALUES (1, '$10.00');",
21194        )
21195        .expect("create table_options_missing_index table");
21196
21197        let err = read_sql_table_chunks_with_options_and_index_col(
21198            &conn,
21199            "table_options_missing_index",
21200            &SqlReadOptions {
21201                params: None,
21202                parse_dates: None,
21203                coerce_float: true,
21204                dtype: None,
21205                schema: None,
21206                columns: None,
21207                index_col: None,
21208            },
21209            Some("missing"),
21210            1,
21211        )
21212        .expect_err("missing index_col should error during iterator construction");
21213
21214        assert!(matches!(err, IoError::Sql(msg) if msg.contains("index_col")));
21215    }
21216
21217    #[cfg(feature = "sql-sqlite")]
21218    #[test]
21219    fn sql_read_with_parse_dates_coerces_named_columns() {
21220        let conn = make_sql_test_conn();
21221        conn.execute_batch(
21222            "CREATE TABLE events (ts TEXT, value INTEGER);
21223             INSERT INTO events (ts, value) VALUES
21224                ('2024-01-15', 1),
21225                ('2024-02-01 05:06:07', 2);",
21226        )
21227        .expect("create events table");
21228
21229        let frame = read_sql_with_options(
21230            &conn,
21231            "SELECT ts, value FROM events ORDER BY value",
21232            &SqlReadOptions {
21233                params: None,
21234                parse_dates: Some(vec!["ts".to_owned()]),
21235                coerce_float: false,
21236                dtype: None,
21237                schema: None,
21238                columns: None,
21239                index_col: None,
21240            },
21241        )
21242        .expect("read sql with parse_dates");
21243
21244        // parse_dates now yields typed Datetime64[ns] (br-frankenpandas-0ezw7).
21245        assert_eq!(
21246            frame.column("ts").unwrap().values()[0],
21247            Scalar::Datetime64(1_705_276_800_000_000_000)
21248        );
21249        assert_eq!(
21250            frame.column("ts").unwrap().values()[1],
21251            Scalar::Datetime64(1_706_763_967_000_000_000)
21252        );
21253        assert_eq!(frame.column("value").unwrap().values()[0], Scalar::Int64(1));
21254        assert_eq!(frame.column("value").unwrap().values()[1], Scalar::Int64(2));
21255    }
21256
21257    #[cfg(feature = "sql-sqlite")]
21258    #[test]
21259    fn sql_read_with_parse_dates_missing_column_errors() {
21260        let conn = make_sql_test_conn();
21261        conn.execute_batch(
21262            "CREATE TABLE metrics (value INTEGER);
21263             INSERT INTO metrics (value) VALUES (1);",
21264        )
21265        .expect("create metrics table");
21266
21267        let err = read_sql_with_options(
21268            &conn,
21269            "SELECT value FROM metrics",
21270            &SqlReadOptions {
21271                params: None,
21272                parse_dates: Some(vec!["ts".to_owned()]),
21273                coerce_float: false,
21274                dtype: None,
21275                schema: None,
21276                columns: None,
21277                index_col: None,
21278            },
21279        )
21280        .expect_err("missing parse_dates column should error");
21281
21282        assert!(
21283            matches!(err, IoError::MissingParseDateColumns(missing) if missing == vec!["ts".to_owned()])
21284        );
21285    }
21286
21287    #[cfg(feature = "sql-sqlite")]
21288    #[test]
21289    fn sql_read_with_params_binds_positional_placeholders() {
21290        let frame = make_test_dataframe();
21291        let conn = make_sql_test_conn();
21292        write_sql(&frame, &conn, "data", SqlIfExists::Fail).unwrap();
21293
21294        let filtered = read_sql_with_options(
21295            &conn,
21296            "SELECT ints, names FROM data WHERE ints > ? AND names != ? ORDER BY ints",
21297            &SqlReadOptions {
21298                params: Some(vec![Scalar::Int64(15), Scalar::Utf8("bob".to_owned())]),
21299                parse_dates: None,
21300                coerce_float: false,
21301                dtype: None,
21302                schema: None,
21303                columns: None,
21304                index_col: None,
21305            },
21306        )
21307        .expect("read sql with params");
21308
21309        assert_eq!(filtered.index().len(), 1);
21310        assert_eq!(
21311            filtered.column("ints").unwrap().values(),
21312            &[Scalar::Int64(30)]
21313        );
21314        assert_eq!(
21315            filtered.column("names").unwrap().values(),
21316            &[Scalar::Utf8("carol".into())]
21317        );
21318    }
21319
21320    #[cfg(feature = "sql-sqlite")]
21321    #[test]
21322    fn sql_read_with_params_wrong_arity_errors() {
21323        let frame = make_test_dataframe();
21324        let conn = make_sql_test_conn();
21325        write_sql(&frame, &conn, "data", SqlIfExists::Fail).unwrap();
21326
21327        let err = read_sql_with_options(
21328            &conn,
21329            "SELECT ints FROM data WHERE ints > ? AND names != ?",
21330            &SqlReadOptions {
21331                params: Some(vec![Scalar::Int64(15)]),
21332                parse_dates: None,
21333                coerce_float: false,
21334                dtype: None,
21335                schema: None,
21336                columns: None,
21337                index_col: None,
21338            },
21339        )
21340        .expect_err("wrong arity should error");
21341
21342        assert!(matches!(err, IoError::Sql(msg) if msg.contains("parameter")));
21343    }
21344
21345    #[cfg(feature = "sql-sqlite")]
21346    #[test]
21347    fn sql_read_coerce_float_promotes_decimal_like_text_columns() {
21348        let conn = make_sql_test_conn();
21349        conn.execute_batch(
21350            "CREATE TABLE payments (id INTEGER, amount TEXT, fee TEXT);
21351             INSERT INTO payments (id, amount, fee) VALUES
21352                (1, '12.50', '$1,234.50'),
21353                (2, '-3.25', NULL);",
21354        )
21355        .expect("create payments table");
21356
21357        // Per fd90.41: pandas default for coerce_float is True, and our
21358        // SqlReadOptions::default() now matches. So the bare read_sql
21359        // path coerces decimal-like text columns to Float64 by default.
21360        let default_frame =
21361            read_sql(&conn, "SELECT amount FROM payments ORDER BY id").expect("default read");
21362        assert_eq!(
21363            default_frame.column("amount").unwrap().dtype(),
21364            DType::Float64
21365        );
21366        assert_eq!(
21367            default_frame.column("amount").unwrap().values(),
21368            &[Scalar::Float64(12.5), Scalar::Float64(-3.25)],
21369        );
21370
21371        // Explicitly opting out of coerce_float keeps the raw Utf8.
21372        let no_coerce = read_sql_with_options(
21373            &conn,
21374            "SELECT amount FROM payments ORDER BY id",
21375            &SqlReadOptions {
21376                coerce_float: false,
21377                ..SqlReadOptions::default()
21378            },
21379        )
21380        .expect("read without coerce_float");
21381        assert_eq!(
21382            no_coerce.column("amount").unwrap().values(),
21383            &[
21384                Scalar::Utf8("12.50".to_owned()),
21385                Scalar::Utf8("-3.25".to_owned()),
21386            ],
21387        );
21388
21389        let coerced = read_sql_with_options(
21390            &conn,
21391            "SELECT amount, fee FROM payments ORDER BY id",
21392            &SqlReadOptions {
21393                coerce_float: true,
21394                ..SqlReadOptions::default()
21395            },
21396        )
21397        .expect("read with coerce_float");
21398
21399        let amount = coerced.column("amount").expect("amount");
21400        assert_eq!(amount.dtype(), DType::Float64);
21401        assert_eq!(
21402            amount.values(),
21403            &[Scalar::Float64(12.5), Scalar::Float64(-3.25)],
21404        );
21405
21406        let fee = coerced.column("fee").expect("fee");
21407        assert_eq!(fee.dtype(), DType::Float64);
21408        assert_eq!(fee.values()[0], Scalar::Float64(1234.5));
21409        assert!(matches!(fee.values()[1], Scalar::Null(NullKind::NaN)));
21410    }
21411
21412    #[cfg(feature = "sql-sqlite")]
21413    #[test]
21414    fn sql_read_coerce_float_leaves_non_numeric_text_columns_unchanged() {
21415        let conn = make_sql_test_conn();
21416        conn.execute_batch(
21417            "CREATE TABLE mixed (id INTEGER, maybe_amount TEXT, label TEXT);
21418             INSERT INTO mixed (id, maybe_amount, label) VALUES
21419                (1, '12.50', 'alpha'),
21420                (2, 'not numeric', '20.0');",
21421        )
21422        .expect("create mixed table");
21423
21424        let frame = read_sql_with_options(
21425            &conn,
21426            "SELECT maybe_amount, label FROM mixed ORDER BY id",
21427            &SqlReadOptions {
21428                coerce_float: true,
21429                dtype: None,
21430                schema: None,
21431                columns: None,
21432                index_col: None,
21433                ..SqlReadOptions::default()
21434            },
21435        )
21436        .expect("read with coerce_float");
21437
21438        assert_eq!(
21439            frame.column("maybe_amount").unwrap().values(),
21440            &[
21441                Scalar::Utf8("12.50".to_owned()),
21442                Scalar::Utf8("not numeric".to_owned()),
21443            ],
21444        );
21445        assert_eq!(
21446            frame.column("label").unwrap().values(),
21447            &[
21448                Scalar::Utf8("alpha".to_owned()),
21449                Scalar::Utf8("20.0".to_owned()),
21450            ],
21451        );
21452    }
21453
21454    #[cfg(feature = "sql-sqlite")]
21455    #[test]
21456    fn sql_read_chunks_batches_rows_and_resets_index_per_chunk() {
21457        let conn = make_sql_test_conn();
21458        conn.execute_batch(
21459            "CREATE TABLE chunked (id INTEGER, name TEXT);
21460             INSERT INTO chunked (id, name) VALUES
21461                (1, 'alpha'),
21462                (2, 'beta'),
21463                (3, 'gamma'),
21464                (4, 'delta'),
21465                (5, 'epsilon');",
21466        )
21467        .expect("create chunked table");
21468
21469        let chunks = read_sql_chunks(&conn, "SELECT id, name FROM chunked ORDER BY id", 2)
21470            .expect("chunk iterator")
21471            .collect::<Result<Vec<_>, _>>()
21472            .expect("all chunks");
21473
21474        assert_eq!(chunks.len(), 3);
21475        assert_eq!(
21476            chunks[0].index().labels(),
21477            &[IndexLabel::Int64(0), IndexLabel::Int64(1)]
21478        );
21479        assert_eq!(
21480            chunks[1].index().labels(),
21481            &[IndexLabel::Int64(0), IndexLabel::Int64(1)]
21482        );
21483        assert_eq!(chunks[2].index().labels(), &[IndexLabel::Int64(0)]);
21484        assert_eq!(
21485            chunks[0].column("id").unwrap().values(),
21486            &[Scalar::Int64(1), Scalar::Int64(2)]
21487        );
21488        assert_eq!(
21489            chunks[1].column("id").unwrap().values(),
21490            &[Scalar::Int64(3), Scalar::Int64(4)]
21491        );
21492        assert_eq!(
21493            chunks[2].column("name").unwrap().values(),
21494            &[Scalar::Utf8("epsilon".to_owned())]
21495        );
21496    }
21497
21498    #[cfg(feature = "sql-sqlite")]
21499    #[test]
21500    fn sql_read_chunks_sqlite_uses_paged_iterator_state() {
21501        let conn = make_sql_test_conn();
21502        conn.execute_batch(
21503            "CREATE TABLE fp_sqlite_paged_chunks (id INTEGER, name TEXT);
21504             INSERT INTO fp_sqlite_paged_chunks (id, name) VALUES
21505                (1, 'alpha'),
21506                (2, 'beta');",
21507        )
21508        .expect("create sqlite_paged_chunks table");
21509
21510        let mut chunks = read_sql_chunks(
21511            &conn,
21512            "SELECT id, name FROM fp_sqlite_paged_chunks ORDER BY id",
21513            1,
21514        )
21515        .expect("chunk iterator");
21516
21517        let initial_debug = format!("{chunks:?}");
21518        assert!(
21519            initial_debug.contains("mode: \"paged\""),
21520            "SQLite chunk reads must use paged mode, got {initial_debug}"
21521        );
21522        assert!(initial_debug.contains("next_offset: 0"));
21523
21524        let first = chunks
21525            .next()
21526            .expect("first chunk")
21527            .expect("first chunk should read");
21528        assert_eq!(first.column("id").unwrap().values(), &[Scalar::Int64(1)]);
21529
21530        let after_first_debug = format!("{chunks:?}");
21531        assert!(after_first_debug.contains("next_offset: 1"));
21532    }
21533
21534    #[cfg(feature = "sql-sqlite")]
21535    #[test]
21536    fn sql_read_chunks_with_options_applies_params_parse_dates_and_coerce_float() {
21537        let conn = make_sql_test_conn();
21538        conn.execute_batch(
21539            "CREATE TABLE events (ts TEXT, amount TEXT, keep INTEGER);
21540             INSERT INTO events (ts, amount, keep) VALUES
21541                ('2024-01-15', '12.50', 0),
21542                ('2024-02-01 05:06:07', '$1,234.50', 1),
21543                ('2024-03-03', '-3.25', 1);",
21544        )
21545        .expect("create events table");
21546
21547        let chunks = read_sql_chunks_with_options(
21548            &conn,
21549            "SELECT ts, amount FROM events WHERE keep = ? ORDER BY ts",
21550            &SqlReadOptions {
21551                params: Some(vec![Scalar::Int64(1)]),
21552                parse_dates: Some(vec!["ts".to_owned()]),
21553                coerce_float: true,
21554                dtype: None,
21555                schema: None,
21556                columns: None,
21557                index_col: None,
21558            },
21559            1,
21560        )
21561        .expect("chunk iterator")
21562        .collect::<Result<Vec<_>, _>>()
21563        .expect("all chunks");
21564
21565        assert_eq!(chunks.len(), 2);
21566        // parse_dates now yields typed Datetime64[ns] (br-frankenpandas-0ezw7).
21567        assert_eq!(
21568            chunks[0].column("ts").unwrap().values(),
21569            &[Scalar::Datetime64(1_706_763_967_000_000_000)]
21570        );
21571        assert_eq!(
21572            chunks[0].column("amount").unwrap().values(),
21573            &[Scalar::Float64(1234.5)]
21574        );
21575        assert_eq!(
21576            chunks[1].column("ts").unwrap().values(),
21577            &[Scalar::Datetime64(1_709_424_000_000_000_000)]
21578        );
21579        assert_eq!(
21580            chunks[1].column("amount").unwrap().values(),
21581            &[Scalar::Float64(-3.25)]
21582        );
21583    }
21584
21585    #[cfg(feature = "sql-sqlite")]
21586    #[test]
21587    fn sql_read_chunks_rejects_zero_chunksize() {
21588        let conn = make_sql_test_conn();
21589
21590        let err =
21591            read_sql_chunks(&conn, "SELECT 1", 0).expect_err("zero chunksize should be rejected");
21592
21593        assert!(matches!(err, IoError::Sql(msg) if msg.contains("chunksize")));
21594    }
21595
21596    #[cfg(feature = "sql-sqlite")]
21597    #[test]
21598    fn sql_duplicate_column_names_error() {
21599        let conn = make_sql_test_conn();
21600        let err = read_sql(&conn, "SELECT 1 as dup, 2 as dup");
21601        assert!(matches!(err, Err(IoError::DuplicateColumnName(name)) if name == "dup"));
21602    }
21603
21604    #[cfg(feature = "sql-sqlite")]
21605    #[test]
21606    fn sql_if_exists_fail() {
21607        let frame = make_test_dataframe();
21608        let conn = make_sql_test_conn();
21609        write_sql(&frame, &conn, "tbl", SqlIfExists::Fail).unwrap();
21610
21611        let err = write_sql(&frame, &conn, "tbl", SqlIfExists::Fail);
21612        assert!(err.is_err());
21613        assert!(matches!(&err.unwrap_err(), IoError::Sql(msg) if msg.contains("already exists")),);
21614    }
21615
21616    #[cfg(feature = "sql-sqlite")]
21617    #[test]
21618    fn sql_if_exists_replace() {
21619        let frame = make_test_dataframe();
21620        let conn = make_sql_test_conn();
21621        write_sql(&frame, &conn, "tbl", SqlIfExists::Fail).unwrap();
21622
21623        // Replace should succeed and overwrite.
21624        write_sql(&frame, &conn, "tbl", SqlIfExists::Replace).unwrap();
21625        let frame2 = read_sql_table(&conn, "tbl").unwrap();
21626        assert_eq!(frame2.index().len(), 3);
21627    }
21628
21629    #[cfg(feature = "sql-sqlite")]
21630    #[test]
21631    fn sql_if_exists_append() {
21632        let frame = make_test_dataframe();
21633        let conn = make_sql_test_conn();
21634        write_sql(&frame, &conn, "tbl", SqlIfExists::Fail).unwrap();
21635
21636        // Append should add rows.
21637        write_sql(&frame, &conn, "tbl", SqlIfExists::Append).unwrap();
21638        let frame2 = read_sql_table(&conn, "tbl").unwrap();
21639        assert_eq!(frame2.index().len(), 6); // 3 + 3
21640    }
21641
21642    #[cfg(feature = "sql-sqlite")]
21643    #[test]
21644    fn sql_with_nulls() {
21645        use fp_types::DType;
21646
21647        let mut columns = BTreeMap::new();
21648        columns.insert(
21649            "vals".to_string(),
21650            Column::new(
21651                DType::Float64,
21652                vec![
21653                    Scalar::Float64(1.0),
21654                    Scalar::Null(NullKind::NaN),
21655                    Scalar::Float64(3.0),
21656                ],
21657            )
21658            .unwrap(),
21659        );
21660
21661        let labels = vec![
21662            IndexLabel::Int64(0),
21663            IndexLabel::Int64(1),
21664            IndexLabel::Int64(2),
21665        ];
21666        let frame =
21667            DataFrame::new_with_column_order(Index::new(labels), columns, vec!["vals".to_string()])
21668                .unwrap();
21669
21670        let conn = make_sql_test_conn();
21671        write_sql(&frame, &conn, "nulltest", SqlIfExists::Fail).unwrap();
21672        let frame2 = read_sql_table(&conn, "nulltest").unwrap();
21673
21674        assert_eq!(
21675            frame2.column("vals").unwrap().values()[0],
21676            Scalar::Float64(1.0)
21677        );
21678        assert!(frame2.column("vals").unwrap().values()[1].is_missing());
21679        assert_eq!(
21680            frame2.column("vals").unwrap().values()[2],
21681            Scalar::Float64(3.0)
21682        );
21683    }
21684
21685    #[cfg(feature = "sql-sqlite")]
21686    #[test]
21687    fn sql_bool_roundtrip() {
21688        use fp_types::DType;
21689
21690        let mut columns = BTreeMap::new();
21691        columns.insert(
21692            "flags".to_string(),
21693            Column::new(
21694                DType::Bool,
21695                vec![Scalar::Bool(true), Scalar::Bool(false), Scalar::Bool(true)],
21696            )
21697            .unwrap(),
21698        );
21699
21700        let labels = vec![
21701            IndexLabel::Int64(0),
21702            IndexLabel::Int64(1),
21703            IndexLabel::Int64(2),
21704        ];
21705        let frame = DataFrame::new_with_column_order(
21706            Index::new(labels),
21707            columns,
21708            vec!["flags".to_string()],
21709        )
21710        .unwrap();
21711
21712        let conn = make_sql_test_conn();
21713        write_sql(&frame, &conn, "booltest", SqlIfExists::Fail).unwrap();
21714        let frame2 = read_sql_table(&conn, "booltest").unwrap();
21715
21716        // Bools stored as INTEGER(0/1), read back as Int64.
21717        assert_eq!(
21718            frame2.column("flags").unwrap().values()[0],
21719            Scalar::Int64(1)
21720        );
21721        assert_eq!(
21722            frame2.column("flags").unwrap().values()[1],
21723            Scalar::Int64(0)
21724        );
21725    }
21726
21727    #[cfg(feature = "sql-sqlite")]
21728    #[test]
21729    fn sql_invalid_table_name_rejected() {
21730        let conn = make_sql_test_conn();
21731        let err = read_sql_table(&conn, "Robert'; DROP TABLE students; --");
21732        assert!(err.is_err());
21733        assert!(
21734            matches!(&err.unwrap_err(), IoError::Sql(msg) if msg.contains("invalid table name")),
21735        );
21736    }
21737
21738    #[cfg(feature = "sql-sqlite")]
21739    #[test]
21740    fn sql_empty_table_name_rejected() {
21741        let conn = make_sql_test_conn();
21742        let err = read_sql_table(&conn, "");
21743        assert!(err.is_err());
21744        assert!(
21745            matches!(&err.unwrap_err(), IoError::Sql(msg) if msg.contains("invalid table name")),
21746        );
21747
21748        let frame = make_test_dataframe();
21749        let err = write_sql(&frame, &conn, "", SqlIfExists::Fail);
21750        assert!(err.is_err());
21751    }
21752
21753    #[cfg(feature = "sql-sqlite")]
21754    #[test]
21755    fn sql_empty_result() {
21756        let conn = make_sql_test_conn();
21757        conn.execute_batch("CREATE TABLE empty (x INTEGER, y TEXT)")
21758            .unwrap();
21759        let frame = read_sql_table(&conn, "empty").unwrap();
21760        assert_eq!(frame.index().len(), 0);
21761        assert_eq!(frame.column_names().len(), 2);
21762        assert_eq!(frame.column("x").unwrap().dtype(), DType::Int64);
21763        assert_eq!(frame.column("y").unwrap().dtype(), DType::Utf8);
21764
21765        conn.execute_batch(
21766            "CREATE TABLE typed_nulls (i INTEGER, r REAL, t TEXT);
21767             INSERT INTO typed_nulls VALUES (NULL, NULL, NULL);",
21768        )
21769        .unwrap();
21770        let null_frame = read_sql_table(&conn, "typed_nulls").unwrap();
21771        assert_eq!(null_frame.index().len(), 1);
21772        assert_eq!(null_frame.column("i").unwrap().dtype(), DType::Int64);
21773        assert_eq!(null_frame.column("r").unwrap().dtype(), DType::Float64);
21774        assert_eq!(null_frame.column("t").unwrap().dtype(), DType::Utf8);
21775    }
21776
21777    #[cfg(feature = "sql-sqlite")]
21778    #[test]
21779    fn sql_empty_filtered_query_preserves_declared_dtypes() {
21780        let conn = make_sql_test_conn();
21781        conn.execute_batch(
21782            "CREATE TABLE filtered_empty (i INTEGER, r REAL, t TEXT);
21783             INSERT INTO filtered_empty VALUES (1, 1.25, 'kept');",
21784        )
21785        .unwrap();
21786
21787        let frame = read_sql_with_options(
21788            &conn,
21789            "SELECT i, r, t FROM filtered_empty WHERE i > ?",
21790            &SqlReadOptions {
21791                params: Some(vec![Scalar::Int64(10)]),
21792                ..SqlReadOptions::default()
21793            },
21794        )
21795        .expect("empty filtered query must preserve cursor dtype hints");
21796
21797        assert_eq!(frame.index().len(), 0);
21798        assert_eq!(frame.column_names(), vec!["i", "r", "t"]);
21799        assert_eq!(frame.column("i").unwrap().dtype(), DType::Int64);
21800        assert_eq!(frame.column("r").unwrap().dtype(), DType::Float64);
21801        assert_eq!(frame.column("t").unwrap().dtype(), DType::Utf8);
21802    }
21803
21804    #[cfg(feature = "sql-sqlite")]
21805    #[test]
21806    fn sql_extension_trait() {
21807        let frame = make_test_dataframe();
21808        let conn = make_sql_test_conn();
21809
21810        // Use the extension trait method.
21811        use super::DataFrameIoExt;
21812        frame.to_sql(&conn, "ext_test", SqlIfExists::Fail).unwrap();
21813        frame
21814            .to_sql_with_options(
21815                &conn,
21816                "ext_test_options",
21817                &SqlWriteOptions {
21818                    if_exists: SqlIfExists::Fail,
21819                    index: false,
21820                    index_label: None,
21821                    schema: None,
21822                    dtype: None,
21823                    method: SqlInsertMethod::Single,
21824                    chunksize: None,
21825                },
21826            )
21827            .unwrap();
21828
21829        let frame2 = read_sql_table(&conn, "ext_test").unwrap();
21830        assert_eq!(frame2.index().len(), 3);
21831        let frame3 = read_sql_table(&conn, "ext_test_options").unwrap();
21832        assert_eq!(frame3.index().len(), 3);
21833    }
21834
21835    #[cfg(feature = "sql-sqlite")]
21836    #[test]
21837    fn series_sql_extension_aliases_roundtrip_to_single_column_table() {
21838        use super::SeriesIoExt;
21839
21840        let source = Series::from_values(
21841            "sales",
21842            vec!["r1".into(), "r2".into()],
21843            vec![Scalar::Int64(10), Scalar::Int64(12)],
21844        )
21845        .expect("source series");
21846
21847        let conn = make_sql_test_conn();
21848        source
21849            .to_sql(&conn, "series_ext", SqlIfExists::Fail)
21850            .expect("series to_sql");
21851        let roundtrip = read_sql_table(&conn, "series_ext").expect("read series table");
21852        assert_eq!(roundtrip.column_names(), vec!["index", "sales"]);
21853        assert_eq!(
21854            roundtrip.column("index").expect("index column").values(),
21855            &[Scalar::Utf8("r1".into()), Scalar::Utf8("r2".into())]
21856        );
21857        assert_eq!(
21858            roundtrip.column("sales").expect("sales column").values(),
21859            source.values()
21860        );
21861
21862        source
21863            .to_sql_with_options(
21864                &conn,
21865                "series_ext_no_index",
21866                &SqlWriteOptions {
21867                    if_exists: SqlIfExists::Fail,
21868                    index: false,
21869                    index_label: None,
21870                    schema: None,
21871                    dtype: None,
21872                    method: SqlInsertMethod::Single,
21873                    chunksize: None,
21874                },
21875            )
21876            .expect("series to_sql index false");
21877        let no_index =
21878            read_sql_table(&conn, "series_ext_no_index").expect("read no-index series table");
21879        assert_eq!(no_index.column_names(), vec!["sales"]);
21880        assert_eq!(
21881            no_index.column("sales").expect("sales column").values(),
21882            source.values()
21883        );
21884    }
21885
21886    // ── Arrow IPC / Feather tests ────────────────────────────────────
21887
21888    #[test]
21889    fn feather_bytes_roundtrip() {
21890        let frame = make_test_dataframe();
21891        let bytes = super::write_feather_bytes(&frame).expect("write feather");
21892        assert!(!bytes.is_empty());
21893
21894        let frame2 = super::read_feather_bytes(&bytes).expect("read feather");
21895        assert_eq!(frame2.index().len(), 3);
21896
21897        // Check all column values survive round-trip exactly.
21898        let ints = frame2.column("ints").unwrap();
21899        assert_eq!(ints.values()[0], Scalar::Int64(10));
21900        assert_eq!(ints.values()[1], Scalar::Int64(20));
21901        assert_eq!(ints.values()[2], Scalar::Int64(30));
21902
21903        let floats = frame2.column("floats").unwrap();
21904        assert_eq!(floats.values()[0], Scalar::Float64(1.5));
21905        assert_eq!(floats.values()[2], Scalar::Float64(3.5));
21906
21907        let names = frame2.column("names").unwrap();
21908        assert_eq!(names.values()[0], Scalar::Utf8("alice".into()));
21909        assert_eq!(names.values()[2], Scalar::Utf8("carol".into()));
21910    }
21911
21912    #[test]
21913    fn feather_row_multiindex_roundtrip_restores_logical_row_axis() {
21914        let frame = make_row_multiindex_test_dataframe();
21915        let bytes = super::write_feather_bytes(&frame).expect("write feather");
21916        let roundtrip = super::read_feather_bytes(&bytes).expect("read feather");
21917
21918        assert!(roundtrip.equals(&frame));
21919        assert!(roundtrip.column("__index_level_0__").is_none());
21920        assert_eq!(
21921            roundtrip
21922                .row_multiindex()
21923                .expect("row multiindex should be restored")
21924                .get_level_values(1)
21925                .unwrap()
21926                .labels(),
21927            frame
21928                .row_multiindex()
21929                .expect("source row multiindex")
21930                .get_level_values(1)
21931                .unwrap()
21932                .labels()
21933        );
21934    }
21935
21936    #[test]
21937    fn feather_file_roundtrip() {
21938        let frame = make_test_dataframe();
21939        let dir = std::env::temp_dir();
21940        let path = dir.join("fp_io_test_feather_roundtrip.feather");
21941
21942        super::write_feather(&frame, &path).expect("write feather file");
21943        let frame2 = super::read_feather(&path).expect("read feather file");
21944        assert_eq!(frame2.index().len(), 3);
21945        assert_eq!(
21946            frame2.column("ints").unwrap().values()[0],
21947            Scalar::Int64(10)
21948        );
21949        std::fs::remove_file(&path).ok();
21950    }
21951
21952    #[test]
21953    fn ipc_stream_bytes_roundtrip() {
21954        let frame = make_test_dataframe();
21955        let bytes = super::write_ipc_stream_bytes(&frame).expect("write ipc stream");
21956        assert!(!bytes.is_empty());
21957
21958        let frame2 = super::read_ipc_stream_bytes(&bytes).expect("read ipc stream");
21959        assert_eq!(frame2.index().len(), 3);
21960        assert_eq!(
21961            frame2.column("ints").unwrap().values()[1],
21962            Scalar::Int64(20)
21963        );
21964        assert_eq!(
21965            frame2.column("names").unwrap().values()[1],
21966            Scalar::Utf8("bob".into())
21967        );
21968    }
21969
21970    #[test]
21971    fn ipc_stream_row_multiindex_roundtrip_restores_logical_row_axis() {
21972        let frame = make_row_multiindex_test_dataframe();
21973        let bytes = super::write_ipc_stream_bytes(&frame).expect("write ipc stream");
21974        let roundtrip = super::read_ipc_stream_bytes(&bytes).expect("read ipc stream");
21975
21976        assert!(roundtrip.equals(&frame));
21977        assert!(roundtrip.row_multiindex().is_some());
21978    }
21979
21980    #[test]
21981    fn feather_with_nulls() {
21982        use fp_types::DType;
21983
21984        let mut columns = BTreeMap::new();
21985        columns.insert(
21986            "vals".to_string(),
21987            Column::new(
21988                DType::Float64,
21989                vec![
21990                    Scalar::Float64(1.0),
21991                    Scalar::Null(NullKind::NaN),
21992                    Scalar::Float64(3.0),
21993                ],
21994            )
21995            .unwrap(),
21996        );
21997
21998        let labels = vec![
21999            IndexLabel::Int64(0),
22000            IndexLabel::Int64(1),
22001            IndexLabel::Int64(2),
22002        ];
22003        let frame =
22004            DataFrame::new_with_column_order(Index::new(labels), columns, vec!["vals".to_string()])
22005                .unwrap();
22006
22007        let bytes = super::write_feather_bytes(&frame).expect("write");
22008        let frame2 = super::read_feather_bytes(&bytes).expect("read");
22009
22010        assert_eq!(
22011            frame2.column("vals").unwrap().values()[0],
22012            Scalar::Float64(1.0)
22013        );
22014        assert!(frame2.column("vals").unwrap().values()[1].is_missing());
22015        assert_eq!(
22016            frame2.column("vals").unwrap().values()[2],
22017            Scalar::Float64(3.0)
22018        );
22019    }
22020
22021    #[test]
22022    fn feather_nullable_int_roundtrip_preserves_int_dtype() {
22023        use fp_types::DType;
22024
22025        let mut columns = BTreeMap::new();
22026        columns.insert(
22027            "vals".to_string(),
22028            Column::new(
22029                DType::Int64,
22030                vec![
22031                    Scalar::Int64(10),
22032                    Scalar::Null(NullKind::Null),
22033                    Scalar::Int64(30),
22034                ],
22035            )
22036            .unwrap(),
22037        );
22038
22039        let labels = vec![
22040            IndexLabel::Int64(0),
22041            IndexLabel::Int64(1),
22042            IndexLabel::Int64(2),
22043        ];
22044        let frame =
22045            DataFrame::new_with_column_order(Index::new(labels), columns, vec!["vals".to_string()])
22046                .unwrap();
22047
22048        let bytes = super::write_feather_bytes(&frame).expect("write");
22049        let frame2 = super::read_feather_bytes(&bytes).expect("read");
22050        let vals = frame2.column("vals").unwrap();
22051
22052        assert_eq!(vals.dtype(), DType::Int64);
22053        assert_eq!(vals.values()[0], Scalar::Int64(10));
22054        assert_eq!(vals.values()[1], Scalar::Null(NullKind::Null));
22055        assert_eq!(vals.values()[2], Scalar::Int64(30));
22056    }
22057
22058    #[test]
22059    fn series_arrow_array_nullable_int_roundtrip() {
22060        let series = Series::from_values(
22061            "vals",
22062            vec![
22063                IndexLabel::Utf8("r0".into()),
22064                IndexLabel::Utf8("r1".into()),
22065                IndexLabel::Utf8("r2".into()),
22066            ],
22067            vec![
22068                Scalar::Int64(10),
22069                Scalar::Null(NullKind::Null),
22070                Scalar::Int64(30),
22071            ],
22072        )
22073        .unwrap();
22074
22075        let (dt, arr) = super::series_to_arrow_array(&series).expect("arrow encode");
22076        assert_eq!(dt, ArrowDataType::Int64);
22077
22078        let typed = arr
22079            .as_any()
22080            .downcast_ref::<Int64Array>()
22081            .expect("int64 arrow array");
22082        assert_eq!(typed.value(0), 10);
22083        assert!(typed.is_null(1));
22084        assert_eq!(typed.value(2), 30);
22085
22086        let roundtrip = super::series_from_arrow_array(
22087            series.name(),
22088            series.index().labels().to_vec(),
22089            arr.as_ref(),
22090            &dt,
22091        )
22092        .expect("arrow decode");
22093
22094        assert_eq!(roundtrip.name(), "vals");
22095        assert_eq!(roundtrip.index().labels(), series.index().labels());
22096        assert_eq!(roundtrip.column().dtype(), DType::Int64);
22097        assert_eq!(roundtrip.values(), series.values());
22098    }
22099
22100    #[test]
22101    fn feather_bool_column() {
22102        use fp_types::DType;
22103
22104        let mut columns = BTreeMap::new();
22105        columns.insert(
22106            "flags".to_string(),
22107            Column::new(
22108                DType::Bool,
22109                vec![Scalar::Bool(true), Scalar::Bool(false), Scalar::Bool(true)],
22110            )
22111            .unwrap(),
22112        );
22113
22114        let labels = vec![
22115            IndexLabel::Int64(0),
22116            IndexLabel::Int64(1),
22117            IndexLabel::Int64(2),
22118        ];
22119        let frame = DataFrame::new_with_column_order(
22120            Index::new(labels),
22121            columns,
22122            vec!["flags".to_string()],
22123        )
22124        .unwrap();
22125
22126        let bytes = super::write_feather_bytes(&frame).expect("write");
22127        let frame2 = super::read_feather_bytes(&bytes).expect("read");
22128
22129        assert_eq!(
22130            frame2.column("flags").unwrap().values()[0],
22131            Scalar::Bool(true)
22132        );
22133        assert_eq!(
22134            frame2.column("flags").unwrap().values()[1],
22135            Scalar::Bool(false)
22136        );
22137    }
22138
22139    #[test]
22140    fn feather_preserves_column_order() {
22141        let frame = make_test_dataframe();
22142        let bytes = super::write_feather_bytes(&frame).expect("write");
22143        let frame2 = super::read_feather_bytes(&bytes).expect("read");
22144
22145        assert_eq!(
22146            frame2
22147                .column_names()
22148                .iter()
22149                .map(|s| s.as_str())
22150                .collect::<Vec<_>>(),
22151            frame
22152                .column_names()
22153                .iter()
22154                .map(|s| s.as_str())
22155                .collect::<Vec<_>>()
22156        );
22157    }
22158
22159    #[test]
22160    fn feather_extension_trait() {
22161        use super::DataFrameIoExt;
22162
22163        let frame = make_test_dataframe();
22164        let bytes = frame.to_feather_bytes().unwrap();
22165        let frame2 = super::read_feather_bytes(&bytes).unwrap();
22166        assert_eq!(frame2.index().len(), 3);
22167    }
22168
22169    // ── Adversarial parser tests (frankenpandas-yby) ─────────────────
22170
22171    // ── CsvReadOptions extended params tests (frankenpandas-qoz) ────
22172
22173    #[test]
22174    fn csv_nrows_limits_rows() {
22175        let input = "x\n1\n2\n3\n4\n5\n";
22176        let opts = CsvReadOptions {
22177            nrows: Some(3),
22178            ..Default::default()
22179        };
22180        let frame = read_csv_with_options(input, &opts).expect("parse");
22181        assert_eq!(frame.index().len(), 3);
22182        assert_eq!(frame.column("x").unwrap().values()[2], Scalar::Int64(3));
22183    }
22184
22185    #[test]
22186    fn csv_skiprows_skips_data_rows() {
22187        let input = "x\n1\n2\n3\n4\n5\n";
22188        let opts = CsvReadOptions {
22189            skiprows: 2,
22190            ..Default::default()
22191        };
22192        let frame = read_csv_with_options(input, &opts).expect("parse");
22193        assert_eq!(frame.index().len(), 3); // skipped header + first data row
22194        assert_eq!(frame.column("2").unwrap().values()[0], Scalar::Int64(3));
22195    }
22196
22197    #[test]
22198    fn csv_skiprows_and_nrows_combined() {
22199        let input = "x\n1\n2\n3\n4\n5\n";
22200        let opts = CsvReadOptions {
22201            skiprows: 1,
22202            nrows: Some(2),
22203            ..Default::default()
22204        };
22205        let frame = read_csv_with_options(input, &opts).expect("parse");
22206        assert_eq!(frame.index().len(), 2); // skipped header; read 2 data rows
22207        assert_eq!(frame.column("1").unwrap().values()[0], Scalar::Int64(2));
22208        assert_eq!(frame.column("1").unwrap().values()[1], Scalar::Int64(3));
22209    }
22210
22211    #[test]
22212    fn csv_usecols_selects_columns() {
22213        let input = "a,b,c\n1,2,3\n4,5,6\n";
22214        let opts = CsvReadOptions {
22215            usecols: Some(vec!["a".into(), "c".into()]),
22216            ..Default::default()
22217        };
22218        let frame = read_csv_with_options(input, &opts).expect("parse");
22219        assert_eq!(frame.column_names().len(), 2);
22220        assert!(frame.column("a").is_some());
22221        assert!(frame.column("b").is_none());
22222        assert!(frame.column("c").is_some());
22223        assert_eq!(frame.column("a").unwrap().values()[0], Scalar::Int64(1));
22224        assert_eq!(frame.column("c").unwrap().values()[1], Scalar::Int64(6));
22225    }
22226
22227    #[test]
22228    fn csv_usecols_nonexistent_column_errors() {
22229        let input = "a,b\n1,2\n";
22230        let opts = CsvReadOptions {
22231            usecols: Some(vec!["a".into(), "nonexistent".into()]),
22232            ..Default::default()
22233        };
22234        let err = read_csv_with_options(input, &opts).expect_err("missing usecols should error");
22235        assert!(matches!(err, IoError::MissingUsecols(_)));
22236    }
22237
22238    #[test]
22239    fn csv_dtype_coercion() {
22240        let input = "id,score\n1,95\n2,87\n";
22241        let mut dtype_map = std::collections::HashMap::new();
22242        dtype_map.insert("score".to_owned(), fp_types::DType::Float64);
22243        let opts = CsvReadOptions {
22244            dtype: Some(dtype_map),
22245            ..Default::default()
22246        };
22247        let frame = read_csv_with_options(input, &opts).expect("parse");
22248        // score column should be Float64, not Int64
22249        assert_eq!(
22250            frame.column("score").unwrap().values()[0],
22251            Scalar::Float64(95.0)
22252        );
22253        assert_eq!(
22254            frame.column("score").unwrap().values()[1],
22255            Scalar::Float64(87.0)
22256        );
22257        // id column should remain Int64 (not in dtype map)
22258        assert_eq!(frame.column("id").unwrap().values()[0], Scalar::Int64(1));
22259    }
22260
22261    #[test]
22262    fn csv_dtype_coercion_invalid_value_errors() {
22263        let input = "id,score\n1,abc\n";
22264        let mut dtype_map = std::collections::HashMap::new();
22265        dtype_map.insert("score".to_owned(), fp_types::DType::Int64);
22266        let opts = CsvReadOptions {
22267            dtype: Some(dtype_map),
22268            ..Default::default()
22269        };
22270        let err = read_csv_with_options(input, &opts).expect_err("invalid cast must error");
22271        assert!(matches!(
22272            err,
22273            IoError::Column(fp_columnar::ColumnError::Type(
22274                fp_types::TypeError::InvalidCast { .. }
22275            ))
22276        ));
22277    }
22278
22279    #[test]
22280    fn csv_skiprows_beyond_data_errors() {
22281        let input = "x\n1\n2\n";
22282        let opts = CsvReadOptions {
22283            skiprows: 100,
22284            ..Default::default()
22285        };
22286        let err = read_csv_with_options(input, &opts).expect_err("skiprows removes header");
22287        assert!(matches!(err, IoError::MissingHeaders));
22288    }
22289
22290    #[test]
22291    fn csv_nrows_zero_returns_empty() {
22292        let input = "x\n1\n2\n3\n";
22293        let opts = CsvReadOptions {
22294            nrows: Some(0),
22295            ..Default::default()
22296        };
22297        let frame = read_csv_with_options(input, &opts).expect("parse");
22298        assert_eq!(frame.index().len(), 0);
22299    }
22300
22301    #[test]
22302    fn csv_decimal_comma_parses_quoted_float_fields() {
22303        let input = "price\n\"1,50\"\n\"3,75\"\n";
22304        let opts = CsvReadOptions {
22305            decimal: b',',
22306            ..Default::default()
22307        };
22308        let frame = read_csv_with_options(input, &opts).expect("parse");
22309        assert_eq!(
22310            frame.column("price").unwrap().values(),
22311            &[Scalar::Float64(1.5), Scalar::Float64(3.75)]
22312        );
22313    }
22314
22315    #[test]
22316    fn csv_default_decimal_keeps_comma_decimal_strings_as_utf8() {
22317        let input = "price\n\"1,50\"\n";
22318        let frame = read_csv_with_options(input, &CsvReadOptions::default()).expect("parse");
22319        assert_eq!(
22320            frame.column("price").unwrap().values(),
22321            &[Scalar::Utf8("1,50".to_owned())]
22322        );
22323    }
22324
22325    #[test]
22326    fn csv_true_false_values_do_not_override_numeric_inference() {
22327        let input = "flag\n1\n0\n";
22328        let opts = CsvReadOptions {
22329            true_values: vec!["1".to_owned()],
22330            false_values: vec!["0".to_owned()],
22331            ..Default::default()
22332        };
22333        let frame = read_csv_with_options(input, &opts).expect("parse");
22334        assert_eq!(
22335            frame.column("flag").unwrap().values(),
22336            &[Scalar::Int64(1), Scalar::Int64(0)]
22337        );
22338    }
22339
22340    #[test]
22341    fn csv_true_false_values_convert_non_numeric_tokens() {
22342        let input = "flag\nyes\nno\n";
22343        let opts = CsvReadOptions {
22344            true_values: vec!["yes".to_owned()],
22345            false_values: vec!["no".to_owned()],
22346            ..Default::default()
22347        };
22348        let frame = read_csv_with_options(input, &opts).expect("parse");
22349        assert_eq!(
22350            frame.column("flag").unwrap().values(),
22351            &[Scalar::Bool(true), Scalar::Bool(false)]
22352        );
22353    }
22354
22355    #[test]
22356    fn csv_default_parsing_keeps_numeric_boolean_tokens_as_ints() {
22357        let input = "flag\n1\n0\n";
22358        let frame = read_csv_with_options(input, &CsvReadOptions::default()).expect("parse");
22359        assert_eq!(
22360            frame.column("flag").unwrap().values(),
22361            &[Scalar::Int64(1), Scalar::Int64(0)]
22362        );
22363    }
22364
22365    #[test]
22366    fn csv_missing_numeric_column_preserves_int() {
22367        // DISC-011: Nullable extension Int64 dtype parity - Int64 preserved, not promoted to Float64.
22368        let input = "a,b,c\n,NA,NaN\n1,,x\n";
22369        let frame = read_csv_with_options(input, &CsvReadOptions::default()).expect("parse");
22370        assert_eq!(
22371            frame.column("a").unwrap().values(),
22372            &[Scalar::Null(NullKind::Null), Scalar::Int64(1)]
22373        );
22374        assert!(frame.column("b").unwrap().values()[0].is_missing());
22375        assert!(frame.column("b").unwrap().values()[1].is_missing());
22376        assert_eq!(
22377            frame.column("c").unwrap().values(),
22378            &[Scalar::Null(NullKind::Null), Scalar::Utf8("x".to_owned())]
22379        );
22380    }
22381
22382    #[test]
22383    fn csv_parse_dates_mixed_naive_and_aware_strings_normalizes_per_value() {
22384        // pandas pd.read_csv(parse_dates=["ts"]) CANNOT unify a column mixing
22385        // tz-naive and tz-aware timestamps into datetime64[ns], so it keeps the
22386        // whole column as object — a Series of mixed Timestamp objects whose
22387        // str() forms are the naive `YYYY-MM-DD HH:MM:SS` and the aware
22388        // `... +HH:MM`. FrankenPandas reproduces that (br-frankenpandas-unz0t):
22389        // both entries are normalized to their pandas object-string form rather
22390        // than coercing the naive one to Datetime64 (which contradicted both
22391        // pandas and conformance fixture FP-P2D-mixed-timezone).
22392        let input = "ts,value\n2024-01-15 10:30:00,1\n2024-01-15T10:30:00Z,2\n";
22393        let opts = CsvReadOptions {
22394            parse_dates: Some(vec!["ts".to_owned()]),
22395            ..Default::default()
22396        };
22397        let frame = read_csv_with_options(input, &opts).expect("parse");
22398        assert_eq!(
22399            frame.column("ts").unwrap().values(),
22400            &[
22401                Scalar::Utf8("2024-01-15 10:30:00".to_owned()),
22402                Scalar::Utf8("2024-01-15 10:30:00+00:00".to_owned()),
22403            ]
22404        );
22405        assert_eq!(
22406            frame.column("value").unwrap().values(),
22407            &[Scalar::Int64(1), Scalar::Int64(2)]
22408        );
22409    }
22410
22411    #[test]
22412    fn csv_parse_dates_fixed_naive_fast_path_accepts_only_safe_domain() {
22413        let values = vec![
22414            Scalar::Utf8("2024-01-15 10:30:00".to_owned()),
22415            Scalar::Utf8("2024-02-29".to_owned()),
22416            Scalar::Null(NullKind::NaT),
22417        ];
22418        let parsed = super::parse_csv_fixed_naive_datetime_values(&values).expect("fixed parse");
22419        assert_eq!(
22420            parsed,
22421            vec![
22422                Scalar::Datetime64(1_705_314_600_000_000_000),
22423                Scalar::Datetime64(1_709_164_800_000_000_000),
22424                Scalar::Datetime64(Timestamp::NAT),
22425            ]
22426        );
22427
22428        for rejected in [
22429            "2024-01-15T10:30:00Z",
22430            "2024-02-30",
22431            "2024-01-15 10:30:00.123",
22432        ] {
22433            assert!(
22434                super::parse_csv_fixed_naive_datetime_values(&[Scalar::Utf8(rejected.to_owned())])
22435                    .is_none(),
22436                "{rejected:?} must use the general parse_dates path"
22437            );
22438        }
22439    }
22440
22441    #[test]
22442    fn csv_parse_dates_raw_fast_path_preserves_na_semantics() {
22443        let input = "ts,value\nMISSING,1\n2024-01-15 10:30:00,2\n";
22444        let opts = CsvReadOptions {
22445            parse_dates: Some(vec!["ts".to_owned()]),
22446            na_values: vec!["MISSING".to_owned()],
22447            ..Default::default()
22448        };
22449        let frame = read_csv_with_options(input, &opts).expect("parse");
22450        assert_eq!(
22451            frame.column("ts").unwrap().values(),
22452            &[
22453                Scalar::Datetime64(Timestamp::NAT),
22454                Scalar::Datetime64(1_705_314_600_000_000_000),
22455            ]
22456        );
22457        assert_eq!(
22458            frame.column("value").unwrap().values(),
22459            &[Scalar::Int64(1), Scalar::Int64(2)]
22460        );
22461    }
22462
22463    #[test]
22464    fn csv_parse_dates_deferred_fallback_replays_scalar_inference() {
22465        let input = "ts,value\n2024-01-15 10:30:00,1\nnot-a-date,2\n";
22466        let opts = CsvReadOptions {
22467            parse_dates: Some(vec!["ts".to_owned()]),
22468            ..Default::default()
22469        };
22470        let frame = read_csv_with_options(input, &opts).expect("parse");
22471        assert_eq!(
22472            frame.column("ts").unwrap().values(),
22473            &[
22474                Scalar::Utf8("2024-01-15 10:30:00".to_owned()),
22475                Scalar::Utf8("not-a-date".to_owned()),
22476            ]
22477        );
22478
22479        let keep_na_literal = CsvReadOptions {
22480            parse_dates: Some(vec!["ts".to_owned()]),
22481            keep_default_na: false,
22482            ..Default::default()
22483        };
22484        let frame = read_csv_with_options("ts\nNA\n2024-01-15\n", &keep_na_literal).expect("parse");
22485        assert_eq!(
22486            frame.column("ts").unwrap().values(),
22487            &[
22488                Scalar::Utf8("NA".to_owned()),
22489                Scalar::Utf8("2024-01-15".to_owned()),
22490            ]
22491        );
22492    }
22493
22494    #[test]
22495    fn csv_parse_dates_deferred_mask_tracks_usecols_and_headerless() {
22496        let input = "2024-01-15 10:30:00,10\n2024-01-16 11:45:30,20\n";
22497        let opts = CsvReadOptions {
22498            has_headers: false,
22499            parse_dates: Some(vec!["column_0".to_owned()]),
22500            usecols: Some(vec!["column_0".to_owned()]),
22501            ..Default::default()
22502        };
22503        let frame = read_csv_with_options(input, &opts).expect("parse");
22504        assert_eq!(frame.column_names(), vec!["column_0"]);
22505        assert_eq!(
22506            frame.column("column_0").unwrap().values(),
22507            &[
22508                Scalar::Datetime64(1_705_314_600_000_000_000),
22509                Scalar::Datetime64(1_705_405_530_000_000_000),
22510            ]
22511        );
22512    }
22513
22514    #[test]
22515    fn csv_parse_dates_combined_columns_replaces_source_columns() {
22516        let input = "date,time,value\n2024-01-15,10:30:00,1\n2024-01-16,11:45:30,2\n";
22517        let opts = CsvReadOptions {
22518            parse_date_combinations: Some(vec![vec!["date".to_owned(), "time".to_owned()]]),
22519            ..Default::default()
22520        };
22521        let frame = read_csv_with_options(input, &opts).expect("parse");
22522        assert_eq!(frame.column_names(), vec!["date_time", "value"]);
22523        assert_eq!(
22524            frame.column("date_time").unwrap().values(),
22525            &[
22526                Scalar::Datetime64(1_705_314_600_000_000_000),
22527                Scalar::Datetime64(1_705_405_530_000_000_000),
22528            ]
22529        );
22530        assert!(frame.column("date").is_none());
22531        assert!(frame.column("time").is_none());
22532        assert_eq!(
22533            frame.column("value").unwrap().values(),
22534            &[Scalar::Int64(1), Scalar::Int64(2)]
22535        );
22536    }
22537
22538    #[test]
22539    fn csv_parse_date_combinations_named_uses_caller_supplied_name() {
22540        let input = "date,time,value\n2024-01-15,10:30:00,1\n2024-01-16,11:45:30,2\n";
22541        let opts = CsvReadOptions {
22542            parse_date_combinations_named: Some(vec![(
22543                "timestamp".to_owned(),
22544                vec!["date".to_owned(), "time".to_owned()],
22545            )]),
22546            ..Default::default()
22547        };
22548        let frame = read_csv_with_options(input, &opts).expect("parse");
22549        // Dict-style rename: combined column named "timestamp" rather than
22550        // the default underscore-joined "date_time".
22551        assert_eq!(frame.column_names(), vec!["timestamp", "value"]);
22552        assert!(frame.column("date").is_none());
22553        assert!(frame.column("time").is_none());
22554        assert_eq!(
22555            frame.column("timestamp").unwrap().values(),
22556            &[
22557                Scalar::Datetime64(1_705_314_600_000_000_000),
22558                Scalar::Datetime64(1_705_405_530_000_000_000),
22559            ]
22560        );
22561    }
22562
22563    #[test]
22564    fn csv_parse_date_combinations_named_multiple_groups() {
22565        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";
22566        let opts = CsvReadOptions {
22567            parse_date_combinations_named: Some(vec![
22568                ("start".to_owned(), vec!["d1".to_owned(), "t1".to_owned()]),
22569                ("end".to_owned(), vec!["d2".to_owned(), "t2".to_owned()]),
22570            ]),
22571            ..Default::default()
22572        };
22573        let frame = read_csv_with_options(input, &opts).expect("parse");
22574        let names = frame.column_names();
22575        assert!(names.iter().any(|n| n.as_str() == "start"));
22576        assert!(names.iter().any(|n| n.as_str() == "end"));
22577        assert!(!names.iter().any(|n| n.as_str() == "d1"));
22578        assert!(!names.iter().any(|n| n.as_str() == "t2"));
22579        assert_eq!(
22580            frame.column("value").unwrap().values(),
22581            &[Scalar::Int64(10), Scalar::Int64(20)]
22582        );
22583        assert_eq!(
22584            frame.column("start").unwrap().values(),
22585            &[
22586                Scalar::Datetime64(1_704_099_600_000_000_000),
22587                Scalar::Datetime64(1_706_778_000_000_000_000),
22588            ]
22589        );
22590    }
22591
22592    #[test]
22593    fn csv_parse_date_combinations_named_rejects_duplicate_output_names() {
22594        let input = "a,b,c,d\n2024,01,2024,02\n";
22595        let opts = CsvReadOptions {
22596            parse_date_combinations_named: Some(vec![
22597                ("ts".to_owned(), vec!["a".to_owned(), "b".to_owned()]),
22598                ("ts".to_owned(), vec!["c".to_owned(), "d".to_owned()]),
22599            ]),
22600            ..Default::default()
22601        };
22602        let err = read_csv_with_options(input, &opts).unwrap_err();
22603        assert!(matches!(err, IoError::DuplicateColumnName(name) if name == "ts"));
22604    }
22605
22606    #[test]
22607    fn csv_parse_date_combinations_named_rejects_missing_source_column() {
22608        let input = "date,time,value\n2024-01-01,09:00:00,1\n";
22609        let opts = CsvReadOptions {
22610            parse_date_combinations_named: Some(vec![(
22611                "ts".to_owned(),
22612                vec!["date".to_owned(), "missing".to_owned()],
22613            )]),
22614            ..Default::default()
22615        };
22616        let err = read_csv_with_options(input, &opts).unwrap_err();
22617        assert!(matches!(err, IoError::MissingParseDateColumns(_)));
22618    }
22619
22620    #[test]
22621    fn csv_parse_date_combinations_named_empty_sources_skipped() {
22622        let input = "a,b\n1,2\n";
22623        let opts = CsvReadOptions {
22624            parse_date_combinations_named: Some(vec![("unused".to_owned(), Vec::new())]),
22625            ..Default::default()
22626        };
22627        let frame = read_csv_with_options(input, &opts).expect("parse");
22628        // Empty source list is a no-op; original columns remain.
22629        assert_eq!(frame.column_names(), vec!["a", "b"]);
22630    }
22631
22632    // ── JSONL tests (frankenpandas-sue) ──────────────────────────────
22633
22634    #[test]
22635    fn jsonl_write_read_roundtrip() {
22636        let frame = make_test_dataframe();
22637        let jsonl = super::write_jsonl_string(&frame).expect("JSONL write failed");
22638
22639        // Each line should be a valid JSON object.
22640        let line_count = jsonl.lines().count();
22641        assert_eq!(line_count, 3, "3 rows = 3 lines");
22642
22643        let back = super::read_jsonl_str(&jsonl).expect("JSONL read failed");
22644        assert_eq!(back.index().len(), 3);
22645        assert_eq!(back.column("ints").unwrap().values()[0], Scalar::Int64(10));
22646        assert_eq!(
22647            back.column("names").unwrap().values()[2],
22648            Scalar::Utf8("carol".into())
22649        );
22650    }
22651
22652    #[test]
22653    fn jsonl_preserves_column_order() {
22654        let input = r#"
22655{"b":1,"a":2}
22656{"c":3}
22657"#;
22658        let frame = super::read_jsonl_str(input).expect("JSONL read failed");
22659        let order: Vec<&str> = frame
22660            .column_names()
22661            .iter()
22662            .map(|name| name.as_str())
22663            .collect();
22664        assert_eq!(order, vec!["b", "a", "c"]);
22665    }
22666
22667    #[test]
22668    fn jsonl_each_line_is_valid_json() {
22669        let frame = make_test_dataframe();
22670        let jsonl = super::write_jsonl_string(&frame).unwrap();
22671
22672        for (i, line) in jsonl.lines().enumerate() {
22673            let parsed: serde_json::Value =
22674                serde_json::from_str(line).expect("jsonl line must be valid JSON");
22675            assert!(parsed.is_object(), "line {i} must be a JSON object");
22676        }
22677    }
22678
22679    #[test]
22680    fn jsonl_with_nulls() {
22681        use fp_types::DType;
22682
22683        let mut columns = BTreeMap::new();
22684        columns.insert(
22685            "v".to_string(),
22686            Column::new(
22687                DType::Float64,
22688                vec![
22689                    Scalar::Float64(1.0),
22690                    Scalar::Null(NullKind::NaN),
22691                    Scalar::Float64(3.0),
22692                ],
22693            )
22694            .unwrap(),
22695        );
22696        let labels = vec![
22697            IndexLabel::Int64(0),
22698            IndexLabel::Int64(1),
22699            IndexLabel::Int64(2),
22700        ];
22701        let frame =
22702            DataFrame::new_with_column_order(Index::new(labels), columns, vec!["v".to_string()])
22703                .unwrap();
22704
22705        let jsonl = super::write_jsonl_string(&frame).unwrap();
22706        let back = super::read_jsonl_str(&jsonl).unwrap();
22707        assert!(back.column("v").unwrap().values()[1].is_missing());
22708    }
22709
22710    #[test]
22711    fn jsonl_records_write_preserves_nullable_int_column() {
22712        // DISC-011: Nullable extension Int64 dtype parity - Int64 preserved, not promoted to Float64.
22713        let frame = DataFrame::from_dict(
22714            &["a"],
22715            vec![("a", vec![Scalar::Int64(1), Scalar::Null(NullKind::Null)])],
22716        )
22717        .unwrap();
22718
22719        let jsonl = super::write_jsonl_string(&frame).expect("write jsonl");
22720        let rows = jsonl
22721            .lines()
22722            .map(|line| serde_json::from_str::<serde_json::Value>(line).unwrap())
22723            .collect::<Vec<_>>();
22724
22725        assert_eq!(
22726            rows,
22727            vec![serde_json::json!({"a": 1}), serde_json::json!({"a": null})]
22728        );
22729    }
22730
22731    #[test]
22732    fn jsonl_empty_input() {
22733        let back = super::read_jsonl_str("").expect("empty JSONL must parse");
22734        assert_eq!(back.index().len(), 0);
22735    }
22736
22737    #[test]
22738    fn jsonl_blank_lines_skipped() {
22739        let input = "{\"a\":1}\n\n{\"a\":2}\n\n";
22740        let back = super::read_jsonl_str(input).expect("JSONL with blanks must parse");
22741        assert_eq!(back.index().len(), 2);
22742    }
22743
22744    #[test]
22745    fn jsonl_non_object_line_errors() {
22746        let input = "{\"a\":1}\n[1,2,3]\n";
22747        let err = super::read_jsonl_str(input);
22748        assert!(err.is_err());
22749    }
22750
22751    #[test]
22752    fn jsonl_different_keys_across_rows() {
22753        // Rows with different keys should produce union of all columns.
22754        let input = "{\"a\":1,\"b\":2}\n{\"a\":3,\"c\":4}\n";
22755        let frame = super::read_jsonl_str(input).expect("JSONL with different keys must parse");
22756        assert_eq!(frame.index().len(), 2);
22757        // Should have columns a, b, c (union of all keys).
22758        assert!(frame.column("a").is_some(), "column a must exist");
22759        assert!(frame.column("b").is_some(), "column b must exist");
22760        assert!(frame.column("c").is_some(), "column c must exist");
22761        // Row 0: a=1, b=2, c=null.
22762        assert_eq!(frame.column("a").unwrap().values()[0], Scalar::Int64(1));
22763        assert_eq!(frame.column("b").unwrap().values()[0], Scalar::Float64(2.0));
22764        assert!(frame.column("c").unwrap().values()[0].is_missing());
22765        // Row 1: a=3, b=null, c=4.
22766        assert_eq!(frame.column("a").unwrap().values()[1], Scalar::Int64(3));
22767        assert!(frame.column("b").unwrap().values()[1].is_missing());
22768        assert_eq!(frame.column("c").unwrap().values()[1], Scalar::Float64(4.0));
22769    }
22770
22771    #[test]
22772    fn adversarial_csv_very_long_field() {
22773        // A single field with >100K characters should parse without panic.
22774        let long_val = "x".repeat(200_000);
22775        let input = format!("col\n{long_val}\n");
22776        let frame = read_csv_str(&input).expect("long field must parse");
22777        assert_eq!(frame.index().len(), 1);
22778        match &frame.column("col").unwrap().values()[0] {
22779            Scalar::Utf8(s) => assert_eq!(s.len(), 200_000),
22780            other => assert!(
22781                matches!(other, Scalar::Utf8(_)),
22782                "expected Utf8 for long field"
22783            ),
22784        }
22785    }
22786
22787    #[test]
22788    fn adversarial_csv_many_columns() {
22789        // CSV with 1000 columns should parse correctly.
22790        let ncols = 1000;
22791        let headers: Vec<String> = (0..ncols).map(|i| format!("c{i}")).collect();
22792        let mut csv = headers.join(",");
22793        csv.push('\n');
22794        let vals: Vec<String> = (0..ncols).map(|i| i.to_string()).collect();
22795        csv.push_str(&vals.join(","));
22796        csv.push('\n');
22797
22798        let frame = read_csv_str(&csv).expect("1000-column CSV must parse");
22799        assert_eq!(frame.columns().len(), ncols);
22800        assert_eq!(frame.index().len(), 1);
22801    }
22802
22803    #[test]
22804    fn adversarial_csv_empty_rows() {
22805        // CSV with empty rows between data should handle gracefully.
22806        // The csv crate skips truly empty records, but rows with the right
22807        // number of empty fields produce null values.
22808        let input = "a,b\n1,2\n,\n3,4\n";
22809        let frame = read_csv_str(input).expect("parse");
22810        assert_eq!(frame.index().len(), 3);
22811        // Row 1 (index 1) has empty fields → null
22812        assert!(frame.column("a").unwrap().values()[1].is_missing());
22813    }
22814
22815    #[test]
22816    fn adversarial_csv_field_with_newlines_in_quotes() {
22817        // Embedded newlines in quoted fields must not break row boundaries.
22818        let input = "msg\n\"line1\nline2\nline3\"\n\"single\"\n";
22819        let frame = read_csv_str(input).expect("quoted newlines must parse");
22820        assert_eq!(frame.index().len(), 2);
22821    }
22822
22823    #[test]
22824    fn adversarial_csv_header_only_no_data() {
22825        let input = "x,y,z\n";
22826        let frame = read_csv_str(input).expect("header-only must parse");
22827        assert_eq!(frame.index().len(), 0);
22828        assert_eq!(frame.columns().len(), 3);
22829    }
22830
22831    #[test]
22832    fn adversarial_json_deeply_nested_values() {
22833        // JSON with nested objects as values should store them as strings.
22834        let input = r#"[{"a":1,"b":{"nested":"value"}}]"#;
22835        let frame = read_json_str(input, JsonOrient::Records).expect("nested JSON must parse");
22836        assert_eq!(frame.index().len(), 1);
22837        // The nested object becomes a Utf8 representation.
22838        let b_val = &frame.column("b").unwrap().values()[0];
22839        assert!(matches!(b_val, Scalar::Utf8(_)));
22840    }
22841
22842    #[test]
22843    fn adversarial_json_i64_max_value() {
22844        // JSON with values at i64 boundary.
22845        let input = format!(r#"[{{"v":{}}}]"#, i64::MAX);
22846        let frame = read_json_str(&input, JsonOrient::Records).expect("i64::MAX must parse");
22847        assert_eq!(
22848            frame.column("v").unwrap().values()[0],
22849            Scalar::Int64(i64::MAX)
22850        );
22851    }
22852
22853    #[test]
22854    fn adversarial_json_i64_min_value() {
22855        let input = format!(r#"[{{"v":{}}}]"#, i64::MIN);
22856        let frame = read_json_str(&input, JsonOrient::Records).expect("i64::MIN must parse");
22857        assert_eq!(
22858            frame.column("v").unwrap().values()[0],
22859            Scalar::Int64(i64::MIN)
22860        );
22861    }
22862
22863    #[test]
22864    fn adversarial_json_float_special_values() {
22865        // JSON doesn't natively support Infinity/NaN, but we should handle
22866        // null gracefully.
22867        let input = r#"[{"v":null},{"v":1.7976931348623157e+308}]"#;
22868        let frame = read_json_str(input, JsonOrient::Records).expect("special floats must parse");
22869        assert!(frame.column("v").unwrap().values()[0].is_missing());
22870        // f64::MAX is approximately 1.7976931348623157e+308
22871        if let Scalar::Float64(v) = frame.column("v").unwrap().values()[1] {
22872            assert!(v.is_finite());
22873        }
22874    }
22875
22876    #[test]
22877    fn adversarial_json_empty_records_array() {
22878        let input = r#"[]"#;
22879        let frame = read_json_str(input, JsonOrient::Records).expect("empty array must parse");
22880        assert_eq!(frame.index().len(), 0);
22881    }
22882
22883    #[test]
22884    fn adversarial_json_empty_columns_object() {
22885        let input = r#"{}"#;
22886        let frame = read_json_str(input, JsonOrient::Columns).expect("empty object must parse");
22887        assert_eq!(frame.index().len(), 0);
22888        assert_eq!(frame.columns().len(), 0);
22889    }
22890
22891    #[test]
22892    fn adversarial_csv_unicode_values() {
22893        // CSV with multi-byte UTF-8 characters in values.
22894        let input = "name,emoji\n日本語,🎉\nрусский,🚀\n";
22895        let frame = read_csv_str(input).expect("unicode CSV must parse");
22896        assert_eq!(frame.index().len(), 2);
22897        assert_eq!(
22898            frame.column("name").unwrap().values()[0],
22899            Scalar::Utf8("日本語".into())
22900        );
22901        assert_eq!(
22902            frame.column("emoji").unwrap().values()[1],
22903            Scalar::Utf8("🚀".into())
22904        );
22905    }
22906
22907    #[test]
22908    fn adversarial_csv_single_column_no_trailing_newline() {
22909        let input = "val\n42";
22910        let frame = read_csv_str(input).expect("no trailing newline must parse");
22911        assert_eq!(frame.index().len(), 1);
22912        assert_eq!(frame.column("val").unwrap().values()[0], Scalar::Int64(42));
22913    }
22914
22915    #[cfg(feature = "sql-sqlite")]
22916    #[test]
22917    fn adversarial_sql_large_batch_insert() {
22918        // Insert 10K rows in a single write_sql call.
22919        let n = 10_000;
22920        let vals: Vec<Scalar> = (0..n).map(|i| Scalar::Int64(i as i64)).collect();
22921        let df = fp_frame::DataFrame::from_dict(&["x"], vec![("x", vals)]).unwrap();
22922
22923        let conn = make_sql_test_conn();
22924        write_sql(&df, &conn, "big_table", SqlIfExists::Fail).unwrap();
22925        let back = read_sql_table(&conn, "big_table").unwrap();
22926        assert_eq!(back.index().len(), n);
22927        assert_eq!(
22928            back.column("x").unwrap().values()[n - 1],
22929            Scalar::Int64((n - 1) as i64)
22930        );
22931    }
22932
22933    #[cfg(feature = "sql-sqlite")]
22934    #[test]
22935    fn adversarial_sql_column_name_with_spaces_accepted() {
22936        // Column names with spaces are valid in SQL (quoted identifiers).
22937        // Table names are restricted, but column names go through quoting.
22938        let df = fp_frame::DataFrame::from_dict(
22939            &["has space"],
22940            vec![("has space", vec![Scalar::Int64(1)])],
22941        )
22942        .unwrap();
22943
22944        let conn = make_sql_test_conn();
22945        // This should work since column names are quoted.
22946        let result = write_sql(&df, &conn, "test_spaces", SqlIfExists::Fail);
22947        assert!(
22948            result.is_ok(),
22949            "columns with spaces should work: {:?}",
22950            result.err()
22951        );
22952
22953        let back = read_sql_table(&conn, "test_spaces").unwrap();
22954        assert!(back.column("has space").is_some());
22955    }
22956
22957    #[cfg(feature = "sql-sqlite")]
22958    #[test]
22959    fn adversarial_sql_column_name_with_quotes_accepted() {
22960        let col_name = "has\"quote";
22961        let df =
22962            fp_frame::DataFrame::from_dict(&[col_name], vec![(col_name, vec![Scalar::Int64(7)])])
22963                .unwrap();
22964
22965        let conn = make_sql_test_conn();
22966        let result = write_sql(&df, &conn, "test_quotes", SqlIfExists::Fail);
22967        assert!(
22968            result.is_ok(),
22969            "columns with quotes should work: {:?}",
22970            result.err()
22971        );
22972
22973        let back = read_sql_table(&conn, "test_quotes").unwrap();
22974        assert_eq!(back.column(col_name).unwrap().values()[0], Scalar::Int64(7));
22975    }
22976
22977    // ── SqlConnection capability + dialect probes (br-frankenpandas-6dtf) ────
22978
22979    #[cfg(feature = "sql-sqlite")]
22980    #[test]
22981    fn rusqlite_dialect_name_is_sqlite() {
22982        let conn = make_sql_test_conn();
22983        assert_eq!(super::SqlConnection::dialect_name(&conn), "sqlite");
22984    }
22985
22986    #[cfg(feature = "sql-sqlite")]
22987    #[test]
22988    fn rusqlite_supports_returning_is_true() {
22989        // Bundled SQLite is 3.35+, so RETURNING is supported.
22990        let conn = make_sql_test_conn();
22991        assert!(super::SqlConnection::supports_returning(&conn));
22992    }
22993
22994    #[cfg(feature = "sql-sqlite")]
22995    #[test]
22996    fn rusqlite_max_param_count_is_32766() {
22997        let conn = make_sql_test_conn();
22998        assert_eq!(super::SqlConnection::max_param_count(&conn), Some(32766));
22999    }
23000
23001    #[cfg(feature = "sql-sqlite")]
23002    #[test]
23003    fn rusqlite_with_transaction_commits_on_ok() {
23004        let conn = make_sql_test_conn();
23005        super::SqlConnection::execute_batch(&conn, "CREATE TABLE txn_test (x INTEGER)").unwrap();
23006        let result: Result<i64, IoError> = super::SqlConnection::with_transaction(&conn, |c| {
23007            super::SqlConnection::execute_batch(c, "INSERT INTO txn_test VALUES (42)")?;
23008            Ok(42)
23009        });
23010        assert_eq!(result.unwrap(), 42);
23011        // Verify the row committed.
23012        let row_count =
23013            super::SqlConnection::query(&conn, "SELECT COUNT(*) FROM txn_test", &[]).unwrap();
23014        assert_eq!(row_count.rows.len(), 1);
23015        assert_eq!(row_count.rows[0][0], Scalar::Int64(1));
23016    }
23017
23018    #[cfg(feature = "sql-sqlite")]
23019    #[test]
23020    fn rusqlite_with_transaction_rolls_back_on_err() {
23021        let conn = make_sql_test_conn();
23022        super::SqlConnection::execute_batch(&conn, "CREATE TABLE txn_rollback (x INTEGER)")
23023            .unwrap();
23024        let result: Result<(), IoError> = super::SqlConnection::with_transaction(&conn, |c| {
23025            super::SqlConnection::execute_batch(c, "INSERT INTO txn_rollback VALUES (99)")?;
23026            Err(IoError::Sql("simulated failure".to_string()))
23027        });
23028        assert!(result.is_err());
23029        // Row should NOT have committed.
23030        let row_count =
23031            super::SqlConnection::query(&conn, "SELECT COUNT(*) FROM txn_rollback", &[]).unwrap();
23032        assert_eq!(row_count.rows[0][0], Scalar::Int64(0));
23033    }
23034
23035    #[cfg(feature = "sql-sqlite")]
23036    #[test]
23037    fn rusqlite_with_transaction_rolls_back_on_panic() {
23038        let conn = make_sql_test_conn();
23039        super::SqlConnection::execute_batch(&conn, "CREATE TABLE txn_panic (x INTEGER)").unwrap();
23040
23041        let panic_result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
23042            let _: Result<(), IoError> = super::SqlConnection::with_transaction(&conn, |c| {
23043                super::SqlConnection::execute_batch(c, "INSERT INTO txn_panic VALUES (99)")?;
23044                std::panic::resume_unwind(Box::new("simulated transaction panic"));
23045            });
23046        }));
23047        assert!(panic_result.is_err());
23048
23049        let row_count =
23050            super::SqlConnection::query(&conn, "SELECT COUNT(*) FROM txn_panic", &[]).unwrap();
23051        assert_eq!(row_count.rows[0][0], Scalar::Int64(0));
23052
23053        let result: Result<(), IoError> = super::SqlConnection::with_transaction(&conn, |c| {
23054            super::SqlConnection::execute_batch(c, "INSERT INTO txn_panic VALUES (7)")
23055        });
23056        assert!(result.is_ok());
23057        let rows =
23058            super::SqlConnection::query(&conn, "SELECT x FROM txn_panic ORDER BY x", &[]).unwrap();
23059        assert_eq!(rows.rows, vec![vec![Scalar::Int64(7)]]);
23060    }
23061
23062    #[test]
23063    fn default_capability_probes_are_conservative() {
23064        // A test-double SqlConnection that doesn't override defaults
23065        // should report the conservative-default values from the trait.
23066        struct StubSql;
23067        impl super::SqlConnection for StubSql {
23068            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<super::SqlQueryResult, IoError> {
23069                Ok(super::SqlQueryResult {
23070                    columns: vec![],
23071                    rows: vec![],
23072                })
23073            }
23074            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
23075                Ok(())
23076            }
23077            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
23078                Ok(false)
23079            }
23080            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
23081                Ok(())
23082            }
23083            fn dtype_sql(&self, _dtype: DType) -> &'static str {
23084                "TEXT"
23085            }
23086            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
23087                "TEXT"
23088            }
23089        }
23090
23091        let stub = StubSql;
23092        assert_eq!(super::SqlConnection::dialect_name(&stub), "unknown");
23093        assert!(!super::SqlConnection::supports_returning(&stub));
23094        assert_eq!(super::SqlConnection::max_param_count(&stub), None);
23095        // Default with_transaction passes through (no BEGIN/COMMIT).
23096        let result: Result<i64, IoError> = super::SqlConnection::with_transaction(&stub, |_| Ok(7));
23097        assert_eq!(result.unwrap(), 7);
23098        // Default quote_identifier produces ANSI double-quotes.
23099        assert_eq!(
23100            super::SqlConnection::quote_identifier(&stub, "col").unwrap(),
23101            r#""col""#
23102        );
23103    }
23104
23105    // ── quote_identifier tests (br-frankenpandas-2y7w / fd90.10) ────────
23106
23107    #[cfg(feature = "sql-sqlite")]
23108    #[test]
23109    fn rusqlite_quote_identifier_uses_ansi_double_quotes() {
23110        let conn = make_sql_test_conn();
23111        assert_eq!(
23112            super::SqlConnection::quote_identifier(&conn, "users").unwrap(),
23113            r#""users""#
23114        );
23115    }
23116
23117    #[cfg(feature = "sql-sqlite")]
23118    #[test]
23119    fn rusqlite_quote_identifier_doubles_embedded_quotes() {
23120        let conn = make_sql_test_conn();
23121        // Identifier containing a `"` must be escaped by doubling the quote.
23122        assert_eq!(
23123            super::SqlConnection::quote_identifier(&conn, r#"value"raw"#).unwrap(),
23124            r#""value""raw""#
23125        );
23126    }
23127
23128    #[cfg(feature = "sql-sqlite")]
23129    #[test]
23130    fn rusqlite_quote_identifier_rejects_null_bytes() {
23131        let conn = make_sql_test_conn();
23132        let err = super::SqlConnection::quote_identifier(&conn, "evil\0name").expect_err("nul");
23133        assert!(matches!(err, IoError::Sql(_)));
23134    }
23135
23136    #[test]
23137    fn default_quote_identifier_doubles_embedded_quotes() {
23138        // Verify the default impl on a non-overriding stub matches the
23139        // SQLite behavior (ANSI is the shared default for SQLite + Postgres).
23140        struct StubSql;
23141        impl super::SqlConnection for StubSql {
23142            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<super::SqlQueryResult, IoError> {
23143                Ok(super::SqlQueryResult {
23144                    columns: vec![],
23145                    rows: vec![],
23146                })
23147            }
23148            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
23149                Ok(())
23150            }
23151            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
23152                Ok(false)
23153            }
23154            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
23155                Ok(())
23156            }
23157            fn dtype_sql(&self, _dtype: DType) -> &'static str {
23158                "TEXT"
23159            }
23160            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
23161                "TEXT"
23162            }
23163        }
23164        let stub = StubSql;
23165        assert_eq!(
23166            super::SqlConnection::quote_identifier(&stub, r#"value"raw"#).unwrap(),
23167            r#""value""raw""#
23168        );
23169        assert!(super::SqlConnection::quote_identifier(&stub, "evil\0").is_err());
23170    }
23171
23172    // ── SqlReadOptions::dtype tests (br-frankenpandas-l9pt / fd90.11) ───
23173
23174    #[cfg(feature = "sql-sqlite")]
23175    #[test]
23176    fn read_sql_dtype_override_int_to_float() {
23177        let conn = make_sql_test_conn();
23178        super::SqlConnection::execute_batch(
23179            &conn,
23180            "CREATE TABLE amounts (amount INTEGER); INSERT INTO amounts VALUES (1), (2), (3);",
23181        )
23182        .unwrap();
23183        let mut dtype_map = BTreeMap::new();
23184        dtype_map.insert("amount".to_owned(), DType::Float64);
23185        let frame = read_sql_with_options(
23186            &conn,
23187            "SELECT amount FROM amounts ORDER BY amount",
23188            &SqlReadOptions {
23189                params: None,
23190                parse_dates: None,
23191                coerce_float: false,
23192                dtype: Some(dtype_map),
23193                schema: None,
23194                columns: None,
23195                index_col: None,
23196            },
23197        )
23198        .expect("read with dtype");
23199        let col = frame.column("amount").expect("amount");
23200        assert_eq!(col.dtype(), DType::Float64);
23201        assert_eq!(col.values()[0], Scalar::Float64(1.0));
23202        assert_eq!(col.values()[2], Scalar::Float64(3.0));
23203    }
23204
23205    #[cfg(feature = "sql-sqlite")]
23206    #[test]
23207    fn read_sql_dtype_override_unsupported_cast_returns_typed_error() {
23208        // This test asserts that when a dtype override cast is unsupported,
23209        // SQL IO surfaces a typed IoError::Sql with diagnostic context, NOT a
23210        // panic and not a silent skip.
23211        let conn = make_sql_test_conn();
23212        super::SqlConnection::execute_batch(
23213            &conn,
23214            "CREATE TABLE labels (id TEXT); INSERT INTO labels VALUES ('yes'), ('no');",
23215        )
23216        .unwrap();
23217        let mut dtype_map = BTreeMap::new();
23218        dtype_map.insert("id".to_owned(), DType::Bool);
23219        let err = read_sql_with_options(
23220            &conn,
23221            "SELECT id FROM labels ORDER BY id",
23222            &SqlReadOptions {
23223                params: None,
23224                parse_dates: None,
23225                coerce_float: false,
23226                dtype: Some(dtype_map),
23227                schema: None,
23228                columns: None,
23229                index_col: None,
23230            },
23231        )
23232        .expect_err("expected dtype override error");
23233        match err {
23234            IoError::Sql(message) => {
23235                assert!(
23236                    message.contains("dtype override on column 'id'"),
23237                    "unexpected error message: {message}"
23238                );
23239                assert!(
23240                    message.contains("Bool"),
23241                    "unexpected error message: {message}"
23242                );
23243            }
23244            other => unreachable!("expected IoError::Sql, got {other:?}"),
23245        }
23246    }
23247
23248    #[cfg(feature = "sql-sqlite")]
23249    #[test]
23250    fn read_sql_dtype_override_missing_column_is_ignored() {
23251        let conn = make_sql_test_conn();
23252        super::SqlConnection::execute_batch(
23253            &conn,
23254            "CREATE TABLE t (x INTEGER); INSERT INTO t VALUES (1);",
23255        )
23256        .unwrap();
23257        let mut dtype_map = BTreeMap::new();
23258        dtype_map.insert("nonexistent".to_owned(), DType::Float64);
23259        let frame = read_sql_with_options(
23260            &conn,
23261            "SELECT x FROM t",
23262            &SqlReadOptions {
23263                params: None,
23264                parse_dates: None,
23265                coerce_float: false,
23266                dtype: Some(dtype_map),
23267                schema: None,
23268                columns: None,
23269                index_col: None,
23270            },
23271        )
23272        .expect("read with dtype-on-missing-col");
23273        let col = frame.column("x").expect("x");
23274        assert_eq!(col.dtype(), DType::Int64);
23275    }
23276
23277    #[cfg(feature = "sql-sqlite")]
23278    #[test]
23279    fn read_sql_dtype_override_preserves_nulls() {
23280        let conn = make_sql_test_conn();
23281        super::SqlConnection::execute_batch(
23282            &conn,
23283            "CREATE TABLE nulls_tbl (v INTEGER); INSERT INTO nulls_tbl VALUES (1), (NULL), (3);",
23284        )
23285        .unwrap();
23286        let mut dtype_map = BTreeMap::new();
23287        dtype_map.insert("v".to_owned(), DType::Float64);
23288        let frame = read_sql_with_options(
23289            &conn,
23290            "SELECT v FROM nulls_tbl ORDER BY rowid",
23291            &SqlReadOptions {
23292                params: None,
23293                parse_dates: None,
23294                coerce_float: false,
23295                dtype: Some(dtype_map),
23296                schema: None,
23297                columns: None,
23298                index_col: None,
23299            },
23300        )
23301        .expect("read with dtype + nulls");
23302        let col = frame.column("v").expect("v");
23303        assert_eq!(col.dtype(), DType::Float64);
23304        assert!(col.values()[1].is_missing());
23305    }
23306
23307    #[cfg(feature = "sql-sqlite")]
23308    #[test]
23309    fn read_sql_dtype_skipped_when_column_in_parse_dates() {
23310        let conn = make_sql_test_conn();
23311        super::SqlConnection::execute_batch(
23312            &conn,
23313            "CREATE TABLE evt (ts TEXT); INSERT INTO evt VALUES ('2024-01-01 00:00:00');",
23314        )
23315        .unwrap();
23316        let mut dtype_map = BTreeMap::new();
23317        dtype_map.insert("ts".to_owned(), DType::Float64);
23318        let frame = read_sql_with_options(
23319            &conn,
23320            "SELECT ts FROM evt",
23321            &SqlReadOptions {
23322                params: None,
23323                parse_dates: Some(vec!["ts".to_owned()]),
23324                coerce_float: false,
23325                dtype: Some(dtype_map),
23326                schema: None,
23327                columns: None,
23328                index_col: None,
23329            },
23330        )
23331        .expect("read with parse_dates priority");
23332        let col = frame.column("ts").expect("ts");
23333        // parse_dates wins over the dtype override and yields typed
23334        // Datetime64[ns] (br-frankenpandas-0ezw7).
23335        assert_eq!(col.dtype(), DType::Datetime64);
23336    }
23337
23338    // ── Schema probes (br-frankenpandas-6dk9 / fd90.13) ─────────────────
23339
23340    #[cfg(feature = "sql-sqlite")]
23341    #[test]
23342    fn rusqlite_does_not_support_schemas_by_default() {
23343        let conn = make_sql_test_conn();
23344        assert!(!super::SqlConnection::supports_schemas(&conn));
23345        assert_eq!(super::SqlConnection::default_schema(&conn), None);
23346    }
23347
23348    #[test]
23349    fn default_schema_probes_are_conservative() {
23350        // A test-double with no schema overrides reports the conservative
23351        // single-namespace defaults (matches SQLite + most embedded
23352        // backends). Production multi-schema backends (PG, MySQL) override.
23353        struct StubSql;
23354        impl super::SqlConnection for StubSql {
23355            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<super::SqlQueryResult, IoError> {
23356                Ok(super::SqlQueryResult {
23357                    columns: vec![],
23358                    rows: vec![],
23359                })
23360            }
23361            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
23362                Ok(())
23363            }
23364            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
23365                Ok(false)
23366            }
23367            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
23368                Ok(())
23369            }
23370            fn dtype_sql(&self, _dtype: DType) -> &'static str {
23371                "TEXT"
23372            }
23373            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
23374                "TEXT"
23375            }
23376        }
23377        let stub = StubSql;
23378        assert!(!super::SqlConnection::supports_schemas(&stub));
23379        assert_eq!(super::SqlConnection::default_schema(&stub), None);
23380    }
23381
23382    #[test]
23383    fn schema_probe_overrides_take_effect() {
23384        // A multi-schema-style test backend (e.g. simulating PostgreSQL)
23385        // overrides supports_schemas + default_schema. The overrides MUST
23386        // win over the trait defaults.
23387        struct PgLikeSqlConn;
23388        impl super::SqlConnection for PgLikeSqlConn {
23389            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<super::SqlQueryResult, IoError> {
23390                Ok(super::SqlQueryResult {
23391                    columns: vec![],
23392                    rows: vec![],
23393                })
23394            }
23395            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
23396                Ok(())
23397            }
23398            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
23399                Ok(false)
23400            }
23401            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
23402                Ok(())
23403            }
23404            fn dtype_sql(&self, _dtype: DType) -> &'static str {
23405                "TEXT"
23406            }
23407            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
23408                "TEXT"
23409            }
23410            fn supports_schemas(&self) -> bool {
23411                true
23412            }
23413            fn default_schema(&self) -> Option<String> {
23414                Some("public".to_owned())
23415            }
23416        }
23417        let conn = PgLikeSqlConn;
23418        assert!(super::SqlConnection::supports_schemas(&conn));
23419        assert_eq!(
23420            super::SqlConnection::default_schema(&conn).as_deref(),
23421            Some("public")
23422        );
23423    }
23424
23425    // ── SqlReadOptions::schema tests (br-frankenpandas-u6zn / fd90.14) ──
23426
23427    #[test]
23428    fn sql_select_all_query_no_schema_uses_bare_table() {
23429        struct StubSql;
23430        impl super::SqlConnection for StubSql {
23431            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<super::SqlQueryResult, IoError> {
23432                Ok(super::SqlQueryResult {
23433                    columns: vec![],
23434                    rows: vec![],
23435                })
23436            }
23437            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
23438                Ok(())
23439            }
23440            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
23441                Ok(false)
23442            }
23443            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
23444                Ok(())
23445            }
23446            fn dtype_sql(&self, _dtype: DType) -> &'static str {
23447                "TEXT"
23448            }
23449            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
23450                "TEXT"
23451            }
23452        }
23453        let conn = StubSql;
23454        let q1 = super::sql_select_all_query_in_schema(&conn, "users", None).expect("q1");
23455        assert_eq!(q1, "SELECT * FROM \"users\"");
23456    }
23457
23458    #[test]
23459    fn sql_select_query_with_schema_rejects_non_schema_backend() {
23460        struct StubSql;
23461        impl super::SqlConnection for StubSql {
23462            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<super::SqlQueryResult, IoError> {
23463                Ok(super::SqlQueryResult {
23464                    columns: vec![],
23465                    rows: vec![],
23466                })
23467            }
23468            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
23469                Ok(())
23470            }
23471            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
23472                Ok(false)
23473            }
23474            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
23475                Ok(())
23476            }
23477            fn dtype_sql(&self, _dtype: DType) -> &'static str {
23478                "TEXT"
23479            }
23480            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
23481                "TEXT"
23482            }
23483            fn dialect_name(&self) -> &'static str {
23484                "stub"
23485            }
23486        }
23487        let conn = StubSql;
23488        let err = super::sql_select_all_query_in_schema(&conn, "users", Some("analytics"))
23489            .expect_err("schema must reject when backend has no schema support");
23490        assert!(
23491            matches!(err, IoError::Sql(msg) if msg.contains("schema is not supported by stub backend"))
23492        );
23493
23494        let err =
23495            super::sql_select_columns_query_in_schema(&conn, "users", Some("analytics"), &["id"])
23496                .expect_err("projected schema select must reject too");
23497        assert!(
23498            matches!(err, IoError::Sql(msg) if msg.contains("schema is not supported by stub backend"))
23499        );
23500    }
23501
23502    #[test]
23503    fn sql_select_all_query_with_schema_qualifies_on_multi_schema_backend() {
23504        struct PgLikeSchemaSql;
23505        impl super::SqlConnection for PgLikeSchemaSql {
23506            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<super::SqlQueryResult, IoError> {
23507                Ok(super::SqlQueryResult {
23508                    columns: vec![],
23509                    rows: vec![],
23510                })
23511            }
23512            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
23513                Ok(())
23514            }
23515            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
23516                Ok(false)
23517            }
23518            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
23519                Ok(())
23520            }
23521            fn dtype_sql(&self, _dtype: DType) -> &'static str {
23522                "TEXT"
23523            }
23524            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
23525                "TEXT"
23526            }
23527            fn supports_schemas(&self) -> bool {
23528                true
23529            }
23530        }
23531        let conn = PgLikeSchemaSql;
23532        let q =
23533            super::sql_select_all_query_in_schema(&conn, "users", Some("analytics")).expect("q");
23534        assert_eq!(q, "SELECT * FROM \"analytics\".\"users\"");
23535        let bare = super::sql_select_all_query_in_schema(&conn, "users", None).expect("bare");
23536        assert_eq!(bare, "SELECT * FROM \"users\"");
23537    }
23538
23539    #[cfg(feature = "sql-sqlite")]
23540    #[test]
23541    fn read_sql_table_with_options_schema_rejected_on_sqlite() {
23542        let conn = make_sql_test_conn();
23543        super::SqlConnection::execute_batch(
23544            &conn,
23545            "CREATE TABLE bare_tbl (x INTEGER); INSERT INTO bare_tbl VALUES (1), (2);",
23546        )
23547        .unwrap();
23548        let err = read_sql_table_with_options(
23549            &conn,
23550            "bare_tbl",
23551            &SqlReadOptions {
23552                params: None,
23553                parse_dates: None,
23554                coerce_float: false,
23555                dtype: None,
23556                schema: Some("ignored_on_sqlite".to_owned()),
23557                columns: None,
23558                index_col: None,
23559            },
23560        )
23561        .expect_err("read_sql_table schema=Some must reject on SQLite");
23562        assert!(
23563            matches!(err, IoError::Sql(msg) if msg.contains("schema is not supported by sqlite backend"))
23564        );
23565    }
23566
23567    #[cfg(feature = "sql-sqlite")]
23568    #[test]
23569    fn read_sql_table_chunks_with_options_schema_rejected_on_sqlite() {
23570        let conn = make_sql_test_conn();
23571        super::SqlConnection::execute_batch(
23572            &conn,
23573            "CREATE TABLE chunk_bare_tbl (x INTEGER); INSERT INTO chunk_bare_tbl VALUES (1), (2);",
23574        )
23575        .unwrap();
23576        let err = read_sql_table_chunks_with_options(
23577            &conn,
23578            "chunk_bare_tbl",
23579            &SqlReadOptions {
23580                schema: Some("ignored_on_sqlite".to_owned()),
23581                ..Default::default()
23582            },
23583            1,
23584        )
23585        .expect_err("chunked read_sql_table schema=Some must reject on SQLite");
23586        assert!(
23587            matches!(err, IoError::Sql(msg) if msg.contains("schema is not supported by sqlite backend"))
23588        );
23589    }
23590
23591    #[test]
23592    fn sql_select_all_query_in_schema_validates_schema_name() {
23593        struct PgLikeValidate;
23594        impl super::SqlConnection for PgLikeValidate {
23595            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<super::SqlQueryResult, IoError> {
23596                Ok(super::SqlQueryResult {
23597                    columns: vec![],
23598                    rows: vec![],
23599                })
23600            }
23601            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
23602                Ok(())
23603            }
23604            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
23605                Ok(false)
23606            }
23607            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
23608                Ok(())
23609            }
23610            fn dtype_sql(&self, _dtype: DType) -> &'static str {
23611                "TEXT"
23612            }
23613            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
23614                "TEXT"
23615            }
23616            fn supports_schemas(&self) -> bool {
23617                true
23618            }
23619        }
23620        let conn = PgLikeValidate;
23621        let err = super::sql_select_all_query_in_schema(&conn, "users", Some("evil; DROP"))
23622            .expect_err("malformed schema must reject");
23623        // Per fd90.56: error message now correctly identifies the
23624        // bad identifier as a schema, not a table.
23625        assert!(matches!(err, IoError::Sql(msg) if msg.contains("invalid schema name")));
23626    }
23627
23628    // ── SqlWriteOptions::schema tests (br-frankenpandas-udn6 / fd90.15) ─
23629
23630    #[test]
23631    fn sql_create_table_query_in_schema_qualifies_on_multi_schema_backend() {
23632        struct PgLikeWrite;
23633        impl super::SqlConnection for PgLikeWrite {
23634            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<super::SqlQueryResult, IoError> {
23635                Ok(super::SqlQueryResult {
23636                    columns: vec![],
23637                    rows: vec![],
23638                })
23639            }
23640            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
23641                Ok(())
23642            }
23643            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
23644                Ok(false)
23645            }
23646            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
23647                Ok(())
23648            }
23649            fn dtype_sql(&self, _dtype: DType) -> &'static str {
23650                "TEXT"
23651            }
23652            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
23653                "TEXT"
23654            }
23655            fn supports_schemas(&self) -> bool {
23656                true
23657            }
23658        }
23659        let conn = PgLikeWrite;
23660        let cols = vec!["id INTEGER".to_owned(), "name TEXT".to_owned()];
23661        let q = super::sql_create_table_query_in_schema(&conn, "users", Some("analytics"), &cols)
23662            .expect("create");
23663        assert_eq!(
23664            q,
23665            "CREATE TABLE IF NOT EXISTS \"analytics\".\"users\" (id INTEGER, name TEXT)"
23666        );
23667        let bare =
23668            super::sql_create_table_query_in_schema(&conn, "users", None, &cols).expect("bare");
23669        assert_eq!(
23670            bare,
23671            "CREATE TABLE IF NOT EXISTS \"users\" (id INTEGER, name TEXT)"
23672        );
23673    }
23674
23675    #[test]
23676    fn sql_insert_rows_query_in_schema_qualifies_on_multi_schema_backend() {
23677        struct PgLikeInsert;
23678        impl super::SqlConnection for PgLikeInsert {
23679            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<super::SqlQueryResult, IoError> {
23680                Ok(super::SqlQueryResult {
23681                    columns: vec![],
23682                    rows: vec![],
23683                })
23684            }
23685            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
23686                Ok(())
23687            }
23688            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
23689                Ok(false)
23690            }
23691            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
23692                Ok(())
23693            }
23694            fn dtype_sql(&self, _dtype: DType) -> &'static str {
23695                "TEXT"
23696            }
23697            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
23698                "TEXT"
23699            }
23700            fn supports_schemas(&self) -> bool {
23701                true
23702            }
23703        }
23704        let conn = PgLikeInsert;
23705        let cols = vec!["id".to_owned(), "name".to_owned()];
23706        let q = super::sql_insert_rows_query_in_schema(&conn, "users", Some("analytics"), &cols)
23707            .expect("insert");
23708        assert_eq!(
23709            q,
23710            "INSERT INTO \"analytics\".\"users\" (\"id\", \"name\") VALUES (?, ?)"
23711        );
23712    }
23713
23714    #[cfg(feature = "sql-sqlite")]
23715    #[test]
23716    fn write_sql_with_options_schema_silently_ignored_on_sqlite() {
23717        let conn = make_sql_test_conn();
23718        let frame = fp_frame::DataFrame::from_dict(
23719            &["x"],
23720            vec![("x", vec![Scalar::Int64(1), Scalar::Int64(2)])],
23721        )
23722        .unwrap();
23723        // SQLite reports supports_schemas=false; passing schema=Some(s) must
23724        // not break the write — the bare table reference is used.
23725        write_sql_with_options(
23726            &frame,
23727            &conn,
23728            "bare_write_tbl",
23729            &SqlWriteOptions {
23730                if_exists: SqlIfExists::Fail,
23731                index: false,
23732                index_label: None,
23733                schema: Some("ignored_on_sqlite".to_owned()),
23734                dtype: None,
23735                method: SqlInsertMethod::Single,
23736                chunksize: None,
23737            },
23738        )
23739        .expect("write with schema=Some on SQLite");
23740        let back = read_sql_table(&conn, "bare_write_tbl").expect("read");
23741        let col = back.column("x").expect("x");
23742        assert_eq!(col.values()[0], Scalar::Int64(1));
23743        assert_eq!(col.values()[1], Scalar::Int64(2));
23744    }
23745
23746    #[test]
23747    fn sql_create_table_query_in_schema_validates_schema_name() {
23748        struct PgLikeValidate;
23749        impl super::SqlConnection for PgLikeValidate {
23750            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<super::SqlQueryResult, IoError> {
23751                Ok(super::SqlQueryResult {
23752                    columns: vec![],
23753                    rows: vec![],
23754                })
23755            }
23756            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
23757                Ok(())
23758            }
23759            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
23760                Ok(false)
23761            }
23762            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
23763                Ok(())
23764            }
23765            fn dtype_sql(&self, _dtype: DType) -> &'static str {
23766                "TEXT"
23767            }
23768            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
23769                "TEXT"
23770            }
23771            fn supports_schemas(&self) -> bool {
23772                true
23773            }
23774        }
23775        let conn = PgLikeValidate;
23776        let cols = vec!["x INTEGER".to_owned()];
23777        let err =
23778            super::sql_create_table_query_in_schema(&conn, "users", Some("evil; DROP"), &cols)
23779                .expect_err("malformed schema must reject");
23780        // Per fd90.56: schema validation error now says invalid
23781        // schema name (not invalid table name).
23782        assert!(matches!(err, IoError::Sql(msg) if msg.contains("invalid schema name")));
23783    }
23784
23785    // ── DROP TABLE schema-qualification (br-frankenpandas-hxob / fd90.16) ─
23786
23787    #[test]
23788    fn sql_drop_table_query_bare_on_non_multi_schema() {
23789        struct StubSql;
23790        impl super::SqlConnection for StubSql {
23791            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<super::SqlQueryResult, IoError> {
23792                Ok(super::SqlQueryResult {
23793                    columns: vec![],
23794                    rows: vec![],
23795                })
23796            }
23797            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
23798                Ok(())
23799            }
23800            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
23801                Ok(false)
23802            }
23803            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
23804                Ok(())
23805            }
23806            fn dtype_sql(&self, _dtype: DType) -> &'static str {
23807                "TEXT"
23808            }
23809            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
23810                "TEXT"
23811            }
23812        }
23813        let conn = StubSql;
23814        let q = super::sql_drop_table_query_in_schema(&conn, "users", None).expect("drop none");
23815        assert_eq!(q, "DROP TABLE IF EXISTS \"users\"");
23816        // schema=Some on non-multi-schema is silently ignored.
23817        let q2 =
23818            super::sql_drop_table_query_in_schema(&conn, "users", Some("ignored")).expect("drop");
23819        assert_eq!(q2, "DROP TABLE IF EXISTS \"users\"");
23820    }
23821
23822    #[test]
23823    fn sql_drop_table_query_qualifies_on_multi_schema_backend() {
23824        struct PgLikeDrop;
23825        impl super::SqlConnection for PgLikeDrop {
23826            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<super::SqlQueryResult, IoError> {
23827                Ok(super::SqlQueryResult {
23828                    columns: vec![],
23829                    rows: vec![],
23830                })
23831            }
23832            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
23833                Ok(())
23834            }
23835            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
23836                Ok(false)
23837            }
23838            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
23839                Ok(())
23840            }
23841            fn dtype_sql(&self, _dtype: DType) -> &'static str {
23842                "TEXT"
23843            }
23844            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
23845                "TEXT"
23846            }
23847            fn supports_schemas(&self) -> bool {
23848                true
23849            }
23850        }
23851        let conn = PgLikeDrop;
23852        let q = super::sql_drop_table_query_in_schema(&conn, "users", Some("analytics"))
23853            .expect("drop qualified");
23854        assert_eq!(q, "DROP TABLE IF EXISTS \"analytics\".\"users\"");
23855        let bare = super::sql_drop_table_query_in_schema(&conn, "users", None).expect("drop bare");
23856        assert_eq!(bare, "DROP TABLE IF EXISTS \"users\"");
23857    }
23858
23859    #[cfg(feature = "sql-sqlite")]
23860    #[test]
23861    fn write_sql_replace_with_schema_silently_ignored_on_sqlite() {
23862        // Replace path drops + recreates. SQLite reports supports_schemas
23863        // == false; the schema is silently ignored on the DROP and on the
23864        // CREATE/INSERT — the round trip lands data in the bare table.
23865        let conn = make_sql_test_conn();
23866        super::SqlConnection::execute_batch(
23867            &conn,
23868            "CREATE TABLE replace_tbl (x INTEGER); INSERT INTO replace_tbl VALUES (99);",
23869        )
23870        .unwrap();
23871        let frame = fp_frame::DataFrame::from_dict(
23872            &["x"],
23873            vec![("x", vec![Scalar::Int64(1), Scalar::Int64(2)])],
23874        )
23875        .unwrap();
23876        write_sql_with_options(
23877            &frame,
23878            &conn,
23879            "replace_tbl",
23880            &SqlWriteOptions {
23881                if_exists: SqlIfExists::Replace,
23882                index: false,
23883                index_label: None,
23884                schema: Some("ignored_on_sqlite".to_owned()),
23885                dtype: None,
23886                method: SqlInsertMethod::Single,
23887                chunksize: None,
23888            },
23889        )
23890        .expect("replace + schema=Some on SQLite");
23891        let back = read_sql_table(&conn, "replace_tbl").expect("read");
23892        let col = back.column("x").expect("x");
23893        // Pre-existing 99 was dropped; new rows present.
23894        assert_eq!(col.values().len(), 2);
23895        assert_eq!(col.values()[0], Scalar::Int64(1));
23896        assert_eq!(col.values()[1], Scalar::Int64(2));
23897    }
23898
23899    // ── table_exists_in_schema (br-frankenpandas-70d1 / fd90.17) ────────
23900
23901    #[test]
23902    fn default_table_exists_in_schema_delegates_to_table_exists() {
23903        // A stub that returns table_exists=true for "users" must report the
23904        // same value via the schema-aware default impl regardless of schema.
23905        struct StubExistsTrue;
23906        impl super::SqlConnection for StubExistsTrue {
23907            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<super::SqlQueryResult, IoError> {
23908                Ok(super::SqlQueryResult {
23909                    columns: vec![],
23910                    rows: vec![],
23911                })
23912            }
23913            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
23914                Ok(())
23915            }
23916            fn table_exists(&self, name: &str) -> Result<bool, IoError> {
23917                Ok(name == "users")
23918            }
23919            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
23920                Ok(())
23921            }
23922            fn dtype_sql(&self, _dtype: DType) -> &'static str {
23923                "TEXT"
23924            }
23925            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
23926                "TEXT"
23927            }
23928        }
23929        let conn = StubExistsTrue;
23930        // Schema is ignored by the default impl.
23931        assert!(super::SqlConnection::table_exists_in_schema(&conn, "users", None).unwrap());
23932        assert!(
23933            super::SqlConnection::table_exists_in_schema(&conn, "users", Some("ignored")).unwrap()
23934        );
23935        assert!(!super::SqlConnection::table_exists_in_schema(&conn, "missing", None).unwrap());
23936    }
23937
23938    #[test]
23939    fn multi_schema_override_scopes_table_exists() {
23940        // PgLikeSchemaCheck overrides table_exists_in_schema to scope by
23941        // schema: only ('analytics', 'users') exists.
23942        struct PgLikeSchemaCheck;
23943        impl super::SqlConnection for PgLikeSchemaCheck {
23944            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<super::SqlQueryResult, IoError> {
23945                Ok(super::SqlQueryResult {
23946                    columns: vec![],
23947                    rows: vec![],
23948                })
23949            }
23950            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
23951                Ok(())
23952            }
23953            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
23954                // Bare table_exists isn't queried by the override path.
23955                Ok(false)
23956            }
23957            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
23958                Ok(())
23959            }
23960            fn dtype_sql(&self, _dtype: DType) -> &'static str {
23961                "TEXT"
23962            }
23963            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
23964                "TEXT"
23965            }
23966            fn supports_schemas(&self) -> bool {
23967                true
23968            }
23969            fn table_exists_in_schema(
23970                &self,
23971                table: &str,
23972                schema: Option<&str>,
23973            ) -> Result<bool, IoError> {
23974                Ok(table == "users" && schema == Some("analytics"))
23975            }
23976        }
23977        let conn = PgLikeSchemaCheck;
23978        assert!(
23979            super::SqlConnection::table_exists_in_schema(&conn, "users", Some("analytics"))
23980                .unwrap()
23981        );
23982        // Different schema → false.
23983        assert!(
23984            !super::SqlConnection::table_exists_in_schema(&conn, "users", Some("audit")).unwrap()
23985        );
23986        // No schema → false (override scopes by Some).
23987        assert!(!super::SqlConnection::table_exists_in_schema(&conn, "users", None).unwrap());
23988    }
23989
23990    #[cfg(feature = "sql-sqlite")]
23991    #[test]
23992    fn write_sql_fail_with_schema_some_still_rejects_existing_on_sqlite() {
23993        // SQLite ignores schema everywhere; the Fail branch still reports
23994        // 'table already exists' when the bare table is present.
23995        let conn = make_sql_test_conn();
23996        super::SqlConnection::execute_batch(&conn, "CREATE TABLE preexists_tbl (x INTEGER);")
23997            .unwrap();
23998        let frame =
23999            fp_frame::DataFrame::from_dict(&["x"], vec![("x", vec![Scalar::Int64(1)])]).unwrap();
24000        let err = write_sql_with_options(
24001            &frame,
24002            &conn,
24003            "preexists_tbl",
24004            &SqlWriteOptions {
24005                if_exists: SqlIfExists::Fail,
24006                index: false,
24007                index_label: None,
24008                schema: Some("ignored_on_sqlite".to_owned()),
24009                dtype: None,
24010                method: SqlInsertMethod::Single,
24011                chunksize: None,
24012            },
24013        )
24014        .expect_err("Fail branch must still reject pre-existing");
24015        assert!(matches!(err, IoError::Sql(msg) if msg.contains("already exists")));
24016    }
24017
24018    // ── SqlWriteOptions::dtype overrides (br-frankenpandas-ev2s / fd90.18) ─
24019
24020    #[cfg(feature = "sql-sqlite")]
24021    #[test]
24022    fn write_sql_dtype_override_emits_custom_sql_type() {
24023        // SQLite is permissive on declared types — the column-type string
24024        // ends up in sqlite_master.sql verbatim, which we can grep to verify
24025        // the override took effect during CREATE TABLE.
24026        let conn = make_sql_test_conn();
24027        let frame = fp_frame::DataFrame::from_dict(
24028            &["amount"],
24029            vec![("amount", vec![Scalar::Int64(100), Scalar::Int64(250)])],
24030        )
24031        .unwrap();
24032        let mut overrides = BTreeMap::new();
24033        overrides.insert("amount".to_owned(), "NUMERIC(10,2)".to_owned());
24034        write_sql_with_options(
24035            &frame,
24036            &conn,
24037            "money_tbl",
24038            &SqlWriteOptions {
24039                if_exists: SqlIfExists::Fail,
24040                index: false,
24041                index_label: None,
24042                schema: None,
24043                dtype: Some(overrides),
24044                method: SqlInsertMethod::Single,
24045                chunksize: None,
24046            },
24047        )
24048        .expect("write with dtype override");
24049        let sm = super::SqlConnection::query(
24050            &conn,
24051            "SELECT sql FROM sqlite_master WHERE name = 'money_tbl'",
24052            &[],
24053        )
24054        .unwrap();
24055        let create_sql = match &sm.rows[0][0] {
24056            Scalar::Utf8(s) => s.clone(),
24057            other => unreachable!("unexpected sqlite_master payload: {other:?}"),
24058        };
24059        assert!(
24060            create_sql.contains("NUMERIC(10,2)"),
24061            "expected override to land in CREATE TABLE; got: {create_sql}"
24062        );
24063    }
24064
24065    #[cfg(feature = "sql-sqlite")]
24066    #[test]
24067    fn write_sql_dtype_override_multiple_columns() {
24068        let conn = make_sql_test_conn();
24069        let frame = fp_frame::DataFrame::from_dict(
24070            &["a", "b"],
24071            vec![
24072                ("a", vec![Scalar::Int64(1)]),
24073                ("b", vec![Scalar::Float64(1.5)]),
24074            ],
24075        )
24076        .unwrap();
24077        let mut overrides = BTreeMap::new();
24078        overrides.insert("a".to_owned(), "BIGINT".to_owned());
24079        overrides.insert("b".to_owned(), "DECIMAL(8,4)".to_owned());
24080        write_sql_with_options(
24081            &frame,
24082            &conn,
24083            "multi_tbl",
24084            &SqlWriteOptions {
24085                if_exists: SqlIfExists::Fail,
24086                index: false,
24087                index_label: None,
24088                schema: None,
24089                dtype: Some(overrides),
24090                method: SqlInsertMethod::Single,
24091                chunksize: None,
24092            },
24093        )
24094        .expect("write with multi-column overrides");
24095        let sm = super::SqlConnection::query(
24096            &conn,
24097            "SELECT sql FROM sqlite_master WHERE name = 'multi_tbl'",
24098            &[],
24099        )
24100        .unwrap();
24101        let create_sql = match &sm.rows[0][0] {
24102            Scalar::Utf8(s) => s.clone(),
24103            other => unreachable!("unexpected sqlite_master payload: {other:?}"),
24104        };
24105        assert!(create_sql.contains("BIGINT"));
24106        assert!(create_sql.contains("DECIMAL(8,4)"));
24107    }
24108
24109    #[cfg(feature = "sql-sqlite")]
24110    #[test]
24111    fn write_sql_dtype_override_for_missing_column_silently_ignored() {
24112        let conn = make_sql_test_conn();
24113        let frame =
24114            fp_frame::DataFrame::from_dict(&["x"], vec![("x", vec![Scalar::Int64(1)])]).unwrap();
24115        let mut overrides = BTreeMap::new();
24116        overrides.insert("nonexistent".to_owned(), "BIGINT".to_owned());
24117        // No error — pandas silently ignores dtype entries for columns not in the frame.
24118        write_sql_with_options(
24119            &frame,
24120            &conn,
24121            "missing_col_tbl",
24122            &SqlWriteOptions {
24123                if_exists: SqlIfExists::Fail,
24124                index: false,
24125                index_label: None,
24126                schema: None,
24127                dtype: Some(overrides),
24128                method: SqlInsertMethod::Single,
24129                chunksize: None,
24130            },
24131        )
24132        .expect("write with override on missing col");
24133        // The actual 'x' column kept its inferred type.
24134        let sm = super::SqlConnection::query(
24135            &conn,
24136            "SELECT sql FROM sqlite_master WHERE name = 'missing_col_tbl'",
24137            &[],
24138        )
24139        .unwrap();
24140        let create_sql = match &sm.rows[0][0] {
24141            Scalar::Utf8(s) => s.clone(),
24142            other => unreachable!("unexpected sqlite_master payload: {other:?}"),
24143        };
24144        assert!(create_sql.contains("INTEGER"));
24145        assert!(!create_sql.contains("BIGINT"));
24146    }
24147
24148    #[cfg(feature = "sql-sqlite")]
24149    #[test]
24150    fn write_sql_dtype_none_falls_back_to_inferred_type() {
24151        let conn = make_sql_test_conn();
24152        let frame =
24153            fp_frame::DataFrame::from_dict(&["x"], vec![("x", vec![Scalar::Int64(1)])]).unwrap();
24154        write_sql_with_options(
24155            &frame,
24156            &conn,
24157            "no_override_tbl",
24158            &SqlWriteOptions {
24159                if_exists: SqlIfExists::Fail,
24160                index: false,
24161                index_label: None,
24162                schema: None,
24163                dtype: None,
24164                method: SqlInsertMethod::Single,
24165                chunksize: None,
24166            },
24167        )
24168        .expect("write without override");
24169        let sm = super::SqlConnection::query(
24170            &conn,
24171            "SELECT sql FROM sqlite_master WHERE name = 'no_override_tbl'",
24172            &[],
24173        )
24174        .unwrap();
24175        let create_sql = match &sm.rows[0][0] {
24176            Scalar::Utf8(s) => s.clone(),
24177            other => unreachable!("unexpected sqlite_master payload: {other:?}"),
24178        };
24179        // INTEGER is conn.dtype_sql(DType::Int64) for rusqlite.
24180        assert!(create_sql.contains("INTEGER"));
24181    }
24182
24183    // ── SqlInsertMethod::Multi (br-frankenpandas-i0ml / fd90.19) ─────────
24184
24185    #[cfg(feature = "sql-sqlite")]
24186    #[test]
24187    fn write_sql_multi_round_trip_matches_single() {
24188        // Same frame written via Single vs Multi must produce identical
24189        // SELECT * results — the only observable difference should be
24190        // the wire-format efficiency, never the stored values.
24191        let frame = fp_frame::DataFrame::from_dict(
24192            &["id", "name", "amount"],
24193            vec![
24194                (
24195                    "id",
24196                    vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
24197                ),
24198                (
24199                    "name",
24200                    vec![
24201                        Scalar::Utf8("alice".into()),
24202                        Scalar::Utf8("bob".into()),
24203                        Scalar::Utf8("carol".into()),
24204                    ],
24205                ),
24206                (
24207                    "amount",
24208                    vec![
24209                        Scalar::Float64(1.5),
24210                        Scalar::Float64(2.5),
24211                        Scalar::Float64(3.5),
24212                    ],
24213                ),
24214            ],
24215        )
24216        .unwrap();
24217
24218        let conn_single = make_sql_test_conn();
24219        write_sql_with_options(
24220            &frame,
24221            &conn_single,
24222            "single_tbl",
24223            &SqlWriteOptions {
24224                if_exists: SqlIfExists::Fail,
24225                index: false,
24226                index_label: None,
24227                schema: None,
24228                dtype: None,
24229                method: SqlInsertMethod::Single,
24230                chunksize: None,
24231            },
24232        )
24233        .unwrap();
24234        let single = read_sql(&conn_single, "SELECT * FROM single_tbl ORDER BY id").unwrap();
24235
24236        let conn_multi = make_sql_test_conn();
24237        write_sql_with_options(
24238            &frame,
24239            &conn_multi,
24240            "multi_tbl",
24241            &SqlWriteOptions {
24242                if_exists: SqlIfExists::Fail,
24243                index: false,
24244                index_label: None,
24245                schema: None,
24246                dtype: None,
24247                method: SqlInsertMethod::Multi,
24248                chunksize: None,
24249            },
24250        )
24251        .unwrap();
24252        let multi = read_sql(&conn_multi, "SELECT * FROM multi_tbl ORDER BY id").unwrap();
24253
24254        assert_eq!(single.column_names(), multi.column_names());
24255        for name in single.column_names() {
24256            let s = single.column(name).unwrap().values().to_vec();
24257            let m = multi.column(name).unwrap().values().to_vec();
24258            assert_eq!(s, m, "column {name} diverged between Single and Multi");
24259        }
24260    }
24261
24262    #[test]
24263    fn sql_multi_row_insert_query_emits_correct_placeholder_count() {
24264        // 3 rows × 2 cols = 6 placeholders, ordinals 1..=6.
24265        struct PgLikeStub;
24266        impl super::SqlConnection for PgLikeStub {
24267            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
24268                Ok(SqlQueryResult {
24269                    columns: vec![],
24270                    rows: vec![],
24271                })
24272            }
24273            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
24274                Ok(())
24275            }
24276            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
24277                Ok(false)
24278            }
24279            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
24280                Ok(())
24281            }
24282            fn dtype_sql(&self, _dtype: DType) -> &'static str {
24283                "TEXT"
24284            }
24285            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
24286                "TEXT"
24287            }
24288            fn parameter_marker(&self, ordinal: usize) -> String {
24289                format!("${ordinal}")
24290            }
24291        }
24292        let conn = PgLikeStub;
24293        let cols = vec!["a".to_owned(), "b".to_owned()];
24294        let sql =
24295            super::sql_multi_row_insert_query_in_schema(&conn, "tbl", None, &cols, 3).unwrap();
24296        // Expect: INSERT INTO "tbl" ("a", "b") VALUES ($1, $2), ($3, $4), ($5, $6)
24297        assert!(
24298            sql.contains("VALUES ($1, $2), ($3, $4), ($5, $6)"),
24299            "got: {sql}"
24300        );
24301    }
24302
24303    #[test]
24304    fn sql_multi_row_insert_query_rejects_zero_rows() {
24305        struct StubConn;
24306        impl super::SqlConnection for StubConn {
24307            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
24308                Ok(SqlQueryResult {
24309                    columns: vec![],
24310                    rows: vec![],
24311                })
24312            }
24313            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
24314                Ok(())
24315            }
24316            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
24317                Ok(false)
24318            }
24319            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
24320                Ok(())
24321            }
24322            fn dtype_sql(&self, _dtype: DType) -> &'static str {
24323                "TEXT"
24324            }
24325            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
24326                "TEXT"
24327            }
24328        }
24329        let conn = StubConn;
24330        let cols = vec!["a".to_owned()];
24331        let err = super::sql_multi_row_insert_query_in_schema(&conn, "tbl", None, &cols, 0)
24332            .expect_err("zero rows must be rejected");
24333        assert!(matches!(err, IoError::Sql(msg) if msg.contains("at least one row")));
24334    }
24335
24336    #[cfg(feature = "sql-sqlite")]
24337    #[test]
24338    fn write_sql_multi_chunks_at_max_param_boundary() {
24339        // Verify the chunking logic dispatches multiple INSERT statements
24340        // when num_rows * num_cols exceeds max_param_count. We override
24341        // max_param_count on a recording stub to force a tiny budget.
24342        use std::cell::RefCell;
24343        struct ChunkRecorder {
24344            statements: RefCell<Vec<String>>,
24345            row_counts: RefCell<Vec<usize>>,
24346        }
24347        impl super::SqlConnection for ChunkRecorder {
24348            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
24349                Ok(SqlQueryResult {
24350                    columns: vec![],
24351                    rows: vec![],
24352                })
24353            }
24354            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
24355                Ok(())
24356            }
24357            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
24358                Ok(false)
24359            }
24360            fn insert_rows(&self, sql: &str, rows: &[Vec<Scalar>]) -> Result<(), IoError> {
24361                self.statements.borrow_mut().push(sql.to_owned());
24362                self.row_counts
24363                    .borrow_mut()
24364                    .push(rows.first().map_or(0, std::vec::Vec::len));
24365                Ok(())
24366            }
24367            fn dtype_sql(&self, _dtype: DType) -> &'static str {
24368                "TEXT"
24369            }
24370            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
24371                "TEXT"
24372            }
24373            fn max_param_count(&self) -> Option<usize> {
24374                // 4 params total, ncols=2 → 2 rows per chunk.
24375                Some(4)
24376            }
24377        }
24378        let conn = ChunkRecorder {
24379            statements: RefCell::new(vec![]),
24380            row_counts: RefCell::new(vec![]),
24381        };
24382        let frame = fp_frame::DataFrame::from_dict(
24383            &["a", "b"],
24384            vec![
24385                (
24386                    "a",
24387                    vec![
24388                        Scalar::Int64(1),
24389                        Scalar::Int64(2),
24390                        Scalar::Int64(3),
24391                        Scalar::Int64(4),
24392                        Scalar::Int64(5),
24393                    ],
24394                ),
24395                (
24396                    "b",
24397                    vec![
24398                        Scalar::Int64(10),
24399                        Scalar::Int64(20),
24400                        Scalar::Int64(30),
24401                        Scalar::Int64(40),
24402                        Scalar::Int64(50),
24403                    ],
24404                ),
24405            ],
24406        )
24407        .unwrap();
24408        write_sql_with_options(
24409            &frame,
24410            &conn,
24411            "chunked",
24412            &SqlWriteOptions {
24413                if_exists: SqlIfExists::Fail,
24414                index: false,
24415                index_label: None,
24416                schema: None,
24417                dtype: None,
24418                method: SqlInsertMethod::Multi,
24419                chunksize: None,
24420            },
24421        )
24422        .unwrap();
24423        // 5 rows / 2 per chunk = 3 chunks (2, 2, 1).
24424        let stmts = conn.statements.borrow();
24425        let counts = conn.row_counts.borrow();
24426        assert_eq!(stmts.len(), 3, "expected 3 chunked INSERTs");
24427        // Flat row payloads: 2 rows * 2 cols = 4 scalars, 4, then 1 row * 2 = 2.
24428        assert_eq!(counts.as_slice(), &[4, 4, 2]);
24429    }
24430
24431    #[cfg(feature = "sql-sqlite")]
24432    #[test]
24433    fn write_sql_multi_no_max_param_sends_single_statement() {
24434        // When the backend reports max_param_count() == None, the whole
24435        // frame should ship in a single multi-row INSERT.
24436        use std::cell::RefCell;
24437        struct UnboundedStub {
24438            statements: RefCell<Vec<String>>,
24439        }
24440        impl super::SqlConnection for UnboundedStub {
24441            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
24442                Ok(SqlQueryResult {
24443                    columns: vec![],
24444                    rows: vec![],
24445                })
24446            }
24447            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
24448                Ok(())
24449            }
24450            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
24451                Ok(false)
24452            }
24453            fn insert_rows(&self, sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
24454                self.statements.borrow_mut().push(sql.to_owned());
24455                Ok(())
24456            }
24457            fn dtype_sql(&self, _dtype: DType) -> &'static str {
24458                "TEXT"
24459            }
24460            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
24461                "TEXT"
24462            }
24463            fn max_param_count(&self) -> Option<usize> {
24464                None
24465            }
24466        }
24467        let conn = UnboundedStub {
24468            statements: RefCell::new(vec![]),
24469        };
24470        let frame = fp_frame::DataFrame::from_dict(
24471            &["x"],
24472            vec![(
24473                "x",
24474                vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)],
24475            )],
24476        )
24477        .unwrap();
24478        write_sql_with_options(
24479            &frame,
24480            &conn,
24481            "uncapped",
24482            &SqlWriteOptions {
24483                if_exists: SqlIfExists::Fail,
24484                index: false,
24485                index_label: None,
24486                schema: None,
24487                dtype: None,
24488                method: SqlInsertMethod::Multi,
24489                chunksize: None,
24490            },
24491        )
24492        .unwrap();
24493        let stmts = conn.statements.borrow();
24494        assert_eq!(stmts.len(), 1, "expected exactly one multi-row INSERT");
24495        // 3 tuples → 2 commas separating tuples in VALUES (...), (...), (...).
24496        let stmt = &stmts[0];
24497        assert_eq!(
24498            stmt.matches("(?)").count(),
24499            3,
24500            "expected 3 row tuples in: {stmt}"
24501        );
24502    }
24503
24504    #[cfg(feature = "sql-sqlite")]
24505    #[test]
24506    fn write_sql_multi_preserves_nulls() {
24507        // NaT/Null values must round-trip through the multi-row path.
24508        let frame = fp_frame::DataFrame::from_dict(
24509            &["a", "b"],
24510            vec![
24511                (
24512                    "a",
24513                    vec![
24514                        Scalar::Int64(1),
24515                        Scalar::Null(NullKind::Null),
24516                        Scalar::Int64(3),
24517                    ],
24518                ),
24519                (
24520                    "b",
24521                    vec![
24522                        Scalar::Utf8("x".into()),
24523                        Scalar::Utf8("y".into()),
24524                        Scalar::Null(NullKind::Null),
24525                    ],
24526                ),
24527            ],
24528        )
24529        .unwrap();
24530        let conn = make_sql_test_conn();
24531        write_sql_with_options(
24532            &frame,
24533            &conn,
24534            "nulls_tbl",
24535            &SqlWriteOptions {
24536                if_exists: SqlIfExists::Fail,
24537                index: false,
24538                index_label: None,
24539                schema: None,
24540                dtype: None,
24541                method: SqlInsertMethod::Multi,
24542                chunksize: None,
24543            },
24544        )
24545        .unwrap();
24546        let back = read_sql(&conn, "SELECT a, b FROM nulls_tbl ORDER BY rowid").unwrap();
24547        let a = back.column("a").unwrap().values();
24548        let b = back.column("b").unwrap().values();
24549        assert_eq!(a[0], Scalar::Int64(1));
24550        assert!(matches!(a[1], Scalar::Null(_)));
24551        assert_eq!(a[2], Scalar::Int64(3));
24552        assert_eq!(b[0], Scalar::Utf8("x".into()));
24553        assert_eq!(b[1], Scalar::Utf8("y".into()));
24554        assert!(matches!(b[2], Scalar::Null(_)));
24555    }
24556
24557    #[test]
24558    fn sql_insert_method_default_is_single() {
24559        assert_eq!(SqlInsertMethod::default(), SqlInsertMethod::Single);
24560    }
24561
24562    // ── list_sql_tables / SqlConnection::list_tables (br-vhq2 / fd90.20) ─
24563
24564    #[cfg(feature = "sql-sqlite")]
24565    #[test]
24566    fn list_sql_tables_empty_db_returns_empty_vec() {
24567        let conn = make_sql_test_conn();
24568        let tables = list_sql_tables(&conn, None).unwrap();
24569        assert!(tables.is_empty(), "expected no tables; got {tables:?}");
24570    }
24571
24572    #[cfg(feature = "sql-sqlite")]
24573    #[test]
24574    fn list_sql_tables_returns_user_tables_sorted() {
24575        let conn = make_sql_test_conn();
24576        super::SqlConnection::execute_batch(&conn, "CREATE TABLE zebra (x INTEGER);").unwrap();
24577        super::SqlConnection::execute_batch(&conn, "CREATE TABLE alpha (y TEXT);").unwrap();
24578        super::SqlConnection::execute_batch(&conn, "CREATE TABLE mango (z REAL);").unwrap();
24579        let tables = list_sql_tables(&conn, None).unwrap();
24580        assert_eq!(tables, vec!["alpha", "mango", "zebra"]);
24581    }
24582
24583    #[cfg(feature = "sql-sqlite")]
24584    #[test]
24585    fn list_sql_tables_excludes_sqlite_internal_tables() {
24586        let conn = make_sql_test_conn();
24587        // Forcing creation of an internal sqlite_sequence table by using
24588        // AUTOINCREMENT — that table must NOT appear in the result.
24589        super::SqlConnection::execute_batch(
24590            &conn,
24591            "CREATE TABLE seq_demo (id INTEGER PRIMARY KEY AUTOINCREMENT, v TEXT);",
24592        )
24593        .unwrap();
24594        super::SqlConnection::execute_batch(&conn, "INSERT INTO seq_demo (v) VALUES ('one');")
24595            .unwrap();
24596        let tables = list_sql_tables(&conn, None).unwrap();
24597        assert_eq!(tables, vec!["seq_demo"]);
24598        assert!(!tables.iter().any(|name| name.starts_with("sqlite_")));
24599    }
24600
24601    #[cfg(feature = "sql-sqlite")]
24602    #[test]
24603    fn list_sql_tables_keeps_user_tables_with_sqlite_prefix_no_underscore() {
24604        // Per fd90.50: a user table named like 'sqliteX' (no underscore
24605        // between 'sqlite' and the rest) was being incorrectly excluded
24606        // by the buggy `NOT LIKE 'sqlite_%'` filter (where `_` is a
24607        // single-char wildcard). After the ESCAPE '\' fix the
24608        // underscore is treated literally, so only names starting with
24609        // the literal substring 'sqlite_' are excluded.
24610        let conn = make_sql_test_conn();
24611        super::SqlConnection::execute_batch(&conn, "CREATE TABLE sqliteX (x INTEGER);").unwrap();
24612        super::SqlConnection::execute_batch(&conn, "CREATE TABLE sqliteY (y TEXT);").unwrap();
24613        super::SqlConnection::execute_batch(&conn, "CREATE TABLE sqlite1234 (z REAL);").unwrap();
24614        let tables = list_sql_tables(&conn, None).unwrap();
24615        assert_eq!(tables, vec!["sqlite1234", "sqliteX", "sqliteY"]);
24616    }
24617
24618    #[cfg(feature = "sql-sqlite")]
24619    #[test]
24620    fn list_sql_views_keeps_user_views_with_sqlite_prefix_no_underscore() {
24621        // Companion to the list_tables case (fd90.50): same escape fix
24622        // applies to list_views.
24623        let conn = make_sql_test_conn();
24624        super::SqlConnection::execute_batch(&conn, "CREATE TABLE base (x INTEGER);").unwrap();
24625        super::SqlConnection::execute_batch(
24626            &conn,
24627            "CREATE VIEW sqliteX_view AS SELECT x FROM base;",
24628        )
24629        .unwrap();
24630        let views = list_sql_views(&conn, None).unwrap();
24631        // sqliteX_view: 'sqliteX' (no underscore after 'sqlite') so the
24632        // literal-underscore filter accepts it.
24633        assert_eq!(views, vec!["sqliteX_view"]);
24634    }
24635
24636    #[cfg(feature = "sql-sqlite")]
24637    #[test]
24638    fn list_sql_tables_schema_silently_ignored_on_sqlite() {
24639        // SQLite reports supports_schemas() == false. Passing a schema
24640        // arg must NOT error; it is silently dropped and all tables are
24641        // returned (matches the documented option-struct ignore policy).
24642        let conn = make_sql_test_conn();
24643        super::SqlConnection::execute_batch(&conn, "CREATE TABLE only_one (x INTEGER);").unwrap();
24644        let with_schema =
24645            list_sql_tables(&conn, Some("ignored_on_sqlite")).expect("schema arg must not error");
24646        let without_schema = list_sql_tables(&conn, None).unwrap();
24647        assert_eq!(with_schema, without_schema);
24648    }
24649
24650    #[test]
24651    fn list_sql_tables_default_impl_returns_empty() {
24652        // A backend that doesn't override list_tables falls through to
24653        // the trait default — returns empty rather than erroring.
24654        struct NoIntrospection;
24655        impl super::SqlConnection for NoIntrospection {
24656            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
24657                Ok(SqlQueryResult {
24658                    columns: vec![],
24659                    rows: vec![],
24660                })
24661            }
24662            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
24663                Ok(())
24664            }
24665            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
24666                Ok(false)
24667            }
24668            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
24669                Ok(())
24670            }
24671            fn dtype_sql(&self, _dtype: DType) -> &'static str {
24672                "TEXT"
24673            }
24674            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
24675                "TEXT"
24676            }
24677        }
24678        let conn = NoIntrospection;
24679        let tables = list_sql_tables(&conn, None).unwrap();
24680        assert!(tables.is_empty());
24681        let with_schema = list_sql_tables(&conn, Some("any")).unwrap();
24682        assert!(with_schema.is_empty());
24683    }
24684
24685    #[test]
24686    fn list_sql_tables_routes_schema_to_backend_override() {
24687        // Multi-schema backend stub: returns different tables per schema.
24688        struct MultiSchema;
24689        impl super::SqlConnection for MultiSchema {
24690            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
24691                Ok(SqlQueryResult {
24692                    columns: vec![],
24693                    rows: vec![],
24694                })
24695            }
24696            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
24697                Ok(())
24698            }
24699            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
24700                Ok(false)
24701            }
24702            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
24703                Ok(())
24704            }
24705            fn dtype_sql(&self, _dtype: DType) -> &'static str {
24706                "TEXT"
24707            }
24708            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
24709                "TEXT"
24710            }
24711            fn supports_schemas(&self) -> bool {
24712                true
24713            }
24714            fn list_tables(&self, schema: Option<&str>) -> Result<Vec<String>, IoError> {
24715                Ok(match schema {
24716                    Some("analytics") => {
24717                        vec!["users".to_owned(), "events".to_owned()]
24718                    }
24719                    Some("audit") => vec!["logs".to_owned()],
24720                    Some(_) => vec![],
24721                    None => vec!["public_table".to_owned()],
24722                })
24723            }
24724        }
24725        let conn = MultiSchema;
24726        assert_eq!(
24727            list_sql_tables(&conn, Some("analytics")).unwrap(),
24728            vec!["users", "events"]
24729        );
24730        assert_eq!(list_sql_tables(&conn, Some("audit")).unwrap(), vec!["logs"]);
24731        assert_eq!(
24732            list_sql_tables(&conn, Some("missing")).unwrap(),
24733            Vec::<String>::new()
24734        );
24735        assert_eq!(list_sql_tables(&conn, None).unwrap(), vec!["public_table"]);
24736    }
24737
24738    // ── sql_table_schema / SqlConnection::table_schema (br-w43q / fd90.21) ─
24739
24740    #[cfg(feature = "sql-sqlite")]
24741    #[test]
24742    fn sql_table_schema_unknown_table_returns_none() {
24743        let conn = make_sql_test_conn();
24744        let result = sql_table_schema(&conn, "no_such_table", None).unwrap();
24745        assert!(result.is_none());
24746    }
24747
24748    #[cfg(feature = "sql-sqlite")]
24749    #[test]
24750    fn sql_table_schema_simple_table() {
24751        let conn = make_sql_test_conn();
24752        super::SqlConnection::execute_batch(&conn, "CREATE TABLE simple (id INTEGER, name TEXT);")
24753            .unwrap();
24754        let schema = sql_table_schema(&conn, "simple", None).unwrap().unwrap();
24755        assert_eq!(schema.table_name, "simple");
24756        assert_eq!(schema.columns.len(), 2);
24757        assert_eq!(schema.columns[0].name, "id");
24758        assert_eq!(schema.columns[0].declared_type.as_deref(), Some("INTEGER"));
24759        assert!(schema.columns[0].nullable);
24760        assert!(schema.columns[0].primary_key_ordinal.is_none());
24761        assert_eq!(schema.columns[1].name, "name");
24762        assert_eq!(schema.columns[1].declared_type.as_deref(), Some("TEXT"));
24763        assert!(schema.columns[1].nullable);
24764    }
24765
24766    #[cfg(feature = "sql-sqlite")]
24767    #[test]
24768    fn sql_table_schema_pk_notnull_default() {
24769        let conn = make_sql_test_conn();
24770        super::SqlConnection::execute_batch(
24771            &conn,
24772            "CREATE TABLE meta ( \
24773                id INTEGER PRIMARY KEY, \
24774                name TEXT NOT NULL, \
24775                status TEXT DEFAULT 'active' \
24776             );",
24777        )
24778        .unwrap();
24779        let schema = sql_table_schema(&conn, "meta", None).unwrap().unwrap();
24780        assert_eq!(schema.columns.len(), 3);
24781
24782        let id = schema.column("id").expect("id col");
24783        assert_eq!(id.primary_key_ordinal, Some(0));
24784        // PRIMARY KEY columns in SQLite (without explicit NOT NULL on
24785        // INTEGER PRIMARY KEY) are reported as nullable=true by
24786        // table_info — we surface that as-is rather than fabricating.
24787        // The point is just that primary_key_ordinal is populated.
24788
24789        let name = schema.column("name").expect("name col");
24790        assert!(!name.nullable);
24791        assert!(name.default_value.is_none());
24792        assert!(name.primary_key_ordinal.is_none());
24793
24794        let status = schema.column("status").expect("status col");
24795        assert!(status.nullable);
24796        assert_eq!(
24797            status.default_value.as_deref(),
24798            Some("'active'"),
24799            "expected SQL literal default text"
24800        );
24801    }
24802
24803    #[cfg(feature = "sql-sqlite")]
24804    #[test]
24805    fn sql_table_schema_schema_silently_ignored_on_sqlite() {
24806        let conn = make_sql_test_conn();
24807        super::SqlConnection::execute_batch(&conn, "CREATE TABLE only_one (x INTEGER);").unwrap();
24808        let with_schema = sql_table_schema(&conn, "only_one", Some("ignored_on_sqlite"))
24809            .expect("schema arg must not error")
24810            .expect("table exists");
24811        let without_schema = sql_table_schema(&conn, "only_one", None).unwrap().unwrap();
24812        assert_eq!(with_schema, without_schema);
24813    }
24814
24815    #[cfg(feature = "sql-sqlite")]
24816    #[test]
24817    fn sql_table_schema_rejects_invalid_table_name() {
24818        // The PRAGMA path can't bind parameters, so we validate the
24819        // identifier first. Reject anything with non-alphanumeric chars.
24820        let conn = make_sql_test_conn();
24821        let err = sql_table_schema(&conn, "x; DROP TABLE users", None).expect_err("must reject");
24822        assert!(matches!(err, IoError::Sql(msg) if msg.contains("invalid")));
24823    }
24824
24825    #[test]
24826    fn sql_table_schema_default_impl_returns_none() {
24827        struct NoIntrospection;
24828        impl super::SqlConnection for NoIntrospection {
24829            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
24830                Ok(SqlQueryResult {
24831                    columns: vec![],
24832                    rows: vec![],
24833                })
24834            }
24835            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
24836                Ok(())
24837            }
24838            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
24839                Ok(false)
24840            }
24841            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
24842                Ok(())
24843            }
24844            fn dtype_sql(&self, _dtype: DType) -> &'static str {
24845                "TEXT"
24846            }
24847            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
24848                "TEXT"
24849            }
24850        }
24851        let conn = NoIntrospection;
24852        assert!(sql_table_schema(&conn, "anything", None).unwrap().is_none());
24853    }
24854
24855    #[test]
24856    fn sql_table_schema_routes_schema_to_backend_override() {
24857        struct MultiSchema;
24858        impl super::SqlConnection for MultiSchema {
24859            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
24860                Ok(SqlQueryResult {
24861                    columns: vec![],
24862                    rows: vec![],
24863                })
24864            }
24865            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
24866                Ok(())
24867            }
24868            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
24869                Ok(false)
24870            }
24871            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
24872                Ok(())
24873            }
24874            fn dtype_sql(&self, _dtype: DType) -> &'static str {
24875                "TEXT"
24876            }
24877            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
24878                "TEXT"
24879            }
24880            fn supports_schemas(&self) -> bool {
24881                true
24882            }
24883            fn table_schema(
24884                &self,
24885                table: &str,
24886                schema: Option<&str>,
24887            ) -> Result<Option<SqlTableSchema>, IoError> {
24888                if table == "users" && schema == Some("analytics") {
24889                    Ok(Some(SqlTableSchema {
24890                        table_name: "users".to_owned(),
24891                        columns: vec![SqlColumnSchema {
24892                            name: "id".to_owned(),
24893                            declared_type: Some("BIGINT".to_owned()),
24894                            nullable: false,
24895                            default_value: None,
24896                            primary_key_ordinal: Some(0),
24897                            comment: None,
24898                            autoincrement: false,
24899                        }],
24900                    }))
24901                } else {
24902                    Ok(None)
24903                }
24904            }
24905        }
24906        let conn = MultiSchema;
24907        let analytics_users = sql_table_schema(&conn, "users", Some("analytics"))
24908            .unwrap()
24909            .expect("found");
24910        assert_eq!(
24911            analytics_users.columns[0].declared_type.as_deref(),
24912            Some("BIGINT")
24913        );
24914        assert!(
24915            sql_table_schema(&conn, "users", Some("audit"))
24916                .unwrap()
24917                .is_none()
24918        );
24919        assert!(sql_table_schema(&conn, "users", None).unwrap().is_none());
24920    }
24921
24922    // ── list_sql_schemas / SqlConnection::list_schemas (br-lxhi / fd90.22) ─
24923
24924    #[cfg(feature = "sql-sqlite")]
24925    #[test]
24926    fn list_sql_schemas_returns_empty_on_sqlite() {
24927        // SQLite has no meaningful schema concept; the trait default
24928        // (empty Vec) is the right answer.
24929        let conn = make_sql_test_conn();
24930        let schemas = list_sql_schemas(&conn).unwrap();
24931        assert!(schemas.is_empty(), "expected no schemas; got {schemas:?}");
24932    }
24933
24934    #[test]
24935    fn list_sql_schemas_default_impl_returns_empty() {
24936        struct NoIntrospection;
24937        impl super::SqlConnection for NoIntrospection {
24938            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
24939                Ok(SqlQueryResult {
24940                    columns: vec![],
24941                    rows: vec![],
24942                })
24943            }
24944            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
24945                Ok(())
24946            }
24947            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
24948                Ok(false)
24949            }
24950            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
24951                Ok(())
24952            }
24953            fn dtype_sql(&self, _dtype: DType) -> &'static str {
24954                "TEXT"
24955            }
24956            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
24957                "TEXT"
24958            }
24959        }
24960        let conn = NoIntrospection;
24961        assert!(list_sql_schemas(&conn).unwrap().is_empty());
24962    }
24963
24964    #[test]
24965    fn list_sql_schemas_routes_to_backend_override() {
24966        // Multi-schema backend stub: returns the schemas the connection's
24967        // role can see, with internal schemas filtered out.
24968        struct MultiSchemaServer;
24969        impl super::SqlConnection for MultiSchemaServer {
24970            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
24971                Ok(SqlQueryResult {
24972                    columns: vec![],
24973                    rows: vec![],
24974                })
24975            }
24976            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
24977                Ok(())
24978            }
24979            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
24980                Ok(false)
24981            }
24982            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
24983                Ok(())
24984            }
24985            fn dtype_sql(&self, _dtype: DType) -> &'static str {
24986                "TEXT"
24987            }
24988            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
24989                "TEXT"
24990            }
24991            fn supports_schemas(&self) -> bool {
24992                true
24993            }
24994            fn list_schemas(&self) -> Result<Vec<String>, IoError> {
24995                // Filter out information_schema + pg_catalog by default.
24996                Ok(vec![
24997                    "public".to_owned(),
24998                    "analytics".to_owned(),
24999                    "audit".to_owned(),
25000                ])
25001            }
25002        }
25003        let conn = MultiSchemaServer;
25004        let schemas = list_sql_schemas(&conn).unwrap();
25005        assert_eq!(schemas, vec!["public", "analytics", "audit"]);
25006        // Verify the override actually filters internal schemas
25007        // (test contract: stub never returns 'pg_catalog' or
25008        // 'information_schema').
25009        assert!(!schemas.iter().any(|s| s.starts_with("pg_")));
25010        assert!(!schemas.iter().any(|s| s == "information_schema"));
25011    }
25012
25013    #[test]
25014    fn list_sql_schemas_propagates_backend_error() {
25015        // If the backend errors during introspection, the error should
25016        // surface through the wrapper unchanged.
25017        struct BrokenIntrospection;
25018        impl super::SqlConnection for BrokenIntrospection {
25019            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
25020                Ok(SqlQueryResult {
25021                    columns: vec![],
25022                    rows: vec![],
25023                })
25024            }
25025            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
25026                Ok(())
25027            }
25028            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
25029                Ok(false)
25030            }
25031            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
25032                Ok(())
25033            }
25034            fn dtype_sql(&self, _dtype: DType) -> &'static str {
25035                "TEXT"
25036            }
25037            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
25038                "TEXT"
25039            }
25040            fn list_schemas(&self) -> Result<Vec<String>, IoError> {
25041                Err(IoError::Sql("permission denied for catalog".to_owned()))
25042            }
25043        }
25044        let conn = BrokenIntrospection;
25045        let err = list_sql_schemas(&conn).expect_err("should surface backend error");
25046        assert!(matches!(err, IoError::Sql(msg) if msg.contains("permission denied")));
25047    }
25048
25049    // ── truncate_sql_table / SqlConnection::truncate_table (br-phum / fd90.23) ─
25050
25051    #[cfg(feature = "sql-sqlite")]
25052    #[test]
25053    fn truncate_sql_table_clears_rows_but_preserves_schema() {
25054        let conn = make_sql_test_conn();
25055        super::SqlConnection::execute_batch(&conn, "CREATE TABLE rolling (id INTEGER, val TEXT);")
25056            .unwrap();
25057        super::SqlConnection::execute_batch(
25058            &conn,
25059            "INSERT INTO rolling VALUES (1, 'a'), (2, 'b'), (3, 'c');",
25060        )
25061        .unwrap();
25062        // Sanity: rows present.
25063        let before =
25064            super::SqlConnection::query(&conn, "SELECT COUNT(*) FROM rolling", &[]).unwrap();
25065        assert_eq!(before.rows[0][0], Scalar::Int64(3));
25066
25067        truncate_sql_table(&conn, "rolling", None).unwrap();
25068
25069        // Rows gone, table still there.
25070        let after =
25071            super::SqlConnection::query(&conn, "SELECT COUNT(*) FROM rolling", &[]).unwrap();
25072        assert_eq!(after.rows[0][0], Scalar::Int64(0));
25073        assert!(super::SqlConnection::table_exists(&conn, "rolling").unwrap());
25074    }
25075
25076    #[cfg(feature = "sql-sqlite")]
25077    #[test]
25078    fn truncate_sql_table_schema_silently_ignored_on_sqlite() {
25079        let conn = make_sql_test_conn();
25080        super::SqlConnection::execute_batch(&conn, "CREATE TABLE t (x INTEGER);").unwrap();
25081        super::SqlConnection::execute_batch(&conn, "INSERT INTO t VALUES (1);").unwrap();
25082        truncate_sql_table(&conn, "t", Some("ignored_on_sqlite"))
25083            .expect("schema arg must not error on SQLite");
25084        let count = super::SqlConnection::query(&conn, "SELECT COUNT(*) FROM t", &[]).unwrap();
25085        assert_eq!(count.rows[0][0], Scalar::Int64(0));
25086    }
25087
25088    #[cfg(feature = "sql-sqlite")]
25089    #[test]
25090    fn truncate_sql_table_rejects_invalid_table_name() {
25091        let conn = make_sql_test_conn();
25092        let err = truncate_sql_table(&conn, "x; DROP TABLE users", None)
25093            .expect_err("must reject invalid identifier");
25094        assert!(matches!(err, IoError::Sql(msg) if msg.contains("invalid")));
25095    }
25096
25097    #[test]
25098    fn truncate_sql_table_routes_schema_to_quote_identifier() {
25099        // Multi-schema backend stub records the SQL it receives.
25100        use std::cell::RefCell;
25101        struct PgLikeRecorder {
25102            statements: RefCell<Vec<String>>,
25103        }
25104        impl super::SqlConnection for PgLikeRecorder {
25105            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
25106                Ok(SqlQueryResult {
25107                    columns: vec![],
25108                    rows: vec![],
25109                })
25110            }
25111            fn execute_batch(&self, sql: &str) -> Result<(), IoError> {
25112                self.statements.borrow_mut().push(sql.to_owned());
25113                Ok(())
25114            }
25115            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
25116                Ok(false)
25117            }
25118            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
25119                Ok(())
25120            }
25121            fn dtype_sql(&self, _dtype: DType) -> &'static str {
25122                "TEXT"
25123            }
25124            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
25125                "TEXT"
25126            }
25127            fn supports_schemas(&self) -> bool {
25128                true
25129            }
25130        }
25131        let conn = PgLikeRecorder {
25132            statements: RefCell::new(vec![]),
25133        };
25134        truncate_sql_table(&conn, "events", Some("analytics")).unwrap();
25135        let stmts = conn.statements.borrow();
25136        assert_eq!(stmts.len(), 1);
25137        // Default impl uses DELETE FROM ... and quote_identifier on
25138        // both schema + table parts.
25139        assert!(
25140            stmts[0].contains("DELETE FROM \"analytics\".\"events\""),
25141            "expected schema-qualified DELETE; got: {}",
25142            stmts[0]
25143        );
25144    }
25145
25146    #[test]
25147    fn truncate_sql_table_backend_override_uses_truncate_keyword() {
25148        // PG/MySQL impls would override with TRUNCATE TABLE for speed.
25149        // Verify the trait dispatch picks up the override.
25150        use std::cell::RefCell;
25151        struct FastTruncate {
25152            statements: RefCell<Vec<String>>,
25153        }
25154        impl super::SqlConnection for FastTruncate {
25155            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
25156                Ok(SqlQueryResult {
25157                    columns: vec![],
25158                    rows: vec![],
25159                })
25160            }
25161            fn execute_batch(&self, sql: &str) -> Result<(), IoError> {
25162                self.statements.borrow_mut().push(sql.to_owned());
25163                Ok(())
25164            }
25165            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
25166                Ok(false)
25167            }
25168            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
25169                Ok(())
25170            }
25171            fn dtype_sql(&self, _dtype: DType) -> &'static str {
25172                "TEXT"
25173            }
25174            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
25175                "TEXT"
25176            }
25177            fn truncate_table(
25178                &self,
25179                table_name: &str,
25180                _schema: Option<&str>,
25181            ) -> Result<(), IoError> {
25182                self.execute_batch(&format!("TRUNCATE TABLE \"{table_name}\""))
25183            }
25184        }
25185        let conn = FastTruncate {
25186            statements: RefCell::new(vec![]),
25187        };
25188        truncate_sql_table(&conn, "events", None).unwrap();
25189        let stmts = conn.statements.borrow();
25190        assert_eq!(stmts.len(), 1);
25191        assert!(stmts[0].starts_with("TRUNCATE TABLE"), "got: {}", stmts[0]);
25192    }
25193
25194    // ── sql_server_version / SqlConnection::server_version (br-e23k / fd90.24) ─
25195
25196    #[cfg(feature = "sql-sqlite")]
25197    #[test]
25198    fn sql_server_version_returns_sqlite_version_string() {
25199        let conn = make_sql_test_conn();
25200        let version = sql_server_version(&conn)
25201            .unwrap()
25202            .expect("SQLite reports version");
25203        // Expect dotted-version format like "3.45.1". The parts must be
25204        // non-empty digits — exact value depends on the bundled SQLite.
25205        let parts: Vec<&str> = version.split('.').collect();
25206        assert!(parts.len() >= 2, "expected dotted version; got: {version}");
25207        for part in &parts {
25208            assert!(
25209                !part.is_empty() && part.chars().all(|c| c.is_ascii_digit()),
25210                "expected numeric version parts; got {version}"
25211            );
25212        }
25213    }
25214
25215    #[cfg(feature = "sql-sqlite")]
25216    #[test]
25217    fn sql_server_version_starts_with_three_for_sqlite_3_x() {
25218        // SQLite has been at major version 3 since 2004; bundled
25219        // rusqlite is current (3.40+), so the major must be "3".
25220        let conn = make_sql_test_conn();
25221        let version = sql_server_version(&conn).unwrap().unwrap();
25222        assert!(
25223            version.starts_with("3."),
25224            "expected SQLite 3.x; got {version}"
25225        );
25226    }
25227
25228    #[test]
25229    fn sql_server_version_default_impl_returns_none() {
25230        struct NoIntrospection;
25231        impl super::SqlConnection for NoIntrospection {
25232            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
25233                Ok(SqlQueryResult {
25234                    columns: vec![],
25235                    rows: vec![],
25236                })
25237            }
25238            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
25239                Ok(())
25240            }
25241            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
25242                Ok(false)
25243            }
25244            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
25245                Ok(())
25246            }
25247            fn dtype_sql(&self, _dtype: DType) -> &'static str {
25248                "TEXT"
25249            }
25250            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
25251                "TEXT"
25252            }
25253        }
25254        let conn = NoIntrospection;
25255        assert!(sql_server_version(&conn).unwrap().is_none());
25256    }
25257
25258    #[test]
25259    fn sql_server_version_routes_to_backend_override() {
25260        struct PgLikeStub;
25261        impl super::SqlConnection for PgLikeStub {
25262            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
25263                Ok(SqlQueryResult {
25264                    columns: vec![],
25265                    rows: vec![],
25266                })
25267            }
25268            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
25269                Ok(())
25270            }
25271            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
25272                Ok(false)
25273            }
25274            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
25275                Ok(())
25276            }
25277            fn dtype_sql(&self, _dtype: DType) -> &'static str {
25278                "TEXT"
25279            }
25280            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
25281                "TEXT"
25282            }
25283            fn server_version(&self) -> Result<Option<String>, IoError> {
25284                // Mimic `SHOW server_version` payload.
25285                Ok(Some("16.2".to_owned()))
25286            }
25287        }
25288        let conn = PgLikeStub;
25289        assert_eq!(sql_server_version(&conn).unwrap().as_deref(), Some("16.2"));
25290    }
25291
25292    #[test]
25293    fn sql_server_version_propagates_backend_error() {
25294        struct BrokenIntrospection;
25295        impl super::SqlConnection for BrokenIntrospection {
25296            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
25297                Ok(SqlQueryResult {
25298                    columns: vec![],
25299                    rows: vec![],
25300                })
25301            }
25302            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
25303                Ok(())
25304            }
25305            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
25306                Ok(false)
25307            }
25308            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
25309                Ok(())
25310            }
25311            fn dtype_sql(&self, _dtype: DType) -> &'static str {
25312                "TEXT"
25313            }
25314            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
25315                "TEXT"
25316            }
25317            fn server_version(&self) -> Result<Option<String>, IoError> {
25318                Err(IoError::Sql("connection lost".to_owned()))
25319            }
25320        }
25321        let conn = BrokenIntrospection;
25322        let err = sql_server_version(&conn).expect_err("should surface backend error");
25323        assert!(matches!(err, IoError::Sql(msg) if msg.contains("connection lost")));
25324    }
25325
25326    // ── sql_primary_key_columns / SqlConnection::primary_key_columns
25327    //    (br-uw3y / fd90.25) ────────────────────────────────────────────────
25328
25329    #[cfg(feature = "sql-sqlite")]
25330    #[test]
25331    fn sql_primary_key_columns_unknown_table_returns_empty() {
25332        let conn = make_sql_test_conn();
25333        let pk = sql_primary_key_columns(&conn, "no_such_table", None).unwrap();
25334        assert!(pk.is_empty());
25335    }
25336
25337    #[cfg(feature = "sql-sqlite")]
25338    #[test]
25339    fn sql_primary_key_columns_table_without_pk_returns_empty() {
25340        let conn = make_sql_test_conn();
25341        super::SqlConnection::execute_batch(&conn, "CREATE TABLE no_pk (a INTEGER, b TEXT);")
25342            .unwrap();
25343        let pk = sql_primary_key_columns(&conn, "no_pk", None).unwrap();
25344        assert!(pk.is_empty());
25345    }
25346
25347    #[cfg(feature = "sql-sqlite")]
25348    #[test]
25349    fn sql_primary_key_columns_single_pk() {
25350        let conn = make_sql_test_conn();
25351        super::SqlConnection::execute_batch(
25352            &conn,
25353            "CREATE TABLE single_pk (id INTEGER PRIMARY KEY, name TEXT);",
25354        )
25355        .unwrap();
25356        let pk = sql_primary_key_columns(&conn, "single_pk", None).unwrap();
25357        assert_eq!(pk, vec!["id"]);
25358    }
25359
25360    #[cfg(feature = "sql-sqlite")]
25361    #[test]
25362    fn sql_primary_key_columns_composite_pk_ordered_by_ordinal() {
25363        let conn = make_sql_test_conn();
25364        super::SqlConnection::execute_batch(
25365            &conn,
25366            "CREATE TABLE composite ( \
25367                year INTEGER NOT NULL, \
25368                month INTEGER NOT NULL, \
25369                code TEXT NOT NULL, \
25370                value REAL, \
25371                PRIMARY KEY (year, month, code) \
25372             );",
25373        )
25374        .unwrap();
25375        let pk = sql_primary_key_columns(&conn, "composite", None).unwrap();
25376        // PK declaration order: year, month, code.
25377        assert_eq!(pk, vec!["year", "month", "code"]);
25378    }
25379
25380    #[test]
25381    fn sql_primary_key_columns_default_impl_returns_empty_when_no_introspection() {
25382        // Backend with no table_schema override returns Ok(None) →
25383        // primary_key_columns falls through to empty Vec.
25384        struct NoIntrospection;
25385        impl super::SqlConnection for NoIntrospection {
25386            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
25387                Ok(SqlQueryResult {
25388                    columns: vec![],
25389                    rows: vec![],
25390                })
25391            }
25392            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
25393                Ok(())
25394            }
25395            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
25396                Ok(false)
25397            }
25398            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
25399                Ok(())
25400            }
25401            fn dtype_sql(&self, _dtype: DType) -> &'static str {
25402                "TEXT"
25403            }
25404            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
25405                "TEXT"
25406            }
25407        }
25408        let conn = NoIntrospection;
25409        assert!(
25410            sql_primary_key_columns(&conn, "anything", None)
25411                .unwrap()
25412                .is_empty()
25413        );
25414    }
25415
25416    #[test]
25417    fn sql_primary_key_columns_routes_schema_to_table_schema_override() {
25418        // Backend that returns ordinal-sorted PK columns from a
25419        // multi-schema introspection.
25420        struct MultiSchemaPk;
25421        impl super::SqlConnection for MultiSchemaPk {
25422            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
25423                Ok(SqlQueryResult {
25424                    columns: vec![],
25425                    rows: vec![],
25426                })
25427            }
25428            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
25429                Ok(())
25430            }
25431            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
25432                Ok(false)
25433            }
25434            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
25435                Ok(())
25436            }
25437            fn dtype_sql(&self, _dtype: DType) -> &'static str {
25438                "TEXT"
25439            }
25440            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
25441                "TEXT"
25442            }
25443            fn supports_schemas(&self) -> bool {
25444                true
25445            }
25446            fn table_schema(
25447                &self,
25448                table: &str,
25449                schema: Option<&str>,
25450            ) -> Result<Option<SqlTableSchema>, IoError> {
25451                if table == "events" && schema == Some("analytics") {
25452                    Ok(Some(SqlTableSchema {
25453                        table_name: "events".to_owned(),
25454                        columns: vec![
25455                            // Intentionally out-of-declaration-order to
25456                            // verify the helper sorts by ordinal.
25457                            SqlColumnSchema {
25458                                name: "code".to_owned(),
25459                                declared_type: Some("TEXT".to_owned()),
25460                                nullable: false,
25461                                default_value: None,
25462                                primary_key_ordinal: Some(2),
25463                                comment: None,
25464                                autoincrement: false,
25465                            },
25466                            SqlColumnSchema {
25467                                name: "year".to_owned(),
25468                                declared_type: Some("INTEGER".to_owned()),
25469                                nullable: false,
25470                                default_value: None,
25471                                primary_key_ordinal: Some(0),
25472                                comment: None,
25473                                autoincrement: false,
25474                            },
25475                            SqlColumnSchema {
25476                                name: "value".to_owned(),
25477                                declared_type: Some("REAL".to_owned()),
25478                                nullable: true,
25479                                default_value: None,
25480                                primary_key_ordinal: None,
25481                                comment: None,
25482                                autoincrement: false,
25483                            },
25484                            SqlColumnSchema {
25485                                name: "month".to_owned(),
25486                                declared_type: Some("INTEGER".to_owned()),
25487                                nullable: false,
25488                                default_value: None,
25489                                primary_key_ordinal: Some(1),
25490                                comment: None,
25491                                autoincrement: false,
25492                            },
25493                        ],
25494                    }))
25495                } else {
25496                    Ok(None)
25497                }
25498            }
25499        }
25500        let conn = MultiSchemaPk;
25501        let pk = sql_primary_key_columns(&conn, "events", Some("analytics")).unwrap();
25502        // Sorted by primary_key_ordinal: 0=year, 1=month, 2=code.
25503        assert_eq!(pk, vec!["year", "month", "code"]);
25504        // Wrong schema → empty (table_schema returns None).
25505        assert!(
25506            sql_primary_key_columns(&conn, "events", Some("audit"))
25507                .unwrap()
25508                .is_empty()
25509        );
25510    }
25511
25512    // ── sql_max_identifier_length / SqlConnection::max_identifier_length
25513    //    (br-cs81 / fd90.26) ────────────────────────────────────────────────
25514
25515    #[cfg(feature = "sql-sqlite")]
25516    #[test]
25517    fn sql_max_identifier_length_returns_none_on_sqlite() {
25518        // SQLite has no documented identifier-length limit; the trait
25519        // default (None) is the right answer.
25520        let conn = make_sql_test_conn();
25521        assert_eq!(sql_max_identifier_length(&conn), None);
25522    }
25523
25524    #[test]
25525    fn sql_max_identifier_length_default_impl_returns_none() {
25526        struct Generic;
25527        impl super::SqlConnection for Generic {
25528            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
25529                Ok(SqlQueryResult {
25530                    columns: vec![],
25531                    rows: vec![],
25532                })
25533            }
25534            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
25535                Ok(())
25536            }
25537            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
25538                Ok(false)
25539            }
25540            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
25541                Ok(())
25542            }
25543            fn dtype_sql(&self, _dtype: DType) -> &'static str {
25544                "TEXT"
25545            }
25546            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
25547                "TEXT"
25548            }
25549        }
25550        assert_eq!(sql_max_identifier_length(&Generic), None);
25551    }
25552
25553    #[test]
25554    fn sql_max_identifier_length_pg_override_reports_63() {
25555        struct PgLikeStub;
25556        impl super::SqlConnection for PgLikeStub {
25557            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
25558                Ok(SqlQueryResult {
25559                    columns: vec![],
25560                    rows: vec![],
25561                })
25562            }
25563            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
25564                Ok(())
25565            }
25566            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
25567                Ok(false)
25568            }
25569            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
25570                Ok(())
25571            }
25572            fn dtype_sql(&self, _dtype: DType) -> &'static str {
25573                "TEXT"
25574            }
25575            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
25576                "TEXT"
25577            }
25578            fn max_identifier_length(&self) -> Option<usize> {
25579                Some(63)
25580            }
25581        }
25582        assert_eq!(sql_max_identifier_length(&PgLikeStub), Some(63));
25583    }
25584
25585    #[test]
25586    fn sql_max_identifier_length_mysql_override_reports_64() {
25587        struct MySqlLikeStub;
25588        impl super::SqlConnection for MySqlLikeStub {
25589            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
25590                Ok(SqlQueryResult {
25591                    columns: vec![],
25592                    rows: vec![],
25593                })
25594            }
25595            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
25596                Ok(())
25597            }
25598            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
25599                Ok(false)
25600            }
25601            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
25602                Ok(())
25603            }
25604            fn dtype_sql(&self, _dtype: DType) -> &'static str {
25605                "TEXT"
25606            }
25607            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
25608                "TEXT"
25609            }
25610            fn max_identifier_length(&self) -> Option<usize> {
25611                Some(64)
25612            }
25613        }
25614        assert_eq!(sql_max_identifier_length(&MySqlLikeStub), Some(64));
25615    }
25616
25617    #[test]
25618    fn sql_max_identifier_length_mssql_override_reports_128() {
25619        struct MsSqlLikeStub;
25620        impl super::SqlConnection for MsSqlLikeStub {
25621            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
25622                Ok(SqlQueryResult {
25623                    columns: vec![],
25624                    rows: vec![],
25625                })
25626            }
25627            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
25628                Ok(())
25629            }
25630            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
25631                Ok(false)
25632            }
25633            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
25634                Ok(())
25635            }
25636            fn dtype_sql(&self, _dtype: DType) -> &'static str {
25637                "TEXT"
25638            }
25639            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
25640                "TEXT"
25641            }
25642            fn max_identifier_length(&self) -> Option<usize> {
25643                Some(128)
25644            }
25645        }
25646        assert_eq!(sql_max_identifier_length(&MsSqlLikeStub), Some(128));
25647    }
25648
25649    // ── sql backend capability probes / SqlInspector caps
25650    //    (frankenpandas-fd90.10) ───────────────────────────────────────────
25651
25652    #[cfg(feature = "sql-sqlite")]
25653    #[test]
25654    fn sql_backend_caps_sqlite_reports_param_and_row_caps() {
25655        let conn = make_sql_test_conn();
25656        let caps = sql_backend_caps(&conn).unwrap();
25657
25658        assert_eq!(caps.dialect_name, "sqlite");
25659        assert!(
25660            caps.server_version
25661                .as_deref()
25662                .is_some_and(|v| v.starts_with("3."))
25663        );
25664        assert!(caps.supports_returning);
25665        assert!(!caps.supports_schemas);
25666        assert_eq!(caps.max_param_count, Some(32766));
25667        assert_eq!(caps.max_identifier_length, None);
25668        assert_eq!(caps.max_insert_rows(3), Some(10922));
25669        assert_eq!(caps.max_insert_rows(0), None);
25670        assert_eq!(sql_max_param_count(&conn), Some(32766));
25671        assert_eq!(sql_max_insert_rows(&conn, 4), Some(8191));
25672        assert!(sql_supports_returning(&conn));
25673        assert!(!sql_supports_schemas(&conn));
25674    }
25675
25676    #[test]
25677    fn sql_inspector_backend_caps_pg_like_stub_reports_limits() {
25678        struct PgLikeCaps;
25679        impl super::SqlConnection for PgLikeCaps {
25680            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
25681                Ok(SqlQueryResult {
25682                    columns: vec![],
25683                    rows: vec![],
25684                })
25685            }
25686            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
25687                Ok(())
25688            }
25689            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
25690                Ok(false)
25691            }
25692            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
25693                Ok(())
25694            }
25695            fn dtype_sql(&self, _dtype: DType) -> &'static str {
25696                "TEXT"
25697            }
25698            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
25699                "TEXT"
25700            }
25701            fn dialect_name(&self) -> &'static str {
25702                "postgresql"
25703            }
25704            fn server_version(&self) -> Result<Option<String>, IoError> {
25705                Ok(Some("16.3".to_owned()))
25706            }
25707            fn supports_returning(&self) -> bool {
25708                true
25709            }
25710            fn supports_schemas(&self) -> bool {
25711                true
25712            }
25713            fn max_param_count(&self) -> Option<usize> {
25714                Some(65535)
25715            }
25716            fn max_identifier_length(&self) -> Option<usize> {
25717                Some(63)
25718            }
25719        }
25720
25721        let conn = PgLikeCaps;
25722        let inspector = SqlInspector::new(&conn);
25723        let caps = inspector.backend_caps().unwrap();
25724
25725        assert_eq!(inspector.dialect_name(), "postgresql");
25726        assert_eq!(inspector.server_version().unwrap().as_deref(), Some("16.3"));
25727        assert!(inspector.supports_returning());
25728        assert!(inspector.supports_schemas());
25729        assert_eq!(inspector.max_param_count(), Some(65535));
25730        assert_eq!(inspector.max_identifier_length(), Some(63));
25731        assert_eq!(inspector.max_insert_rows(4), Some(16383));
25732        assert_eq!(caps.max_insert_rows(4), Some(16383));
25733        assert_eq!(
25734            caps,
25735            SqlBackendCaps {
25736                dialect_name: "postgresql",
25737                server_version: Some("16.3".to_owned()),
25738                supports_returning: true,
25739                supports_schemas: true,
25740                max_param_count: Some(65535),
25741                max_identifier_length: Some(63),
25742            }
25743        );
25744    }
25745
25746    // ── write_sql identifier-length validation (br-9ynk / fd90.27) ────────
25747
25748    #[cfg(feature = "sql-sqlite")]
25749    #[test]
25750    fn write_sql_long_column_name_succeeds_on_sqlite() {
25751        // SQLite reports max_identifier_length() == None → no validation.
25752        let conn = make_sql_test_conn();
25753        // 80 chars > PG/MySQL caps but fine on SQLite.
25754        let long_col: String = std::iter::repeat_n('a', 80).collect();
25755        let frame = fp_frame::DataFrame::from_dict(
25756            &[long_col.as_str()],
25757            vec![(long_col.as_str(), vec![Scalar::Int64(1)])],
25758        )
25759        .unwrap();
25760        write_sql_with_options(
25761            &frame,
25762            &conn,
25763            "long_col_tbl",
25764            &SqlWriteOptions {
25765                if_exists: SqlIfExists::Fail,
25766                index: false,
25767                index_label: None,
25768                schema: None,
25769                dtype: None,
25770                method: SqlInsertMethod::Single,
25771                chunksize: None,
25772            },
25773        )
25774        .expect("SQLite has no identifier limit");
25775    }
25776
25777    fn make_pg_like_recorder() -> impl super::SqlConnection + 'static {
25778        // Stub PG-like backend: enforces 63-char limit, accepts all
25779        // execute_batch / insert_rows so write_sql can reach the
25780        // identifier-length check before failing on emit.
25781        struct PgLikeLimit;
25782        impl super::SqlConnection for PgLikeLimit {
25783            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
25784                Ok(SqlQueryResult {
25785                    columns: vec![],
25786                    rows: vec![],
25787                })
25788            }
25789            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
25790                Ok(())
25791            }
25792            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
25793                Ok(false)
25794            }
25795            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
25796                Ok(())
25797            }
25798            fn dtype_sql(&self, _dtype: DType) -> &'static str {
25799                "TEXT"
25800            }
25801            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
25802                "TEXT"
25803            }
25804            fn max_identifier_length(&self) -> Option<usize> {
25805                Some(63)
25806            }
25807            fn supports_schemas(&self) -> bool {
25808                true
25809            }
25810        }
25811        PgLikeLimit
25812    }
25813
25814    #[test]
25815    fn write_sql_rejects_long_column_name_on_pg_like_backend() {
25816        let conn = make_pg_like_recorder();
25817        let long_col: String = std::iter::repeat_n('c', 64).collect();
25818        let frame = fp_frame::DataFrame::from_dict(
25819            &[long_col.as_str()],
25820            vec![(long_col.as_str(), vec![Scalar::Int64(1)])],
25821        )
25822        .unwrap();
25823        let err = write_sql_with_options(
25824            &frame,
25825            &conn,
25826            "ok_tbl",
25827            &SqlWriteOptions {
25828                if_exists: SqlIfExists::Fail,
25829                index: false,
25830                index_label: None,
25831                schema: None,
25832                dtype: None,
25833                method: SqlInsertMethod::Single,
25834                chunksize: None,
25835            },
25836        )
25837        .expect_err("64-char column must exceed PG limit");
25838        assert!(matches!(err, IoError::Sql(msg) if msg.contains("column") && msg.contains("63")));
25839    }
25840
25841    #[test]
25842    fn write_sql_rejects_long_table_name_on_pg_like_backend() {
25843        let conn = make_pg_like_recorder();
25844        // 64-char identifier (table names also subject to the PG cap).
25845        // Use only alphanumeric so validate_sql_table_name passes first.
25846        let long_tbl: String = std::iter::repeat_n('t', 64).collect();
25847        let frame =
25848            fp_frame::DataFrame::from_dict(&["x"], vec![("x", vec![Scalar::Int64(1)])]).unwrap();
25849        let err = write_sql_with_options(
25850            &frame,
25851            &conn,
25852            &long_tbl,
25853            &SqlWriteOptions {
25854                if_exists: SqlIfExists::Fail,
25855                index: false,
25856                index_label: None,
25857                schema: None,
25858                dtype: None,
25859                method: SqlInsertMethod::Single,
25860                chunksize: None,
25861            },
25862        )
25863        .expect_err("64-char table must exceed PG limit");
25864        assert!(matches!(err, IoError::Sql(msg) if msg.contains("table") && msg.contains("63")));
25865    }
25866
25867    #[test]
25868    fn write_sql_rejects_long_index_label_on_pg_like_backend() {
25869        let conn = make_pg_like_recorder();
25870        let long_label: String = std::iter::repeat_n('i', 64).collect();
25871        let frame =
25872            fp_frame::DataFrame::from_dict(&["x"], vec![("x", vec![Scalar::Int64(1)])]).unwrap();
25873        let err = write_sql_with_options(
25874            &frame,
25875            &conn,
25876            "ok_tbl",
25877            &SqlWriteOptions {
25878                if_exists: SqlIfExists::Fail,
25879                index: true,
25880                index_label: Some(long_label),
25881                schema: None,
25882                dtype: None,
25883                method: SqlInsertMethod::Single,
25884                chunksize: None,
25885            },
25886        )
25887        .expect_err("64-char index label must exceed PG limit");
25888        assert!(
25889            matches!(err, IoError::Sql(msg) if msg.contains("index label") && msg.contains("63"))
25890        );
25891    }
25892
25893    #[test]
25894    fn write_sql_rejects_long_schema_name_on_pg_like_backend() {
25895        let conn = make_pg_like_recorder();
25896        let long_schema: String = std::iter::repeat_n('s', 64).collect();
25897        let frame =
25898            fp_frame::DataFrame::from_dict(&["x"], vec![("x", vec![Scalar::Int64(1)])]).unwrap();
25899        let err = write_sql_with_options(
25900            &frame,
25901            &conn,
25902            "ok_tbl",
25903            &SqlWriteOptions {
25904                if_exists: SqlIfExists::Fail,
25905                index: false,
25906                index_label: None,
25907                schema: Some(long_schema),
25908                dtype: None,
25909                method: SqlInsertMethod::Single,
25910                chunksize: None,
25911            },
25912        )
25913        .expect_err("64-char schema must exceed PG limit");
25914        assert!(matches!(err, IoError::Sql(msg) if msg.contains("schema") && msg.contains("63")));
25915    }
25916
25917    #[test]
25918    fn write_sql_just_at_the_boundary_is_accepted() {
25919        let conn = make_pg_like_recorder();
25920        // Exactly 63 chars: at the PG limit, must be accepted.
25921        let just_fits: String = std::iter::repeat_n('a', 63).collect();
25922        let frame = fp_frame::DataFrame::from_dict(
25923            &[just_fits.as_str()],
25924            vec![(just_fits.as_str(), vec![Scalar::Int64(1)])],
25925        )
25926        .unwrap();
25927        write_sql_with_options(
25928            &frame,
25929            &conn,
25930            "ok_tbl",
25931            &SqlWriteOptions {
25932                if_exists: SqlIfExists::Fail,
25933                index: false,
25934                index_label: None,
25935                schema: None,
25936                dtype: None,
25937                method: SqlInsertMethod::Single,
25938                chunksize: None,
25939            },
25940        )
25941        .expect("63-char column at boundary should be accepted");
25942    }
25943
25944    // ── list_sql_indexes / SqlConnection::list_indexes (br-bgv9 / fd90.28) ─
25945
25946    #[cfg(feature = "sql-sqlite")]
25947    #[test]
25948    fn list_sql_indexes_unknown_table_returns_empty() {
25949        let conn = make_sql_test_conn();
25950        let indexes = list_sql_indexes(&conn, "no_such_tbl", None).unwrap();
25951        assert!(indexes.is_empty());
25952    }
25953
25954    #[cfg(feature = "sql-sqlite")]
25955    #[test]
25956    fn list_sql_indexes_table_without_indexes() {
25957        let conn = make_sql_test_conn();
25958        super::SqlConnection::execute_batch(&conn, "CREATE TABLE plain (a INTEGER, b TEXT);")
25959            .unwrap();
25960        let indexes = list_sql_indexes(&conn, "plain", None).unwrap();
25961        assert!(indexes.is_empty());
25962    }
25963
25964    #[cfg(feature = "sql-sqlite")]
25965    #[test]
25966    fn list_sql_indexes_single_column() {
25967        let conn = make_sql_test_conn();
25968        super::SqlConnection::execute_batch(&conn, "CREATE TABLE events (id INTEGER, ts TEXT);")
25969            .unwrap();
25970        super::SqlConnection::execute_batch(&conn, "CREATE INDEX idx_events_ts ON events (ts);")
25971            .unwrap();
25972        let indexes = list_sql_indexes(&conn, "events", None).unwrap();
25973        assert_eq!(indexes.len(), 1);
25974        assert_eq!(indexes[0].name, "idx_events_ts");
25975        assert_eq!(indexes[0].columns, vec!["ts"]);
25976        assert!(!indexes[0].unique);
25977    }
25978
25979    #[cfg(feature = "sql-sqlite")]
25980    #[test]
25981    fn list_sql_indexes_unique_index() {
25982        let conn = make_sql_test_conn();
25983        super::SqlConnection::execute_batch(&conn, "CREATE TABLE users (id INTEGER, email TEXT);")
25984            .unwrap();
25985        super::SqlConnection::execute_batch(
25986            &conn,
25987            "CREATE UNIQUE INDEX idx_users_email ON users (email);",
25988        )
25989        .unwrap();
25990        let indexes = list_sql_indexes(&conn, "users", None).unwrap();
25991        assert_eq!(indexes.len(), 1);
25992        assert_eq!(indexes[0].name, "idx_users_email");
25993        assert_eq!(indexes[0].columns, vec!["email"]);
25994        assert!(indexes[0].unique);
25995    }
25996
25997    #[cfg(feature = "sql-sqlite")]
25998    #[test]
25999    fn list_sql_indexes_composite_columns_in_definition_order() {
26000        let conn = make_sql_test_conn();
26001        super::SqlConnection::execute_batch(
26002            &conn,
26003            "CREATE TABLE rolling (year INT, month INT, code TEXT, val REAL);",
26004        )
26005        .unwrap();
26006        super::SqlConnection::execute_batch(
26007            &conn,
26008            "CREATE INDEX idx_rolling_y_m_c ON rolling (year, month, code);",
26009        )
26010        .unwrap();
26011        let indexes = list_sql_indexes(&conn, "rolling", None).unwrap();
26012        assert_eq!(indexes.len(), 1);
26013        assert_eq!(indexes[0].columns, vec!["year", "month", "code"]);
26014    }
26015
26016    #[cfg(feature = "sql-sqlite")]
26017    #[test]
26018    fn list_sql_indexes_filters_pk_auto_index() {
26019        // INTEGER PRIMARY KEY in SQLite creates an automatic index that
26020        // SQLAlchemy.Inspector hides. We must hide it too — only the
26021        // explicit CREATE INDEX should surface.
26022        let conn = make_sql_test_conn();
26023        super::SqlConnection::execute_batch(
26024            &conn,
26025            "CREATE TABLE pk_only (id INTEGER PRIMARY KEY, name TEXT);",
26026        )
26027        .unwrap();
26028        super::SqlConnection::execute_batch(
26029            &conn,
26030            "CREATE INDEX idx_pk_only_name ON pk_only (name);",
26031        )
26032        .unwrap();
26033        let indexes = list_sql_indexes(&conn, "pk_only", None).unwrap();
26034        // Only the explicit user index should appear.
26035        assert_eq!(indexes.len(), 1);
26036        assert_eq!(indexes[0].name, "idx_pk_only_name");
26037    }
26038
26039    #[cfg(feature = "sql-sqlite")]
26040    #[test]
26041    fn list_sql_indexes_rejects_invalid_table_name() {
26042        let conn = make_sql_test_conn();
26043        let err = list_sql_indexes(&conn, "x; DROP TABLE users", None)
26044            .expect_err("must reject invalid identifier");
26045        assert!(matches!(err, IoError::Sql(msg) if msg.contains("invalid")));
26046    }
26047
26048    #[test]
26049    fn list_sql_indexes_default_impl_returns_empty() {
26050        struct NoIntrospection;
26051        impl super::SqlConnection for NoIntrospection {
26052            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
26053                Ok(SqlQueryResult {
26054                    columns: vec![],
26055                    rows: vec![],
26056                })
26057            }
26058            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
26059                Ok(())
26060            }
26061            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
26062                Ok(false)
26063            }
26064            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
26065                Ok(())
26066            }
26067            fn dtype_sql(&self, _dtype: DType) -> &'static str {
26068                "TEXT"
26069            }
26070            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
26071                "TEXT"
26072            }
26073        }
26074        assert!(
26075            list_sql_indexes(&NoIntrospection, "anything", None)
26076                .unwrap()
26077                .is_empty()
26078        );
26079    }
26080
26081    #[test]
26082    fn list_sql_indexes_routes_to_backend_override() {
26083        struct MultiSchemaIdx;
26084        impl super::SqlConnection for MultiSchemaIdx {
26085            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
26086                Ok(SqlQueryResult {
26087                    columns: vec![],
26088                    rows: vec![],
26089                })
26090            }
26091            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
26092                Ok(())
26093            }
26094            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
26095                Ok(false)
26096            }
26097            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
26098                Ok(())
26099            }
26100            fn dtype_sql(&self, _dtype: DType) -> &'static str {
26101                "TEXT"
26102            }
26103            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
26104                "TEXT"
26105            }
26106            fn supports_schemas(&self) -> bool {
26107                true
26108            }
26109            fn list_indexes(
26110                &self,
26111                table: &str,
26112                schema: Option<&str>,
26113            ) -> Result<Vec<SqlIndexSchema>, IoError> {
26114                if table == "events" && schema == Some("analytics") {
26115                    Ok(vec![
26116                        SqlIndexSchema {
26117                            name: "idx_events_ts".to_owned(),
26118                            columns: vec!["ts".to_owned()],
26119                            unique: false,
26120                        },
26121                        SqlIndexSchema {
26122                            name: "uq_events_uid".to_owned(),
26123                            columns: vec!["user_id".to_owned()],
26124                            unique: true,
26125                        },
26126                    ])
26127                } else {
26128                    Ok(vec![])
26129                }
26130            }
26131        }
26132        let conn = MultiSchemaIdx;
26133        let indexes = list_sql_indexes(&conn, "events", Some("analytics")).unwrap();
26134        assert_eq!(indexes.len(), 2);
26135        assert!(
26136            indexes
26137                .iter()
26138                .any(|i| i.unique && i.name == "uq_events_uid")
26139        );
26140        // Wrong schema → empty (override scopes by Some).
26141        assert!(
26142            list_sql_indexes(&conn, "events", Some("audit"))
26143                .unwrap()
26144                .is_empty()
26145        );
26146    }
26147
26148    // ── list_sql_foreign_keys / SqlConnection::list_foreign_keys
26149    //    (br-uht8 / fd90.29) ────────────────────────────────────────────────
26150
26151    #[cfg(feature = "sql-sqlite")]
26152    #[test]
26153    fn list_sql_foreign_keys_unknown_table_returns_empty() {
26154        let conn = make_sql_test_conn();
26155        let fks = list_sql_foreign_keys(&conn, "no_such_tbl", None).unwrap();
26156        assert!(fks.is_empty());
26157    }
26158
26159    #[cfg(feature = "sql-sqlite")]
26160    #[test]
26161    fn list_sql_foreign_keys_table_without_fk() {
26162        let conn = make_sql_test_conn();
26163        super::SqlConnection::execute_batch(&conn, "CREATE TABLE plain (a INTEGER, b TEXT);")
26164            .unwrap();
26165        let fks = list_sql_foreign_keys(&conn, "plain", None).unwrap();
26166        assert!(fks.is_empty());
26167    }
26168
26169    #[cfg(feature = "sql-sqlite")]
26170    #[test]
26171    fn list_sql_foreign_keys_single_column_fk() {
26172        let conn = make_sql_test_conn();
26173        super::SqlConnection::execute_batch(
26174            &conn,
26175            "CREATE TABLE parent (id INTEGER PRIMARY KEY, label TEXT);",
26176        )
26177        .unwrap();
26178        super::SqlConnection::execute_batch(
26179            &conn,
26180            "CREATE TABLE child (cid INTEGER, parent_id INTEGER, \
26181             FOREIGN KEY (parent_id) REFERENCES parent(id));",
26182        )
26183        .unwrap();
26184        let fks = list_sql_foreign_keys(&conn, "child", None).unwrap();
26185        assert_eq!(fks.len(), 1);
26186        assert_eq!(fks[0].columns, vec!["parent_id"]);
26187        assert_eq!(fks[0].referenced_table, "parent");
26188        assert_eq!(fks[0].referenced_columns, vec!["id"]);
26189        // SQLite PRAGMA does not surface constraint names.
26190        assert!(fks[0].constraint_name.is_none());
26191    }
26192
26193    #[cfg(feature = "sql-sqlite")]
26194    #[test]
26195    fn list_sql_foreign_keys_composite_fk_ordered_by_seq() {
26196        let conn = make_sql_test_conn();
26197        super::SqlConnection::execute_batch(
26198            &conn,
26199            "CREATE TABLE rolling ( \
26200                year INTEGER NOT NULL, \
26201                month INTEGER NOT NULL, \
26202                code TEXT NOT NULL, \
26203                PRIMARY KEY (year, month, code) \
26204             );",
26205        )
26206        .unwrap();
26207        super::SqlConnection::execute_batch(
26208            &conn,
26209            "CREATE TABLE rolling_fact ( \
26210                fact_id INTEGER, year INTEGER, month INTEGER, code TEXT, \
26211                FOREIGN KEY (year, month, code) \
26212                  REFERENCES rolling(year, month, code) \
26213             );",
26214        )
26215        .unwrap();
26216        let fks = list_sql_foreign_keys(&conn, "rolling_fact", None).unwrap();
26217        assert_eq!(fks.len(), 1);
26218        // Pairs preserved in declaration order (seq=0,1,2).
26219        assert_eq!(fks[0].columns, vec!["year", "month", "code"]);
26220        assert_eq!(fks[0].referenced_columns, vec!["year", "month", "code"]);
26221        assert_eq!(fks[0].referenced_table, "rolling");
26222    }
26223
26224    #[cfg(feature = "sql-sqlite")]
26225    #[test]
26226    fn list_sql_foreign_keys_multiple_fks_on_one_table() {
26227        let conn = make_sql_test_conn();
26228        super::SqlConnection::execute_batch(&conn, "CREATE TABLE users (id INTEGER PRIMARY KEY);")
26229            .unwrap();
26230        super::SqlConnection::execute_batch(&conn, "CREATE TABLE products (sku TEXT PRIMARY KEY);")
26231            .unwrap();
26232        super::SqlConnection::execute_batch(
26233            &conn,
26234            "CREATE TABLE orders ( \
26235                oid INTEGER, \
26236                user_id INTEGER, \
26237                product_sku TEXT, \
26238                FOREIGN KEY (user_id) REFERENCES users(id), \
26239                FOREIGN KEY (product_sku) REFERENCES products(sku) \
26240             );",
26241        )
26242        .unwrap();
26243        let fks = list_sql_foreign_keys(&conn, "orders", None).unwrap();
26244        assert_eq!(fks.len(), 2);
26245        let user_fk = fks.iter().find(|f| f.referenced_table == "users").unwrap();
26246        assert_eq!(user_fk.columns, vec!["user_id"]);
26247        assert_eq!(user_fk.referenced_columns, vec!["id"]);
26248        let prod_fk = fks
26249            .iter()
26250            .find(|f| f.referenced_table == "products")
26251            .unwrap();
26252        assert_eq!(prod_fk.columns, vec!["product_sku"]);
26253        assert_eq!(prod_fk.referenced_columns, vec!["sku"]);
26254    }
26255
26256    #[cfg(feature = "sql-sqlite")]
26257    #[test]
26258    fn list_sql_foreign_keys_rejects_invalid_table_name() {
26259        let conn = make_sql_test_conn();
26260        let err = list_sql_foreign_keys(&conn, "x; DROP TABLE users", None)
26261            .expect_err("must reject invalid identifier");
26262        assert!(matches!(err, IoError::Sql(msg) if msg.contains("invalid")));
26263    }
26264
26265    #[cfg(feature = "sql-sqlite")]
26266    #[test]
26267    fn list_sql_foreign_keys_resolves_implicit_pk_single_column() {
26268        // Per fd90.44: FOREIGN KEY (parent_id) REFERENCES parent
26269        // (no column list) is an implicit reference to parent's PK.
26270        // SQLite returns NULL for the 'to' column; we now resolve via
26271        // the parent's primary_key_columns.
26272        let conn = make_sql_test_conn();
26273        super::SqlConnection::execute_batch(
26274            &conn,
26275            "CREATE TABLE imp_parent (pid INTEGER PRIMARY KEY, label TEXT);",
26276        )
26277        .unwrap();
26278        super::SqlConnection::execute_batch(
26279            &conn,
26280            "CREATE TABLE imp_child ( \
26281                cid INTEGER, \
26282                parent_id INTEGER, \
26283                FOREIGN KEY (parent_id) REFERENCES imp_parent \
26284             );",
26285        )
26286        .unwrap();
26287        let fks = list_sql_foreign_keys(&conn, "imp_child", None).unwrap();
26288        assert_eq!(
26289            fks.len(),
26290            1,
26291            "implicit-PK FK must surface (was being silently dropped)"
26292        );
26293        assert_eq!(fks[0].columns, vec!["parent_id"]);
26294        assert_eq!(fks[0].referenced_table, "imp_parent");
26295        // resolved from parent's PK.
26296        assert_eq!(fks[0].referenced_columns, vec!["pid"]);
26297    }
26298
26299    #[cfg(feature = "sql-sqlite")]
26300    #[test]
26301    fn list_sql_foreign_keys_resolves_implicit_pk_composite() {
26302        // Composite FK with implicit reference to composite PK.
26303        let conn = make_sql_test_conn();
26304        super::SqlConnection::execute_batch(
26305            &conn,
26306            "CREATE TABLE imp_parent_comp ( \
26307                year INTEGER NOT NULL, \
26308                month INTEGER NOT NULL, \
26309                PRIMARY KEY (year, month) \
26310             );",
26311        )
26312        .unwrap();
26313        super::SqlConnection::execute_batch(
26314            &conn,
26315            "CREATE TABLE imp_child_comp ( \
26316                cid INTEGER, \
26317                fyear INTEGER NOT NULL, \
26318                fmonth INTEGER NOT NULL, \
26319                FOREIGN KEY (fyear, fmonth) REFERENCES imp_parent_comp \
26320             );",
26321        )
26322        .unwrap();
26323        let fks = list_sql_foreign_keys(&conn, "imp_child_comp", None).unwrap();
26324        assert_eq!(fks.len(), 1);
26325        assert_eq!(fks[0].columns, vec!["fyear", "fmonth"]);
26326        assert_eq!(fks[0].referenced_table, "imp_parent_comp");
26327        // Resolved from composite PK in declaration order.
26328        assert_eq!(fks[0].referenced_columns, vec!["year", "month"]);
26329    }
26330
26331    #[cfg(feature = "sql-sqlite")]
26332    #[test]
26333    fn list_sql_foreign_keys_explicit_columns_unchanged() {
26334        // Existing behavior preserved: explicit columns still
26335        // round-trip exactly as before fd90.44.
26336        let conn = make_sql_test_conn();
26337        super::SqlConnection::execute_batch(
26338            &conn,
26339            "CREATE TABLE exp_parent (pid INTEGER PRIMARY KEY);",
26340        )
26341        .unwrap();
26342        super::SqlConnection::execute_batch(
26343            &conn,
26344            "CREATE TABLE exp_child ( \
26345                cid INTEGER, \
26346                parent_id INTEGER, \
26347                FOREIGN KEY (parent_id) REFERENCES exp_parent(pid) \
26348             );",
26349        )
26350        .unwrap();
26351        let fks = list_sql_foreign_keys(&conn, "exp_child", None).unwrap();
26352        assert_eq!(fks.len(), 1);
26353        assert_eq!(fks[0].columns, vec!["parent_id"]);
26354        assert_eq!(fks[0].referenced_columns, vec!["pid"]);
26355    }
26356
26357    #[test]
26358    fn list_sql_foreign_keys_default_impl_returns_empty() {
26359        struct NoIntrospection;
26360        impl super::SqlConnection for NoIntrospection {
26361            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
26362                Ok(SqlQueryResult {
26363                    columns: vec![],
26364                    rows: vec![],
26365                })
26366            }
26367            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
26368                Ok(())
26369            }
26370            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
26371                Ok(false)
26372            }
26373            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
26374                Ok(())
26375            }
26376            fn dtype_sql(&self, _dtype: DType) -> &'static str {
26377                "TEXT"
26378            }
26379            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
26380                "TEXT"
26381            }
26382        }
26383        assert!(
26384            list_sql_foreign_keys(&NoIntrospection, "anything", None)
26385                .unwrap()
26386                .is_empty()
26387        );
26388    }
26389
26390    #[test]
26391    fn list_sql_foreign_keys_routes_to_backend_override() {
26392        struct MultiSchemaFk;
26393        impl super::SqlConnection for MultiSchemaFk {
26394            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
26395                Ok(SqlQueryResult {
26396                    columns: vec![],
26397                    rows: vec![],
26398                })
26399            }
26400            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
26401                Ok(())
26402            }
26403            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
26404                Ok(false)
26405            }
26406            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
26407                Ok(())
26408            }
26409            fn dtype_sql(&self, _dtype: DType) -> &'static str {
26410                "TEXT"
26411            }
26412            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
26413                "TEXT"
26414            }
26415            fn supports_schemas(&self) -> bool {
26416                true
26417            }
26418            fn list_foreign_keys(
26419                &self,
26420                table: &str,
26421                schema: Option<&str>,
26422            ) -> Result<Vec<SqlForeignKeySchema>, IoError> {
26423                if table == "orders" && schema == Some("sales") {
26424                    Ok(vec![SqlForeignKeySchema {
26425                        constraint_name: Some("orders_user_fk".to_owned()),
26426                        columns: vec!["user_id".to_owned()],
26427                        referenced_table: "users".to_owned(),
26428                        referenced_columns: vec!["id".to_owned()],
26429                    }])
26430                } else {
26431                    Ok(vec![])
26432                }
26433            }
26434        }
26435        let conn = MultiSchemaFk;
26436        let fks = list_sql_foreign_keys(&conn, "orders", Some("sales")).unwrap();
26437        assert_eq!(fks.len(), 1);
26438        assert_eq!(fks[0].constraint_name.as_deref(), Some("orders_user_fk"));
26439        assert_eq!(fks[0].referenced_table, "users");
26440        // Wrong schema → empty (override scopes by Some).
26441        assert!(
26442            list_sql_foreign_keys(&conn, "orders", Some("audit"))
26443                .unwrap()
26444                .is_empty()
26445        );
26446    }
26447
26448    // ── list_sql_views / SqlConnection::list_views (br-gm3r / fd90.30) ────
26449
26450    #[cfg(feature = "sql-sqlite")]
26451    #[test]
26452    fn list_sql_views_empty_db_returns_empty() {
26453        let conn = make_sql_test_conn();
26454        let views = list_sql_views(&conn, None).unwrap();
26455        assert!(views.is_empty());
26456    }
26457
26458    #[cfg(feature = "sql-sqlite")]
26459    #[test]
26460    fn list_sql_views_returns_user_views_sorted() {
26461        let conn = make_sql_test_conn();
26462        super::SqlConnection::execute_batch(&conn, "CREATE TABLE base (id INTEGER, val TEXT);")
26463            .unwrap();
26464        super::SqlConnection::execute_batch(
26465            &conn,
26466            "CREATE VIEW zebra_view AS SELECT id FROM base;",
26467        )
26468        .unwrap();
26469        super::SqlConnection::execute_batch(
26470            &conn,
26471            "CREATE VIEW alpha_view AS SELECT val FROM base;",
26472        )
26473        .unwrap();
26474        let views = list_sql_views(&conn, None).unwrap();
26475        assert_eq!(views, vec!["alpha_view", "zebra_view"]);
26476    }
26477
26478    #[cfg(feature = "sql-sqlite")]
26479    #[test]
26480    fn list_sql_views_separated_from_list_tables() {
26481        // list_views must NOT surface tables; list_tables must NOT surface
26482        // views. The two buckets are disjoint per SQLAlchemy.Inspector.
26483        let conn = make_sql_test_conn();
26484        super::SqlConnection::execute_batch(&conn, "CREATE TABLE just_tbl (x INTEGER);").unwrap();
26485        super::SqlConnection::execute_batch(
26486            &conn,
26487            "CREATE VIEW just_view AS SELECT x FROM just_tbl;",
26488        )
26489        .unwrap();
26490
26491        let tables = list_sql_tables(&conn, None).unwrap();
26492        let views = list_sql_views(&conn, None).unwrap();
26493        assert_eq!(tables, vec!["just_tbl"]);
26494        assert_eq!(views, vec!["just_view"]);
26495        assert!(!tables.contains(&"just_view".to_owned()));
26496        assert!(!views.contains(&"just_tbl".to_owned()));
26497    }
26498
26499    #[cfg(feature = "sql-sqlite")]
26500    #[test]
26501    fn list_sql_views_schema_silently_ignored_on_sqlite() {
26502        let conn = make_sql_test_conn();
26503        super::SqlConnection::execute_batch(&conn, "CREATE TABLE t (x INTEGER);").unwrap();
26504        super::SqlConnection::execute_batch(&conn, "CREATE VIEW v AS SELECT x FROM t;").unwrap();
26505        let with_schema =
26506            list_sql_views(&conn, Some("ignored_on_sqlite")).expect("schema arg must not error");
26507        let without_schema = list_sql_views(&conn, None).unwrap();
26508        assert_eq!(with_schema, without_schema);
26509    }
26510
26511    #[test]
26512    fn list_sql_views_default_impl_returns_empty() {
26513        struct NoIntrospection;
26514        impl super::SqlConnection for NoIntrospection {
26515            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
26516                Ok(SqlQueryResult {
26517                    columns: vec![],
26518                    rows: vec![],
26519                })
26520            }
26521            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
26522                Ok(())
26523            }
26524            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
26525                Ok(false)
26526            }
26527            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
26528                Ok(())
26529            }
26530            fn dtype_sql(&self, _dtype: DType) -> &'static str {
26531                "TEXT"
26532            }
26533            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
26534                "TEXT"
26535            }
26536        }
26537        let conn = NoIntrospection;
26538        assert!(list_sql_views(&conn, None).unwrap().is_empty());
26539        assert!(list_sql_views(&conn, Some("any")).unwrap().is_empty());
26540    }
26541
26542    #[test]
26543    fn list_sql_views_routes_schema_to_backend_override() {
26544        struct MultiSchemaViews;
26545        impl super::SqlConnection for MultiSchemaViews {
26546            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
26547                Ok(SqlQueryResult {
26548                    columns: vec![],
26549                    rows: vec![],
26550                })
26551            }
26552            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
26553                Ok(())
26554            }
26555            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
26556                Ok(false)
26557            }
26558            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
26559                Ok(())
26560            }
26561            fn dtype_sql(&self, _dtype: DType) -> &'static str {
26562                "TEXT"
26563            }
26564            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
26565                "TEXT"
26566            }
26567            fn supports_schemas(&self) -> bool {
26568                true
26569            }
26570            fn list_views(&self, schema: Option<&str>) -> Result<Vec<String>, IoError> {
26571                Ok(match schema {
26572                    Some("reporting") => vec!["daily".to_owned(), "weekly".to_owned()],
26573                    Some("audit") => vec!["log_view".to_owned()],
26574                    _ => vec![],
26575                })
26576            }
26577        }
26578        let conn = MultiSchemaViews;
26579        assert_eq!(
26580            list_sql_views(&conn, Some("reporting")).unwrap(),
26581            vec!["daily", "weekly"]
26582        );
26583        assert_eq!(
26584            list_sql_views(&conn, Some("audit")).unwrap(),
26585            vec!["log_view"]
26586        );
26587        assert!(list_sql_views(&conn, None).unwrap().is_empty());
26588    }
26589
26590    // ── list_sql_unique_constraints / SqlConnection::list_unique_constraints
26591    //    (br-sh4v / fd90.31) ────────────────────────────────────────────────
26592
26593    #[cfg(feature = "sql-sqlite")]
26594    #[test]
26595    fn list_sql_unique_constraints_unknown_table_returns_empty() {
26596        let conn = make_sql_test_conn();
26597        let uqs = list_sql_unique_constraints(&conn, "no_such", None).unwrap();
26598        assert!(uqs.is_empty());
26599    }
26600
26601    #[cfg(feature = "sql-sqlite")]
26602    #[test]
26603    fn list_sql_unique_constraints_table_without_uq() {
26604        let conn = make_sql_test_conn();
26605        super::SqlConnection::execute_batch(&conn, "CREATE TABLE plain (a INTEGER, b TEXT);")
26606            .unwrap();
26607        let uqs = list_sql_unique_constraints(&conn, "plain", None).unwrap();
26608        assert!(uqs.is_empty());
26609    }
26610
26611    #[cfg(feature = "sql-sqlite")]
26612    #[test]
26613    fn list_sql_unique_constraints_inline_unique() {
26614        let conn = make_sql_test_conn();
26615        super::SqlConnection::execute_batch(
26616            &conn,
26617            "CREATE TABLE users (id INTEGER PRIMARY KEY, email TEXT UNIQUE);",
26618        )
26619        .unwrap();
26620        let uqs = list_sql_unique_constraints(&conn, "users", None).unwrap();
26621        assert_eq!(uqs.len(), 1);
26622        assert_eq!(uqs[0].columns, vec!["email"]);
26623        // SQLite gives backend-generated names like sqlite_autoindex_users_1.
26624        assert!(
26625            uqs[0].name.starts_with("sqlite_autoindex_users_"),
26626            "expected sqlite_autoindex_ name; got {}",
26627            uqs[0].name
26628        );
26629    }
26630
26631    #[cfg(feature = "sql-sqlite")]
26632    #[test]
26633    fn list_sql_unique_constraints_composite_table_constraint() {
26634        let conn = make_sql_test_conn();
26635        super::SqlConnection::execute_batch(
26636            &conn,
26637            "CREATE TABLE rolling ( \
26638                year INTEGER, month INTEGER, code TEXT, val REAL, \
26639                UNIQUE (year, month, code) \
26640             );",
26641        )
26642        .unwrap();
26643        let uqs = list_sql_unique_constraints(&conn, "rolling", None).unwrap();
26644        assert_eq!(uqs.len(), 1);
26645        assert_eq!(uqs[0].columns, vec!["year", "month", "code"]);
26646    }
26647
26648    #[cfg(feature = "sql-sqlite")]
26649    #[test]
26650    fn list_sql_unique_constraints_disjoint_from_create_unique_index() {
26651        // Per SQLAlchemy: get_unique_constraints surfaces declared UNIQUE
26652        // constraints (origin='u'); get_indexes surfaces user-created
26653        // CREATE UNIQUE INDEX (origin='c'). The two must be disjoint.
26654        let conn = make_sql_test_conn();
26655        super::SqlConnection::execute_batch(
26656            &conn,
26657            "CREATE TABLE mixed ( \
26658                a INTEGER, \
26659                b TEXT, \
26660                c TEXT, \
26661                UNIQUE (a) \
26662             );",
26663        )
26664        .unwrap();
26665        super::SqlConnection::execute_batch(&conn, "CREATE UNIQUE INDEX idx_mixed_b ON mixed (b);")
26666            .unwrap();
26667
26668        let uqs = list_sql_unique_constraints(&conn, "mixed", None).unwrap();
26669        let idxs = list_sql_indexes(&conn, "mixed", None).unwrap();
26670
26671        // The UNIQUE constraint is in uqs only.
26672        assert_eq!(uqs.len(), 1);
26673        assert_eq!(uqs[0].columns, vec!["a"]);
26674        // The CREATE UNIQUE INDEX is in idxs only.
26675        assert_eq!(idxs.len(), 1);
26676        assert_eq!(idxs[0].name, "idx_mixed_b");
26677        assert!(idxs[0].unique);
26678        assert_eq!(idxs[0].columns, vec!["b"]);
26679
26680        // No overlap by name (uqs uses sqlite_autoindex_, idxs uses idx_).
26681        assert!(!uqs.iter().any(|u| u.name == "idx_mixed_b"));
26682        assert!(!idxs.iter().any(|i| i.name.starts_with("sqlite_autoindex_")));
26683    }
26684
26685    #[cfg(feature = "sql-sqlite")]
26686    #[test]
26687    fn list_sql_unique_constraints_rejects_invalid_table_name() {
26688        let conn = make_sql_test_conn();
26689        let err = list_sql_unique_constraints(&conn, "x; DROP TABLE users", None)
26690            .expect_err("must reject invalid identifier");
26691        assert!(matches!(err, IoError::Sql(msg) if msg.contains("invalid")));
26692    }
26693
26694    #[test]
26695    fn list_sql_unique_constraints_default_impl_returns_empty() {
26696        struct NoIntrospection;
26697        impl super::SqlConnection for NoIntrospection {
26698            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
26699                Ok(SqlQueryResult {
26700                    columns: vec![],
26701                    rows: vec![],
26702                })
26703            }
26704            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
26705                Ok(())
26706            }
26707            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
26708                Ok(false)
26709            }
26710            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
26711                Ok(())
26712            }
26713            fn dtype_sql(&self, _dtype: DType) -> &'static str {
26714                "TEXT"
26715            }
26716            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
26717                "TEXT"
26718            }
26719        }
26720        assert!(
26721            list_sql_unique_constraints(&NoIntrospection, "anything", None)
26722                .unwrap()
26723                .is_empty()
26724        );
26725    }
26726
26727    #[test]
26728    fn list_sql_unique_constraints_routes_to_backend_override() {
26729        struct MultiSchemaUq;
26730        impl super::SqlConnection for MultiSchemaUq {
26731            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
26732                Ok(SqlQueryResult {
26733                    columns: vec![],
26734                    rows: vec![],
26735                })
26736            }
26737            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
26738                Ok(())
26739            }
26740            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
26741                Ok(false)
26742            }
26743            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
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 supports_schemas(&self) -> bool {
26753                true
26754            }
26755            fn list_unique_constraints(
26756                &self,
26757                table: &str,
26758                schema: Option<&str>,
26759            ) -> Result<Vec<SqlUniqueConstraintSchema>, IoError> {
26760                if table == "users" && schema == Some("public") {
26761                    Ok(vec![SqlUniqueConstraintSchema {
26762                        name: "users_email_key".to_owned(),
26763                        columns: vec!["email".to_owned()],
26764                    }])
26765                } else {
26766                    Ok(vec![])
26767                }
26768            }
26769        }
26770        let conn = MultiSchemaUq;
26771        let uqs = list_sql_unique_constraints(&conn, "users", Some("public")).unwrap();
26772        assert_eq!(uqs.len(), 1);
26773        assert_eq!(uqs[0].name, "users_email_key");
26774        assert!(
26775            list_sql_unique_constraints(&conn, "users", Some("audit"))
26776                .unwrap()
26777                .is_empty()
26778        );
26779    }
26780
26781    // ── sql_table_comment / SqlConnection::table_comment (br-yu3w / fd90.32) ─
26782
26783    #[cfg(feature = "sql-sqlite")]
26784    #[test]
26785    fn sql_table_comment_returns_none_on_sqlite() {
26786        // SQLite has no native table-comment storage; the trait default
26787        // returns None even for a real table.
26788        let conn = make_sql_test_conn();
26789        super::SqlConnection::execute_batch(&conn, "CREATE TABLE t (x INTEGER);").unwrap();
26790        let comment = sql_table_comment(&conn, "t", None).unwrap();
26791        assert!(comment.is_none());
26792    }
26793
26794    #[cfg(feature = "sql-sqlite")]
26795    #[test]
26796    fn sql_table_comment_returns_none_on_sqlite_for_unknown_table() {
26797        let conn = make_sql_test_conn();
26798        let comment = sql_table_comment(&conn, "no_such", None).unwrap();
26799        assert!(comment.is_none());
26800    }
26801
26802    #[test]
26803    fn sql_table_comment_default_impl_returns_none() {
26804        struct NoIntrospection;
26805        impl super::SqlConnection for NoIntrospection {
26806            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
26807                Ok(SqlQueryResult {
26808                    columns: vec![],
26809                    rows: vec![],
26810                })
26811            }
26812            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
26813                Ok(())
26814            }
26815            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
26816                Ok(false)
26817            }
26818            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
26819                Ok(())
26820            }
26821            fn dtype_sql(&self, _dtype: DType) -> &'static str {
26822                "TEXT"
26823            }
26824            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
26825                "TEXT"
26826            }
26827        }
26828        let conn = NoIntrospection;
26829        assert!(
26830            sql_table_comment(&conn, "anything", None)
26831                .unwrap()
26832                .is_none()
26833        );
26834    }
26835
26836    #[test]
26837    fn sql_table_comment_routes_to_backend_override() {
26838        struct PgLikeStub;
26839        impl super::SqlConnection for PgLikeStub {
26840            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
26841                Ok(SqlQueryResult {
26842                    columns: vec![],
26843                    rows: vec![],
26844                })
26845            }
26846            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
26847                Ok(())
26848            }
26849            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
26850                Ok(false)
26851            }
26852            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
26853                Ok(())
26854            }
26855            fn dtype_sql(&self, _dtype: DType) -> &'static str {
26856                "TEXT"
26857            }
26858            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
26859                "TEXT"
26860            }
26861            fn supports_schemas(&self) -> bool {
26862                true
26863            }
26864            fn table_comment(
26865                &self,
26866                table: &str,
26867                schema: Option<&str>,
26868            ) -> Result<Option<String>, IoError> {
26869                if table == "users" && schema == Some("public") {
26870                    Ok(Some("Customer accounts table".to_owned()))
26871                } else {
26872                    Ok(None)
26873                }
26874            }
26875        }
26876        let conn = PgLikeStub;
26877        assert_eq!(
26878            sql_table_comment(&conn, "users", Some("public"))
26879                .unwrap()
26880                .as_deref(),
26881            Some("Customer accounts table")
26882        );
26883        assert!(
26884            sql_table_comment(&conn, "users", Some("audit"))
26885                .unwrap()
26886                .is_none()
26887        );
26888        assert!(
26889            sql_table_comment(&conn, "missing", Some("public"))
26890                .unwrap()
26891                .is_none()
26892        );
26893    }
26894
26895    #[test]
26896    fn sql_table_comment_propagates_backend_error() {
26897        struct BrokenIntrospection;
26898        impl super::SqlConnection for BrokenIntrospection {
26899            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
26900                Ok(SqlQueryResult {
26901                    columns: vec![],
26902                    rows: vec![],
26903                })
26904            }
26905            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
26906                Ok(())
26907            }
26908            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
26909                Ok(false)
26910            }
26911            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
26912                Ok(())
26913            }
26914            fn dtype_sql(&self, _dtype: DType) -> &'static str {
26915                "TEXT"
26916            }
26917            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
26918                "TEXT"
26919            }
26920            fn table_comment(
26921                &self,
26922                _table: &str,
26923                _schema: Option<&str>,
26924            ) -> Result<Option<String>, IoError> {
26925                Err(IoError::Sql(
26926                    "permission denied for pg_description".to_owned(),
26927                ))
26928            }
26929        }
26930        let conn = BrokenIntrospection;
26931        let err =
26932            sql_table_comment(&conn, "anything", None).expect_err("backend error must surface");
26933        assert!(matches!(err, IoError::Sql(msg) if msg.contains("permission denied")));
26934    }
26935
26936    // ── SqlWriteOptions::chunksize (br-ls9z / fd90.33) ────────────────────
26937
26938    #[cfg(feature = "sql-sqlite")]
26939    #[test]
26940    fn write_sql_chunksize_zero_rejected() {
26941        let conn = make_sql_test_conn();
26942        let frame =
26943            fp_frame::DataFrame::from_dict(&["x"], vec![("x", vec![Scalar::Int64(1)])]).unwrap();
26944        let err = write_sql_with_options(
26945            &frame,
26946            &conn,
26947            "t",
26948            &SqlWriteOptions {
26949                if_exists: SqlIfExists::Fail,
26950                index: false,
26951                index_label: None,
26952                schema: None,
26953                dtype: None,
26954                method: SqlInsertMethod::Single,
26955                chunksize: Some(0),
26956            },
26957        )
26958        .expect_err("chunksize=0 must be rejected");
26959        assert!(matches!(err, IoError::Sql(msg) if msg.contains("chunksize")));
26960    }
26961
26962    #[cfg(feature = "sql-sqlite")]
26963    #[test]
26964    fn write_sql_chunksize_none_preserves_single_transaction_semantics() {
26965        // 5 rows, chunksize=None — should round-trip cleanly into one
26966        // transaction (same as before fd90.33 landed).
26967        let conn = make_sql_test_conn();
26968        let frame = fp_frame::DataFrame::from_dict(
26969            &["id"],
26970            vec![(
26971                "id",
26972                vec![
26973                    Scalar::Int64(1),
26974                    Scalar::Int64(2),
26975                    Scalar::Int64(3),
26976                    Scalar::Int64(4),
26977                    Scalar::Int64(5),
26978                ],
26979            )],
26980        )
26981        .unwrap();
26982        write_sql_with_options(
26983            &frame,
26984            &conn,
26985            "no_chunk",
26986            &SqlWriteOptions {
26987                if_exists: SqlIfExists::Fail,
26988                index: false,
26989                index_label: None,
26990                schema: None,
26991                dtype: None,
26992                method: SqlInsertMethod::Single,
26993                chunksize: None,
26994            },
26995        )
26996        .unwrap();
26997        let count =
26998            super::SqlConnection::query(&conn, "SELECT COUNT(*) FROM no_chunk", &[]).unwrap();
26999        assert_eq!(count.rows[0][0], Scalar::Int64(5));
27000    }
27001
27002    #[cfg(feature = "sql-sqlite")]
27003    #[test]
27004    fn write_sql_single_chunksize_round_trips_all_rows() {
27005        // 5 rows with chunksize=2: chunks of (2, 2, 1). All rows must
27006        // round-trip and the table must contain every row regardless
27007        // of how the chunks committed.
27008        let conn = make_sql_test_conn();
27009        let frame = fp_frame::DataFrame::from_dict(
27010            &["id"],
27011            vec![(
27012                "id",
27013                vec![
27014                    Scalar::Int64(1),
27015                    Scalar::Int64(2),
27016                    Scalar::Int64(3),
27017                    Scalar::Int64(4),
27018                    Scalar::Int64(5),
27019                ],
27020            )],
27021        )
27022        .unwrap();
27023        write_sql_with_options(
27024            &frame,
27025            &conn,
27026            "chunked",
27027            &SqlWriteOptions {
27028                if_exists: SqlIfExists::Fail,
27029                index: false,
27030                index_label: None,
27031                schema: None,
27032                dtype: None,
27033                method: SqlInsertMethod::Single,
27034                chunksize: Some(2),
27035            },
27036        )
27037        .unwrap();
27038        let result =
27039            super::SqlConnection::query(&conn, "SELECT id FROM chunked ORDER BY id", &[]).unwrap();
27040        let ids: Vec<i64> = result
27041            .rows
27042            .iter()
27043            .map(|r| match &r[0] {
27044                Scalar::Int64(v) => *v,
27045                other => unreachable!("unexpected scalar: {other:?}"),
27046            })
27047            .collect();
27048        assert_eq!(ids, vec![1, 2, 3, 4, 5]);
27049    }
27050
27051    #[test]
27052    fn write_sql_single_chunksize_dispatches_correct_chunk_counts() {
27053        // Recording stub verifies the chunk boundaries.
27054        use std::cell::RefCell;
27055        struct Recorder {
27056            row_counts: RefCell<Vec<usize>>,
27057        }
27058        impl super::SqlConnection for Recorder {
27059            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
27060                Ok(SqlQueryResult {
27061                    columns: vec![],
27062                    rows: vec![],
27063                })
27064            }
27065            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
27066                Ok(())
27067            }
27068            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
27069                Ok(false)
27070            }
27071            fn insert_rows(&self, _sql: &str, rows: &[Vec<Scalar>]) -> Result<(), IoError> {
27072                self.row_counts.borrow_mut().push(rows.len());
27073                Ok(())
27074            }
27075            fn dtype_sql(&self, _dtype: DType) -> &'static str {
27076                "TEXT"
27077            }
27078            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
27079                "TEXT"
27080            }
27081        }
27082        let conn = Recorder {
27083            row_counts: RefCell::new(vec![]),
27084        };
27085        let frame = fp_frame::DataFrame::from_dict(
27086            &["x"],
27087            vec![(
27088                "x",
27089                vec![
27090                    Scalar::Int64(1),
27091                    Scalar::Int64(2),
27092                    Scalar::Int64(3),
27093                    Scalar::Int64(4),
27094                    Scalar::Int64(5),
27095                ],
27096            )],
27097        )
27098        .unwrap();
27099        write_sql_with_options(
27100            &frame,
27101            &conn,
27102            "chunked",
27103            &SqlWriteOptions {
27104                if_exists: SqlIfExists::Fail,
27105                index: false,
27106                index_label: None,
27107                schema: None,
27108                dtype: None,
27109                method: SqlInsertMethod::Single,
27110                chunksize: Some(2),
27111            },
27112        )
27113        .unwrap();
27114        // Single mode: each chunk submits a slice of rows to insert_rows.
27115        // chunks of size 2, 2, 1 → 3 calls with row counts [2, 2, 1].
27116        assert_eq!(*conn.row_counts.borrow(), vec![2usize, 2, 1]);
27117    }
27118
27119    #[test]
27120    fn write_sql_multi_chunksize_takes_min_with_param_cap() {
27121        // Multi mode with max_param_count=10, ncols=2 → param chunk = 5
27122        // rows. chunksize=3 should win (min(3, 5) = 3).
27123        // Multi mode flattens each chunk to a single insert_rows call
27124        // where rows[0].len() = chunk_size * ncols.
27125        use std::cell::RefCell;
27126        struct ParamCapRecorder {
27127            row_counts: RefCell<Vec<usize>>,
27128        }
27129        impl super::SqlConnection for ParamCapRecorder {
27130            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
27131                Ok(SqlQueryResult {
27132                    columns: vec![],
27133                    rows: vec![],
27134                })
27135            }
27136            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
27137                Ok(())
27138            }
27139            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
27140                Ok(false)
27141            }
27142            fn insert_rows(&self, _sql: &str, rows: &[Vec<Scalar>]) -> Result<(), IoError> {
27143                // Multi mode passes a single flattened "row" per chunk.
27144                self.row_counts
27145                    .borrow_mut()
27146                    .push(rows.first().map_or(0, std::vec::Vec::len));
27147                Ok(())
27148            }
27149            fn dtype_sql(&self, _dtype: DType) -> &'static str {
27150                "TEXT"
27151            }
27152            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
27153                "TEXT"
27154            }
27155            fn max_param_count(&self) -> Option<usize> {
27156                Some(10)
27157            }
27158        }
27159        let conn = ParamCapRecorder {
27160            row_counts: RefCell::new(vec![]),
27161        };
27162        let frame = fp_frame::DataFrame::from_dict(
27163            &["a", "b"],
27164            vec![
27165                (
27166                    "a",
27167                    vec![
27168                        Scalar::Int64(1),
27169                        Scalar::Int64(2),
27170                        Scalar::Int64(3),
27171                        Scalar::Int64(4),
27172                        Scalar::Int64(5),
27173                    ],
27174                ),
27175                (
27176                    "b",
27177                    vec![
27178                        Scalar::Int64(10),
27179                        Scalar::Int64(20),
27180                        Scalar::Int64(30),
27181                        Scalar::Int64(40),
27182                        Scalar::Int64(50),
27183                    ],
27184                ),
27185            ],
27186        )
27187        .unwrap();
27188        write_sql_with_options(
27189            &frame,
27190            &conn,
27191            "chunked",
27192            &SqlWriteOptions {
27193                if_exists: SqlIfExists::Fail,
27194                index: false,
27195                index_label: None,
27196                schema: None,
27197                dtype: None,
27198                method: SqlInsertMethod::Multi,
27199                chunksize: Some(3),
27200            },
27201        )
27202        .unwrap();
27203        // chunksize=3 wins over param cap (5). 5 rows / 3 per chunk = 2
27204        // chunks (3, 2). Flat scalars per chunk: 3*2=6 then 2*2=4.
27205        assert_eq!(*conn.row_counts.borrow(), vec![6usize, 4]);
27206    }
27207
27208    #[test]
27209    fn write_sql_multi_chunksize_param_cap_wins_when_smaller() {
27210        // Param cap = 4 (ncols=2 → 2 rows/chunk). chunksize=10 (loose).
27211        // Effective chunk = min(10, 2) = 2.
27212        use std::cell::RefCell;
27213        struct TightCap {
27214            row_counts: RefCell<Vec<usize>>,
27215        }
27216        impl super::SqlConnection for TightCap {
27217            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
27218                Ok(SqlQueryResult {
27219                    columns: vec![],
27220                    rows: vec![],
27221                })
27222            }
27223            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
27224                Ok(())
27225            }
27226            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
27227                Ok(false)
27228            }
27229            fn insert_rows(&self, _sql: &str, rows: &[Vec<Scalar>]) -> Result<(), IoError> {
27230                self.row_counts
27231                    .borrow_mut()
27232                    .push(rows.first().map_or(0, std::vec::Vec::len));
27233                Ok(())
27234            }
27235            fn dtype_sql(&self, _dtype: DType) -> &'static str {
27236                "TEXT"
27237            }
27238            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
27239                "TEXT"
27240            }
27241            fn max_param_count(&self) -> Option<usize> {
27242                Some(4)
27243            }
27244        }
27245        let conn = TightCap {
27246            row_counts: RefCell::new(vec![]),
27247        };
27248        let frame = fp_frame::DataFrame::from_dict(
27249            &["a", "b"],
27250            vec![
27251                (
27252                    "a",
27253                    vec![
27254                        Scalar::Int64(1),
27255                        Scalar::Int64(2),
27256                        Scalar::Int64(3),
27257                        Scalar::Int64(4),
27258                        Scalar::Int64(5),
27259                    ],
27260                ),
27261                (
27262                    "b",
27263                    vec![
27264                        Scalar::Int64(10),
27265                        Scalar::Int64(20),
27266                        Scalar::Int64(30),
27267                        Scalar::Int64(40),
27268                        Scalar::Int64(50),
27269                    ],
27270                ),
27271            ],
27272        )
27273        .unwrap();
27274        write_sql_with_options(
27275            &frame,
27276            &conn,
27277            "chunked",
27278            &SqlWriteOptions {
27279                if_exists: SqlIfExists::Fail,
27280                index: false,
27281                index_label: None,
27282                schema: None,
27283                dtype: None,
27284                method: SqlInsertMethod::Multi,
27285                chunksize: Some(10),
27286            },
27287        )
27288        .unwrap();
27289        // 5 rows / 2 per chunk = 3 chunks (2, 2, 1). Flat scalars: 4, 4, 2.
27290        assert_eq!(*conn.row_counts.borrow(), vec![4usize, 4, 2]);
27291    }
27292
27293    // ── SqlReadOptions::columns (br-d3e9 / fd90.34) ──────────────────────
27294
27295    #[cfg(feature = "sql-sqlite")]
27296    #[test]
27297    fn read_sql_table_with_options_columns_none_selects_all() {
27298        let conn = make_sql_test_conn();
27299        super::SqlConnection::execute_batch(
27300            &conn,
27301            "CREATE TABLE projection_default (a INTEGER, b TEXT, c REAL);",
27302        )
27303        .unwrap();
27304        super::SqlConnection::execute_batch(
27305            &conn,
27306            "INSERT INTO projection_default VALUES (1, 'x', 1.5);",
27307        )
27308        .unwrap();
27309        let frame = read_sql_table_with_options(
27310            &conn,
27311            "projection_default",
27312            &SqlReadOptions {
27313                columns: None,
27314                ..Default::default()
27315            },
27316        )
27317        .unwrap();
27318        assert_eq!(frame.column_names(), vec!["a", "b", "c"]);
27319    }
27320
27321    #[cfg(feature = "sql-sqlite")]
27322    #[test]
27323    fn read_sql_table_with_options_columns_projects_subset() {
27324        let conn = make_sql_test_conn();
27325        super::SqlConnection::execute_batch(
27326            &conn,
27327            "CREATE TABLE projection (id INTEGER, name TEXT, ts TEXT, value REAL);",
27328        )
27329        .unwrap();
27330        super::SqlConnection::execute_batch(
27331            &conn,
27332            "INSERT INTO projection VALUES (1, 'a', '2024-01-01', 1.5), \
27333                                            (2, 'b', '2024-01-02', 2.5);",
27334        )
27335        .unwrap();
27336        let frame = read_sql_table_with_options(
27337            &conn,
27338            "projection",
27339            &SqlReadOptions {
27340                columns: Some(vec!["id".to_owned(), "name".to_owned()]),
27341                ..Default::default()
27342            },
27343        )
27344        .unwrap();
27345        // Only id + name, in that order.
27346        assert_eq!(frame.column_names(), vec!["id", "name"]);
27347        assert_eq!(frame.column("id").unwrap().values()[0], Scalar::Int64(1));
27348        assert_eq!(
27349            frame.column("name").unwrap().values()[0],
27350            Scalar::Utf8("a".into())
27351        );
27352    }
27353
27354    #[cfg(feature = "sql-sqlite")]
27355    #[test]
27356    fn read_sql_table_with_options_columns_preserves_specified_order() {
27357        // pandas: pd.read_sql_table(t, con, columns=['c', 'a']) →
27358        // returns ['c', 'a'] in that exact order, NOT alphabetical.
27359        let conn = make_sql_test_conn();
27360        super::SqlConnection::execute_batch(
27361            &conn,
27362            "CREATE TABLE ordered_proj (a INT, b INT, c INT);",
27363        )
27364        .unwrap();
27365        super::SqlConnection::execute_batch(&conn, "INSERT INTO ordered_proj VALUES (1, 2, 3);")
27366            .unwrap();
27367        let frame = read_sql_table_with_options(
27368            &conn,
27369            "ordered_proj",
27370            &SqlReadOptions {
27371                columns: Some(vec!["c".to_owned(), "a".to_owned()]),
27372                ..Default::default()
27373            },
27374        )
27375        .unwrap();
27376        assert_eq!(frame.column_names(), vec!["c", "a"]);
27377    }
27378
27379    #[cfg(feature = "sql-sqlite")]
27380    #[test]
27381    fn read_sql_table_with_options_columns_empty_vec_rejected() {
27382        let conn = make_sql_test_conn();
27383        super::SqlConnection::execute_batch(&conn, "CREATE TABLE t (x INTEGER);").unwrap();
27384        let err = read_sql_table_with_options(
27385            &conn,
27386            "t",
27387            &SqlReadOptions {
27388                columns: Some(vec![]),
27389                ..Default::default()
27390            },
27391        )
27392        .expect_err("empty columns must be rejected");
27393        assert!(matches!(err, IoError::Sql(msg) if msg.contains("columns must be non-empty")));
27394    }
27395
27396    #[cfg(feature = "sql-sqlite")]
27397    #[test]
27398    fn read_sql_table_with_options_columns_invalid_name_rejected() {
27399        let conn = make_sql_test_conn();
27400        super::SqlConnection::execute_batch(&conn, "CREATE TABLE t (x INTEGER);").unwrap();
27401        let err = read_sql_table_with_options(
27402            &conn,
27403            "t",
27404            &SqlReadOptions {
27405                columns: Some(vec!["x; DROP TABLE t".to_owned()]),
27406                ..Default::default()
27407            },
27408        )
27409        .expect_err("invalid column name must be rejected");
27410        assert!(matches!(err, IoError::Sql(msg) if msg.contains("invalid")));
27411    }
27412
27413    #[cfg(feature = "sql-sqlite")]
27414    #[test]
27415    fn read_sql_table_with_options_columns_combines_with_parse_dates() {
27416        // columns + parse_dates: project a subset, then date-coerce.
27417        let conn = make_sql_test_conn();
27418        super::SqlConnection::execute_batch(
27419            &conn,
27420            "CREATE TABLE events (id INT, ts TEXT, note TEXT);",
27421        )
27422        .unwrap();
27423        super::SqlConnection::execute_batch(
27424            &conn,
27425            "INSERT INTO events VALUES (1, '2024-01-15', 'launched');",
27426        )
27427        .unwrap();
27428        let frame = read_sql_table_with_options(
27429            &conn,
27430            "events",
27431            &SqlReadOptions {
27432                columns: Some(vec!["id".to_owned(), "ts".to_owned()]),
27433                index_col: None,
27434                parse_dates: Some(vec!["ts".to_owned()]),
27435                ..Default::default()
27436            },
27437        )
27438        .unwrap();
27439        // Only id + ts surfaced; ts was coerced by parse_dates into a typed
27440        // Datetime64[ns] column (br-frankenpandas-0ezw7).
27441        assert_eq!(frame.column_names(), vec!["id", "ts"]);
27442        assert_eq!(
27443            frame.column("ts").unwrap().values()[0],
27444            Scalar::Datetime64(1_705_276_800_000_000_000)
27445        );
27446    }
27447
27448    #[cfg(feature = "sql-sqlite")]
27449    #[test]
27450    fn read_sql_table_chunks_with_options_columns_projects_before_chunking() {
27451        let conn = make_sql_test_conn();
27452        super::SqlConnection::execute_batch(
27453            &conn,
27454            "CREATE TABLE chunk_projection (id INTEGER, name TEXT, hidden REAL);",
27455        )
27456        .unwrap();
27457        super::SqlConnection::execute_batch(
27458            &conn,
27459            "INSERT INTO chunk_projection VALUES \
27460                (1, 'a', 10.0), \
27461                (2, 'b', 20.0), \
27462                (3, 'c', 30.0);",
27463        )
27464        .unwrap();
27465
27466        let chunks: Vec<DataFrame> = read_sql_table_chunks_with_options(
27467            &conn,
27468            "chunk_projection",
27469            &SqlReadOptions {
27470                columns: Some(vec!["name".to_owned(), "id".to_owned()]),
27471                ..Default::default()
27472            },
27473            2,
27474        )
27475        .unwrap()
27476        .collect::<Result<Vec<_>, _>>()
27477        .unwrap();
27478
27479        assert_eq!(chunks.len(), 2);
27480        assert_eq!(chunks[0].column_names(), vec!["name", "id"]);
27481        assert_eq!(chunks[1].column_names(), vec!["name", "id"]);
27482        assert_eq!(
27483            chunks[0].column("name").unwrap().values(),
27484            &[Scalar::Utf8("a".into()), Scalar::Utf8("b".into())]
27485        );
27486        assert_eq!(
27487            chunks[1].column("id").unwrap().values(),
27488            &[Scalar::Int64(3)]
27489        );
27490        assert!(chunks[0].column("hidden").is_none());
27491    }
27492
27493    #[test]
27494    fn read_sql_table_chunks_with_options_schema_projects_before_chunking() {
27495        use std::cell::RefCell;
27496
27497        struct MultiSchemaProjectedChunks {
27498            queries: RefCell<Vec<String>>,
27499        }
27500
27501        impl super::SqlConnection for MultiSchemaProjectedChunks {
27502            fn query(&self, query: &str, _params: &[Scalar]) -> Result<SqlQueryResult, IoError> {
27503                self.queries.borrow_mut().push(query.to_owned());
27504                Ok(SqlQueryResult {
27505                    columns: vec!["name".to_owned(), "id".to_owned()],
27506                    rows: vec![
27507                        vec![Scalar::Utf8("a".to_owned()), Scalar::Int64(1)],
27508                        vec![Scalar::Utf8("b".to_owned()), Scalar::Int64(2)],
27509                        vec![Scalar::Utf8("c".to_owned()), Scalar::Int64(3)],
27510                    ],
27511                })
27512            }
27513
27514            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
27515                Ok(())
27516            }
27517
27518            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
27519                Ok(false)
27520            }
27521
27522            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
27523                Ok(())
27524            }
27525
27526            fn dtype_sql(&self, _dtype: DType) -> &'static str {
27527                "TEXT"
27528            }
27529
27530            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
27531                "TEXT"
27532            }
27533
27534            fn supports_schemas(&self) -> bool {
27535                true
27536            }
27537        }
27538
27539        let conn = MultiSchemaProjectedChunks {
27540            queries: RefCell::new(Vec::new()),
27541        };
27542
27543        let chunks: Vec<DataFrame> = super::read_sql_table_chunks_with_options(
27544            &conn,
27545            "events",
27546            &SqlReadOptions {
27547                schema: Some("analytics".to_owned()),
27548                columns: Some(vec!["name".to_owned(), "id".to_owned()]),
27549                ..Default::default()
27550            },
27551            2,
27552        )
27553        .unwrap()
27554        .collect::<Result<Vec<_>, _>>()
27555        .unwrap();
27556
27557        assert_eq!(
27558            conn.queries.borrow().as_slice(),
27559            &["SELECT \"name\", \"id\" FROM \"analytics\".\"events\"".to_owned()]
27560        );
27561        assert_eq!(chunks.len(), 2);
27562        assert_eq!(chunks[0].column_names(), vec!["name", "id"]);
27563        assert_eq!(chunks[1].column_names(), vec!["name", "id"]);
27564        assert_eq!(
27565            chunks[0].index().labels(),
27566            &[IndexLabel::Int64(0), IndexLabel::Int64(1)]
27567        );
27568        assert_eq!(chunks[1].index().labels(), &[IndexLabel::Int64(0)]);
27569        assert_eq!(
27570            chunks[0].column("name").unwrap().values(),
27571            &[Scalar::Utf8("a".into()), Scalar::Utf8("b".into())]
27572        );
27573        assert_eq!(
27574            chunks[1].column("id").unwrap().values(),
27575            &[Scalar::Int64(3)]
27576        );
27577    }
27578
27579    // ── SqlColumnSchema::comment (br-cfld / fd90.35) ─────────────────────
27580
27581    #[cfg(feature = "sql-sqlite")]
27582    #[test]
27583    fn sql_table_schema_comment_is_none_on_sqlite() {
27584        // SQLite has no column-comment storage; the rusqlite override
27585        // must always emit comment=None even when the table is real.
27586        let conn = make_sql_test_conn();
27587        super::SqlConnection::execute_batch(&conn, "CREATE TABLE labeled (id INTEGER, name TEXT);")
27588            .unwrap();
27589        let schema = sql_table_schema(&conn, "labeled", None).unwrap().unwrap();
27590        for col in &schema.columns {
27591            assert!(
27592                col.comment.is_none(),
27593                "SQLite should report no column comment; got {:?} on {}",
27594                col.comment,
27595                col.name
27596            );
27597        }
27598    }
27599
27600    #[test]
27601    fn sql_table_schema_comment_routes_to_backend_override() {
27602        // PG-like backend stub returns explicit comment text per column.
27603        struct PgLikeWithComments;
27604        impl super::SqlConnection for PgLikeWithComments {
27605            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
27606                Ok(SqlQueryResult {
27607                    columns: vec![],
27608                    rows: vec![],
27609                })
27610            }
27611            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
27612                Ok(())
27613            }
27614            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
27615                Ok(false)
27616            }
27617            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
27618                Ok(())
27619            }
27620            fn dtype_sql(&self, _dtype: DType) -> &'static str {
27621                "TEXT"
27622            }
27623            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
27624                "TEXT"
27625            }
27626            fn supports_schemas(&self) -> bool {
27627                true
27628            }
27629            fn table_schema(
27630                &self,
27631                table: &str,
27632                _schema: Option<&str>,
27633            ) -> Result<Option<SqlTableSchema>, IoError> {
27634                if table == "users" {
27635                    Ok(Some(SqlTableSchema {
27636                        table_name: "users".to_owned(),
27637                        columns: vec![
27638                            SqlColumnSchema {
27639                                name: "id".to_owned(),
27640                                declared_type: Some("BIGINT".to_owned()),
27641                                nullable: false,
27642                                default_value: None,
27643                                primary_key_ordinal: Some(0),
27644                                comment: Some("Surrogate primary key".to_owned()),
27645                                autoincrement: false,
27646                            },
27647                            SqlColumnSchema {
27648                                name: "email".to_owned(),
27649                                declared_type: Some("TEXT".to_owned()),
27650                                nullable: false,
27651                                default_value: None,
27652                                primary_key_ordinal: None,
27653                                comment: Some("Login identifier".to_owned()),
27654                                autoincrement: false,
27655                            },
27656                            SqlColumnSchema {
27657                                name: "name".to_owned(),
27658                                declared_type: Some("TEXT".to_owned()),
27659                                nullable: true,
27660                                default_value: None,
27661                                primary_key_ordinal: None,
27662                                comment: None,
27663                                autoincrement: false,
27664                            },
27665                        ],
27666                    }))
27667                } else {
27668                    Ok(None)
27669                }
27670            }
27671        }
27672        let conn = PgLikeWithComments;
27673        let schema = sql_table_schema(&conn, "users", None).unwrap().unwrap();
27674        let id = schema.column("id").unwrap();
27675        assert_eq!(id.comment.as_deref(), Some("Surrogate primary key"));
27676        let email = schema.column("email").unwrap();
27677        assert_eq!(email.comment.as_deref(), Some("Login identifier"));
27678        // Mixed: some columns may have no comment even on PG.
27679        let name = schema.column("name").unwrap();
27680        assert!(name.comment.is_none());
27681    }
27682
27683    // ── SqlReadOptions::index_col (br-c1h9 / fd90.36) ─────────────────────
27684
27685    #[cfg(feature = "sql-sqlite")]
27686    #[test]
27687    fn read_sql_with_options_index_col_none_keeps_range_index() {
27688        let conn = make_sql_test_conn();
27689        super::SqlConnection::execute_batch(&conn, "CREATE TABLE keyed (id INTEGER, val INTEGER);")
27690            .unwrap();
27691        super::SqlConnection::execute_batch(&conn, "INSERT INTO keyed VALUES (1, 10), (2, 20);")
27692            .unwrap();
27693        let frame = read_sql_with_options(
27694            &conn,
27695            "SELECT id, val FROM keyed ORDER BY id",
27696            &SqlReadOptions {
27697                index_col: None,
27698                ..Default::default()
27699            },
27700        )
27701        .unwrap();
27702        // Default RangeIndex: labels 0, 1.
27703        assert_eq!(frame.index().len(), 2);
27704        assert_eq!(frame.column_names(), vec!["id", "val"]);
27705    }
27706
27707    #[cfg(feature = "sql-sqlite")]
27708    #[test]
27709    fn read_sql_with_options_index_col_promotes_named_column() {
27710        let conn = make_sql_test_conn();
27711        super::SqlConnection::execute_batch(&conn, "CREATE TABLE keyed (id INTEGER, val INTEGER);")
27712            .unwrap();
27713        super::SqlConnection::execute_batch(&conn, "INSERT INTO keyed VALUES (10, 1), (20, 2);")
27714            .unwrap();
27715        let frame = read_sql_with_options(
27716            &conn,
27717            "SELECT id, val FROM keyed ORDER BY id",
27718            &SqlReadOptions {
27719                index_col: Some("id".to_owned()),
27720                ..Default::default()
27721            },
27722        )
27723        .unwrap();
27724        // 'id' removed from columns, used as index labels.
27725        assert_eq!(frame.column_names(), vec!["val"]);
27726        assert_eq!(frame.index().len(), 2);
27727        // Index labels should be the id values (10, 20).
27728        let labels: Vec<i64> = frame
27729            .index()
27730            .labels()
27731            .iter()
27732            .filter_map(|l| match l {
27733                IndexLabel::Int64(v) => Some(*v),
27734                _ => None,
27735            })
27736            .collect();
27737        assert_eq!(labels, vec![10, 20]);
27738    }
27739
27740    #[cfg(feature = "sql-sqlite")]
27741    #[test]
27742    fn read_sql_with_options_index_col_missing_column_errors() {
27743        let conn = make_sql_test_conn();
27744        super::SqlConnection::execute_batch(&conn, "CREATE TABLE t (a INTEGER);").unwrap();
27745        super::SqlConnection::execute_batch(&conn, "INSERT INTO t VALUES (1);").unwrap();
27746        let err = read_sql_with_options(
27747            &conn,
27748            "SELECT a FROM t",
27749            &SqlReadOptions {
27750                index_col: Some("nonexistent".to_owned()),
27751                ..Default::default()
27752            },
27753        )
27754        .expect_err("missing index_col must error");
27755        assert!(matches!(err, IoError::Sql(msg) if msg.contains("not present")));
27756    }
27757
27758    #[cfg(feature = "sql-sqlite")]
27759    #[test]
27760    fn read_sql_with_options_index_col_empty_string_rejected() {
27761        let conn = make_sql_test_conn();
27762        super::SqlConnection::execute_batch(&conn, "CREATE TABLE t (a INTEGER);").unwrap();
27763        let err = read_sql_with_options(
27764            &conn,
27765            "SELECT a FROM t",
27766            &SqlReadOptions {
27767                index_col: Some(String::new()),
27768                ..Default::default()
27769            },
27770        )
27771        .expect_err("empty index_col must be rejected");
27772        assert!(matches!(err, IoError::Sql(msg) if msg.contains("empty string")));
27773    }
27774
27775    #[cfg(feature = "sql-sqlite")]
27776    #[test]
27777    fn read_sql_explicit_index_col_empty_string_rejected_across_entrypoints() {
27778        fn assert_empty_index_col(err: IoError) {
27779            assert!(
27780                matches!(err, IoError::Sql(ref msg) if msg.contains("empty string")),
27781                "expected empty index_col error, got {err:?}"
27782            );
27783        }
27784
27785        let conn = make_sql_test_conn();
27786        super::SqlConnection::execute_batch(
27787            &conn,
27788            "CREATE TABLE explicit_idx (a INTEGER, b TEXT);
27789             INSERT INTO explicit_idx VALUES (1, 'x'), (2, 'y');",
27790        )
27791        .unwrap();
27792
27793        assert_empty_index_col(
27794            read_sql_with_index_col(&conn, "SELECT a, b FROM explicit_idx", Some(""))
27795                .expect_err("empty explicit read_sql index_col must be rejected"),
27796        );
27797        assert_empty_index_col(
27798            read_sql_query_with_options_and_index_col(
27799                &conn,
27800                "SELECT a, b FROM explicit_idx",
27801                &SqlReadOptions::default(),
27802                Some(""),
27803            )
27804            .expect_err("empty explicit read_sql_query index_col must be rejected"),
27805        );
27806        assert_empty_index_col(
27807            read_sql_query_chunks_with_options_and_index_col(
27808                &conn,
27809                "SELECT a, b FROM explicit_idx",
27810                &SqlReadOptions::default(),
27811                Some(""),
27812                1,
27813            )
27814            .expect_err("empty explicit query chunk index_col must be rejected"),
27815        );
27816        assert_empty_index_col(
27817            read_sql_table_with_index_col(&conn, "explicit_idx", Some(""))
27818                .expect_err("empty explicit table index_col must be rejected"),
27819        );
27820        assert_empty_index_col(
27821            read_sql_table_with_options_and_index_col(
27822                &conn,
27823                "explicit_idx",
27824                &SqlReadOptions::default(),
27825                Some(""),
27826            )
27827            .expect_err("empty explicit table options index_col must be rejected"),
27828        );
27829        assert_empty_index_col(
27830            read_sql_table_columns_with_index_col(&conn, "explicit_idx", &["a"], Some(""))
27831                .expect_err("empty explicit table-columns index_col must be rejected"),
27832        );
27833        assert_empty_index_col(
27834            read_sql_table_columns_chunks_with_index_col(
27835                &conn,
27836                "explicit_idx",
27837                &["a"],
27838                Some(""),
27839                1,
27840            )
27841            .expect_err("empty explicit table-columns chunk index_col must be rejected"),
27842        );
27843    }
27844
27845    #[cfg(feature = "sql-sqlite")]
27846    #[test]
27847    fn read_sql_table_with_options_index_col_combines_with_columns_projection() {
27848        // columns + index_col: project ['id', 'val'], promote 'id' to
27849        // index, leaving only 'val' as a data column.
27850        let conn = make_sql_test_conn();
27851        super::SqlConnection::execute_batch(
27852            &conn,
27853            "CREATE TABLE wide (id INTEGER, val INTEGER, ts TEXT, note TEXT);",
27854        )
27855        .unwrap();
27856        super::SqlConnection::execute_batch(
27857            &conn,
27858            "INSERT INTO wide VALUES (5, 100, 't1', 'first');",
27859        )
27860        .unwrap();
27861        let frame = read_sql_table_with_options(
27862            &conn,
27863            "wide",
27864            &SqlReadOptions {
27865                columns: Some(vec!["id".to_owned(), "val".to_owned()]),
27866                index_col: Some("id".to_owned()),
27867                ..Default::default()
27868            },
27869        )
27870        .unwrap();
27871        assert_eq!(frame.column_names(), vec!["val"]);
27872        let labels: Vec<i64> = frame
27873            .index()
27874            .labels()
27875            .iter()
27876            .filter_map(|l| match l {
27877                IndexLabel::Int64(v) => Some(*v),
27878                _ => None,
27879            })
27880            .collect();
27881        assert_eq!(labels, vec![5]);
27882    }
27883
27884    #[cfg(feature = "sql-sqlite")]
27885    #[test]
27886    fn read_sql_table_with_options_columns_auto_project_index_col() {
27887        let conn = make_sql_test_conn();
27888        super::SqlConnection::execute_batch(
27889            &conn,
27890            "CREATE TABLE projected_index (id INTEGER, val TEXT, hidden TEXT);",
27891        )
27892        .unwrap();
27893        super::SqlConnection::execute_batch(
27894            &conn,
27895            "INSERT INTO projected_index VALUES (10, 'a', 'x'), (20, 'b', 'y');",
27896        )
27897        .unwrap();
27898
27899        let frame = read_sql_table_with_options(
27900            &conn,
27901            "projected_index",
27902            &SqlReadOptions {
27903                columns: Some(vec!["val".to_owned()]),
27904                index_col: Some("id".to_owned()),
27905                ..Default::default()
27906            },
27907        )
27908        .unwrap();
27909
27910        assert_eq!(frame.column_names(), vec!["val"]);
27911        assert!(frame.column("id").is_none());
27912        assert!(frame.column("hidden").is_none());
27913        assert_eq!(
27914            frame.index().labels(),
27915            &[IndexLabel::Int64(10), IndexLabel::Int64(20)]
27916        );
27917        assert_eq!(
27918            frame.column("val").unwrap().values(),
27919            &[Scalar::Utf8("a".into()), Scalar::Utf8("b".into())]
27920        );
27921    }
27922
27923    #[cfg(feature = "sql-sqlite")]
27924    #[test]
27925    fn read_sql_table_chunks_with_options_columns_auto_project_index_col() {
27926        let conn = make_sql_test_conn();
27927        super::SqlConnection::execute_batch(
27928            &conn,
27929            "CREATE TABLE projected_index_chunks (id INTEGER, val TEXT, hidden TEXT);",
27930        )
27931        .unwrap();
27932        super::SqlConnection::execute_batch(
27933            &conn,
27934            "INSERT INTO projected_index_chunks VALUES \
27935                (10, 'a', 'x'), \
27936                (20, 'b', 'y'), \
27937                (30, 'c', 'z');",
27938        )
27939        .unwrap();
27940
27941        let chunks: Vec<DataFrame> = read_sql_table_chunks_with_options_and_index_col(
27942            &conn,
27943            "projected_index_chunks",
27944            &SqlReadOptions {
27945                columns: Some(vec!["val".to_owned()]),
27946                ..Default::default()
27947            },
27948            Some("id"),
27949            2,
27950        )
27951        .unwrap()
27952        .collect::<Result<Vec<_>, _>>()
27953        .unwrap();
27954
27955        assert_eq!(chunks.len(), 2);
27956        assert_eq!(chunks[0].column_names(), vec!["val"]);
27957        assert!(chunks[0].column("id").is_none());
27958        assert!(chunks[0].column("hidden").is_none());
27959        assert_eq!(
27960            chunks[0].index().labels(),
27961            &[IndexLabel::Int64(10), IndexLabel::Int64(20)]
27962        );
27963        assert_eq!(chunks[1].index().labels(), &[IndexLabel::Int64(30)]);
27964        assert_eq!(
27965            chunks[1].column("val").unwrap().values(),
27966            &[Scalar::Utf8("c".into())]
27967        );
27968    }
27969
27970    #[cfg(feature = "sql-sqlite")]
27971    #[test]
27972    fn read_sql_table_with_options_and_index_col_explicit_arg_wins_over_options() {
27973        // Both options.index_col=Some('a') and explicit index_col=Some('b').
27974        // The explicit arg must win — options.index_col is silently
27975        // overridden to avoid double-promotion.
27976        let conn = make_sql_test_conn();
27977        super::SqlConnection::execute_batch(
27978            &conn,
27979            "CREATE TABLE both (a INTEGER, b INTEGER, c TEXT);",
27980        )
27981        .unwrap();
27982        super::SqlConnection::execute_batch(
27983            &conn,
27984            "INSERT INTO both VALUES (1, 100, 'x'), (2, 200, 'y');",
27985        )
27986        .unwrap();
27987        let frame = read_sql_table_with_options_and_index_col(
27988            &conn,
27989            "both",
27990            &SqlReadOptions {
27991                index_col: Some("a".to_owned()),
27992                ..Default::default()
27993            },
27994            Some("b"),
27995        )
27996        .unwrap();
27997        // 'b' is promoted to index, 'a' and 'c' remain as columns.
27998        assert_eq!(frame.column_names(), vec!["a", "c"]);
27999        let labels: Vec<i64> = frame
28000            .index()
28001            .labels()
28002            .iter()
28003            .filter_map(|l| match l {
28004                IndexLabel::Int64(v) => Some(*v),
28005                _ => None,
28006            })
28007            .collect();
28008        assert_eq!(labels, vec![100, 200]);
28009    }
28010
28011    // ── SqlColumnSchema::autoincrement (br-bkl2 / fd90.37) ────────────────
28012
28013    #[cfg(feature = "sql-sqlite")]
28014    #[test]
28015    fn sql_table_schema_autoincrement_detected_on_integer_primary_key() {
28016        // SQLite rowid-alias rule: INTEGER PRIMARY KEY is an
28017        // auto-incrementing rowid alias.
28018        let conn = make_sql_test_conn();
28019        super::SqlConnection::execute_batch(
28020            &conn,
28021            "CREATE TABLE auto_a (id INTEGER PRIMARY KEY, name TEXT);",
28022        )
28023        .unwrap();
28024        let schema = sql_table_schema(&conn, "auto_a", None).unwrap().unwrap();
28025        let id = schema.column("id").unwrap();
28026        assert!(
28027            id.autoincrement,
28028            "INTEGER PRIMARY KEY must be autoincrement; got {id:?}"
28029        );
28030        let name = schema.column("name").unwrap();
28031        assert!(
28032            !name.autoincrement,
28033            "non-PK column must not be autoincrement"
28034        );
28035    }
28036
28037    #[cfg(feature = "sql-sqlite")]
28038    #[test]
28039    fn sql_table_schema_autoincrement_detected_with_explicit_keyword() {
28040        // The explicit AUTOINCREMENT keyword affects rowid reuse, not
28041        // the autoincrement property pandas surfaces.
28042        let conn = make_sql_test_conn();
28043        super::SqlConnection::execute_batch(
28044            &conn,
28045            "CREATE TABLE auto_b (id INTEGER PRIMARY KEY AUTOINCREMENT, val TEXT);",
28046        )
28047        .unwrap();
28048        let schema = sql_table_schema(&conn, "auto_b", None).unwrap().unwrap();
28049        let id = schema.column("id").unwrap();
28050        assert!(id.autoincrement);
28051    }
28052
28053    #[cfg(feature = "sql-sqlite")]
28054    #[test]
28055    fn sql_table_schema_autoincrement_not_set_for_text_primary_key() {
28056        // TEXT PRIMARY KEY is NOT a rowid alias; not auto-incrementing.
28057        let conn = make_sql_test_conn();
28058        super::SqlConnection::execute_batch(
28059            &conn,
28060            "CREATE TABLE text_pk (code TEXT PRIMARY KEY, name TEXT);",
28061        )
28062        .unwrap();
28063        let schema = sql_table_schema(&conn, "text_pk", None).unwrap().unwrap();
28064        let code = schema.column("code").unwrap();
28065        assert!(
28066            !code.autoincrement,
28067            "TEXT PRIMARY KEY is not autoincrement; got {code:?}"
28068        );
28069    }
28070
28071    #[cfg(feature = "sql-sqlite")]
28072    #[test]
28073    fn sql_table_schema_autoincrement_not_set_for_non_pk_integer() {
28074        let conn = make_sql_test_conn();
28075        super::SqlConnection::execute_batch(
28076            &conn,
28077            "CREATE TABLE plain_int (val INTEGER, name TEXT);",
28078        )
28079        .unwrap();
28080        let schema = sql_table_schema(&conn, "plain_int", None).unwrap().unwrap();
28081        let val = schema.column("val").unwrap();
28082        assert!(!val.autoincrement, "non-PK INTEGER is not autoincrement");
28083    }
28084
28085    #[cfg(feature = "sql-sqlite")]
28086    #[test]
28087    fn sql_table_schema_autoincrement_not_set_for_composite_pk_integer() {
28088        // Per fd90.42: SQLite's rowid-alias rule requires the column
28089        // to be the SOLE primary key. The tightened heuristic counts
28090        // PK columns first; composite PKs (multiple pk>0 rows) never
28091        // qualify even when the first column is INTEGER.
28092        let conn = make_sql_test_conn();
28093        super::SqlConnection::execute_batch(
28094            &conn,
28095            "CREATE TABLE composite_pk ( \
28096                year INTEGER NOT NULL, \
28097                month INTEGER NOT NULL, \
28098                code TEXT NOT NULL, \
28099                PRIMARY KEY (year, month, code) \
28100             );",
28101        )
28102        .unwrap();
28103        let schema = sql_table_schema(&conn, "composite_pk", None)
28104            .unwrap()
28105            .unwrap();
28106        let year = schema.column("year").unwrap();
28107        let month = schema.column("month").unwrap();
28108        let code = schema.column("code").unwrap();
28109        // Each part of the composite PK keeps its declaration-order
28110        // ordinal but NONE of them is autoincrement.
28111        assert_eq!(year.primary_key_ordinal, Some(0));
28112        assert_eq!(month.primary_key_ordinal, Some(1));
28113        assert_eq!(code.primary_key_ordinal, Some(2));
28114        assert!(
28115            !year.autoincrement,
28116            "composite PK first col must not be autoincrement"
28117        );
28118        assert!(!month.autoincrement);
28119        assert!(!code.autoincrement);
28120    }
28121
28122    #[cfg(feature = "sql-sqlite")]
28123    #[test]
28124    fn sql_table_schema_autoincrement_two_pass_count_distinguishes_single_vs_composite() {
28125        // Confirm the fix path: single-column INTEGER PRIMARY KEY -> true,
28126        // composite INTEGER+INTEGER PRIMARY KEY -> false on both.
28127        let conn = make_sql_test_conn();
28128        super::SqlConnection::execute_batch(
28129            &conn,
28130            "CREATE TABLE single_int_pk (id INTEGER PRIMARY KEY, label TEXT);",
28131        )
28132        .unwrap();
28133        super::SqlConnection::execute_batch(
28134            &conn,
28135            "CREATE TABLE composite_int_pk ( \
28136                a INTEGER NOT NULL, \
28137                b INTEGER NOT NULL, \
28138                PRIMARY KEY (a, b) \
28139             );",
28140        )
28141        .unwrap();
28142
28143        let single = sql_table_schema(&conn, "single_int_pk", None)
28144            .unwrap()
28145            .unwrap();
28146        assert!(single.column("id").unwrap().autoincrement);
28147
28148        let composite = sql_table_schema(&conn, "composite_int_pk", None)
28149            .unwrap()
28150            .unwrap();
28151        // Both columns have INTEGER type and pk>0 but neither qualifies.
28152        assert!(!composite.column("a").unwrap().autoincrement);
28153        assert!(!composite.column("b").unwrap().autoincrement);
28154    }
28155
28156    #[test]
28157    fn sql_table_schema_autoincrement_routes_to_backend_override() {
28158        // PG-like backend stub returns explicit autoincrement true for
28159        // a SERIAL/IDENTITY column.
28160        struct PgLikeAutoinc;
28161        impl super::SqlConnection for PgLikeAutoinc {
28162            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
28163                Ok(SqlQueryResult {
28164                    columns: vec![],
28165                    rows: vec![],
28166                })
28167            }
28168            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
28169                Ok(())
28170            }
28171            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
28172                Ok(false)
28173            }
28174            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
28175                Ok(())
28176            }
28177            fn dtype_sql(&self, _dtype: DType) -> &'static str {
28178                "TEXT"
28179            }
28180            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
28181                "TEXT"
28182            }
28183            fn supports_schemas(&self) -> bool {
28184                true
28185            }
28186            fn table_schema(
28187                &self,
28188                table: &str,
28189                _schema: Option<&str>,
28190            ) -> Result<Option<SqlTableSchema>, IoError> {
28191                if table == "users" {
28192                    Ok(Some(SqlTableSchema {
28193                        table_name: "users".to_owned(),
28194                        columns: vec![
28195                            SqlColumnSchema {
28196                                name: "id".to_owned(),
28197                                declared_type: Some("BIGSERIAL".to_owned()),
28198                                nullable: false,
28199                                default_value: None,
28200                                primary_key_ordinal: Some(0),
28201                                comment: None,
28202                                autoincrement: true,
28203                            },
28204                            SqlColumnSchema {
28205                                name: "email".to_owned(),
28206                                declared_type: Some("TEXT".to_owned()),
28207                                nullable: false,
28208                                default_value: None,
28209                                primary_key_ordinal: None,
28210                                comment: None,
28211                                autoincrement: false,
28212                            },
28213                        ],
28214                    }))
28215                } else {
28216                    Ok(None)
28217                }
28218            }
28219        }
28220        let conn = PgLikeAutoinc;
28221        let schema = sql_table_schema(&conn, "users", None).unwrap().unwrap();
28222        assert!(schema.column("id").unwrap().autoincrement);
28223        assert!(!schema.column("email").unwrap().autoincrement);
28224    }
28225
28226    // ── SqlInspector facade (br-szs9 / fd90.38) ──────────────────────────
28227
28228    #[cfg(feature = "sql-sqlite")]
28229    #[test]
28230    fn sql_inspector_tables_views_schemas() {
28231        let conn = make_sql_test_conn();
28232        super::SqlConnection::execute_batch(&conn, "CREATE TABLE t1 (x INTEGER);").unwrap();
28233        super::SqlConnection::execute_batch(&conn, "CREATE TABLE t2 (y TEXT);").unwrap();
28234        super::SqlConnection::execute_batch(&conn, "CREATE VIEW v1 AS SELECT x FROM t1;").unwrap();
28235
28236        let inspector = SqlInspector::new(&conn);
28237        assert_eq!(inspector.tables(None).unwrap(), vec!["t1", "t2"]);
28238        assert_eq!(inspector.views(None).unwrap(), vec!["v1"]);
28239        // SQLite has no meaningful schemas → empty vec.
28240        assert!(inspector.schemas().unwrap().is_empty());
28241    }
28242
28243    #[cfg(feature = "sql-sqlite")]
28244    #[test]
28245    fn sql_inspector_columns_pk_indexes_fks() {
28246        let conn = make_sql_test_conn();
28247        super::SqlConnection::execute_batch(
28248            &conn,
28249            "CREATE TABLE parent (pid INTEGER PRIMARY KEY);",
28250        )
28251        .unwrap();
28252        super::SqlConnection::execute_batch(
28253            &conn,
28254            "CREATE TABLE child ( \
28255                cid INTEGER PRIMARY KEY, \
28256                parent_id INTEGER, \
28257                tag TEXT, \
28258                FOREIGN KEY (parent_id) REFERENCES parent(pid) \
28259             );",
28260        )
28261        .unwrap();
28262        super::SqlConnection::execute_batch(&conn, "CREATE INDEX idx_child_tag ON child(tag);")
28263            .unwrap();
28264
28265        let inspector = SqlInspector::new(&conn);
28266
28267        // columns: 3 columns on 'child', cid + parent_id + tag.
28268        let schema = inspector.columns("child", None).unwrap().unwrap();
28269        let names: Vec<&str> = schema.columns.iter().map(|c| c.name.as_str()).collect();
28270        assert_eq!(names, vec!["cid", "parent_id", "tag"]);
28271
28272        // primary_key_columns: cid is the sole PK.
28273        let pk = inspector.primary_key_columns("child", None).unwrap();
28274        assert_eq!(pk, vec!["cid"]);
28275
28276        // indexes: only the explicit user index (PK auto-index filtered).
28277        let indexes = inspector.indexes("child", None).unwrap();
28278        assert_eq!(indexes.len(), 1);
28279        assert_eq!(indexes[0].name, "idx_child_tag");
28280
28281        // foreign_keys: child references parent.
28282        let fks = inspector.foreign_keys("child", None).unwrap();
28283        assert_eq!(fks.len(), 1);
28284        assert_eq!(fks[0].columns, vec!["parent_id"]);
28285        assert_eq!(fks[0].referenced_table, "parent");
28286        assert_eq!(fks[0].referenced_columns, vec!["pid"]);
28287    }
28288
28289    #[cfg(feature = "sql-sqlite")]
28290    #[test]
28291    fn sql_inspector_unique_constraints_and_table_exists() {
28292        let conn = make_sql_test_conn();
28293        super::SqlConnection::execute_batch(
28294            &conn,
28295            "CREATE TABLE users (id INTEGER PRIMARY KEY, email TEXT UNIQUE);",
28296        )
28297        .unwrap();
28298        let inspector = SqlInspector::new(&conn);
28299        let uqs = inspector.unique_constraints("users", None).unwrap();
28300        assert_eq!(uqs.len(), 1);
28301        assert_eq!(uqs[0].columns, vec!["email"]);
28302        assert!(inspector.table_exists("users", None).unwrap());
28303        assert!(!inspector.table_exists("not_there", None).unwrap());
28304    }
28305
28306    #[cfg(feature = "sql-sqlite")]
28307    #[test]
28308    fn sql_inspector_server_version_and_dialect() {
28309        let conn = make_sql_test_conn();
28310        let inspector = SqlInspector::new(&conn);
28311        let version = inspector.server_version().unwrap().unwrap();
28312        assert!(version.starts_with("3."));
28313        assert_eq!(inspector.dialect_name(), "sqlite");
28314        // SQLite has no documented identifier-length cap.
28315        assert_eq!(inspector.max_identifier_length(), None);
28316    }
28317
28318    #[cfg(feature = "sql-sqlite")]
28319    #[test]
28320    fn sql_inspector_table_comment_returns_none_on_sqlite() {
28321        let conn = make_sql_test_conn();
28322        super::SqlConnection::execute_batch(&conn, "CREATE TABLE t (x INTEGER);").unwrap();
28323        let inspector = SqlInspector::new(&conn);
28324        assert!(inspector.table_comment("t", None).unwrap().is_none());
28325    }
28326
28327    #[cfg(feature = "sql-sqlite")]
28328    #[test]
28329    fn sql_inspector_via_inspect_helper() {
28330        // The free-fn `inspect(&conn)` is the one-shot construction helper.
28331        // Per fd90.46: import lives inside the test so --no-default-features
28332        // builds don't see it as unused.
28333        use super::inspect;
28334        let conn = make_sql_test_conn();
28335        super::SqlConnection::execute_batch(&conn, "CREATE TABLE one (x INTEGER);").unwrap();
28336        let inspector = inspect(&conn);
28337        assert_eq!(inspector.tables(None).unwrap(), vec!["one"]);
28338    }
28339
28340    #[test]
28341    fn sql_inspector_routes_schema_arg_to_backend() {
28342        // Multi-schema backend: verifies SqlInspector forwards the schema
28343        // arg to every method that accepts one.
28344        struct PgLikeStub;
28345        impl super::SqlConnection for PgLikeStub {
28346            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
28347                Ok(SqlQueryResult {
28348                    columns: vec![],
28349                    rows: vec![],
28350                })
28351            }
28352            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
28353                Ok(())
28354            }
28355            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
28356                Ok(false)
28357            }
28358            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
28359                Ok(())
28360            }
28361            fn dtype_sql(&self, _dtype: DType) -> &'static str {
28362                "TEXT"
28363            }
28364            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
28365                "TEXT"
28366            }
28367            fn supports_schemas(&self) -> bool {
28368                true
28369            }
28370            fn list_tables(&self, schema: Option<&str>) -> Result<Vec<String>, IoError> {
28371                Ok(match schema {
28372                    Some("analytics") => vec!["events".to_owned()],
28373                    _ => vec![],
28374                })
28375            }
28376            fn list_views(&self, schema: Option<&str>) -> Result<Vec<String>, IoError> {
28377                Ok(match schema {
28378                    Some("analytics") => vec!["daily".to_owned()],
28379                    _ => vec![],
28380                })
28381            }
28382            fn list_schemas(&self) -> Result<Vec<String>, IoError> {
28383                Ok(vec!["public".to_owned(), "analytics".to_owned()])
28384            }
28385            fn dialect_name(&self) -> &'static str {
28386                "postgresql"
28387            }
28388            fn max_identifier_length(&self) -> Option<usize> {
28389                Some(63)
28390            }
28391        }
28392        let conn = PgLikeStub;
28393        let inspector = SqlInspector::new(&conn);
28394
28395        assert_eq!(inspector.tables(Some("analytics")).unwrap(), vec!["events"]);
28396        assert_eq!(inspector.views(Some("analytics")).unwrap(), vec!["daily"]);
28397        assert!(inspector.tables(Some("audit")).unwrap().is_empty());
28398        assert_eq!(inspector.schemas().unwrap(), vec!["public", "analytics"]);
28399        assert_eq!(inspector.dialect_name(), "postgresql");
28400        assert_eq!(inspector.max_identifier_length(), Some(63));
28401    }
28402
28403    // ── SqlInspector::has_column / column (br-ppry / fd90.39) ─────────────
28404
28405    #[cfg(feature = "sql-sqlite")]
28406    #[test]
28407    fn sql_inspector_has_column_returns_true_for_present_column() {
28408        let conn = make_sql_test_conn();
28409        super::SqlConnection::execute_batch(
28410            &conn,
28411            "CREATE TABLE has_col_tbl (id INTEGER, name TEXT);",
28412        )
28413        .unwrap();
28414        let inspector = SqlInspector::new(&conn);
28415        assert!(inspector.has_column("has_col_tbl", "id", None).unwrap());
28416        assert!(inspector.has_column("has_col_tbl", "name", None).unwrap());
28417    }
28418
28419    #[cfg(feature = "sql-sqlite")]
28420    #[test]
28421    fn sql_inspector_has_column_returns_false_for_missing_column() {
28422        let conn = make_sql_test_conn();
28423        super::SqlConnection::execute_batch(&conn, "CREATE TABLE only_id (id INTEGER);").unwrap();
28424        let inspector = SqlInspector::new(&conn);
28425        // Table exists but no such column.
28426        assert!(!inspector.has_column("only_id", "name", None).unwrap());
28427    }
28428
28429    #[cfg(feature = "sql-sqlite")]
28430    #[test]
28431    fn sql_inspector_has_column_returns_false_for_missing_table() {
28432        let conn = make_sql_test_conn();
28433        let inspector = SqlInspector::new(&conn);
28434        // Table doesn't exist → has_column propagates Ok(false), not error.
28435        assert!(
28436            !inspector
28437                .has_column("no_such_tbl", "any_col", None)
28438                .unwrap()
28439        );
28440    }
28441
28442    #[cfg(feature = "sql-sqlite")]
28443    #[test]
28444    fn sql_inspector_column_returns_full_metadata_for_present_column() {
28445        let conn = make_sql_test_conn();
28446        super::SqlConnection::execute_batch(
28447            &conn,
28448            "CREATE TABLE detailed (id INTEGER PRIMARY KEY, status TEXT DEFAULT 'active');",
28449        )
28450        .unwrap();
28451        let inspector = SqlInspector::new(&conn);
28452        let id = inspector.column("detailed", "id", None).unwrap().unwrap();
28453        assert_eq!(id.name, "id");
28454        assert_eq!(id.declared_type.as_deref(), Some("INTEGER"));
28455        assert_eq!(id.primary_key_ordinal, Some(0));
28456        // INTEGER PRIMARY KEY → SQLite autoincrement (rowid alias).
28457        assert!(id.autoincrement);
28458
28459        let status = inspector
28460            .column("detailed", "status", None)
28461            .unwrap()
28462            .unwrap();
28463        assert_eq!(status.declared_type.as_deref(), Some("TEXT"));
28464        assert!(status.nullable);
28465        assert_eq!(status.default_value.as_deref(), Some("'active'"));
28466        assert!(!status.autoincrement);
28467    }
28468
28469    #[cfg(feature = "sql-sqlite")]
28470    #[test]
28471    fn sql_inspector_column_returns_none_for_missing_column_or_table() {
28472        let conn = make_sql_test_conn();
28473        super::SqlConnection::execute_batch(&conn, "CREATE TABLE only_x (x INTEGER);").unwrap();
28474        let inspector = SqlInspector::new(&conn);
28475        // Existing table, missing column → None.
28476        assert!(
28477            inspector
28478                .column("only_x", "missing", None)
28479                .unwrap()
28480                .is_none()
28481        );
28482        // Missing table → None.
28483        assert!(inspector.column("no_such", "any", None).unwrap().is_none());
28484    }
28485
28486    #[test]
28487    fn sql_inspector_has_column_routes_schema_arg_to_backend() {
28488        struct PgLikeColumns;
28489        impl super::SqlConnection for PgLikeColumns {
28490            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
28491                Ok(SqlQueryResult {
28492                    columns: vec![],
28493                    rows: vec![],
28494                })
28495            }
28496            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
28497                Ok(())
28498            }
28499            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
28500                Ok(false)
28501            }
28502            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
28503                Ok(())
28504            }
28505            fn dtype_sql(&self, _dtype: DType) -> &'static str {
28506                "TEXT"
28507            }
28508            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
28509                "TEXT"
28510            }
28511            fn supports_schemas(&self) -> bool {
28512                true
28513            }
28514            fn table_schema(
28515                &self,
28516                table: &str,
28517                schema: Option<&str>,
28518            ) -> Result<Option<SqlTableSchema>, IoError> {
28519                if table == "users" && schema == Some("public") {
28520                    Ok(Some(SqlTableSchema {
28521                        table_name: "users".to_owned(),
28522                        columns: vec![SqlColumnSchema {
28523                            name: "id".to_owned(),
28524                            declared_type: Some("BIGINT".to_owned()),
28525                            nullable: false,
28526                            default_value: None,
28527                            primary_key_ordinal: Some(0),
28528                            comment: None,
28529                            autoincrement: true,
28530                        }],
28531                    }))
28532                } else {
28533                    Ok(None)
28534                }
28535            }
28536        }
28537        let conn = PgLikeColumns;
28538        let inspector = SqlInspector::new(&conn);
28539        assert!(inspector.has_column("users", "id", Some("public")).unwrap());
28540        assert!(!inspector.has_column("users", "id", Some("audit")).unwrap());
28541        assert!(
28542            !inspector
28543                .has_column("users", "missing", Some("public"))
28544                .unwrap()
28545        );
28546
28547        let id_col = inspector
28548            .column("users", "id", Some("public"))
28549            .unwrap()
28550            .unwrap();
28551        assert_eq!(id_col.declared_type.as_deref(), Some("BIGINT"));
28552        assert!(id_col.autoincrement);
28553        assert!(
28554            inspector
28555                .column("users", "id", Some("audit"))
28556                .unwrap()
28557                .is_none()
28558        );
28559    }
28560
28561    // ── SqlInspector::reflect_table (br-76mw / fd90.40) ──────────────────
28562
28563    #[cfg(feature = "sql-sqlite")]
28564    #[test]
28565    fn sql_inspector_reflect_table_unknown_returns_none() {
28566        let conn = make_sql_test_conn();
28567        let inspector = SqlInspector::new(&conn);
28568        let result = inspector.reflect_table("no_such", None).unwrap();
28569        assert!(result.is_none());
28570    }
28571
28572    #[cfg(feature = "sql-sqlite")]
28573    #[test]
28574    fn sql_inspector_reflect_table_bundles_all_metadata() {
28575        let conn = make_sql_test_conn();
28576        super::SqlConnection::execute_batch(
28577            &conn,
28578            "CREATE TABLE parent (pid INTEGER PRIMARY KEY, code TEXT);",
28579        )
28580        .unwrap();
28581        super::SqlConnection::execute_batch(
28582            &conn,
28583            "CREATE TABLE bundled ( \
28584                id INTEGER PRIMARY KEY, \
28585                parent_id INTEGER, \
28586                slug TEXT, \
28587                email TEXT UNIQUE, \
28588                FOREIGN KEY (parent_id) REFERENCES parent(pid) \
28589             );",
28590        )
28591        .unwrap();
28592        super::SqlConnection::execute_batch(
28593            &conn,
28594            "CREATE INDEX idx_bundled_slug ON bundled(slug);",
28595        )
28596        .unwrap();
28597
28598        let inspector = SqlInspector::new(&conn);
28599        let bundle = inspector
28600            .reflect_table("bundled", None)
28601            .unwrap()
28602            .expect("table exists");
28603
28604        assert_eq!(bundle.table_name, "bundled");
28605
28606        // Columns: id, parent_id, slug, email.
28607        let names: Vec<&str> = bundle.columns.iter().map(|c| c.name.as_str()).collect();
28608        assert_eq!(names, vec!["id", "parent_id", "slug", "email"]);
28609        // INTEGER PRIMARY KEY id is autoincrement.
28610        let id_col = bundle
28611            .columns
28612            .iter()
28613            .find(|c| c.name == "id")
28614            .expect("id col");
28615        assert!(id_col.autoincrement);
28616
28617        // Primary key.
28618        assert_eq!(bundle.primary_key_columns, vec!["id"]);
28619
28620        // Indexes (only the user CREATE INDEX; the UNIQUE constraint
28621        // index goes via unique_constraints, the PK auto-index is
28622        // hidden).
28623        assert_eq!(bundle.indexes.len(), 1);
28624        assert_eq!(bundle.indexes[0].name, "idx_bundled_slug");
28625
28626        // Unique constraints (the inline UNIQUE on email).
28627        assert_eq!(bundle.unique_constraints.len(), 1);
28628        assert_eq!(bundle.unique_constraints[0].columns, vec!["email"]);
28629
28630        // Foreign keys (parent_id -> parent.pid).
28631        assert_eq!(bundle.foreign_keys.len(), 1);
28632        assert_eq!(bundle.foreign_keys[0].columns, vec!["parent_id"]);
28633        assert_eq!(bundle.foreign_keys[0].referenced_table, "parent");
28634
28635        // SQLite has no native column/table comment; comment is None.
28636        assert!(bundle.comment.is_none());
28637    }
28638
28639    #[test]
28640    fn sql_inspector_reflect_table_routes_to_backend_override() {
28641        // Multi-schema PG-like backend that returns explicit comment +
28642        // populated metadata. Verifies all five sub-calls flow through
28643        // and end up in the bundled struct.
28644        struct PgLikeBundle;
28645        impl super::SqlConnection for PgLikeBundle {
28646            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
28647                Ok(SqlQueryResult {
28648                    columns: vec![],
28649                    rows: vec![],
28650                })
28651            }
28652            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
28653                Ok(())
28654            }
28655            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
28656                Ok(false)
28657            }
28658            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
28659                Ok(())
28660            }
28661            fn dtype_sql(&self, _dtype: DType) -> &'static str {
28662                "TEXT"
28663            }
28664            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
28665                "TEXT"
28666            }
28667            fn supports_schemas(&self) -> bool {
28668                true
28669            }
28670            fn table_schema(
28671                &self,
28672                table: &str,
28673                schema: Option<&str>,
28674            ) -> Result<Option<SqlTableSchema>, IoError> {
28675                if table == "users" && schema == Some("public") {
28676                    Ok(Some(SqlTableSchema {
28677                        table_name: "users".to_owned(),
28678                        columns: vec![SqlColumnSchema {
28679                            name: "id".to_owned(),
28680                            declared_type: Some("BIGINT".to_owned()),
28681                            nullable: false,
28682                            default_value: None,
28683                            primary_key_ordinal: Some(0),
28684                            comment: None,
28685                            autoincrement: true,
28686                        }],
28687                    }))
28688                } else {
28689                    Ok(None)
28690                }
28691            }
28692            fn primary_key_columns(
28693                &self,
28694                table: &str,
28695                schema: Option<&str>,
28696            ) -> Result<Vec<String>, IoError> {
28697                if table == "users" && schema == Some("public") {
28698                    Ok(vec!["id".to_owned()])
28699                } else {
28700                    Ok(vec![])
28701                }
28702            }
28703            fn list_indexes(
28704                &self,
28705                _table: &str,
28706                _schema: Option<&str>,
28707            ) -> Result<Vec<SqlIndexSchema>, IoError> {
28708                Ok(vec![SqlIndexSchema {
28709                    name: "users_status_idx".to_owned(),
28710                    columns: vec!["status".to_owned()],
28711                    unique: false,
28712                }])
28713            }
28714            fn list_foreign_keys(
28715                &self,
28716                _table: &str,
28717                _schema: Option<&str>,
28718            ) -> Result<Vec<SqlForeignKeySchema>, IoError> {
28719                Ok(vec![])
28720            }
28721            fn list_unique_constraints(
28722                &self,
28723                _table: &str,
28724                _schema: Option<&str>,
28725            ) -> Result<Vec<SqlUniqueConstraintSchema>, IoError> {
28726                Ok(vec![SqlUniqueConstraintSchema {
28727                    name: "users_email_key".to_owned(),
28728                    columns: vec!["email".to_owned()],
28729                }])
28730            }
28731            fn table_comment(
28732                &self,
28733                _table: &str,
28734                _schema: Option<&str>,
28735            ) -> Result<Option<String>, IoError> {
28736                Ok(Some("Customer accounts".to_owned()))
28737            }
28738        }
28739        let conn = PgLikeBundle;
28740        let inspector = SqlInspector::new(&conn);
28741        let bundle = inspector
28742            .reflect_table("users", Some("public"))
28743            .unwrap()
28744            .expect("present");
28745        assert_eq!(bundle.table_name, "users");
28746        assert_eq!(bundle.columns.len(), 1);
28747        assert_eq!(bundle.primary_key_columns, vec!["id"]);
28748        assert_eq!(bundle.indexes.len(), 1);
28749        assert_eq!(bundle.indexes[0].name, "users_status_idx");
28750        assert_eq!(bundle.unique_constraints.len(), 1);
28751        assert_eq!(bundle.foreign_keys.len(), 0);
28752        assert_eq!(bundle.comment.as_deref(), Some("Customer accounts"));
28753
28754        // Wrong schema -> None (table_schema returns None).
28755        assert!(
28756            inspector
28757                .reflect_table("users", Some("audit"))
28758                .unwrap()
28759                .is_none()
28760        );
28761    }
28762
28763    // Use SqlReflectedTable in a smoke test so the struct's named
28764    // fields are exercised at the use-site too.
28765    #[test]
28766    fn sql_reflected_table_bundle_smoke_test() {
28767        let bundle = SqlReflectedTable {
28768            table_name: "t".to_owned(),
28769            columns: vec![],
28770            primary_key_columns: vec![],
28771            indexes: vec![],
28772            foreign_keys: vec![],
28773            unique_constraints: vec![],
28774            comment: None,
28775        };
28776        assert_eq!(bundle.table_name, "t");
28777        assert!(bundle.columns.is_empty());
28778    }
28779
28780    // ── SqlReflectedTable accessor methods (br-63ac / fd90.51) ────────────
28781
28782    #[test]
28783    fn sql_reflected_table_accessors_find_named_entries() {
28784        let bundle = SqlReflectedTable {
28785            table_name: "orders".to_owned(),
28786            columns: vec![
28787                SqlColumnSchema {
28788                    name: "id".to_owned(),
28789                    declared_type: Some("INTEGER".to_owned()),
28790                    nullable: false,
28791                    default_value: None,
28792                    primary_key_ordinal: Some(0),
28793                    comment: None,
28794                    autoincrement: true,
28795                },
28796                SqlColumnSchema {
28797                    name: "user_id".to_owned(),
28798                    declared_type: Some("INTEGER".to_owned()),
28799                    nullable: false,
28800                    default_value: None,
28801                    primary_key_ordinal: None,
28802                    comment: None,
28803                    autoincrement: false,
28804                },
28805            ],
28806            primary_key_columns: vec!["id".to_owned()],
28807            indexes: vec![SqlIndexSchema {
28808                name: "idx_orders_user".to_owned(),
28809                columns: vec!["user_id".to_owned()],
28810                unique: false,
28811            }],
28812            foreign_keys: vec![SqlForeignKeySchema {
28813                constraint_name: None,
28814                columns: vec!["user_id".to_owned()],
28815                referenced_table: "users".to_owned(),
28816                referenced_columns: vec!["id".to_owned()],
28817            }],
28818            unique_constraints: vec![SqlUniqueConstraintSchema {
28819                name: "uq_orders_id".to_owned(),
28820                columns: vec!["id".to_owned()],
28821            }],
28822            comment: Some("Customer orders".to_owned()),
28823        };
28824
28825        // column(name): present + missing.
28826        let id = bundle.column("id").expect("id column");
28827        assert_eq!(id.declared_type.as_deref(), Some("INTEGER"));
28828        assert!(id.autoincrement);
28829        assert!(bundle.column("missing").is_none());
28830
28831        // index(name): present + missing.
28832        let idx = bundle.index("idx_orders_user").expect("idx");
28833        assert_eq!(idx.columns, vec!["user_id"]);
28834        assert!(bundle.index("idx_does_not_exist").is_none());
28835
28836        // unique_constraint(name).
28837        let uq = bundle.unique_constraint("uq_orders_id").expect("uq");
28838        assert_eq!(uq.columns, vec!["id"]);
28839        assert!(bundle.unique_constraint("uq_missing").is_none());
28840
28841        // foreign_keys_for_column(col): matches the FK touching user_id.
28842        let fks = bundle.foreign_keys_for_column("user_id");
28843        assert_eq!(fks.len(), 1);
28844        assert_eq!(fks[0].referenced_table, "users");
28845        // Column not part of any FK -> empty.
28846        assert!(bundle.foreign_keys_for_column("id").is_empty());
28847        assert!(bundle.foreign_keys_for_column("nonexistent").is_empty());
28848    }
28849
28850    #[test]
28851    fn sql_reflected_table_foreign_keys_for_column_handles_composite_fks() {
28852        let bundle = SqlReflectedTable {
28853            table_name: "rolling_fact".to_owned(),
28854            columns: vec![],
28855            primary_key_columns: vec![],
28856            indexes: vec![],
28857            foreign_keys: vec![SqlForeignKeySchema {
28858                constraint_name: None,
28859                columns: vec!["fyear".to_owned(), "fmonth".to_owned()],
28860                referenced_table: "rolling".to_owned(),
28861                referenced_columns: vec!["year".to_owned(), "month".to_owned()],
28862            }],
28863            unique_constraints: vec![],
28864            comment: None,
28865        };
28866        // Composite FK touches both fyear and fmonth — both should
28867        // surface the same FK.
28868        assert_eq!(bundle.foreign_keys_for_column("fyear").len(), 1);
28869        assert_eq!(bundle.foreign_keys_for_column("fmonth").len(), 1);
28870        assert!(bundle.foreign_keys_for_column("year").is_empty()); // referenced col, not from col
28871    }
28872
28873    #[test]
28874    fn sql_reflected_table_foreign_keys_for_column_returns_multiple_when_relevant() {
28875        // Rare but valid: one column participates in two FKs (e.g.
28876        // same column referenced by separate FKs to two parents).
28877        let bundle = SqlReflectedTable {
28878            table_name: "audit".to_owned(),
28879            columns: vec![],
28880            primary_key_columns: vec![],
28881            indexes: vec![],
28882            foreign_keys: vec![
28883                SqlForeignKeySchema {
28884                    constraint_name: Some("fk_audit_a".to_owned()),
28885                    columns: vec!["entity_id".to_owned()],
28886                    referenced_table: "users".to_owned(),
28887                    referenced_columns: vec!["id".to_owned()],
28888                },
28889                SqlForeignKeySchema {
28890                    constraint_name: Some("fk_audit_b".to_owned()),
28891                    columns: vec!["entity_id".to_owned()],
28892                    referenced_table: "products".to_owned(),
28893                    referenced_columns: vec!["id".to_owned()],
28894                },
28895            ],
28896            unique_constraints: vec![],
28897            comment: None,
28898        };
28899        let fks = bundle.foreign_keys_for_column("entity_id");
28900        assert_eq!(fks.len(), 2);
28901        // Order preserved.
28902        assert_eq!(fks[0].constraint_name.as_deref(), Some("fk_audit_a"));
28903        assert_eq!(fks[1].constraint_name.as_deref(), Some("fk_audit_b"));
28904    }
28905
28906    // ── indexes_for_column / unique_constraints_for_column (br-37uy / fd90.52) ─
28907
28908    #[test]
28909    fn sql_reflected_table_indexes_for_column_matches_any_position() {
28910        let bundle = SqlReflectedTable {
28911            table_name: "rolling".to_owned(),
28912            columns: vec![],
28913            primary_key_columns: vec![],
28914            indexes: vec![
28915                SqlIndexSchema {
28916                    name: "idx_rolling_year".to_owned(),
28917                    columns: vec!["year".to_owned()],
28918                    unique: false,
28919                },
28920                SqlIndexSchema {
28921                    name: "idx_rolling_y_m_c".to_owned(),
28922                    columns: vec!["year".to_owned(), "month".to_owned(), "code".to_owned()],
28923                    unique: false,
28924                },
28925            ],
28926            foreign_keys: vec![],
28927            unique_constraints: vec![],
28928            comment: None,
28929        };
28930
28931        // 'year' appears in both indexes (first in idx_year, first in
28932        // composite). Returns both.
28933        let year_idxs = bundle.indexes_for_column("year");
28934        assert_eq!(year_idxs.len(), 2);
28935
28936        // 'month' only appears in the composite index, in middle position.
28937        let month_idxs = bundle.indexes_for_column("month");
28938        assert_eq!(month_idxs.len(), 1);
28939        assert_eq!(month_idxs[0].name, "idx_rolling_y_m_c");
28940
28941        // 'code' appears only in the composite, last position.
28942        let code_idxs = bundle.indexes_for_column("code");
28943        assert_eq!(code_idxs.len(), 1);
28944
28945        // Column not in any index.
28946        assert!(bundle.indexes_for_column("nonexistent").is_empty());
28947    }
28948
28949    #[test]
28950    fn sql_reflected_table_unique_constraints_for_column_matches_any_position() {
28951        let bundle = SqlReflectedTable {
28952            table_name: "events".to_owned(),
28953            columns: vec![],
28954            primary_key_columns: vec![],
28955            indexes: vec![],
28956            foreign_keys: vec![],
28957            unique_constraints: vec![
28958                SqlUniqueConstraintSchema {
28959                    name: "uq_events_email".to_owned(),
28960                    columns: vec!["email".to_owned()],
28961                },
28962                SqlUniqueConstraintSchema {
28963                    name: "uq_events_user_event_ts".to_owned(),
28964                    columns: vec!["user_id".to_owned(), "event_id".to_owned(), "ts".to_owned()],
28965                },
28966            ],
28967            comment: None,
28968        };
28969
28970        let email_uqs = bundle.unique_constraints_for_column("email");
28971        assert_eq!(email_uqs.len(), 1);
28972        assert_eq!(email_uqs[0].name, "uq_events_email");
28973
28974        // 'event_id' middle position in composite.
28975        let event_uqs = bundle.unique_constraints_for_column("event_id");
28976        assert_eq!(event_uqs.len(), 1);
28977        assert_eq!(event_uqs[0].columns, vec!["user_id", "event_id", "ts"]);
28978
28979        // 'ts' last position in composite.
28980        let ts_uqs = bundle.unique_constraints_for_column("ts");
28981        assert_eq!(ts_uqs.len(), 1);
28982
28983        assert!(
28984            bundle
28985                .unique_constraints_for_column("nonexistent")
28986                .is_empty()
28987        );
28988    }
28989
28990    #[test]
28991    fn sql_reflected_table_for_column_accessors_return_multiple() {
28992        // A column can appear in multiple indexes / unique constraints.
28993        let bundle = SqlReflectedTable {
28994            table_name: "wide".to_owned(),
28995            columns: vec![],
28996            primary_key_columns: vec![],
28997            indexes: vec![
28998                SqlIndexSchema {
28999                    name: "idx_a".to_owned(),
29000                    columns: vec!["x".to_owned()],
29001                    unique: false,
29002                },
29003                SqlIndexSchema {
29004                    name: "idx_b".to_owned(),
29005                    columns: vec!["x".to_owned(), "y".to_owned()],
29006                    unique: true,
29007                },
29008            ],
29009            foreign_keys: vec![],
29010            unique_constraints: vec![
29011                SqlUniqueConstraintSchema {
29012                    name: "uq_a".to_owned(),
29013                    columns: vec!["x".to_owned()],
29014                },
29015                SqlUniqueConstraintSchema {
29016                    name: "uq_b".to_owned(),
29017                    columns: vec!["x".to_owned(), "z".to_owned()],
29018                },
29019            ],
29020            comment: None,
29021        };
29022
29023        let idx_for_x = bundle.indexes_for_column("x");
29024        assert_eq!(idx_for_x.len(), 2);
29025        assert_eq!(idx_for_x[0].name, "idx_a");
29026        assert_eq!(idx_for_x[1].name, "idx_b");
29027
29028        let uq_for_x = bundle.unique_constraints_for_column("x");
29029        assert_eq!(uq_for_x.len(), 2);
29030        assert_eq!(uq_for_x[0].name, "uq_a");
29031        assert_eq!(uq_for_x[1].name, "uq_b");
29032    }
29033
29034    // ── SqlInspector::reflect_all_tables (br-jmmo / fd90.53) ─────────────
29035
29036    #[cfg(feature = "sql-sqlite")]
29037    #[test]
29038    fn sql_inspector_reflect_all_tables_empty_db() {
29039        let conn = make_sql_test_conn();
29040        let inspector = SqlInspector::new(&conn);
29041        let bundles = inspector.reflect_all_tables(None).unwrap();
29042        assert!(bundles.is_empty());
29043    }
29044
29045    #[cfg(feature = "sql-sqlite")]
29046    #[test]
29047    fn sql_inspector_reflect_all_tables_returns_one_bundle_per_table() {
29048        let conn = make_sql_test_conn();
29049        super::SqlConnection::execute_batch(
29050            &conn,
29051            "CREATE TABLE alpha (id INTEGER PRIMARY KEY, name TEXT);",
29052        )
29053        .unwrap();
29054        super::SqlConnection::execute_batch(&conn, "CREATE TABLE beta (uid INTEGER, label TEXT);")
29055            .unwrap();
29056        let inspector = SqlInspector::new(&conn);
29057        let bundles = inspector.reflect_all_tables(None).unwrap();
29058        assert_eq!(bundles.len(), 2);
29059        // Ordered alphabetically by list_tables.
29060        assert_eq!(bundles[0].table_name, "alpha");
29061        assert_eq!(bundles[1].table_name, "beta");
29062        // Each bundle has full metadata.
29063        assert_eq!(
29064            bundles[0]
29065                .columns
29066                .iter()
29067                .map(|c| c.name.as_str())
29068                .collect::<Vec<_>>(),
29069            vec!["id", "name"]
29070        );
29071        assert_eq!(bundles[0].primary_key_columns, vec!["id"]);
29072        assert_eq!(bundles[1].columns.len(), 2);
29073        assert!(bundles[1].primary_key_columns.is_empty());
29074    }
29075
29076    #[test]
29077    fn sql_inspector_reflect_all_tables_skips_disappearing_tables() {
29078        // Race-condition stub: list_tables returns ["a", "b"] but
29079        // table_schema returns None for "b" (simulating a concurrent
29080        // DROP between list and reflect). reflect_all_tables must
29081        // skip "b" without erroring.
29082        struct DisappearingTable;
29083        impl super::SqlConnection for DisappearingTable {
29084            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
29085                Ok(SqlQueryResult {
29086                    columns: vec![],
29087                    rows: vec![],
29088                })
29089            }
29090            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
29091                Ok(())
29092            }
29093            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
29094                Ok(false)
29095            }
29096            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
29097                Ok(())
29098            }
29099            fn dtype_sql(&self, _dtype: DType) -> &'static str {
29100                "TEXT"
29101            }
29102            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
29103                "TEXT"
29104            }
29105            fn list_tables(&self, _schema: Option<&str>) -> Result<Vec<String>, IoError> {
29106                Ok(vec!["a".to_owned(), "b".to_owned()])
29107            }
29108            fn table_schema(
29109                &self,
29110                table: &str,
29111                _schema: Option<&str>,
29112            ) -> Result<Option<SqlTableSchema>, IoError> {
29113                if table == "a" {
29114                    Ok(Some(SqlTableSchema {
29115                        table_name: "a".to_owned(),
29116                        columns: vec![SqlColumnSchema {
29117                            name: "x".to_owned(),
29118                            declared_type: Some("INTEGER".to_owned()),
29119                            nullable: true,
29120                            default_value: None,
29121                            primary_key_ordinal: None,
29122                            comment: None,
29123                            autoincrement: false,
29124                        }],
29125                    }))
29126                } else {
29127                    // b "disappeared" between list and reflect.
29128                    Ok(None)
29129                }
29130            }
29131        }
29132        let conn = DisappearingTable;
29133        let inspector = SqlInspector::new(&conn);
29134        let bundles = inspector.reflect_all_tables(None).unwrap();
29135        assert_eq!(bundles.len(), 1);
29136        assert_eq!(bundles[0].table_name, "a");
29137    }
29138
29139    #[test]
29140    fn sql_inspector_reflect_all_tables_routes_schema_arg() {
29141        // Multi-schema stub: list_tables returns different sets per
29142        // schema; reflect_all_tables must propagate the schema arg.
29143        struct MultiSchemaReflect;
29144        impl super::SqlConnection for MultiSchemaReflect {
29145            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
29146                Ok(SqlQueryResult {
29147                    columns: vec![],
29148                    rows: vec![],
29149                })
29150            }
29151            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
29152                Ok(())
29153            }
29154            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
29155                Ok(false)
29156            }
29157            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
29158                Ok(())
29159            }
29160            fn dtype_sql(&self, _dtype: DType) -> &'static str {
29161                "TEXT"
29162            }
29163            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
29164                "TEXT"
29165            }
29166            fn supports_schemas(&self) -> bool {
29167                true
29168            }
29169            fn list_tables(&self, schema: Option<&str>) -> Result<Vec<String>, IoError> {
29170                Ok(match schema {
29171                    Some("analytics") => vec!["events".to_owned()],
29172                    _ => vec![],
29173                })
29174            }
29175            fn table_schema(
29176                &self,
29177                table: &str,
29178                schema: Option<&str>,
29179            ) -> Result<Option<SqlTableSchema>, IoError> {
29180                if table == "events" && schema == Some("analytics") {
29181                    Ok(Some(SqlTableSchema {
29182                        table_name: "events".to_owned(),
29183                        columns: vec![SqlColumnSchema {
29184                            name: "ts".to_owned(),
29185                            declared_type: Some("TIMESTAMPTZ".to_owned()),
29186                            nullable: false,
29187                            default_value: None,
29188                            primary_key_ordinal: None,
29189                            comment: None,
29190                            autoincrement: false,
29191                        }],
29192                    }))
29193                } else {
29194                    Ok(None)
29195                }
29196            }
29197        }
29198        let conn = MultiSchemaReflect;
29199        let inspector = SqlInspector::new(&conn);
29200        let bundles = inspector.reflect_all_tables(Some("analytics")).unwrap();
29201        assert_eq!(bundles.len(), 1);
29202        assert_eq!(bundles[0].table_name, "events");
29203        assert_eq!(
29204            bundles[0].columns[0].declared_type.as_deref(),
29205            Some("TIMESTAMPTZ")
29206        );
29207        // Wrong schema -> empty.
29208        assert!(
29209            inspector
29210                .reflect_all_tables(Some("audit"))
29211                .unwrap()
29212                .is_empty()
29213        );
29214    }
29215
29216    // ── SqlInspector::reflect_all_views (br-zuqt / fd90.54) ──────────────
29217
29218    #[cfg(feature = "sql-sqlite")]
29219    #[test]
29220    fn sql_inspector_reflect_all_views_empty_db() {
29221        let conn = make_sql_test_conn();
29222        let inspector = SqlInspector::new(&conn);
29223        let bundles = inspector.reflect_all_views(None).unwrap();
29224        assert!(bundles.is_empty());
29225    }
29226
29227    #[cfg(feature = "sql-sqlite")]
29228    #[test]
29229    fn sql_inspector_reflect_all_views_returns_one_bundle_per_view() {
29230        let conn = make_sql_test_conn();
29231        super::SqlConnection::execute_batch(&conn, "CREATE TABLE base (id INTEGER, label TEXT);")
29232            .unwrap();
29233        super::SqlConnection::execute_batch(
29234            &conn,
29235            "CREATE VIEW alpha_view AS SELECT id FROM base;",
29236        )
29237        .unwrap();
29238        super::SqlConnection::execute_batch(
29239            &conn,
29240            "CREATE VIEW zebra_view AS SELECT label FROM base;",
29241        )
29242        .unwrap();
29243        let inspector = SqlInspector::new(&conn);
29244        let bundles = inspector.reflect_all_views(None).unwrap();
29245        // Tables ARE NOT included — only views.
29246        assert_eq!(bundles.len(), 2);
29247        assert_eq!(bundles[0].table_name, "alpha_view");
29248        assert_eq!(bundles[1].table_name, "zebra_view");
29249        // Each view's columns are surfaced via PRAGMA table_info.
29250        assert_eq!(
29251            bundles[0]
29252                .columns
29253                .iter()
29254                .map(|c| c.name.as_str())
29255                .collect::<Vec<_>>(),
29256            vec!["id"]
29257        );
29258        assert_eq!(
29259            bundles[1]
29260                .columns
29261                .iter()
29262                .map(|c| c.name.as_str())
29263                .collect::<Vec<_>>(),
29264            vec!["label"]
29265        );
29266        // Views don't carry constraints — PK/FK/UC/index lists are empty.
29267        for bundle in &bundles {
29268            assert!(bundle.primary_key_columns.is_empty());
29269            assert!(bundle.indexes.is_empty());
29270            assert!(bundle.foreign_keys.is_empty());
29271            assert!(bundle.unique_constraints.is_empty());
29272        }
29273    }
29274
29275    #[test]
29276    fn sql_inspector_reflect_all_views_routes_schema_arg() {
29277        // Multi-schema stub: list_views returns different sets per schema.
29278        struct MultiSchemaViewReflect;
29279        impl super::SqlConnection for MultiSchemaViewReflect {
29280            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
29281                Ok(SqlQueryResult {
29282                    columns: vec![],
29283                    rows: vec![],
29284                })
29285            }
29286            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
29287                Ok(())
29288            }
29289            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
29290                Ok(false)
29291            }
29292            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
29293                Ok(())
29294            }
29295            fn dtype_sql(&self, _dtype: DType) -> &'static str {
29296                "TEXT"
29297            }
29298            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
29299                "TEXT"
29300            }
29301            fn supports_schemas(&self) -> bool {
29302                true
29303            }
29304            fn list_views(&self, schema: Option<&str>) -> Result<Vec<String>, IoError> {
29305                Ok(match schema {
29306                    Some("reporting") => vec!["weekly_summary".to_owned()],
29307                    _ => vec![],
29308                })
29309            }
29310            fn table_schema(
29311                &self,
29312                table: &str,
29313                schema: Option<&str>,
29314            ) -> Result<Option<SqlTableSchema>, IoError> {
29315                if table == "weekly_summary" && schema == Some("reporting") {
29316                    Ok(Some(SqlTableSchema {
29317                        table_name: "weekly_summary".to_owned(),
29318                        columns: vec![SqlColumnSchema {
29319                            name: "week".to_owned(),
29320                            declared_type: Some("DATE".to_owned()),
29321                            nullable: true,
29322                            default_value: None,
29323                            primary_key_ordinal: None,
29324                            comment: None,
29325                            autoincrement: false,
29326                        }],
29327                    }))
29328                } else {
29329                    Ok(None)
29330                }
29331            }
29332        }
29333        let conn = MultiSchemaViewReflect;
29334        let inspector = SqlInspector::new(&conn);
29335        let bundles = inspector.reflect_all_views(Some("reporting")).unwrap();
29336        assert_eq!(bundles.len(), 1);
29337        assert_eq!(bundles[0].table_name, "weekly_summary");
29338        assert_eq!(bundles[0].columns[0].declared_type.as_deref(), Some("DATE"));
29339        // Wrong schema -> empty.
29340        assert!(
29341            inspector
29342                .reflect_all_views(Some("audit"))
29343                .unwrap()
29344                .is_empty()
29345        );
29346    }
29347
29348    #[test]
29349    fn sql_inspector_reflect_table_calls_table_schema_only_once() {
29350        // Per fd90.43: reflect_table must derive primary_key_columns
29351        // from the fetched SqlTableSchema rather than dispatching
29352        // primary_key_columns() (which itself calls table_schema). A
29353        // recording stub counts table_schema invocations and asserts
29354        // exactly one round-trip.
29355        use std::cell::Cell;
29356        struct CountingTableSchema {
29357            table_schema_calls: Cell<usize>,
29358        }
29359        impl super::SqlConnection for CountingTableSchema {
29360            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<SqlQueryResult, IoError> {
29361                Ok(SqlQueryResult {
29362                    columns: vec![],
29363                    rows: vec![],
29364                })
29365            }
29366            fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
29367                Ok(())
29368            }
29369            fn table_exists(&self, _name: &str) -> Result<bool, IoError> {
29370                Ok(false)
29371            }
29372            fn insert_rows(&self, _sql: &str, _rows: &[Vec<Scalar>]) -> Result<(), IoError> {
29373                Ok(())
29374            }
29375            fn dtype_sql(&self, _dtype: DType) -> &'static str {
29376                "TEXT"
29377            }
29378            fn index_dtype_sql(&self, _index: &Index) -> &'static str {
29379                "TEXT"
29380            }
29381            fn table_schema(
29382                &self,
29383                _table: &str,
29384                _schema: Option<&str>,
29385            ) -> Result<Option<SqlTableSchema>, IoError> {
29386                self.table_schema_calls
29387                    .set(self.table_schema_calls.get() + 1);
29388                Ok(Some(SqlTableSchema {
29389                    table_name: "x".to_owned(),
29390                    columns: vec![SqlColumnSchema {
29391                        name: "id".to_owned(),
29392                        declared_type: Some("BIGINT".to_owned()),
29393                        nullable: false,
29394                        default_value: None,
29395                        primary_key_ordinal: Some(0),
29396                        comment: None,
29397                        autoincrement: true,
29398                    }],
29399                }))
29400            }
29401        }
29402        let conn = CountingTableSchema {
29403            table_schema_calls: Cell::new(0),
29404        };
29405        let inspector = SqlInspector::new(&conn);
29406        let bundle = inspector.reflect_table("x", None).unwrap().unwrap();
29407        // Exactly one table_schema fetch — primary_key_columns derived
29408        // from the fetched meta, NOT a second round-trip.
29409        assert_eq!(conn.table_schema_calls.get(), 1);
29410        assert_eq!(bundle.primary_key_columns, vec!["id"]);
29411    }
29412
29413    // ── SqlReadOptions default coerce_float (br-o0x6 / fd90.41) ──────────
29414
29415    #[test]
29416    fn sql_read_options_default_coerce_float_matches_pandas() {
29417        // Pandas defaults coerce_float=True for read_sql / read_sql_query
29418        // / read_sql_table. We must match — any bare ::default() call
29419        // should opt INTO coerce_float, not opt out.
29420        let opts = SqlReadOptions::default();
29421        assert!(
29422            opts.coerce_float,
29423            "default coerce_float must be true (pandas parity)"
29424        );
29425        // Sanity: other defaults are the natural empty / None values.
29426        assert!(opts.params.is_none());
29427        assert!(opts.parse_dates.is_none());
29428        assert!(opts.dtype.is_none());
29429        assert!(opts.schema.is_none());
29430        assert!(opts.columns.is_none());
29431        assert!(opts.index_col.is_none());
29432    }
29433
29434    // ── SQL identifier quoting regression matrix (br-frankenpandas-fd90.12) ─
29435    //
29436    // Cross-product of (ANSI / MySQL backtick / MSSQL bracket) quoting
29437    // backends × (SELECT * / SELECT cols / CREATE TABLE / INSERT /
29438    // multi-row INSERT / DROP / TRUNCATE) × identifier shapes that the
29439    // shared validator currently allows: reserved-word names, mixed case,
29440    // leading digits, embedded quote chars (where the backend defines an
29441    // escape rule). All tests are pure query-builder assertions — no live
29442    // backend touched.
29443
29444    #[derive(Default)]
29445    struct AnsiSchemaConn;
29446    impl super::SqlConnection for AnsiSchemaConn {
29447        fn query(&self, _q: &str, _p: &[Scalar]) -> Result<super::SqlQueryResult, IoError> {
29448            Ok(super::SqlQueryResult {
29449                columns: vec![],
29450                rows: vec![],
29451            })
29452        }
29453        fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
29454            Ok(())
29455        }
29456        fn table_exists(&self, _n: &str) -> Result<bool, IoError> {
29457            Ok(false)
29458        }
29459        fn insert_rows(&self, _s: &str, _r: &[Vec<Scalar>]) -> Result<(), IoError> {
29460            Ok(())
29461        }
29462        fn dtype_sql(&self, _d: DType) -> &'static str {
29463            "TEXT"
29464        }
29465        fn index_dtype_sql(&self, _i: &Index) -> &'static str {
29466            "TEXT"
29467        }
29468        fn supports_schemas(&self) -> bool {
29469            true
29470        }
29471        fn parameter_marker(&self, ordinal: usize) -> String {
29472            format!("${ordinal}")
29473        }
29474        fn max_identifier_length(&self) -> Option<usize> {
29475            Some(63)
29476        }
29477    }
29478
29479    #[derive(Default)]
29480    struct MysqlBacktickConn;
29481    impl super::SqlConnection for MysqlBacktickConn {
29482        fn query(&self, _q: &str, _p: &[Scalar]) -> Result<super::SqlQueryResult, IoError> {
29483            Ok(super::SqlQueryResult {
29484                columns: vec![],
29485                rows: vec![],
29486            })
29487        }
29488        fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
29489            Ok(())
29490        }
29491        fn table_exists(&self, _n: &str) -> Result<bool, IoError> {
29492            Ok(false)
29493        }
29494        fn insert_rows(&self, _s: &str, _r: &[Vec<Scalar>]) -> Result<(), IoError> {
29495            Ok(())
29496        }
29497        fn dtype_sql(&self, _d: DType) -> &'static str {
29498            "TEXT"
29499        }
29500        fn index_dtype_sql(&self, _i: &Index) -> &'static str {
29501            "TEXT"
29502        }
29503        fn supports_schemas(&self) -> bool {
29504            true
29505        }
29506        fn parameter_marker(&self, _ordinal: usize) -> String {
29507            "?".to_owned()
29508        }
29509        fn max_identifier_length(&self) -> Option<usize> {
29510            Some(64)
29511        }
29512        fn quote_identifier(&self, ident: &str) -> Result<String, IoError> {
29513            if ident.contains('\0') {
29514                return Err(IoError::Sql("invalid SQL identifier: NUL byte".to_owned()));
29515            }
29516            Ok(format!("`{}`", ident.replace('`', "``")))
29517        }
29518    }
29519
29520    #[derive(Default)]
29521    struct MssqlBracketConn;
29522    impl super::SqlConnection for MssqlBracketConn {
29523        fn query(&self, _q: &str, _p: &[Scalar]) -> Result<super::SqlQueryResult, IoError> {
29524            Ok(super::SqlQueryResult {
29525                columns: vec![],
29526                rows: vec![],
29527            })
29528        }
29529        fn execute_batch(&self, _sql: &str) -> Result<(), IoError> {
29530            Ok(())
29531        }
29532        fn table_exists(&self, _n: &str) -> Result<bool, IoError> {
29533            Ok(false)
29534        }
29535        fn insert_rows(&self, _s: &str, _r: &[Vec<Scalar>]) -> Result<(), IoError> {
29536            Ok(())
29537        }
29538        fn dtype_sql(&self, _d: DType) -> &'static str {
29539            "NVARCHAR(MAX)"
29540        }
29541        fn index_dtype_sql(&self, _i: &Index) -> &'static str {
29542            "NVARCHAR(MAX)"
29543        }
29544        fn supports_schemas(&self) -> bool {
29545            true
29546        }
29547        fn parameter_marker(&self, ordinal: usize) -> String {
29548            format!("@p{ordinal}")
29549        }
29550        fn max_identifier_length(&self) -> Option<usize> {
29551            Some(128)
29552        }
29553        fn quote_identifier(&self, ident: &str) -> Result<String, IoError> {
29554            if ident.contains('\0') {
29555                return Err(IoError::Sql("invalid SQL identifier: NUL byte".to_owned()));
29556            }
29557            // T-SQL bracket quoting: doubled `]` escapes a literal `]`.
29558            Ok(format!("[{}]", ident.replace(']', "]]")))
29559        }
29560    }
29561
29562    /// Reserved SQL keywords that the shape validator allows as
29563    /// alphanumeric identifiers — they must round-trip through every
29564    /// query builder safely (i.e. quoted, never bare).
29565    const FD90_12_RESERVED_WORDS: &[&str] = &[
29566        "select", "from", "where", "order", "group", "table", "index", "join",
29567    ];
29568
29569    #[test]
29570    fn fd90_12_quoting_matrix_select_all_reserved_words_quoted_per_dialect() {
29571        let ansi = AnsiSchemaConn;
29572        let mysql = MysqlBacktickConn;
29573        let mssql = MssqlBracketConn;
29574        for word in FD90_12_RESERVED_WORDS {
29575            assert_eq!(
29576                super::sql_select_all_query(&ansi, word).expect("ansi select"),
29577                format!("SELECT * FROM \"{word}\""),
29578                "ansi reserved word `{word}`"
29579            );
29580            assert_eq!(
29581                super::sql_select_all_query(&mysql, word).expect("mysql select"),
29582                format!("SELECT * FROM `{word}`"),
29583                "mysql reserved word `{word}`"
29584            );
29585            assert_eq!(
29586                super::sql_select_all_query(&mssql, word).expect("mssql select"),
29587                format!("SELECT * FROM [{word}]"),
29588                "mssql reserved word `{word}`"
29589            );
29590        }
29591    }
29592
29593    #[test]
29594    fn fd90_12_quoting_matrix_select_columns_mixed_case_preserved_per_dialect() {
29595        let ansi = AnsiSchemaConn;
29596        let mysql = MysqlBacktickConn;
29597        let mssql = MssqlBracketConn;
29598        let cases: &[&str] = &["MyCol", "MIXEDcase", "camelCase", "SCREAMING_SNAKE"];
29599        for col in cases {
29600            assert_eq!(
29601                super::sql_select_columns_query(&ansi, "users", &[col]).expect("ansi cols"),
29602                format!("SELECT \"{col}\" FROM \"users\""),
29603                "ansi mixed-case col `{col}`"
29604            );
29605            assert_eq!(
29606                super::sql_select_columns_query(&mysql, "users", &[col]).expect("mysql cols"),
29607                format!("SELECT `{col}` FROM `users`"),
29608                "mysql mixed-case col `{col}`"
29609            );
29610            assert_eq!(
29611                super::sql_select_columns_query(&mssql, "users", &[col]).expect("mssql cols"),
29612                format!("SELECT [{col}] FROM [users]"),
29613                "mssql mixed-case col `{col}`"
29614            );
29615        }
29616    }
29617
29618    #[test]
29619    fn fd90_12_quoting_matrix_leading_digit_identifiers_quoted_per_dialect() {
29620        let ansi = AnsiSchemaConn;
29621        let mysql = MysqlBacktickConn;
29622        let mssql = MssqlBracketConn;
29623        let cases: &[&str] = &["1col", "2nd_place", "9lives", "123"];
29624        for col in cases {
29625            assert_eq!(
29626                super::sql_select_columns_query(&ansi, "tbl", &[col]).expect("ansi"),
29627                format!("SELECT \"{col}\" FROM \"tbl\"")
29628            );
29629            assert_eq!(
29630                super::sql_select_columns_query(&mysql, "tbl", &[col]).expect("mysql"),
29631                format!("SELECT `{col}` FROM `tbl`")
29632            );
29633            assert_eq!(
29634                super::sql_select_columns_query(&mssql, "tbl", &[col]).expect("mssql"),
29635                format!("SELECT [{col}] FROM [tbl]")
29636            );
29637        }
29638    }
29639
29640    #[test]
29641    fn fd90_12_quoting_matrix_schema_qualified_select_per_dialect() {
29642        let ansi = AnsiSchemaConn;
29643        let mysql = MysqlBacktickConn;
29644        let mssql = MssqlBracketConn;
29645        assert_eq!(
29646            super::sql_select_all_query_in_schema(&ansi, "users", Some("analytics")).expect("ansi"),
29647            "SELECT * FROM \"analytics\".\"users\""
29648        );
29649        assert_eq!(
29650            super::sql_select_all_query_in_schema(&mysql, "users", Some("analytics"))
29651                .expect("mysql"),
29652            "SELECT * FROM `analytics`.`users`"
29653        );
29654        assert_eq!(
29655            super::sql_select_all_query_in_schema(&mssql, "users", Some("dbo")).expect("mssql"),
29656            "SELECT * FROM [dbo].[users]"
29657        );
29658    }
29659
29660    #[test]
29661    fn fd90_12_quoting_matrix_create_table_per_dialect() {
29662        let ansi = AnsiSchemaConn;
29663        let mysql = MysqlBacktickConn;
29664        let mssql = MssqlBracketConn;
29665        let cols = vec![
29666            super::sql_column_definition(&ansi, "id", "BIGINT").expect("ansi col"),
29667            super::sql_column_definition(&ansi, "select", "TEXT").expect("ansi reserved col"),
29668        ];
29669        assert_eq!(
29670            super::sql_create_table_query_in_schema(&ansi, "events", Some("public"), &cols)
29671                .expect("ansi create"),
29672            "CREATE TABLE IF NOT EXISTS \"public\".\"events\" (\"id\" BIGINT, \"select\" TEXT)"
29673        );
29674        let mysql_cols = vec![
29675            super::sql_column_definition(&mysql, "id", "BIGINT").expect("mysql col"),
29676            super::sql_column_definition(&mysql, "select", "TEXT").expect("mysql reserved col"),
29677        ];
29678        assert_eq!(
29679            super::sql_create_table_query_in_schema(
29680                &mysql,
29681                "events",
29682                Some("analytics"),
29683                &mysql_cols
29684            )
29685            .expect("mysql create"),
29686            "CREATE TABLE IF NOT EXISTS `analytics`.`events` (`id` BIGINT, `select` TEXT)"
29687        );
29688        let mssql_cols = vec![
29689            super::sql_column_definition(&mssql, "id", "BIGINT").expect("mssql col"),
29690            super::sql_column_definition(&mssql, "select", "NVARCHAR(MAX)")
29691                .expect("mssql reserved col"),
29692        ];
29693        assert_eq!(
29694            super::sql_create_table_query_in_schema(&mssql, "events", Some("dbo"), &mssql_cols)
29695                .expect("mssql create"),
29696            "CREATE TABLE IF NOT EXISTS [dbo].[events] ([id] BIGINT, [select] NVARCHAR(MAX))"
29697        );
29698    }
29699
29700    #[test]
29701    fn fd90_12_quoting_matrix_insert_per_dialect_with_param_markers() {
29702        let ansi = AnsiSchemaConn;
29703        let mysql = MysqlBacktickConn;
29704        let mssql = MssqlBracketConn;
29705        let cols = vec!["id".to_owned(), "MixedCase".to_owned(), "select".to_owned()];
29706        assert_eq!(
29707            super::sql_insert_rows_query_in_schema(&ansi, "events", Some("public"), &cols)
29708                .expect("ansi insert"),
29709            "INSERT INTO \"public\".\"events\" (\"id\", \"MixedCase\", \"select\") VALUES ($1, $2, $3)"
29710        );
29711        assert_eq!(
29712            super::sql_insert_rows_query_in_schema(&mysql, "events", Some("analytics"), &cols)
29713                .expect("mysql insert"),
29714            "INSERT INTO `analytics`.`events` (`id`, `MixedCase`, `select`) VALUES (?, ?, ?)"
29715        );
29716        assert_eq!(
29717            super::sql_insert_rows_query_in_schema(&mssql, "events", Some("dbo"), &cols)
29718                .expect("mssql insert"),
29719            "INSERT INTO [dbo].[events] ([id], [MixedCase], [select]) VALUES (@p1, @p2, @p3)"
29720        );
29721    }
29722
29723    #[test]
29724    fn fd90_12_quoting_matrix_multi_row_insert_param_ordinals_span_rows() {
29725        let ansi = AnsiSchemaConn;
29726        let mysql = MysqlBacktickConn;
29727        let cols = vec!["a".to_owned(), "b".to_owned()];
29728        assert_eq!(
29729            super::sql_multi_row_insert_query_in_schema(&ansi, "tbl", None, &cols, 2)
29730                .expect("ansi multi"),
29731            "INSERT INTO \"tbl\" (\"a\", \"b\") VALUES ($1, $2), ($3, $4)"
29732        );
29733        assert_eq!(
29734            super::sql_multi_row_insert_query_in_schema(&mysql, "tbl", None, &cols, 2)
29735                .expect("mysql multi"),
29736            "INSERT INTO `tbl` (`a`, `b`) VALUES (?, ?), (?, ?)"
29737        );
29738    }
29739
29740    #[test]
29741    fn fd90_12_quoting_matrix_drop_table_per_dialect() {
29742        let ansi = AnsiSchemaConn;
29743        let mysql = MysqlBacktickConn;
29744        let mssql = MssqlBracketConn;
29745        assert_eq!(
29746            super::sql_drop_table_query_in_schema(&ansi, "events", Some("public"))
29747                .expect("ansi drop"),
29748            "DROP TABLE IF EXISTS \"public\".\"events\""
29749        );
29750        assert_eq!(
29751            super::sql_drop_table_query_in_schema(&mysql, "events", Some("analytics"))
29752                .expect("mysql drop"),
29753            "DROP TABLE IF EXISTS `analytics`.`events`"
29754        );
29755        assert_eq!(
29756            super::sql_drop_table_query_in_schema(&mssql, "events", Some("dbo"))
29757                .expect("mssql drop"),
29758            "DROP TABLE IF EXISTS [dbo].[events]"
29759        );
29760    }
29761
29762    #[test]
29763    fn fd90_12_quoting_matrix_truncate_uses_default_delete_with_per_dialect_quoting() {
29764        // Default truncate_table impl emits `DELETE FROM <quoted>` and
29765        // routes through the backend's quote_identifier.
29766        #[derive(Default)]
29767        struct CapturingAnsi {
29768            captured: std::cell::RefCell<Vec<String>>,
29769        }
29770        impl super::SqlConnection for CapturingAnsi {
29771            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<super::SqlQueryResult, IoError> {
29772                Ok(super::SqlQueryResult {
29773                    columns: vec![],
29774                    rows: vec![],
29775                })
29776            }
29777            fn execute_batch(&self, sql: &str) -> Result<(), IoError> {
29778                self.captured.borrow_mut().push(sql.to_owned());
29779                Ok(())
29780            }
29781            fn table_exists(&self, _n: &str) -> Result<bool, IoError> {
29782                Ok(false)
29783            }
29784            fn insert_rows(&self, _s: &str, _r: &[Vec<Scalar>]) -> Result<(), IoError> {
29785                Ok(())
29786            }
29787            fn dtype_sql(&self, _d: DType) -> &'static str {
29788                "TEXT"
29789            }
29790            fn index_dtype_sql(&self, _i: &Index) -> &'static str {
29791                "TEXT"
29792            }
29793            fn supports_schemas(&self) -> bool {
29794                true
29795            }
29796        }
29797        let ansi = CapturingAnsi::default();
29798        super::SqlConnection::truncate_table(&ansi, "events", Some("public"))
29799            .expect("ansi truncate");
29800        assert_eq!(
29801            ansi.captured.borrow().as_slice(),
29802            &["DELETE FROM \"public\".\"events\"".to_owned()]
29803        );
29804
29805        #[derive(Default)]
29806        struct CapturingMysql {
29807            captured: std::cell::RefCell<Vec<String>>,
29808        }
29809        impl super::SqlConnection for CapturingMysql {
29810            fn query(&self, _q: &str, _p: &[Scalar]) -> Result<super::SqlQueryResult, IoError> {
29811                Ok(super::SqlQueryResult {
29812                    columns: vec![],
29813                    rows: vec![],
29814                })
29815            }
29816            fn execute_batch(&self, sql: &str) -> Result<(), IoError> {
29817                self.captured.borrow_mut().push(sql.to_owned());
29818                Ok(())
29819            }
29820            fn table_exists(&self, _n: &str) -> Result<bool, IoError> {
29821                Ok(false)
29822            }
29823            fn insert_rows(&self, _s: &str, _r: &[Vec<Scalar>]) -> Result<(), IoError> {
29824                Ok(())
29825            }
29826            fn dtype_sql(&self, _d: DType) -> &'static str {
29827                "TEXT"
29828            }
29829            fn index_dtype_sql(&self, _i: &Index) -> &'static str {
29830                "TEXT"
29831            }
29832            fn supports_schemas(&self) -> bool {
29833                true
29834            }
29835            fn quote_identifier(&self, ident: &str) -> Result<String, IoError> {
29836                if ident.contains('\0') {
29837                    return Err(IoError::Sql("invalid SQL identifier: NUL byte".to_owned()));
29838                }
29839                Ok(format!("`{}`", ident.replace('`', "``")))
29840            }
29841        }
29842        let mysql = CapturingMysql::default();
29843        super::SqlConnection::truncate_table(&mysql, "events", Some("analytics"))
29844            .expect("mysql truncate");
29845        assert_eq!(
29846            mysql.captured.borrow().as_slice(),
29847            &["DELETE FROM `analytics`.`events`".to_owned()]
29848        );
29849    }
29850
29851    #[test]
29852    fn fd90_12_quoting_matrix_embedded_quote_chars_doubled_per_dialect() {
29853        // Embedded quote chars must be doubled per the dialect's escape
29854        // rule. quote_identifier is exposed for column names which may
29855        // legitimately contain embedded quotes (sql_column_definition
29856        // takes any string).
29857        let ansi = AnsiSchemaConn;
29858        let mysql = MysqlBacktickConn;
29859        let mssql = MssqlBracketConn;
29860        use super::SqlConnection as _;
29861        assert_eq!(ansi.quote_identifier("a\"b").expect("ansi"), "\"a\"\"b\"");
29862        assert_eq!(mysql.quote_identifier("a`b").expect("mysql"), "`a``b`");
29863        assert_eq!(mssql.quote_identifier("a]b").expect("mssql"), "[a]]b]");
29864        // Cross-dialect non-escape: ANSI doesn't escape backticks, etc.
29865        assert_eq!(
29866            ansi.quote_identifier("a`b")
29867                .expect("ansi backtick passthrough"),
29868            "\"a`b\""
29869        );
29870        assert_eq!(
29871            mysql
29872                .quote_identifier("a\"b")
29873                .expect("mysql quote passthrough"),
29874            "`a\"b`"
29875        );
29876        assert_eq!(
29877            mssql
29878                .quote_identifier("a\"b")
29879                .expect("mssql quote passthrough"),
29880            "[a\"b]"
29881        );
29882    }
29883
29884    #[test]
29885    fn fd90_12_quoting_matrix_long_identifier_within_cap_succeeds_over_cap_rejected() {
29886        // PG cap = 63, MySQL cap = 64, MSSQL cap = 128.
29887        use super::SqlConnection as _;
29888        let ansi = AnsiSchemaConn;
29889        let mysql = MysqlBacktickConn;
29890        let mssql = MssqlBracketConn;
29891        let pg63 = "a".repeat(63);
29892        let pg64 = "a".repeat(64);
29893        let mysql64 = "b".repeat(64);
29894        let mysql65 = "b".repeat(65);
29895        let mssql128 = "c".repeat(128);
29896        let mssql129 = "c".repeat(129);
29897
29898        super::validate_sql_identifier_length(&pg63, ansi.max_identifier_length(), "table")
29899            .expect("pg 63 ok");
29900        super::validate_sql_identifier_length(&mysql64, mysql.max_identifier_length(), "table")
29901            .expect("mysql 64 ok");
29902        super::validate_sql_identifier_length(&mssql128, mssql.max_identifier_length(), "table")
29903            .expect("mssql 128 ok");
29904
29905        let err =
29906            super::validate_sql_identifier_length(&pg64, ansi.max_identifier_length(), "table")
29907                .expect_err("pg 64 over cap");
29908        assert!(matches!(err, IoError::Sql(msg) if msg.contains("63") && msg.contains("table")));
29909        let err =
29910            super::validate_sql_identifier_length(&mysql65, mysql.max_identifier_length(), "table")
29911                .expect_err("mysql 65 over cap");
29912        assert!(matches!(err, IoError::Sql(msg) if msg.contains("64")));
29913        let err = super::validate_sql_identifier_length(
29914            &mssql129,
29915            mssql.max_identifier_length(),
29916            "table",
29917        )
29918        .expect_err("mssql 129 over cap");
29919        assert!(matches!(err, IoError::Sql(msg) if msg.contains("128")));
29920    }
29921
29922    #[test]
29923    fn fd90_12_query_builders_enforce_identifier_length_caps() {
29924        fn assert_length_error(err: IoError, kind: &str) {
29925            assert!(
29926                matches!(&err, IoError::Sql(msg)
29927                    if msg.contains(kind)
29928                        && msg.contains("63")
29929                        && msg.contains("backend identifier limit")),
29930                "expected SQL identifier-length error for {kind}, got {err:?}"
29931            );
29932        }
29933
29934        let conn = AnsiSchemaConn;
29935        let over_cap = "a".repeat(64);
29936        let cols = vec![over_cap.clone()];
29937        let defs = vec!["id BIGINT".to_owned()];
29938
29939        assert_length_error(
29940            super::sql_select_all_query_in_schema(&conn, &over_cap, None)
29941                .expect_err("SELECT * table over cap"),
29942            "table",
29943        );
29944        assert_length_error(
29945            super::sql_select_all_query_in_schema(&conn, "events", Some(&over_cap))
29946                .expect_err("SELECT * schema over cap"),
29947            "schema",
29948        );
29949        assert_length_error(
29950            super::sql_select_columns_query_in_schema(&conn, "events", None, &[over_cap.as_str()])
29951                .expect_err("SELECT column over cap"),
29952            "column",
29953        );
29954        assert_length_error(
29955            super::sql_create_table_query_in_schema(&conn, &over_cap, None, &defs)
29956                .expect_err("CREATE table over cap"),
29957            "table",
29958        );
29959        assert_length_error(
29960            super::sql_insert_rows_query_in_schema(&conn, "events", None, &cols)
29961                .expect_err("INSERT column over cap"),
29962            "column",
29963        );
29964        assert_length_error(
29965            super::sql_multi_row_insert_query_in_schema(&conn, "events", None, &cols, 1)
29966                .expect_err("multi-row INSERT column over cap"),
29967            "column",
29968        );
29969        assert_length_error(
29970            super::sql_drop_table_query_in_schema(&conn, &over_cap, None)
29971                .expect_err("DROP table over cap"),
29972            "table",
29973        );
29974        assert_length_error(
29975            super::SqlConnection::truncate_table(&conn, &over_cap, None)
29976                .expect_err("TRUNCATE fallback table over cap"),
29977            "table",
29978        );
29979    }
29980
29981    #[test]
29982    fn fd90_12_quoting_matrix_special_characters_rejected_by_validator() {
29983        // Per validate_sql_ident: only alphanumeric + underscore allowed.
29984        // Special chars (`-`, `.`, ` `, `:`, `'`, `"`, `;`) and dotted
29985        // names must be rejected before they ever reach quote_identifier.
29986        let bad: &[&str] = &[
29987            "my-col",
29988            "my.col",
29989            "my col",
29990            "my:col",
29991            "my'col",
29992            "my\"col",
29993            "my;col",
29994            "schema.table",
29995            "DROP--",
29996            "",
29997        ];
29998        for name in bad {
29999            let err =
30000                super::validate_sql_table_name(name).expect_err(&format!("must reject `{name}`"));
30001            assert!(matches!(err, IoError::Sql(msg) if msg.contains("invalid table name")));
30002            let err = super::validate_sql_column_name(name)
30003                .expect_err(&format!("must reject col `{name}`"));
30004            assert!(matches!(err, IoError::Sql(msg) if msg.contains("invalid column name")));
30005        }
30006    }
30007
30008    #[test]
30009    fn fd90_12_quoting_matrix_nul_byte_rejected_at_quote_identifier_layer() {
30010        // Defense in depth: even if a backend's quote_identifier is
30011        // called with a NUL-containing string (bypassing
30012        // validate_sql_ident), every dialect must reject — guards
30013        // against C-string driver-layer statement injection via
30014        // embedded null terminators.
30015        use super::SqlConnection as _;
30016        let ansi = AnsiSchemaConn;
30017        let mysql = MysqlBacktickConn;
30018        let mssql = MssqlBracketConn;
30019        let err_ansi = ansi
30020            .quote_identifier("ab\0cd")
30021            .expect_err("ansi must reject NUL");
30022        assert!(matches!(err_ansi, IoError::Sql(msg) if msg.contains("NUL")));
30023        let err_mysql = mysql
30024            .quote_identifier("ab\0cd")
30025            .expect_err("mysql must reject NUL");
30026        assert!(matches!(err_mysql, IoError::Sql(msg) if msg.contains("NUL")));
30027        let err_mssql = mssql
30028            .quote_identifier("ab\0cd")
30029            .expect_err("mssql must reject NUL");
30030        assert!(matches!(err_mssql, IoError::Sql(msg) if msg.contains("NUL")));
30031    }
30032
30033    #[cfg(feature = "sql-sqlite")]
30034    #[test]
30035    fn read_sql_empty_typed_table_preserves_column_dtypes_ex8ec() {
30036        let conn = make_sql_test_conn();
30037        super::SqlConnection::execute_batch(
30038            &conn,
30039            "CREATE TABLE empty_typed_ex8ec (i INTEGER, t TEXT, r REAL);",
30040        )
30041        .expect("create");
30042        // No INSERTs — empty result set.
30043
30044        let frame = read_sql(&conn, "SELECT * FROM empty_typed_ex8ec").expect("read empty");
30045        assert_eq!(frame.index().len(), 0, "empty table should yield zero rows");
30046
30047        let i_col = frame.column("i").expect("column i must exist");
30048        assert_eq!(i_col.dtype(), crate::DType::Int64);
30049        let t_col = frame.column("t").expect("column t must exist");
30050        assert_eq!(t_col.dtype(), crate::DType::Utf8);
30051        let r_col = frame.column("r").expect("column r must exist");
30052        assert_eq!(r_col.dtype(), crate::DType::Float64);
30053    }
30054
30055    #[cfg(feature = "sql-sqlite")]
30056    #[test]
30057    fn read_sql_all_null_typed_table_preserves_column_dtypes_0qo9c() {
30058        let conn = make_sql_test_conn();
30059        super::SqlConnection::execute_batch(
30060            &conn,
30061            "CREATE TABLE all_null_typed_0qo9c (i INTEGER, t TEXT, r REAL);
30062             INSERT INTO all_null_typed_0qo9c (i, t, r) VALUES (NULL, NULL, NULL);",
30063        )
30064        .expect("create and insert");
30065
30066        let frame = read_sql(&conn, "SELECT * FROM all_null_typed_0qo9c")
30067            .expect("read all-null typed table");
30068        assert_eq!(frame.index().len(), 1);
30069
30070        let i_col = frame.column("i").expect("column i must exist");
30071        assert_eq!(i_col.dtype(), crate::DType::Int64);
30072        assert!(i_col.values()[0].is_missing());
30073        let t_col = frame.column("t").expect("column t must exist");
30074        assert_eq!(t_col.dtype(), crate::DType::Utf8);
30075        assert!(t_col.values()[0].is_missing());
30076        let r_col = frame.column("r").expect("column r must exist");
30077        assert_eq!(r_col.dtype(), crate::DType::Float64);
30078        assert!(r_col.values()[0].is_missing());
30079    }
30080}
30081
30082#[cfg(test)]
30083mod fused_numeric_csv_field_tests {
30084    use super::{
30085        CsvTypedColumnValues, fuse_scan_numeric_csv_field, push_csv_default_numeric_field,
30086        push_fused_numeric_csv_field,
30087    };
30088
30089    fn assert_same_columns(base: &CsvTypedColumnValues, fused: &CsvTypedColumnValues, token: &str) {
30090        match (base, fused) {
30091            (CsvTypedColumnValues::Int64(lhs), CsvTypedColumnValues::Int64(rhs)) => {
30092                assert_eq!(lhs, rhs, "Int64 mismatch for token {token:?}");
30093            }
30094            (CsvTypedColumnValues::Float64(lhs), CsvTypedColumnValues::Float64(rhs)) => {
30095                let lhs_bits: Vec<u64> = lhs.iter().map(|value| value.to_bits()).collect();
30096                let rhs_bits: Vec<u64> = rhs.iter().map(|value| value.to_bits()).collect();
30097                assert_eq!(
30098                    lhs_bits, rhs_bits,
30099                    "Float64 bit mismatch for token {token:?}"
30100                );
30101            }
30102            _ => panic!("column dtype diverged for token {token:?}"),
30103        }
30104    }
30105
30106    /// Every token the fused scanner admits must produce bit-identical column
30107    /// state to the `push_csv_default_numeric_field` fallback, for both a
30108    /// fresh Int64 column and a Float64 column, under every terminator.
30109    #[test]
30110    fn fused_field_matches_fallback_parser() {
30111        let tokens = [
30112            "0",
30113            "-0",
30114            "+7",
30115            "007",
30116            "5",
30117            "-5",
30118            "123456789",
30119            "999999999999999999",
30120            "-999999999999999999",
30121            "9007199254740993",
30122            "1234567890123456789",
30123            "0.1",
30124            "-0.1",
30125            "+0.5",
30126            ".5",
30127            "-.5",
30128            "00.5",
30129            "5.",
30130            "12.34",
30131            "123456.7",
30132            "0.30000000000000004",
30133            "9007199254740993.0",
30134            "1e5",
30135            "1E5",
30136            "1.5e-3",
30137            "inf",
30138            "-inf",
30139            "nan",
30140            "NaN",
30141            "",
30142            " 5",
30143            "5 ",
30144            "true",
30145            "false",
30146            "TRUE",
30147            "1.2.3",
30148            "--5",
30149            "+-5",
30150            "1-2",
30151            "#N/A",
30152            "NULL",
30153            "abc",
30154        ];
30155
30156        for token in tokens {
30157            for suffix in ["", ",", "\n", ",9\n"] {
30158                let data = format!("{token}{suffix}");
30159                let Some(field) = fuse_scan_numeric_csv_field(data.as_bytes(), 0) else {
30160                    // Rejected tokens take the unchanged fallback route;
30161                    // nothing further to prove.
30162                    continue;
30163                };
30164                assert_eq!(
30165                    field.end,
30166                    token.len(),
30167                    "fused scanner must stop at the delimiter for token {token:?}"
30168                );
30169
30170                // The fallback must accept every token the fused scanner
30171                // admits (the fused grammar is a strict subset).
30172                let mut base_int = CsvTypedColumnValues::Int64(Vec::new());
30173                assert!(
30174                    push_csv_default_numeric_field(&mut base_int, token.as_bytes()),
30175                    "fallback rejected fused-admitted token {token:?}"
30176                );
30177                let mut fused_int = CsvTypedColumnValues::Int64(Vec::new());
30178                push_fused_numeric_csv_field(&mut fused_int, &field);
30179                assert_same_columns(&base_int, &fused_int, token);
30180
30181                let mut base_float = CsvTypedColumnValues::Float64(Vec::new());
30182                assert!(
30183                    push_csv_default_numeric_field(&mut base_float, token.as_bytes()),
30184                    "fallback Float64 rejected fused-admitted token {token:?}"
30185                );
30186                let mut fused_float = CsvTypedColumnValues::Float64(Vec::new());
30187                push_fused_numeric_csv_field(&mut fused_float, &field);
30188                assert_same_columns(&base_float, &fused_float, token);
30189            }
30190        }
30191    }
30192
30193    /// The sign of zero must survive the fused route on Float64 columns:
30194    /// `-0` parses to -0.0 via `parse_f64_csv_number`, and the fused field
30195    /// must carry the same bits.
30196    #[test]
30197    fn fused_field_preserves_negative_zero_bits() {
30198        let field = fuse_scan_numeric_csv_field(b"-0,", 0).expect("fused scanner must admit -0");
30199        assert_eq!(field.int_value, Some(0));
30200        assert_eq!(field.float_value.to_bits(), (-0.0f64).to_bits());
30201
30202        let mut float_column = CsvTypedColumnValues::Float64(Vec::new());
30203        push_fused_numeric_csv_field(&mut float_column, &field);
30204        match float_column {
30205            CsvTypedColumnValues::Float64(values) => {
30206                assert_eq!(values.len(), 1);
30207                assert_eq!(values[0].to_bits(), (-0.0f64).to_bits());
30208            }
30209            CsvTypedColumnValues::Int64(_) => panic!("expected Float64 column"),
30210        }
30211    }
30212}
30213
30214#[cfg(test)]
30215mod merge_simple_numeric_csv_chunks_tests {
30216    use super::{CsvTypedColumnValues, merge_simple_numeric_csv_chunks};
30217
30218    /// Verbatim copy of the pre-parallel chunk-major merge, kept as the
30219    /// reference implementation for the differential test below.
30220    fn reference_merge(
30221        parsed_chunks: Vec<(Vec<CsvTypedColumnValues>, i64)>,
30222        header_count: usize,
30223    ) -> Option<(Vec<CsvTypedColumnValues>, i64)> {
30224        let mut final_is_float = vec![false; header_count];
30225        let mut row_count = 0i64;
30226        for (columns, rows) in &parsed_chunks {
30227            if columns.len() != header_count {
30228                return None;
30229            }
30230            row_count = row_count.checked_add(*rows)?;
30231            for (idx, column) in columns.iter().enumerate() {
30232                final_is_float[idx] |= matches!(column, CsvTypedColumnValues::Float64(_));
30233            }
30234        }
30235
30236        let capacity = usize::try_from(row_count).ok()?;
30237        let mut merged: Vec<CsvTypedColumnValues> = final_is_float
30238            .into_iter()
30239            .map(|is_float| {
30240                if is_float {
30241                    CsvTypedColumnValues::Float64(Vec::with_capacity(capacity))
30242                } else {
30243                    CsvTypedColumnValues::Int64(Vec::with_capacity(capacity))
30244                }
30245            })
30246            .collect();
30247
30248        for (columns, _) in parsed_chunks {
30249            for (dst, src) in merged.iter_mut().zip(columns) {
30250                match (dst, src) {
30251                    (CsvTypedColumnValues::Int64(dst), CsvTypedColumnValues::Int64(src)) => {
30252                        dst.extend(src);
30253                    }
30254                    (CsvTypedColumnValues::Float64(dst), CsvTypedColumnValues::Int64(src)) => {
30255                        dst.extend(src.into_iter().map(|value| value as f64));
30256                    }
30257                    (CsvTypedColumnValues::Float64(dst), CsvTypedColumnValues::Float64(src)) => {
30258                        dst.extend(src);
30259                    }
30260                    (CsvTypedColumnValues::Int64(_), CsvTypedColumnValues::Float64(_)) => {
30261                        return None;
30262                    }
30263                }
30264            }
30265        }
30266
30267        Some((merged, row_count))
30268    }
30269
30270    fn build_chunks(
30271        chunk_count: usize,
30272        rows_per_chunk: usize,
30273        header_count: usize,
30274        float_from_chunk_for_col: impl Fn(usize) -> usize,
30275    ) -> Vec<(Vec<CsvTypedColumnValues>, i64)> {
30276        (0..chunk_count)
30277            .map(|chunk| {
30278                let columns = (0..header_count)
30279                    .map(|col| {
30280                        if chunk >= float_from_chunk_for_col(col) {
30281                            CsvTypedColumnValues::Float64(
30282                                (0..rows_per_chunk)
30283                                    .map(|row| {
30284                                        (chunk * rows_per_chunk + row) as f64 * 0.5
30285                                            + col as f64 * 1000.0
30286                                    })
30287                                    .collect(),
30288                            )
30289                        } else {
30290                            CsvTypedColumnValues::Int64(
30291                                (0..rows_per_chunk)
30292                                    .map(|row| {
30293                                        (chunk * rows_per_chunk + row) as i64 + col as i64 * 1000
30294                                    })
30295                                    .collect(),
30296                            )
30297                        }
30298                    })
30299                    .collect();
30300                (columns, rows_per_chunk as i64)
30301            })
30302            .collect()
30303    }
30304
30305    fn assert_merge_matches_reference(
30306        chunks: Vec<(Vec<CsvTypedColumnValues>, i64)>,
30307        header_count: usize,
30308    ) {
30309        let reference_chunks: Vec<(Vec<CsvTypedColumnValues>, i64)> = chunks
30310            .iter()
30311            .map(|(columns, rows)| {
30312                let cloned = columns
30313                    .iter()
30314                    .map(|column| match column {
30315                        CsvTypedColumnValues::Int64(values) => {
30316                            CsvTypedColumnValues::Int64(values.clone())
30317                        }
30318                        CsvTypedColumnValues::Float64(values) => {
30319                            CsvTypedColumnValues::Float64(values.clone())
30320                        }
30321                    })
30322                    .collect();
30323                (cloned, *rows)
30324            })
30325            .collect();
30326
30327        let expected = reference_merge(reference_chunks, header_count);
30328        let actual = merge_simple_numeric_csv_chunks(chunks, header_count);
30329
30330        match (expected, actual) {
30331            (None, None) => {}
30332            (Some((expected_columns, expected_rows)), Some((actual_columns, actual_rows))) => {
30333                assert_eq!(expected_rows, actual_rows);
30334                assert_eq!(expected_columns.len(), actual_columns.len());
30335                for (idx, (lhs, rhs)) in expected_columns
30336                    .iter()
30337                    .zip(actual_columns.iter())
30338                    .enumerate()
30339                {
30340                    match (lhs, rhs) {
30341                        (CsvTypedColumnValues::Int64(lhs), CsvTypedColumnValues::Int64(rhs)) => {
30342                            assert_eq!(lhs, rhs, "Int64 column {idx} diverged");
30343                        }
30344                        (
30345                            CsvTypedColumnValues::Float64(lhs),
30346                            CsvTypedColumnValues::Float64(rhs),
30347                        ) => {
30348                            let lhs_bits: Vec<u64> =
30349                                lhs.iter().map(|value| value.to_bits()).collect();
30350                            let rhs_bits: Vec<u64> =
30351                                rhs.iter().map(|value| value.to_bits()).collect();
30352                            assert_eq!(lhs_bits, rhs_bits, "Float64 column {idx} bits diverged");
30353                        }
30354                        _ => panic!("column {idx} dtype diverged"),
30355                    }
30356                }
30357            }
30358            (expected, actual) => panic!(
30359                "merge outcome diverged: reference some={} actual some={}",
30360                expected.is_some(),
30361                actual.is_some()
30362            ),
30363        }
30364    }
30365
30366    /// Big merge (crosses the parallel threshold): mixed promotion patterns —
30367    /// some columns all-Int64, some all-Float64, some promoting mid-stream —
30368    /// must match the chunk-major reference bit-for-bit, in column order.
30369    #[test]
30370    fn parallel_merge_matches_reference_with_mixed_promotion() {
30371        // 8 chunks x 1000 rows x 12 columns = 96000 values > 65536 threshold.
30372        let chunks = build_chunks(8, 1000, 12, |col| match col % 4 {
30373            0 => usize::MAX, // never float: stays Int64
30374            1 => 0,          // float from the first chunk
30375            2 => 3,          // promotes mid-stream
30376            _ => 7,          // promotes at the last chunk
30377        });
30378        assert_merge_matches_reference(chunks, 12);
30379    }
30380
30381    /// Small merge (below the parallel threshold) takes the sequential path
30382    /// and must also match.
30383    #[test]
30384    fn sequential_merge_matches_reference() {
30385        let chunks = build_chunks(3, 4, 5, |col| if col % 2 == 0 { usize::MAX } else { 1 });
30386        assert_merge_matches_reference(chunks, 5);
30387    }
30388
30389    /// More worker groups than columns (header_count < MAX_WORKERS) and
30390    /// header_count not divisible by the group size must keep column order.
30391    #[test]
30392    fn parallel_merge_handles_narrow_and_ragged_widths() {
30393        for header_count in [2, 3, 7, 9, 17] {
30394            let chunks = build_chunks(5, 2000, header_count, |col| col % 6);
30395            assert_merge_matches_reference(chunks, header_count);
30396        }
30397    }
30398
30399    /// A chunk whose column count disagrees with the header must reject, as
30400    /// before.
30401    #[test]
30402    fn merge_rejects_mismatched_chunk_width() {
30403        let mut chunks = build_chunks(2, 10, 4, |_| usize::MAX);
30404        chunks[1].0.pop();
30405        assert!(merge_simple_numeric_csv_chunks(chunks, 4).is_none());
30406    }
30407}