

def generate_insert(self, query):
    model = query.model_class
    meta = model._meta
    alias_map = self.alias_map_class()
    alias_map.add(model, model._meta.db_table)
    if query._upsert:
        statement = meta.database.upsert_sql
    elif query._on_conflict:
        statement = ('INSERT OR %s INTO' % query._on_conflict)
    else:
        statement = 'INSERT INTO'
    clauses = [SQL(statement), model.as_entity()]
    if (query._query is not None):
        if query._fields:
            clauses.append(self._get_field_clause(query._fields))
        clauses.append(_StripParens(query._query))
    elif (query._rows is not None):
        (fields, value_clauses) = ([], [])
        have_fields = False
        for row_dict in query._iter_rows():
            if (not have_fields):
                fields = sorted(row_dict.keys(), key=operator.attrgetter('_sort_key'))
                have_fields = True
            values = []
            for field in fields:
                value = row_dict[field]
                if (not isinstance(value, (Node, Model))):
                    value = Param(value, conv=field.db_value)
                values.append(value)
            value_clauses.append(EnclosedClause(*values))
        if fields:
            clauses.extend([self._get_field_clause(fields), SQL('VALUES'), CommaClause(*value_clauses)])
        elif query.model_class._meta.auto_increment:
            clauses.append(query.database.default_insert_clause(query.model_class))
    if query.is_insert_returning:
        clauses.extend([SQL('RETURNING'), self._get_field_clause(meta.get_primary_key_fields(), clause_type=CommaClause)])
    elif (query._returning is not None):
        returning_clause = Clause(*query._returning)
        returning_clause.glue = ', '
        clauses.extend([SQL('RETURNING'), returning_clause])
    return self.build_query(clauses, alias_map)

dataset/ETHPy150Open coleifer/peewee/peewee.py QueryCompiler.generate_insert/original