/usr/lib/python2.7/dist-packages/sqlalchemy_utils/types/pg_composite.py is in python-sqlalchemy-utils 0.30.12-4.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 | """
CompositeType provides means to interact with
`PostgreSQL composite types`_. Currently this type features:
* Easy attribute access to composite type fields
* Supports SQLAlchemy TypeDecorator types
* Ability to include composite types as part of PostgreSQL arrays
* Type creation and dropping
Installation
^^^^^^^^^^^^
CompositeType automatically attaches `before_create` and `after_drop` DDL
listeners. These listeners create and drop the composite type in the
database. This means it works out of the box in your test environment where
you create the tables on each test run.
When you already have your database set up you should call
:func:`register_composites` after you've set up all models.
::
register_composites(conn)
Usage
^^^^^
::
from collections import OrderedDict
import sqlalchemy as sa
from sqlalchemy_utils import Composite, CurrencyType
class Account(Base):
__tablename__ = 'account'
id = sa.Column(sa.Integer, primary_key=True)
balance = sa.Column(
CompositeType(
'money_type',
[
sa.Column('currency', CurrencyType),
sa.Column('amount', sa.Integer)
]
)
)
Accessing fields
^^^^^^^^^^^^^^^^
CompositeType provides attribute access to underlying fields. In the following
example we find all accounts with balance amount more than 5000.
::
session.query(Account).filter(Account.balance.amount > 5000)
Arrays of composites
^^^^^^^^^^^^^^^^^^^^
::
from sqlalchemy_utils import CompositeArray
class Account(Base):
__tablename__ = 'account'
id = sa.Column(sa.Integer, primary_key=True)
balances = sa.Column(
CompositeArray(
CompositeType(
'money_type',
[
sa.Column('currency', CurrencyType),
sa.Column('amount', sa.Integer)
]
)
)
)
.. _PostgreSQL composite types:
http://www.postgresql.org/docs/devel/static/rowtypes.html
Related links:
http://schinckel.net/2014/09/24/using-postgres-composite-types-in-django/
"""
from collections import namedtuple
import sqlalchemy as sa
from sqlalchemy.dialects.postgresql import ARRAY
from sqlalchemy.dialects.postgresql.psycopg2 import PGDialect_psycopg2
from sqlalchemy.ext.compiler import compiles
from sqlalchemy.schema import _CreateDropBase
from sqlalchemy.sql.expression import FunctionElement
from sqlalchemy.types import (
SchemaType,
to_instance,
TypeDecorator,
UserDefinedType
)
from sqlalchemy_utils import ImproperlyConfigured
psycopg2 = None
CompositeCaster = None
adapt = None
AsIs = None
register_adapter = None
try:
import psycopg2
from psycopg2.extras import CompositeCaster
from psycopg2.extensions import adapt, AsIs, register_adapter
except ImportError:
pass
class CompositeElement(FunctionElement):
"""
Instances of this class wrap a Postgres composite type.
"""
def __init__(self, base, field, type_):
self.name = field
self.type = to_instance(type_)
super(CompositeElement, self).__init__(base)
@compiles(CompositeElement)
def _compile_pgelem(expr, compiler, **kw):
return '(%s).%s' % (compiler.process(expr.clauses, **kw), expr.name)
class CompositeArray(ARRAY):
def _proc_array(self, arr, itemproc, dim, collection):
if dim is None:
if isinstance(self.item_type, CompositeType):
arr = [itemproc(a) for a in arr]
return arr
return ARRAY._proc_array(self, arr, itemproc, dim, collection)
# TODO: Make the registration work on connection level instead of global level
registered_composites = {}
class CompositeType(UserDefinedType, SchemaType):
"""
Represents a PostgreSQL composite type.
:param name:
Name of the composite type.
:param columns:
List of columns that this composite type consists of
"""
python_type = tuple
class comparator_factory(UserDefinedType.Comparator):
def __getattr__(self, key):
try:
type_ = self.type.typemap[key]
except KeyError:
raise KeyError(
"Type '%s' doesn't have an attribute: '%s'" % (
self.name, key
)
)
return CompositeElement(self.expr, key, type_)
def __init__(self, name, columns):
if psycopg2 is None:
raise ImproperlyConfigured(
"'psycopg2' package is required in order to use CompositeType."
)
SchemaType.__init__(self)
self.name = name
self.columns = columns
if name in registered_composites:
self.type_cls = registered_composites[name].type_cls
else:
self.type_cls = namedtuple(
self.name, [c.name for c in columns]
)
registered_composites[name] = self
class Caster(CompositeCaster):
def make(obj, values):
return self.type_cls(*values)
self.caster = Caster
attach_composite_listeners()
def get_col_spec(self):
return self.name
def bind_processor(self, dialect):
def process(value):
if value is None:
return None
processed_value = []
for i, column in enumerate(self.columns):
if isinstance(column.type, TypeDecorator):
processed_value.append(
column.type.process_bind_param(
value[i], dialect
)
)
else:
processed_value.append(value[i])
return self.type_cls(*processed_value)
return process
def result_processor(self, dialect, coltype):
def process(value):
if value is None:
return None
cls = value.__class__
kwargs = {}
for column in self.columns:
if isinstance(column.type, TypeDecorator):
kwargs[column.name] = column.type.process_result_value(
getattr(value, column.name), dialect
)
else:
kwargs[column.name] = getattr(value, column.name)
return cls(**kwargs)
return process
def create(self, bind=None, checkfirst=None):
if (
not checkfirst or
not bind.dialect.has_type(bind, self.name, schema=self.schema)
):
bind.execute(CreateCompositeType(self))
def drop(self, bind=None, checkfirst=True):
if (
checkfirst and
bind.dialect.has_type(bind, self.name, schema=self.schema)
):
bind.execute(DropCompositeType(self))
def register_psycopg2_composite(dbapi_connection, composite):
psycopg2.extras.register_composite(
composite.name,
dbapi_connection,
globally=True,
factory=composite.caster
)
def adapt_composite(value):
values = [
adapt(
getattr(value, column.name)
if not isinstance(column.type, TypeDecorator)
else column.type.process_bind_param(
getattr(value, column.name),
PGDialect_psycopg2()
)
).getquoted().decode('utf-8')
for column in
composite.columns
]
return AsIs("(%s)::%s" % (', '.join(values), composite.name))
register_adapter(composite.type_cls, adapt_composite)
def before_create(target, connection, **kw):
for name, composite in registered_composites.items():
composite.create(connection, checkfirst=True)
register_psycopg2_composite(
connection.connection.connection,
composite
)
def after_drop(target, connection, **kw):
for name, composite in registered_composites.items():
composite.drop(connection, checkfirst=True)
def register_composites(connection):
for name, composite in registered_composites.items():
register_psycopg2_composite(
connection.connection.connection,
composite
)
def attach_composite_listeners():
listeners = [
(sa.MetaData, 'before_create', before_create),
(sa.MetaData, 'after_drop', after_drop),
]
for listener in listeners:
if not sa.event.contains(*listener):
sa.event.listen(*listener)
def remove_composite_listeners():
listeners = [
(sa.MetaData, 'before_create', before_create),
(sa.MetaData, 'after_drop', after_drop),
]
for listener in listeners:
if sa.event.contains(*listener):
sa.event.remove(*listener)
class CreateCompositeType(_CreateDropBase):
pass
@compiles(CreateCompositeType)
def _visit_create_composite_type(create, compiler, **kw):
type_ = create.element
fields = ', '.join(
'{name} {type}'.format(
name=column.name,
type=compiler.dialect.type_compiler.process(
to_instance(column.type)
)
)
for column in type_.columns
)
return 'CREATE TYPE {name} AS ({fields})'.format(
name=compiler.preparer.format_type(type_),
fields=fields
)
class DropCompositeType(_CreateDropBase):
pass
@compiles(DropCompositeType)
def _visit_drop_composite_type(drop, compiler, **kw):
type_ = drop.element
return 'DROP TYPE {name}'.format(name=compiler.preparer.format_type(type_))
|