Python sqlalchemy.types.to_instance() Examples

The following are 21 code examples of sqlalchemy.types.to_instance(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module sqlalchemy.types , or try the search function .
Example #1
Source File: mysql.py    From jbox with MIT License 6 votes vote down vote up
def __init__(self, name, column_name, schema=None,
                 newname=None,
                 type_=None,
                 nullable=None,
                 default=False,
                 autoincrement=None):
        super(AlterColumn, self).__init__(name, schema=schema)
        self.column_name = column_name
        self.nullable = nullable
        self.newname = newname
        self.default = default
        self.autoincrement = autoincrement
        if type_ is None:
            raise util.CommandError(
                "All MySQL CHANGE/MODIFY COLUMN operations "
                "require the existing type."
            )

        self.type_ = sqltypes.to_instance(type_) 
Example #2
Source File: mysql.py    From android_universal with MIT License 6 votes vote down vote up
def __init__(self, name, column_name, schema=None,
                 newname=None,
                 type_=None,
                 nullable=None,
                 default=False,
                 autoincrement=None):
        super(AlterColumn, self).__init__(name, schema=schema)
        self.column_name = column_name
        self.nullable = nullable
        self.newname = newname
        self.default = default
        self.autoincrement = autoincrement
        if type_ is None:
            raise util.CommandError(
                "All MySQL CHANGE/MODIFY COLUMN operations "
                "require the existing type."
            )

        self.type_ = sqltypes.to_instance(type_) 
Example #3
Source File: base.py    From alembic with MIT License 6 votes vote down vote up
def __init__(
        self,
        name,
        column_name,
        schema=None,
        existing_type=None,
        existing_nullable=None,
        existing_server_default=None,
        existing_comment=None,
    ):
        super(AlterColumn, self).__init__(name, schema=schema)
        self.column_name = column_name
        self.existing_type = (
            sqltypes.to_instance(existing_type)
            if existing_type is not None
            else None
        )
        self.existing_nullable = existing_nullable
        self.existing_server_default = existing_server_default
        self.existing_comment = existing_comment 
Example #4
Source File: test_compiler.py    From sqlalchemy with MIT License 6 votes vote down vote up
def test_varchar_raise(self, type_):
        type_ = sqltypes.to_instance(type_)
        assert_raises_message(
            exc.CompileError,
            "VARCHAR requires a length on dialect mysql",
            type_.compile,
            dialect=mysql.dialect(),
        )

        t1 = Table("sometable", MetaData(), Column("somecolumn", type_))
        assert_raises_message(
            exc.CompileError,
            r"\(in table 'sometable', column 'somecolumn'\)\: "
            r"(?:N)?VARCHAR requires a length on dialect mysql",
            schema.CreateTable(t1).compile,
            dialect=mysql.dialect(),
        ) 
Example #5
Source File: csv2db.py    From cgat-core with MIT License 6 votes vote down vote up
def to_sql_pkey(self, frame, name, if_exists='fail', index=True,
             index_label=None, schema=None,
             dtype=None, **kwargs):
    '''Function to load a table with the reqirement for a primary key.'''
    if dtype is not None:
        from sqlalchemy.types import to_instance, TypeEngine
        for col, my_type in dtype.items():
            if not isinstance(to_instance(my_type), TypeEngine):
                raise ValueError('The type of %s is not a SQLAlchemy '
                                 'type ' % col)

    table = pandas.io.sql.SQLTable(name, self,
                               frame=frame,
                               index=index,
                               if_exists=if_exists,
                               index_label=index_label,
                               schema=schema,
                               dtype=dtype, **kwargs)
    table.create()
    table.insert() 
Example #6
Source File: test_firebird.py    From sqlalchemy with MIT License 6 votes vote down vote up
def test_varchar_raise(self):
        for type_ in (
            String,
            VARCHAR,
            String(),
            VARCHAR(),
            Unicode,
            Unicode(),
        ):
            type_ = sqltypes.to_instance(type_)
            assert_raises_message(
                exc.CompileError,
                "VARCHAR requires a length on dialect firebird",
                type_.compile,
                dialect=firebird.dialect(),
            )

            t1 = Table("sometable", MetaData(), Column("somecolumn", type_))
            assert_raises_message(
                exc.CompileError,
                r"\(in table 'sometable', column 'somecolumn'\)\: "
                r"(?:N)?VARCHAR requires a length on dialect firebird",
                schema.CreateTable(t1).compile,
                dialect=firebird.dialect(),
            ) 
Example #7
Source File: ndb.py    From oslo.db with Apache License 2.0 6 votes vote down vote up
def _compile_ndb_string(element, compiler, **kw):
    """Process ndb specific overrides for String.

    Function will intercept mysql_ndb_length and mysql_ndb_type
    arguments to adjust columns automatically.

    mysql_ndb_length argument will adjust the String length
    to the requested value.

    mysql_ndb_type will change the column type to the requested
    data type.
    """
    if not ndb_status(compiler):
        return compiler.visit_string(element, **kw)

    if element.mysql_ndb_length:
        effective_type = element.adapt(
            _String, length=element.mysql_ndb_length)
        return compiler.visit_string(effective_type, **kw)
    elif element.mysql_ndb_type:
        effective_type = to_instance(element.mysql_ndb_type)
        return compiler.process(effective_type, **kw)
    else:
        return compiler.visit_string(element, **kw) 
Example #8
Source File: base.py    From android_universal with MIT License 5 votes vote down vote up
def __init__(self, name, column_name, type_, **kw):
        super(ColumnType, self).__init__(name, column_name,
                                         **kw)
        self.type_ = sqltypes.to_instance(type_) 
Example #9
Source File: base.py    From android_universal with MIT License 5 votes vote down vote up
def __init__(self, name, column_name, schema=None,
                 existing_type=None,
                 existing_nullable=None,
                 existing_server_default=None):
        super(AlterColumn, self).__init__(name, schema=schema)
        self.column_name = column_name
        self.existing_type = sqltypes.to_instance(existing_type) \
            if existing_type is not None else None
        self.existing_nullable = existing_nullable
        self.existing_server_default = existing_server_default 
Example #10
Source File: postgresql.py    From android_universal with MIT License 5 votes vote down vote up
def __init__(self, name, column_name, type_, **kw):
        using = kw.pop('using', None)
        super(PostgresqlColumnType, self).__init__(name, column_name, **kw)
        self.type_ = sqltypes.to_instance(type_)
        self.using = using 
Example #11
Source File: test_types.py    From sqlalchemy with MIT License 5 votes vote down vote up
def test_typedecorator_impl(self):
        for impl_, exp, kw in [
            (Float, "FLOAT", {}),
            (Float, "FLOAT(2)", {"precision": 2}),
            (Float(2), "FLOAT(2)", {"precision": 4}),
            (Numeric(19, 2), "NUMERIC(19, 2)", {}),
        ]:
            for dialect_ in (
                dialects.postgresql,
                dialects.mssql,
                dialects.mysql,
            ):
                dialect_ = dialect_.dialect()

                raw_impl = types.to_instance(impl_, **kw)

                class MyType(types.TypeDecorator):
                    impl = impl_

                dec_type = MyType(**kw)

                eq_(dec_type.impl.__class__, raw_impl.__class__)

                raw_dialect_impl = raw_impl.dialect_impl(dialect_)
                dec_dialect_impl = dec_type.dialect_impl(dialect_)
                eq_(dec_dialect_impl.__class__, MyType)
                eq_(
                    raw_dialect_impl.__class__, dec_dialect_impl.impl.__class__
                )

                self.assert_compile(MyType(**kw), exp, dialect=dialect_) 
Example #12
Source File: test_types.py    From sqlalchemy with MIT License 5 votes vote down vote up
def test_uppercase_rendering(self, dialect, type_, expected):
        """Test that uppercase types from types.py always render as their
        type.

        As of SQLA 0.6, using an uppercase type means you want specifically
        that type. If the database in use doesn't support that DDL, it (the DB
        backend) should raise an error - it means you should be using a
        lowercased (genericized) type.

        """

        if isinstance(expected, str):
            expected = (expected,)

        try:
            compiled = type_.compile(dialect=dialect)
        except NotImplementedError:
            return

        assert compiled in expected, "%r matches none of %r for dialect %s" % (
            compiled,
            expected,
            dialect.name,
        )

        assert (
            str(types.to_instance(type_)) in expected
        ), "default str() of type %r not expected, %r" % (type_, expected) 
Example #13
Source File: elements.py    From stdm with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, base, field, type_):
        self.name = field
        self.type = to_instance(type_)

        super(CompositeElement, self).__init__(base) 
