Python sqlalchemy.types.VARCHAR Examples

The following are 30 code examples of sqlalchemy.types.VARCHAR(). 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_sqlite.py    From sqlalchemy with MIT License 6 votes vote down vote up
def test_on_conflict_clause_primary_key_constraint(self):

        meta = MetaData()
        t = Table(
            "n",
            meta,
            Column("id", Integer),
            Column("x", String(30)),
            PrimaryKeyConstraint("id", "x", sqlite_on_conflict="FAIL"),
        )

        self.assert_compile(
            CreateTable(t),
            "CREATE TABLE n ("
            "id INTEGER NOT NULL, "
            "x VARCHAR(30) NOT NULL, "
            "PRIMARY KEY (id, x) ON CONFLICT FAIL)",
            dialect=sqlite.dialect(),
        ) 
Example #2
Source File: __init__.py    From parade with MIT License 6 votes vote down vote up
def str_to_sqltype(expr):
    import re
    import sqlalchemy.types as sqltypes
    norm_expr = expr.lower()
    if norm_expr.startswith('integer'):
        match_result = re.match(r'integer\((\d+)\)', norm_expr)
        if match_result is not None:
            return sqltypes.BIGINT() if int(match_result.group(1)) > 11 else sqltypes.INTEGER()
        return sqltypes.BIGINT()
    if norm_expr == 'decimal':
        return sqltypes.DECIMAL()
    if norm_expr == 'date':
        return sqltypes.DATETIME()
    if norm_expr == 'bool' or norm_expr == 'boolean':
        return sqltypes.BOOLEAN()
    if norm_expr.startswith('string'):
        match_result = re.match(r'string\((\d+)\)', norm_expr)
        if match_result is not None:
            maxlen = int(match_result.group(1))
            return sqltypes.VARCHAR(maxlen) if maxlen < 65536 else sqltypes.TEXT
        return sqltypes.TEXT()
    raise RuntimeError("Unsupported data type [" + expr + "]") 
Example #3
Source File: test_types.py    From sqlalchemy with MIT License 6 votes vote down vote up
def test_reflect_unicode_no_nvarchar(self):
        metadata = self.metadata
        Table("tnv", metadata, Column("data", sqltypes.Unicode(255)))
        metadata.create_all()
        m2 = MetaData(testing.db)
        t2 = Table("tnv", m2, autoload=True)
        assert isinstance(t2.c.data.type, sqltypes.VARCHAR)

        if testing.against("oracle+cx_oracle"):
            assert isinstance(
                t2.c.data.type.dialect_impl(testing.db.dialect),
                cx_oracle._OracleString,
            )

        data = u("m’a réveillé.")
        t2.insert().execute(data=data)
        res = t2.select().execute().first()["data"]
        eq_(res, data)
        assert isinstance(res, util.text_type) 
Example #4
Source File: test_types.py    From sqlalchemy with MIT License 6 votes vote down vote up
def test_no_clobs_for_string_params(self):
        """test that simple string params get a DBAPI type of
        VARCHAR, not CLOB. This is to prevent setinputsizes
        from setting up cx_oracle.CLOBs on
        string-based bind params [ticket:793]."""

        class FakeDBAPI(object):
            def __getattr__(self, attr):
                return attr

        dialect = oracle.OracleDialect()
        dbapi = FakeDBAPI()

        b = bindparam("foo", "hello world!")
        eq_(b.type.dialect_impl(dialect).get_dbapi_type(dbapi), "STRING")

        b = bindparam("foo", "hello world!")
        eq_(b.type.dialect_impl(dialect).get_dbapi_type(dbapi), "STRING") 
Example #5
Source File: test_column_loading.py    From sqlalchemy-redshift with MIT License 6 votes vote down vote up
def test_varchar_as_nulltype(self):
        """
        Varchar columns with no length should be considered NullType columns
        """
        dialect = RedshiftDialect()
        column_info = dialect._get_column_info(
            'Null Column',
            'character varying', None, False, {}, {}, 'default', 'test column'
        )
        assert isinstance(column_info['type'], NullType)
        column_info_1 = dialect._get_column_info(
            'character column',
            'character varying(30)', None, False, {}, {}, 'default',
            comment='test column'
        )
        assert isinstance(column_info_1['type'], VARCHAR) 
Example #6
Source File: test_codegen.py    From safrs with GNU General Public License v3.0 6 votes vote down vote up
def test_metadata_column(metadata):
    Table("simple", metadata, Column("id", INTEGER, primary_key=True), Column("metadata", VARCHAR))

    assert (
        generate_code(metadata)
        == """\
# coding: utf-8
from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()
metadata = Base.metadata


class Simple(Base):
    __tablename__ = 'simple'

    id = Column(Integer, primary_key=True)
    metadata_ = Column('metadata', String)
"""
    ) 
