Python sqlalchemy.util.u() Examples

The following are 30 code examples of sqlalchemy.util.u(). 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.util , or try the search function .
Example #1
Source File: test_mapper.py    From sqlalchemy with MIT License 6 votes vote down vote up
def test_replace_col_prop_w_syn(self):
        users, User = self.tables.users, self.classes.User

        m = mapper(User, users)
        m.add_property("_name", users.c.name)
        m.add_property("name", synonym("_name"))

        sess = create_session()
        u = sess.query(User).filter_by(name="jack").one()
        eq_(u._name, "jack")
        eq_(u.name, "jack")
        u.name = "jacko"
        assert m._columntoproperty[users.c.name] is m.get_property("_name")

        sa.orm.clear_mappers()

        m = mapper(User, users)
        m.add_property("name", synonym("_name", map_column=True))

        sess.expunge_all()
        u = sess.query(User).filter_by(name="jack").one()
        eq_(u._name, "jack")
        eq_(u.name, "jack")
        u.name = "jacko"
        assert m._columntoproperty[users.c.name] is m.get_property("_name") 
Example #2
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 #3
Source File: test_defaults.py    From sqlalchemy with MIT License 6 votes vote down vote up
def define_tables(cls, metadata):
        Table(
            "q",
            metadata,
            Column("x", Integer, default=2),
            Column("y", Integer, onupdate=5),
            Column("z", Integer),
        )

        Table(
            "p",
            metadata,
            Column("s", Integer),
            Column("t", Integer),
            Column("u", Integer, onupdate=1),
        ) 
Example #4
Source File: test_cascade.py    From sqlalchemy with MIT License 6 votes vote down vote up
def test_list_assignment_new(self):
        User, Order = self.classes.User, self.classes.Order

        sess = Session()
        u = User(
            name="jack",
            orders=[
                Order(description="order 1"),
                Order(description="order 2"),
            ],
        )
        sess.add(u)
        sess.commit()

        eq_(
            u,
            User(
                name="jack",
                orders=[
                    Order(description="order 1"),
                    Order(description="order 2"),
                ],
            ),
        ) 
Example #5
Source File: test_reflection.py    From sqlalchemy with MIT License 6 votes vote down vote up
def _bug_88718_96365_casing_1(self):
        fkeys_casing_1 = [
            {
                "name": "FK_PlaylistTTrackId",
                "constrained_columns": ["TTrackID"],
                "referred_schema": "Test_Schema",
                "referred_table": "Track",
                "referred_columns": ["trackid"],
                "options": {},
            },
            {
                "name": "FK_PlaylistTrackId",
                "constrained_columns": ["TrackID"],
                "referred_schema": None,
                "referred_table": "Track",
                "referred_columns": ["trackid"],
                "options": {},
            },
        ]
        ischema_casing_1 = [
            (util.u("Test"), util.u("Track"), "TrackID"),
            (util.u("Test_Schema"), util.u("Track"), "TrackID"),
        ]
        return fkeys_casing_1, ischema_casing_1 
Example #6
Source File: test_cascade.py    From sqlalchemy with MIT License 6 votes vote down vote up
def test_remove_pending_from_pending_parent(self):
        # test issue #4040

        User, Order = self.classes.User, self.classes.Order

        sess = Session()

        u = User(name="jack")

        o1 = Order()
        sess.add(o1)

        # object becomes an orphan, but parent is not in session
        u.orders.append(o1)
        u.orders.remove(o1)

        sess.add(u)

        assert o1 in sess

        sess.flush()

        assert o1 not in sess 
Example #7
Source File: test_execute.py    From sqlalchemy with MIT License 6 votes vote down vote up
def test_stmt_exception_bytestring_raised(self):
        name = util.u("méil")
        with testing.db.connect() as conn:
            assert_raises_message(
                tsa.exc.StatementError,
                util.u(
                    "A value is required for bind parameter 'uname'\n"
                    r".*SELECT users.user_name AS .m\xe9il."
                )
                if util.py2k
                else util.u(
                    "A value is required for bind parameter 'uname'\n"
                    ".*SELECT users.user_name AS .méil."
                ),
                conn.execute,
                select([users.c.user_name.label(name)]).where(
                    users.c.user_name == bindparam("uname")
                ),
                {"uname_incorrect": "foo"},
            ) 