Example #14
Source File: base.py    From alembic with MIT License 5 votes vote down vote up
def __init__(self, name, column_name, type_, **kw):
        super(ColumnType, self).__init__(name, column_name, **kw)
        self.type_ = sqltypes.to_instance(type_) 
Example #15
Source File: postgresql.py    From alembic with MIT License 5 votes vote down vote up
def __init__(self, name, column_name, type_, **kw):
        using = kw.pop("using", None)
        super(PostgresqlColumnType, self).__init__(name, column_name, **kw)
        self.type_ = sqltypes.to_instance(type_)
        self.using = using 
Example #16
Source File: mysql.py    From alembic with MIT License 5 votes vote down vote up
def __init__(
        self,
        name,
        column_name,
        schema=None,
        newname=None,
        type_=None,
        nullable=None,
        default=False,
        autoincrement=None,
        comment=False,
    ):
        super(AlterColumn, self).__init__(name, schema=schema)
        self.column_name = column_name
        self.nullable = nullable
        self.newname = newname
        self.default = default
        self.autoincrement = autoincrement
        self.comment = comment
        if type_ is None:
            raise util.CommandError(
                "All MySQL CHANGE/MODIFY COLUMN operations "
                "require the existing type."
            )

        self.type_ = sqltypes.to_instance(type_) 
Example #17
Source File: base.py    From jbox with MIT License 5 votes vote down vote up
def __init__(self, name, column_name, type_, **kw):
        super(ColumnType, self).__init__(name, column_name,
                                         **kw)
        self.type_ = sqltypes.to_instance(type_) 
