diff options
author | Mike Bayer <mike_mp@zzzcomputing.com> | 2013-12-27 18:25:57 -0500 |
---|---|---|
committer | Mike Bayer <mike_mp@zzzcomputing.com> | 2013-12-27 18:25:57 -0500 |
commit | 2104d0ba2d612a26d363a3049d5e49efe4284e15 (patch) | |
tree | 94878393dfd1d689dd5173e86c575af4b44c5261 /lib/sqlalchemy/dialects/postgresql/json.py | |
parent | de786a4208e621229769a8fb1f876f358dc4e70e (diff) | |
download | sqlalchemy-2104d0ba2d612a26d363a3049d5e49efe4284e15.tar.gz |
- rework the JSON expression system so that "astext" is called *after*
the indexing. this is for more natural operation.
- also add cast() to the JSON expression to complement astext. This integrates
the CAST call which will be needed frequently. Part of [ticket:2687].
- it's a little unclear how more advanced unicode attribute-access is going to go,
some quick attempts at testing yielded strange error messages from psycopg2.
- do other cross linking as mentioned in [ticket:2687].
Diffstat (limited to 'lib/sqlalchemy/dialects/postgresql/json.py')
-rw-r--r-- | lib/sqlalchemy/dialects/postgresql/json.py | 120 |
1 files changed, 89 insertions, 31 deletions
diff --git a/lib/sqlalchemy/dialects/postgresql/json.py b/lib/sqlalchemy/dialects/postgresql/json.py index 7ba8b1abe..7f8aad51e 100644 --- a/lib/sqlalchemy/dialects/postgresql/json.py +++ b/lib/sqlalchemy/dialects/postgresql/json.py @@ -10,9 +10,83 @@ import json from .base import ischema_names from ... import types as sqltypes from ...sql.operators import custom_op +from ... import sql +from ...sql import elements from ... import util -__all__ = ('JSON', ) +__all__ = ('JSON', 'JSONElement') + + +class JSONElement(elements.BinaryExpression): + """Represents accessing an element of a :class:`.JSON` value. + + The :class:`.JSONElement` is produced whenever using the Python index + operator on an expression that has the type :class:`.JSON`:: + + expr = mytable.c.json_data['some_key'] + + The expression typically compiles to a JSON access such as ``col -> key``. + Modifiers are then available for typing behavior, including :meth:`.JSONElement.cast` + and :attr:`.JSONElement.astext`. + + """ + def __init__(self, left, right, astext=False, opstring=None, result_type=None): + self._astext = astext + if opstring is None: + if hasattr(right, '__iter__') and \ + not isinstance(right, util.string_types): + opstring = "#>" + right = "{%s}" % (", ".join(util.text_type(elem) for elem in right)) + else: + opstring = "->" + + self._json_opstring = opstring + operator = custom_op(opstring, precedence=5) + right = left._check_literal(left, operator, right) + super(JSONElement, self).__init__(left, right, operator, type_=result_type) + + @property + def astext(self): + """Convert this :class:`.JSONElement` to use the 'astext' operator + when evaluated. + + E.g.:: + + select([data_table.c.data['some key'].astext]) + + .. seealso:: + + :meth:`.JSONElement.cast` + + """ + if self._astext: + return self + else: + return JSONElement( + self.left, + self.right, + astext=True, + opstring=self._json_opstring + ">", + result_type=sqltypes.String(convert_unicode=True) + ) + + def cast(self, type_): + """Convert this :class:`.JSONElement` to apply both the 'astext' operator + as well as an explicit type cast when evaulated. + + E.g.:: + + select([data_table.c.data['some key'].cast(Integer)]) + + .. seealso:: + + :attr:`.JSONElement.astext` + + """ + if not self._astext: + return self.astext.cast(type_) + else: + return sql.cast(self, type_) class JSON(sqltypes.TypeEngine): @@ -37,17 +111,26 @@ class JSON(sqltypes.TypeEngine): data_table.c.data['some key'] - * Index operations returning text (required for text comparison or casting):: + * Index operations returning text (required for text comparison):: + + data_table.c.data['some key'].astext == 'some value' + + * Index operations with a built-in CAST call:: - data_table.c.data.astext['some key'] == 'some value' + data_table.c.data['some key'].cast(Integer) == 5 * Path index operations:: data_table.c.data[('key_1', 'key_2', ..., 'key_n')] - * Path index operations returning text (required for text comparison or casting):: + * Path index operations returning text (required for text comparison):: - data_table.c.data.astext[('key_1', 'key_2', ..., 'key_n')] == 'some value' + data_table.c.data[('key_1', 'key_2', ..., 'key_n')].astext == 'some value' + + Index operations return an instance of :class:`.JSONElement`, which represents + an expression such as ``column -> index``. This element then defines + methods such as :attr:`.JSONElement.astext` and :meth:`.JSONElement.cast` + for setting up type behavior. The :class:`.JSON` type, when used with the SQLAlchemy ORM, does not detect in-place mutations to the structure. In order to detect these, the @@ -78,35 +161,10 @@ class JSON(sqltypes.TypeEngine): class comparator_factory(sqltypes.Concatenable.Comparator): """Define comparison operations for :class:`.JSON`.""" - class _astext(object): - def __init__(self, parent): - self.parent = parent - - def __getitem__(self, other): - return self.parent.expr._get_item(other, True) - - def _get_item(self, other, astext): - if hasattr(other, '__iter__') and \ - not isinstance(other, util.string_types): - op = "#>" - other = "{%s}" % (", ".join(util.text_type(elem) for elem in other)) - else: - op = "->" - - if astext: - op += ">" - - # ops: ->, ->>, #>, #>> - return self.expr.op(op, precedence=5)(other) - def __getitem__(self, other): """Get the value at a given key.""" - return self._get_item(other, False) - - @property - def astext(self): - return self._astext(self) + return JSONElement(self.expr, other) def _adapt_expression(self, op, other_comparator): if isinstance(op, custom_op): |