A website inspired by Last.fm that will keep track of your listening statistics
lastfm music statistics
at main 55 lines 1.1 kB view raw
1package database 2 3import ( 4 "context" 5 "database/sql" 6 "fmt" 7 "slices" 8 "strings" 9) 10 11type insertOptions struct { 12 ignore bool 13} 14 15type InsertOption func(*insertOptions) 16 17func WithIgnore() InsertOption { 18 return func(o *insertOptions) { 19 o.ignore = true 20 } 21} 22 23func Insert(ctx context.Context, db *sql.DB, table string, values map[string]any, opts ...InsertOption) (int, error) { 24 var ( 25 id int 26 args []any 27 columns []string 28 ) 29 statement := /*sql*/ ` 30 INSERT %s INTO %s (%s) VALUES (%s) RETURNING id 31 ` 32 33 options := insertOptions{} 34 for _, opt := range opts { 35 opt(&options) 36 } 37 38 ignore := "" 39 if options.ignore { 40 ignore = "OR IGNORE" 41 } 42 43 for key, value := range values { 44 columns = append(columns, key) 45 args = append(args, value) 46 } 47 48 placeholders := strings.Join(slices.Repeat([]string{"?"}, len(values)), ", ") 49 statement = fmt.Sprintf(statement, ignore, table, strings.Join(columns, ", "), placeholders) 50 51 return QueryOne(ctx, db, statement, args, func(r *sql.Rows) (int, error) { 52 err := r.Scan(&id) 53 return id, err 54 }) 55}