Skip to content

Honor table policies when exporting empty datasets to SQL - #8875

Open
emme1t wants to merge 1 commit into
huggingface:mainfrom
emme1t:fix/empty-sql-export-20261022
Open

emme1t wants to merge 1 commit into
huggingface:mainfrom
emme1t:fix/empty-sql-export-20261022

Conversation

@emme1t

@emme1t emme1t commented Oct 22, 2026

Copy link
Copy Markdown

Exporting an empty dataset skips the SQL writer entirely. As a result, if_exists="replace" returns zero while leaving old rows in the table, if_exists="fail" accepts an existing table, and exporting a new empty split leaves its table missing.

Write one empty batch through the existing pandas conversion so the requested table policy, schema, index and dtype options take effect. The returned row count remains zero. This also handles num_proc > 1 directly when there are no rows to distribute.

A zero-column export with index=False raises before reaching the database, preserving an existing table. index=True remains available for creating an index-only table.

Reproduction:

import sqlite3
from datasets import Dataset, Features, Value

con = sqlite3.connect(":memory:")
con.execute("CREATE TABLE samples (value INTEGER)")
con.execute("INSERT INTO samples VALUES (42)")
con.commit()
empty = Dataset.from_dict({"value": []}, features=Features({"value": Value("int64")}))
empty.to_sql("samples", con, if_exists="replace")
print(con.execute("SELECT * FROM samples").fetchall())

The original implementation prints [(42,)]; this change prints [].

Validation on Python 3.13 / Windows:

  • Added regressions on the original implementation: 16 failed, 3 passed.
  • Full tests/io/test_sql.py: 35 passed.
  • Repository-wide Ruff lint and formatting passed (257 files), and git diff --check passed.
  • Regressions cover all three table policies, existing and missing tables, num_proc=None/1/2, schema preservation, and index/dtype options.
  • An independent check covered SQLAlchemy URI, Engine and Connection inputs across 54 combinations, plus empty indexed selections. SQLite and SQLAlchemy checks also confirmed that rejected zero-column replacements preserve existing data.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant