~evanj/cms

ref: ed17a2199584ba94d1ca44e9002b52c48b2c02fa cms/internal/s/db/action.go -rw-r--r-- 1.3 KiB
ed17a219Evan J Feat(context): Thread context throughout data layer. TODO: Update 1 year, 14 days ago
                                                                                
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
package db

import (
	"context"
	"database/sql"
	"time"

	"git.sr.ht/~evanj/cms/internal/m/org"
)

func (db *DB) ActionNew(ctx context.Context, o org.Org, at time.Time) error {
	t, err := db.BeginTx(ctx, nil)
	if err != nil {
		return err
	}
	defer t.Rollback()

	if err := db.actionNew(ctx, t, o, at); err != nil {
		return err
	}

	return t.Commit()
}

func (db *DB) actionNew(ctx context.Context, t *sql.Tx, o org.Org, at time.Time) error {
	_, err := t.ExecContext(ctx, "INSERT INTO cms_action (ORG_ID, AT) VALUES (?, ?)", o.ID(), at.Format("2006-01-02 03:04:05"))
	return err
}

func (db *DB) ActionGetCount(ctx context.Context, o org.Org, from, to time.Time) (int, error) {
	t, err := db.BeginTx(ctx, nil)
	if err != nil {
		return 0, err
	}
	defer t.Rollback()

	i, err := db.actionGetCount(ctx, t, o, from, to)
	if err != nil {
		return 0, err
	}

	return i, t.Commit()
}

func (db *DB) actionGetCount(ctx context.Context, t *sql.Tx, o org.Org, from, to time.Time) (int, error) {
	var (
		count int
		q     = "SELECT COUNT(*) FROM cms_action WHERE cms_action.ORG_ID=? AND AT>? AND AT<?"
	)

	a := from.Format("2006-01-02 03:04:05")
	b := to.Format("2006-01-02 03:04:05")
	if err := t.QueryRowContext(ctx, q, o.ID(), a, b).Scan(&count); err != nil {
		return 0, err
	}

	return count, nil
}