Python sqlalchemy.util.OrderedDict() Examples

The following are 30 code examples of sqlalchemy.util.OrderedDict(). 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_compiler.py    From sqlalchemy with MIT License 6 votes vote down vote up
def test_do_update_str_index_elements_target_one(self):
        i = insert(self.table_with_metadata).values(myid=1, name="foo")
        i = i.on_conflict_do_update(
            index_elements=["myid"],
            set_=OrderedDict(
                [
                    ("name", i.excluded.name),
                    ("description", i.excluded.description),
                ]
            ),
        )
        self.assert_compile(
            i,
            "INSERT INTO mytable (myid, name) VALUES "
            "(%(myid)s, %(name)s) ON CONFLICT (myid) "
            "DO UPDATE SET name = excluded.name, "
            "description = excluded.description",
        ) 
Example #2
Source File: __init__.py    From daf-recipes with GNU General Public License v3.0 6 votes vote down vote up
def revision_as_dict(revision, include_packages=True, include_groups=True,
                     ref_package_by='name'):
    revision_dict = OrderedDict((
        ('id', revision.id),
        ('timestamp', revision.timestamp.isoformat()),
        ('message', revision.message),
        ('author', revision.author),
        ('approved_timestamp',
         revision.approved_timestamp.isoformat() \
         if revision.approved_timestamp else None),
        ))
    if include_packages:
        revision_dict['packages'] = [getattr(pkg, ref_package_by) \
                                     for pkg in revision.packages
                                     if (pkg and not pkg.private)]
    if include_groups:
        revision_dict['groups'] = [getattr(grp, ref_package_by) \
                                     for grp in revision.groups if grp]

    return revision_dict 
Example #3
Source File: test_compiler.py    From sqlalchemy with MIT License 6 votes vote down vote up
def test_do_update_set_clause_literal(self):
        i = insert(self.table_with_metadata).values(myid=1, name="foo")
        i = i.on_conflict_do_update(
            index_elements=["myid"],
            set_=OrderedDict(
                [("name", "I'm a name"), ("description", null())]
            ),
        )
        self.assert_compile(
            i,
            "INSERT INTO mytable (myid, name) VALUES "
            "(%(myid)s, %(name)s) ON CONFLICT (myid) "
            "DO UPDATE SET name = %(param_1)s, "
            "description = NULL",
            {"myid": 1, "name": "foo", "param_1": "I'm a name"},
        ) 
Example #4
Source File: test_compiler.py    From sqlalchemy with MIT License 6 votes vote down vote up
def test_do_update_set_clause_none(self):
        i = insert(self.table_with_metadata).values(myid=1, name="foo")
        i = i.on_conflict_do_update(
            index_elements=["myid"],
            set_=OrderedDict([("name", "I'm a name"), ("description", None)]),
        )
        self.assert_compile(
            i,
            "INSERT INTO mytable (myid, name) VALUES "
            "(%(myid)s, %(name)s) ON CONFLICT (myid) "
            "DO UPDATE SET name = %(param_1)s, "
            "description = %(param_2)s",
            {
                "myid": 1,
                "name": "foo",
                "param_1": "I'm a name",
                "param_2": None,
            },
        ) 
Example #5
Source File: _poly_fixtures.py    From sqlalchemy with MIT License 6 votes vote down vote up
def _get_polymorphics(cls):
        people, engineers, managers, boss = (
            cls.tables.people,
            cls.tables.engineers,
            cls.tables.managers,
            cls.tables.boss,
        )
        person_join = polymorphic_union(
            util.OrderedDict(
                [
                    ("engineer", people.join(engineers)),
                    ("manager", people.join(managers)),
                ]
            ),
            None,
            "pjoin",
        )

        manager_join = people.join(managers).outerjoin(boss)
        person_with_polymorphic = ([Person, Manager, Engineer], person_join)
        manager_with_polymorphic = ("*", manager_join)
        return person_with_polymorphic, manager_with_polymorphic 
