Skip to content

Commit 443a71b

Browse files
committed
add start of sqlalchemy code examples
1 parent e8c036b commit 443a71b

File tree

60 files changed

+8431
-18
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

60 files changed

+8431
-18
lines changed
Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
title: sqlalchemy.dialects.postgresql.base PGTypeCompiler code examples
2+
category: page
3+
slug: sqlalchemy-dialects-postgresql-base-pgtypecompiler-examples
4+
sortorder: 500031000
5+
toc: False
6+
sidebartitle: sqlalchemy.dialects.postgresql.base PGTypeCompiler
7+
meta: Python example code for the PGTypeCompiler class from the sqlalchemy.dialects.postgresql.base module of the SQLAlchemy project.
8+
9+
10+
PGTypeCompiler is a class within the sqlalchemy.dialects.postgresql.base module of the SQLAlchemy project.
11+
12+
13+
## Example 1 from sqlalchemy-utils
14+
[sqlalchemy-utils](https://github.com/kvesteri/sqlalchemy-utils)
15+
([project documentation](https://sqlalchemy-utils.readthedocs.io/en/latest/)
16+
and
17+
[PyPI package information](https://pypi.org/project/SQLAlchemy-Utils/))
18+
is a code library with various helper functions and new data types
19+
that make it easier to use [SQLAlchemy](/sqlachemy.html) when building
20+
projects that involve more specific storage requirements such as
21+
[currency](https://sqlalchemy-utils.readthedocs.io/en/latest/data_types.html#module-sqlalchemy_utils.types.currency).
22+
The wide array of
23+
[data types](https://sqlalchemy-utils.readthedocs.io/en/latest/data_types.html)
24+
includes [ranged values](https://sqlalchemy-utils.readthedocs.io/en/latest/range_data_types.html)
25+
and [aggregated attributes](https://sqlalchemy-utils.readthedocs.io/en/latest/aggregates.html).
26+
27+
[**sqlalchemy-utils / sqlalchemy_utils / types / ltree.py**](https://github.com/kvesteri/sqlalchemy-utils/blob/master/sqlalchemy_utils/types/ltree.py)
28+
29+
```python
30+
# ltree.py
31+
from __future__ import absolute_import
32+
33+
from sqlalchemy import types
34+
from sqlalchemy.dialects.postgresql import ARRAY
35+
~~from sqlalchemy.dialects.postgresql.base import ischema_names, PGTypeCompiler
36+
from sqlalchemy.sql import expression
37+
38+
from ..primitives import Ltree
39+
from .scalar_coercible import ScalarCoercible
40+
41+
42+
class LtreeType(types.Concatenable, types.UserDefinedType, ScalarCoercible):
43+
"""Postgresql LtreeType type.
44+
45+
The LtreeType datatype can be used for representing labels of data stored
46+
in hierarchial tree-like structure. For more detailed information please
47+
refer to http://www.postgresql.org/docs/current/static/ltree.html
48+
49+
::
50+
51+
from sqlalchemy_utils import LtreeType, Ltree
52+
53+
54+
class DocumentSection(Base):
55+
__tablename__ = 'document_section'
56+
id = sa.Column(sa.Integer, autoincrement=True, primary_key=True)
57+
path = sa.Column(LtreeType)
58+
59+
60+
61+
62+
## ... source file abbreviated to get to PGTypeCompiler examples ...
63+
64+
65+
__visit_name__ = 'LTXTQUERY'
66+
67+
68+
ischema_names['ltree'] = LtreeType
69+
ischema_names['lquery'] = LQUERY
70+
ischema_names['ltxtquery'] = LTXTQUERY
71+
72+
73+
def visit_LTREE(self, type_, **kw):
74+
return 'LTREE'
75+
76+
77+
def visit_LQUERY(self, type_, **kw):
78+
return 'LQUERY'
79+
80+
81+
def visit_LTXTQUERY(self, type_, **kw):
82+
return 'LTXTQUERY'
83+
84+
85+
~~PGTypeCompiler.visit_LTREE = visit_LTREE
86+
~~PGTypeCompiler.visit_LQUERY = visit_LQUERY
87+
~~PGTypeCompiler.visit_LTXTQUERY = visit_LTXTQUERY
88+
89+
90+
## ... source file continues with no further PGTypeCompiler examples...
91+
92+
93+
```
94+
Lines changed: 167 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,167 @@
1+
title: sqlalchemy.dialects.postgresql.psycopg2 PGDialect_psycopg2 code examples
2+
category: page
3+
slug: sqlalchemy-dialects-postgresql-psycopg2-pgdialect-psycopg2-examples
4+
sortorder: 500031000
5+
toc: False
6+
sidebartitle: sqlalchemy.dialects.postgresql.psycopg2 PGDialect_psycopg2
7+
meta: Python example code for the PGDialect_psycopg2 class from the sqlalchemy.dialects.postgresql.psycopg2 module of the SQLAlchemy project.
8+
9+
10+
PGDialect_psycopg2 is a class within the sqlalchemy.dialects.postgresql.psycopg2 module of the SQLAlchemy project.
11+
12+
13+
## Example 1 from sqlalchemy-utils
14+
[sqlalchemy-utils](https://github.com/kvesteri/sqlalchemy-utils)
15+
([project documentation](https://sqlalchemy-utils.readthedocs.io/en/latest/)
16+
and
17+
[PyPI package information](https://pypi.org/project/SQLAlchemy-Utils/))
18+
is a code library with various helper functions and new data types
19+
that make it easier to use [SQLAlchemy](/sqlachemy.html) when building
20+
projects that involve more specific storage requirements such as
21+
[currency](https://sqlalchemy-utils.readthedocs.io/en/latest/data_types.html#module-sqlalchemy_utils.types.currency).
22+
The wide array of
23+
[data types](https://sqlalchemy-utils.readthedocs.io/en/latest/data_types.html)
24+
includes [ranged values](https://sqlalchemy-utils.readthedocs.io/en/latest/range_data_types.html)
25+
and [aggregated attributes](https://sqlalchemy-utils.readthedocs.io/en/latest/aggregates.html).
26+
27+
[**sqlalchemy-utils / sqlalchemy_utils / types / pg_composite.py**](https://github.com/kvesteri/sqlalchemy-utils/blob/master/sqlalchemy_utils/types/pg_composite.py)
28+
29+
```python
30+
# pg_composite.py
31+
"""
32+
CompositeType provides means to interact with
33+
`PostgreSQL composite types`_. Currently this type features:
34+
35+
* Easy attribute access to composite type fields
36+
* Supports SQLAlchemy TypeDecorator types
37+
* Ability to include composite types as part of PostgreSQL arrays
38+
* Type creation and dropping
39+
40+
Installation
41+
^^^^^^^^^^^^
42+
43+
CompositeType automatically attaches `before_create` and `after_drop` DDL
44+
listeners. These listeners create and drop the composite type in the
45+
database. This means it works out of the box in your test environment where
46+
you create the tables on each test run.
47+
48+
When you already have your database set up you should call
49+
:func:`register_composites` after you've set up all models.
50+
51+
::
52+
53+
register_composites(conn)
54+
55+
56+
57+
Usage
58+
^^^^^
59+
60+
::
61+
62+
63+
## ... source file abbreviated to get to PGDialect_psycopg2 examples ...
64+
65+
66+
sa.Column('amount', sa.Integer)
67+
]
68+
)
69+
)
70+
)
71+
72+
73+
.. _PostgreSQL composite types:
74+
http://www.postgresql.org/docs/current/static/rowtypes.html
75+
76+
77+
Related links:
78+
79+
http://schinckel.net/2014/09/24/using-postgres-composite-types-in-django/
80+
"""
81+
from collections import namedtuple
82+
83+
import six
84+
import sqlalchemy as sa
85+
from sqlalchemy.dialects.postgresql import ARRAY
86+
~~from sqlalchemy.dialects.postgresql.psycopg2 import PGDialect_psycopg2
87+
from sqlalchemy.ext.compiler import compiles
88+
from sqlalchemy.schema import _CreateDropBase
89+
from sqlalchemy.sql.expression import FunctionElement
90+
from sqlalchemy.types import (
91+
SchemaType,
92+
to_instance,
93+
TypeDecorator,
94+
UserDefinedType
95+
)
96+
97+
from .. import ImproperlyConfigured
98+
99+
psycopg2 = None
100+
CompositeCaster = None
101+
adapt = None
102+
AsIs = None
103+
register_adapter = None
104+
try:
105+
import psycopg2
106+
from psycopg2.extras import CompositeCaster
107+
from psycopg2.extensions import adapt, AsIs, register_adapter
108+
except ImportError:
109+
pass
110+
111+
112+
113+
## ... source file abbreviated to get to PGDialect_psycopg2 examples ...
114+
115+
116+
bind.dialect.has_type(bind, self.name, schema=self.schema)
117+
):
118+
bind.execute(DropCompositeType(self))
119+
120+
121+
def register_psycopg2_composite(dbapi_connection, composite):
122+
psycopg2.extras.register_composite(
123+
composite.name,
124+
dbapi_connection,
125+
globally=True,
126+
factory=composite.caster
127+
)
128+
129+
def adapt_composite(value):
130+
adapted = [
131+
adapt(
132+
getattr(value, column.name)
133+
if not isinstance(column.type, TypeDecorator)
134+
else column.type.process_bind_param(
135+
getattr(value, column.name),
136+
~~ PGDialect_psycopg2()
137+
)
138+
)
139+
for column in
140+
composite.columns
141+
]
142+
for value in adapted:
143+
if hasattr(value, 'prepare'):
144+
value.prepare(dbapi_connection)
145+
values = [
146+
value.getquoted().decode(dbapi_connection.encoding)
147+
if six.PY3
148+
else value.getquoted()
149+
for value in adapted
150+
]
151+
return AsIs("(%s)::%s" % (', '.join(values), composite.name))
152+
153+
register_adapter(composite.type_cls, adapt_composite)
154+
155+
156+
def before_create(target, connection, **kw):
157+
for name, composite in registered_composites.items():
158+
composite.create(connection, checkfirst=True)
159+
register_psycopg2_composite(
160+
connection.connection.connection,
161+
162+
163+
## ... source file continues with no further PGDialect_psycopg2 examples...
164+
165+
166+
```
167+
Lines changed: 114 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,114 @@
1+
title: sqlalchemy.engine.default DefaultDialect code examples
2+
category: page
3+
slug: sqlalchemy-engine-default-defaultdialect-examples
4+
sortorder: 500031000
5+
toc: False
6+
sidebartitle: sqlalchemy.engine.default DefaultDialect
7+
meta: Python example code for the DefaultDialect class from the sqlalchemy.engine.default module of the SQLAlchemy project.
8+
9+
10+
DefaultDialect is a class within the sqlalchemy.engine.default module of the SQLAlchemy project.
11+
12+
13+
## Example 1 from alembic
14+
[Alembic](https://github.com/sqlalchemy/alembic)
15+
([project documentation](https://alembic.sqlalchemy.org/) and
16+
[PyPI page](https://pypi.org/project/alembic/))
17+
is a data migrations tool used with [SQLAlchemy](/sqlalchemy.html) to make
18+
database schema changes. The Alembic project is open sourced under the
19+
[MIT license](https://github.com/sqlalchemy/alembic/blob/master/LICENSE).
20+
21+
[**alembic / alembic / autogenerate / api.py**](https://github.com/sqlalchemy/alembic/blob/master/alembic/autogenerate/api.py)
22+
23+
```python
24+
# api.py
25+
"""Provide the 'autogenerate' feature which can produce migration operations
26+
automatically."""
27+
28+
import contextlib
29+
30+
from sqlalchemy import inspect
31+
32+
from . import compare
33+
from . import render
34+
from .. import util
35+
from ..operations import ops
36+
37+
38+
def compare_metadata(context, metadata):
39+
"""Compare a database schema to that given in a
40+
:class:`-sqlalchemy.schema.MetaData` instance.
41+
42+
The database connection is presented in the context
43+
of a :class:`.MigrationContext` object, which
44+
provides database connectivity as well as optional
45+
comparison functions to use for datatypes and
46+
server defaults - see the "autogenerate" arguments
47+
at :meth:`.EnvironmentContext.configure`
48+
for details on these.
49+
50+
The return format is a list of "diff" directives,
51+
each representing individual differences::
52+
53+
from alembic.migration import MigrationContext
54+
from alembic.autogenerate import compare_metadata
55+
56+
57+
## ... source file abbreviated to get to DefaultDialect examples ...
58+
59+
60+
imports=(),
61+
render_item=None,
62+
migration_context=None,
63+
):
64+
"""Render Python code given an :class:`.UpgradeOps` or
65+
:class:`.DowngradeOps` object.
66+
67+
This is a convenience function that can be used to test the
68+
autogenerate output of a user-defined :class:`.MigrationScript` structure.
69+
70+
"""
71+
opts = {
72+
"sqlalchemy_module_prefix": sqlalchemy_module_prefix,
73+
"alembic_module_prefix": alembic_module_prefix,
74+
"render_item": render_item,
75+
"render_as_batch": render_as_batch,
76+
}
77+
78+
if migration_context is None:
79+
from ..runtime.migration import MigrationContext
80+
~~ from sqlalchemy.engine.default import DefaultDialect
81+
82+
migration_context = MigrationContext.configure(
83+
~~ dialect=DefaultDialect()
84+
)
85+
86+
autogen_context = AutogenContext(migration_context, opts=opts)
87+
autogen_context.imports = set(imports)
88+
return render._indent(
89+
render._render_cmd_body(up_or_down_op, autogen_context)
90+
)
91+
92+
93+
def _render_migration_diffs(context, template_args):
94+
"""legacy, used by test_autogen_composition at the moment"""
95+
96+
autogen_context = AutogenContext(context)
97+
98+
upgrade_ops = ops.UpgradeOps([])
99+
compare._produce_net_changes(autogen_context, upgrade_ops)
100+
101+
migration_script = ops.MigrationScript(
102+
rev_id=None,
103+
upgrade_ops=upgrade_ops,
104+
downgrade_ops=upgrade_ops.reverse(),
105+
)
106+
107+
render._render_python_into_templatevars(
108+
109+
110+
## ... source file continues with no further DefaultDialect examples...
111+
112+
113+
```
114+

0 commit comments

Comments
 (0)