Example #8
Source File: test_execute.py    From sqlalchemy with MIT License 6 votes vote down vote up
def test_exception_wrapping_non_dbapi_statement(self):
        class MyType(TypeDecorator):
            impl = Integer

            def process_bind_param(self, value, dialect):
                raise SomeException("nope")

        def _go(conn):
            assert_raises_message(
                tsa.exc.StatementError,
                r"\(.*.SomeException\) " r"nope\n\[SQL\: u?SELECT 1 ",
                conn.execute,
                select([1]).where(column("foo") == literal("bar", MyType())),
            )

        _go(testing.db)
        with testing.db.connect() as conn:
            _go(conn) 
Example #9
Source File: test_cascade.py    From sqlalchemy with MIT License 6 votes vote down vote up
def test_delete(self):
        User, users, orders, Order = (
            self.classes.User,
            self.tables.users,
            self.tables.orders,
            self.classes.Order,
        )

        sess = create_session()
        u = User(
            name="jack",
            orders=[
                Order(description="someorder"),
                Order(description="someotherorder"),
            ],
        )
        sess.add(u)
        sess.flush()

        sess.delete(u)
        sess.flush()
        eq_(select([func.count("*")]).select_from(users).scalar(), 0)
        eq_(select([func.count("*")]).select_from(orders).scalar(), 0) 
Example #10
Source File: test_types.py    From sqlalchemy with MIT License 6 votes vote down vote up
def test_unicode_roundtrip(self):
        set_table = Table(
            "t",
            self.metadata,
            Column("id", Integer, primary_key=True),
            Column("data", mysql.SET(u("réveillé"), u("drôle"), u("S’il"))),
        )

        set_table.create()
        with testing.db.begin() as conn:
            conn.execute(
                set_table.insert(), {"data": set([u("réveillé"), u("drôle")])}
            )

            row = conn.execute(set_table.select()).first()

            eq_(row, (1, set([u("réveillé"), u("drôle")]))) 
Example #11
Source File: test_types.py    From sqlalchemy with MIT License 6 votes vote down vote up
def test_charset_collate_table(self):
        t = Table(
            "foo",
            self.metadata,
            Column("id", Integer),
            Column("data", UnicodeText),
            mysql_default_charset="utf8",
            mysql_collate="utf8_bin",
        )
        t.create()
        m2 = MetaData(testing.db)
        t2 = Table("foo", m2, autoload=True)
        eq_(t2.kwargs["mysql_collate"], "utf8_bin")
        eq_(t2.kwargs["mysql_default charset"], "utf8")

        # test [ticket:2906]
        # in order to test the condition here, need to use
        # MySQLdb 1.2.3 and also need to pass either use_unicode=1
        # or charset=utf8 to the URL.
        t.insert().execute(id=1, data=u("some text"))
        assert isinstance(
            testing.db.scalar(select([t.c.data])), util.text_type
        ) 
Example #12
Source File: test_compiler.py    From sqlalchemy with MIT License 6 votes vote down vote up
def test_create_drop_enum(self):
        # test escaping and unicode within CREATE TYPE for ENUM
        typ = postgresql.ENUM(
            "val1", "val2", "val's 3", u("méil"), name="myname"
        )
        self.assert_compile(
            postgresql.CreateEnumType(typ),
            u(
                "CREATE TYPE myname AS "
                "ENUM ('val1', 'val2', 'val''s 3', 'méil')"
            ),
        )

        typ = postgresql.ENUM("val1", "val2", "val's 3", name="PleaseQuoteMe")
        self.assert_compile(
            postgresql.CreateEnumType(typ),
            'CREATE TYPE "PleaseQuoteMe" AS ENUM '
            "('val1', 'val2', 'val''s 3')",
        ) 