Example #6
Source File: test_eager_relations.py    From sqlalchemy with MIT License 5 votes vote down vote up
def setup_mappers(cls):
        A, B, C1, C2, D1, D2, E1 = (
            cls.classes.A,
            cls.classes.B,
            cls.classes.C1,
            cls.classes.C2,
            cls.classes.D1,
            cls.classes.D2,
            cls.classes.E1,
        )
        mapper(A, cls.tables.a, properties={"bs": relationship(B)})
        mapper(
            B,
            cls.tables.b,
            properties=odict(
                [
                    ("c1s", relationship(C1, order_by=cls.tables.c1.c.id)),
                    ("c2s", relationship(C2, order_by=cls.tables.c2.c.id)),
                ]
            ),
        )
        mapper(
            C1,
            cls.tables.c1,
            properties={"d1s": relationship(D1, order_by=cls.tables.d1.c.id)},
        )
        mapper(
            C2,
            cls.tables.c2,
            properties={"d2s": relationship(D2, order_by=cls.tables.d2.c.id)},
        )
        mapper(
            D1,
            cls.tables.d1,
            properties={"e1s": relationship(E1, order_by=cls.tables.e1.c.id)},
        )
        mapper(D2, cls.tables.d2)
        mapper(E1, cls.tables.e1) 
Example #7
Source File: test_compiler.py    From sqlalchemy with MIT License 5 votes vote down vote up
def test_quote_raw_string_col(self):
        t = table("t", column("FancyName"), column("other name"))

        stmt = (
            insert(t)
            .values(FancyName="something new")
            .on_conflict_do_update(
                index_elements=["FancyName", "other name"],
                set_=OrderedDict(
                    [
                        ("FancyName", "something updated"),
                        ("other name", "something else"),
                    ]
                ),
            )
        )

        self.assert_compile(
            stmt,
            'INSERT INTO t ("FancyName") VALUES (%(FancyName)s) '
            'ON CONFLICT ("FancyName", "other name") '
            'DO UPDATE SET "FancyName" = %(param_1)s, '
            '"other name" = %(param_2)s',
            {
                "param_1": "something updated",
                "param_2": "something else",
                "FancyName": "something new",
            },
        ) 
Example #8
Source File: batch.py    From jbox with MIT License 5 votes vote down vote up
def __init__(self, table, table_args, table_kwargs):
        self.table = table  # this is a Table object
        self.table_args = table_args
        self.table_kwargs = table_kwargs
        self.new_table = None
        self.column_transfers = OrderedDict(
            (c.name, {'expr': c}) for c in self.table.c
        )
        self._grab_table_elements() 
Example #9
Source File: test_core_compilation.py    From sqlalchemy with MIT License 5 votes vote down vote up
def column_property_fixture(self):
        users, Address, addresses, User = (
            self.tables.users,
            self.classes.Address,
            self.tables.addresses,
            self.classes.User,
        )

        mapper(
            User,
            users,
            properties=util.OrderedDict(
                [
                    ("concat", column_property((users.c.id * 2))),
                    (
                        "count",
                        column_property(
                            select(func.count(addresses.c.id))
                            .where(users.c.id == addresses.c.user_id,)
                            .correlate(users)
                            .scalar_subquery()
                        ),
                    ),
                ]
            ),
        )

        mapper(Address, addresses, properties={"user": relationship(User,)})

        return User, Address 
Example #10
Source File: test_collection.py    From sqlalchemy with MIT License 5 votes vote down vote up
def test_dict_subclass3(self):
        class MyOrdered(util.OrderedDict, collections.MappedCollection):
            def __init__(self):
                collections.MappedCollection.__init__(self, lambda e: e.a)
                util.OrderedDict.__init__(self)

        self._test_adapter(
            MyOrdered, self.dictable_entity, to_set=lambda c: set(c.values())
        )
        self._test_dict(MyOrdered)
        self._test_dict_bulk(MyOrdered)
        self.assert_(getattr(MyOrdered, "_sa_instrumented") == id(MyOrdered)) 
