@@ -277,7 +277,51 @@ def as_sql(self, with_limits=True, with_col_aliases=False):
277277
278278
279279class SQLInsertCompiler (compiler .SQLInsertCompiler , SQLCompiler ):
280+
281+ def as_sql_legacy (self ):
282+ # We don't need quote_name_unless_alias() here, since these are all
283+ # going to be column names (so we can avoid the extra overhead).
284+ qn = self .connection .ops .quote_name
285+ opts = self .query .model ._meta
286+ returns_id = bool (self .return_id and
287+ self .connection .features .can_return_id_from_insert )
288+
289+ result = ['INSERT INTO %s' % qn (opts .db_table )]
290+ result .append ('(%s)' % ', ' .join ([qn (c ) for c in self .query .columns ]))
291+
292+ if returns_id :
293+ result .append ('OUTPUT inserted.%s' % qn (opts .pk .column ))
294+
295+ values = [self .placeholder (* v ) for v in self .query .values ]
296+ result .append ('VALUES (%s)' % ', ' .join (values ))
297+
298+ params = self .query .params
299+ sql = ' ' .join (result )
300+
301+ meta = self .query .get_meta ()
302+ if meta .has_auto_field :
303+ # db_column is None if not explicitly specified by model field
304+ auto_field_column = meta .auto_field .db_column or meta .auto_field .column
305+
306+ if auto_field_column in self .query .columns :
307+ quoted_table = self .connection .ops .quote_name (meta .db_table )
308+
309+ if len (self .query .columns ) == 1 and not params :
310+ result = ['INSERT INTO %s' % quoted_table ]
311+ if returns_id :
312+ result .append ('OUTPUT inserted.%s' % qn (opts .pk .column ))
313+ result .append ('DEFAULT VALUES' )
314+ sql = ' ' .join (result )
315+ else :
316+ sql = "SET IDENTITY_INSERT %s ON;\n %s;\n SET IDENTITY_INSERT %s OFF" % \
317+ (quoted_table , sql , quoted_table )
318+
319+ return sql , params
320+
280321 def as_sql (self ):
322+ if self .connection ._DJANGO_VERSION < 14 :
323+ return self .as_sql_legacy ()
324+
281325 # We don't need quote_name_unless_alias() here, since these are all
282326 # going to be column names (so we can avoid the extra overhead).
283327 qn = self .connection .ops .quote_name
0 commit comments