Example #13
Source File: test_unicode_ddl.py    From sqlalchemy with MIT License 6 votes vote down vote up
def test_insert(self, connection):
        connection.execute(t1.insert(), {u("méil"): 1, ue("\u6e2c\u8a66"): 5})
        connection.execute(t2.insert(), {u("a"): 1, u("b"): 1})
        connection.execute(
            t3.insert(),
            {
                ue("\u6e2c\u8a66_id"): 1,
                ue("unitable1_\u6e2c\u8a66"): 5,
                u("Unitéble2_b"): 1,
                ue("\u6e2c\u8a66_self"): 1,
            },
        )

        eq_(connection.execute(t1.select()).fetchall(), [(1, 5)])
        eq_(connection.execute(t2.select()).fetchall(), [(1, 1)])
        eq_(connection.execute(t3.select()).fetchall(), [(1, 5, 1, 1)]) 
Example #14
Source File: test_types.py    From sqlalchemy with MIT License 6 votes vote down vote up
def test_unicode_round_trip(self, connection):
        s = select(
            [
                cast(
                    {
                        util.u("réveillé"): util.u("réveillé"),
                        "data": {"k1": util.u("drôle")},
                    },
                    self.test_type,
                )
            ]
        )
        eq_(
            connection.scalar(s),
            {
                util.u("réveillé"): util.u("réveillé"),
                "data": {"k1": util.u("drôle")},
            },
        ) 
Example #15
Source File: test_dialect.py    From sqlalchemy with MIT License 6 votes vote down vote up
def define_tables(cls, metadata):
        Table(
            "data",
            metadata,
            Column("id", Integer, primary_key=True),
            Column("x", String),
            Column("y", String),
            Column("z", Integer, server_default="5"),
        )

        Table(
            u("Unitéble2"),
            metadata,
            Column(u("méil"), Integer, primary_key=True),
            Column(ue("\u6e2c\u8a66"), Integer),
        ) 
Example #16
Source File: test_mapper.py    From sqlalchemy with MIT License 6 votes vote down vote up
def test_column_prefix(self):
        users, User = self.tables.users, self.classes.User

        mapper(
            User,
            users,
            column_prefix="_",
            properties={"user_name": synonym("_name")},
        )

        s = create_session()
        u = s.query(User).get(7)
        eq_(u._name, "jack")
        eq_(u._id, 7)
        u2 = s.query(User).filter_by(user_name="jack").one()
        assert u is u2 
Example #17
Source File: test_cascade.py    From sqlalchemy with MIT License 5 votes vote down vote up
def test_pending_collection_expunge(self):
        """Removing a pending item from a collection expunges it from
        the session."""

        users, Address, addresses, User = (
            self.tables.users,
            self.classes.Address,
            self.tables.addresses,
            self.classes.User,
        )

        mapper(Address, addresses)
        mapper(
            User,
            users,
            properties=dict(
                addresses=relationship(
                    Address, cascade="all,delete-orphan", backref="user"
                )
            ),
        )
        s = create_session()

        u = User()
        s.add(u)
        s.flush()
        a = Address()

        u.addresses.append(a)
        assert a in s

        u.addresses.remove(a)
        assert a not in s

        s.delete(u)
        s.flush()

        assert a.address_id is None, "Error: address should not be persistent" 
Example #18
Source File: test_types.py    From sqlalchemy with MIT License 5 votes vote down vote up
def test_string_text_literal_binds_explicit_unicode_right(self):
        self.assert_compile(
            column("x", String()) == util.u("foo"),
            "x = 'foo'",
            literal_binds=True,
        ) 
Example #19
Source File: test_cascade.py    From sqlalchemy with MIT License 5 votes vote down vote up
def test_none_o2m_collection_assignment(self):
        User = self.classes.User
        s = Session()
        u1 = User(name="u", addresses=[None])
        s.add(u1)
        eq_(u1.addresses, [None])
        assert_raises_message(
            orm_exc.FlushError,
            "Can't flush None value found in collection User.addresses",
            s.commit,
        )
        eq_(u1.addresses, [None]) 
Example #20
Source File: test_cascade.py    From sqlalchemy with MIT License 5 votes vote down vote up
def test_collection_orphans(self):
        User, users, orders, Order = (
            self.classes.User,
            self.tables.users,
            self.tables.orders,
            self.classes.Order,
        )

        sess = create_session()
        u = User(
            name="jack",
            orders=[
                Order(description="someorder"),
                Order(description="someotherorder"),
            ],
        )
        sess.add(u)
        sess.flush()

        eq_(select([func.count("*")]).select_from(users).scalar(), 1)
        eq_(select([func.count("*")]).select_from(orders).scalar(), 2)

        u.orders[:] = []

        sess.flush()

        eq_(select([func.count("*")]).select_from(users).scalar(), 1)
        eq_(select([func.count("*")]).select_from(orders).scalar(), 0) 