Example #7
Source File: test_codegen.py    From safrs with GNU General Public License v3.0 6 votes vote down vote up
def test_foreign_key_options(metadata):
    Table(
        "simple_items",
        metadata,
        Column(
            "name", VARCHAR, ForeignKey("simple_items.name", ondelete="CASCADE", onupdate="CASCADE", deferrable=True, initially="DEFERRED")
        ),
    )

    assert (
        generate_code(metadata)
        == """\
# coding: utf-8
from sqlalchemy import Column, ForeignKey, MetaData, String, Table

metadata = MetaData()


t_simple_items = Table(
    'simple_items', metadata,
    Column('name', String, ForeignKey('simple_items.name', ondelete='CASCADE', \
onupdate='CASCADE', deferrable=True, initially='DEFERRED'))
)
"""
    ) 
Example #8
Source File: test_sqlite.py    From sqlalchemy with MIT License 6 votes vote down vote up
def test_on_conflict_clause_primary_key_constraint_from_column(self):

        meta = MetaData()
        t = Table(
            "n",
            meta,
            Column(
                "x",
                String(30),
                sqlite_on_conflict_primary_key="FAIL",
                primary_key=True,
            ),
        )

        self.assert_compile(
            CreateTable(t),
            "CREATE TABLE n (x VARCHAR(30) NOT NULL, "
            "PRIMARY KEY (x) ON CONFLICT FAIL)",
            dialect=sqlite.dialect(),
        ) 
Example #9
Source File: test_codegen.py    From safrs with GNU General Public License v3.0 6 votes vote down vote up
def test_indexes_table(metadata):
    simple_items = Table("simple_items", metadata, Column("id", INTEGER), Column("number", INTEGER), Column("text", VARCHAR))
    simple_items.indexes.add(Index("idx_number", simple_items.c.number))
    simple_items.indexes.add(Index("idx_text_number", simple_items.c.text, simple_items.c.number, unique=True))
    simple_items.indexes.add(Index("idx_text", simple_items.c.text, unique=True))

    assert (
        generate_code(metadata)
        == """\
# coding: utf-8
from sqlalchemy import Column, Index, Integer, MetaData, String, Table

metadata = MetaData()


t_simple_items = Table(
    'simple_items', metadata,
    Column('id', Integer),
    Column('number', Integer, index=True),
    Column('text', String, unique=True),
    Index('idx_text_number', 'text', 'number', unique=True)
)
"""
    ) 
Example #10
Source File: test_codegen.py    From safrs with GNU General Public License v3.0 6 votes vote down vote up
def test_mysql_column_types(metadata):
    Table("simple_items", metadata, Column("id", mysql.INTEGER), Column("name", mysql.VARCHAR(255)))

    assert (
        generate_code(metadata)
        == """\
# coding: utf-8
from sqlalchemy import Column, Integer, MetaData, String, Table

metadata = MetaData()


t_simple_items = Table(
    'simple_items', metadata,
    Column('id', Integer),
    Column('name', String(255))
)
"""
    ) 
Example #11
Source File: test_codegen.py    From safrs with GNU General Public License v3.0 6 votes vote down vote up
def test_enum_detection(metadata):
    Table("simple_items", metadata, Column("enum", VARCHAR(255)), CheckConstraint(r"simple_items.enum IN ('A', '\'B', 'C')"))

    assert (
        generate_code(metadata)
        == """\
# coding: utf-8
from sqlalchemy import Column, Enum, MetaData, Table

metadata = MetaData()


t_simple_items = Table(
    'simple_items', metadata,
    Column('enum', Enum('A', "\\\\'B", 'C'))
)
"""
    ) 
Example #12
Source File: test_sqlite.py    From sqlalchemy with MIT License 6 votes vote down vote up
def test_on_conflict_clause_unique_constraint(self):

        meta = MetaData()
        t = Table(
            "n",
            meta,
            Column("id", Integer),
            Column("x", String(30)),
            UniqueConstraint("id", "x", sqlite_on_conflict="FAIL"),
        )

        self.assert_compile(
            CreateTable(t),
            "CREATE TABLE n (id INTEGER, x VARCHAR(30), "
            "UNIQUE (id, x) ON CONFLICT FAIL)",
            dialect=sqlite.dialect(),
        ) 
Example #13
Source File: test_sqlite.py    From sqlalchemy with MIT License 6 votes vote down vote up
def test_default_reflection_3(self):
        db = testing.db
        table = """CREATE TABLE r_defaults (
            data VARCHAR(40) DEFAULT 'my_default',
            val INTEGER NOT NULL DEFAULT 0
            )"""
        try:
            exec_sql(db, table)
            m1 = MetaData(db)
            t1 = Table("r_defaults", m1, autoload=True)
            exec_sql(db, "DROP TABLE r_defaults")
            t1.create()
            m2 = MetaData(db)
            t2 = Table("r_defaults", m2, autoload=True)
            self.assert_compile(
                CreateTable(t2),
                "CREATE TABLE r_defaults (data VARCHAR(40) "
                "DEFAULT 'my_default', val INTEGER DEFAULT 0 "
                "NOT NULL)",
            )
        finally:
            exec_sql(db, "DROP TABLE r_defaults") 
