Python sqlalchemy.dialects.sqlite.pysqlite.dialect() Examples

The following are code examples for showing how to use sqlalchemy.dialects.sqlite.pysqlite.dialect(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: sqlalchemy   Author: sqlalchemy   File: test_sqlite.py    MIT License 6 votes vote down vote up
def test_no_convert_unicode(self):
        """test no utf-8 encoding occurs"""

        dialect = sqlite.dialect()
        for t in (
            String(),
            sqltypes.CHAR(),
            sqltypes.Unicode(),
            sqltypes.UnicodeText(),
            String(),
            sqltypes.CHAR(),
            sqltypes.Unicode(),
            sqltypes.UnicodeText(),
        ):
            bindproc = t.dialect_impl(dialect).bind_processor(dialect)
            assert not bindproc or isinstance(
                bindproc(util.u("some string")), util.text_type
            ) 
Example 2
Project: sqlalchemy   Author: sqlalchemy   File: test_sqlite.py    MIT License 6 votes vote down vote up
def test_in_tuple(self):
        compiled = (
            tuple_(column("q"), column("p"))
            .in_([(1, 2), (3, 4)])
            .compile(dialect=sqlite.dialect())
        )
        eq_(str(compiled), "(q, p) IN ([POSTCOMPILE_param_1])")
        eq_(
            compiled._literal_execute_expanding_parameter(
                "param_1",
                compiled.binds["param_1"],
                compiled.binds["param_1"].value,
            ),
            (
                [
                    ("param_1_1_1", 1),
                    ("param_1_1_2", 2),
                    ("param_1_2_1", 3),
                    ("param_1_2_2", 4),
                ],
                "VALUES (?, ?), (?, ?)",
            ),
        ) 
Example 3
Project: sqlalchemy   Author: sqlalchemy   File: test_sqlite.py    MIT License 6 votes vote down vote up
def test_on_conflict_clause_column_many_clause(self):
        meta = MetaData()
        t = Table(
            "n",
            meta,
            Column(
                "test",
                Integer,
                nullable=False,
                primary_key=True,
                sqlite_on_conflict_not_null="FAIL",
                sqlite_on_conflict_primary_key="IGNORE",
            ),
        )

        self.assert_compile(
            CreateTable(t),
            "CREATE TABLE n ("
            "test INTEGER NOT NULL ON CONFLICT FAIL, "
            "PRIMARY KEY (test) ON CONFLICT IGNORE)",
            dialect=sqlite.dialect(),
        ) 
Example 4
Project: sqlalchemy   Author: sqlalchemy   File: test_sqlite.py    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 5
Project: sqlalchemy   Author: sqlalchemy   File: test_sqlite.py    MIT License 6 votes vote down vote up
def test_on_conflict_clause_primary_key(self):

        meta = MetaData()
        t = Table(
            "n",
            meta,
            Column(
                "id",
                Integer,
                primary_key=True,
                sqlite_on_conflict_primary_key="FAIL",
            ),
            sqlite_autoincrement=True,
        )

        self.assert_compile(
            CreateTable(t),
            "CREATE TABLE n (id INTEGER NOT NULL "
            "PRIMARY KEY ON CONFLICT FAIL AUTOINCREMENT)",
            dialect=sqlite.dialect(),
        ) 
Example 6
Project: sqlalchemy   Author: sqlalchemy   File: test_sqlite.py    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 7
Project: sqlalchemy   Author: sqlalchemy   File: test_sqlite.py    MIT License 6 votes vote down vote up
def test_on_conflict_clause_check_constraint_from_column(self):

        meta = MetaData()
        t = Table(
            "n",
            meta,
            Column(
                "x",
                Integer,
                CheckConstraint("x > 1", sqlite_on_conflict="FAIL"),
            ),
        )

        assert_raises_message(
            exc.CompileError,
            "SQLite does not support on conflict "
            "clause for column check constraint",
            CreateTable(t).compile,
            dialect=sqlite.dialect(),
        ) 
Example 8
Project: sqlalchemy   Author: sqlalchemy   File: test_sqlite.py    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 9
Project: sqlalchemy   Author: sqlalchemy   File: test_sqlite.py    MIT License 6 votes vote down vote up
def test_sqlite_autoincrement_constraint(self):
        table = Table(
            "autoinctable",
            MetaData(),
            Column("id", Integer, primary_key=True),
            Column("x", Integer, default=None),
            UniqueConstraint("x"),
            sqlite_autoincrement=True,
        )
        self.assert_compile(
            schema.CreateTable(table),
            "CREATE TABLE autoinctable (id INTEGER NOT "
            "NULL PRIMARY KEY AUTOINCREMENT, x "
            "INTEGER, UNIQUE (x))",
            dialect=sqlite.dialect(),
        ) 
Example 10
Project: sqlalchemy   Author: sqlalchemy   File: test_sqlite.py    MIT License 6 votes vote down vote up
def test_sqlite_autoincrement_int_affinity(self):
        class MyInteger(sqltypes.TypeDecorator):
            impl = Integer

        table = Table(
            "autoinctable",
            MetaData(),
            Column("id", MyInteger, primary_key=True),
            sqlite_autoincrement=True,
        )
        self.assert_compile(
            schema.CreateTable(table),
            "CREATE TABLE autoinctable (id INTEGER NOT "
            "NULL PRIMARY KEY AUTOINCREMENT)",
            dialect=sqlite.dialect(),
        ) 
Example 11
Project: sqlalchemy   Author: sqlalchemy   File: test_sqlite.py    MIT License 5 votes vote down vote up
def test_native_datetime(self):
        dbapi = testing.db.dialect.dbapi
        connect_args = {
            "detect_types": dbapi.PARSE_DECLTYPES | dbapi.PARSE_COLNAMES
        }
        engine = engines.testing_engine(
            options={"connect_args": connect_args, "native_datetime": True}
        )
        t = Table(
            "datetest",
            MetaData(),
            Column("id", Integer, primary_key=True),
            Column("d1", Date),
            Column("d2", sqltypes.TIMESTAMP),
        )
        t.create(engine)
        try:
            engine.execute(
                t.insert(),
                {
                    "d1": datetime.date(2010, 5, 10),
                    "d2": datetime.datetime(2010, 5, 10, 12, 15, 25),
                },
            )
            row = engine.execute(t.select()).first()
            eq_(
                row,
                (
                    1,
                    datetime.date(2010, 5, 10),
                    datetime.datetime(2010, 5, 10, 12, 15, 25),
                ),
            )
            r = engine.execute(func.current_date()).scalar()
            assert isinstance(r, util.string_types)
        finally:
            t.drop(engine)
            engine.dispose() 
Example 12
Project: sqlalchemy   Author: sqlalchemy   File: test_sqlite.py    MIT License 5 votes vote down vote up
def test_deprecated_serializer_args(self):
        sqlite_json = Table(
            "json_test", self.metadata, Column("foo", sqlite.JSON)
        )
        data_element = {"foo": "bar"}

        js = mock.Mock(side_effect=json.dumps)
        jd = mock.Mock(side_effect=json.loads)

        with testing.expect_deprecated(
            "The _json_deserializer argument to the SQLite "
            "dialect has been renamed",
            "The _json_serializer argument to the SQLite "
            "dialect has been renamed",
        ):
            engine = engines.testing_engine(
                options=dict(_json_serializer=js, _json_deserializer=jd)
            )
        self.metadata.create_all(engine)

        engine.execute(sqlite_json.insert(), {"foo": data_element})

        row = engine.execute(select([sqlite_json.c.foo])).first()

        eq_(row, (data_element,))
        eq_(js.mock_calls, [mock.call(data_element)])
        eq_(jd.mock_calls, [mock.call(json.dumps(data_element))]) 
Example 13
Project: sqlalchemy   Author: sqlalchemy   File: test_sqlite.py    MIT License 5 votes vote down vote up
def test_old_style_default(self):
        """test non-quoted integer value on older sqlite pragma"""

        dialect = sqlite.dialect()
        info = dialect._get_column_info("foo", "INTEGER", False, 3, False)
        eq_(info["default"], "3") 
Example 14
Project: sqlalchemy   Author: sqlalchemy   File: test_sqlite.py    MIT License 5 votes vote down vote up
def test_3_7_16_warning(self):
        with expect_warnings(
            r"SQLite version \(3, 2, 8\) is older than 3.7.16, and "
            "will not support right nested joins"
        ):
            sqlite.dialect(
                dbapi=mock.Mock(
                    version_info=(2, 6, 0), sqlite_version_info=(3, 2, 8)
                )
            ) 
Example 15
Project: sqlalchemy   Author: sqlalchemy   File: test_sqlite.py    MIT License 5 votes vote down vote up
def test_column_computed(self, persisted):
        m = MetaData()
        kwargs = {"persisted": persisted} if persisted != "ignore" else {}
        t = Table(
            "t",
            m,
            Column("x", Integer),
            Column("y", Integer, Computed("x + 2", **kwargs)),
        )
        assert_raises_message(
            exc.CompileError,
            "SQLite does not support computed columns",
            schema.CreateTable(t).compile,
            dialect=sqlite.dialect(),
        ) 
Example 16
Project: sqlalchemy   Author: sqlalchemy   File: test_sqlite.py    MIT License 5 votes vote down vote up
def test_create_partial_index(self):
        m = MetaData()
        tbl = Table("testtbl", m, Column("data", Integer))
        idx = Index(
            "test_idx1",
            tbl.c.data,
            sqlite_where=and_(tbl.c.data > 5, tbl.c.data < 10),
        )

        # test quoting and all that

        idx2 = Index(
            "test_idx2",
            tbl.c.data,
            sqlite_where=and_(tbl.c.data > "a", tbl.c.data < "b's"),
        )
        self.assert_compile(
            schema.CreateIndex(idx),
            "CREATE INDEX test_idx1 ON testtbl (data) "
            "WHERE data > 5 AND data < 10",
            dialect=sqlite.dialect(),
        )
        self.assert_compile(
            schema.CreateIndex(idx2),
            "CREATE INDEX test_idx2 ON testtbl (data) "
            "WHERE data > 'a' AND data < 'b''s'",
            dialect=sqlite.dialect(),
        ) 
Example 17
Project: sqlalchemy   Author: sqlalchemy   File: test_sqlite.py    MIT License 5 votes vote down vote up
def test_no_autoinc_on_composite_pk(self):
        m = MetaData()
        t = Table(
            "t",
            m,
            Column("x", Integer, primary_key=True, autoincrement=True),
            Column("y", Integer, primary_key=True),
        )
        assert_raises_message(
            exc.CompileError,
            "SQLite does not support autoincrement for composite",
            CreateTable(t).compile,
            dialect=sqlite.dialect(),
        ) 
Example 18
Project: sqlalchemy   Author: sqlalchemy   File: test_sqlite.py    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 19
Project: sqlalchemy   Author: sqlalchemy   File: test_sqlite.py    MIT License 5 votes vote down vote up
def test_expression(self):
        self.assert_compile(
            matchtable.c.title.match("somstr"),
            "matchtable.title MATCH ?",
            dialect=sqlite.dialect(),
        ) 
Example 20
Project: sqlalchemy   Author: sqlalchemy   File: test_sqlite.py    MIT License 5 votes vote down vote up
def test_sqlite_autoincrement(self):
        table = Table(
            "autoinctable",
            MetaData(),
            Column("id", Integer, primary_key=True),
            Column("x", Integer, default=None),
            sqlite_autoincrement=True,
        )
        self.assert_compile(
            schema.CreateTable(table),
            "CREATE TABLE autoinctable (id INTEGER NOT "
            "NULL PRIMARY KEY AUTOINCREMENT, x INTEGER)",
            dialect=sqlite.dialect(),
        ) 
Example 21
Project: sqlalchemy   Author: sqlalchemy   File: test_sqlite.py    MIT License 5 votes vote down vote up
def _test_lookup_direct(self, fixture, warnings=False):
        dialect = sqlite.dialect()
        for from_, to_ in self._fixture_as_string(fixture):
            if warnings:

                def go():
                    return dialect._resolve_type_affinity(from_)

                final_type = testing.assert_warnings(
                    go, ["Could not instantiate"], regex=True
                )
            else:
                final_type = dialect._resolve_type_affinity(from_)
            expected_type = type(to_)
            is_(type(final_type), expected_type) 
Example 22
Project: sqlalchemy   Author: sqlalchemy   File: test_sqlite.py    MIT License 4 votes vote down vote up
def test_connect_args(self):
        """test create_connect_args scenarios including support for uri=True"""

        d = pysqlite_dialect.dialect()
        for url, expected in [
            (
                "sqlite:///foo.db",  # file path is absolute
                ([os.path.abspath("foo.db")], {}),
            ),
            ("sqlite:////abs/path/to/foo.db", (["/abs/path/to/foo.db"], {})),
            ("sqlite://", ([":memory:"], {})),
            (
                "sqlite:///?check_same_thread=true",
                ([":memory:"], {"check_same_thread": True}),
            ),
            (
                "sqlite:///file:path/to/database?"
                "check_same_thread=true&timeout=10&mode=ro&nolock=1&uri=true",
                (
                    ["file:path/to/database?mode=ro&nolock=1"],
                    {"check_same_thread": True, "timeout": 10.0, "uri": True},
                ),
            ),
            (
                "sqlite:///file:path/to/database?" "mode=ro&uri=true",
                (["file:path/to/database?mode=ro"], {"uri": True}),
            ),
            (
                "sqlite:///file:path/to/database?uri=true",
                (["file:path/to/database"], {"uri": True}),
            ),
        ]:
            url = make_url(url)
            eq_(d.create_connect_args(url), expected) 
Example 23
Project: sqlalchemy   Author: sqlalchemy   File: test_sqlite.py    MIT License 4 votes vote down vote up
def test_legacy_quoted_identifiers_unit(self):
        dialect = sqlite.dialect()
        dialect._broken_fk_pragma_quotes = True

        for row in [
            (0, None, "target", "tid", "id", None),
            (0, None, '"target"', "tid", "id", None),
            (0, None, "[target]", "tid", "id", None),
            (0, None, "'target'", "tid", "id", None),
            (0, None, "`target`", "tid", "id", None),
        ]:

            def _get_table_pragma(*arg, **kw):
                return [row]

            def _get_table_sql(*arg, **kw):
                return (
                    "CREATE TABLE foo "
                    "(tid INTEGER, "
                    "FOREIGN KEY(tid) REFERENCES %s (id))" % row[2]
                )

            with mock.patch.object(
                dialect, "_get_table_pragma", _get_table_pragma
            ):
                with mock.patch.object(
                    dialect, "_get_table_sql", _get_table_sql
                ):

                    fkeys = dialect.get_foreign_keys(None, "foo")
                    eq_(
                        fkeys,
                        [
                            {
                                "referred_table": "target",
                                "referred_columns": ["id"],
                                "referred_schema": None,
                                "name": None,
                                "constrained_columns": ["tid"],
                                "options": {},
                            }
                        ],
                    )