Skip to content

Commit 0353f3c

Browse files
committed
add union() and union_select() methods
1 parent 1b6bf62 commit 0353f3c

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

simple_query_builder/querybuilder.py

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -624,6 +624,38 @@ def join(self, table: Union[str, dict] = "", on: Union[str, tuple, list] = (), j
624624
self.set_error()
625625
return self
626626

627+
def union(self, union_all: bool = False):
628+
self._concat = True
629+
self._sql += " UNION ALL " if union_all else " UNION "
630+
return self
631+
632+
def union_select(self, table: Union[str, dict], union_all: bool = False):
633+
if not table:
634+
self.set_error(f"Empty table in {inspect.stack()[0][3]} method")
635+
return self
636+
637+
if 'UNION' in self._sql:
638+
self.set_error(f"SQL has already UNION in {inspect.stack()[0][3]} method")
639+
return self
640+
641+
self._concat = True
642+
fields = self._fields
643+
self._sql += " UNION ALL " if union_all else " UNION "
644+
645+
if isinstance(fields, dict) or isinstance(fields, list) or isinstance(fields, str):
646+
self._sql += f"SELECT {self._prepare_aliases(fields)}"
647+
else:
648+
self.set_error(f"Incorrect type of fields in {inspect.stack()[0][3]} method. Fields must be String, List or Dictionary")
649+
return self
650+
651+
if isinstance(table, dict) or isinstance(table, str):
652+
self._sql += f" FROM {self._prepare_aliases(table)}"
653+
else:
654+
self.set_error(f"Incorrect type of table in {inspect.stack()[0][3]} method. Table must be String or Dictionary")
655+
return self
656+
657+
return self
658+
627659
def drop(self, table: str, add_exists: bool = True):
628660
# this method will be moved to another class
629661
if not table:

0 commit comments

Comments
 (0)