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 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390
|
"""
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 CompositeType, 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)
]
)
)
Creation
~~~~~~~~
When creating CompositeType, you can either pass in a tuple or a dictionary.
::
account1 = Account()
account1.balance = ('USD', 15)
account2 = Account()
account2.balance = {'currency': 'USD', 'amount': 15}
session.add(account1)
session.add(account2)
session.commit()
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.dialects.postgresql import ARRAY
class Account(Base):
__tablename__ = 'account'
id = sa.Column(sa.Integer, primary_key=True)
balances = sa.Column(
ARRAY(
CompositeType(
'money_type',
[
sa.Column('currency', CurrencyType),
sa.Column('amount', sa.Integer)
]
),
dimensions=1
)
)
.. _PostgreSQL composite types:
https://www.postgresql.org/docs/current/rowtypes.html
Related links:
https://schinckel.net/2014/09/24/using-postgres-composite-types-in-django/
"""
from collections import namedtuple
import sqlalchemy as sa
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 .. import ImproperlyConfigured
psycopg2 = None
CompositeCaster = None
adapt = None
AsIs = None
register_adapter = None
try:
import psycopg2
from psycopg2.extensions import adapt, AsIs, register_adapter
from psycopg2.extras import CompositeCaster
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().__init__(base)
@compiles(CompositeElement)
def _compile_pgelem(expr, compiler, **kw):
return f'({compiler.process(expr.clauses, **kw)}).{expr.name}'
# 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 '{}' doesn't have an attribute: '{}'".format(
self.name, key
)
)
return CompositeElement(self.expr, key, type_)
def __init__(self, name, columns, quote=None, **kwargs):
if psycopg2 is None:
raise ImproperlyConfigured(
"'psycopg2' package is required in order to use CompositeType."
)
SchemaType.__init__(
self,
name=name,
quote=quote
)
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):
current_value = (
value.get(column.name)
if isinstance(value, dict)
else value[i]
)
if isinstance(column.type, TypeDecorator):
processed_value.append(
column.type.process_bind_param(
current_value, dialect
)
)
else:
processed_value.append(current_value)
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):
dialect = PGDialect_psycopg2()
adapted = [
adapt(
getattr(value, column.name)
if not isinstance(column.type, TypeDecorator)
else column.type.process_bind_param(
getattr(value, column.name),
dialect
)
)
for column in
composite.columns
]
for value in adapted:
if hasattr(value, 'prepare'):
value.prepare(dbapi_connection)
values = [
value.getquoted().decode(dbapi_connection.encoding)
for value in adapted
]
return AsIs(
'({})::{}'.format(
', '.join(values),
dialect.identifier_preparer.quote(composite.name)
)
)
register_adapter(composite.type_cls, adapt_composite)
def get_driver_connection(connection):
try:
# SQLAlchemy 2.0
return connection.connection.driver_connection
except AttributeError:
return connection.connection.connection
def before_create(target, connection, **kw):
for name, composite in registered_composites.items():
composite.create(connection, checkfirst=True)
register_psycopg2_composite(
get_driver_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(
get_driver_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 f'DROP TYPE {compiler.preparer.format_type(type_)}'
|