Files
davidandClaude Opus 5.5 1b2947de7c Phase 9, part 2: one database layer for SQLite and Postgres
db.DB wraps database/sql for either database. The SQL stays SQLite's: on
Postgres each statement's ? become $n and LIKE ignores case as SQLite's
does, and the Postgres schema (postgres.sql, schema 29 as a whole) adds
SQLite's instr, json_extract and two-argument max/min, and a nocase ICU
collation. Needs Postgres 18.

LastInsertId became db.Insert (RETURNING id), INSERT OR IGNORE became ON
CONFLICT DO NOTHING, upserts qualify their columns, and three queries
group by every column they use. SUPERMARKET_TEST_POSTGRES runs the test
suite on Postgres, a new schema per test; all tests pass on both.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 07:10:44 -07:00

215 lines
6.0 KiB
Go

// Package signals keeps the buying signals (hypotheses about why a company
// buys now) and the funnel: every step someone takes, from being found to
// paying, recorded as an event tagged with a signal and a channel. The
// scorecard counts them, so signals can be tested against what was done
// for them, directly (email, LinkedIn) and indirectly (posts, pages).
package signals
import (
"database/sql"
"errors"
"fmt"
"strings"
"time"
"supermarket/internal/db"
"supermarket/internal/slug"
)
// Statuses of a signal, in order.
const (
StatusIdea = "idea"
StatusTesting = "testing"
StatusProven = "proven"
StatusRetired = "retired"
)
var Statuses = []string{StatusIdea, StatusTesting, StatusProven, StatusRetired}
// Signal is one buying signal.
type Signal struct {
ID int64
Slug string // utm_campaign
Name string
Hypothesis string
Spot string // how to find it: queries and keywords, one per line
Angle string // the pain and promise for messages and content
Status string
CreatedAt time.Time
UpdatedAt time.Time
DiscoverEveryDays int // find companies on a schedule; 0: only by hand
ExpleeDefinition string // what the companies do, for explee.com's search
}
// SpotLines are the non-empty lines of Spot.
func (s *Signal) SpotLines() []string {
var out []string
for _, l := range strings.Split(s.Spot, "\n") {
if l = strings.TrimSpace(l); l != "" {
out = append(out, l)
}
}
return out
}
// ErrNotFound means there's no signal with that ID.
var ErrNotFound = errors.New("no such signal")
const timeFormat = time.RFC3339
func formatTime(t time.Time) string { return t.UTC().Format(timeFormat) }
// Slugify makes a utm_campaign-safe slug from a name.
func Slugify(name string) string {
s := slug.Make(name)
if len(s) > 60 {
s = strings.TrimRight(s[:60], "-")
}
return s
}
func validStatus(s string) bool {
for _, st := range Statuses {
if s == st {
return true
}
}
return false
}
// Save creates or updates a signal. An empty slug is made from the name;
// slugs are unique, so a taken one gets a number.
func Save(d *db.DB, s *Signal) error {
s.Name = strings.TrimSpace(s.Name)
s.Hypothesis = strings.TrimSpace(s.Hypothesis)
s.Spot = strings.TrimSpace(s.Spot)
s.Angle = strings.TrimSpace(s.Angle)
s.ExpleeDefinition = strings.TrimSpace(s.ExpleeDefinition)
if s.DiscoverEveryDays < 0 {
s.DiscoverEveryDays = 0
}
if s.Name == "" {
return errors.New("a signal needs a name")
}
if s.Status == "" {
s.Status = StatusIdea
}
if !validStatus(s.Status) {
return fmt.Errorf("unknown status %q", s.Status)
}
s.Slug = Slugify(s.Slug)
if s.Slug == "" {
s.Slug = Slugify(s.Name)
}
if s.Slug == "" {
return errors.New("the name needs some letters or digits, for the campaign tag")
}
base := s.Slug
for i := 2; ; i++ {
var other int64
err := d.QueryRow(`SELECT id FROM signals WHERE slug = ?`, s.Slug).Scan(&other)
if errors.Is(err, sql.ErrNoRows) || other == s.ID {
break
}
if err != nil {
return err
}
s.Slug = fmt.Sprintf("%s-%d", base, i)
}
now := formatTime(time.Now())
if s.ID == 0 {
newID, err := d.Insert(`INSERT INTO signals (slug, name, hypothesis, spot, angle, status, created_at, updated_at,
discover_every_days, explee_definition) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
s.Slug, s.Name, s.Hypothesis, s.Spot, s.Angle, s.Status, now, now, s.DiscoverEveryDays, s.ExpleeDefinition)
if err != nil {
return err
}
s.ID = newID
return err
}
res, err := d.Exec(`UPDATE signals SET slug = ?, name = ?, hypothesis = ?, spot = ?, angle = ?, status = ?, updated_at = ?,
discover_every_days = ?, explee_definition = ? WHERE id = ?`,
s.Slug, s.Name, s.Hypothesis, s.Spot, s.Angle, s.Status, now, s.DiscoverEveryDays, s.ExpleeDefinition, s.ID)
if err != nil {
return err
}
if n, _ := res.RowsAffected(); n == 0 {
return ErrNotFound
}
return nil
}
// Delete removes a signal. Its prospects, campaigns and events stay, without
// a signal.
func Delete(d *db.DB, id int64) error {
_, err := d.Exec(`DELETE FROM signals WHERE id = ?`, id)
return err
}
const columns = `id, slug, name, hypothesis, spot, angle, status, created_at, updated_at, discover_every_days, explee_definition`
func scan(rows *sql.Rows) ([]Signal, error) {
defer rows.Close()
var out []Signal
for rows.Next() {
var s Signal
var created, updated string
if err := rows.Scan(&s.ID, &s.Slug, &s.Name, &s.Hypothesis, &s.Spot, &s.Angle, &s.Status, &created, &updated,
&s.DiscoverEveryDays, &s.ExpleeDefinition); err != nil {
return nil, err
}
s.CreatedAt, _ = time.Parse(timeFormat, created)
s.UpdatedAt, _ = time.Parse(timeFormat, updated)
out = append(out, s)
}
return out, rows.Err()
}
// Get returns one signal.
func Get(d *db.DB, id int64) (*Signal, error) {
rows, err := d.Query(`SELECT `+columns+` FROM signals WHERE id = ?`, id)
if err != nil {
return nil, err
}
ss, err := scan(rows)
if err != nil {
return nil, err
}
if len(ss) == 0 {
return nil, ErrNotFound
}
return &ss[0], nil
}
// List returns every signal: in testing first, then ideas, proven and
// retired; by name within each.
func List(d *db.DB) ([]Signal, error) {
rows, err := d.Query(`SELECT ` + columns + ` FROM signals ORDER BY
CASE status WHEN 'testing' THEN 0 WHEN 'idea' THEN 1 WHEN 'proven' THEN 2 ELSE 3 END, name COLLATE NOCASE`)
if err != nil {
return nil, err
}
return scan(rows)
}
// Search finds signals containing every (lower-case) word.
func Search(d *db.DB, words []string, limit int) ([]Signal, error) {
if len(words) == 0 {
return nil, nil
}
hay := "lower(name || ' ' || slug || ' ' || hypothesis || ' ' || spot || ' ' || angle)"
conds := make([]string, len(words))
args := make([]any, 0, len(words)+1)
for i, w := range words {
conds[i] = "instr(" + hay + ", ?) > 0"
args = append(args, w)
}
rows, err := d.Query(`SELECT `+columns+` FROM signals WHERE `+strings.Join(conds, " AND ")+` ORDER BY name LIMIT ?`,
append(args, limit)...)
if err != nil {
return nil, err
}
return scan(rows)
}