-
Notifications
You must be signed in to change notification settings - Fork 138
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat: add JSON type, bindparam support #1147
Open
r1b
wants to merge
5
commits into
googleapis:main
Choose a base branch
from
r1b:feat/json-support-inc-type
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+94
−1
Open
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
140ca3a
feat: add JSON type, bindparam support
r1b d0fd734
formatting fixes
r1b 65d676d
move bindparam workaround to visit_JSON
r1b b168080
Revert "move bindparam workaround to visit_JSON"
r1b 2a03b31
move bindparam workaround to visit_JSON better
r1b File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,8 @@ | ||
import sqlalchemy | ||
|
||
|
||
class JSON(sqlalchemy.sql.sqltypes.JSON): | ||
def bind_expression(self, bindvalue): | ||
# JSON query parameters have type STRING | ||
# This hook ensures that the rendered expression has type JSON | ||
return sqlalchemy.func.PARSE_JSON(bindvalue, type_=self) | ||
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -59,7 +59,7 @@ | |
import re | ||
|
||
from .parse_url import parse_url | ||
from . import _helpers, _struct, _types | ||
from . import _helpers, _json, _struct, _types | ||
import sqlalchemy_bigquery_vendored.sqlalchemy.postgresql.base as vendored_postgresql | ||
|
||
# Illegal characters is intended to be all characters that are not explicitly | ||
|
@@ -641,6 +641,17 @@ def visit_NUMERIC(self, type_, **kw): | |
|
||
visit_DECIMAL = visit_NUMERIC | ||
|
||
def visit_JSON(self, type_, **kw): | ||
if isinstance( | ||
kw.get("type_expression"), Column | ||
): # column def | ||
return "JSON" | ||
# FIXME: JSON is not a member of `SqlParameterScalarTypes` in the DBAPI | ||
# For now, we hack around this by: | ||
# - Rewriting the bindparam type to STRING | ||
# - Applying a bind expression that converts the parameter back to JSON | ||
return "STRING" | ||
|
||
|
||
class BigQueryDDLCompiler(DDLCompiler): | ||
option_datatype_mapping = { | ||
|
@@ -1076,6 +1087,7 @@ class BigQueryDialect(DefaultDialect): | |
sqlalchemy.sql.sqltypes.TIMESTAMP: BQTimestamp, | ||
sqlalchemy.sql.sqltypes.ARRAY: BQArray, | ||
sqlalchemy.sql.sqltypes.Enum: sqlalchemy.sql.sqltypes.Enum, | ||
sqlalchemy.sql.sqltypes.JSON: _json.JSON, | ||
} | ||
|
||
def __init__( | ||
|
@@ -1086,6 +1098,8 @@ def __init__( | |
credentials_info=None, | ||
credentials_base64=None, | ||
list_tables_page_size=1000, | ||
json_serializer=None, | ||
json_deserializer=None, | ||
Comment on lines
+1101
to
+1102
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. note See https://docs.sqlalchemy.org/en/20/core/type_basics.html#sqlalchemy.types.JSON section "Customizing the JSON Serializer" |
||
*args, | ||
**kwargs, | ||
): | ||
|
@@ -1098,6 +1112,8 @@ def __init__( | |
self.identifier_preparer = self.preparer(self) | ||
self.dataset_id = None | ||
self.list_tables_page_size = list_tables_page_size | ||
self._json_serializer = json_serializer | ||
self._json_deserializer = json_deserializer | ||
|
||
@classmethod | ||
def dbapi(cls): | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,64 @@ | ||
import json | ||
from unittest import mock | ||
|
||
import pytest | ||
import sqlalchemy | ||
|
||
|
||
@pytest.fixture | ||
def json_table(metadata): | ||
from sqlalchemy_bigquery import JSON | ||
|
||
return sqlalchemy.Table("json_table", metadata, sqlalchemy.Column("json", JSON)) | ||
|
||
|
||
@pytest.fixture | ||
def json_data(): | ||
return {"foo": "bar"} | ||
|
||
|
||
def test_set_json_serde(faux_conn, metadata, json_table, json_data): | ||
from sqlalchemy_bigquery import JSON | ||
|
||
json_serializer = mock.Mock(side_effect=json.dumps) | ||
json_deserializer = mock.Mock(side_effect=json.loads) | ||
|
||
engine = sqlalchemy.create_engine( | ||
"bigquery://myproject/mydataset", | ||
json_serializer=json_serializer, | ||
json_deserializer=json_deserializer, | ||
) | ||
|
||
json_column = json_table.c.json | ||
|
||
process_bind = json_column.type.bind_processor(engine.dialect) | ||
process_bind(json_data) | ||
assert json_serializer.mock_calls == [mock.call(json_data)] | ||
|
||
process_result = json_column.type.result_processor(engine.dialect, JSON) | ||
process_result(json.dumps(json_data)) | ||
assert json_deserializer.mock_calls == [mock.call(json.dumps(json_data))] | ||
|
||
|
||
def test_json_create(faux_conn, metadata, json_table, json_data): | ||
expr = sqlalchemy.schema.CreateTable(json_table) | ||
sql = expr.compile(faux_conn.engine).string | ||
assert sql == "\nCREATE TABLE `json_table` (\n\t`json` JSON\n) \n\n" | ||
|
||
|
||
def test_json_insert(faux_conn, metadata, json_table, json_data): | ||
expr = sqlalchemy.insert(json_table).values(json=json_data) | ||
sql = expr.compile(faux_conn.engine).string | ||
assert ( | ||
sql == "INSERT INTO `json_table` (`json`) VALUES (PARSE_JSON(%(json:STRING)s))" | ||
) | ||
|
||
|
||
def test_json_where(faux_conn, metadata, json_table, json_data): | ||
expr = sqlalchemy.select(json_table.c.json).where(json_table.c.json == json_data) | ||
sql = expr.compile(faux_conn.engine).string | ||
assert sql == ( | ||
"SELECT `json_table`.`json` \n" | ||
"FROM `json_table` \n" | ||
"WHERE `json_table`.`json` = PARSE_JSON(%(json_1:STRING)s)" | ||
) |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
note An alternative here would be to just preserve the STRING type and let BigQuery handle the cast, but this seems hard to reason about. It feels right to have the expression type in BigQuery match the expression type here in SQLAlchemy.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Looking at [1] and pondering this - it wouldn't be that surprising if a user wanted to submit invalid JSON as a query parameter at some point. This could be supported by parameterizing this behavior in the type, i.e:
JSON(strict=False)
or similar. Not worried about it right now, though.[1] https://cloud.google.com/bigquery/docs/reference/standard-sql/json_functions#non-validation_of_string_inputs