Python sqlalchemy.types.TypeEngine() Examples

The following are 20 code examples of sqlalchemy.types.TypeEngine(). 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: test_bulk_insert.py    From alembic with MIT License 6 votes vote down vote up
def test_bulk_insert_inline_literal_as_sql(self):
        context = op_fixture("postgresql", True)

        class MyType(TypeEngine):
            pass

        t1 = table("t", column("id", Integer), column("data", MyType()))

        op.bulk_insert(
            t1,
            [
                {"id": 1, "data": op.inline_literal("d1")},
                {"id": 2, "data": op.inline_literal("d2")},
            ],
        )
        context.assert_(
            "INSERT INTO t (id, data) VALUES (1, 'd1')",
            "INSERT INTO t (id, data) VALUES (2, 'd2')",
        ) 
Example #2
Source File: test_bulk_insert.py    From alembic with MIT License 6 votes vote down vote up
def test_bulk_insert_inline_literal(self):
        class MyType(TypeEngine):
            pass

        t1 = table("foo", column("id", Integer), column("data", MyType()))

        self.op.bulk_insert(
            t1,
            [
                {"id": 1, "data": self.op.inline_literal("d1")},
                {"id": 2, "data": self.op.inline_literal("d2")},
            ],
            multiinsert=False,
        )

        eq_(
            self.conn.execute(text("select id, data from foo")).fetchall(),
            [(1, "d1"), (2, "d2")],
        ) 
Example #3
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 #4
Source File: types.py    From android_universal with MIT License 6 votes vote down vote up
def guess(cls, sample):
        """Given a single sample, guess the column type for the field.

        If the sample is an instance of an SQLAlchemy type, the type will be
        used instead.
        """
        if isinstance(sample, TypeEngine):
            return sample
        if isinstance(sample, bool):
            return cls.boolean
        elif isinstance(sample, int):
            return cls.integer
        elif isinstance(sample, float):
            return cls.float
        elif isinstance(sample, datetime):
            return cls.datetime
        elif isinstance(sample, date):
            return cls.date
        return cls.text 
Example #5
Source File: base.py    From incubator-superset with Apache License 2.0 6 votes vote down vote up
def column_datatype_to_string(
        cls, sqla_column_type: TypeEngine, dialect: Dialect
    ) -> str:
        """
        Convert sqlalchemy column type to string representation.
        By default removes collation and character encoding info to avoid unnecessarily
        long datatypes.

        :param sqla_column_type: SqlAlchemy column type
        :param dialect: Sqlalchemy dialect
        :return: Compiled column type
        """
        sqla_column_type = sqla_column_type.copy()
        if hasattr(sqla_column_type, "collation"):
            sqla_column_type.collation = None
        if hasattr(sqla_column_type, "charset"):
            sqla_column_type.charset = None
        return sqla_column_type.compile(dialect=dialect).upper() 
Example #6
Source File: test_types.py    From sqlalchemy with MIT License 6 votes vote down vote up
def _all_types(omit_special_types=False):
    seen = set()
    for typ in _types_for_mod(types):
        if omit_special_types and typ in (
            types.TypeDecorator,
            types.TypeEngine,
            types.Variant,
        ):
            continue

        if typ in seen:
            continue
        seen.add(typ)
        yield typ
    for dialect in _all_dialect_modules():
        for typ in _types_for_mod(dialect):
            if typ in seen:
                continue
            seen.add(typ)
            yield typ 
Example #7
Source File: test_compiler.py    From sqlalchemy with MIT License 6 votes vote down vote up
def test_types(self):
        class MyType(TypeEngine):
            pass

        @compiles(MyType, "sqlite")
        def visit_sqlite_type(type_, compiler, **kw):
            return "SQLITE_FOO"

        @compiles(MyType, "postgresql")
        def visit_pg_type(type_, compiler, **kw):
            return "POSTGRES_FOO"

        from sqlalchemy.dialects.sqlite import base as sqlite
        from sqlalchemy.dialects.postgresql import base as postgresql

        self.assert_compile(MyType(), "SQLITE_FOO", dialect=sqlite.dialect())

        self.assert_compile(
            MyType(), "POSTGRES_FOO", dialect=postgresql.dialect()
        ) 
