Bobochka
7/16/2017 - 12:47 PM

Bulk insert POC

Bulk insert POC

func BulkInsert(table string, columns []string, bindings [][]interface{}, onConflict ...string) error {
	valueGroups := []string{}
	values := []interface{}{}

	valueGroup := buildPlaceholderGroup(len(columns))

	for _, row := range bindings {
		valueGroups = append(valueGroups, valueGroup)
		values = append(values, row...)
	}

	suffix := ""
	if len(onConflict) > 0 {
		suffix = onConflict[0]
	}

	stmt := fmt.Sprintf("INSERT INTO %s (%s) VALUES %s %s;",
		table, strings.Join(columns, ","), strings.Join(valueGroups, ","), suffix)

	return DB.Exec(stmt, values...).Error
}

func buildPlaceholderGroup(n int) string {
	arr := make([]string, n)
	for i := 0; i < n; i++ {
		arr[i] = "?"
	}
	return fmt.Sprintf("(%s)", strings.Join(arr, ","))
}