Example #18
Source File: base.py    From jbox with MIT License 5 votes vote down vote up
def __init__(self, name, column_name, schema=None,
                 existing_type=None,
                 existing_nullable=None,
                 existing_server_default=None):
        super(AlterColumn, self).__init__(name, schema=schema)
        self.column_name = column_name
        self.existing_type = sqltypes.to_instance(existing_type) \
            if existing_type is not None else None
        self.existing_nullable = existing_nullable
        self.existing_server_default = existing_server_default 
Example #19
Source File: batch.py    From android_universal with MIT License 4 votes vote down vote up
def alter_column(self, table_name, column_name,
                     nullable=None,
                     server_default=False,
                     name=None,
                     type_=None,
                     autoincrement=None,
                     **kw
                     ):
        existing = self.columns[column_name]
        existing_transfer = self.column_transfers[column_name]
        if name is not None and name != column_name:
            # note that we don't change '.key' - we keep referring
            # to the renamed column by its old key in _create().  neat!
            existing.name = name
            existing_transfer["name"] = name

        if type_ is not None:
            type_ = sqltypes.to_instance(type_)
            # old type is being discarded so turn off eventing
            # rules. Alternatively we can
            # erase the events set up by this type, but this is simpler.
            # we also ignore the drop_constraint that will come here from
            # Operations.implementation_for(alter_column)
            if isinstance(existing.type, SchemaEventTarget):
                existing.type._create_events = \
                    existing.type.create_constraint = False

            if existing.type._type_affinity is not type_._type_affinity:
                existing_transfer["expr"] = cast(
                    existing_transfer["expr"], type_)

            existing.type = type_

            # we *dont* however set events for the new type, because
            # alter_column is invoked from
            # Operations.implementation_for(alter_column) which already
            # will emit an add_constraint()

        if nullable is not None:
            existing.nullable = nullable
        if server_default is not False:
            if server_default is None:
                existing.server_default = None
            else:
                sql_schema.DefaultClause(server_default)._set_parent(existing)
        if autoincrement is not None:
            existing.autoincrement = bool(autoincrement) 
Example #20
Source File: batch.py    From alembic with MIT License 4 votes vote down vote up
def alter_column(
        self,
        table_name,
        column_name,
        nullable=None,
        server_default=False,
        name=None,
        type_=None,
        autoincrement=None,
        **kw
    ):
        existing = self.columns[column_name]
        existing_transfer = self.column_transfers[column_name]
        if name is not None and name != column_name:
            # note that we don't change '.key' - we keep referring
            # to the renamed column by its old key in _create().  neat!
            existing.name = name
            existing_transfer["name"] = name

        if type_ is not None:
            type_ = sqltypes.to_instance(type_)
            # old type is being discarded so turn off eventing
            # rules. Alternatively we can
            # erase the events set up by this type, but this is simpler.
            # we also ignore the drop_constraint that will come here from
            # Operations.implementation_for(alter_column)
            if isinstance(existing.type, SchemaEventTarget):
                existing.type._create_events = (
                    existing.type.create_constraint
                ) = False

            self.impl.cast_for_batch_migrate(
                existing, existing_transfer, type_
            )

            existing.type = type_

            # we *dont* however set events for the new type, because
            # alter_column is invoked from
            # Operations.implementation_for(alter_column) which already
            # will emit an add_constraint()

        if nullable is not None:
            existing.nullable = nullable
        if server_default is not False:
            if server_default is None:
                existing.server_default = None
            else:
                sql_schema.DefaultClause(server_default)._set_parent(existing)
        if autoincrement is not None:
            existing.autoincrement = bool(autoincrement) 
Example #21
Source File: batch.py    From jbox with MIT License 4 votes vote down vote up
def alter_column(self, table_name, column_name,
                     nullable=None,
                     server_default=False,
                     name=None,
                     type_=None,
                     autoincrement=None,
                     **kw
                     ):
        existing = self.columns[column_name]
        existing_transfer = self.column_transfers[column_name]
        if name is not None and name != column_name:
            # note that we don't change '.key' - we keep referring
            # to the renamed column by its old key in _create().  neat!
            existing.name = name
            existing_transfer["name"] = name

        if type_ is not None:
            type_ = sqltypes.to_instance(type_)
            # old type is being discarded so turn off eventing
            # rules. Alternatively we can
            # erase the events set up by this type, but this is simpler.
            # we also ignore the drop_constraint that will come here from
            # Operations.implementation_for(alter_column)
            if isinstance(existing.type, SchemaEventTarget):
                existing.type._create_events = \
                    existing.type.create_constraint = False

            existing.type = type_

            # we *dont* however set events for the new type, because
            # alter_column is invoked from
            # Operations.implementation_for(alter_column) which already
            # will emit an add_constraint()

            existing_transfer["expr"] = cast(existing_transfer["expr"], type_)
        if nullable is not None:
            existing.nullable = nullable
        if server_default is not False:
            if server_default is None:
                existing.server_default = None
            else:
                sql_schema.DefaultClause(server_default)._set_parent(existing)
        if autoincrement is not None:
            existing.autoincrement = bool(autoincrement)