Represent a :class:`_schema.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.ex
| 933 | |
| 934 | |
| 935 | class CreateColumn(BaseDDLElement): |
| 936 | """Represent a :class:`_schema.Column` |
| 937 | as rendered in a CREATE TABLE statement, |
| 938 | via the :class:`.CreateTable` construct. |
| 939 | |
| 940 | This is provided to support custom column DDL within the generation |
| 941 | of CREATE TABLE statements, by using the |
| 942 | compiler extension documented in :ref:`sqlalchemy.ext.compiler_toplevel` |
| 943 | to extend :class:`.CreateColumn`. |
| 944 | |
| 945 | Typical integration is to examine the incoming :class:`_schema.Column` |
| 946 | object, and to redirect compilation if a particular flag or condition |
| 947 | is found:: |
| 948 | |
| 949 | from sqlalchemy import schema |
| 950 | from sqlalchemy.ext.compiler import compiles |
| 951 | |
| 952 | |
| 953 | @compiles(schema.CreateColumn) |
| 954 | def compile(element, compiler, **kw): |
| 955 | column = element.element |
| 956 | |
| 957 | if "special" not in column.info: |
| 958 | return compiler.visit_create_column(element, **kw) |
| 959 | |
| 960 | text = "%s SPECIAL DIRECTIVE %s" % ( |
| 961 | column.name, |
| 962 | compiler.type_compiler.process(column.type), |
| 963 | ) |
| 964 | default = compiler.get_column_default_string(column) |
| 965 | if default is not None: |
| 966 | text += " DEFAULT " + default |
| 967 | |
| 968 | if not column.nullable: |
| 969 | text += " NOT NULL" |
| 970 | |
| 971 | if column.constraints: |
| 972 | text += " ".join( |
| 973 | compiler.process(const) for const in column.constraints |
| 974 | ) |
| 975 | return text |
| 976 | |
| 977 | The above construct can be applied to a :class:`_schema.Table` |
| 978 | as follows:: |
| 979 | |
| 980 | from sqlalchemy import Table, Metadata, Column, Integer, String |
| 981 | from sqlalchemy import schema |
| 982 | |
| 983 | metadata = MetaData() |
| 984 | |
| 985 | table = Table( |
| 986 | "mytable", |
| 987 | MetaData(), |
| 988 | Column("x", Integer, info={"special": True}, primary_key=True), |
| 989 | Column("y", String(50)), |
| 990 | Column("z", String(20), info={"special": True}), |
| 991 | ) |
| 992 |