1 Commits

Author SHA1 Message Date
4b5dc8e71a Distinct 2018-10-09 10:25:56 +02:00

View File

@@ -241,6 +241,7 @@ class SQLQuery(object):
self._limits = None self._limits = None
self._sql = sql self._sql = sql
self._nolock = False self._nolock = False
self._distinct = False
def has_filters(self,): def has_filters(self,):
return self._order_by or self._group_by or self._joins\ return self._order_by or self._group_by or self._joins\
@@ -272,6 +273,11 @@ class SQLQuery(object):
clone._nolock = enabled clone._nolock = enabled
return clone return clone
def distinct(self, enabled=True):
clone = self._clone()
clone._distinct = enabled
return clone
def filter(self, *args, **kwargs): def filter(self, *args, **kwargs):
clone = self._clone() clone = self._clone()
clone._filters &= self._q(*args, **kwargs) clone._filters &= self._q(*args, **kwargs)
@@ -292,9 +298,6 @@ class SQLQuery(object):
clone._group_by = args clone._group_by = args
return clone return clone
def first(self):
return self[:1]
def join(self, table, on="", how="inner join"): def join(self, table, on="", how="inner join"):
clone = self._clone() clone = self._clone()
if on: if on:
@@ -377,6 +380,11 @@ class SQLCompiler(object):
return " WITH (NOLOCK)" return " WITH (NOLOCK)"
return "" return ""
def get_distinct(self,):
if self._distinct:
return " DISTINCT "
return ""
def get_limits(self,): def get_limits(self,):
if self._limits and self.sql_mode != "SQL_SERVER": if self._limits and self.sql_mode != "SQL_SERVER":
offset = self._limits.start offset = self._limits.start
@@ -400,7 +408,10 @@ class SQLCompiler(object):
else: else:
table = self.get_table() table = self.get_table()
sql = ["SELECT", self.get_top(), self.get_columns(), sql = ["SELECT",
self.get_distinct(),
self.get_top(),
self.get_columns(),
"FROM", table, "FROM", table,
self.get_nolock(), self.get_nolock(),
self.get_joins(), self.get_where(), self.get_joins(), self.get_where(),
@@ -426,31 +437,6 @@ class SQLCompiler(object):
self.get_group_by(), self.get_group_by(),
self.get_limits(), ") as tbl_paginated WHERE ", conds] self.get_limits(), ") as tbl_paginated WHERE ", conds]
if self.sql_mode == "ACCESS" and self._limits and \
self._limits.start is not None and self._limits.stop is not None:
conds = []
if self._limits.start is not None:
conds.append("row_number > %s" % self._limits.start)
if self._limits.stop is not None:
conds.append("row_number <= %s" % self._limits.stop)
conds = " AND ".join(conds)
count = "(select count(*) FROM {table} as t2 WHERE t2.{id} <= {table}.{id}) as row_number".format(table=table,
id=self._order_by[0])
return ["SELECT * FROM (", "SELECT", self.get_columns(), ",",
count,
# "FROM",
# table,
self.get_joins(),
self.get_where(),
self.get_group_by(),
" FROM ",
table,
") WHERE ", conds]
return sql return sql
def _compile(self): def _compile(self):