This repository was archived by the owner on Apr 29, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtimerange.go
More file actions
83 lines (76 loc) · 2.43 KB
/
timerange.go
File metadata and controls
83 lines (76 loc) · 2.43 KB
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package typeid
import (
"database/sql/driver"
"fmt"
"time"
)
// TimeRange holds optional floor/ceil bounds for time-based ID range queries
// against a primary key column. It satisfies squirrel.Sqlizer structurally
// via [TimeRange.ToSql], so it can be passed directly to squirrel.Where
// without importing squirrel in this package.
//
// Construct via [UUIDRange] or [Int64Range].
type TimeRange struct {
column string
floor driver.Valuer
ceil driver.Valuer
}
// UUIDRange builds a [TimeRange] that brackets column with [FloorUUID] / [CeilUUID].
// Nil since or until leaves that side unbounded.
func UUIDRange[P Prefixer](column string, since, until *time.Time) TimeRange {
r := TimeRange{column: column}
if since != nil {
r.floor = floorUUID[P](*since)
}
if until != nil {
r.ceil = ceilUUID[P](*until)
}
return r
}
// Int64Range builds a [TimeRange] that brackets column with [FloorInt64] / [CeilInt64].
// Nil since or until leaves that side unbounded.
func Int64Range[P Prefixer](column string, since, until *time.Time) TimeRange {
r := TimeRange{column: column}
if since != nil {
r.floor = floorInt64[P](*since)
}
if until != nil {
r.ceil = ceilInt64[P](*until)
}
return r
}
// Floor returns the lower-bound ID and true, or (nil, false) if unbounded.
func (r TimeRange) Floor() (driver.Valuer, bool) { return r.floor, r.floor != nil }
// Ceil returns the upper-bound ID and true, or (nil, false) if unbounded.
func (r TimeRange) Ceil() (driver.Valuer, bool) { return r.ceil, r.ceil != nil }
// ToSql emits a SQL predicate and bind args for the range.
// Returns "column BETWEEN ? AND ?", "column >= ?", "column <= ?",
// or "1=1" depending on which bounds are set.
func (r TimeRange) ToSql() (string, []any, error) {
switch {
case r.floor != nil && r.ceil != nil:
fv, err := r.floor.Value()
if err != nil {
return "", nil, fmt.Errorf("typeid: floor value: %w", err)
}
cv, err := r.ceil.Value()
if err != nil {
return "", nil, fmt.Errorf("typeid: ceil value: %w", err)
}
return r.column + " BETWEEN ? AND ?", []any{fv, cv}, nil
case r.floor != nil:
fv, err := r.floor.Value()
if err != nil {
return "", nil, fmt.Errorf("typeid: floor value: %w", err)
}
return r.column + " >= ?", []any{fv}, nil
case r.ceil != nil:
cv, err := r.ceil.Value()
if err != nil {
return "", nil, fmt.Errorf("typeid: ceil value: %w", err)
}
return r.column + " <= ?", []any{cv}, nil
default:
return "1=1", nil, nil
}
}