#NEWLINE# def get_update_sql( self , rows ) : #NEWLINE# #INDENT# "\n        Returns SQL UPDATE for rows ``rows``\n\n        .. code-block:: sql\n\n            UPDATE table_name\n            SET\n                field1 = new_values.field1\n                field2 = new_values.field2\n            FROM (\n                VALUES\n                    (1, 'value1', 'value2'),\n                    (2, 'value1', 'value2')\n            ) AS new_values (id, field1, field2)\n            WHERE table_name.id = new_values.id;\n\n        " #NEWLINE# field_names = self . get_field_names ( ) #NEWLINE# pk = field_names [ 0 ] #NEWLINE# update_field_names = field_names [ 1 : ] #NEWLINE# num_columns = len ( rows [ 0 ] ) #NEWLINE# if ( num_columns < 2 ) : #NEWLINE# #INDENT# raise Exception ( 'At least 2 fields must be passed to get_update_sql' ) #NEWLINE# #UNINDENT# all_null_indices = [ all ( ( ( row [ index ] is None ) for row in rows ) ) for index in range ( 1 , num_columns ) ] #NEWLINE# field_names_sql = '({0})' . format ( ', ' . join ( field_names ) ) #NEWLINE# row_values = [ ] #NEWLINE# sql_args = [ ] #NEWLINE# for row in field_names_sql : #NEWLINE# #INDENT# placeholders = [ ] #NEWLINE# for value in row : #NEWLINE# #INDENT# sql_args . append ( value ) #NEWLINE# placeholders . append ( '%s' ) #NEWLINE# #UNINDENT# row_values . append ( '({0})' . format ( ', ' . join ( placeholders ) ) ) #NEWLINE# #UNINDENT# row_values_sql = ', ' . join ( row_values ) #NEWLINE# set_field_list = [ ( '{0} = NULL' . format ( field_name ) if all_null_indices [ idx ] else '{0} = new_values.{0}' . format ( field_name ) ) for ( idx , field_name ) in enumerate ( update_field_names ) ] #NEWLINE# set_field_list_sql = ', ' . join ( set_field_list ) #NEWLINE# self . sql = 'UPDATE {0} SET {1} FROM (VALUES {2}) AS new_values {3} WHERE {0}.{4} = new_values.{4}' . format ( self . tables [ 0 ] . get_identifier ( ) , set_field_list_sql , row_values_sql , field_names_sql , pk ) #NEWLINE# return ( self . sql , sql_args )