def save_to_sql(self, diff, engine):
        if not diff:
            # empty indicator document
            return

        default_key = (self.id,) + tuple(diff['group_values'])
        rows = {}

        def set_row_val(rowkey, col_name, col_value):
            row = rows.setdefault(rowkey, {})
            row[col_name] = col_value

        flat_keys = None
        try:
            flat_keys = self._flat_fields.keys()
        except __HOLE__:
            pass

        for change in diff['indicator_changes']:
            name = '{0}_{1}'.format(change['calculator'], change['emitter'])
            for value_dict in change['values']:
                value = value_dict['value']
                group_by = value_dict['group_by']
                date = value_dict['date']
                if group_by:
                    key = (self.id,) + tuple(group_by) + (date,)
                else:
                    key = default_key + (date,)
                set_row_val(key, name, value)
                for flat_key in flat_keys:
                    set_row_val(key, flat_key, self[flat_key])

        types = self.get_group_types()
        types['date'] = 'date'
        names = ['doc_id'] + self.get_group_names() + ['date']
        connection = engine.connect()
        try:
            # delete all existing rows for this doc to ensure we aren't left with stale data
            delete = self._table.delete(self._table.c.doc_id == self.id)
            connection.execute(delete)

            for key, columns in rows.items():
                key_columns = dict(zip(names, key))
                for name, value in key_columns.items():
                    if value is None:
                        key_columns[name] = default_null_value_placeholder(types[name])
                all_columns = dict(key_columns.items() + columns.items())

                try:
                    insert = self._table.insert().values(**all_columns)
                    connection.execute(insert)
                except sqlalchemy.exc.IntegrityError:
                    if columns:
                        update = self._table.update().values(**columns)
                        for k, v in key_columns.items():
                            update = update.where(self._table.c[k] == v)
                        connection.execute(update)
        finally:
            connection.close()
dataset/ETHPy150Open dimagi/commcare-hq/corehq/ex-submodules/fluff/indicators.py/IndicatorDocument.save_to_sql