|
| 1 | +"""Oracle native JSON type handlers. |
| 2 | +
|
| 3 | +Provides automatic conversion between Python ``dict`` / ``list`` / ``tuple`` values |
| 4 | +and Oracle's JSON storage types via connection type handlers. |
| 5 | +
|
| 6 | +Routing matrix (input): |
| 7 | +
|
| 8 | +* Oracle 21c+ native ``JSON``: bind via ``DB_TYPE_JSON`` (binary OSON). |
| 9 | +* Oracle 19c-20c with ``BLOB CHECK (... IS JSON)``: bind via ``DB_TYPE_BLOB`` with |
| 10 | + UTF-8 JSON bytes. |
| 11 | +* Oracle 12c-18c with ``CLOB CHECK (... IS JSON)``: bind via ``DB_TYPE_CLOB`` with |
| 12 | + serialized JSON string. |
| 13 | +* Server major version is read from ``connection._sqlspec_oracle_major`` (set in |
| 14 | + ``OracleSyncConfig._init_connection`` / ``OracleAsyncConfig._init_connection``). |
| 15 | + When unknown, default to 21c+ behavior. |
| 16 | +
|
| 17 | +Routing matrix (output): |
| 18 | +
|
| 19 | +* ``DB_TYPE_JSON``: passthrough (python-oracledb already returns ``dict``). |
| 20 | +* ``DB_TYPE_BLOB`` with ``JSON`` in column ``type_name``: parse via |
| 21 | + ``json_converter_out_blob``. |
| 22 | +* ``DB_TYPE_CLOB`` with ``JSON`` in column ``type_name``: parse via |
| 23 | + ``json_converter_out_clob``. |
| 24 | +
|
| 25 | +Handlers chain to any pre-existing ``inputtypehandler`` / ``outputtypehandler`` |
| 26 | +registered on the connection (e.g. NumPy vector, UUID), so registration order |
| 27 | +matters: register JSON after numpy, before UUID is also safe because each |
| 28 | +handler returns ``None`` for values it does not own. |
| 29 | +""" |
| 30 | + |
| 31 | +from typing import TYPE_CHECKING, Any |
| 32 | + |
| 33 | +from sqlspec.adapters.oracledb._typing import DB_TYPE_BLOB, DB_TYPE_CLOB, DB_TYPE_JSON |
| 34 | +from sqlspec.utils.serializers import from_json, to_json |
| 35 | + |
| 36 | +if TYPE_CHECKING: |
| 37 | + from oracledb import AsyncConnection, AsyncCursor, Connection, Cursor |
| 38 | + |
| 39 | +__all__ = ( |
| 40 | + "json_converter_in_blob", |
| 41 | + "json_converter_in_clob", |
| 42 | + "json_converter_out_blob", |
| 43 | + "json_converter_out_clob", |
| 44 | + "json_input_type_handler", |
| 45 | + "json_output_type_handler", |
| 46 | + "register_json_handlers", |
| 47 | +) |
| 48 | + |
| 49 | + |
| 50 | +_JSON_TYPE_NAME_MARKER = "JSON" |
| 51 | + |
| 52 | +# Server-version thresholds for JSON binding strategy selection. |
| 53 | +# 21c+ supports DB_TYPE_JSON (binary OSON); 19c-20c uses BLOB CHECK (... IS JSON); |
| 54 | +# pre-19c uses CLOB CHECK (... IS JSON). |
| 55 | +_NATIVE_JSON_MIN_MAJOR = 21 |
| 56 | +_BLOB_IS_JSON_MIN_MAJOR = 19 |
| 57 | + |
| 58 | + |
| 59 | +def json_converter_in_clob(value: Any) -> str: |
| 60 | + """Serialize a Python value to a JSON string for CLOB binding.""" |
| 61 | + return to_json(value) |
| 62 | + |
| 63 | + |
| 64 | +def json_converter_in_blob(value: Any) -> bytes: |
| 65 | + """Serialize a Python value to UTF-8 JSON bytes for BLOB binding.""" |
| 66 | + return to_json(value, as_bytes=True) |
| 67 | + |
| 68 | + |
| 69 | +def json_converter_out_clob(value: "str | None") -> Any: |
| 70 | + """Parse a JSON string from a CLOB read back into a Python value.""" |
| 71 | + if value is None: |
| 72 | + return None |
| 73 | + return from_json(value) |
| 74 | + |
| 75 | + |
| 76 | +def json_converter_out_blob(value: "bytes | None") -> Any: |
| 77 | + """Parse JSON bytes from a BLOB read back into a Python value.""" |
| 78 | + if value is None: |
| 79 | + return None |
| 80 | + return from_json(value) |
| 81 | + |
| 82 | + |
| 83 | +def _is_json_payload(value: Any) -> bool: |
| 84 | + """Return True if the value should be claimed by the JSON input handler. |
| 85 | +
|
| 86 | + ``dict`` and ``tuple``/``list`` of dicts are claimed. Sequences whose first |
| 87 | + element is a number are NOT claimed — those are vector embeddings and |
| 88 | + belong to the vector handler. |
| 89 | + """ |
| 90 | + if isinstance(value, dict): |
| 91 | + return True |
| 92 | + if isinstance(value, (list, tuple)): |
| 93 | + if not value: |
| 94 | + # Empty sequence: ambiguous (could be empty vector or empty list). |
| 95 | + # Defer to the next handler in the chain. |
| 96 | + return False |
| 97 | + first = value[0] |
| 98 | + # Reject sequences of numbers (vector embeddings). |
| 99 | + return not (isinstance(first, (int, float)) and not isinstance(first, bool)) |
| 100 | + return False |
| 101 | + |
| 102 | + |
| 103 | +def _input_type_handler(cursor: "Cursor | AsyncCursor", value: Any, arraysize: int) -> Any: |
| 104 | + """Oracle input type handler for JSON-shaped Python values.""" |
| 105 | + if not _is_json_payload(value): |
| 106 | + return None |
| 107 | + |
| 108 | + server_major = getattr(cursor.connection, "_sqlspec_oracle_major", None) |
| 109 | + |
| 110 | + if server_major is None or server_major >= _NATIVE_JSON_MIN_MAJOR: |
| 111 | + return cursor.var(DB_TYPE_JSON, arraysize=arraysize) |
| 112 | + if server_major >= _BLOB_IS_JSON_MIN_MAJOR: |
| 113 | + return cursor.var(DB_TYPE_BLOB, arraysize=arraysize, inconverter=json_converter_in_blob) |
| 114 | + return cursor.var(DB_TYPE_CLOB, arraysize=arraysize, inconverter=json_converter_in_clob) |
| 115 | + |
| 116 | + |
| 117 | +def _output_type_handler(cursor: "Cursor | AsyncCursor", metadata: Any) -> Any: |
| 118 | + """Oracle output type handler for JSON-bearing column reads.""" |
| 119 | + type_code = getattr(metadata, "type_code", None) |
| 120 | + |
| 121 | + if type_code is DB_TYPE_JSON: |
| 122 | + # Native JSON: python-oracledb returns dict/list directly. No conversion. |
| 123 | + return None |
| 124 | + |
| 125 | + type_name = (getattr(metadata, "type_name", "") or "").upper() |
| 126 | + if _JSON_TYPE_NAME_MARKER not in type_name: |
| 127 | + return None |
| 128 | + |
| 129 | + if type_code is DB_TYPE_BLOB: |
| 130 | + return cursor.var(DB_TYPE_BLOB, arraysize=cursor.arraysize, outconverter=json_converter_out_blob) |
| 131 | + if type_code is DB_TYPE_CLOB: |
| 132 | + return cursor.var(DB_TYPE_CLOB, arraysize=cursor.arraysize, outconverter=json_converter_out_clob) |
| 133 | + return None |
| 134 | + |
| 135 | + |
| 136 | +def json_input_type_handler(cursor: "Cursor | AsyncCursor", value: Any, arraysize: int) -> Any: |
| 137 | + """Public input type handler entry point.""" |
| 138 | + return _input_type_handler(cursor, value, arraysize) |
| 139 | + |
| 140 | + |
| 141 | +def json_output_type_handler(cursor: "Cursor | AsyncCursor", metadata: Any) -> Any: |
| 142 | + """Public output type handler entry point.""" |
| 143 | + return _output_type_handler(cursor, metadata) |
| 144 | + |
| 145 | + |
| 146 | +def register_json_handlers(connection: "Connection | AsyncConnection") -> None: |
| 147 | + """Register JSON type handlers on an Oracle connection. |
| 148 | +
|
| 149 | + Chains to any existing handlers via ``_JsonInputHandler`` / ``_JsonOutputHandler`` |
| 150 | + wrapper classes so vector / UUID handlers continue to fire for non-JSON values. |
| 151 | + """ |
| 152 | + try: |
| 153 | + existing_input = connection.inputtypehandler |
| 154 | + except AttributeError: |
| 155 | + existing_input = None |
| 156 | + try: |
| 157 | + existing_output = connection.outputtypehandler |
| 158 | + except AttributeError: |
| 159 | + existing_output = None |
| 160 | + |
| 161 | + connection.inputtypehandler = _JsonInputHandler(existing_input) |
| 162 | + connection.outputtypehandler = _JsonOutputHandler(existing_output) |
| 163 | + |
| 164 | + |
| 165 | +class _JsonInputHandler: |
| 166 | + """Chaining wrapper that claims dict/list/tuple values, falling back otherwise.""" |
| 167 | + |
| 168 | + __slots__ = ("_fallback",) |
| 169 | + |
| 170 | + def __init__(self, fallback: "Any | None") -> None: |
| 171 | + self._fallback = fallback |
| 172 | + |
| 173 | + def __call__(self, cursor: "Cursor | AsyncCursor", value: Any, arraysize: int) -> Any: |
| 174 | + result = _input_type_handler(cursor, value, arraysize) |
| 175 | + if result is not None: |
| 176 | + return result |
| 177 | + if self._fallback is not None: |
| 178 | + return self._fallback(cursor, value, arraysize) |
| 179 | + return None |
| 180 | + |
| 181 | + |
| 182 | +class _JsonOutputHandler: |
| 183 | + """Chaining wrapper that claims JSON-bearing columns, falling back otherwise.""" |
| 184 | + |
| 185 | + __slots__ = ("_fallback",) |
| 186 | + |
| 187 | + def __init__(self, fallback: "Any | None") -> None: |
| 188 | + self._fallback = fallback |
| 189 | + |
| 190 | + def __call__(self, cursor: "Cursor | AsyncCursor", metadata: Any) -> Any: |
| 191 | + result = _output_type_handler(cursor, metadata) |
| 192 | + if result is not None: |
| 193 | + return result |
| 194 | + if self._fallback is not None: |
| 195 | + return self._fallback(cursor, metadata) |
| 196 | + return None |
0 commit comments