Example #8
Source File: test_compiler.py    From sqlalchemy with MIT License 5 votes vote down vote up
def _illegal_type_fixture(self):
        class MyType(types.TypeEngine):
            pass

        @compiles(MyType)
        def compile_(element, compiler, **kw):
            raise exc.CompileError("Couldn't compile type")

        return MyType 
Example #9
Source File: render.py    From android_universal with MIT License 5 votes vote down vote up
def _render_check_constraint(constraint, autogen_context):
    rendered = _user_defined_render("check", constraint, autogen_context)
    if rendered is not False:
        return rendered

    # detect the constraint being part of
    # a parent type which is probably in the Table already.
    # ideally SQLAlchemy would give us more of a first class
    # way to detect this.
    if constraint._create_rule and \
        hasattr(constraint._create_rule, 'target') and \
        isinstance(constraint._create_rule.target,
                   sqltypes.TypeEngine):
        return None
    opts = []
    if constraint.name:
        opts.append(
            (
                "name",
                repr(
                    _render_gen_name(
                        autogen_context, constraint.name))
            )
        )
    return "%(prefix)sCheckConstraint(%(sqltext)s%(opts)s)" % {
        "prefix": _sqlalchemy_autogenerate_prefix(autogen_context),
        "opts": ", " + (", ".join("%s=%s" % (k, v)
                                  for k, v in opts)) if opts else "",
        "sqltext": _render_potential_expr(
            constraint.sqltext, autogen_context, wrap_in_text=False)
    } 
Example #10
Source File: base.py    From incubator-superset with Apache License 2.0 5 votes vote down vote up
def get_sqla_column_type(cls, type_: str) -> Optional[TypeEngine]:
        """
        Return a sqlalchemy native column type that corresponds to the column type
        defined in the data source (return None to use default type inferred by
        SQLAlchemy). Needs to be overridden if column requires special handling
        (see MSSQL for example of NCHAR/NVARCHAR handling).

        :param type_: Column type returned by inspector
        :return: SqlAlchemy column type
        """
        return None 
Example #11
Source File: mssql.py    From incubator-superset with Apache License 2.0 5 votes vote down vote up
def get_sqla_column_type(cls, type_: str) -> Optional[TypeEngine]:
        for sqla_type, regex in cls.column_types:
            if regex.match(type_):
                return sqla_type
        return None 
Example #12
Source File: test_compiler.py    From sqlalchemy with MIT License 5 votes vote down vote up
def test_no_default_has_no_visit(self):
        class MyThingy(TypeEngine):
            pass

        @compiles(MyThingy, "postgresql")
        def visit_thingy(thingy, compiler, **kw):
            return "mythingy"

        assert_raises_message(
            exc.CompileError,
            "<class 'test.ext.test_compiler..*MyThingy'> "
            "construct has no default compilation handler.",
            str,
            MyThingy(),
        ) 
Example #13
Source File: test_metadata.py    From sqlalchemy with MIT License 5 votes vote down vote up
def test_before_parent_attach_typedec_enclosing_schematype(self):
        # additional test for [ticket:2919] as part of test for
        # [ticket:3832]

        class MySchemaType(sqltypes.TypeEngine, sqltypes.SchemaType):
            pass

        target_typ = MySchemaType()

        class MyType(TypeDecorator):
            impl = target_typ

        typ = MyType()
        self._test_before_parent_attach(typ, target_typ, double=True) 
Example #14
Source File: test_metadata.py    From sqlalchemy with MIT License 5 votes vote down vote up
def _on_metadata_create(self, target, bind, **kw):
            super(SchemaTypeTest.TrackEvents, self)._on_metadata_create(
                target, bind, **kw
            )
            self.evt_targets += (target,)

    # TODO: Enum and Boolean put TypeEngine first.  Changing that here
    # causes collection-mutate-while-iterated errors in the event system
    # since the hooks here call upon the adapted type.  Need to figure out
    # why Enum and Boolean don't have this problem. 