Example #11
Source File: test_collection.py    From sqlalchemy with MIT License 5 votes vote down vote up
def test_mixin(self):
        class Ordered(util.OrderedDict, collections.MappedCollection):
            def __init__(self):
                collections.MappedCollection.__init__(self, lambda v: v.a)
                util.OrderedDict.__init__(self)

        collection_class = Ordered
        self._test_scalar_mapped(collection_class) 
Example #12
Source File: test_collection.py    From sqlalchemy with MIT License 5 votes vote down vote up
def test_mixin2(self):
        class Ordered2(util.OrderedDict, collections.MappedCollection):
            def __init__(self, keyfunc):
                collections.MappedCollection.__init__(self, keyfunc)
                util.OrderedDict.__init__(self)

        def collection_class():
            return Ordered2(lambda v: (v.a, v.b))

        self._test_composite_mapped(collection_class) 
Example #13
Source File: test_eager_relations.py    From sqlalchemy with MIT License 5 votes vote down vote up
def test_unnested_outerjoin_propagation_only_on_correct_path(self):
        # test #3131

        User, users = self.classes.User, self.tables.users
        Order, orders = self.classes.Order, self.tables.orders
        Address, addresses = self.classes.Address, self.tables.addresses

        mapper(
            User,
            users,
            properties=odict(
                [
                    ("orders", relationship(Order)),
                    ("addresses", relationship(Address)),
                ]
            ),
        )
        mapper(Order, orders)
        mapper(Address, addresses)

        sess = create_session()
        q = sess.query(User).options(
            joinedload("orders"), joinedload("addresses", innerjoin="unnested")
        )

        self.assert_compile(
            q,
            "SELECT users.id AS users_id, users.name AS users_name, "
            "orders_1.id AS orders_1_id, "
            "orders_1.user_id AS orders_1_user_id, "
            "orders_1.address_id AS orders_1_address_id, "
            "orders_1.description AS orders_1_description, "
            "orders_1.isopen AS orders_1_isopen, "
            "addresses_1.id AS addresses_1_id, "
            "addresses_1.user_id AS addresses_1_user_id, "
            "addresses_1.email_address AS addresses_1_email_address "
            "FROM users LEFT OUTER JOIN orders AS orders_1 "
            "ON users.id = orders_1.user_id JOIN addresses AS addresses_1 "
            "ON users.id = addresses_1.user_id",
        ) 
Example #14
Source File: test_update.py    From sqlalchemy with MIT License 5 votes vote down vote up
def test_update_ordereddict(self):
        table1 = self.tables.mytable

        # Confirm that ordered dicts are treated as normal dicts,
        # columns sorted in table order
        values = util.OrderedDict(
            (
                (table1.c.name, table1.c.name + "lala"),
                (table1.c.myid, func.do_stuff(table1.c.myid, literal("hoho"))),
            )
        )

        self.assert_compile(
            update(
                table1,
                (table1.c.myid == func.hoho(4))
                & (
                    table1.c.name
                    == literal("foo") + table1.c.name + literal("lala")
                ),
                values=values,
            ),
            "UPDATE mytable "
            "SET "
            "myid=do_stuff(mytable.myid, :param_1), "
            "name=(mytable.name || :name_1) "
            "WHERE "
            "mytable.myid = hoho(:hoho_1) AND "
            "mytable.name = :param_2 || mytable.name || :param_3",
        ) 
Example #15
Source File: test_eager_relations.py    From sqlalchemy with MIT License 5 votes vote down vote up
def setup_mappers(cls):
        A, B, C, D = (
            cls.classes.A,
            cls.classes.B,
            cls.classes.C,
            cls.classes.D,
        )
        mapper(A, cls.tables.a, properties={"b": relationship(B)})
        mapper(B, cls.tables.b, properties=odict([("c", relationship(C))]))
        mapper(
            C,
            cls.tables.c,
            properties=odict(
                [
                    (
                        "ds",
                        relationship(
                            D,
                            secondary=cls.tables.ctod,
                            order_by=cls.tables.d.c.id,
                        ),
                    )
                ]
            ),
        )
        mapper(D, cls.tables.d) 
