Repository navigation
Expand file tree
/
Copy pathjson.py
More file actions
107 lines (90 loc) · 3.84 KB
/
Copy pathjson.py
File metadata and controls
107 lines (90 loc) · 3.84 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
"""Explicit native SQL Server JSON inputs and result decoding."""
from __future__ import annotations
import json
from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence
from dataclasses import dataclass, field
from typing import Any, final
from .exceptions import DataError, NotSupportedError
def _validate(value: object, active: set[int]) -> None:
if type(value) in (dict, list):
identity = id(value)
if identity in active:
raise ValueError("Json does not support circular references")
active.add(identity)
try:
if isinstance(value, dict):
for key, item in value.items():
if type(key) is not str:
raise TypeError("Json object keys must be strings")
_validate(item, active)
elif isinstance(value, list):
for item in value:
_validate(item, active)
finally:
active.remove(identity)
elif value is not None and type(value) not in (str, int, float, bool):
raise TypeError("Json values must be objects, arrays, strings, numbers, booleans or None")
@final
@dataclass(frozen=True, slots=True, init=False, repr=False)
class Json:
"""Native JSON input: serialize a dict/list or retain already-serialized str.
Text is not parsed or normalized in Python; the provider/server validates
its JSON syntax and object/array root when the statement executes.
"""
_text: str = field(repr=False)
_utf16_length: int = field(repr=False)
def __init__(self, value: dict[str, Any] | list[Any] | str) -> None:
if type(value) is str:
text = value
elif type(value) in (dict, list):
_validate(value, set())
text = json.dumps(value, ensure_ascii=False, allow_nan=False, separators=(",", ":"))
else:
raise TypeError("Json requires a dict, list or str; use bare None for SQL NULL")
units = len(text.encode("utf-16-le", "strict")) // 2
object.__setattr__(self, "_text", text)
object.__setattr__(self, "_utf16_length", units)
def __repr__(self) -> str:
return "Json(<serialized>)"
def _decode_json(value: str) -> dict[str, Any] | list[Any]:
try:
result = json.loads(value)
except ValueError as error:
raise DataError("Invalid native JSON result", "") from error
if not isinstance(result, (dict, list)):
raise DataError("Native JSON result must have an object or array root", "")
return result
def _reject_json_parameters(values: Any, backend: str) -> None:
if isinstance(values, Mapping):
values = values.values()
elif not isinstance(values, Sequence):
return
if any(isinstance(value, Json) for value in values):
raise NotSupportedError(f"Json parameters are not supported by {backend}", "")
def _bulkcopy_json_rows(
rows: Iterable[tuple[Any, ...]],
carrier: Callable[[str], object],
column_mappings: list[str] | list[tuple[int, str]] | None,
) -> Iterator[tuple[Any, ...]]:
mapped = (
None
if column_mappings is None
else {
index if isinstance(mapping, str) else mapping[0]
for index, mapping in enumerate(column_mappings)
}
)
for row in rows:
if not isinstance(row, tuple):
# Preserve invalid row shapes for the native writer to reject.
yield row
continue
converted = None
for index, value in enumerate(row):
if (mapped is None or index in mapped) and type(value) is Json:
if converted is None:
converted = list(row)
converted[index] = carrier(value._text)
yield row if converted is None else tuple(converted)