Supermarket looks at each Inventory partner's pages that list providers, hosts or partners (from their sitemap and home page) and keeps the ones that list others but not the site; once a month by itself, or on request. On request (up to 4 web searches), the AI finds lists of alternatives to a competitor, and each page is read to keep the ones that name others but not the company. Each opportunity can be marked asked, won or dismissed; it's marked won when a link from its site shows up. SEO → Links lists them; open ones join What to write next. Nothing is sent: asking is the user's. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
783 lines
31 KiB
Go
783 lines
31 KiB
Go
// Package db opens the app's SQLite database and keeps its schema current.
|
||
package db
|
||
|
||
import (
|
||
"database/sql"
|
||
"encoding/json"
|
||
"errors"
|
||
"fmt"
|
||
|
||
_ "modernc.org/sqlite" // registers the "sqlite" driver (pure Go, no cgo)
|
||
)
|
||
|
||
// migrations are applied in order, once each. Never edit or reorder one that
|
||
// has shipped: add a new one instead.
|
||
var migrations = []string{
|
||
// 1: settings, inventory, the content pipeline's state, and the Hermes bridge
|
||
`
|
||
CREATE TABLE settings (
|
||
key TEXT PRIMARY KEY,
|
||
value TEXT NOT NULL
|
||
);
|
||
|
||
CREATE TABLE inventory (
|
||
id INTEGER PRIMARY KEY,
|
||
name TEXT NOT NULL UNIQUE COLLATE NOCASE,
|
||
relationship TEXT NOT NULL CHECK (relationship IN ('partner', 'competitor', 'watch')),
|
||
data TEXT NOT NULL,
|
||
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now')),
|
||
updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now'))
|
||
);
|
||
|
||
-- When each source was last checked (was state.json)
|
||
CREATE TABLE fetch_state (
|
||
key TEXT PRIMARY KEY,
|
||
last_checked TEXT NOT NULL
|
||
);
|
||
|
||
-- Content items the user dismissed (was dismissed.json)
|
||
CREATE TABLE dismissed (
|
||
item_id TEXT PRIMARY KEY,
|
||
dismissed_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now'))
|
||
);
|
||
|
||
-- Generated posts waiting to be published (was posts.json). posted_to is a
|
||
-- JSON list of platforms already published to, so a partial failure can be
|
||
-- retried without posting twice.
|
||
CREATE TABLE posts (
|
||
id TEXT PRIMARY KEY,
|
||
inventory_name TEXT NOT NULL,
|
||
content TEXT NOT NULL,
|
||
source_url TEXT NOT NULL DEFAULT '',
|
||
generated_at TEXT NOT NULL,
|
||
posted_to TEXT NOT NULL DEFAULT '[]'
|
||
);
|
||
|
||
-- Each time Hermes reaches the app through MCP
|
||
CREATE TABLE bridge_checkins (
|
||
id INTEGER PRIMARY KEY,
|
||
at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now')),
|
||
agent TEXT NOT NULL,
|
||
mcphub_tools TEXT NOT NULL DEFAULT '[]',
|
||
note TEXT NOT NULL DEFAULT ''
|
||
);
|
||
`,
|
||
// 2: the Content module. Fetched items are kept so browsing doesn't fetch
|
||
// again, and posts become per-channel drafts. Statuses and channels are
|
||
// checked in Go, not by CHECK constraints, so later phases can add some
|
||
// without rebuilding the table.
|
||
`
|
||
CREATE TABLE content_items (
|
||
id TEXT PRIMARY KEY, -- the source's own ID (tweet, video), or rss:<hash>
|
||
inventory_name TEXT NOT NULL COLLATE NOCASE,
|
||
source TEXT NOT NULL,
|
||
author TEXT NOT NULL DEFAULT '',
|
||
author_handle TEXT NOT NULL DEFAULT '',
|
||
title TEXT NOT NULL DEFAULT '',
|
||
body TEXT NOT NULL DEFAULT '',
|
||
url TEXT NOT NULL DEFAULT '',
|
||
published_at TEXT NOT NULL,
|
||
fetched_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now')),
|
||
used_at TEXT -- when a draft was written from it
|
||
);
|
||
CREATE INDEX content_items_by_entry ON content_items (inventory_name, published_at);
|
||
|
||
-- One row per channel: a generation that targets X and LinkedIn makes two
|
||
-- drafts with the same batch. Each is edited, published and retried on its
|
||
-- own, so a failure on one channel never re-posts to the other.
|
||
CREATE TABLE drafts (
|
||
id INTEGER PRIMARY KEY,
|
||
batch TEXT NOT NULL,
|
||
inventory_name TEXT NOT NULL DEFAULT '',
|
||
kind TEXT NOT NULL, -- partner, competitor, watch (later: product)
|
||
channel TEXT NOT NULL, -- x, linkedin (later: reddit)
|
||
content TEXT NOT NULL,
|
||
source_url TEXT NOT NULL DEFAULT '',
|
||
item_ids TEXT NOT NULL DEFAULT '[]',
|
||
status TEXT NOT NULL DEFAULT 'draft', -- draft, publishing, published, failed, discarded
|
||
error TEXT NOT NULL DEFAULT '',
|
||
post_url TEXT NOT NULL DEFAULT '',
|
||
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now')),
|
||
updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now')),
|
||
published_at TEXT
|
||
);
|
||
CREATE INDEX drafts_by_status ON drafts (status, created_at);
|
||
|
||
-- Queued posts become drafts for the platforms they haven't reached yet.
|
||
INSERT INTO drafts (batch, inventory_name, kind, channel, content, source_url, created_at, updated_at)
|
||
SELECT p.id, p.inventory_name,
|
||
COALESCE((SELECT relationship FROM inventory WHERE name = p.inventory_name), 'partner'),
|
||
c.channel, p.content, p.source_url, p.generated_at, p.generated_at
|
||
FROM posts p, (SELECT 'x' AS channel UNION ALL SELECT 'linkedin') c
|
||
WHERE NOT EXISTS (SELECT 1 FROM json_each(p.posted_to) WHERE value = c.channel)
|
||
ORDER BY p.generated_at, c.channel;
|
||
DROP TABLE posts;
|
||
`,
|
||
// 3: scheduling. An approved draft is "scheduled" with the time it goes
|
||
// out; "publish now" is a schedule for the present.
|
||
`
|
||
ALTER TABLE drafts ADD COLUMN publish_at TEXT;
|
||
CREATE INDEX drafts_due ON drafts (status, publish_at);
|
||
`,
|
||
// 4: Reddit. A Reddit draft has a title and is for one subreddit
|
||
// (target). Subreddits' rules are cached so Posts can show them.
|
||
`
|
||
ALTER TABLE drafts ADD COLUMN title TEXT NOT NULL DEFAULT '';
|
||
ALTER TABLE drafts ADD COLUMN target TEXT NOT NULL DEFAULT '';
|
||
CREATE TABLE subreddits (
|
||
name TEXT PRIMARY KEY COLLATE NOCASE,
|
||
data TEXT NOT NULL,
|
||
fetched_at TEXT NOT NULL
|
||
);
|
||
`,
|
||
// 5: the CRM bridge. Supermarket never writes to EspoCRM itself: actions
|
||
// wait here until Hermes carries them out through the Core's MCP hub and
|
||
// reports back. Hermes also copies CRM records here, for dedupe.
|
||
`
|
||
CREATE TABLE crm_actions (
|
||
id INTEGER PRIMARY KEY,
|
||
key TEXT NOT NULL UNIQUE, -- one action per key, however often it's queued
|
||
kind TEXT NOT NULL, -- create (later: update, note)
|
||
entity TEXT NOT NULL, -- Lead, Account, Contact…
|
||
fields TEXT NOT NULL, -- JSON: the record's fields
|
||
match TEXT NOT NULL DEFAULT '{}', -- JSON: fields that identify an existing record
|
||
origin TEXT NOT NULL DEFAULT '', -- what queued it, e.g. test, prospect:12
|
||
status TEXT NOT NULL DEFAULT 'pending', -- pending, claimed, done, failed, cancelled
|
||
outcome TEXT NOT NULL DEFAULT '', -- created, existing
|
||
espo_id TEXT NOT NULL DEFAULT '',
|
||
error TEXT NOT NULL DEFAULT '',
|
||
attempts INTEGER NOT NULL DEFAULT 0,
|
||
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now')),
|
||
claimed_at TEXT,
|
||
done_at TEXT
|
||
);
|
||
CREATE INDEX crm_actions_by_status ON crm_actions (status, id);
|
||
|
||
CREATE TABLE crm_records (
|
||
entity TEXT NOT NULL,
|
||
espo_id TEXT NOT NULL,
|
||
name TEXT NOT NULL DEFAULT '',
|
||
email TEXT NOT NULL DEFAULT '' COLLATE NOCASE,
|
||
domain TEXT NOT NULL DEFAULT '' COLLATE NOCASE, -- of the website, or the email
|
||
data TEXT NOT NULL, -- JSON: the fields Hermes sent
|
||
modified_at TEXT NOT NULL DEFAULT '',
|
||
synced_at TEXT NOT NULL,
|
||
PRIMARY KEY (entity, espo_id)
|
||
);
|
||
CREATE INDEX crm_records_by_email ON crm_records (email);
|
||
CREATE INDEX crm_records_by_domain ON crm_records (domain);
|
||
`,
|
||
// 6: prospects. Companies and people Supermarket found (or the user
|
||
// added), waiting for review; nothing reaches the CRM until accepted.
|
||
// Every one records where and when it was found.
|
||
`
|
||
CREATE TABLE prospect_companies (
|
||
id INTEGER PRIMARY KEY,
|
||
name TEXT NOT NULL,
|
||
domain TEXT NOT NULL DEFAULT '' COLLATE NOCASE, -- one company per domain
|
||
website TEXT NOT NULL DEFAULT '',
|
||
linkedin TEXT NOT NULL DEFAULT '',
|
||
industry TEXT NOT NULL DEFAULT '',
|
||
size TEXT NOT NULL DEFAULT '',
|
||
location TEXT NOT NULL DEFAULT '',
|
||
why TEXT NOT NULL DEFAULT '', -- why it fits the targets
|
||
source TEXT NOT NULL, -- manual, discovery, hunter, csv…
|
||
source_detail TEXT NOT NULL DEFAULT '', -- a URL or note: where exactly
|
||
found_at TEXT NOT NULL,
|
||
status TEXT NOT NULL DEFAULT 'new', -- new, accepted, rejected
|
||
decided_at TEXT,
|
||
action_id INTEGER -- the CRM action that adds it as an Account
|
||
);
|
||
CREATE UNIQUE INDEX prospect_companies_by_domain ON prospect_companies (domain) WHERE domain != '';
|
||
CREATE INDEX prospect_companies_by_status ON prospect_companies (status, id);
|
||
|
||
CREATE TABLE prospect_contacts (
|
||
id INTEGER PRIMARY KEY,
|
||
company_id INTEGER REFERENCES prospect_companies (id) ON DELETE SET NULL,
|
||
first_name TEXT NOT NULL DEFAULT '',
|
||
last_name TEXT NOT NULL DEFAULT '',
|
||
title TEXT NOT NULL DEFAULT '',
|
||
email TEXT NOT NULL DEFAULT '' COLLATE NOCASE, -- one contact per email
|
||
email_status TEXT NOT NULL DEFAULT '', -- '', valid, risky, invalid (from verification)
|
||
linkedin TEXT NOT NULL DEFAULT '',
|
||
phone TEXT NOT NULL DEFAULT '',
|
||
source TEXT NOT NULL,
|
||
source_detail TEXT NOT NULL DEFAULT '',
|
||
found_at TEXT NOT NULL,
|
||
status TEXT NOT NULL DEFAULT 'new', -- new, accepted, rejected
|
||
decided_at TEXT,
|
||
action_id INTEGER -- the CRM action that adds them as a Lead
|
||
);
|
||
CREATE UNIQUE INDEX prospect_contacts_by_email ON prospect_contacts (email) WHERE email != '';
|
||
CREATE INDEX prospect_contacts_by_company ON prospect_contacts (company_id);
|
||
|
||
-- People and companies who must never be contacted or added: checked
|
||
-- before anything is found, shown or queued.
|
||
CREATE TABLE suppressions (
|
||
kind TEXT NOT NULL, -- email or domain
|
||
value TEXT NOT NULL COLLATE NOCASE,
|
||
reason TEXT NOT NULL DEFAULT '',
|
||
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now')),
|
||
PRIMARY KEY (kind, value)
|
||
);
|
||
`,
|
||
// 7: buying signals and the funnel. A signal is a hypothesis about why a
|
||
// company buys now; everything Supermarket and the outside tools do is
|
||
// tagged with one, and every step through the funnel is an event.
|
||
`
|
||
CREATE TABLE signals (
|
||
id INTEGER PRIMARY KEY,
|
||
slug TEXT NOT NULL UNIQUE, -- used as utm_campaign
|
||
name TEXT NOT NULL,
|
||
hypothesis TEXT NOT NULL DEFAULT '',
|
||
spot TEXT NOT NULL DEFAULT '', -- how to find it: queries, keywords, one per line
|
||
angle TEXT NOT NULL DEFAULT '', -- the pain and promise for messages and content
|
||
status TEXT NOT NULL DEFAULT 'idea', -- idea, testing, proven, retired
|
||
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now')),
|
||
updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now'))
|
||
);
|
||
|
||
ALTER TABLE prospect_companies ADD COLUMN signal_id INTEGER REFERENCES signals (id) ON DELETE SET NULL;
|
||
ALTER TABLE prospect_contacts ADD COLUMN signal_id INTEGER REFERENCES signals (id) ON DELETE SET NULL;
|
||
|
||
-- Campaigns in outside tools (origami.chat, explee.com), each assigned to a
|
||
-- signal by the user.
|
||
CREATE TABLE outside_campaigns (
|
||
source TEXT NOT NULL, -- origami, explee
|
||
id TEXT NOT NULL,
|
||
name TEXT NOT NULL DEFAULT '',
|
||
status TEXT NOT NULL DEFAULT '',
|
||
signal_id INTEGER REFERENCES signals (id) ON DELETE SET NULL,
|
||
spend_cents INTEGER NOT NULL DEFAULT 0, -- lifetime, as the tool reports it
|
||
stats TEXT NOT NULL DEFAULT '{}', -- JSON: the tool's own numbers
|
||
synced_at TEXT NOT NULL,
|
||
PRIMARY KEY (source, id)
|
||
);
|
||
|
||
-- One row per step someone (or a group, for counts) took through the funnel.
|
||
CREATE TABLE funnel_events (
|
||
id INTEGER PRIMARY KEY,
|
||
signal_id INTEGER REFERENCES signals (id) ON DELETE SET NULL,
|
||
stage TEXT NOT NULL, -- found, contacted, replied, interested, booked, visited, signed_up, paid
|
||
channel TEXT NOT NULL, -- email, linkedin, social, blog, website, origami, explee, other
|
||
subject TEXT NOT NULL DEFAULT '', -- who: contact:12, company:3, explee:<person>…
|
||
email TEXT NOT NULL DEFAULT '' COLLATE NOCASE, -- to tie it to the CRM and Stripe later
|
||
campaign TEXT NOT NULL DEFAULT '', -- origami:<id>, explee:<id>; its signal is set there
|
||
source TEXT NOT NULL, -- supermarket, manual, origami, explee
|
||
external_id TEXT NOT NULL DEFAULT '', -- dedupes imports
|
||
count INTEGER NOT NULL DEFAULT 1, -- for aggregate numbers (visits)
|
||
value_cents INTEGER NOT NULL DEFAULT 0, -- for paid
|
||
note TEXT NOT NULL DEFAULT '',
|
||
at TEXT NOT NULL
|
||
);
|
||
CREATE UNIQUE INDEX funnel_events_external ON funnel_events (source, external_id) WHERE external_id != '';
|
||
CREATE INDEX funnel_events_by_signal ON funnel_events (signal_id, stage, at);
|
||
CREATE INDEX funnel_events_by_subject ON funnel_events (subject);
|
||
CREATE INDEX funnel_events_by_campaign ON funnel_events (campaign);
|
||
`,
|
||
// 8: discovery. Each signal can be searched for companies that show it
|
||
// (Claude with web search, explee.com's company search), by hand or on
|
||
// a schedule; every run is kept, with what it found and cost.
|
||
`
|
||
ALTER TABLE signals ADD COLUMN discover_every_days INTEGER NOT NULL DEFAULT 0; -- 0: only by hand
|
||
ALTER TABLE signals ADD COLUMN explee_definition TEXT NOT NULL DEFAULT ''; -- what the companies do, for explee.com
|
||
|
||
CREATE TABLE discovery_runs (
|
||
id INTEGER PRIMARY KEY,
|
||
signal_id INTEGER NOT NULL REFERENCES signals (id) ON DELETE CASCADE,
|
||
source TEXT NOT NULL, -- claude, explee
|
||
status TEXT NOT NULL DEFAULT 'running', -- running, done, failed
|
||
started_at TEXT NOT NULL,
|
||
finished_at TEXT,
|
||
found INTEGER NOT NULL DEFAULT 0, -- companies reported
|
||
added INTEGER NOT NULL DEFAULT 0, -- new prospects
|
||
existing INTEGER NOT NULL DEFAULT 0, -- already prospects
|
||
skipped INTEGER NOT NULL DEFAULT 0, -- suppressed, ours, or without a source it read
|
||
searches INTEGER NOT NULL DEFAULT 0, -- web searches (each billed)
|
||
error TEXT NOT NULL DEFAULT '',
|
||
notes TEXT NOT NULL DEFAULT '[]' -- JSON: why companies were skipped
|
||
);
|
||
CREATE INDEX discovery_runs_by_signal ON discovery_runs (signal_id, id);
|
||
`,
|
||
// 9: enrichment with Hunter.io. Every search and verification is kept,
|
||
// with what it found and the credits it used.
|
||
`
|
||
CREATE TABLE enrich_runs (
|
||
id INTEGER PRIMARY KEY,
|
||
kind TEXT NOT NULL, -- people (at a company), email (for a person), verify
|
||
subject TEXT NOT NULL, -- company:3, contact:12
|
||
at TEXT NOT NULL,
|
||
found INTEGER NOT NULL DEFAULT 0,
|
||
added INTEGER NOT NULL DEFAULT 0,
|
||
credits REAL NOT NULL DEFAULT 0, -- Hunter.io credits used
|
||
result TEXT NOT NULL DEFAULT '', -- what happened, in words
|
||
error TEXT NOT NULL DEFAULT ''
|
||
);
|
||
CREATE INDEX enrich_runs_by_subject ON enrich_runs (subject, id);
|
||
CREATE INDEX enrich_runs_by_time ON enrich_runs (at);
|
||
`,
|
||
// 10: direct outreach. Each email or LinkedIn message to a prospect,
|
||
// from draft to sent, with the reply read from the mailbox.
|
||
`
|
||
CREATE TABLE outreach (
|
||
id INTEGER PRIMARY KEY,
|
||
contact_id INTEGER NOT NULL REFERENCES prospect_contacts (id) ON DELETE CASCADE,
|
||
signal_id INTEGER REFERENCES signals (id) ON DELETE SET NULL,
|
||
channel TEXT NOT NULL, -- email, linkedin
|
||
status TEXT NOT NULL DEFAULT 'draft', -- draft, queued, sent, failed, bounced, discarded
|
||
subject TEXT NOT NULL DEFAULT '',
|
||
body TEXT NOT NULL DEFAULT '',
|
||
to_addr TEXT NOT NULL DEFAULT '' COLLATE NOCASE,
|
||
message_id TEXT NOT NULL DEFAULT '', -- the email's Message-ID, to match replies
|
||
created_at TEXT NOT NULL,
|
||
queued_at TEXT,
|
||
sent_at TEXT,
|
||
replied_at TEXT,
|
||
reply TEXT NOT NULL DEFAULT '', -- the start of their reply
|
||
error TEXT NOT NULL DEFAULT ''
|
||
);
|
||
CREATE INDEX outreach_by_status ON outreach (status, id);
|
||
CREATE INDEX outreach_by_contact ON outreach (contact_id);
|
||
CREATE INDEX outreach_by_to ON outreach (to_addr);
|
||
CREATE UNIQUE INDEX outreach_message_id ON outreach (message_id) WHERE message_id != '';
|
||
`,
|
||
// 11: the end of the funnel. Posts written for a buying signal; Stripe
|
||
// customers with the campaign they came from; where each import stopped
|
||
// is kept in settings.
|
||
`
|
||
ALTER TABLE drafts ADD COLUMN signal_id INTEGER REFERENCES signals (id) ON DELETE SET NULL;
|
||
CREATE INDEX drafts_by_signal ON drafts (signal_id) WHERE signal_id IS NOT NULL;
|
||
|
||
CREATE TABLE stripe_customers (
|
||
id TEXT PRIMARY KEY, -- cus_…
|
||
email TEXT NOT NULL DEFAULT '' COLLATE NOCASE,
|
||
name TEXT NOT NULL DEFAULT '',
|
||
signal_id INTEGER REFERENCES signals (id) ON DELETE SET NULL,
|
||
subject TEXT NOT NULL DEFAULT '', -- contact:12 when they're a prospect
|
||
channel TEXT NOT NULL DEFAULT '',
|
||
utm_campaign TEXT NOT NULL DEFAULT '',
|
||
utm_source TEXT NOT NULL DEFAULT '',
|
||
utm_medium TEXT NOT NULL DEFAULT '',
|
||
first_seen TEXT NOT NULL
|
||
);
|
||
`,
|
||
// 12: Search Console, by day: the property's totals, each page's, and
|
||
// each page and query's (Google leaves out the queries it hides, so the
|
||
// page totals are kept apart). Position is stored as position ×
|
||
// impressions, so averages over days weigh by impressions.
|
||
`
|
||
CREATE TABLE gsc_site_days (
|
||
site TEXT NOT NULL, -- the Search Console property
|
||
date TEXT NOT NULL, -- YYYY-MM-DD
|
||
clicks INTEGER NOT NULL,
|
||
impressions INTEGER NOT NULL,
|
||
pos_sum REAL NOT NULL,
|
||
PRIMARY KEY (site, date)
|
||
);
|
||
CREATE TABLE gsc_page_days (
|
||
site TEXT NOT NULL,
|
||
date TEXT NOT NULL,
|
||
page TEXT NOT NULL,
|
||
clicks INTEGER NOT NULL,
|
||
impressions INTEGER NOT NULL,
|
||
pos_sum REAL NOT NULL,
|
||
PRIMARY KEY (site, date, page)
|
||
);
|
||
CREATE TABLE gsc_query_days (
|
||
site TEXT NOT NULL,
|
||
date TEXT NOT NULL,
|
||
page TEXT NOT NULL,
|
||
query TEXT NOT NULL,
|
||
clicks INTEGER NOT NULL,
|
||
impressions INTEGER NOT NULL,
|
||
pos_sum REAL NOT NULL,
|
||
PRIMARY KEY (site, date, page, query)
|
||
);
|
||
CREATE INDEX gsc_query_days_by_query ON gsc_query_days (site, query, date);
|
||
`,
|
||
// 13: the Monday SEO reports, kept so each week compares with the last.
|
||
`
|
||
CREATE TABLE seo_reports (
|
||
site TEXT NOT NULL,
|
||
week_to TEXT NOT NULL, -- the week's last day of final data
|
||
created_at TEXT NOT NULL,
|
||
data TEXT NOT NULL, -- the report, as JSON
|
||
PRIMARY KEY (site, week_to)
|
||
);
|
||
`,
|
||
// 14: technical audits of the websites.
|
||
`
|
||
CREATE TABLE seo_audits (
|
||
id INTEGER PRIMARY KEY,
|
||
site TEXT NOT NULL, -- the website's address
|
||
status TEXT NOT NULL DEFAULT 'running', -- running, done, failed
|
||
started_at TEXT NOT NULL,
|
||
finished_at TEXT,
|
||
error TEXT NOT NULL DEFAULT '',
|
||
data TEXT NOT NULL DEFAULT '{}' -- pages, issues and checks, as JSON
|
||
);
|
||
CREATE INDEX seo_audits_by_site ON seo_audits (site, id);
|
||
`,
|
||
// 15: SEO changes, from proposal to the user's yes, the pull request,
|
||
// and the page's numbers before and after.
|
||
`
|
||
CREATE TABLE seo_changes (
|
||
id INTEGER PRIMARY KEY,
|
||
site TEXT NOT NULL, -- the website's address
|
||
property TEXT NOT NULL DEFAULT '',
|
||
page TEXT NOT NULL,
|
||
cur_title TEXT NOT NULL DEFAULT '',
|
||
new_title TEXT NOT NULL DEFAULT '',
|
||
cur_description TEXT NOT NULL DEFAULT '',
|
||
new_description TEXT NOT NULL DEFAULT '',
|
||
why TEXT NOT NULL DEFAULT '',
|
||
status TEXT NOT NULL DEFAULT 'proposed',
|
||
repo TEXT NOT NULL DEFAULT '',
|
||
file TEXT NOT NULL DEFAULT '',
|
||
branch TEXT NOT NULL DEFAULT '',
|
||
pr_number INTEGER NOT NULL DEFAULT 0,
|
||
pr_url TEXT NOT NULL DEFAULT '',
|
||
diff TEXT NOT NULL DEFAULT '',
|
||
note TEXT NOT NULL DEFAULT '',
|
||
error TEXT NOT NULL DEFAULT '',
|
||
created_at TEXT NOT NULL,
|
||
decided_at TEXT,
|
||
merged_at TEXT,
|
||
live_at TEXT
|
||
);
|
||
CREATE INDEX seo_changes_by_site ON seo_changes (site, id);
|
||
CREATE INDEX seo_changes_by_status ON seo_changes (status);
|
||
`,
|
||
// 16: the next keywords: searches a site has no page for.
|
||
`
|
||
CREATE TABLE seo_keywords (
|
||
id INTEGER PRIMARY KEY,
|
||
site TEXT NOT NULL,
|
||
keyword TEXT NOT NULL,
|
||
intent TEXT NOT NULL DEFAULT 'info', -- buyer, info
|
||
sources TEXT NOT NULL DEFAULT '[]', -- where it came from
|
||
impressions INTEGER NOT NULL DEFAULT 0, -- Search Console, 90 days
|
||
position REAL NOT NULL DEFAULT 0,
|
||
shown_on TEXT NOT NULL DEFAULT '',
|
||
status TEXT NOT NULL DEFAULT 'new', -- new, picked, dismissed
|
||
top TEXT NOT NULL DEFAULT '[]', -- the live top results, when read
|
||
top_at TEXT,
|
||
searches INTEGER NOT NULL DEFAULT 0, -- web searches used
|
||
created_at TEXT NOT NULL,
|
||
picked_at TEXT,
|
||
UNIQUE (site, keyword)
|
||
);
|
||
`,
|
||
// 17: briefs, and the pages written from them.
|
||
`
|
||
CREATE TABLE seo_briefs (
|
||
id INTEGER PRIMARY KEY,
|
||
site TEXT NOT NULL,
|
||
property TEXT NOT NULL DEFAULT '',
|
||
keyword TEXT NOT NULL,
|
||
page TEXT NOT NULL DEFAULT '', -- a rewrite's page; a new page's once it's live
|
||
status TEXT NOT NULL DEFAULT 'brief',
|
||
shown_for TEXT NOT NULL DEFAULT '[]', -- Search Console: what the page is shown for
|
||
top TEXT NOT NULL DEFAULT '[]', -- the live top results
|
||
plan TEXT NOT NULL DEFAULT '{}', -- the brief
|
||
answers TEXT NOT NULL DEFAULT '[]', -- the user's answers to its questions
|
||
draft TEXT NOT NULL DEFAULT '', -- the page, Markdown
|
||
claims TEXT NOT NULL DEFAULT '[]', -- sentences claiming an experience
|
||
path TEXT NOT NULL DEFAULT '', -- a new page's address
|
||
file TEXT NOT NULL DEFAULT '',
|
||
pr_number INTEGER NOT NULL DEFAULT 0,
|
||
pr_url TEXT NOT NULL DEFAULT '',
|
||
note TEXT NOT NULL DEFAULT '',
|
||
error TEXT NOT NULL DEFAULT '',
|
||
searches INTEGER NOT NULL DEFAULT 0,
|
||
created_at TEXT NOT NULL,
|
||
merged_at TEXT,
|
||
live_at TEXT
|
||
);
|
||
CREATE INDEX seo_briefs_by_site ON seo_briefs (site, id);
|
||
`,
|
||
// 18: the full Stripe data for the metrics: every customer, invoice,
|
||
// credit note and refund as Stripe sent it, and the invoice lines the
|
||
// MRR model reads.
|
||
`
|
||
CREATE TABLE stripe_objects (
|
||
kind TEXT NOT NULL, -- customer, invoice, credit_note, refund
|
||
id TEXT NOT NULL,
|
||
customer TEXT NOT NULL DEFAULT '',
|
||
created INTEGER NOT NULL DEFAULT 0,
|
||
status TEXT NOT NULL DEFAULT '',
|
||
currency TEXT NOT NULL DEFAULT '',
|
||
amount INTEGER NOT NULL DEFAULT 0, -- invoice: total; credit note: total; refund: amount
|
||
data TEXT NOT NULL,
|
||
PRIMARY KEY (kind, id)
|
||
);
|
||
CREATE INDEX stripe_objects_by_customer ON stripe_objects (kind, customer);
|
||
CREATE TABLE stripe_invoice_lines (
|
||
invoice TEXT NOT NULL,
|
||
id TEXT NOT NULL,
|
||
customer TEXT NOT NULL DEFAULT '',
|
||
status TEXT NOT NULL DEFAULT '', -- the invoice's
|
||
currency TEXT NOT NULL DEFAULT '',
|
||
amount INTEGER NOT NULL DEFAULT 0, -- after discounts, before tax
|
||
period_start INTEGER NOT NULL DEFAULT 0,
|
||
period_end INTEGER NOT NULL DEFAULT 0,
|
||
subscription TEXT NOT NULL DEFAULT '',
|
||
price TEXT NOT NULL DEFAULT '',
|
||
product TEXT NOT NULL DEFAULT '',
|
||
interval TEXT NOT NULL DEFAULT '',
|
||
interval_count INTEGER NOT NULL DEFAULT 0,
|
||
quantity INTEGER NOT NULL DEFAULT 0,
|
||
proration INTEGER NOT NULL DEFAULT 0,
|
||
recurring INTEGER NOT NULL DEFAULT 0,
|
||
PRIMARY KEY (invoice, id)
|
||
);
|
||
CREATE INDEX stripe_invoice_lines_by_customer ON stripe_invoice_lines (customer, period_start);
|
||
`,
|
||
// 19: invoice lines' descriptions, which name the product when the key
|
||
// can't read Products.
|
||
`
|
||
ALTER TABLE stripe_invoice_lines ADD COLUMN description TEXT NOT NULL DEFAULT '';
|
||
`,
|
||
// 20: Stripe customers matched to EspoCRM Accounts by hand (the
|
||
// automatic matches are worked out each time).
|
||
`
|
||
CREATE TABLE crm_matches (
|
||
customer TEXT PRIMARY KEY, -- cus_…
|
||
espo_id TEXT NOT NULL DEFAULT '', -- the Account; '' means "not in the CRM"
|
||
set_at TEXT NOT NULL
|
||
);
|
||
`,
|
||
// 21: the spend log, for CAC.
|
||
`
|
||
CREATE TABLE spend (
|
||
id INTEGER PRIMARY KEY,
|
||
month TEXT NOT NULL, -- YYYY-MM
|
||
channel TEXT NOT NULL, -- a funnel channel, or general
|
||
amount_cents INTEGER NOT NULL,
|
||
note TEXT NOT NULL DEFAULT '',
|
||
source TEXT NOT NULL DEFAULT 'manual', -- manual, csv, origami, explee
|
||
created_at TEXT NOT NULL
|
||
);
|
||
CREATE INDEX spend_by_month ON spend (month);
|
||
-- What each outside campaign had spent when last seen, so only the
|
||
-- difference is added.
|
||
CREATE TABLE spend_seen (
|
||
source TEXT NOT NULL,
|
||
campaign TEXT NOT NULL,
|
||
spend_cents INTEGER NOT NULL,
|
||
PRIMARY KEY (source, campaign)
|
||
);
|
||
`,
|
||
// 22: pages built from a site's own sections (Sites → Pages).
|
||
`
|
||
CREATE TABLE site_pages (
|
||
id INTEGER PRIMARY KEY,
|
||
site TEXT NOT NULL, -- the website's URL, from the profile
|
||
repo TEXT NOT NULL DEFAULT '', -- owner/name
|
||
kind TEXT NOT NULL, -- landing, product, alternative, comparison, blog
|
||
source TEXT NOT NULL DEFAULT '{}', -- JSON: what it was built from
|
||
notes TEXT NOT NULL DEFAULT '', -- what the user asked for
|
||
path TEXT NOT NULL DEFAULT '',
|
||
title TEXT NOT NULL DEFAULT '',
|
||
description TEXT NOT NULL DEFAULT '',
|
||
sections TEXT NOT NULL DEFAULT '', -- YAML, as in the page's front matter
|
||
needs TEXT NOT NULL DEFAULT '[]',
|
||
warnings TEXT NOT NULL DEFAULT '[]',
|
||
claims TEXT NOT NULL DEFAULT '[]',
|
||
status TEXT NOT NULL DEFAULT 'draft',
|
||
branch TEXT NOT NULL DEFAULT '',
|
||
file TEXT NOT NULL DEFAULT '',
|
||
pr_number INTEGER NOT NULL DEFAULT 0,
|
||
pr_url TEXT NOT NULL DEFAULT '',
|
||
note TEXT NOT NULL DEFAULT '', -- what the build check found
|
||
error TEXT NOT NULL DEFAULT '',
|
||
created_at TEXT NOT NULL,
|
||
updated_at TEXT NOT NULL,
|
||
merged_at TEXT
|
||
);
|
||
CREATE INDEX site_pages_by_site ON site_pages (site, created_at);
|
||
`,
|
||
// 23: taking a published page off the site, through its own pull request.
|
||
`
|
||
ALTER TABLE site_pages ADD COLUMN removal_branch TEXT NOT NULL DEFAULT '';
|
||
ALTER TABLE site_pages ADD COLUMN removal_pr_number INTEGER NOT NULL DEFAULT 0;
|
||
ALTER TABLE site_pages ADD COLUMN removal_pr_url TEXT NOT NULL DEFAULT '';
|
||
`,
|
||
// 24: whether a merged page is on the live site (or a removed one gone).
|
||
`
|
||
ALTER TABLE site_pages ADD COLUMN live_at TEXT;
|
||
ALTER TABLE site_pages ADD COLUMN gone_at TEXT;
|
||
ALTER TABLE site_pages ADD COLUMN checked_at TEXT;
|
||
ALTER TABLE site_pages ADD COLUMN live_note TEXT NOT NULL DEFAULT '';
|
||
`,
|
||
// 25: a LinkedIn draft posts as the member ('') or the company page ('page').
|
||
`
|
||
ALTER TABLE drafts ADD COLUMN linkedin_as TEXT NOT NULL DEFAULT '';
|
||
`,
|
||
// 26: what each page turns visits into (Plausible, by entry page).
|
||
`
|
||
CREATE TABLE page_days (
|
||
site TEXT NOT NULL, -- the Plausible site
|
||
date TEXT NOT NULL, -- YYYY-MM-DD
|
||
page TEXT NOT NULL, -- the entry page's path, e.g. /freescout/
|
||
visitors INTEGER NOT NULL DEFAULT 0,
|
||
signups INTEGER NOT NULL DEFAULT 0, -- visitors who clicked a sign-up link
|
||
leads INTEGER NOT NULL DEFAULT 0, -- visitors who sent a form (the Lead goal)
|
||
PRIMARY KEY (site, date, page)
|
||
);
|
||
`,
|
||
// 27: backlinks: who sends visitors (Plausible), the links found
|
||
// (Plausible, Bing, by hand), and whether each is still there.
|
||
`
|
||
CREATE TABLE referrer_days (
|
||
site TEXT NOT NULL, -- the Plausible site
|
||
date TEXT NOT NULL, -- YYYY-MM-DD
|
||
source TEXT NOT NULL, -- the referring site, as Plausible names it
|
||
referrer TEXT NOT NULL DEFAULT '', -- the linking page, when Plausible has it
|
||
page TEXT NOT NULL, -- the entry page's path
|
||
visitors INTEGER NOT NULL DEFAULT 0,
|
||
signups INTEGER NOT NULL DEFAULT 0,
|
||
leads INTEGER NOT NULL DEFAULT 0,
|
||
PRIMARY KEY (site, date, source, referrer, page)
|
||
);
|
||
CREATE TABLE backlinks (
|
||
id INTEGER PRIMARY KEY,
|
||
site TEXT NOT NULL, -- the website's URL, from the profile
|
||
source_url TEXT NOT NULL, -- the page that links
|
||
target TEXT NOT NULL DEFAULT '', -- our page it links to (a path), when known
|
||
anchor TEXT NOT NULL DEFAULT '',
|
||
origin TEXT NOT NULL, -- plausible, bing, manual
|
||
first_seen TEXT NOT NULL,
|
||
last_seen TEXT NOT NULL,
|
||
status TEXT NOT NULL DEFAULT 'unchecked', -- unchecked, kept, gone, page-gone, target-404
|
||
checked_at TEXT,
|
||
note TEXT NOT NULL DEFAULT '',
|
||
UNIQUE (site, source_url, target)
|
||
);
|
||
`,
|
||
// 28: places a link could be won: partners' provider pages, lists of
|
||
// alternatives to a competitor.
|
||
`
|
||
CREATE TABLE link_opportunities (
|
||
id INTEGER PRIMARY KEY,
|
||
site TEXT NOT NULL, -- the website's URL, from the profile
|
||
kind TEXT NOT NULL, -- partner, alternatives
|
||
about TEXT NOT NULL DEFAULT '', -- the partner or competitor, by name
|
||
page_url TEXT NOT NULL,
|
||
title TEXT NOT NULL DEFAULT '',
|
||
note TEXT NOT NULL DEFAULT '', -- why it's an opportunity
|
||
status TEXT NOT NULL DEFAULT 'open', -- open, asked, won, listed, dismissed
|
||
found_at TEXT NOT NULL,
|
||
updated_at TEXT NOT NULL,
|
||
UNIQUE (site, page_url)
|
||
);
|
||
`,
|
||
}
|
||
|
||
// DB wraps the database with the settings helpers every package uses.
|
||
type DB struct {
|
||
*sql.DB
|
||
}
|
||
|
||
// Open opens (creating if needed) the database at path and migrates it.
|
||
// BeforeMigrate, if set, runs before an existing database is migrated to
|
||
// a newer schema (from and to are the schema versions): the app backs it
|
||
// up. A new, empty database isn't backed up.
|
||
var BeforeMigrate func(d *sql.DB, from, to int) error
|
||
|
||
// Schema is the schema version this build migrates databases to.
|
||
func Schema() int { return len(migrations) }
|
||
|
||
func Open(path string) (*DB, error) {
|
||
// WAL lets the web UI read while a background job writes; busy_timeout
|
||
// waits out short write locks instead of failing.
|
||
dsn := "file:" + path + "?_pragma=journal_mode(WAL)&_pragma=busy_timeout(5000)&_pragma=foreign_keys(ON)"
|
||
sqldb, err := sql.Open("sqlite", dsn)
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
// SQLite allows one writer; a single connection avoids "database is
|
||
// locked" between our own goroutines.
|
||
sqldb.SetMaxOpenConns(1)
|
||
if err := sqldb.Ping(); err != nil {
|
||
sqldb.Close()
|
||
return nil, fmt.Errorf("opening %s: %w", path, err)
|
||
}
|
||
d := &DB{sqldb}
|
||
if BeforeMigrate != nil {
|
||
var version int
|
||
if err := d.QueryRow(`PRAGMA user_version`).Scan(&version); err != nil {
|
||
sqldb.Close()
|
||
return nil, err
|
||
}
|
||
if version > 0 && version < len(migrations) {
|
||
if err := BeforeMigrate(sqldb, version, len(migrations)); err != nil {
|
||
sqldb.Close()
|
||
return nil, fmt.Errorf("backing up before migrating to schema %d: %w", len(migrations), err)
|
||
}
|
||
}
|
||
}
|
||
if err := d.migrate(); err != nil {
|
||
sqldb.Close()
|
||
return nil, err
|
||
}
|
||
return d, nil
|
||
}
|
||
|
||
func (d *DB) migrate() error {
|
||
var version int
|
||
if err := d.QueryRow(`PRAGMA user_version`).Scan(&version); err != nil {
|
||
return err
|
||
}
|
||
if version > len(migrations) {
|
||
return fmt.Errorf("the database is from a newer Supermarket (schema %d, this version knows %d); update Supermarket", version, len(migrations))
|
||
}
|
||
for i := version; i < len(migrations); i++ {
|
||
tx, err := d.Begin()
|
||
if err != nil {
|
||
return err
|
||
}
|
||
if _, err := tx.Exec(migrations[i]); err != nil {
|
||
tx.Rollback()
|
||
return fmt.Errorf("migration %d: %w", i+1, err)
|
||
}
|
||
// PRAGMA can't take a bound parameter; i+1 is our own integer.
|
||
if _, err := tx.Exec(fmt.Sprintf(`PRAGMA user_version = %d`, i+1)); err != nil {
|
||
tx.Rollback()
|
||
return err
|
||
}
|
||
if err := tx.Commit(); err != nil {
|
||
return err
|
||
}
|
||
}
|
||
return nil
|
||
}
|
||
|
||
// GetJSON reads the setting key into out. It reports false, with out
|
||
// untouched, if the setting doesn't exist.
|
||
func (d *DB) GetJSON(key string, out any) (bool, error) {
|
||
var raw string
|
||
err := d.QueryRow(`SELECT value FROM settings WHERE key = ?`, key).Scan(&raw)
|
||
if errors.Is(err, sql.ErrNoRows) {
|
||
return false, nil
|
||
}
|
||
if err != nil {
|
||
return false, err
|
||
}
|
||
if err := json.Unmarshal([]byte(raw), out); err != nil {
|
||
return false, fmt.Errorf("setting %s: %w", key, err)
|
||
}
|
||
return true, nil
|
||
}
|
||
|
||
// PutJSON stores v as the setting key.
|
||
func (d *DB) PutJSON(key string, v any) error {
|
||
raw, err := json.Marshal(v)
|
||
if err != nil {
|
||
return err
|
||
}
|
||
_, err = d.Exec(`INSERT INTO settings (key, value) VALUES (?, ?)
|
||
ON CONFLICT (key) DO UPDATE SET value = excluded.value`, key, string(raw))
|
||
return err
|
||
}
|