summaryrefslogtreecommitdiff
path: root/lib/sqlalchemy/dialects
diff options
context:
space:
mode:
authornathan <nathan.alexander.rice@gmail.com>2013-12-09 11:46:36 -0500
committernathan <nathan.alexander.rice@gmail.com>2013-12-09 11:46:36 -0500
commit64288c7d6ffc021e2388aa764e9a3b921506c7a0 (patch)
treeadf83af6255bc1e0d1e86cd0d4c0ed4735a737ad /lib/sqlalchemy/dialects
parent3a03c2e715544476ab2e53ab9b26d83800e437ed (diff)
downloadsqlalchemy-64288c7d6ffc021e2388aa764e9a3b921506c7a0.tar.gz
sqlalchemy/dialects/postgresql/__init__.py:
- Added import references to JSON class sqlalchemy/dialects/postgresql/base.py: - Added visitor method for JSON class sqlalchemy/dialects/postgresql/pgjson (new): - JSON class, supports automatic serialization and deserialization of json data, as well as basic json operators.
Diffstat (limited to 'lib/sqlalchemy/dialects')
-rw-r--r--lib/sqlalchemy/dialects/postgresql/__init__.py3
-rw-r--r--lib/sqlalchemy/dialects/postgresql/base.py3
-rw-r--r--lib/sqlalchemy/dialects/postgresql/pgjson.py109
3 files changed, 114 insertions, 1 deletions
diff --git a/lib/sqlalchemy/dialects/postgresql/__init__.py b/lib/sqlalchemy/dialects/postgresql/__init__.py
index 408b67846..00bbc7268 100644
--- a/lib/sqlalchemy/dialects/postgresql/__init__.py
+++ b/lib/sqlalchemy/dialects/postgresql/__init__.py
@@ -14,6 +14,7 @@ from .base import \
DATE, BYTEA, BOOLEAN, INTERVAL, ARRAY, ENUM, dialect, array, Any, All
from .constraints import ExcludeConstraint
from .hstore import HSTORE, hstore
+from .pgjson import JSON
from .ranges import INT4RANGE, INT8RANGE, NUMRANGE, DATERANGE, TSRANGE, \
TSTZRANGE
@@ -23,5 +24,5 @@ __all__ = (
'DOUBLE_PRECISION', 'TIMESTAMP', 'TIME', 'DATE', 'BYTEA', 'BOOLEAN',
'INTERVAL', 'ARRAY', 'ENUM', 'dialect', 'Any', 'All', 'array', 'HSTORE',
'hstore', 'INT4RANGE', 'INT8RANGE', 'NUMRANGE', 'DATERANGE',
- 'TSRANGE', 'TSTZRANGE'
+ 'TSRANGE', 'TSTZRANGE', 'json', 'JSON'
)
diff --git a/lib/sqlalchemy/dialects/postgresql/base.py b/lib/sqlalchemy/dialects/postgresql/base.py
index b80f269c1..6469f3b70 100644
--- a/lib/sqlalchemy/dialects/postgresql/base.py
+++ b/lib/sqlalchemy/dialects/postgresql/base.py
@@ -1187,6 +1187,9 @@ class PGTypeCompiler(compiler.GenericTypeCompiler):
def visit_HSTORE(self, type_):
return "HSTORE"
+ def visit_JSON(self, type_):
+ return "JSON"
+
def visit_INT4RANGE(self, type_):
return "INT4RANGE"
diff --git a/lib/sqlalchemy/dialects/postgresql/pgjson.py b/lib/sqlalchemy/dialects/postgresql/pgjson.py
new file mode 100644
index 000000000..aef54709b
--- /dev/null
+++ b/lib/sqlalchemy/dialects/postgresql/pgjson.py
@@ -0,0 +1,109 @@
+# postgresql/json.py
+# Copyright (C) 2005-2013 the SQLAlchemy authors and contributors <see AUTHORS file>
+#
+# This module is part of SQLAlchemy and is released under
+# the MIT License: http://www.opensource.org/licenses/mit-license.php
+
+import json
+
+from .base import ARRAY, ischema_names
+from ... import types as sqltypes
+from ...sql import functions as sqlfunc
+from ...sql.operators import custom_op
+from ... import util
+
+__all__ = ('JSON', 'json')
+
+
+class JSON(sqltypes.TypeEngine):
+ """Represent the Postgresql HSTORE type.
+
+ The :class:`.JSON` type stores arbitrary JSON format data, e.g.::
+
+ data_table = Table('data_table', metadata,
+ Column('id', Integer, primary_key=True),
+ Column('data', JSON)
+ )
+
+ with engine.connect() as conn:
+ conn.execute(
+ data_table.insert(),
+ data = {"key1": "value1", "key2": "value2"}
+ )
+
+ :class:`.JSON` provides two operations:
+
+ * Index operations::
+
+ data_table.c.data['some key'] == 'some value'
+
+ * Path Index operations::
+
+ data_table.c.data.get_path('{key_1, key_2, ..., key_n}']
+
+ Please be aware that when used with the SQL Alchemy ORM, you will need to
+ replace the JSON object present on an attribute with a new object in order
+ for any changes to be properly persisted.
+
+ .. versionadded:: 0.9
+ """
+
+ __visit_name__ = 'JSON'
+
+ def __init__(self, json_serializer=None, json_deserializer=None):
+ if json_serializer:
+ self.json_serializer = json_serializer
+ else:
+ self.json_serializer = json.dumps
+ if json_deserializer:
+ self.json_deserializer = json_deserializer
+ else:
+ self.json_deserializer = json.loads
+
+ class comparator_factory(sqltypes.Concatenable.Comparator):
+ """Define comparison operations for :class:`.JSON`."""
+
+ def __getitem__(self, other):
+ """Text expression. Get the value at a given key."""
+ # I'm choosing to return text here so the result can be cast,
+ # compared with strings, etc.
+ #
+ # The only downside to this is that you cannot dereference more
+ # than one level deep in json structures, though comparator
+ # support for multi-level dereference is lacking anyhow.
+ return self.expr.op('->>', precedence=5)(other)
+
+ def get_path(self, other):
+ """Text expression. Get the value at a given path. Paths are of
+ the form {key_1, key_2, ..., key_n}."""
+ return self.expr.op('#>>', precedence=5)(other)
+
+ def _adapt_expression(self, op, other_comparator):
+ if isinstance(op, custom_op):
+ if op.opstring == '->':
+ return op, sqltypes.Text
+ return sqltypes.Concatenable.Comparator.\
+ _adapt_expression(self, op, other_comparator)
+
+ def bind_processor(self, dialect):
+ if util.py2k:
+ encoding = dialect.encoding
+ def process(value):
+ return self.json_serializer(value).encode(encoding)
+ else:
+ def process(value):
+ return self.json_serializer(value)
+ return process
+
+ def result_processor(self, dialect, coltype):
+ if util.py2k:
+ encoding = dialect.encoding
+ def process(value):
+ return self.json_deserializer(value.decode(encoding))
+ else:
+ def process(value):
+ return self.json_deserializer(value)
+ return process
+
+
+ischema_names['json'] = JSON