Example #21
Source File: test_cascade.py    From sqlalchemy with MIT License 5 votes vote down vote up
def test_cascade_delete_plusorphans(self):
        User, users, orders, Order = (
            self.classes.User,
            self.tables.users,
            self.tables.orders,
            self.classes.Order,
        )

        sess = create_session()
        u = User(
            name="jack",
            orders=[
                Order(description="someorder"),
                Order(description="someotherorder"),
            ],
        )
        sess.add(u)
        sess.flush()
        eq_(select([func.count("*")]).select_from(users).scalar(), 1)
        eq_(select([func.count("*")]).select_from(orders).scalar(), 2)

        del u.orders[0]
        sess.delete(u)
        sess.flush()
        eq_(select([func.count("*")]).select_from(users).scalar(), 0)
        eq_(select([func.count("*")]).select_from(orders).scalar(), 0) 
Example #22
Source File: test_cascade.py    From sqlalchemy with MIT License 5 votes vote down vote up
def test_none_o2m_collection_append(self):
        User = self.classes.User
        s = Session()

        u1 = User(name="u")
        s.add(u1)
        u1.addresses.append(None)
        eq_(u1.addresses, [None])
        assert_raises_message(
            orm_exc.FlushError,
            "Can't flush None value found in collection User.addresses",
            s.commit,
        )
        eq_(u1.addresses, [None]) 
Example #23
Source File: test_dialect.py    From sqlalchemy with MIT License 5 votes vote down vote up
def test_psycopg2_empty_connection_string_w_query_two(self):
        dialect = psycopg2_dialect.dialect()
        u = url.make_url("postgresql:///?any_random_thing=yes")
        cargs, cparams = dialect.create_connect_args(u)
        eq_(cargs, [])
        eq_(cparams, {"any_random_thing": "yes"}) 
Example #24
Source File: test_types.py    From sqlalchemy with MIT License 5 votes vote down vote up
def test_unicode_warnings_typelevel_native_unicode(self):

        unicodedata = self.data
        u = Unicode()
        dialect = default.DefaultDialect()
        dialect.supports_unicode_binds = True
        uni = u.dialect_impl(dialect).bind_processor(dialect)
        if util.py3k:
            assert_raises(exc.SAWarning, uni, b"x")
            assert isinstance(uni(unicodedata), str)
        else:
            assert_raises(exc.SAWarning, uni, "x")
            assert isinstance(uni(unicodedata), unicode)  # noqa 
Example #25
Source File: test_types.py    From sqlalchemy with MIT License 5 votes vote down vote up
def test_convert_unicode(
        self, datatype, convert_unicode, returns_unicode_strings
    ):
        s1 = datatype()
        dialect = mock.Mock(
            returns_unicode_strings=returns_unicode_strings,
            encoding="utf-8",
            convert_unicode=convert_unicode,
        )

        proc = s1.result_processor(dialect, None)

        string = u("méil")
        bytestring = string.encode("utf-8")

        if (
            datatype is Unicode or convert_unicode
        ) and returns_unicode_strings in (
            String.RETURNS_CONDITIONAL,
            String.RETURNS_BYTES,
        ):
            eq_(proc(bytestring), string)

            if returns_unicode_strings is String.RETURNS_CONDITIONAL:
                eq_(proc(string), string)
            else:
                if util.py3k:
                    # trying to decode a unicode
                    assert_raises(TypeError, proc, string)
                else:
                    assert_raises(UnicodeEncodeError, proc, string)
        else:
            is_(proc, None) 
