Skip to content

Commit

Permalink
test: add ser/de json test
Browse files Browse the repository at this point in the history
  • Loading branch information
Mause committed Mar 18, 2024
1 parent 895685e commit 2b2863f
Showing 1 changed file with 55 additions and 3 deletions.
58 changes: 55 additions & 3 deletions duckdb_engine/tests/test_datatypes.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,24 @@
import decimal
import json
import warnings
from typing import Type
from typing import Any, Dict, Type
from uuid import uuid4

import duckdb
from pytest import importorskip, mark
from sqlalchemy import Column, Integer, MetaData, String, Table, inspect, text
from sqlalchemy import (
Column,
Integer,
MetaData,
Sequence,
String,
Table,
inspect,
select,
text,
)
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.engine import Engine
from sqlalchemy.engine import Engine, create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import Session
from sqlalchemy.sql import sqltypes
Expand Down Expand Up @@ -57,6 +69,46 @@ def test_raw_json(engine: Engine) -> None:
)


@mark.remote_data()
def test_custom_json_serializer() -> None:
def default(o: Any) -> Any:
if isinstance(o, decimal.Decimal):
return {"__tag": "decimal", "value": str(o)}

def object_hook(pairs: Dict[str, Any]) -> Any:
if pairs.get("__tag", None) == "decimal":
return decimal.Decimal(pairs["value"])
else:
return pairs

engine = create_engine(
"duckdb://",
json_serializer=json.JSONEncoder(default=default).encode,
json_deserializer=json.JSONDecoder(object_hook=object_hook).decode,
)

Base = declarative_base()

class Entry(Base):
__tablename__ = "test_json"
id = Column(Integer, Sequence("id_seq"), primary_key=True)
data = Column(JSON, nullable=False)

Base.metadata.create_all(engine)

with engine.connect() as conn:
session = Session(bind=conn)

data = {"hello": decimal.Decimal("42")}

session.add(Entry(data=data)) # type: ignore[call-arg]
session.commit()

(res,) = session.execute(select(Entry)).one()

assert res.data == data


def test_json(engine: Engine, session: Session) -> None:
base = declarative_base()

Expand Down

0 comments on commit 2b2863f

Please sign in to comment.