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>
283 lines
8.5 KiB
Go
283 lines
8.5 KiB
Go
// Package inventory is the list of partners and competitors (and other
|
|
// projects worth watching) that content is built around. It replaces the old
|
|
// config's hard-coded `applications:` list.
|
|
package inventory
|
|
|
|
import (
|
|
"database/sql"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"strings"
|
|
"time"
|
|
|
|
"gopkg.in/yaml.v3"
|
|
|
|
"supermarket/internal/db"
|
|
"supermarket/internal/profile"
|
|
)
|
|
|
|
// Relationships an entry can have.
|
|
const (
|
|
Partner = "partner" // amplify their news, co-promote
|
|
Competitor = "competitor" // counter-program: position our product against theirs
|
|
Watch = "watch" // ecosystem news to curate, no promotion either way
|
|
)
|
|
|
|
var Relationships = []string{Partner, Competitor, Watch}
|
|
|
|
// Mention policies for competitors.
|
|
const (
|
|
MentionByName = "name" // posts may name the competitor
|
|
MentionCategory = "category" // talk about the category, never name them
|
|
)
|
|
|
|
// Entry is one partner, competitor or watched project. The YAML names of the
|
|
// fields the old config had (twitter_handle, youtube_channel_id,
|
|
// instagram_handle, hashtags) are kept so old lists import as they are.
|
|
type Entry struct {
|
|
ID int64 `json:"-" yaml:"-"`
|
|
Name string `json:"name" yaml:"name"`
|
|
Relationship string `json:"relationship" yaml:"relationship"`
|
|
Description string `json:"description" yaml:"description"`
|
|
Websites []string `json:"websites,omitempty" yaml:"websites,omitempty"`
|
|
TwitterHandle string `json:"twitter_handle,omitempty" yaml:"twitter_handle,omitempty"`
|
|
YouTubeChannelID string `json:"youtube_channel_id,omitempty" yaml:"youtube_channel_id,omitempty"`
|
|
InstagramHandle string `json:"instagram_handle,omitempty" yaml:"instagram_handle,omitempty"`
|
|
LinkedIn string `json:"linkedin,omitempty" yaml:"linkedin,omitempty"`
|
|
Subreddits []string `json:"subreddits,omitempty" yaml:"subreddits,omitempty"`
|
|
RSS []string `json:"rss,omitempty" yaml:"rss,omitempty"`
|
|
Hashtags []string `json:"hashtags,omitempty" yaml:"hashtags,omitempty"`
|
|
Keywords []string `json:"keywords,omitempty" yaml:"keywords,omitempty"`
|
|
TalkingPoints string `json:"talking_points,omitempty" yaml:"talking_points,omitempty"`
|
|
MentionPolicy string `json:"mention_policy,omitempty" yaml:"mention_policy,omitempty"`
|
|
Prices []Price `json:"prices,omitempty" yaml:"prices,omitempty"` // their plans' prices, as checked
|
|
}
|
|
|
|
// Normalize tidies an entry and checks it.
|
|
func (e *Entry) Normalize() error {
|
|
e.Name = strings.TrimSpace(e.Name)
|
|
if e.Name == "" {
|
|
return errors.New("a name is required")
|
|
}
|
|
e.Relationship = strings.ToLower(strings.TrimSpace(e.Relationship))
|
|
if e.Relationship == "" {
|
|
e.Relationship = Watch
|
|
}
|
|
if !validRelationship(e.Relationship) {
|
|
return fmt.Errorf("%s: relationship must be partner, competitor or watch, not %q", e.Name, e.Relationship)
|
|
}
|
|
e.Description = strings.TrimSpace(e.Description)
|
|
e.TwitterHandle = strings.TrimPrefix(strings.TrimSpace(e.TwitterHandle), "@")
|
|
e.YouTubeChannelID = strings.TrimSpace(e.YouTubeChannelID)
|
|
e.InstagramHandle = strings.TrimPrefix(strings.TrimSpace(e.InstagramHandle), "@")
|
|
e.LinkedIn = strings.TrimSpace(e.LinkedIn)
|
|
e.Websites = profile.CleanList(e.Websites)
|
|
e.RSS = profile.CleanList(e.RSS)
|
|
e.Keywords = profile.CleanList(e.Keywords)
|
|
e.TalkingPoints = strings.TrimSpace(e.TalkingPoints)
|
|
if err := e.normalizePrices(); err != nil {
|
|
return err
|
|
}
|
|
|
|
subs := profile.CleanList(e.Subreddits)
|
|
for i, s := range subs {
|
|
subs[i] = strings.TrimPrefix(strings.TrimPrefix(s, "/"), "r/")
|
|
}
|
|
e.Subreddits = subs
|
|
|
|
// Hashtags are stored with their #, however they were typed.
|
|
tags := profile.CleanList(e.Hashtags)
|
|
for i, t := range tags {
|
|
tags[i] = "#" + strings.TrimLeft(t, "#")
|
|
}
|
|
e.Hashtags = tags
|
|
|
|
e.MentionPolicy = strings.ToLower(strings.TrimSpace(e.MentionPolicy))
|
|
if e.Relationship == Competitor {
|
|
if e.MentionPolicy == "" {
|
|
e.MentionPolicy = MentionCategory
|
|
}
|
|
if e.MentionPolicy != MentionByName && e.MentionPolicy != MentionCategory {
|
|
return fmt.Errorf("%s: mention_policy must be name or category, not %q", e.Name, e.MentionPolicy)
|
|
}
|
|
} else {
|
|
e.MentionPolicy = ""
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func validRelationship(r string) bool {
|
|
for _, v := range Relationships {
|
|
if r == v {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
// List returns the entries, by name, optionally only those with one
|
|
// relationship.
|
|
func List(d *db.DB, relationship string) ([]Entry, error) {
|
|
q := `SELECT id, data FROM inventory`
|
|
var args []any
|
|
if relationship != "" {
|
|
q += ` WHERE relationship = ?`
|
|
args = append(args, relationship)
|
|
}
|
|
q += ` ORDER BY name COLLATE NOCASE`
|
|
rows, err := d.Query(q, args...)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
var out []Entry
|
|
for rows.Next() {
|
|
var id int64
|
|
var raw string
|
|
if err := rows.Scan(&id, &raw); err != nil {
|
|
return nil, err
|
|
}
|
|
var e Entry
|
|
if err := json.Unmarshal([]byte(raw), &e); err != nil {
|
|
return nil, fmt.Errorf("inventory entry %d: %w", id, err)
|
|
}
|
|
e.ID = id
|
|
out = append(out, e)
|
|
}
|
|
return out, rows.Err()
|
|
}
|
|
|
|
// Get returns one entry, or nil if there is none with that ID.
|
|
func Get(d *db.DB, id int64) (*Entry, error) {
|
|
var raw string
|
|
err := d.QueryRow(`SELECT data FROM inventory WHERE id = ?`, id).Scan(&raw)
|
|
if errors.Is(err, sql.ErrNoRows) {
|
|
return nil, nil
|
|
}
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
var e Entry
|
|
if err := json.Unmarshal([]byte(raw), &e); err != nil {
|
|
return nil, err
|
|
}
|
|
e.ID = id
|
|
return &e, nil
|
|
}
|
|
|
|
// ErrDuplicate is returned when another entry already has the name.
|
|
var ErrDuplicate = errors.New("another entry already has that name")
|
|
|
|
// Save inserts the entry (ID 0) or updates it, and sets its ID.
|
|
func Save(d *db.DB, e *Entry) error {
|
|
if err := e.Normalize(); err != nil {
|
|
return err
|
|
}
|
|
raw, err := json.Marshal(e)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
var other int64
|
|
err = d.QueryRow(`SELECT id FROM inventory WHERE name = ? AND id != ?`, e.Name, e.ID).Scan(&other)
|
|
if err == nil {
|
|
return fmt.Errorf("%s: %w", e.Name, ErrDuplicate)
|
|
}
|
|
if !errors.Is(err, sql.ErrNoRows) {
|
|
return err
|
|
}
|
|
if e.ID == 0 {
|
|
newID, err := d.Insert(`INSERT INTO inventory (name, relationship, data) VALUES (?, ?, ?)`, e.Name, e.Relationship, string(raw))
|
|
if err != nil {
|
|
return err
|
|
}
|
|
e.ID = newID
|
|
return err
|
|
}
|
|
res, err := d.Exec(`UPDATE inventory SET name = ?, relationship = ?, data = ?,
|
|
updated_at = ? WHERE id = ?`,
|
|
e.Name, e.Relationship, string(raw), time.Now().UTC().Format("2006-01-02T15:04:05Z"), e.ID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if n, _ := res.RowsAffected(); n == 0 {
|
|
return fmt.Errorf("inventory entry %d doesn't exist", e.ID)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// Delete removes an entry.
|
|
func Delete(d *db.DB, id int64) error {
|
|
_, err := d.Exec(`DELETE FROM inventory WHERE id = ?`, id)
|
|
return err
|
|
}
|
|
|
|
// ImportResult says what an import did.
|
|
type ImportResult struct {
|
|
Added, Updated, Skipped int
|
|
Errors []string
|
|
}
|
|
|
|
// ParseYAML reads entries from YAML: a plain list, or a document with an
|
|
// `inventory:` or (old config) `applications:` list. defaultRel is used for
|
|
// entries without a relationship.
|
|
func ParseYAML(data []byte, defaultRel string) ([]Entry, error) {
|
|
var list []Entry
|
|
if err := yaml.Unmarshal(data, &list); err != nil {
|
|
var doc struct {
|
|
Inventory []Entry `yaml:"inventory"`
|
|
Applications []Entry `yaml:"applications"`
|
|
}
|
|
if err2 := yaml.Unmarshal(data, &doc); err2 != nil {
|
|
return nil, fmt.Errorf("not a Market list: %w", err2)
|
|
}
|
|
list = append(doc.Inventory, doc.Applications...)
|
|
}
|
|
for i := range list {
|
|
if strings.TrimSpace(list[i].Relationship) == "" {
|
|
list[i].Relationship = defaultRel
|
|
}
|
|
}
|
|
return list, nil
|
|
}
|
|
|
|
// Import adds the entries. An entry whose name is already in the inventory is
|
|
// updated if overwrite is set, and skipped otherwise.
|
|
func Import(d *db.DB, entries []Entry, overwrite bool) ImportResult {
|
|
var r ImportResult
|
|
existing, err := List(d, "")
|
|
if err != nil {
|
|
r.Errors = append(r.Errors, err.Error())
|
|
return r
|
|
}
|
|
byName := map[string]int64{}
|
|
for _, e := range existing {
|
|
byName[strings.ToLower(e.Name)] = e.ID
|
|
}
|
|
for _, e := range entries {
|
|
e := e
|
|
id, exists := byName[strings.ToLower(strings.TrimSpace(e.Name))]
|
|
if exists && !overwrite {
|
|
r.Skipped++
|
|
continue
|
|
}
|
|
e.ID = id
|
|
if err := Save(d, &e); err != nil {
|
|
r.Errors = append(r.Errors, err.Error())
|
|
continue
|
|
}
|
|
byName[strings.ToLower(e.Name)] = e.ID
|
|
if exists {
|
|
r.Updated++
|
|
} else {
|
|
r.Added++
|
|
}
|
|
}
|
|
return r
|
|
}
|
|
|
|
// ExportYAML writes the entries in the format ParseYAML reads.
|
|
func ExportYAML(entries []Entry) ([]byte, error) {
|
|
return yaml.Marshal(map[string][]Entry{"inventory": entries})
|
|
}
|