Example #26
Source File: test_deprecations.py    From sqlalchemy with MIT License 5 votes vote down vote up
def test_alias_union(self):

        # same as testunion, except its an alias of the union

        u = (
            select(
                [
                    self.table1.c.col1,
                    self.table1.c.col2,
                    self.table1.c.col3,
                    self.table1.c.colx,
                    null().label("coly"),
                ]
            )
            .union(
                select(
                    [
                        self.table2.c.col1,
                        self.table2.c.col2,
                        self.table2.c.col3,
                        null().label("colx"),
                        self.table2.c.coly,
                    ]
                )
            )
            .alias("analias")
        )
        s1 = self.table1.select(use_labels=True)
        s2 = self.table2.select(use_labels=True)
        with self._c_deprecated():
            assert u.corresponding_column(s1.c.table1_col2) is u.c.col2
            assert u.corresponding_column(s2.c.table2_col2) is u.c.col2
            assert u.corresponding_column(s2.c.table2_coly) is u.c.coly
            assert s2.c.corresponding_column(u.c.coly) is s2.c.table2_coly 
Example #27
Source File: test_dialect.py    From sqlalchemy with MIT License 5 votes vote down vote up
def test_psycopg2_empty_connection_string_w_query_one(self):
        dialect = psycopg2_dialect.dialect()
        u = url.make_url("postgresql:///?service=swh-log")
        cargs, cparams = dialect.create_connect_args(u)
        eq_(cargs, [])
        eq_(cparams, {"service": "swh-log"}) 
Example #28
Source File: test_types.py    From sqlalchemy with MIT License 5 votes vote down vote up
def test_unicode_enum(self):
        metadata = self.metadata
        t1 = Table(
            "table",
            metadata,
            Column("id", Integer, primary_key=True),
            Column("value", Enum(u("réveillé"), u("drôle"), u("S’il"))),
            Column("value2", mysql.ENUM(u("réveillé"), u("drôle"), u("S’il"))),
        )
        metadata.create_all()
        t1.insert().execute(value=u("drôle"), value2=u("drôle"))
        t1.insert().execute(value=u("réveillé"), value2=u("réveillé"))
        t1.insert().execute(value=u("S’il"), value2=u("S’il"))
        eq_(
            t1.select().order_by(t1.c.id).execute().fetchall(),
            [
                (1, u("drôle"), u("drôle")),
                (2, u("réveillé"), u("réveillé")),
                (3, u("S’il"), u("S’il")),
            ],
        )

        # test reflection of the enum labels

        m2 = MetaData(testing.db)
        t2 = Table("table", m2, autoload=True)

        # TODO: what's wrong with the last element ?  is there
        #       latin-1 stuff forcing its way in ?

        eq_(
            t2.c.value.type.enums[0:2], [u("réveillé"), u("drôle")]
        )  # u'S’il') # eh ?

        eq_(
            t2.c.value2.type.enums[0:2], [u("réveillé"), u("drôle")]
        )  # u'S’il') # eh ? 
Example #29
Source File: test_dialect.py    From sqlalchemy with MIT License 5 votes vote down vote up
def test_insert_unicode_keys(self, connection):
        table = self.tables[u("Unitéble2")]

        stmt = table.insert()

        connection.execute(
            stmt,
            [
                {u("méil"): 1, ue("\u6e2c\u8a66"): 1},
                {u("méil"): 2, ue("\u6e2c\u8a66"): 2},
                {u("méil"): 3, ue("\u6e2c\u8a66"): 3},
            ],
        )

        eq_(connection.execute(table.select()).all(), [(1, 1), (2, 2), (3, 3)]) 
Example #30
Source File: test_compiler.py    From sqlalchemy with MIT License 5 votes vote down vote up
def test_update_returning(self):
        dialect = postgresql.dialect()
        table1 = table(
            "mytable",
            column("myid", Integer),
            column("name", String(128)),
            column("description", String(128)),
        )
        u = update(table1, values=dict(name="foo")).returning(
            table1.c.myid, table1.c.name
        )
        self.assert_compile(
            u,
            "UPDATE mytable SET name=%(name)s "
            "RETURNING mytable.myid, mytable.name",
            dialect=dialect,
        )
        u = update(table1, values=dict(name="foo")).returning(table1)
        self.assert_compile(
            u,
            "UPDATE mytable SET name=%(name)s "
            "RETURNING mytable.myid, mytable.name, "
            "mytable.description",
            dialect=dialect,
        )
        u = update(table1, values=dict(name="foo")).returning(
            func.length(table1.c.name)
        )
        self.assert_compile(
            u,
            "UPDATE mytable SET name=%(name)s "
            "RETURNING length(mytable.name) AS length_1",
            dialect=dialect,
        )