Example #14
Source File: test_sqlite.py    From sqlalchemy with MIT License 6 votes vote down vote up
def test_default_reflection_2(self):

        db = testing.db
        m = MetaData(db)
        expected = ["'my_default'", "0"]
        table = """CREATE TABLE r_defaults (
            data VARCHAR(40) DEFAULT 'my_default',
            val INTEGER NOT NULL DEFAULT 0
            )"""
        try:
            exec_sql(db, table)
            rt = Table("r_defaults", m, autoload=True)
            for i, reflected in enumerate(rt.c):
                eq_(str(reflected.server_default.arg), expected[i])
        finally:
            exec_sql(db, "DROP TABLE r_defaults") 
Example #15
Source File: test_mutable.py    From sqlalchemy with MIT License 5 votes vote down vote up
def define_tables(cls, metadata):
        import json

        class JSONEncodedDict(TypeDecorator):
            impl = VARCHAR(50)

            def process_bind_param(self, value, dialect):
                if value is not None:
                    value = json.dumps(value)

                return value

            def process_result_value(self, value, dialect):
                if value is not None:
                    value = json.loads(value)
                return value

        CustomMutableDict = cls._type_fixture()
        CustomMutableDict.associate_with(JSONEncodedDict)

        Table(
            "foo",
            metadata,
            Column(
                "id", Integer, primary_key=True, test_needs_autoincrement=True
            ),
            Column("data", JSONEncodedDict),
            Column("unrelated_data", String(50)),
        ) 
Example #16
Source File: test_sqlite.py    From sqlalchemy with MIT License 5 votes vote down vote up
def test_on_conflict_clause_unique_constraint_from_column(self):
        meta = MetaData()
        t = Table(
            "n",
            meta,
            Column(
                "x", String(30), unique=True, sqlite_on_conflict_unique="FAIL"
            ),
        )

        self.assert_compile(
            CreateTable(t),
            "CREATE TABLE n (x VARCHAR(30), " "UNIQUE (x) ON CONFLICT FAIL)",
            dialect=sqlite.dialect(),
        ) 
Example #17
Source File: test_types.py    From sqlalchemy with MIT License 5 votes vote down vote up
def test_char_length(self):
        self.assert_compile(VARCHAR(50), "VARCHAR(50 CHAR)")

        oracle8dialect = oracle.dialect()
        oracle8dialect.server_version_info = (8, 0)
        self.assert_compile(VARCHAR(50), "VARCHAR(50)", dialect=oracle8dialect)

        self.assert_compile(NVARCHAR(50), "NVARCHAR2(50)")
        self.assert_compile(CHAR(50), "CHAR(50)") 
Example #18
Source File: test_types.py    From sqlalchemy with MIT License 5 votes vote down vote up
def test_char_length(self):
        metadata = self.metadata
        t1 = Table(
            "t1",
            metadata,
            Column("c1", VARCHAR(50)),
            Column("c2", NVARCHAR(250)),
            Column("c3", CHAR(200)),
            Column("c4", NCHAR(180)),
        )
        t1.create()
        m2 = MetaData(testing.db)
        t2 = Table("t1", m2, autoload=True)
        eq_(t2.c.c1.type.length, 50)
        eq_(t2.c.c2.type.length, 250)
        eq_(t2.c.c3.type.length, 200)
        eq_(t2.c.c4.type.length, 180) 
Example #19
Source File: test_mutable.py    From sqlalchemy with MIT License 5 votes vote down vote up
def define_tables(cls, metadata):
        import json
        from sqlalchemy.ext.declarative import declarative_base

        class JSONEncodedDict(TypeDecorator):
            impl = VARCHAR(50)

            def process_bind_param(self, value, dialect):
                if value is not None:
                    value = json.dumps(value)

                return value

            def process_result_value(self, value, dialect):
                if value is not None:
                    value = json.loads(value)
                return value

        MutableDict = cls._type_fixture()

        Base = declarative_base(metadata=metadata)

        class AbstractFoo(Base):
            __abstract__ = True

            id = Column(
                Integer, primary_key=True, test_needs_autoincrement=True
            )
            data = Column(MutableDict.as_mutable(JSONEncodedDict))
            non_mutable_data = Column(JSONEncodedDict)
            unrelated_data = Column(String(50))

        class Foo(AbstractFoo):
            __tablename__ = "foo"
            column_prop = column_property(
                func.lower(AbstractFoo.unrelated_data)
            )

        assert Foo.data.property.columns[0].type is not AbstractFoo.data.type 