Example #16
Source File: test_basic.py    From sqlalchemy with MIT License 5 votes vote down vote up
def test_type_col_present(self):
        t1, t2, t3 = self._fixture()
        self.assert_compile(
            polymorphic_union(
                util.OrderedDict([("a", t1), ("b", t2), ("c", t3)]), "q1"
            ),
            "SELECT t1.c1, t1.c2, t1.c3, CAST(NULL AS INTEGER) AS c4, "
            "CAST(NULL AS INTEGER) AS c5, 'a' AS q1 FROM t1 UNION ALL "
            "SELECT t2.c1, t2.c2, t2.c3, t2.c4, CAST(NULL AS INTEGER) AS c5, "
            "'b' AS q1 FROM t2 UNION ALL SELECT t3.c1, "
            "CAST(NULL AS INTEGER) AS c2, t3.c3, CAST(NULL AS INTEGER) AS c4, "
            "t3.c5, 'c' AS q1 FROM t3",
        ) 
Example #17
Source File: test_basic.py    From sqlalchemy with MIT License 5 votes vote down vote up
def test_no_cast_null(self):
        t1, t2, t3 = self._fixture()
        self.assert_compile(
            polymorphic_union(
                util.OrderedDict([("a", t1), ("b", t2), ("c", t3)]),
                "q1",
                cast_nulls=False,
            ),
            "SELECT t1.c1, t1.c2, t1.c3, NULL AS c4, NULL AS c5, 'a' AS q1 "
            "FROM t1 UNION ALL SELECT t2.c1, t2.c2, t2.c3, t2.c4, NULL AS c5, "
            "'b' AS q1 FROM t2 UNION ALL SELECT t3.c1, NULL AS c2, t3.c3, "
            "NULL AS c4, t3.c5, 'c' AS q1 FROM t3",
        ) 
Example #18
Source File: test_mapper.py    From sqlalchemy with MIT License 5 votes vote down vote up
def test_synonym_map_column_conflict(self):
        users, User = self.tables.users, self.classes.User

        assert_raises(
            sa.exc.ArgumentError,
            mapper,
            User,
            users,
            properties=util.OrderedDict(
                [
                    ("_user_id", users.c.id),
                    ("id", synonym("_user_id", map_column=True)),
                ]
            ),
        )

        assert_raises(
            sa.exc.ArgumentError,
            mapper,
            User,
            users,
            properties=util.OrderedDict(
                [
                    ("id", synonym("_user_id", map_column=True)),
                    ("_user_id", users.c.id),
                ]
            ),
        ) 
Example #19
Source File: test_utils.py    From sqlalchemy with MIT License 5 votes vote down vote up
def test_serialize_context_dict(self):
        reg = util.OrderedDict()
        umapper = inspect(self.classes.User)
        amapper = inspect(self.classes.Address)

        p1 = PathRegistry.coerce((umapper, umapper.attrs.addresses))
        p2 = PathRegistry.coerce((umapper, umapper.attrs.addresses, amapper))
        p3 = PathRegistry.coerce((amapper, amapper.attrs.email_address))

        p1.set(reg, "p1key", "p1value")
        p2.set(reg, "p2key", "p2value")
        p3.set(reg, "p3key", "p3value")
        eq_(
            reg,
            {
                ("p1key", p1.path): "p1value",
                ("p2key", p2.path): "p2value",
                ("p3key", p3.path): "p3value",
            },
        )

        serialized = PathRegistry.serialize_context_dict(
            reg, ("p1key", "p2key")
        )
        eq_(
            serialized,
            [
                (("p1key", p1.serialize()), "p1value"),
                (("p2key", p2.serialize()), "p2value"),
            ],
        ) 
