sqlite-utils/tests/test_column_affinity.py
Parker Gurney f34dfb25da Auto-decode columns declared as JSON in output modes (issue #579)
Columns declared with type JSON now decode automatically wherever nested
JSON is already supported (query/rows/search/memory output, and the
Python API), without needing --json-cols. Uses sqlite3's built-in
detect_types=PARSE_DECLTYPES + a registered JSON converter, so it works
transparently through joins and aliases. Flat formats (CSV/TSV/table/raw)
re-serialize decoded values back to JSON text instead of a Python repr.
Also adds "JSON" as a first-class column type for create()/add_column()/
transform(), and fixes column_affinity("JSON") so transform() doesn't
rewrite JSON columns as REAL.
2026-08-05 14:19:51 -07:00

49 lines
1.4 KiB
Python

import pytest
from sqlite_utils.utils import column_affinity
EXAMPLES = [
# Examples from https://www.sqlite.org/datatype3.html#affinity_name_examples
("INT", int),
("INTEGER", int),
("TINYINT", int),
("SMALLINT", int),
("MEDIUMINT", int),
("BIGINT", int),
("UNSIGNED BIG INT", int),
("INT2", int),
("INT8", int),
("CHARACTER(20)", str),
("VARCHAR(255)", str),
("VARYING CHARACTER(255)", str),
("NCHAR(55)", str),
("NATIVE CHARACTER(70)", str),
("NVARCHAR(100)", str),
("TEXT", str),
("CLOB", str),
("BLOB", bytes),
("REAL", float),
("DOUBLE", float),
("DOUBLE PRECISION", float),
("FLOAT", float),
# Numeric, treated as float:
("NUMERIC", float),
("DECIMAL(10,5)", float),
("BOOLEAN", float),
("DATE", float),
("DATETIME", float),
# Not a real SQLite affinity, but sqlite-utils treats it as TEXT so
# transform() does not mangle JSON columns - see issue 579
("JSON", str),
]
@pytest.mark.parametrize("column_def,expected_type", EXAMPLES)
def test_column_affinity(column_def, expected_type):
assert expected_type is column_affinity(column_def)
@pytest.mark.parametrize("column_def,expected_type", EXAMPLES)
def test_columns_dict(fresh_db, column_def, expected_type):
fresh_db.execute(f"create table foo (col {column_def})")
assert {"col": expected_type} == fresh_db["foo"].columns_dict