summaryrefslogtreecommitdiff
path: root/dbutils/dbutils.go
blob: 4082efd017ee760681e3f79cfe3a64505cffad3d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package dbutils

import (
	"database/sql"
	"fmt"
	"strings"
)

func TxCommitIfOk(tx *sql.Tx, err error) error {
	if err != nil {
		if rollbackErr := tx.Rollback(); rollbackErr != nil {
			return fmt.Errorf("Failed rolling back transaction with error \"%s\" while handling error %w", rollbackErr, err)
		}

		return err
	} else {
		if err = tx.Commit(); err != nil {
			return err
		}

		return nil
	}
}

func BuildInIdsSqlAndArgs(field string, ids []int) (string, []interface{}) {
	if len(ids) == 0 {
		return "0", []interface{}{}
	}

	sb := new(strings.Builder)
	sb.WriteString(field)
	sb.WriteString(" IN (?")

	for i := 1; i < len(ids); i++ {
		sb.WriteString(",?")
	}
	sb.WriteRune(')')

	args := make([]interface{}, 0, len(ids))
	for _, id := range ids {
		args = append(args, interface{}(id))
	}

	return sb.String(), args
}

// GetIndexedValues
// func GetIndexedValues(db *sql.DB, m interface{}, query, args ...interface{}) error {
// 	mv := reflect.ValueOf(m)
// 	mt := mv.Type()
// 	if mt.Kind() != reflect.Map {
// 		panic("GetIndexValue needs a map as argument m")
// 	}
// 	if mt.

// 	rows, err := db.Query(query, args...)
// 	if err != nil {
// 		return err
// 	}
// }