diff --git a/tests/integration/oracle/test_oracle_long_json_parameter.py b/tests/integration/oracle/test_oracle_long_json_parameter.py new file mode 100644 index 00000000..07b56068 --- /dev/null +++ b/tests/integration/oracle/test_oracle_long_json_parameter.py @@ -0,0 +1,126 @@ +""" +A statement that reads a long JSON text bound as a parameter, as the shared compiler will bind a large list or map +literal (`_cyl_`, read as `JSON(:p)`, or `JSON(:p EXTENDED)` where it holds doubles): the text binds and is read +whole on a statement that only reads, at each size around a `VARCHAR2`'s limits, in SQL (4,000 bytes) and PL/SQL +(32,767), and well past them. The compiler is to bind such literals, not write them into the SQL, so that batches of +one shape share one cursor (liberation-data/drivine4j#955); a text past 32,767 bytes binds only as a CLOB, which the +connection makes of it (OracleConnection._bindable). Drivine for TypeScript's OracleLongJsonParameter.spec.ts +(liberation-data/drivine#925). +""" + +import json +from dataclasses import dataclass +from typing import Any + +import pytest + +from drivine import PersistenceManager, QuerySpecification, cypher_statement +from tests.integration.oracle.oracle_seed import ON_ORACLE + +pytestmark = [ON_ORACLE] + + +@dataclass(frozen=True) +class Sample: + """A JSON text, and how many numbers it holds and their sum.""" + + text: str + count: int + sum: float + + +def numbers_text(size: int) -> Sample: + """ + The compact JSON text of a list of numbers 0, 1, …, exactly `size` bytes: the last is given zeros to make up the + length, not spaces, so the text the host writes of the list is as long, and crosses each limit where its text does. + """ + items: list[str] = [] + length = 2 + while length + len(str(len(items))) + 1 <= size: + length += len(str(len(items))) + (1 if items else 0) + items.append(str(len(items))) + items[-1] += "0" * (size - length) + return Sample("[" + ",".join(items) + "]", len(items), sum(int(it) for it in items)) + + +def doubles_text(size: int) -> Sample: + """ + The extended JSON text of a map holding a list of doubles 0.5, 1.5, …, padded with spaces to exactly `size` bytes, + as a literal holding doubles is written for `JSON(:p EXTENDED)`. + """ + + def item(i: int) -> str: + return f'{{"$numberDouble":{i}.5}}' + + items: list[str] = [] + length = len('{"xs":[]}') + while length + len(item(len(items))) + 1 <= size: + length += len(item(len(items))) + (1 if items else 0) + items.append(item(len(items))) + text = '{"xs":[' + ",".join(items) + "]" + count = len(items) + return Sample(text + " " * (size - len(text) - 1) + "}", count, count * (count - 1) / 2 + count * 0.5) + + +SIZES = [4_000, 4_001, 32_767, 32_768, 100 * 1024, 1024 * 1024] + +NUMBERS = """SELECT COUNT(*) AS "n", SUM(v) AS "s" FROM JSON_TABLE(JSON($p), '$[*]' COLUMNS (v NUMBER PATH '$'))""" + + +async def sql(pm: PersistenceManager, text: str, parameters: dict[str, Any]) -> list[Any]: + return await pm.query(QuerySpecification[Any](text).bind(parameters)) + + +@pytest.mark.parametrize("size", SIZES) +async def test_reads_a_list_of_numbers_given_as_json_text_with_json_p(pm: PersistenceManager, size: int): + sample = numbers_text(size) + assert len(sample.text.encode()) == size + assert await sql(pm, NUMBERS, {"p": sample.text}) == [{"n": sample.count, "s": sample.sum}] + + +@pytest.mark.parametrize("size", SIZES) +async def test_reads_a_map_of_doubles_given_as_extended_json_text_with_json_p_extended( + pm: PersistenceManager, size: int +): + sample = doubles_text(size) + assert len(sample.text.encode()) == size + rows = await sql( + pm, + """SELECT COUNT(*) AS "n", SUM(v) AS "s", COUNT(CASE WHEN t = 'double' THEN 1 END) AS "d" + FROM JSON_TABLE(JSON($p EXTENDED), '$.xs[*]' + COLUMNS (v BINARY_DOUBLE PATH '$', t VARCHAR2(20) PATH '$.type()'))""", + {"p": sample.text}, + ) + assert rows == [{"n": sample.count, "s": sample.sum, "d": sample.count}] + + +@pytest.mark.parametrize("size", SIZES) +async def test_reads_back_a_multibyte_text_whole_from_json_p(pm: PersistenceManager, size: int): + # A text of multibyte characters: its length in bytes, not characters, is what a VARCHAR2 is short of. + pairs = (size - 2) // 3 // 2 + value = "é" * pairs + "x" * (size - 2 - pairs * 2) + text = json.dumps(value, ensure_ascii=False) + assert len(text.encode()) == size + rows = await sql(pm, """SELECT JSON_VALUE(JSON($p), '$' RETURNING CLOB) AS "v" FROM DUAL""", {"p": text}) + # A row of one column is its value. Compared so, as a failure would print a megabyte. + assert len(rows) == 1 + assert len(rows[0]) == len(value) + assert rows[0] == value + + +@pytest.mark.parametrize("size", SIZES) +async def test_reads_a_list_parameter_given_as_a_list(pm: PersistenceManager, size: int): + # A list the caller gives, not its text: the host writes its JSON text, as long. + sample = numbers_text(size) + assert await sql(pm, NUMBERS, {"p": json.loads(sample.text)}) == [{"n": sample.count, "s": sample.sum}] + + +@pytest.mark.parametrize("size", SIZES) +async def test_reads_a_list_parameter_in_cypher(pm: PersistenceManager, size: int): + sample = numbers_text(size) + rows = await pm.query( + QuerySpecification[Any](cypher_statement("UNWIND $xs AS x RETURN {n: count(x), s: sum(x)}")).bind( + {"xs": json.loads(sample.text)} + ) + ) + assert rows == [{"n": sample.count, "s": sample.sum}] diff --git a/tests/sync_integration/oracle/test_oracle_long_json_parameter.py b/tests/sync_integration/oracle/test_oracle_long_json_parameter.py new file mode 100644 index 00000000..89d0b160 --- /dev/null +++ b/tests/sync_integration/oracle/test_oracle_long_json_parameter.py @@ -0,0 +1,126 @@ +# Written by scripts/unasync.py from tests/integration/oracle/test_oracle_long_json_parameter.py: +# change that, and run the script again. +""" +A statement that reads a long JSON text bound as a parameter, as the shared compiler will bind a large list or map +literal (`_cyl_`, read as `JSON(:p)`, or `JSON(:p EXTENDED)` where it holds doubles): the text binds and is read +whole on a statement that only reads, at each size around a `VARCHAR2`'s limits, in SQL (4,000 bytes) and PL/SQL +(32,767), and well past them. The compiler is to bind such literals, not write them into the SQL, so that batches of +one shape share one cursor (liberation-data/drivine4j#955); a text past 32,767 bytes binds only as a CLOB, which the +connection makes of it (OracleConnection._bindable). Drivine for TypeScript's OracleLongJsonParameter.spec.ts +(liberation-data/drivine#925). +""" + +import json +from dataclasses import dataclass +from typing import Any + +import pytest + +from drivine.sync import PersistenceManager, QuerySpecification, cypher_statement +from tests.sync_integration.oracle.oracle_seed import ON_ORACLE + +pytestmark = [ON_ORACLE] + + +@dataclass(frozen=True) +class Sample: + """A JSON text, and how many numbers it holds and their sum.""" + + text: str + count: int + sum: float + + +def numbers_text(size: int) -> Sample: + """ + The compact JSON text of a list of numbers 0, 1, …, exactly `size` bytes: the last is given zeros to make up the + length, not spaces, so the text the host writes of the list is as long, and crosses each limit where its text does. + """ + items: list[str] = [] + length = 2 + while length + len(str(len(items))) + 1 <= size: + length += len(str(len(items))) + (1 if items else 0) + items.append(str(len(items))) + items[-1] += "0" * (size - length) + return Sample("[" + ",".join(items) + "]", len(items), sum(int(it) for it in items)) + + +def doubles_text(size: int) -> Sample: + """ + The extended JSON text of a map holding a list of doubles 0.5, 1.5, …, padded with spaces to exactly `size` bytes, + as a literal holding doubles is written for `JSON(:p EXTENDED)`. + """ + + def item(i: int) -> str: + return f'{{"$numberDouble":{i}.5}}' + + items: list[str] = [] + length = len('{"xs":[]}') + while length + len(item(len(items))) + 1 <= size: + length += len(item(len(items))) + (1 if items else 0) + items.append(item(len(items))) + text = '{"xs":[' + ",".join(items) + "]" + count = len(items) + return Sample(text + " " * (size - len(text) - 1) + "}", count, count * (count - 1) / 2 + count * 0.5) + + +SIZES = [4_000, 4_001, 32_767, 32_768, 100 * 1024, 1024 * 1024] + +NUMBERS = """SELECT COUNT(*) AS "n", SUM(v) AS "s" FROM JSON_TABLE(JSON($p), '$[*]' COLUMNS (v NUMBER PATH '$'))""" + + +def sql(pm: PersistenceManager, text: str, parameters: dict[str, Any]) -> list[Any]: + return pm.query(QuerySpecification[Any](text).bind(parameters)) + + +@pytest.mark.parametrize("size", SIZES) +def test_reads_a_list_of_numbers_given_as_json_text_with_json_p(pm: PersistenceManager, size: int): + sample = numbers_text(size) + assert len(sample.text.encode()) == size + assert sql(pm, NUMBERS, {"p": sample.text}) == [{"n": sample.count, "s": sample.sum}] + + +@pytest.mark.parametrize("size", SIZES) +def test_reads_a_map_of_doubles_given_as_extended_json_text_with_json_p_extended(pm: PersistenceManager, size: int): + sample = doubles_text(size) + assert len(sample.text.encode()) == size + rows = sql( + pm, + """SELECT COUNT(*) AS "n", SUM(v) AS "s", COUNT(CASE WHEN t = 'double' THEN 1 END) AS "d" + FROM JSON_TABLE(JSON($p EXTENDED), '$.xs[*]' + COLUMNS (v BINARY_DOUBLE PATH '$', t VARCHAR2(20) PATH '$.type()'))""", + {"p": sample.text}, + ) + assert rows == [{"n": sample.count, "s": sample.sum, "d": sample.count}] + + +@pytest.mark.parametrize("size", SIZES) +def test_reads_back_a_multibyte_text_whole_from_json_p(pm: PersistenceManager, size: int): + # A text of multibyte characters: its length in bytes, not characters, is what a VARCHAR2 is short of. + pairs = (size - 2) // 3 // 2 + value = "é" * pairs + "x" * (size - 2 - pairs * 2) + text = json.dumps(value, ensure_ascii=False) + assert len(text.encode()) == size + rows = sql(pm, """SELECT JSON_VALUE(JSON($p), '$' RETURNING CLOB) AS "v" FROM DUAL""", {"p": text}) + # A row of one column is its value. Compared so, as a failure would print a megabyte. + assert len(rows) == 1 + assert len(rows[0]) == len(value) + assert rows[0] == value + + +@pytest.mark.parametrize("size", SIZES) +def test_reads_a_list_parameter_given_as_a_list(pm: PersistenceManager, size: int): + # A list the caller gives, not its text: the host writes its JSON text, as long. + sample = numbers_text(size) + assert sql(pm, NUMBERS, {"p": json.loads(sample.text)}) == [{"n": sample.count, "s": sample.sum}] + + +@pytest.mark.parametrize("size", SIZES) +def test_reads_a_list_parameter_in_cypher(pm: PersistenceManager, size: int): + sample = numbers_text(size) + rows = pm.query( + QuerySpecification[Any](cypher_statement("UNWIND $xs AS x RETURN {n: count(x), s: sum(x)}")).bind( + {"xs": json.loads(sample.text)} + ) + ) + assert rows == [{"n": sample.count, "s": sample.sum}]