Example #20
Source File: test_mutable.py    From sqlalchemy with MIT License 5 votes vote down vote up
def define_tables(cls, metadata):
        import json

        class JSONEncodedDict(TypeDecorator):
            impl = VARCHAR(50)

            def process_bind_param(self, value, dialect):
                if value is not None:
                    value = json.dumps(value)

                return value

            def process_result_value(self, value, dialect):
                if value is not None:
                    value = json.loads(value)
                return value

        MutableDict = cls._type_fixture()
        MutableDict.associate_with(JSONEncodedDict)

        Table(
            "foo",
            metadata,
            Column(
                "id", Integer, primary_key=True, test_needs_autoincrement=True
            ),
            Column("data", JSONEncodedDict),
            Column("unrelated_data", String(50)),
        ) 
Example #21
Source File: test_introspection.py    From sqlalchemy-cockroachdb with Apache License 2.0 5 votes vote down vote up
def test_varchar(self):
        types = [
            'char',
            'char varying',
            'character',
            'character varying',
            'string',
            'text',
            'varchar',
        ]
        for t in types:
            self._test(t, sqltypes.VARCHAR) 
Example #22
Source File: sqlalchemy.py    From depot with MIT License 5 votes vote down vote up
def load_dialect_impl(self, dialect):
        return dialect.type_descriptor(types.VARCHAR(4000)) 
Example #23
Source File: base.py    From jarvis with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, length=None, **kwargs):
        super(VARCHAR, self).__init__(length=length, **kwargs) 
Example #24
Source File: base.py    From jarvis with GNU General Public License v2.0 5 votes vote down vote up
def visit_VARCHAR(self, type_, **kw):
        if not type_.length:
            raise exc.CompileError(
                "VARCHAR requires a length on dialect %s" %
                self.dialect.name)
        basic = super(FBTypeCompiler, self).visit_VARCHAR(type_, **kw)
        return self._extend_string(type_, basic) 
Example #25
Source File: base.py    From moviegrabber with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, length=None, **kwargs):
        super(VARCHAR, self).__init__(length=length, **kwargs) 
Example #26
Source File: base.py    From moviegrabber with GNU General Public License v3.0 5 votes vote down vote up
def visit_VARCHAR(self, type_):
        if not type_.length:
            raise exc.CompileError(
                    "VARCHAR requires a length on dialect %s" %
                    self.dialect.name)
        basic = super(FBTypeCompiler, self).visit_VARCHAR(type_)
        return self._extend_string(type_, basic) 
Example #27
Source File: base.py    From moviegrabber with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, length=None, **kwargs):
        """Construct a VARCHAR.

        :param collation: Optional, a column-level collation for this string
          value.  Takes precedence to 'binary' short-hand.

        :param binary: Defaults to False: short-hand, pick the binary
          collation type that matches the column's character set.  Generates
          BINARY in schema.  This does not affect the type of data stored,
          only the collation of character data.

        """

        super(VARCHAR, self).__init__(length=length, **kwargs) 
Example #28
Source File: base.py    From android_universal with MIT License 5 votes vote down vote up
def __init__(self, length=None, **kwargs):
        super(VARCHAR, self).__init__(length=length, **kwargs) 
Example #29
Source File: base.py    From android_universal with MIT License 5 votes vote down vote up
def visit_VARCHAR(self, type_, **kw):
        if not type_.length:
            raise exc.CompileError(
                "VARCHAR requires a length on dialect %s" %
                self.dialect.name)
        basic = super(FBTypeCompiler, self).visit_VARCHAR(type_, **kw)
        return self._extend_string(type_, basic) 
Example #30
Source File: __init__.py    From parade with MIT License 5 votes vote down vote up
def sqltype_to_stdtype(sqltype):
    import sqlalchemy.types as sqltypes
    if isinstance(sqltype, (sqltypes.VARCHAR, sqltypes.CHAR, sqltypes.TEXT, sqltypes.Enum, sqltypes.String)):
        return _STRING_TYPE
    if isinstance(sqltype, (sqltypes.DATETIME, sqltypes.DATE, sqltypes.TIME, sqltypes.TIMESTAMP)):
        return _DATE_TYPE
    if isinstance(sqltype, (sqltypes.INTEGER, sqltypes.BIGINT, sqltypes.SMALLINT, sqltypes.Integer)):
        return _INTEGER_TYPE
    if isinstance(sqltype, (sqltypes.REAL, sqltypes.DECIMAL, sqltypes.NUMERIC, sqltypes.FLOAT)):
        return _DECIMAL_TYPE
    if isinstance(sqltype, sqltypes.BOOLEAN):
        return _BOOLEAN_TYPE