summaryrefslogtreecommitdiff
path: root/lib/sqlalchemy
diff options
context:
space:
mode:
authorMike Bayer <mike_mp@zzzcomputing.com>2012-09-09 14:39:25 -0400
committerMike Bayer <mike_mp@zzzcomputing.com>2012-09-09 14:39:25 -0400
commit1c325dc9c73820e78ab79d4aa160dc0f6cbe3b65 (patch)
tree02b1a3fb6f24fe0bddd582a3fec519c99d40d36c /lib/sqlalchemy
parentb96250d0063cd7ce9cc1f95abade68e6656d6acb (diff)
downloadsqlalchemy-1c325dc9c73820e78ab79d4aa160dc0f6cbe3b65.tar.gz
- [feature] Added a hook to the system of rendering
CREATE TABLE that provides access to the render for each Column individually, by constructing a @compiles function against the new schema.CreateColumn construct. [ticket:2463]
Diffstat (limited to 'lib/sqlalchemy')
-rw-r--r--lib/sqlalchemy/ext/compiler.py15
-rw-r--r--lib/sqlalchemy/schema.py88
-rw-r--r--lib/sqlalchemy/sql/compiler.py33
3 files changed, 126 insertions, 10 deletions
diff --git a/lib/sqlalchemy/ext/compiler.py b/lib/sqlalchemy/ext/compiler.py
index d5fbec518..e3e668364 100644
--- a/lib/sqlalchemy/ext/compiler.py
+++ b/lib/sqlalchemy/ext/compiler.py
@@ -368,8 +368,12 @@ Example usage::
"""
from .. import exc
+from ..sql import visitors
def compiles(class_, *specs):
+ """Register a function as a compiler for a
+ given :class:`.ClauseElement` type."""
+
def decorate(fn):
existing = class_.__dict__.get('_compiler_dispatcher', None)
existing_dispatch = class_.__dict__.get('_compiler_dispatch')
@@ -392,6 +396,17 @@ def compiles(class_, *specs):
return fn
return decorate
+def deregister(class_):
+ """Remove all custom compilers associated with a given
+ :class:`.ClauseElement` type."""
+
+ if hasattr(class_, '_compiler_dispatcher'):
+ # regenerate default _compiler_dispatch
+ visitors._generate_dispatch(class_)
+ # remove custom directive
+ del class_._compiler_dispatcher
+
+
class _dispatcher(object):
def __init__(self):
self.specs = {}
diff --git a/lib/sqlalchemy/schema.py b/lib/sqlalchemy/schema.py
index cd14a6452..1c535461a 100644
--- a/lib/sqlalchemy/schema.py
+++ b/lib/sqlalchemy/schema.py
@@ -3186,6 +3186,94 @@ class CreateTable(_CreateDropBase):
__visit_name__ = "create_table"
+ def __init__(self, element, on=None, bind=None):
+ """Create a :class:`.CreateTable` construct.
+
+ :param element: a :class:`.Table` that's the subject
+ of the CREATE
+ :param on: See the description for 'on' in :class:`.DDL`.
+ :param bind: See the description for 'bind' in :class:`.DDL`.
+
+ """
+ super(CreateTable, self).__init__(element, on=on, bind=bind)
+ self.columns = [CreateColumn(column)
+ for column in element.columns
+ ]
+
+class CreateColumn(visitors.Visitable):
+ """Represent a :class:`.Column` as rendered in a CREATE TABLE statement,
+ via the :class:`.CreateTable` construct.
+
+ This is provided to support custom column DDL within the generation
+ of CREATE TABLE statements, by using the
+ compiler extension documented in :ref:`sqlalchemy.ext.compiler_toplevel`
+ to extend :class:`.CreateColumn`.
+
+ Typical integration is to examine the incoming :class:`.Column`
+ object, and to redirect compilation if a particular flag or condition
+ is found::
+
+ from sqlalchemy import schema
+ from sqlalchemy.ext.compiler import compiles
+
+ @compiles(schema.CreateColumn)
+ def compile(element, compiler, **kw):
+ column = element.element
+
+ if "special" not in column.info:
+ return compiler.visit_create_column(element, **kw)
+
+ text = "%s SPECIAL DIRECTIVE %s" % (
+ column.name,
+ compiler.type_compiler.process(column.type)
+ )
+ default = compiler.get_column_default_string(column)
+ if default is not None:
+ text += " DEFAULT " + default
+
+ if not column.nullable:
+ text += " NOT NULL"
+
+ if column.constraints:
+ text += " ".join(
+ compiler.process(const)
+ for const in column.constraints)
+ return text
+
+ The above construct can be applied to a :class:`.Table` as follows::
+
+ from sqlalchemy import Table, Metadata, Column, Integer, String
+ from sqlalchemy import schema
+
+ metadata = MetaData()
+
+ table = Table('mytable', MetaData(),
+ Column('x', Integer, info={"special":True}, primary_key=True),
+ Column('y', String(50)),
+ Column('z', String(20), info={"special":True})
+ )
+
+ metadata.create_all(conn)
+
+ Above, the directives we've added to the :attr:`.Column.info` collection
+ will be detected by our custom compilation scheme::
+
+ CREATE TABLE mytable (
+ x SPECIAL DIRECTIVE INTEGER NOT NULL,
+ y VARCHAR(50),
+ z SPECIAL DIRECTIVE VARCHAR(20),
+ PRIMARY KEY (x)
+ )
+
+ .. versionadded:: 0.8 The :class:`.CreateColumn` construct was added
+ to support custom column creation styles.
+
+ """
+ __visit_name__ = 'create_column'
+
+ def __init__(self, element):
+ self.element = element
+
class DropTable(_CreateDropBase):
"""Represent a DROP TABLE statement."""
diff --git a/lib/sqlalchemy/sql/compiler.py b/lib/sqlalchemy/sql/compiler.py
index 3778c7683..8a7f05eb3 100644
--- a/lib/sqlalchemy/sql/compiler.py
+++ b/lib/sqlalchemy/sql/compiler.py
@@ -1728,6 +1728,10 @@ class DDLCompiler(engine.Compiled):
def sql_compiler(self):
return self.dialect.statement_compiler(self.dialect, None)
+ @util.memoized_property
+ def type_compiler(self):
+ return self.dialect.type_compiler
+
@property
def preparer(self):
return self.dialect.identifier_preparer
@@ -1776,21 +1780,16 @@ class DDLCompiler(engine.Compiled):
# if only one primary key, specify it along with the column
first_pk = False
- for column in table.columns:
+ for create_column in create.columns:
+ column = create_column.element
try:
text += separator
separator = ", \n"
- text += "\t" + self.get_column_specification(
- column,
- first_pk=column.primary_key and \
- not first_pk
- )
+ text += "\t" + self.process(create_column,
+ first_pk=column.primary_key
+ and not first_pk)
if column.primary_key:
first_pk = True
- const = " ".join(self.process(constraint) \
- for constraint in column.constraints)
- if const:
- text += " " + const
except exc.CompileError, ce:
# Py3K
#raise exc.CompileError("(in table '%s', column '%s'): %s"
@@ -1815,6 +1814,20 @@ class DDLCompiler(engine.Compiled):
text += "\n)%s\n\n" % self.post_create_table(table)
return text
+ def visit_create_column(self, create, first_pk=False):
+ column = create.element
+
+ text = self.get_column_specification(
+ column,
+ first_pk=first_pk
+ )
+ const = " ".join(self.process(constraint) \
+ for constraint in column.constraints)
+ if const:
+ text += " " + const
+
+ return text
+
def create_table_constraints(self, table):
# On some DB order is significant: visit PK first, then the