Example #20
Source File: batch.py    From android_universal with MIT License 5 votes vote down vote up
def __init__(self, table, table_args, table_kwargs, reflected):
        self.table = table  # this is a Table object
        self.table_args = table_args
        self.table_kwargs = table_kwargs
        self.temp_table_name = self._calc_temp_name(table.name)
        self.new_table = None
        self.column_transfers = OrderedDict(
            (c.name, {'expr': c}) for c in self.table.c
        )
        self.reflected = reflected
        self._grab_table_elements() 
Example #21
Source File: batch.py    From android_universal with MIT License 5 votes vote down vote up
def _grab_table_elements(self):
        schema = self.table.schema
        self.columns = OrderedDict()
        for c in self.table.c:
            c_copy = c.copy(schema=schema)
            c_copy.unique = c_copy.index = False
            # ensure that the type object was copied,
            # as we may need to modify it in-place
            if isinstance(c.type, SchemaEventTarget):
                assert c_copy.type is not c.type
            self.columns[c.name] = c_copy
        self.named_constraints = {}
        self.unnamed_constraints = []
        self.indexes = {}
        self.new_indexes = {}
        for const in self.table.constraints:
            if _is_type_bound(const):
                continue
            elif self.reflected and isinstance(const, CheckConstraint):
                # TODO: we are skipping reflected CheckConstraint because
                # we have no way to determine _is_type_bound() for these.
                pass
            elif const.name:
                self.named_constraints[const.name] = const
            else:
                self.unnamed_constraints.append(const)

        for idx in self.table.indexes:
            self.indexes[idx.name] = idx

        for k in self.table.kwargs:
            self.table_kwargs.setdefault(k, self.table.kwargs[k]) 
Example #22
Source File: batch.py    From alembic with MIT License 5 votes vote down vote up
def _grab_table_elements(self):
        schema = self.table.schema
        self.columns = OrderedDict()
        for c in self.table.c:
            c_copy = c.copy(schema=schema)
            c_copy.unique = c_copy.index = False
            # ensure that the type object was copied,
            # as we may need to modify it in-place
            if isinstance(c.type, SchemaEventTarget):
                assert c_copy.type is not c.type
            self.columns[c.name] = c_copy
        self.named_constraints = {}
        self.unnamed_constraints = []
        self.indexes = {}
        self.new_indexes = {}
        for const in self.table.constraints:
            if _is_type_bound(const):
                continue
            elif self.reflected and isinstance(const, CheckConstraint):
                # TODO: we are skipping reflected CheckConstraint because
                # we have no way to determine _is_type_bound() for these.
                pass
            elif const.name:
                self.named_constraints[const.name] = const
            else:
                self.unnamed_constraints.append(const)

        for idx in self.table.indexes:
            self.indexes[idx.name] = idx

        for k in self.table.kwargs:
            self.table_kwargs.setdefault(k, self.table.kwargs[k]) 
Example #23
Source File: batch.py    From jbox with MIT License 5 votes vote down vote up
def _grab_table_elements(self):
        schema = self.table.schema
        self.columns = OrderedDict()
        for c in self.table.c:
            c_copy = c.copy(schema=schema)
            c_copy.unique = c_copy.index = False
            # ensure that the type object was copied,
            # as we may need to modify it in-place
            if isinstance(c.type, SchemaEventTarget):
                assert c_copy.type is not c.type
            self.columns[c.name] = c_copy
        self.named_constraints = {}
        self.unnamed_constraints = []
        self.indexes = {}
        self.new_indexes = {}
        for const in self.table.constraints:
            if _is_type_bound(const):
                continue
            elif const.name:
                self.named_constraints[const.name] = const
            else:
                self.unnamed_constraints.append(const)

        for idx in self.table.indexes:
            self.indexes[idx.name] = idx

        for k in self.table.kwargs:
            self.table_kwargs.setdefault(k, self.table.kwargs[k]) 
Example #24
Source File: domain_object.py    From daf-recipes with GNU General Public License v3.0 5 votes vote down vote up
def as_dict(self):
        _dict = OrderedDict()
        table = orm.class_mapper(self.__class__).mapped_table
        for col in table.c:
            val = getattr(self, col.name)
            if isinstance(val, datetime.date):
                val = str(val)
            if isinstance(val, datetime.datetime):
                val = val.isoformat()
            _dict[col.name] = val
        return _dict 
