Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions src/pt_snap_cli/snapshot/PROVENANCE.md
Original file line number Diff line number Diff line change
Expand Up @@ -210,3 +210,12 @@ entry for every future update under `src/pt_snap_cli/snapshot/`, recording the
date, affected scope, source or local-change identity, and reason. Existing
source mappings, modification history, and licensing evidence must not be
rewritten or removed; corrections are appended with their rationale.

## 2026-10-03 — Optional SQLite type mapping (issue #165)

Local first-party change in `snapshot/util/sqlite_meta.py`: recognize PEP 604
`T | None` alongside `typing.Optional[T]` when selecting SQLite column affinity.
Unions with multiple non-None members and unsupported types retain the TEXT
fallback. Regression tests cover both optional spellings, reversed union order,
generated schema, numeric ordering, and nullable value round trips. Audited
upstream source mappings and license terms are unchanged.
9 changes: 5 additions & 4 deletions src/pt_snap_cli/snapshot/util/sqlite_meta.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import os.path
import sqlite3
from collections.abc import Iterable
from types import UnionType
from typing import (
Any,
Union,
Expand All @@ -26,13 +27,13 @@
}


def _map_py_type_to_sqlite(py_type: type) -> str:
def _map_py_type_to_sqlite(py_type: type | UnionType) -> str:
"""将 Python 类型转换为 SQLite 类型"""
origin = get_origin(py_type) or py_type
if origin in _PY_TYPE_TO_SQLITE:
return _PY_TYPE_TO_SQLITE[origin]
# 处理 Optional[T] => T(Optional 是 Union[T, None])
if origin is Union:
# 处理 Optional[T] / T | None => T
if origin is Union or origin is UnionType:
args = get_args(py_type)
non_none = [t for t in args if t is not type(None)]
if len(non_none) == 1:
Expand Down Expand Up @@ -113,7 +114,7 @@ class SqliteColumn:
def __init__(
self,
name: str,
data_type: type = str,
data_type: type | UnionType = str,
primary_key: bool = False, # 是否主键
autoincrement: bool = False, # 是否自增
not_null: bool = False, # 是否不可为空
Expand Down
64 changes: 58 additions & 6 deletions tests/snapshot/test_sqlite_meta.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import sqlite3
from pathlib import Path
from typing import Optional
from typing import Optional, Union

import pytest

Expand Down Expand Up @@ -31,12 +31,64 @@ def test_type_mapping_helpers_cover_supported_and_fallback_types():
assert _sqlite_type_to_py_type("NUMERIC") is str


@pytest.mark.xfail(
strict=True,
reason="runtime does not recognize the Python 3.10+ PEP 604 optional form",
@pytest.mark.parametrize(
("py_type", "sqlite_type"),
[(int, "INTEGER"), (float, "REAL"), (str, "TEXT"), (bool, "INTEGER"), (bytes, "BLOB")],
)
def test_type_mapping_supports_pep604_optional():
assert _map_py_type_to_sqlite(int | None) == "INTEGER" # noqa: UP045
def test_type_mapping_supports_both_optional_spellings(py_type, sqlite_type):
assert _map_py_type_to_sqlite(Optional[py_type]) == sqlite_type # noqa: UP045
assert _map_py_type_to_sqlite(py_type | None) == sqlite_type
assert _map_py_type_to_sqlite(None | py_type) == sqlite_type


@pytest.mark.parametrize(
"py_type",
[
int | str,
int | str | None,
Union[int, str], # noqa: UP007
Union[int, str, None], # noqa: UP007
list[int] | None,
Optional[list[int]], # noqa: UP045
type(None),
],
)
def test_type_mapping_keeps_ambiguous_and_unsupported_types_as_text(py_type):
assert _map_py_type_to_sqlite(py_type) == "TEXT"


def test_pep604_columns_preserve_sqlite_affinity_and_nulls():
connection = sqlite3.connect(":memory:")
try:
table = SqliteTable(
"nullable_values",
[
SqliteColumn("number", int | None),
SqliteColumn("fraction", float | None),
SqliteColumn("flag", bool | None),
SqliteColumn("payload", bytes | None),
],
)
table.create_table(connection)
assert [row[2] for row in connection.execute("PRAGMA table_info(nullable_values)")] == [
"INTEGER",
"REAL",
"INTEGER",
"BLOB",
]
table.insert_records(
connection,
[
{"number": 10, "fraction": 1.5, "flag": True, "payload": b"ten"},
{"number": 2, "fraction": 2.5, "flag": False, "payload": b"two"},
{"number": None, "fraction": None, "flag": None, "payload": None},
],
)
assert connection.execute(
"SELECT number, fraction, flag, payload FROM nullable_values ORDER BY number"
).fetchall() == [(None, None, None, None), (2, 2.5, 0, b"two"), (10, 1.5, 1, b"ten")]
finally:
connection.close()


def test_parse_default_value_handles_literals_bool_and_strings():
Expand Down
Loading