def convert_domain_tree(self, domain, tables): Target = self.get_target() target = Target.__table__() table, _ = tables[None] name, operator, ids = domain red_sql = reduce_ids(target.id, (i for i in ids if i is not None)) if operator.endswith('child_of'): tree = With('id', recursive=True) tree.query = target.select(target.id, where=red_sql) tree.query |= (target .join(tree, condition=Column(target, name) == tree.id) .select(target.id)) else: tree = With('id', name, recursive=True) tree.query = target.select( target.id, Column(target, name), where=red_sql) tree.query |= (target .join(tree, condition=target.id == Column(tree, name)) .select(target.id, Column(target, name))) expression = table.id.in_(tree.select(tree.id, with_=[tree])) if operator.startswith('not'): return ~expression return expression
def test_with_query(self): with AliasManager(): simple = With() simple.query = self.table.select(self.table.id, where=self.table.id == 1) second = With() second.query = simple.select() wq = WithQuery(with_=[simple, second]) self.assertEqual(wq._with_str(), 'WITH "a" AS (' 'SELECT "b"."id" FROM "t" AS "b" WHERE ("b"."id" = %s)' '), "c" AS (' 'SELECT * FROM "a" AS "a"' ') ') self.assertEqual(wq._with_params(), (1,))
def test_with_query(self): with AliasManager(): simple = With() simple.query = self.table.select(self.table.id, where=self.table.id == 1) second = With() second.query = simple.select() wq = WithQuery(with_=[simple, second]) self.assertEqual( wq._with_str(), 'WITH "a" AS (' 'SELECT "b"."id" FROM "t" AS "b" WHERE ("b"."id" = %s)' '), "c" AS (' 'SELECT * FROM "a" AS "a"' ') ') self.assertEqual(wq._with_params(), (1, ))
def group_parent_all_cte(cls): group = cls.__table__() parents = With('id', 'parent', recursive=True) parents.query = group.select(group.id, group.parent) parents.query |= group.select(group.id, group.id) parents.query |= (group .join(parents, condition=group.parent == parents.id) .select(group.id, parents.parent)) return parents
def test_recursive(self): upto10 = With('n', recursive=True) upto10.query = Values([(1, )]) upto10.query |= upto10.select(upto10.n + Literal(1), where=upto10.n < Literal(100)) upto10.query.all_ = True q = upto10.select(with_=[upto10]) self.assertEqual( str(q), 'WITH RECURSIVE "a" ("n") AS (' 'VALUES (%s) ' 'UNION ALL ' 'SELECT ("a"."n" + %s) FROM "a" AS "a" WHERE ("a"."n" < %s)' ') SELECT * FROM "a" AS "a"') self.assertEqual(q.params, (1, 1, 100))
def test_recursive(self): upto10 = With('n', recursive=True) upto10.query = Values([(1,)]) upto10.query |= upto10.select( upto10.n + Literal(1), where=upto10.n < Literal(100)) upto10.query.all_ = True q = upto10.select(with_=[upto10]) self.assertEqual(str(q), 'WITH RECURSIVE "a"("n") AS (' 'VALUES (%s) ' 'UNION ALL ' 'SELECT ("a"."n" + %s) FROM "a" AS "a" WHERE ("a"."n" < %s)' ') SELECT * FROM "a" AS "a"') self.assertEqual(q.params, (1, 1, 100))