Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

Refactored get_date_trunc_sql() to DatabaseOperations.date_trunc_sql(…

…). Refs #5106

git-svn-id: http://code.djangoproject.com/svn/django/trunk@5952 bcc190cf-cafb-0310-a4f2-bffc1f526a37
  • Loading branch information...
commit 5f51f0524a8cd941ea757a0339978f3589193cbb 1 parent aab04a4
Adrian Holovaty authored August 19, 2007
8  django/db/backends/__init__.py
@@ -60,3 +60,11 @@ def date_extract_sql(self, lookup_type, field_name):
60 60
         extracts a value from the given date field field_name.
61 61
         """
62 62
         raise NotImplementedError()
  63
+
  64
+    def date_trunc_sql(self, lookup_type, field_name):
  65
+        """
  66
+        Given a lookup_type of 'year', 'month' or 'day', returns the SQL that
  67
+        truncates the given date field field_name to a DATE object with only
  68
+        the given specificity.
  69
+        """
  70
+        raise NotImplementedError()
17  django/db/backends/ado_mssql/base.py
@@ -52,6 +52,14 @@ class DatabaseOperations(BaseDatabaseOperations):
52 52
     def date_extract_sql(self, lookup_type, field_name):
53 53
         return "DATEPART(%s, %s)" % (lookup_type, field_name)
54 54
 
  55
+    def date_trunc_sql(self, lookup_type, field_name):
  56
+        if lookup_type == 'year':
  57
+            return "Convert(datetime, Convert(varchar, DATEPART(year, %s)) + '/01/01')" % field_name
  58
+        if lookup_type == 'month':
  59
+            return "Convert(datetime, Convert(varchar, DATEPART(year, %s)) + '/' + Convert(varchar, DATEPART(month, %s)) + '/01')" % (field_name, field_name)
  60
+        if lookup_type == 'day':
  61
+            return "Convert(datetime, Convert(varchar(12), %s))" % field_name
  62
+
55 63
 class DatabaseWrapper(BaseDatabaseWrapper):
56 64
     ops = DatabaseOperations()
57 65
 
@@ -89,15 +97,6 @@ def get_last_insert_id(cursor, table_name, pk_name):
89 97
     cursor.execute("SELECT %s FROM %s WHERE %s = @@IDENTITY" % (pk_name, table_name, pk_name))
90 98
     return cursor.fetchone()[0]
91 99
 
92  
-def get_date_trunc_sql(lookup_type, field_name):
93  
-    # lookup_type is 'year', 'month', 'day'
94  
-    if lookup_type=='year':
95  
-        return "Convert(datetime, Convert(varchar, DATEPART(year, %s)) + '/01/01')" % field_name
96  
-    if lookup_type=='month':
97  
-        return "Convert(datetime, Convert(varchar, DATEPART(year, %s)) + '/' + Convert(varchar, DATEPART(month, %s)) + '/01')" % (field_name, field_name)
98  
-    if lookup_type=='day':
99  
-        return "Convert(datetime, Convert(varchar(12), %s))" % field_name
100  
-
101 100
 def get_datetime_cast_sql():
102 101
     return None
103 102
 
1  django/db/backends/dummy/base.py
@@ -44,7 +44,6 @@ def close(self):
44 44
 dictfetchmany = complain
45 45
 dictfetchall = complain
46 46
 get_last_insert_id = complain
47  
-get_date_trunc_sql = complain
48 47
 get_datetime_cast_sql = complain
49 48
 get_limit_offset_sql = complain
50 49
 get_random_function_sql = complain
27  django/db/backends/mysql/base.py
@@ -58,6 +58,19 @@ def date_extract_sql(self, lookup_type, field_name):
58 58
         # http://dev.mysql.com/doc/mysql/en/date-and-time-functions.html
59 59
         return "EXTRACT(%s FROM %s)" % (lookup_type.upper(), field_name)
60 60
 
  61
+    def date_trunc_sql(self, lookup_type, field_name):
  62
+        fields = ['year', 'month', 'day', 'hour', 'minute', 'second']
  63
+        format = ('%%Y-', '%%m', '-%%d', ' %%H:', '%%i', ':%%s') # Use double percents to escape.
  64
+        format_def = ('0000-', '01', '-01', ' 00:', '00', ':00')
  65
+        try:
  66
+            i = fields.index(lookup_type) + 1
  67
+        except ValueError:
  68
+            sql = field_name
  69
+        else:
  70
+            format_str = ''.join([f for f in format[:i]] + [f for f in format_def[i:]])
  71
+            sql = "CAST(DATE_FORMAT(%s, '%s') AS DATETIME)" % (field_name, format_str)
  72
+        return sql
  73
+
61 74
 class DatabaseWrapper(BaseDatabaseWrapper):
62 75
     ops = DatabaseOperations()
63 76
 
@@ -139,20 +152,6 @@ def quote_name(name):
139 152
 def get_last_insert_id(cursor, table_name, pk_name):
140 153
     return cursor.lastrowid
141 154
 
142  
-def get_date_trunc_sql(lookup_type, field_name):
143  
-    # lookup_type is 'year', 'month', 'day'
144  
-    fields = ['year', 'month', 'day', 'hour', 'minute', 'second']
145  
-    format = ('%%Y-', '%%m', '-%%d', ' %%H:', '%%i', ':%%s') # Use double percents to escape.
146  
-    format_def = ('0000-', '01', '-01', ' 00:', '00', ':00')
147  
-    try:
148  
-        i = fields.index(lookup_type) + 1
149  
-    except ValueError:
150  
-        sql = field_name
151  
-    else:
152  
-        format_str = ''.join([f for f in format[:i]] + [f for f in format_def[i:]])
153  
-        sql = "CAST(DATE_FORMAT(%s, '%s') AS DATETIME)" % (field_name, format_str)
154  
-    return sql
155  
-
156 155
 def get_datetime_cast_sql():
157 156
     return None
158 157
 
27  django/db/backends/mysql_old/base.py
@@ -68,6 +68,19 @@ def date_extract_sql(self, lookup_type, field_name):
68 68
         # http://dev.mysql.com/doc/mysql/en/date-and-time-functions.html
69 69
         return "EXTRACT(%s FROM %s)" % (lookup_type.upper(), field_name)
70 70
 
  71
+    def date_trunc_sql(self, lookup_type, field_name):
  72
+        fields = ['year', 'month', 'day', 'hour', 'minute', 'second']
  73
+        format = ('%%Y-', '%%m', '-%%d', ' %%H:', '%%i', ':%%s') # Use double percents to escape.
  74
+        format_def = ('0000-', '01', '-01', ' 00:', '00', ':00')
  75
+        try:
  76
+            i = fields.index(lookup_type) + 1
  77
+        except ValueError:
  78
+            sql = field_name
  79
+        else:
  80
+            format_str = ''.join([f for f in format[:i]] + [f for f in format_def[i:]])
  81
+            sql = "CAST(DATE_FORMAT(%s, '%s') AS DATETIME)" % (field_name, format_str)
  82
+        return sql
  83
+
71 84
 class DatabaseWrapper(BaseDatabaseWrapper):
72 85
     ops = DatabaseOperations()
73 86
 
@@ -158,20 +171,6 @@ def quote_name(name):
158 171
 def get_last_insert_id(cursor, table_name, pk_name):
159 172
     return cursor.lastrowid
160 173
 
161  
-def get_date_trunc_sql(lookup_type, field_name):
162  
-    # lookup_type is 'year', 'month', 'day'
163  
-    fields = ['year', 'month', 'day', 'hour', 'minute', 'second']
164  
-    format = ('%%Y-', '%%m', '-%%d', ' %%H:', '%%i', ':%%s') # Use double percents to escape.
165  
-    format_def = ('0000-', '01', '-01', ' 00:', '00', ':00')
166  
-    try:
167  
-        i = fields.index(lookup_type) + 1
168  
-    except ValueError:
169  
-        sql = field_name
170  
-    else:
171  
-        format_str = ''.join([f for f in format[:i]] + [f for f in format_def[i:]])
172  
-        sql = "CAST(DATE_FORMAT(%s, '%s') AS DATETIME)" % (field_name, format_str)
173  
-    return sql
174  
-
175 174
 def get_datetime_cast_sql():
176 175
     return None
177 176
 
19  django/db/backends/oracle/base.py
@@ -42,6 +42,15 @@ def date_extract_sql(self, lookup_type, field_name):
42 42
         # http://download-east.oracle.com/docs/cd/B10501_01/server.920/a96540/functions42a.htm#1017163
43 43
         return "EXTRACT(%s FROM %s)" % (lookup_type, field_name)
44 44
 
  45
+    def date_trunc_sql(self, lookup_type, field_name):
  46
+        # Oracle uses TRUNC() for both dates and numbers.
  47
+        # http://download-east.oracle.com/docs/cd/B10501_01/server.920/a96540/functions155a.htm#SQLRF06151
  48
+        if lookup_type == 'day':
  49
+            sql = 'TRUNC(%s)' % field_name
  50
+        else:
  51
+            sql = "TRUNC(%s, '%s')" % (field_name, lookup_type)
  52
+        return sql
  53
+
45 54
 class DatabaseWrapper(BaseDatabaseWrapper):
46 55
     ops = DatabaseOperations()
47 56
 
@@ -157,16 +166,6 @@ def get_last_insert_id(cursor, table_name, pk_name):
157 166
     cursor.execute('SELECT %s_sq.currval FROM dual' % sq_name)
158 167
     return cursor.fetchone()[0]
159 168
 
160  
-def get_date_trunc_sql(lookup_type, field_name):
161  
-    # lookup_type is 'year', 'month', 'day'
162  
-    # Oracle uses TRUNC() for both dates and numbers.
163  
-    # http://download-east.oracle.com/docs/cd/B10501_01/server.920/a96540/functions155a.htm#SQLRF06151
164  
-    if lookup_type == 'day':
165  
-        sql = 'TRUNC(%s)' % (field_name,)
166  
-    else:
167  
-        sql = "TRUNC(%s, '%s')" % (field_name, lookup_type)
168  
-    return sql
169  
-
170 169
 def get_datetime_cast_sql():
171 170
     return "TO_TIMESTAMP(%s, 'YYYY-MM-DD HH24:MI:SS.FF')"
172 171
 
9  django/db/backends/postgresql/base.py
@@ -62,6 +62,10 @@ def date_extract_sql(self, lookup_type, field_name):
62 62
         # http://www.postgresql.org/docs/8.0/static/functions-datetime.html#FUNCTIONS-DATETIME-EXTRACT
63 63
         return "EXTRACT('%s' FROM %s)" % (lookup_type, field_name)
64 64
 
  65
+    def date_trunc_sql(self, lookup_type, field_name):
  66
+        # http://www.postgresql.org/docs/8.0/static/functions-datetime.html#FUNCTIONS-DATETIME-TRUNC
  67
+        return "DATE_TRUNC('%s', %s)" % (lookup_type, field_name)
  68
+
65 69
 class DatabaseWrapper(BaseDatabaseWrapper):
66 70
     ops = DatabaseOperations()
67 71
 
@@ -124,11 +128,6 @@ def get_last_insert_id(cursor, table_name, pk_name):
124 128
     cursor.execute("SELECT CURRVAL('\"%s_%s_seq\"')" % (table_name, pk_name))
125 129
     return cursor.fetchone()[0]
126 130
 
127  
-def get_date_trunc_sql(lookup_type, field_name):
128  
-    # lookup_type is 'year', 'month', 'day'
129  
-    # http://www.postgresql.org/docs/8.0/static/functions-datetime.html#FUNCTIONS-DATETIME-TRUNC
130  
-    return "DATE_TRUNC('%s', %s)" % (lookup_type, field_name)
131  
-
132 131
 def get_datetime_cast_sql():
133 132
     return None
134 133
 
9  django/db/backends/postgresql_psycopg2/base.py
@@ -24,6 +24,10 @@ def date_extract_sql(self, lookup_type, field_name):
24 24
         # http://www.postgresql.org/docs/8.0/static/functions-datetime.html#FUNCTIONS-DATETIME-EXTRACT
25 25
         return "EXTRACT('%s' FROM %s)" % (lookup_type, field_name)
26 26
 
  27
+    def date_trunc_sql(self, lookup_type, field_name):
  28
+        # http://www.postgresql.org/docs/8.0/static/functions-datetime.html#FUNCTIONS-DATETIME-TRUNC
  29
+        return "DATE_TRUNC('%s', %s)" % (lookup_type, field_name)
  30
+
27 31
 class DatabaseWrapper(BaseDatabaseWrapper):
28 32
     ops = DatabaseOperations()
29 33
 
@@ -78,11 +82,6 @@ def get_last_insert_id(cursor, table_name, pk_name):
78 82
     cursor.execute("SELECT CURRVAL('\"%s_%s_seq\"')" % (table_name, pk_name))
79 83
     return cursor.fetchone()[0]
80 84
 
81  
-def get_date_trunc_sql(lookup_type, field_name):
82  
-    # lookup_type is 'year', 'month', 'day'
83  
-    # http://www.postgresql.org/docs/8.0/static/functions-datetime.html#FUNCTIONS-DATETIME-TRUNC
84  
-    return "DATE_TRUNC('%s', %s)" % (lookup_type, field_name)
85  
-
86 85
 def get_datetime_cast_sql():
87 86
     return None
88 87
 
12  django/db/backends/sqlite3/base.py
@@ -37,9 +37,14 @@
37 37
 class DatabaseOperations(BaseDatabaseOperations):
38 38
     def date_extract_sql(self, lookup_type, field_name):
39 39
         # sqlite doesn't support extract, so we fake it with the user-defined
40  
-        # function _sqlite_extract that's registered in connect().
  40
+        # function django_extract that's registered in connect().
41 41
         return 'django_extract("%s", %s)' % (lookup_type.lower(), field_name)
42 42
 
  43
+    def date_trunc_sql(self, lookup_type, field_name):
  44
+        # sqlite doesn't support DATE_TRUNC, so we fake it with a user-defined
  45
+        # function django_date_trunc that's registered in connect().
  46
+        return 'django_date_trunc("%s", %s)' % (lookup_type.lower(), field_name)
  47
+
43 48
 class DatabaseWrapper(BaseDatabaseWrapper):
44 49
     ops = DatabaseOperations()
45 50
 
@@ -110,11 +115,6 @@ def _sqlite_extract(lookup_type, dt):
110 115
         return None
111 116
     return str(getattr(dt, lookup_type))
112 117
 
113  
-def get_date_trunc_sql(lookup_type, field_name):
114  
-    # lookup_type is 'year', 'month', 'day'
115  
-    # sqlite doesn't support DATE_TRUNC, so we fake it as above.
116  
-    return 'django_date_trunc("%s", %s)' % (lookup_type.lower(), field_name)
117  
-
118 118
 def get_datetime_cast_sql():
119 119
     return None
120 120
 
5  django/db/models/query.py
@@ -647,11 +647,10 @@ def iterator(self):
647 647
         if backend.allows_group_by_ordinal:
648 648
             group_by = '1'
649 649
         else:
650  
-            group_by = backend.get_date_trunc_sql(self._kind,
651  
-                                                  '%s.%s' % (table_name, field_name))
  650
+            group_by = connection.ops.date_trunc_sql(self._kind, '%s.%s' % (table_name, field_name))
652 651
 
653 652
         sql = 'SELECT %s %s GROUP BY %s ORDER BY 1 %s' % \
654  
-            (backend.get_date_trunc_sql(self._kind, '%s.%s' % (backend.quote_name(self.model._meta.db_table),
  653
+            (connection.ops.date_trunc_sql(self._kind, '%s.%s' % (backend.quote_name(self.model._meta.db_table),
655 654
             backend.quote_name(self._field.column))), sql, group_by, self._order)
656 655
         cursor = connection.cursor()
657 656
         cursor.execute(sql, params)

0 notes on commit 5f51f05

Please sign in to comment.
Something went wrong with that request. Please try again.