Skip to content

Add support for array and struct literals #67

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

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions pybigquery/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
from sqlalchemy.dialects.postgresql import array
from sqlalchemy.sql import expression, operators, sqltypes

__all__ = ["array", "struct"]


class STRUCT(sqltypes.Indexable, sqltypes.TypeEngine):
# NOTE: STRUCT names/types aren't currently supported.

__visit_name__ = "STRUCT"

class Comparator(sqltypes.Indexable.Comparator):
def _setup_getitem(self, index):
return operators.getitem, index, self.type

comparator_factory = Comparator


class struct(expression.ClauseList, expression.ColumnElement):
""" Create a BigQuery struct literal from a collection of named expressions/clauses.
"""
# NOTE: Struct subfields aren't currently propagated/validated.

__visit_name__ = "struct"

def __init__(self, clauses, field=None, **kw):
self.field = field
self.type = STRUCT()
super().__init__(*clauses, **kw)

def _bind_param(self, operator, obj, _assume_scalar=False, type_=None):
if operator is operators.getitem:
# TODO:
# - Validate field in clauses (or error if no clauses)
# - If the field is a sub-struct, return with all clauses, otherwise none.
return struct([], field=obj)

def self_group(self, against=None):
if not self.field and against in (operators.getitem,):
return expression.Grouping(self)
else:
return self
16 changes: 16 additions & 0 deletions pybigquery/sqlalchemy_bigquery.py
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,22 @@ def __init__(self, dialect, statement, column_keys=None,
kwargs['compile_kwargs'] = util.immutabledict({'include_table': False})
super(BigQueryCompiler, self).__init__(dialect, statement, column_keys, inline, **kwargs)

def visit_array(self, element, **kw):
return "[%s]" % self.visit_clauselist(element, **kw)

def visit_struct(self, element, within_columns_clause=True, **kw):
if element.field:
return self.preparer.quote_column(element.field)
kw["within_columns_clause"] = True
values = self.visit_clauselist(element, **kw)
return "struct(%s)" % values

def visit_getitem_binary(self, binary, operator, **kw):
return "%s.%s" % (
self.process(binary.left, **kw),
self.process(binary.right, **kw),
)

def visit_select(self, *args, **kwargs):
"""
Use labels for every column.
Expand Down