Example #25
Source File: resource.py    From daf-recipes with GNU General Public License v3.0 5 votes vote down vote up
def as_dict(self, core_columns_only=False):
        _dict = OrderedDict()
        cols = self.get_columns()
        if not core_columns_only:
            cols = ['id'] + cols + ['position']
        for col in cols:
            value = getattr(self, col)
            if isinstance(value, datetime.datetime):
                value = value.isoformat()
            _dict[col] = value
        for k, v in self.extras.items() if self.extras else []:
            _dict[k] = v
        if self.package_id and not core_columns_only:
            _dict["package_id"] = self.package_id
        return _dict 
Example #26
Source File: plugin.py    From daf-recipes with GNU General Public License v3.0 5 votes vote down vote up
def dataset_facets(self, facets_dict, package_type):

        if package_type <> 'harvest':
            return facets_dict

        return OrderedDict([('frequency', 'Frequency'),
                            ('source_type','Type'),
                           ]) 
Example #27
Source File: plugin.py    From daf-recipes with GNU General Public License v3.0 5 votes vote down vote up
def organization_facets(self, facets_dict, organization_type, package_type):

        if package_type <> 'harvest':
            return facets_dict

        return OrderedDict([('frequency', 'Frequency'),
                            ('source_type','Type'),
                           ]) 
Example #28
Source File: codegen.py    From safrs with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, table, association_tables, inflect_engine, detect_joined):
        super(ModelClass, self).__init__(table)
        self.name = self._tablename_to_classname(table.name, inflect_engine)
        self.children = []
        self.attributes = OrderedDict()

        # Assign attribute names for columns
        for column in table.columns:
            self._add_attribute(column.name, column)

        # Add many-to-one relationships
        pk_column_names = set(col.name for col in table.primary_key.columns)
        for constraint in sorted(table.constraints, key=_get_constraint_sort_key):
            if isinstance(constraint, ForeignKeyConstraint):
                target_cls = self._tablename_to_classname(constraint.elements[0].column.table.name, inflect_engine)
                if detect_joined and self.parent_name == "Base" and set(_get_column_names(constraint)) == pk_column_names:
                    self.parent_name = target_cls
                else:
                    relationship_ = ManyToOneRelationship(self.name, target_cls, constraint, inflect_engine)
                    self._add_attribute(relationship_.preferred_name, relationship_)

        # Add many-to-many relationships
        for association_table in association_tables:
            fk_constraints = [c for c in association_table.constraints if isinstance(c, ForeignKeyConstraint)]
            fk_constraints.sort(key=_get_constraint_sort_key)
            target_cls = self._tablename_to_classname(fk_constraints[1].elements[0].column.table.name, inflect_engine)
            relationship_ = ManyToManyRelationship(self.name, target_cls, association_table)
            self._add_attribute(relationship_.preferred_name, relationship_) 
Example #29
Source File: codegen.py    From safrs with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, source_cls, target_cls):
        super(Relationship, self).__init__()
        self.source_cls = source_cls
        self.target_cls = target_cls
        self.kwargs = OrderedDict() 
Example #30
Source File: batch.py    From alembic with MIT License 5 votes vote down vote up
def __init__(
        self,
        impl,
        table,
        table_args,
        table_kwargs,
        reflected,
        partial_reordering=(),
    ):
        self.impl = impl
        self.table = table  # this is a Table object
        self.table_args = table_args
        self.table_kwargs = table_kwargs
        self.temp_table_name = self._calc_temp_name(table.name)
        self.new_table = None

        self.partial_reordering = partial_reordering  # tuple of tuples
        self.add_col_ordering = ()  # tuple of tuples

        self.column_transfers = OrderedDict(
            (c.name, {"expr": c}) for c in self.table.c
        )
        self.existing_ordering = list(self.column_transfers)

        self.reflected = reflected
        self._grab_table_elements()