Example #15
Source File: render.py    From jbox with MIT License 5 votes vote down vote up
def _render_check_constraint(constraint, autogen_context):
    rendered = _user_defined_render("check", constraint, autogen_context)
    if rendered is not False:
        return rendered

    # detect the constraint being part of
    # a parent type which is probably in the Table already.
    # ideally SQLAlchemy would give us more of a first class
    # way to detect this.
    if constraint._create_rule and \
        hasattr(constraint._create_rule, 'target') and \
        isinstance(constraint._create_rule.target,
                   sqltypes.TypeEngine):
        return None
    opts = []
    if constraint.name:
        opts.append(
            (
                "name",
                repr(
                    _render_gen_name(
                        autogen_context, constraint.name))
            )
        )
    return "%(prefix)sCheckConstraint(%(sqltext)s%(opts)s)" % {
        "prefix": _sqlalchemy_autogenerate_prefix(autogen_context),
        "opts": ", " + (", ".join("%s=%s" % (k, v)
                                  for k, v in opts)) if opts else "",
        "sqltext": _render_potential_expr(
            constraint.sqltext, autogen_context, wrap_in_text=False)
    } 
Example #16
Source File: test_types.py    From sqlalchemy with MIT License 5 votes vote down vote up
def test_user_defined_typedec_impl_bind(self):
        class TypeOne(types.TypeEngine):
            def bind_processor(self, dialect):
                def go(value):
                    return value + " ONE"

                return go

        class TypeTwo(types.TypeEngine):
            def bind_processor(self, dialect):
                def go(value):
                    return value + " TWO"

                return go

        class MyType(types.TypeDecorator):
            impl = TypeOne

            def load_dialect_impl(self, dialect):
                if dialect.name == "sqlite":
                    return TypeOne()
                else:
                    return TypeTwo()

            def process_bind_param(self, value, dialect):
                return "MYTYPE " + value

        sl = dialects.sqlite.dialect()
        pg = dialects.postgresql.dialect()
        t = MyType()
        eq_(t._cached_bind_processor(sl)("foo"), "MYTYPE foo ONE")
        eq_(t._cached_bind_processor(pg)("foo"), "MYTYPE foo TWO") 
Example #17
Source File: test_types.py    From sqlalchemy with MIT License 5 votes vote down vote up
def test_python_type(self):
        eq_(types.Integer().python_type, int)
        eq_(types.Numeric().python_type, decimal.Decimal)
        eq_(types.Numeric(asdecimal=False).python_type, float)
        eq_(types.LargeBinary().python_type, util.binary_type)
        eq_(types.Float().python_type, float)
        eq_(types.Interval().python_type, datetime.timedelta)
        eq_(types.Date().python_type, datetime.date)
        eq_(types.DateTime().python_type, datetime.datetime)
        eq_(types.String().python_type, str)
        eq_(types.Unicode().python_type, util.text_type)
        eq_(types.Enum("one", "two", "three").python_type, str)

        assert_raises(
            NotImplementedError, lambda: types.TypeEngine().python_type
        ) 
Example #18
Source File: test_types.py    From sqlalchemy with MIT License 5 votes vote down vote up
def _types_for_mod(mod):
    for key in dir(mod):
        typ = getattr(mod, key)
        if not isinstance(typ, type) or not issubclass(typ, types.TypeEngine):
            continue
        yield typ 
Example #19
Source File: test_sqlite.py    From sqlalchemy with MIT License 5 votes vote down vote up
def _fixture_as_string(self, fixture):
        for from_, to_ in fixture:
            if isinstance(from_, sqltypes.TypeEngine):
                from_ = str(from_.compile())
            elif isinstance(from_, type):
                from_ = str(from_().compile())
            yield from_, to_ 
Example #20
Source File: render.py    From alembic with MIT License 5 votes vote down vote up
def _render_check_constraint(constraint, autogen_context):
    rendered = _user_defined_render("check", constraint, autogen_context)
    if rendered is not False:
        return rendered

    # detect the constraint being part of
    # a parent type which is probably in the Table already.
    # ideally SQLAlchemy would give us more of a first class
    # way to detect this.
    if (
        constraint._create_rule
        and hasattr(constraint._create_rule, "target")
        and isinstance(constraint._create_rule.target, sqltypes.TypeEngine)
    ):
        return None
    opts = []
    if constraint.name:
        opts.append(
            ("name", repr(_render_gen_name(autogen_context, constraint.name)))
        )
    return "%(prefix)sCheckConstraint(%(sqltext)s%(opts)s)" % {
        "prefix": _sqlalchemy_autogenerate_prefix(autogen_context),
        "opts": ", " + (", ".join("%s=%s" % (k, v) for k, v in opts))
        if opts
        else "",
        "sqltext": _render_potential_expr(
            constraint.sqltext, autogen_context, wrap_in_text=False
        ),
    }