Every analytics tool wants a subscription. And your data. I built Twiligent instead. YouTube stats. Instagram stats. One dashboard. Runs locally on your machine.
feat(database): add a schema tree with one file per object
spacesdrivea92894b86fff
diff --git a/backend/tests/database/migrations.test.ts b/backend/tests/database/migrations.test.tsindex 94db344..2172461 100644--- a/backend/tests/database/migrations.test.ts+++ b/backend/tests/database/migrations.test.ts@@ -10,6 +10,42 @@ const read = (folder: string, name: string) => readFileSync(`${supabase}${folderconst isBaseline = (name: string) => /^\d{14}_baseline_/.test(name);// migrations before this version were applied to production before the rule and stay as recordedconst ONE_ENTITY_FROM = '20261016100000';+// a name starts with what the file does to its one entity, so the folder reads as a list of changes+const VERBS = ['baseline', 'create', 'alter', 'add', 'index', 'revoke', 'check', 'replace', 'drop', 'rename'];+const KINDS = ['table', 'index', 'function', 'trigger'] as const;+type ObjectKind = typeof KINDS[number];++function isRealUtcTime(version: string): boolean {+ const [year, month, day, hour, minute, second] = [[0, 4], [4, 6], [6, 8], [8, 10], [10, 12], [12, 14]].map(([from, to]) => Number(version.slice(from, to)));+ const time = new Date(Date.UTC(year, month - 1, day, hour, minute, second));+ return time.toISOString().replace(/\D/g, '').slice(0, 14) === version;+}++// replays every create and drop in order, so an index dropped and made again counts once+function objectsFromMigrations(): Record<ObjectKind, string[]> {+ const live = Object.fromEntries(KINDS.map(kind => [kind, new Set<string>()])) as Record<ObjectKind, Set<string>>;+ const statement = /\b(create|drop)\s+(?:or replace\s+)?(table|unique index|index|function|trigger)\s+(?:if (?:not )?exists\s+)?(?:public\.)?(\w+)/gi;+ for (const name of migrations) {+ const sql = read('migrations', name).replace(/--.*$/gm, '');+ for (const [, verb, kind, object] of sql.matchAll(statement)) {+ const set = live[kind.toLowerCase().replace('unique ', '') as ObjectKind];+ if (verb.toLowerCase() === 'create') set.add(object);+ else set.delete(object);+ }+ }+ return Object.fromEntries(KINDS.map(kind => [kind, [...live[kind]].sort()])) as Record<ObjectKind, string[]>;+}++function objectsInSchemaTree(): Record<ObjectKind, string[]> {+ const tables = readdirSync(`${supabase}schemas/public/tables`);+ const inTables = (pattern: RegExp) => tables.flatMap(file => [...read('schemas/public/tables', file).matchAll(pattern)].map(match => match[1]));+ return {+ table: tables.map(file => file.replace(/\.sql$/, '')).sort(),+ index: inTables(/CREATE (?:UNIQUE )?INDEX (\w+)/g).sort(),+ function: readdirSync(`${supabase}schemas/public/functions`).map(file => file.replace(/\.sql$/, '')).sort(),+ trigger: inTables(/CREATE TRIGGER (\w+)/g).sort(),+ };+}describe('database migrations', () => {test('every migration is named <14 digit version>_<lowercase name>.sql with a unique version', () => {@@ -18,6 +54,20 @@ describe('database migrations', () => {assert.equal(new Set(versions).size, versions.length);});+ test('every version is a real UTC date and time, as npm run db:new writes it', () => {+ for (const name of migrations) assert.ok(isRealUtcTime(name.slice(0, 14)), `${name}: make the file with npm run db:new`);+ });++ test('every name starts with what the file does: baseline, create, alter, add, index, revoke, check, replace, drop or rename', () => {+ for (const name of migrations) assert.ok(VERBS.includes(name.slice(15).split('_')[0]), name);+ });++ test('the schema tree in supabase/schemas has the same tables, indexes, functions and triggers as the migrations', () => {+ const fromMigrations = objectsFromMigrations();+ const inTree = objectsInSchemaTree();+ for (const kind of KINDS) assert.deepEqual(inTree[kind], fromMigrations[kind], `${kind}s differ; after npm run db:push, run npm run db:schema and commit supabase/schemas`);+ });+test('the baseline files come before every change, so a new instance starts from the same tables', () => {const lastBaseline = migrations.findLastIndex(isBaseline);const firstChange = migrations.findIndex(name => !isBaseline(name));diff --git a/package.json b/package.jsonindex f23365f..8dee155 100644--- a/package.json+++ b/package.json@@ -21,7 +21,8 @@"db:new": "supabase migration new","db:status": "supabase migration list","db:check": "supabase db push --dry-run",- "db:push": "supabase db push"+ "db:push": "supabase db push",+ "db:schema": "supabase db schema declarative generate --linked --schema public --overwrite --yes"},"devDependencies": {"@eslint/js": "^9.39.1",diff --git a/supabase/schemas/.pgdelta-export.json b/supabase/schemas/.pgdelta-export.jsonnew file mode 100644index 0000000..ad827ca--- /dev/null+++ b/supabase/schemas/.pgdelta-export.json@@ -0,0 +1,91 @@+{+ "formatVersion": 1,+ "redactSecrets": true,+ "scope": "database",+ "loadOrder": [+ "public/schema.sql",+ "public/adp_wipes.sql",+ "_cluster/extensions/pgcrypto.sql",+ "_cluster/extensions/uuid-ossp.sql",+ "public/tables/accounts.sql",+ "public/tables/audit_events.sql",+ "public/tables/automation_accounts.sql",+ "public/tables/automation_attempts.sql",+ "public/tables/automation_comments.sql",+ "public/tables/automation_followups.sql",+ "public/tables/automation_public_replies.sql",+ "public/tables/automation_rules.sql",+ "public/tables/scheduled_posts.sql",+ "public/tables/settings.sql",+ "public/tables/tracked_posts.sql",+ "public/functions/automation_followups_for_messages.sql",+ "public/functions/automation_public_review_candidates.sql",+ "public/functions/automation_queue_health.sql",+ "public/functions/automation_review_candidates.sql",+ "public/functions/automation_rules_for_ig_user.sql",+ "public/functions/automation_stats.sql",+ "public/functions/claim_automation_comments.sql",+ "public/functions/claim_automation_followups.sql",+ "public/functions/claim_automation_public_replies.sql",+ "public/functions/expire_automation_jobs.sql",+ "public/functions/finish_automation_followup.sql",+ "public/functions/finish_automation_public_reply.sql",+ "public/functions/finish_automation_send.sql",+ "public/functions/merge_account_data.sql",+ "public/functions/merge_scheduled_post.sql",+ "public/functions/merge_tracked_post_data.sql",+ "public/functions/purge_automation_comments.sql",+ "public/functions/record_automation_public_review.sql",+ "public/functions/record_automation_review.sql",+ "public/functions/reserve_automation_followup.sql",+ "public/functions/reserve_automation_public_reply.sql",+ "public/functions/reserve_automation_send.sql",+ "public/functions/set_updated_at.sql",+ "public/functions/store_automation_comments.sql",+ "public/default_privileges.sql"+ ],+ "profile": "supabase",+ "defaultOwner": "postgres",+ "files": [+ "_cluster/extensions/pgcrypto.sql",+ "_cluster/extensions/uuid-ossp.sql",+ "public/adp_wipes.sql",+ "public/default_privileges.sql",+ "public/functions/automation_followups_for_messages.sql",+ "public/functions/automation_public_review_candidates.sql",+ "public/functions/automation_queue_health.sql",+ "public/functions/automation_review_candidates.sql",+ "public/functions/automation_rules_for_ig_user.sql",+ "public/functions/automation_stats.sql",+ "public/functions/claim_automation_comments.sql",+ "public/functions/claim_automation_followups.sql",+ "public/functions/claim_automation_public_replies.sql",+ "public/functions/expire_automation_jobs.sql",+ "public/functions/finish_automation_followup.sql",+ "public/functions/finish_automation_public_reply.sql",+ "public/functions/finish_automation_send.sql",+ "public/functions/merge_account_data.sql",+ "public/functions/merge_scheduled_post.sql",+ "public/functions/merge_tracked_post_data.sql",+ "public/functions/purge_automation_comments.sql",+ "public/functions/record_automation_public_review.sql",+ "public/functions/record_automation_review.sql",+ "public/functions/reserve_automation_followup.sql",+ "public/functions/reserve_automation_public_reply.sql",+ "public/functions/reserve_automation_send.sql",+ "public/functions/set_updated_at.sql",+ "public/functions/store_automation_comments.sql",+ "public/schema.sql",+ "public/tables/accounts.sql",+ "public/tables/audit_events.sql",+ "public/tables/automation_accounts.sql",+ "public/tables/automation_attempts.sql",+ "public/tables/automation_comments.sql",+ "public/tables/automation_followups.sql",+ "public/tables/automation_public_replies.sql",+ "public/tables/automation_rules.sql",+ "public/tables/scheduled_posts.sql",+ "public/tables/settings.sql",+ "public/tables/tracked_posts.sql"+ ]+}diff --git a/supabase/schemas/_cluster/extensions/pgcrypto.sql b/supabase/schemas/_cluster/extensions/pgcrypto.sqlnew file mode 100644index 0000000..4187b2d--- /dev/null+++ b/supabase/schemas/_cluster/extensions/pgcrypto.sql@@ -0,0 +1,3 @@+CREATE EXTENSION "pgcrypto" SCHEMA "extensions";++COMMENT ON EXTENSION "pgcrypto" IS 'cryptographic functions';diff --git a/supabase/schemas/_cluster/extensions/uuid-ossp.sql b/supabase/schemas/_cluster/extensions/uuid-ossp.sqlnew file mode 100644index 0000000..2e501ea--- /dev/null+++ b/supabase/schemas/_cluster/extensions/uuid-ossp.sql@@ -0,0 +1,3 @@+CREATE EXTENSION "uuid-ossp" SCHEMA "extensions";++COMMENT ON EXTENSION "uuid-ossp" IS 'generate universally unique identifiers (UUIDs)';diff --git a/supabase/schemas/public/adp_wipes.sql b/supabase/schemas/public/adp_wipes.sqlnew file mode 100644index 0000000..bed13ff--- /dev/null+++ b/supabase/schemas/public/adp_wipes.sql@@ -0,0 +1,20 @@+-- Clears assumed destination defaults before creating objects.+-- Safe to load on a project that does not have those defaults.++ALTER DEFAULT PRIVILEGES FOR ROLE "postgres" IN SCHEMA "public" REVOKE ALL ON SEQUENCES FROM "anon";++ALTER DEFAULT PRIVILEGES FOR ROLE "postgres" IN SCHEMA "public" REVOKE ALL ON SEQUENCES FROM "authenticated";++ALTER DEFAULT PRIVILEGES FOR ROLE "postgres" IN SCHEMA "public" REVOKE ALL ON SEQUENCES FROM "service_role";++ALTER DEFAULT PRIVILEGES FOR ROLE "postgres" IN SCHEMA "public" REVOKE ALL ON FUNCTIONS FROM "anon";++ALTER DEFAULT PRIVILEGES FOR ROLE "postgres" IN SCHEMA "public" REVOKE ALL ON FUNCTIONS FROM "authenticated";++ALTER DEFAULT PRIVILEGES FOR ROLE "postgres" IN SCHEMA "public" REVOKE ALL ON FUNCTIONS FROM "service_role";++ALTER DEFAULT PRIVILEGES FOR ROLE "postgres" IN SCHEMA "public" REVOKE ALL ON TABLES FROM "anon";++ALTER DEFAULT PRIVILEGES FOR ROLE "postgres" IN SCHEMA "public" REVOKE ALL ON TABLES FROM "authenticated";++ALTER DEFAULT PRIVILEGES FOR ROLE "postgres" IN SCHEMA "public" REVOKE ALL ON TABLES FROM "service_role";diff --git a/supabase/schemas/public/default_privileges.sql b/supabase/schemas/public/default_privileges.sqlnew file mode 100644index 0000000..20e163d--- /dev/null+++ b/supabase/schemas/public/default_privileges.sql@@ -0,0 +1,11 @@+ALTER DEFAULT PRIVILEGES FOR ROLE "postgres" IN SCHEMA "public" GRANT SELECT, UPDATE, USAGE ON SEQUENCES TO "anon";++ALTER DEFAULT PRIVILEGES FOR ROLE "postgres" IN SCHEMA "public" GRANT SELECT, UPDATE, USAGE ON SEQUENCES TO "authenticated";++ALTER DEFAULT PRIVILEGES FOR ROLE "postgres" IN SCHEMA "public" GRANT SELECT, UPDATE, USAGE ON SEQUENCES TO "service_role";++ALTER DEFAULT PRIVILEGES FOR ROLE "postgres" IN SCHEMA "public" REVOKE ALL ON FUNCTIONS FROM PUBLIC;++ALTER DEFAULT PRIVILEGES FOR ROLE "postgres" IN SCHEMA "public" GRANT EXECUTE ON FUNCTIONS TO "service_role";++ALTER DEFAULT PRIVILEGES FOR ROLE "postgres" IN SCHEMA "public" GRANT DELETE, INSERT, MAINTAIN, REFERENCES, SELECT, TRIGGER, TRUNCATE, UPDATE ON TABLES TO "service_role";diff --git a/supabase/schemas/public/functions/automation_followups_for_messages.sql b/supabase/schemas/public/functions/automation_followups_for_messages.sqlnew file mode 100644index 0000000..c63bddd--- /dev/null+++ b/supabase/schemas/public/functions/automation_followups_for_messages.sql@@ -0,0 +1,45 @@+CREATE OR REPLACE FUNCTION public.automation_followups_for_messages (+ p_ig_user_id text,+ p_messages jsonb+)+ RETURNS TABLE (+ id text+ )+ LANGUAGE sql+ SET search_path TO ''+ AS $function$+ with incoming as (+ select m.id, m.sender_id, m.message_id, m.sent_at+ from jsonb_to_recordset(p_messages) as m (id text, sender_id text, message_id text, sent_at timestamptz)+ where m.id is not null and m.sender_id is not null and m.message_id is not null and m.sent_at is not null+ ),+ waiting as (+ -- the sender's newest reply that waits for them; a minute of slack covers the two clocks, and a reply older+ -- than 7 days no longer waits+ select distinct on (i.message_id)+ i.id as followup_id, i.message_id, i.sent_at, c.id as comment_id, c.user_id, c.account_id, c.recipient_id+ from incoming i+ join public.automation_comments c+ on c.ig_user_id = p_ig_user_id and c.recipient_id = i.sender_id and c.gate_status = 'awaiting_reply'+ and c.accepted_at <= i.sent_at + interval '1 minute' and c.accepted_at > i.sent_at - interval '7 days'+ order by i.message_id, c.accepted_at desc+ )+ insert into public.automation_followups as f (+ id, user_id, account_id, automation_comment_id, ig_user_id, recipient_id, trigger_message_id, status,+ next_attempt_at, window_expires_at+ )+ select w.followup_id, w.user_id, w.account_id, w.comment_id, p_ig_user_id, w.recipient_id, w.message_id, 'queued',+ now() - interval '30 seconds', w.sent_at + interval '1 day'+ from waiting w+ order by w.sent_at+ on conflict do nothing+ returning f.id;+$function$;++GRANT EXECUTE ON FUNCTION "public"."automation_followups_for_messages"(text, jsonb) TO "service_role";++REVOKE ALL ON FUNCTION "public"."automation_followups_for_messages"(text, jsonb) FROM "postgres";++GRANT EXECUTE ON FUNCTION "public"."automation_followups_for_messages"(text, jsonb) TO "postgres";++REVOKE ALL ON FUNCTION "public"."automation_followups_for_messages"(text, jsonb) FROM PUBLIC, "anon", "authenticated";diff --git a/supabase/schemas/public/functions/automation_public_review_candidates.sql b/supabase/schemas/public/functions/automation_public_review_candidates.sqlnew file mode 100644index 0000000..67b5b60--- /dev/null+++ b/supabase/schemas/public/functions/automation_public_review_candidates.sql@@ -0,0 +1,47 @@+CREATE OR REPLACE FUNCTION public.automation_public_review_candidates (+ p_limit integer,+ p_settle_seconds integer,+ p_max_checks integer,+ p_recheck_seconds integer+)+ RETURNS TABLE (+ id text,+ ig_user_id text,+ comment_id text,+ started_at timestamp with time zone,+ message_digest text,+ access_token text,+ review_checks integer,+ ambiguous_attempts integer+ )+ LANGUAGE sql+ STABLE+ SET search_path TO ''+ AS $function$+ select p.id, p.ig_user_id, p.comment_id, t.started_at, t.message_digest, a.data ->> 'accessToken', p.review_checks,+ (select count(*)::integer from public.automation_attempts x where x.public_reply_id = p.id and x.outcome = 'ambiguous')+ from public.automation_public_replies p+ join lateral (+ select t.started_at, t.message_digest+ from public.automation_attempts t+ where t.public_reply_id = p.id and t.outcome = 'ambiguous'+ order by t.started_at desc+ limit 1+ ) t on true+ join public.accounts a on a.id = p.account_id and a.user_id = p.user_id+ where p.status = 'needs_review'+ and p.status_reason in ('no_answer', 'interrupted')+ and p.review_checks < p_max_checks+ and (p.review_checked_at is null or p.review_checked_at < now() - make_interval(secs => p_recheck_seconds))+ and t.started_at < now() - make_interval(secs => p_settle_seconds)+ order by p.review_checked_at nulls first, p.updated_at+ limit p_limit;+$function$;++GRANT EXECUTE ON FUNCTION "public"."automation_public_review_candidates"(integer, integer, integer, integer) TO "service_role";++REVOKE ALL ON FUNCTION "public"."automation_public_review_candidates"(integer, integer, integer, integer) FROM "postgres";++GRANT EXECUTE ON FUNCTION "public"."automation_public_review_candidates"(integer, integer, integer, integer) TO "postgres";++REVOKE ALL ON FUNCTION "public"."automation_public_review_candidates"(integer, integer, integer, integer) FROM PUBLIC, "anon", "authenticated";diff --git a/supabase/schemas/public/functions/automation_queue_health.sql b/supabase/schemas/public/functions/automation_queue_health.sqlnew file mode 100644index 0000000..ec15b53--- /dev/null+++ b/supabase/schemas/public/functions/automation_queue_health.sql@@ -0,0 +1,64 @@+CREATE OR REPLACE FUNCTION public.automation_queue_health (+ p_lease_seconds integer+)+ RETURNS jsonb+ LANGUAGE sql+ STABLE+ SET search_path TO ''+ AS $function$+ select jsonb_build_object(+ 'due', (+ select count(*) from public.automation_comments c+ where c.status in ('queued', 'retry_wait') and c.next_attempt_at <= now()+ ),+ 'oldest_due_at', (+ select min(c.next_attempt_at) from public.automation_comments c+ where c.status in ('queued', 'retry_wait') and c.next_attempt_at <= now()+ ),+ 'waiting', (+ select count(*) from public.automation_comments c where c.status in ('queued', 'retry_wait')+ ),+ 'stale', (+ select count(*) from public.automation_comments c+ where c.status in ('processing', 'sending') and c.claimed_at < now() - make_interval(secs => p_lease_seconds)+ ),+ 'needs_review', (+ select count(*) from public.automation_comments c where c.status = 'needs_review'+ ),+ 'followups_due', (+ select count(*) from public.automation_followups f+ where f.status in ('queued', 'retry_wait') and f.next_attempt_at <= now()+ ),+ 'public_due', (+ select count(*) from public.automation_public_replies p+ where p.status in ('queued', 'retry_wait') and p.next_attempt_at <= now()+ ),+ 'public_oldest_due_at', (+ select min(p.next_attempt_at) from public.automation_public_replies p+ where p.status in ('queued', 'retry_wait') and p.next_attempt_at <= now()+ ),+ 'public_stale', (+ select count(*) from public.automation_public_replies p+ where p.status in ('processing', 'sending') and p.claimed_at < now() - make_interval(secs => p_lease_seconds)+ ),+ 'public_needs_review', (+ select count(*) from public.automation_public_replies p where p.status = 'needs_review'+ ),+ 'paused_accounts', (+ select count(*) from public.automation_accounts a where a.paused+ ),+ 'limited_accounts', (+ select count(*) from public.automation_accounts a+ where a.cooldown_until > now() or a.limited_until > now()+ or a.public_cooldown_until > now() or a.public_limited_until > now()+ )+ );+$function$;++GRANT EXECUTE ON FUNCTION "public"."automation_queue_health"(integer) TO "service_role";++REVOKE ALL ON FUNCTION "public"."automation_queue_health"(integer) FROM "postgres";++GRANT EXECUTE ON FUNCTION "public"."automation_queue_health"(integer) TO "postgres";++REVOKE ALL ON FUNCTION "public"."automation_queue_health"(integer) FROM PUBLIC, "anon", "authenticated";diff --git a/supabase/schemas/public/functions/automation_review_candidates.sql b/supabase/schemas/public/functions/automation_review_candidates.sqlnew file mode 100644index 0000000..deb0cc7--- /dev/null+++ b/supabase/schemas/public/functions/automation_review_candidates.sql@@ -0,0 +1,46 @@+CREATE OR REPLACE FUNCTION public.automation_review_candidates (+ p_limit integer,+ p_settle_seconds integer,+ p_max_checks integer,+ p_recheck_seconds integer+)+ RETURNS TABLE (+ id text,+ ig_user_id text,+ from_id text,+ started_at timestamp with time zone,+ message_digest text,+ access_token text,+ review_checks integer+ )+ LANGUAGE sql+ STABLE+ SET search_path TO ''+ AS $function$+ select c.id, c.ig_user_id, c.from_id, t.started_at, t.message_digest, a.data ->> 'accessToken', c.review_checks+ from public.automation_comments c+ join lateral (+ select t.started_at, t.message_digest+ from public.automation_attempts t+ where t.automation_comment_id = c.id and t.kind = 'private_reply' and t.outcome = 'ambiguous'+ order by t.started_at desc+ limit 1+ ) t on true+ join public.accounts a on a.id = c.account_id and a.user_id = c.user_id+ where c.status = 'needs_review'+ and c.status_reason in ('no_answer', 'interrupted')+ and c.from_id is not null+ and c.review_checks < p_max_checks+ and (c.review_checked_at is null or c.review_checked_at < now() - make_interval(secs => p_recheck_seconds))+ and t.started_at < now() - make_interval(secs => p_settle_seconds)+ order by c.review_checked_at nulls first, c.updated_at+ limit p_limit;+$function$;++GRANT EXECUTE ON FUNCTION "public"."automation_review_candidates"(integer, integer, integer, integer) TO "service_role";++REVOKE ALL ON FUNCTION "public"."automation_review_candidates"(integer, integer, integer, integer) FROM "postgres";++GRANT EXECUTE ON FUNCTION "public"."automation_review_candidates"(integer, integer, integer, integer) TO "postgres";++REVOKE ALL ON FUNCTION "public"."automation_review_candidates"(integer, integer, integer, integer) FROM PUBLIC, "anon", "authenticated";diff --git a/supabase/schemas/public/functions/automation_rules_for_ig_user.sql b/supabase/schemas/public/functions/automation_rules_for_ig_user.sqlnew file mode 100644index 0000000..28c51ca--- /dev/null+++ b/supabase/schemas/public/functions/automation_rules_for_ig_user.sql@@ -0,0 +1,37 @@+CREATE OR REPLACE FUNCTION public.automation_rules_for_ig_user (+ p_ig_user_id text+)+ RETURNS TABLE (+ id text,+ user_id uuid,+ account_id text,+ keywords text[],+ match_mode text,+ case_sensitive boolean,+ media_ids text[],+ created_at timestamp with time zone,+ private_reply_enabled boolean,+ public_reply_enabled boolean,+ public_reply_texts text[]+ )+ LANGUAGE sql+ STABLE+ SET search_path TO ''+ AS $function$+ select r.id, r.user_id, r.account_id, r.keywords, r.match_mode, r.case_sensitive, r.media_ids, r.created_at,+ r.private_reply_enabled, r.public_reply_enabled, r.public_reply_texts+ from public.accounts a+ join public.automation_rules r on r.account_id = a.id and r.user_id = a.user_id+ where a.platform = 'instagram'+ and a.data ->> 'igUserId' = p_ig_user_id+ and r.enabled+ order by a.created_at, a.id, r.created_at, r.id;+$function$;++GRANT EXECUTE ON FUNCTION "public"."automation_rules_for_ig_user"(text) TO "service_role";++REVOKE ALL ON FUNCTION "public"."automation_rules_for_ig_user"(text) FROM "postgres";++GRANT EXECUTE ON FUNCTION "public"."automation_rules_for_ig_user"(text) TO "postgres";++REVOKE ALL ON FUNCTION "public"."automation_rules_for_ig_user"(text) FROM PUBLIC, "anon", "authenticated";diff --git a/supabase/schemas/public/functions/automation_stats.sql b/supabase/schemas/public/functions/automation_stats.sqlnew file mode 100644index 0000000..90e204a--- /dev/null+++ b/supabase/schemas/public/functions/automation_stats.sql@@ -0,0 +1,59 @@+CREATE OR REPLACE FUNCTION public.automation_stats (+ p_user_id uuid,+ p_from timestamp with time zone,+ p_to timestamp with time zone,+ p_account_id text DEFAULT NULL::text,+ p_rule_id text DEFAULT NULL::text+)+ RETURNS jsonb+ LANGUAGE sql+ STABLE+ SET search_path TO ''+ AS $function$+ select jsonb_build_object(+ 'comments', coalesce((+ select jsonb_object_agg(counted.status, counted.total)+ from (+ select c.status, count(*) as total+ from public.automation_comments c+ where c.user_id = p_user_id+ and c.created_at >= p_from and c.created_at < p_to+ and (p_account_id is null or c.account_id = p_account_id)+ and (p_rule_id is null or c.rule_id = p_rule_id)+ group by c.status+ ) counted+ ), '{}'::jsonb),+ 'public_replies', coalesce((+ select jsonb_object_agg(counted.status, counted.total)+ from (+ select p.status, count(*) as total+ from public.automation_public_replies p+ where p.user_id = p_user_id+ and p.created_at >= p_from and p.created_at < p_to+ and (p_account_id is null or p.account_id = p_account_id)+ and (p_rule_id is null or p.rule_id = p_rule_id)+ group by p.status+ ) counted+ ), '{}'::jsonb),+ 'attempts', coalesce((+ select jsonb_object_agg(counted.outcome, counted.total)+ from (+ select t.outcome, count(*) as total+ from public.automation_attempts t+ where t.user_id = p_user_id+ and t.started_at >= p_from and t.started_at < p_to+ and (p_account_id is null or t.account_id = p_account_id)+ and (p_rule_id is null or t.rule_id = p_rule_id)+ group by t.outcome+ ) counted+ ), '{}'::jsonb)+ );+$function$;++GRANT EXECUTE ON FUNCTION "public"."automation_stats"(uuid, timestamp WITH time zone, timestamp WITH time zone, text, text) TO "service_role";++REVOKE ALL ON FUNCTION "public"."automation_stats"(uuid, timestamp WITH time zone, timestamp WITH time zone, text, text) FROM "postgres";++GRANT EXECUTE ON FUNCTION "public"."automation_stats"(uuid, timestamp WITH time zone, timestamp WITH time zone, text, text) TO "postgres";++REVOKE ALL ON FUNCTION "public"."automation_stats"(uuid, timestamp WITH time zone, timestamp WITH time zone, text, text) FROM PUBLIC, "anon", "authenticated";diff --git a/supabase/schemas/public/functions/claim_automation_comments.sql b/supabase/schemas/public/functions/claim_automation_comments.sqlnew file mode 100644index 0000000..e401bf1--- /dev/null+++ b/supabase/schemas/public/functions/claim_automation_comments.sql@@ -0,0 +1,140 @@+CREATE OR REPLACE FUNCTION public.claim_automation_comments (+ p_limit integer,+ p_per_account integer,+ p_lease_seconds integer,+ p_ids text[] DEFAULT NULL::text[]+)+ RETURNS TABLE (+ id text,+ user_id uuid,+ account_id text,+ rule_id text,+ ig_user_id text,+ comment_id text,+ from_id text,+ attempts integer,+ expires_at timestamp with time zone,+ rule_enabled boolean,+ reply_text text,+ link_url text,+ access_token text,+ require_follow boolean,+ follow_prompt_text text+ )+ LANGUAGE plpgsql+ SET search_path TO ''+ AS $function$+#variable_conflict use_column+declare+ stale_before timestamptz := now() - make_interval(secs => p_lease_seconds);+begin+ -- a send whose run stopped may have reached Instagram, so a person decides instead of a second send+ with interrupted as (+ update public.automation_comments c+ set status = 'needs_review',+ status_reason = 'interrupted',+ claimed_at = null,+ error_message = 'The run stopped while this reply was being sent. Check the conversation on Instagram before you retry.'+ where c.status = 'sending' and c.claimed_at < stale_before+ returning c.id+ )+ update public.automation_attempts t+ set outcome = 'ambiguous', finished_at = now()+ where t.automation_comment_id in (select interrupted.id from interrupted) and t.outcome = 'sending';++ return query+ with recursive waiting_accounts as (+ -- one index probe per account instead of reading every waiting job, however long one account's queue is+ (select c.account_id+ from public.automation_comments c+ where c.status in ('queued', 'retry_wait') and p_ids is null+ order by c.account_id+ limit 1)+ union all+ select (select c.account_id+ from public.automation_comments c+ where c.status in ('queued', 'retry_wait') and c.account_id > w.account_id+ order by c.account_id+ limit 1)+ from waiting_accounts w+ where w.account_id is not null+ ),+ due_accounts as (+ select w.account_id from waiting_accounts w where w.account_id is not null+ union+ select c.account_id from public.automation_comments c where c.id = any (p_ids)+ union+ select c.account_id+ from public.automation_comments c+ where c.status = 'processing' and c.claimed_at < stale_before and (p_ids is null or c.id = any (p_ids))+ ),+ open_accounts as (+ select d.account_id+ from due_accounts d+ left join public.automation_accounts s on s.account_id = d.account_id+ where s.account_id is null+ or (not s.paused+ and (s.cooldown_until is null or s.cooldown_until <= now())+ and (s.limited_until is null or s.limited_until <= now()))+ ),+ -- each account's oldest due jobs, locked as they are read: a job another run holds is skipped, so runs at the+ -- same moment take the next jobs instead of the same ones+ candidates as (+ select x.id, x.account_id, x.next_attempt_at as due_at+ from open_accounts o+ cross join lateral (+ select c.id, c.account_id, c.next_attempt_at+ from public.automation_comments c+ where c.account_id = o.account_id and c.status in ('queued', 'retry_wait') and c.next_attempt_at <= now()+ and (p_ids is null or c.id = any (p_ids))+ order by c.next_attempt_at+ limit p_per_account+ for update of c skip locked+ ) x+ union all+ select x.id, x.account_id, x.claimed_at as due_at+ from open_accounts o+ cross join lateral (+ select c.id, c.account_id, c.claimed_at+ from public.automation_comments c+ where c.account_id = o.account_id and c.status = 'processing' and c.claimed_at < stale_before+ and (p_ids is null or c.id = any (p_ids))+ order by c.claimed_at+ limit p_per_account+ for update of c skip locked+ ) x+ ),+ picked as (+ select ranked.id+ from (+ select candidates.id, candidates.due_at,+ row_number() over (partition by candidates.account_id order by candidates.due_at, candidates.id) as place+ from candidates+ ) ranked+ order by ranked.place, ranked.due_at+ limit p_limit+ ),+ claimed as (+ update public.automation_comments c+ set status = 'processing', claimed_at = now()+ from picked+ where c.id = picked.id+ returning c.id, c.user_id, c.account_id, c.rule_id, c.ig_user_id, c.comment_id, c.from_id, c.attempts, c.expires_at+ )+ select claimed.id, claimed.user_id, claimed.account_id, claimed.rule_id, claimed.ig_user_id, claimed.comment_id,+ claimed.from_id, claimed.attempts, claimed.expires_at,+ coalesce(r.enabled and r.private_reply_enabled, false), r.reply_text, r.link_url, a.data ->> 'accessToken',+ coalesce(r.require_follow, false), r.follow_prompt_text+ from claimed+ left join public.automation_rules r on r.id = claimed.rule_id+ left join public.accounts a on a.id = claimed.account_id and a.user_id = claimed.user_id;+end;+$function$;++GRANT EXECUTE ON FUNCTION "public"."claim_automation_comments"(integer, integer, integer, text[]) TO "service_role";++REVOKE ALL ON FUNCTION "public"."claim_automation_comments"(integer, integer, integer, text[]) FROM "postgres";++GRANT EXECUTE ON FUNCTION "public"."claim_automation_comments"(integer, integer, integer, text[]) TO "postgres";++REVOKE ALL ON FUNCTION "public"."claim_automation_comments"(integer, integer, integer, text[]) FROM PUBLIC, "anon", "authenticated";diff --git a/supabase/schemas/public/functions/claim_automation_followups.sql b/supabase/schemas/public/functions/claim_automation_followups.sqlnew file mode 100644index 0000000..0190613--- /dev/null+++ b/supabase/schemas/public/functions/claim_automation_followups.sql@@ -0,0 +1,107 @@+CREATE OR REPLACE FUNCTION public.claim_automation_followups (+ p_limit integer,+ p_lease_seconds integer,+ p_ids text[] DEFAULT NULL::text[]+)+ RETURNS TABLE (+ id text,+ user_id uuid,+ account_id text,+ automation_comment_id text,+ ig_user_id text,+ recipient_id text,+ attempts integer,+ window_expires_at timestamp with time zone,+ gate_status text,+ gate_prompts integer,+ rule_enabled boolean,+ require_follow boolean,+ reply_text text,+ link_url text,+ not_following_text text,+ access_token text+ )+ LANGUAGE plpgsql+ SET search_path TO ''+ AS $function$+#variable_conflict use_column+declare+ stale_before timestamptz := now() - make_interval(secs => p_lease_seconds);+begin+ -- as with private replies, a send whose run stopped may have arrived, so a person decides+ with interrupted as (+ update public.automation_followups f+ set status = 'needs_review',+ status_reason = 'interrupted',+ claimed_at = null,+ error_message = 'The run stopped while this message was being sent. Check the conversation on Instagram before you retry.'+ where f.status = 'sending' and f.claimed_at < stale_before+ returning f.id+ )+ update public.automation_attempts t+ set outcome = 'ambiguous', finished_at = now()+ where t.followup_id in (select interrupted.id from interrupted) and t.outcome = 'sending';++ return query+ with due_accounts as (+ select distinct f.account_id+ from public.automation_followups f+ where ((f.status in ('queued', 'retry_wait') and f.next_attempt_at <= now())+ or (f.status = 'processing' and f.claimed_at < stale_before))+ and (p_ids is null or f.id = any (p_ids))+ ),+ open_accounts as (+ select d.account_id+ from due_accounts d+ left join public.automation_accounts s on s.account_id = d.account_id+ where s.account_id is null or (not s.paused and (s.cooldown_until is null or s.cooldown_until <= now()))+ ),+ candidates as (+ select x.id, x.due_at, row_number() over (partition by o.account_id order by x.due_at, x.id) as place+ from open_accounts o+ cross join lateral (+ select f.id, coalesce(f.next_attempt_at, f.claimed_at) as due_at+ from public.automation_followups f+ where f.account_id = o.account_id+ and ((f.status in ('queued', 'retry_wait') and f.next_attempt_at <= now())+ or (f.status = 'processing' and f.claimed_at < stale_before))+ and (p_ids is null or f.id = any (p_ids))+ order by due_at+ limit p_limit+ ) x+ ),+ picked as (+ select f.id+ from public.automation_followups f+ join candidates on candidates.id = f.id+ where (f.status in ('queued', 'retry_wait') and f.next_attempt_at <= now())+ or (f.status = 'processing' and f.claimed_at < stale_before)+ order by candidates.place, candidates.due_at+ limit p_limit+ for update of f skip locked+ ),+ claimed as (+ update public.automation_followups f+ set status = 'processing', claimed_at = now()+ from picked+ where f.id = picked.id+ returning f.id, f.user_id, f.account_id, f.automation_comment_id, f.ig_user_id, f.recipient_id, f.attempts, f.window_expires_at+ )+ select claimed.id, claimed.user_id, claimed.account_id, claimed.automation_comment_id, claimed.ig_user_id,+ claimed.recipient_id, claimed.attempts, claimed.window_expires_at, c.gate_status, c.gate_prompts,+ coalesce(r.enabled, false), coalesce(r.require_follow, false), r.reply_text, r.link_url, r.not_following_text,+ a.data ->> 'accessToken'+ from claimed+ join public.automation_comments c on c.id = claimed.automation_comment_id+ left join public.automation_rules r on r.id = c.rule_id+ left join public.accounts a on a.id = claimed.account_id and a.user_id = claimed.user_id;+end;+$function$;++GRANT EXECUTE ON FUNCTION "public"."claim_automation_followups"(integer, integer, text[]) TO "service_role";++REVOKE ALL ON FUNCTION "public"."claim_automation_followups"(integer, integer, text[]) FROM "postgres";++GRANT EXECUTE ON FUNCTION "public"."claim_automation_followups"(integer, integer, text[]) TO "postgres";++REVOKE ALL ON FUNCTION "public"."claim_automation_followups"(integer, integer, text[]) FROM PUBLIC, "anon", "authenticated";diff --git a/supabase/schemas/public/functions/claim_automation_public_replies.sql b/supabase/schemas/public/functions/claim_automation_public_replies.sqlnew file mode 100644index 0000000..f34049a--- /dev/null+++ b/supabase/schemas/public/functions/claim_automation_public_replies.sql@@ -0,0 +1,134 @@+CREATE OR REPLACE FUNCTION public.claim_automation_public_replies (+ p_limit integer,+ p_per_account integer,+ p_lease_seconds integer,+ p_ids text[] DEFAULT NULL::text[]+)+ RETURNS TABLE (+ id text,+ user_id uuid,+ account_id text,+ rule_id text,+ ig_user_id text,+ comment_id text,+ attempts integer,+ expires_at timestamp with time zone,+ reply_text text,+ rule_enabled boolean,+ access_token text+ )+ LANGUAGE plpgsql+ SET search_path TO ''+ AS $function$+#variable_conflict use_column+declare+ stale_before timestamptz := now() - make_interval(secs => p_lease_seconds);+begin+ -- a reply whose run stopped while sending may be on Instagram; the review reads the comment's replies to find out+ with interrupted as (+ update public.automation_public_replies p+ set status = 'needs_review',+ status_reason = 'interrupted',+ claimed_at = null,+ error_message = 'The run stopped while this public reply was being sent. Twiligent checks the comment''s replies on Instagram.'+ where p.status = 'sending' and p.claimed_at < stale_before+ returning p.id+ )+ update public.automation_attempts t+ set outcome = 'ambiguous', finished_at = now()+ where t.public_reply_id in (select interrupted.id from interrupted) and t.outcome = 'sending';++ return query+ with recursive waiting_accounts as (+ -- one index probe per account instead of reading every waiting reply+ (select p.account_id+ from public.automation_public_replies p+ where p.status in ('queued', 'retry_wait') and p_ids is null+ order by p.account_id+ limit 1)+ union all+ select (select p.account_id+ from public.automation_public_replies p+ where p.status in ('queued', 'retry_wait') and p.account_id > w.account_id+ order by p.account_id+ limit 1)+ from waiting_accounts w+ where w.account_id is not null+ ),+ due_accounts as (+ select w.account_id from waiting_accounts w where w.account_id is not null+ union+ select p.account_id from public.automation_public_replies p where p.id = any (p_ids)+ union+ select p.account_id+ from public.automation_public_replies p+ where p.status = 'processing' and p.claimed_at < stale_before and (p_ids is null or p.id = any (p_ids))+ ),+ open_accounts as (+ select d.account_id+ from due_accounts d+ left join public.automation_accounts s on s.account_id = d.account_id+ where s.account_id is null+ or (not s.paused+ and (s.public_cooldown_until is null or s.public_cooldown_until <= now())+ and (s.public_limited_until is null or s.public_limited_until <= now()))+ ),+ -- locked as they are read, so runs at the same moment take different replies+ candidates as (+ select x.id, x.account_id, x.next_attempt_at as due_at+ from open_accounts o+ cross join lateral (+ select p.id, p.account_id, p.next_attempt_at+ from public.automation_public_replies p+ where p.account_id = o.account_id and p.status in ('queued', 'retry_wait') and p.next_attempt_at <= now()+ and (p_ids is null or p.id = any (p_ids))+ order by p.next_attempt_at+ limit p_per_account+ for update of p skip locked+ ) x+ union all+ select x.id, x.account_id, x.claimed_at as due_at+ from open_accounts o+ cross join lateral (+ select p.id, p.account_id, p.claimed_at+ from public.automation_public_replies p+ where p.account_id = o.account_id and p.status = 'processing' and p.claimed_at < stale_before+ and (p_ids is null or p.id = any (p_ids))+ order by p.claimed_at+ limit p_per_account+ for update of p skip locked+ ) x+ ),+ picked as (+ select ranked.id+ from (+ select candidates.id, candidates.due_at,+ row_number() over (partition by candidates.account_id order by candidates.due_at, candidates.id) as place+ from candidates+ ) ranked+ order by ranked.place, ranked.due_at+ limit p_limit+ ),+ claimed as (+ update public.automation_public_replies p+ set status = 'processing', claimed_at = now()+ from picked+ where p.id = picked.id+ returning p.id, p.user_id, p.account_id, p.rule_id, p.ig_user_id, p.comment_id, p.attempts, p.expires_at, p.reply_text+ )+ select claimed.id, claimed.user_id, claimed.account_id, claimed.rule_id, claimed.ig_user_id, claimed.comment_id,+ claimed.attempts, claimed.expires_at, claimed.reply_text,+ coalesce(r.enabled and r.public_reply_enabled, false), a.data ->> 'accessToken'+ from claimed+ left join public.automation_rules r on r.id = claimed.rule_id+ left join public.accounts a on a.id = claimed.account_id and a.user_id = claimed.user_id;+end;+$function$;++GRANT EXECUTE ON FUNCTION "public"."claim_automation_public_replies"(integer, integer, integer, text[]) TO "service_role";++REVOKE ALL ON FUNCTION "public"."claim_automation_public_replies"(integer, integer, integer, text[]) FROM "postgres";++GRANT EXECUTE ON FUNCTION "public"."claim_automation_public_replies"(integer, integer, integer, text[]) TO "postgres";++REVOKE ALL ON FUNCTION "public"."claim_automation_public_replies"(integer, integer, integer, text[]) FROM PUBLIC, "anon", "authenticated";diff --git a/supabase/schemas/public/functions/expire_automation_jobs.sql b/supabase/schemas/public/functions/expire_automation_jobs.sqlnew file mode 100644index 0000000..fb8292a--- /dev/null+++ b/supabase/schemas/public/functions/expire_automation_jobs.sql@@ -0,0 +1,75 @@+CREATE OR REPLACE FUNCTION public.expire_automation_jobs (+ p_limit integer+)+ RETURNS jsonb+ LANGUAGE sql+ SET search_path TO ''+ AS $function$+ with due_comments as (+ select c.id+ from public.automation_comments c+ where c.status in ('queued', 'retry_wait') and c.expires_at <= now()+ limit p_limit+ for update skip locked+ ),+ expired_comments as (+ update public.automation_comments c+ set status = 'expired',+ status_reason = 'expired',+ error_message = 'The 7 days in which Instagram allows a private reply to this comment ran out.',+ next_attempt_at = null,+ claimed_at = null+ from due_comments+ where c.id = due_comments.id+ returning c.id+ ),+ due_followups as (+ select f.id+ from public.automation_followups f+ where f.status in ('queued', 'retry_wait') and f.window_expires_at <= now()+ limit p_limit+ for update skip locked+ ),+ expired_followups as (+ update public.automation_followups f+ set status = 'expired',+ status_reason = 'expired',+ error_message = 'The 24 hours in which Instagram allows a message after the person''s reply ran out.',+ next_attempt_at = null,+ claimed_at = null+ from due_followups+ where f.id = due_followups.id+ returning f.id+ ),+ due_public_replies as (+ select p.id+ from public.automation_public_replies p+ where p.status in ('queued', 'retry_wait') and p.expires_at <= now()+ limit p_limit+ for update skip locked+ ),+ expired_public_replies as (+ update public.automation_public_replies p+ set status = 'expired',+ status_reason = 'expired',+ error_message = 'This public reply waited 7 days without going out, so Twiligent stopped trying.',+ next_attempt_at = null,+ claimed_at = null+ from due_public_replies+ where p.id = due_public_replies.id+ returning p.id+ )+ select jsonb_build_object(+ 'comments', (select count(*) from expired_comments),+ 'followups', (select count(*) from expired_followups),+ 'public_replies', (select count(*) from expired_public_replies)+ );+$function$;++GRANT EXECUTE ON FUNCTION "public"."expire_automation_jobs"(integer) TO "service_role";++REVOKE ALL ON FUNCTION "public"."expire_automation_jobs"(integer) FROM "postgres";++GRANT EXECUTE ON FUNCTION "public"."expire_automation_jobs"(integer) TO "postgres";++REVOKE ALL ON FUNCTION "public"."expire_automation_jobs"(integer) FROM PUBLIC, "anon", "authenticated";diff --git a/supabase/schemas/public/functions/finish_automation_followup.sql b/supabase/schemas/public/functions/finish_automation_followup.sqlnew file mode 100644index 0000000..94d8c1d--- /dev/null+++ b/supabase/schemas/public/functions/finish_automation_followup.sql@@ -0,0 +1,88 @@+CREATE OR REPLACE FUNCTION public.finish_automation_followup (+ p_id text,+ p_attempt_id text,+ p_status text,+ p_outcome text,+ p_reason text DEFAULT NULL::text,+ p_error_message text DEFAULT NULL::text,+ p_message_id text DEFAULT NULL::text,+ p_error_code integer DEFAULT NULL::integer,+ p_error_subcode integer DEFAULT NULL::integer,+ p_http_status integer DEFAULT NULL::integer,+ p_next_attempt_at timestamp with time zone DEFAULT NULL::timestamp WITH time zone,+ p_cooldown_until timestamp with time zone DEFAULT NULL::timestamp WITH time zone,+ p_cooldown_reason text DEFAULT NULL::text,+ p_pause_reason text DEFAULT NULL::text,+ p_gate_status text DEFAULT NULL::text,+ p_count_reminder boolean DEFAULT false+)+ RETURNS boolean+ LANGUAGE plpgsql+ SET search_path TO ''+ AS $function$+declare+ job public.automation_followups%rowtype;+begin+ update public.automation_followups f+ set status = p_status,+ status_reason = p_reason,+ error_message = p_error_message,+ message_id = coalesce(p_message_id, f.message_id),+ accepted_at = case when p_status = 'accepted' then now() else f.accepted_at end,+ next_attempt_at = p_next_attempt_at,+ claimed_at = null+ where f.id = p_id and (f.status = 'sending' or (f.status = 'needs_review' and f.status_reason = 'interrupted'))+ returning * into job;+ if not found then+ return false;+ end if;++ update public.automation_attempts t+ set outcome = p_outcome,+ error_code = p_error_code,+ error_subcode = p_error_subcode,+ http_status = p_http_status,+ finished_at = now()+ where t.id = p_attempt_id and t.followup_id = p_id;++ update public.automation_comments c+ set gate_status = coalesce(p_gate_status, c.gate_status),+ gate_prompts = c.gate_prompts + case when p_count_reminder then 1 else 0 end+ where c.id = job.automation_comment_id;++ if p_cooldown_until is not null then+ insert into public.automation_accounts (account_id, user_id, cooldown_until, cooldown_reason)+ values (job.account_id, job.user_id, p_cooldown_until, p_cooldown_reason)+ on conflict (account_id) do update+ set cooldown_until = greatest(coalesce(public.automation_accounts.cooldown_until, excluded.cooldown_until), excluded.cooldown_until),+ cooldown_reason = excluded.cooldown_reason;+ end if;++ if p_pause_reason is not null then+ insert into public.automation_accounts (account_id, user_id, paused, paused_reason)+ values (job.account_id, job.user_id, true, p_pause_reason)+ on conflict (account_id) do update set paused = true, paused_reason = excluded.paused_reason;+ end if;+ return true;+end;+$function$;++GRANT EXECUTE+ ON FUNCTION "public"."finish_automation_followup"(text, text, text, text, text, text, text, integer, integer, integer, timestamp WITH time zone, timestamp+ WITH time zone, text, text, text, boolean)+ TO "service_role";++REVOKE ALL+ ON FUNCTION "public"."finish_automation_followup"(text, text, text, text, text, text, text, integer, integer, integer, timestamp WITH time zone, timestamp+ WITH time zone, text, text, text, boolean)+ FROM "postgres";++GRANT EXECUTE+ ON FUNCTION "public"."finish_automation_followup"(text, text, text, text, text, text, text, integer, integer, integer, timestamp WITH time zone, timestamp+ WITH time zone, text, text, text, boolean)+ TO "postgres";++REVOKE ALL+ ON FUNCTION "public"."finish_automation_followup"(text, text, text, text, text, text, text, integer, integer, integer, timestamp WITH time zone, timestamp+ WITH time zone, text, text, text, boolean)+ FROM PUBLIC, "anon", "authenticated";diff --git a/supabase/schemas/public/functions/finish_automation_public_reply.sql b/supabase/schemas/public/functions/finish_automation_public_reply.sqlnew file mode 100644index 0000000..9663dad--- /dev/null+++ b/supabase/schemas/public/functions/finish_automation_public_reply.sql@@ -0,0 +1,82 @@+CREATE OR REPLACE FUNCTION public.finish_automation_public_reply (+ p_id text,+ p_attempt_id text,+ p_status text,+ p_outcome text,+ p_reason text DEFAULT NULL::text,+ p_error_message text DEFAULT NULL::text,+ p_reply_id text DEFAULT NULL::text,+ p_error_code integer DEFAULT NULL::integer,+ p_error_subcode integer DEFAULT NULL::integer,+ p_http_status integer DEFAULT NULL::integer,+ p_next_attempt_at timestamp with time zone DEFAULT NULL::timestamp WITH time zone,+ p_cooldown_until timestamp with time zone DEFAULT NULL::timestamp WITH time zone,+ p_cooldown_reason text DEFAULT NULL::text,+ p_pause_reason text DEFAULT NULL::text+)+ RETURNS boolean+ LANGUAGE plpgsql+ SET search_path TO ''+ AS $function$+declare+ job public.automation_public_replies%rowtype;+begin+ update public.automation_public_replies p+ set status = p_status,+ status_reason = p_reason,+ error_message = p_error_message,+ reply_id = coalesce(p_reply_id, p.reply_id),+ accepted_at = case when p_status = 'accepted' then now() else p.accepted_at end,+ next_attempt_at = p_next_attempt_at,+ claimed_at = null+ where p.id = p_id and (p.status = 'sending' or (p.status = 'needs_review' and p.status_reason = 'interrupted'))+ returning * into job;+ -- a reply already settled keeps the attempt that settled it+ if not found then+ return false;+ end if;++ update public.automation_attempts t+ set outcome = p_outcome,+ error_code = p_error_code,+ error_subcode = p_error_subcode,+ http_status = p_http_status,+ finished_at = now()+ where t.id = p_attempt_id and t.public_reply_id = p_id;++ if p_cooldown_until is not null then+ insert into public.automation_accounts (account_id, user_id, public_cooldown_until, public_cooldown_reason)+ values (job.account_id, job.user_id, p_cooldown_until, p_cooldown_reason)+ on conflict (account_id) do update+ set public_cooldown_until = greatest(coalesce(public.automation_accounts.public_cooldown_until, excluded.public_cooldown_until), excluded.public_cooldown_until),+ public_cooldown_reason = excluded.public_cooldown_reason;+ end if;++ if p_pause_reason is not null then+ insert into public.automation_accounts (account_id, user_id, paused, paused_reason)+ values (job.account_id, job.user_id, true, p_pause_reason)+ on conflict (account_id) do update set paused = true, paused_reason = excluded.paused_reason;+ end if;+ return true;+end;+$function$;++GRANT EXECUTE+ ON FUNCTION "public"."finish_automation_public_reply"(text, text, text, text, text, text, text, integer, integer, integer, timestamp WITH time zone, timestamp+ WITH time zone, text, text)+ TO "service_role";++REVOKE ALL+ ON FUNCTION "public"."finish_automation_public_reply"(text, text, text, text, text, text, text, integer, integer, integer, timestamp WITH time zone, timestamp+ WITH time zone, text, text)+ FROM "postgres";++GRANT EXECUTE+ ON FUNCTION "public"."finish_automation_public_reply"(text, text, text, text, text, text, text, integer, integer, integer, timestamp WITH time zone, timestamp+ WITH time zone, text, text)+ TO "postgres";++REVOKE ALL+ ON FUNCTION "public"."finish_automation_public_reply"(text, text, text, text, text, text, text, integer, integer, integer, timestamp WITH time zone, timestamp+ WITH time zone, text, text)+ FROM PUBLIC, "anon", "authenticated";diff --git a/supabase/schemas/public/functions/finish_automation_send.sql b/supabase/schemas/public/functions/finish_automation_send.sqlnew file mode 100644index 0000000..9f8ea41--- /dev/null+++ b/supabase/schemas/public/functions/finish_automation_send.sql@@ -0,0 +1,86 @@+CREATE OR REPLACE FUNCTION public.finish_automation_send (+ p_id text,+ p_attempt_id text,+ p_status text,+ p_outcome text,+ p_reason text DEFAULT NULL::text,+ p_error_message text DEFAULT NULL::text,+ p_message_id text DEFAULT NULL::text,+ p_error_code integer DEFAULT NULL::integer,+ p_error_subcode integer DEFAULT NULL::integer,+ p_http_status integer DEFAULT NULL::integer,+ p_next_attempt_at timestamp with time zone DEFAULT NULL::timestamp WITH time zone,+ p_cooldown_until timestamp with time zone DEFAULT NULL::timestamp WITH time zone,+ p_cooldown_reason text DEFAULT NULL::text,+ p_pause_reason text DEFAULT NULL::text,+ p_recipient_id text DEFAULT NULL::text,+ p_gate_status text DEFAULT NULL::text+)+ RETURNS boolean+ LANGUAGE plpgsql+ SET search_path TO ''+ AS $function$+declare+ job public.automation_comments%rowtype;+begin+ update public.automation_comments c+ set status = p_status,+ status_reason = p_reason,+ error_message = p_error_message,+ message_id = coalesce(p_message_id, c.message_id),+ accepted_at = case when p_status = 'accepted' then now() else c.accepted_at end,+ recipient_id = coalesce(p_recipient_id, c.recipient_id),+ gate_status = coalesce(p_gate_status, c.gate_status),+ next_attempt_at = p_next_attempt_at,+ claimed_at = null+ where c.id = p_id and (c.status = 'sending' or (c.status = 'needs_review' and c.status_reason = 'interrupted'))+ returning * into job;+ -- a comment already settled keeps the attempt that settled it+ if not found then+ return false;+ end if;++ update public.automation_attempts t+ set outcome = p_outcome,+ error_code = p_error_code,+ error_subcode = p_error_subcode,+ http_status = p_http_status,+ finished_at = now()+ where t.id = p_attempt_id and t.automation_comment_id = p_id;++ if p_cooldown_until is not null then+ insert into public.automation_accounts (account_id, user_id, cooldown_until, cooldown_reason)+ values (job.account_id, job.user_id, p_cooldown_until, p_cooldown_reason)+ on conflict (account_id) do update+ set cooldown_until = greatest(coalesce(public.automation_accounts.cooldown_until, excluded.cooldown_until), excluded.cooldown_until),+ cooldown_reason = excluded.cooldown_reason;+ end if;++ if p_pause_reason is not null then+ insert into public.automation_accounts (account_id, user_id, paused, paused_reason)+ values (job.account_id, job.user_id, true, p_pause_reason)+ on conflict (account_id) do update set paused = true, paused_reason = excluded.paused_reason;+ end if;+ return true;+end;+$function$;++GRANT EXECUTE+ ON FUNCTION "public"."finish_automation_send"(text, text, text, text, text, text, text, integer, integer, integer, timestamp WITH time zone, timestamp+ WITH time zone, text, text, text, text)+ TO "service_role";++REVOKE ALL+ ON FUNCTION "public"."finish_automation_send"(text, text, text, text, text, text, text, integer, integer, integer, timestamp WITH time zone, timestamp+ WITH time zone, text, text, text, text)+ FROM "postgres";++GRANT EXECUTE+ ON FUNCTION "public"."finish_automation_send"(text, text, text, text, text, text, text, integer, integer, integer, timestamp WITH time zone, timestamp+ WITH time zone, text, text, text, text)+ TO "postgres";++REVOKE ALL+ ON FUNCTION "public"."finish_automation_send"(text, text, text, text, text, text, text, integer, integer, integer, timestamp WITH time zone, timestamp+ WITH time zone, text, text, text, text)+ FROM PUBLIC, "anon", "authenticated";diff --git a/supabase/schemas/public/functions/merge_account_data.sql b/supabase/schemas/public/functions/merge_account_data.sqlnew file mode 100644index 0000000..54a8882--- /dev/null+++ b/supabase/schemas/public/functions/merge_account_data.sql@@ -0,0 +1,22 @@+CREATE OR REPLACE FUNCTION public.merge_account_data (+ p_id text,+ p_user_id uuid,+ p_patch jsonb+)+ RETURNS boolean+ LANGUAGE sql+ SET search_path TO ''+ AS $function$+ update public.accounts+ set data = data || p_patch+ where id = p_id and (p_user_id is null or user_id = p_user_id)+ returning true;+$function$;++GRANT EXECUTE ON FUNCTION "public"."merge_account_data"(text, uuid, jsonb) TO "service_role";++REVOKE ALL ON FUNCTION "public"."merge_account_data"(text, uuid, jsonb) FROM "postgres";++GRANT EXECUTE ON FUNCTION "public"."merge_account_data"(text, uuid, jsonb) TO "postgres";++REVOKE ALL ON FUNCTION "public"."merge_account_data"(text, uuid, jsonb) FROM PUBLIC, "anon", "authenticated";diff --git a/supabase/schemas/public/functions/merge_scheduled_post.sql b/supabase/schemas/public/functions/merge_scheduled_post.sqlnew file mode 100644index 0000000..4e6f485--- /dev/null+++ b/supabase/schemas/public/functions/merge_scheduled_post.sql@@ -0,0 +1,29 @@+CREATE OR REPLACE FUNCTION public.merge_scheduled_post (+ p_id text,+ p_user_id uuid,+ p_patch jsonb,+ p_status text DEFAULT NULL::text,+ p_scheduled_at timestamp with time zone DEFAULT NULL::timestamp WITH time zone,+ p_only_status text DEFAULT NULL::text+)+ RETURNS boolean+ LANGUAGE sql+ SET search_path TO ''+ AS $function$+ update public.scheduled_posts+ set data = data || p_patch,+ status = coalesce(p_status, status),+ scheduled_at = coalesce(p_scheduled_at, scheduled_at)+ where id = p_id+ and (p_user_id is null or user_id = p_user_id)+ and (p_only_status is null or status = p_only_status)+ returning true;+$function$;++GRANT EXECUTE ON FUNCTION "public"."merge_scheduled_post"(text, uuid, jsonb, text, timestamp WITH time zone, text) TO "service_role";++REVOKE ALL ON FUNCTION "public"."merge_scheduled_post"(text, uuid, jsonb, text, timestamp WITH time zone, text) FROM "postgres";++GRANT EXECUTE ON FUNCTION "public"."merge_scheduled_post"(text, uuid, jsonb, text, timestamp WITH time zone, text) TO "postgres";++REVOKE ALL ON FUNCTION "public"."merge_scheduled_post"(text, uuid, jsonb, text, timestamp WITH time zone, text) FROM PUBLIC, "anon", "authenticated";diff --git a/supabase/schemas/public/functions/merge_tracked_post_data.sql b/supabase/schemas/public/functions/merge_tracked_post_data.sqlnew file mode 100644index 0000000..119c605--- /dev/null+++ b/supabase/schemas/public/functions/merge_tracked_post_data.sql@@ -0,0 +1,22 @@+CREATE OR REPLACE FUNCTION public.merge_tracked_post_data (+ p_id text,+ p_user_id uuid,+ p_patch jsonb+)+ RETURNS boolean+ LANGUAGE sql+ SET search_path TO ''+ AS $function$+ update public.tracked_posts+ set data = coalesce(data, '{}'::jsonb) || p_patch+ where id = p_id and user_id = p_user_id+ returning true;+$function$;++GRANT EXECUTE ON FUNCTION "public"."merge_tracked_post_data"(text, uuid, jsonb) TO "service_role";++REVOKE ALL ON FUNCTION "public"."merge_tracked_post_data"(text, uuid, jsonb) FROM "postgres";++GRANT EXECUTE ON FUNCTION "public"."merge_tracked_post_data"(text, uuid, jsonb) TO "postgres";++REVOKE ALL ON FUNCTION "public"."merge_tracked_post_data"(text, uuid, jsonb) FROM PUBLIC, "anon", "authenticated";diff --git a/supabase/schemas/public/functions/purge_automation_comments.sql b/supabase/schemas/public/functions/purge_automation_comments.sqlnew file mode 100644index 0000000..6c02c15--- /dev/null+++ b/supabase/schemas/public/functions/purge_automation_comments.sql@@ -0,0 +1,32 @@+CREATE OR REPLACE FUNCTION public.purge_automation_comments (+ p_before timestamp with time zone,+ p_limit integer+)+ RETURNS integer+ LANGUAGE sql+ SET search_path TO ''+ AS $function$+ with doomed as (+ select c.id+ from public.automation_comments c+ where c.created_at < p_before+ order by c.created_at+ limit p_limit+ for update skip locked+ ),+ deleted as (+ delete from public.automation_comments c+ using doomed+ where c.id = doomed.id+ returning c.id+ )+ select count(*)::integer from deleted;+$function$;++GRANT EXECUTE ON FUNCTION "public"."purge_automation_comments"(timestamp WITH time zone, integer) TO "service_role";++REVOKE ALL ON FUNCTION "public"."purge_automation_comments"(timestamp WITH time zone, integer) FROM "postgres";++GRANT EXECUTE ON FUNCTION "public"."purge_automation_comments"(timestamp WITH time zone, integer) TO "postgres";++REVOKE ALL ON FUNCTION "public"."purge_automation_comments"(timestamp WITH time zone, integer) FROM PUBLIC, "anon", "authenticated";diff --git a/supabase/schemas/public/functions/record_automation_public_review.sql b/supabase/schemas/public/functions/record_automation_public_review.sqlnew file mode 100644index 0000000..3496cf2--- /dev/null+++ b/supabase/schemas/public/functions/record_automation_public_review.sql@@ -0,0 +1,66 @@+CREATE OR REPLACE FUNCTION public.record_automation_public_review (+ p_id text,+ p_found boolean,+ p_reply_id text DEFAULT NULL::text,+ p_sent_at timestamp with time zone DEFAULT NULL::timestamp WITH time zone,+ p_note text DEFAULT NULL::text,+ p_resend boolean DEFAULT false+)+ RETURNS boolean+ LANGUAGE plpgsql+ SET search_path TO ''+ AS $function$+begin+ if p_found then+ update public.automation_public_replies p+ set status = 'accepted',+ status_reason = 'confirmed',+ error_message = null,+ reply_id = coalesce(p_reply_id, p.reply_id),+ accepted_at = coalesce(p_sent_at, now()),+ review_checks = p.review_checks + 1,+ review_checked_at = now()+ where p.id = p_id and p.status = 'needs_review' and p.status_reason in ('no_answer', 'interrupted');+ if not found then+ return false;+ end if;+ update public.automation_attempts t+ set outcome = 'accepted', finished_at = coalesce(t.finished_at, now())+ where t.id = (+ select x.id from public.automation_attempts x+ where x.public_reply_id = p_id and x.outcome = 'ambiguous'+ order by x.started_at desc+ limit 1+ );+ return true;+ end if;++ if p_resend then+ update public.automation_public_replies p+ set status = 'queued',+ status_reason = 'resend_after_check',+ error_message = null,+ next_attempt_at = now(),+ claimed_at = null,+ review_checks = 0,+ review_checked_at = null+ where p.id = p_id and p.status = 'needs_review' and p.status_reason in ('no_answer', 'interrupted');+ return found;+ end if;++ update public.automation_public_replies p+ set review_checks = p.review_checks + 1,+ review_checked_at = now(),+ error_message = coalesce(left(p_note, 500), p.error_message)+ where p.id = p_id and p.status = 'needs_review' and p.status_reason in ('no_answer', 'interrupted');+ return found;+end;+$function$;++GRANT EXECUTE ON FUNCTION "public"."record_automation_public_review"(text, boolean, text, timestamp WITH time zone, text, boolean) TO "service_role";++REVOKE ALL ON FUNCTION "public"."record_automation_public_review"(text, boolean, text, timestamp WITH time zone, text, boolean) FROM "postgres";++GRANT EXECUTE ON FUNCTION "public"."record_automation_public_review"(text, boolean, text, timestamp WITH time zone, text, boolean) TO "postgres";++REVOKE ALL ON FUNCTION "public"."record_automation_public_review"(text, boolean, text, timestamp WITH time zone, text, boolean) FROM PUBLIC, "anon", "authenticated";diff --git a/supabase/schemas/public/functions/record_automation_review.sql b/supabase/schemas/public/functions/record_automation_review.sqlnew file mode 100644index 0000000..7e386a5--- /dev/null+++ b/supabase/schemas/public/functions/record_automation_review.sql@@ -0,0 +1,55 @@+CREATE OR REPLACE FUNCTION public.record_automation_review (+ p_id text,+ p_found boolean,+ p_message_id text DEFAULT NULL::text,+ p_sent_at timestamp with time zone DEFAULT NULL::timestamp WITH time zone,+ p_note text DEFAULT NULL::text+)+ RETURNS boolean+ LANGUAGE plpgsql+ SET search_path TO ''+ AS $function$+declare+ job public.automation_comments%rowtype;+begin+ if p_found then+ update public.automation_comments c+ set status = 'accepted',+ status_reason = 'confirmed',+ error_message = null,+ message_id = coalesce(p_message_id, c.message_id),+ accepted_at = coalesce(p_sent_at, now()),+ recipient_id = coalesce(c.recipient_id, c.from_id),+ gate_status = case+ when (select r.require_follow from public.automation_rules r where r.id = c.rule_id) then 'awaiting_reply'+ else c.gate_status+ end,+ review_checks = c.review_checks + 1,+ review_checked_at = now()+ where c.id = p_id and c.status = 'needs_review' and c.status_reason in ('no_answer', 'interrupted')+ returning * into job;+ if not found then+ return false;+ end if;+ update public.automation_attempts t+ set outcome = 'accepted', finished_at = coalesce(t.finished_at, now())+ where t.automation_comment_id = p_id and t.kind = 'private_reply' and t.outcome = 'ambiguous';+ return true;+ end if;++ update public.automation_comments c+ set review_checks = c.review_checks + 1,+ review_checked_at = now(),+ error_message = coalesce(left(p_note, 500), c.error_message)+ where c.id = p_id and c.status = 'needs_review' and c.status_reason in ('no_answer', 'interrupted');+ return found;+end;+$function$;++GRANT EXECUTE ON FUNCTION "public"."record_automation_review"(text, boolean, text, timestamp WITH time zone, text) TO "service_role";++REVOKE ALL ON FUNCTION "public"."record_automation_review"(text, boolean, text, timestamp WITH time zone, text) FROM "postgres";++GRANT EXECUTE ON FUNCTION "public"."record_automation_review"(text, boolean, text, timestamp WITH time zone, text) TO "postgres";++REVOKE ALL ON FUNCTION "public"."record_automation_review"(text, boolean, text, timestamp WITH time zone, text) FROM PUBLIC, "anon", "authenticated";diff --git a/supabase/schemas/public/functions/reserve_automation_followup.sql b/supabase/schemas/public/functions/reserve_automation_followup.sqlnew file mode 100644index 0000000..05b2e91--- /dev/null+++ b/supabase/schemas/public/functions/reserve_automation_followup.sql@@ -0,0 +1,52 @@+CREATE OR REPLACE FUNCTION public.reserve_automation_followup (+ p_id text,+ p_attempt_id text,+ p_kind text,+ p_message_digest text DEFAULT NULL::text+)+ RETURNS TABLE (+ outcome text,+ retry_at timestamp with time zone+ )+ LANGUAGE plpgsql+ SET search_path TO ''+ AS $function$+#variable_conflict use_column+declare+ job public.automation_followups%rowtype;+ controls public.automation_accounts%rowtype;+ rule text;+begin+ select * into job from public.automation_followups f where f.id = p_id and f.status = 'processing' for update;+ if not found then+ return query select 'gone'::text, null::timestamptz;+ return;+ end if;++ select * into controls from public.automation_accounts a where a.account_id = job.account_id;+ if controls.paused then+ return query select 'paused'::text, null::timestamptz;+ return;+ end if;+ if controls.cooldown_until > now() then+ return query select 'cooldown'::text, controls.cooldown_until;+ return;+ end if;++ select c.rule_id into rule from public.automation_comments c where c.id = job.automation_comment_id;+ update public.automation_followups f+ set status = 'sending', claimed_at = now(), attempts = f.attempts + 1, kind = p_kind+ where f.id = p_id;+ insert into public.automation_attempts (id, user_id, account_id, automation_comment_id, rule_id, recipient_id, kind, followup_id, message_digest)+ values (p_attempt_id, job.user_id, job.account_id, job.automation_comment_id, rule, job.recipient_id, 'followup', job.id, p_message_digest);+ return query select 'ok'::text, null::timestamptz;+end;+$function$;++GRANT EXECUTE ON FUNCTION "public"."reserve_automation_followup"(text, text, text, text) TO "service_role";++REVOKE ALL ON FUNCTION "public"."reserve_automation_followup"(text, text, text, text) FROM "postgres";++GRANT EXECUTE ON FUNCTION "public"."reserve_automation_followup"(text, text, text, text) TO "postgres";++REVOKE ALL ON FUNCTION "public"."reserve_automation_followup"(text, text, text, text) FROM PUBLIC, "anon", "authenticated";diff --git a/supabase/schemas/public/functions/reserve_automation_public_reply.sql b/supabase/schemas/public/functions/reserve_automation_public_reply.sqlnew file mode 100644index 0000000..a2da2e8--- /dev/null+++ b/supabase/schemas/public/functions/reserve_automation_public_reply.sql@@ -0,0 +1,77 @@+CREATE OR REPLACE FUNCTION public.reserve_automation_public_reply (+ p_id text,+ p_attempt_id text,+ p_account_limit integer,+ p_message_digest text DEFAULT NULL::text+)+ RETURNS TABLE (+ outcome text,+ retry_at timestamp with time zone+ )+ LANGUAGE plpgsql+ SET search_path TO ''+ AS $function$+#variable_conflict use_column+declare+ job public.automation_public_replies%rowtype;+ controls public.automation_accounts%rowtype;+ free_at timestamptz;+begin+ -- one public reservation at a time across every Worker; private replies take another lock, so neither waits on the other+ perform pg_advisory_xact_lock(hashtext('reserve_automation_public_reply'));++ select * into job from public.automation_public_replies p where p.id = p_id and p.status = 'processing' for update;+ if not found then+ return query select 'gone'::text, null::timestamptz;+ return;+ end if;++ select * into controls from public.automation_accounts a where a.account_id = job.account_id;+ if controls.paused then+ return query select 'paused'::text, null::timestamptz;+ return;+ end if;+ if controls.public_cooldown_until > now() then+ return query select 'cooldown'::text, controls.public_cooldown_until;+ return;+ end if;++ -- one public reply per person and post a day, however often they comment; it also ends a loop with another+ -- account's automation answering every reply+ if job.from_id is not null and exists (+ select 1 from public.automation_public_replies p+ where p.account_id = job.account_id and p.from_id = job.from_id and p.media_id is not distinct from job.media_id+ and p.id <> job.id and p.status in ('sending', 'accepted', 'needs_review') and p.created_at > now() - interval '1 day'+ ) then+ return query select 'recipient_limit'::text, null::timestamptz;+ return;+ end if;++ -- when the account is full, a reply frees up an hour after the oldest one in the window+ select case when count(*) >= p_account_limit then min(t.started_at) + interval '1 hour' end into free_at+ from public.automation_attempts t+ where t.account_id = job.account_id and t.kind = 'public_reply' and t.started_at > now() - interval '1 hour';+ if free_at is not null then+ insert into public.automation_accounts (account_id, user_id, public_limited_until)+ values (job.account_id, job.user_id, free_at)+ on conflict (account_id) do update set public_limited_until = excluded.public_limited_until;+ return query select 'account_limit'::text, free_at;+ return;+ end if;++ update public.automation_public_replies p+ set status = 'sending', claimed_at = now(), attempts = p.attempts + 1+ where p.id = p_id;+ insert into public.automation_attempts (id, user_id, account_id, automation_comment_id, rule_id, recipient_id, kind, public_reply_id, message_digest)+ values (p_attempt_id, job.user_id, job.account_id, job.automation_comment_id, job.rule_id, job.from_id, 'public_reply', job.id, p_message_digest);+ return query select 'ok'::text, null::timestamptz;+end;+$function$;++GRANT EXECUTE ON FUNCTION "public"."reserve_automation_public_reply"(text, text, integer, text) TO "service_role";++REVOKE ALL ON FUNCTION "public"."reserve_automation_public_reply"(text, text, integer, text) FROM "postgres";++GRANT EXECUTE ON FUNCTION "public"."reserve_automation_public_reply"(text, text, integer, text) TO "postgres";++REVOKE ALL ON FUNCTION "public"."reserve_automation_public_reply"(text, text, integer, text) FROM PUBLIC, "anon", "authenticated";diff --git a/supabase/schemas/public/functions/reserve_automation_send.sql b/supabase/schemas/public/functions/reserve_automation_send.sqlnew file mode 100644index 0000000..5676a79--- /dev/null+++ b/supabase/schemas/public/functions/reserve_automation_send.sql@@ -0,0 +1,105 @@+CREATE OR REPLACE FUNCTION public.reserve_automation_send (+ p_id text,+ p_attempt_id text,+ p_global_limit integer,+ p_user_limit integer,+ p_account_limit integer,+ p_recipient_limit integer,+ p_message_digest text DEFAULT NULL::text+)+ RETURNS TABLE (+ outcome text,+ retry_at timestamp with time zone+ )+ LANGUAGE plpgsql+ SET search_path TO ''+ AS $function$+#variable_conflict use_column+declare+ job public.automation_comments%rowtype;+ controls public.automation_accounts%rowtype;+ rule_limit integer;+ hour_ago timestamptz := now() - interval '1 hour';+ free_at timestamptz;+begin+ -- one reservation at a time across every Worker, so two jobs cannot both take the last free send+ perform pg_advisory_xact_lock(hashtext('reserve_automation_send'));++ select * into job from public.automation_comments c where c.id = p_id and c.status = 'processing' for update;+ if not found then+ return query select 'gone'::text, null::timestamptz;+ return;+ end if;++ select * into controls from public.automation_accounts a where a.account_id = job.account_id;+ if controls.paused then+ return query select 'paused'::text, null::timestamptz;+ return;+ end if;+ if controls.cooldown_until > now() then+ return query select 'cooldown'::text, controls.cooldown_until;+ return;+ end if;++ -- a person who comments again and again gets a few replies a day, never a stream of them; retries of this+ -- comment are one reply, so only other comments count+ if job.from_id is not null and (+ select count(distinct t.automation_comment_id) from public.automation_attempts t+ where t.account_id = job.account_id and t.recipient_id = job.from_id and t.kind = 'private_reply'+ and t.started_at > now() - interval '1 day' and t.automation_comment_id <> job.id+ ) >= p_recipient_limit then+ return query select 'recipient_limit'::text, null::timestamptz;+ return;+ end if;++ -- when a scope is full, a send frees up an hour after the oldest one in the window+ select r.hourly_limit into rule_limit from public.automation_rules r where r.id = job.rule_id;+ if rule_limit is not null then+ select case when count(*) >= rule_limit then min(t.started_at) + interval '1 hour' end into free_at+ from public.automation_attempts t where t.rule_id = job.rule_id and t.kind = 'private_reply' and t.started_at > hour_ago;+ if free_at is not null then+ return query select 'rule_limit'::text, free_at;+ return;+ end if;+ end if;++ select case when count(*) >= p_account_limit then min(t.started_at) + interval '1 hour' end into free_at+ from public.automation_attempts t where t.account_id = job.account_id and t.kind = 'private_reply' and t.started_at > hour_ago;+ if free_at is not null then+ insert into public.automation_accounts (account_id, user_id, limited_until)+ values (job.account_id, job.user_id, free_at)+ on conflict (account_id) do update set limited_until = excluded.limited_until;+ return query select 'account_limit'::text, free_at;+ return;+ end if;++ select case when count(*) >= p_user_limit then min(t.started_at) + interval '1 hour' end into free_at+ from public.automation_attempts t where t.user_id = job.user_id and t.kind = 'private_reply' and t.started_at > hour_ago;+ if free_at is not null then+ return query select 'user_limit'::text, free_at;+ return;+ end if;++ select case when count(*) >= p_global_limit then min(t.started_at) + interval '1 hour' end into free_at+ from public.automation_attempts t where t.kind = 'private_reply' and t.started_at > hour_ago;+ if free_at is not null then+ return query select 'global_limit'::text, free_at;+ return;+ end if;++ update public.automation_comments c+ set status = 'sending', claimed_at = now(), attempts = c.attempts + 1+ where c.id = p_id;+ insert into public.automation_attempts (id, user_id, account_id, automation_comment_id, rule_id, recipient_id, message_digest)+ values (p_attempt_id, job.user_id, job.account_id, job.id, job.rule_id, job.from_id, p_message_digest);+ return query select 'ok'::text, null::timestamptz;+end;+$function$;++GRANT EXECUTE ON FUNCTION "public"."reserve_automation_send"(text, text, integer, integer, integer, integer, text) TO "service_role";++REVOKE ALL ON FUNCTION "public"."reserve_automation_send"(text, text, integer, integer, integer, integer, text) FROM "postgres";++GRANT EXECUTE ON FUNCTION "public"."reserve_automation_send"(text, text, integer, integer, integer, integer, text) TO "postgres";++REVOKE ALL ON FUNCTION "public"."reserve_automation_send"(text, text, integer, integer, integer, integer, text) FROM PUBLIC, "anon", "authenticated";diff --git a/supabase/schemas/public/functions/set_updated_at.sql b/supabase/schemas/public/functions/set_updated_at.sqlnew file mode 100644index 0000000..0e6136e--- /dev/null+++ b/supabase/schemas/public/functions/set_updated_at.sql@@ -0,0 +1,18 @@+CREATE OR REPLACE FUNCTION public.set_updated_at()+ RETURNS TRIGGER+ LANGUAGE plpgsql+ SET search_path TO ''+ AS $function$+begin+ new.updated_at := now();+ return new;+end;+$function$;++GRANT EXECUTE ON FUNCTION "public"."set_updated_at"() TO "service_role";++REVOKE ALL ON FUNCTION "public"."set_updated_at"() FROM "postgres";++GRANT EXECUTE ON FUNCTION "public"."set_updated_at"() TO "postgres";++REVOKE ALL ON FUNCTION "public"."set_updated_at"() FROM PUBLIC, "anon", "authenticated";diff --git a/supabase/schemas/public/functions/store_automation_comments.sql b/supabase/schemas/public/functions/store_automation_comments.sqlnew file mode 100644index 0000000..7555f7c--- /dev/null+++ b/supabase/schemas/public/functions/store_automation_comments.sql@@ -0,0 +1,57 @@+CREATE OR REPLACE FUNCTION public.store_automation_comments (+ p_comments jsonb+)+ RETURNS jsonb+ LANGUAGE plpgsql+ SET search_path TO ''+ AS $function$+declare+ stored jsonb;+ replies jsonb;+begin+ with inserted as (+ insert into public.automation_comments (+ id, user_id, account_id, rule_id, ig_user_id, comment_id, media_id, from_id, from_username, text, status,+ status_reason, next_attempt_at, notified_at, expires_at+ )+ select x.id, x.user_id, x.account_id, x.rule_id, x.ig_user_id, x.comment_id, x.media_id, x.from_id, x.from_username,+ x.text, x.status, x.status_reason, x.next_attempt_at, x.notified_at, x.expires_at+ from jsonb_to_recordset(p_comments) as x(+ id text, user_id uuid, account_id text, rule_id text, ig_user_id text, comment_id text, media_id text,+ from_id text, from_username text, text text, status text, status_reason text, next_attempt_at timestamptz,+ notified_at timestamptz, expires_at timestamptz+ )+ on conflict (ig_user_id, comment_id) do nothing+ returning automation_comments.id, automation_comments.status+ )+ select coalesce(jsonb_agg(jsonb_build_object('id', inserted.id, 'status', inserted.status)), '[]'::jsonb) into stored from inserted;++ -- joined to the comment as stored, new or kept from an earlier copy, and only while the same rule answers it+ with inserted as (+ insert into public.automation_public_replies (+ id, user_id, account_id, automation_comment_id, rule_id, ig_user_id, comment_id, media_id, from_id, reply_text,+ status, next_attempt_at, expires_at+ )+ select x.public_reply_id, c.user_id, c.account_id, c.id, c.rule_id, c.ig_user_id, c.comment_id, c.media_id, c.from_id,+ x.public_reply_text, 'queued', now(), c.expires_at+ from jsonb_to_recordset(p_comments) as x(+ ig_user_id text, comment_id text, rule_id text, public_reply_id text, public_reply_text text+ )+ join public.automation_comments c on c.ig_user_id = x.ig_user_id and c.comment_id = x.comment_id and c.rule_id = x.rule_id+ where x.public_reply_id is not null and x.public_reply_text is not null+ on conflict (automation_comment_id) do nothing+ returning automation_public_replies.id+ )+ select coalesce(jsonb_agg(inserted.id), '[]'::jsonb) into replies from inserted;++ return jsonb_build_object('comments', stored, 'public_replies', replies);+end;+$function$;++GRANT EXECUTE ON FUNCTION "public"."store_automation_comments"(jsonb) TO "service_role";++REVOKE ALL ON FUNCTION "public"."store_automation_comments"(jsonb) FROM "postgres";++GRANT EXECUTE ON FUNCTION "public"."store_automation_comments"(jsonb) TO "postgres";++REVOKE ALL ON FUNCTION "public"."store_automation_comments"(jsonb) FROM PUBLIC, "anon", "authenticated";diff --git a/supabase/schemas/public/schema.sql b/supabase/schemas/public/schema.sqlnew file mode 100644index 0000000..c4fedf9--- /dev/null+++ b/supabase/schemas/public/schema.sql@@ -0,0 +1,25 @@+COMMENT ON SCHEMA "public" IS 'standard public schema';++REVOKE ALL ON SCHEMA "public" FROM PUBLIC;++GRANT USAGE ON SCHEMA "public" TO PUBLIC;++REVOKE ALL ON SCHEMA "public" FROM "anon";++GRANT USAGE ON SCHEMA "public" TO "anon";++REVOKE ALL ON SCHEMA "public" FROM "authenticated";++GRANT USAGE ON SCHEMA "public" TO "authenticated";++REVOKE ALL ON SCHEMA "public" FROM "pg_database_owner";++GRANT CREATE, USAGE ON SCHEMA "public" TO "pg_database_owner";++REVOKE ALL ON SCHEMA "public" FROM "postgres";++GRANT USAGE ON SCHEMA "public" TO "postgres";++REVOKE ALL ON SCHEMA "public" FROM "service_role";++GRANT USAGE ON SCHEMA "public" TO "service_role";diff --git a/supabase/schemas/public/tables/accounts.sql b/supabase/schemas/public/tables/accounts.sqlnew file mode 100644index 0000000..b032943--- /dev/null+++ b/supabase/schemas/public/tables/accounts.sql@@ -0,0 +1,42 @@+CREATE TABLE "public"."accounts" (+ "id" text NOT NULL,+ "user_id" uuid NOT NULL,+ "platform" text NOT NULL,+ "data" jsonb NOT NULL DEFAULT '{}'::jsonb,+ "created_at" timestamp with time zone NOT NULL DEFAULT now(),+ "updated_at" timestamp with time zone NOT NULL DEFAULT now(),+ CONSTRAINT "accounts_data_check" CHECK ((jsonb_typeof(data) = 'object'::text)),+ CONSTRAINT "accounts_id_user_id_key" UNIQUE (id, user_id),+ CONSTRAINT "accounts_pkey" PRIMARY KEY (id),+ CONSTRAINT "accounts_platform_check" CHECK ((platform = ANY (ARRAY['youtube'::text, 'instagram'::text, 'reddit'::text]))),+ CONSTRAINT "accounts_user_id_fkey" FOREIGN KEY (user_id) REFERENCES auth.users(id) ON DELETE CASCADE+);++ALTER TABLE "public"."accounts"+ ENABLE ROW LEVEL SECURITY;++CREATE UNIQUE INDEX accounts_identity_key ON public.accounts USING btree (user_id, platform, (+CASE platform+ WHEN 'youtube'::text THEN (DATA ->> 'channelId'::text)+ WHEN 'reddit'::text THEN (DATA ->> 'username'::text)+ WHEN 'instagram'::text THEN (DATA ->> 'igUserId'::text)+ ELSE NULL::text+END));++CREATE INDEX accounts_instagram_user_idx ON public.accounts USING btree (((DATA ->> 'igUserId'::text)))+ WHERE (platform = 'instagram'::text);++CREATE INDEX accounts_user_id_created_at_idx ON public.accounts USING btree (user_id, created_at, id);++CREATE TRIGGER accounts_set_updated_at+ BEFORE UPDATE ON public.accounts+ FOR EACH ROW+ EXECUTE FUNCTION public.set_updated_at();++GRANT DELETE, INSERT, MAINTAIN, REFERENCES, SELECT, TRIGGER, TRUNCATE, UPDATE ON TABLE "public"."accounts" TO "service_role";++REVOKE ALL ON TABLE "public"."accounts" FROM "postgres";++GRANT DELETE, INSERT, MAINTAIN, REFERENCES, SELECT, TRIGGER, TRUNCATE, UPDATE ON TABLE "public"."accounts" TO "postgres";++REVOKE ALL ON TABLE "public"."accounts" FROM "anon", "authenticated";diff --git a/supabase/schemas/public/tables/audit_events.sql b/supabase/schemas/public/tables/audit_events.sqlnew file mode 100644index 0000000..0a8ede1--- /dev/null+++ b/supabase/schemas/public/tables/audit_events.sql@@ -0,0 +1,36 @@+CREATE TABLE "public"."audit_events" (+ "id" text NOT NULL,+ "user_id" uuid NOT NULL,+ "action" text NOT NULL,+ "subject_type" text NOT NULL,+ "subject_id" text,+ "details" jsonb NOT NULL DEFAULT '{}'::jsonb,+ "created_at" timestamp with time zone NOT NULL DEFAULT now(),+ "updated_at" timestamp with time zone NOT NULL DEFAULT now(),+ CONSTRAINT "audit_events_action_check" CHECK ((action ~ '^[a-z_]+\.[a-z_]+$'::text)),+ CONSTRAINT "audit_events_details_check" CHECK ((jsonb_typeof(details) = 'object'::text)),+ CONSTRAINT "audit_events_pkey" PRIMARY KEY (id),+ CONSTRAINT "audit_events_subject_type_check"+ CHECK ((subject_type = ANY (ARRAY['account'::text, 'automation_rule'::text, 'automation_account'::text, 'automation_comment'::text]))),+ CONSTRAINT "audit_events_user_id_fkey" FOREIGN KEY (user_id) REFERENCES auth.users(id) ON DELETE CASCADE+);++ALTER TABLE "public"."audit_events"+ ENABLE ROW LEVEL SECURITY;++CREATE INDEX audit_events_created_at_idx ON public.audit_events USING btree (created_at);++CREATE INDEX audit_events_user_id_created_at_idx ON public.audit_events USING btree (user_id, created_at DESC);++CREATE TRIGGER audit_events_set_updated_at+ BEFORE UPDATE ON public.audit_events+ FOR EACH ROW+ EXECUTE FUNCTION public.set_updated_at();++GRANT DELETE, INSERT, MAINTAIN, REFERENCES, SELECT, TRIGGER, TRUNCATE, UPDATE ON TABLE "public"."audit_events" TO "service_role";++REVOKE ALL ON TABLE "public"."audit_events" FROM "postgres";++GRANT DELETE, INSERT, MAINTAIN, REFERENCES, SELECT, TRIGGER, TRUNCATE, UPDATE ON TABLE "public"."audit_events" TO "postgres";++REVOKE ALL ON TABLE "public"."audit_events" FROM "anon", "authenticated";diff --git a/supabase/schemas/public/tables/automation_accounts.sql b/supabase/schemas/public/tables/automation_accounts.sqlnew file mode 100644index 0000000..57ba3d6--- /dev/null+++ b/supabase/schemas/public/tables/automation_accounts.sql@@ -0,0 +1,38 @@+CREATE TABLE "public"."automation_accounts" (+ "account_id" text NOT NULL,+ "user_id" uuid NOT NULL,+ "paused" boolean NOT NULL DEFAULT false,+ "paused_reason" text,+ "cooldown_until" timestamp with time zone,+ "cooldown_reason" text,+ "subscribed_at" timestamp with time zone,+ "created_at" timestamp with time zone NOT NULL DEFAULT now(),+ "updated_at" timestamp with time zone NOT NULL DEFAULT now(),+ "limited_until" timestamp with time zone,+ "subscribed_fields" text[],+ "public_cooldown_until" timestamp with time zone,+ "public_cooldown_reason" text,+ "public_limited_until" timestamp with time zone,+ CONSTRAINT "automation_accounts_account_fkey" FOREIGN KEY (account_id, user_id) REFERENCES public.accounts(id, user_id) ON DELETE CASCADE,+ CONSTRAINT "automation_accounts_cooldown_reason_check" CHECK (((cooldown_reason IS NULL) OR (char_length(cooldown_reason) <= 200))),+ CONSTRAINT "automation_accounts_paused_reason_check" CHECK (((paused_reason IS NULL) OR (char_length(paused_reason) <= 200))),+ CONSTRAINT "automation_accounts_pkey" PRIMARY KEY (account_id),+ CONSTRAINT "automation_accounts_public_cooldown_reason_check" CHECK (((public_cooldown_reason IS NULL) OR (char_length(public_cooldown_reason) <= 200))),+ CONSTRAINT "automation_accounts_user_id_fkey" FOREIGN KEY (user_id) REFERENCES auth.users(id) ON DELETE CASCADE+);++ALTER TABLE "public"."automation_accounts"+ ENABLE ROW LEVEL SECURITY;++CREATE TRIGGER automation_accounts_set_updated_at+ BEFORE UPDATE ON public.automation_accounts+ FOR EACH ROW+ EXECUTE FUNCTION public.set_updated_at();++GRANT DELETE, INSERT, MAINTAIN, REFERENCES, SELECT, TRIGGER, TRUNCATE, UPDATE ON TABLE "public"."automation_accounts" TO "service_role";++REVOKE ALL ON TABLE "public"."automation_accounts" FROM "postgres";++GRANT DELETE, INSERT, MAINTAIN, REFERENCES, SELECT, TRIGGER, TRUNCATE, UPDATE ON TABLE "public"."automation_accounts" TO "postgres";++REVOKE ALL ON TABLE "public"."automation_accounts" FROM "anon", "authenticated";diff --git a/supabase/schemas/public/tables/automation_attempts.sql b/supabase/schemas/public/tables/automation_attempts.sqlnew file mode 100644index 0000000..36f680a--- /dev/null+++ b/supabase/schemas/public/tables/automation_attempts.sql@@ -0,0 +1,63 @@+CREATE TABLE "public"."automation_attempts" (+ "id" text NOT NULL,+ "user_id" uuid NOT NULL,+ "account_id" text NOT NULL,+ "automation_comment_id" text NOT NULL,+ "rule_id" text,+ "recipient_id" text,+ "outcome" text NOT NULL DEFAULT 'sending'::text,+ "error_code" integer,+ "error_subcode" integer,+ "http_status" integer,+ "started_at" timestamp with time zone NOT NULL DEFAULT now(),+ "finished_at" timestamp with time zone,+ "created_at" timestamp with time zone NOT NULL DEFAULT now(),+ "updated_at" timestamp with time zone NOT NULL DEFAULT now(),+ "kind" text NOT NULL DEFAULT 'private_reply'::text,+ "message_digest" text,+ "followup_id" text,+ "public_reply_id" text,+ CONSTRAINT "automation_attempts_account_fkey" FOREIGN KEY (account_id, user_id) REFERENCES public.accounts(id, user_id) ON DELETE CASCADE,+ CONSTRAINT "automation_attempts_followup_check" CHECK (((kind = 'followup'::text) = (followup_id IS NOT NULL))),+ CONSTRAINT "automation_attempts_kind_check" CHECK ((kind = ANY (ARRAY['private_reply'::text, 'followup'::text, 'public_reply'::text]))),+ CONSTRAINT "automation_attempts_outcome_check" CHECK ((outcome = ANY (ARRAY['sending'::text, 'accepted'::text, 'rejected'::text, 'rate_limited'::text, 'ambiguous'::text]))),+ CONSTRAINT "automation_attempts_pkey" PRIMARY KEY (id),+ CONSTRAINT "automation_attempts_public_reply_check" CHECK (((kind = 'public_reply'::text) = (public_reply_id IS NOT NULL))),+ CONSTRAINT "automation_attempts_user_id_fkey" FOREIGN KEY (user_id) REFERENCES auth.users(id) ON DELETE CASCADE,+ CONSTRAINT "automation_attempts_automation_comment_id_fkey" FOREIGN KEY (automation_comment_id) REFERENCES public.automation_comments(id) ON DELETE CASCADE,+ CONSTRAINT "automation_attempts_followup_id_fkey" FOREIGN KEY (followup_id) REFERENCES public.automation_followups(id) ON DELETE CASCADE,+ CONSTRAINT "automation_attempts_public_reply_id_fkey" FOREIGN KEY (public_reply_id) REFERENCES public.automation_public_replies(id) ON DELETE CASCADE,+ CONSTRAINT "automation_attempts_rule_id_fkey" FOREIGN KEY (rule_id) REFERENCES public.automation_rules(id) ON DELETE SET NULL+);++ALTER TABLE "public"."automation_attempts"+ ENABLE ROW LEVEL SECURITY;++CREATE INDEX automation_attempts_account_id_started_at_idx ON public.automation_attempts USING btree (account_id, started_at);++CREATE INDEX automation_attempts_comment_idx ON public.automation_attempts USING btree (automation_comment_id);++CREATE INDEX automation_attempts_public_reply_idx ON public.automation_attempts USING btree (public_reply_id)+ WHERE (public_reply_id IS NOT NULL);++CREATE INDEX automation_attempts_recipient_idx ON public.automation_attempts USING btree (account_id, recipient_id, started_at);++CREATE INDEX automation_attempts_rule_id_started_at_idx ON public.automation_attempts USING btree (rule_id, started_at)+ WHERE (rule_id IS NOT NULL);++CREATE INDEX automation_attempts_started_at_idx ON public.automation_attempts USING btree (started_at);++CREATE INDEX automation_attempts_user_id_started_at_idx ON public.automation_attempts USING btree (user_id, started_at);++CREATE TRIGGER automation_attempts_set_updated_at+ BEFORE UPDATE ON public.automation_attempts+ FOR EACH ROW+ EXECUTE FUNCTION public.set_updated_at();++GRANT DELETE, INSERT, MAINTAIN, REFERENCES, SELECT, TRIGGER, TRUNCATE, UPDATE ON TABLE "public"."automation_attempts" TO "service_role";++REVOKE ALL ON TABLE "public"."automation_attempts" FROM "postgres";++GRANT DELETE, INSERT, MAINTAIN, REFERENCES, SELECT, TRIGGER, TRUNCATE, UPDATE ON TABLE "public"."automation_attempts" TO "postgres";++REVOKE ALL ON TABLE "public"."automation_attempts" FROM "anon", "authenticated";diff --git a/supabase/schemas/public/tables/automation_comments.sql b/supabase/schemas/public/tables/automation_comments.sqlnew file mode 100644index 0000000..7447d1e--- /dev/null+++ b/supabase/schemas/public/tables/automation_comments.sql@@ -0,0 +1,83 @@+CREATE TABLE "public"."automation_comments" (+ "id" text NOT NULL,+ "user_id" uuid NOT NULL,+ "account_id" text NOT NULL,+ "rule_id" text,+ "ig_user_id" text NOT NULL,+ "comment_id" text NOT NULL,+ "media_id" text,+ "from_id" text,+ "from_username" text,+ "text" text,+ "status" text NOT NULL,+ "status_reason" text,+ "error_message" text,+ "attempts" integer NOT NULL DEFAULT 0,+ "next_attempt_at" timestamp with time zone,+ "claimed_at" timestamp with time zone,+ "message_id" text,+ "accepted_at" timestamp with time zone,+ "notified_at" timestamp with time zone NOT NULL,+ "expires_at" timestamp with time zone NOT NULL,+ "created_at" timestamp with time zone NOT NULL DEFAULT now(),+ "updated_at" timestamp with time zone NOT NULL DEFAULT now(),+ "recipient_id" text,+ "gate_status" text,+ "gate_prompts" integer NOT NULL DEFAULT 0,+ "review_checks" integer NOT NULL DEFAULT 0,+ "review_checked_at" timestamp with time zone,+ CONSTRAINT "automation_comments_account_fkey" FOREIGN KEY (account_id, user_id) REFERENCES public.accounts(id, user_id) ON DELETE CASCADE,+ CONSTRAINT "automation_comments_attempts_check" CHECK ((attempts >= 0)),+ CONSTRAINT "automation_comments_comment_key" UNIQUE (ig_user_id, comment_id),+ CONSTRAINT "automation_comments_error_message_check" CHECK (((error_message IS NULL) OR (char_length(error_message) <= 500))),+ CONSTRAINT "automation_comments_gate_prompts_check" CHECK ((gate_prompts >= 0)),+ CONSTRAINT "automation_comments_gate_status_check" CHECK (((gate_status IS NULL) OR (gate_status = ANY (ARRAY['awaiting_reply'::text, 'completed'::text, 'closed'::text])))),+ CONSTRAINT "automation_comments_pkey" PRIMARY KEY (id),+ CONSTRAINT "automation_comments_review_checks_check" CHECK ((review_checks >= 0)),+ CONSTRAINT "automation_comments_status_check"+ CHECK+ ((status = ANY (ARRAY['ignored'::text, 'queued'::text, 'processing'::text, 'retry_wait'::text, 'sending'::text, 'accepted'::text, 'failed'::text, 'needs_review'::text,+ 'skipped'::text, 'expired'::text]))),+ CONSTRAINT "automation_comments_text_check" CHECK (((text IS NULL) OR (char_length(text) <= 2200))),+ CONSTRAINT "automation_comments_user_id_fkey" FOREIGN KEY (user_id) REFERENCES auth.users(id) ON DELETE CASCADE,+ CONSTRAINT "automation_comments_waiting_check" CHECK (((status <> ALL (ARRAY['queued'::text, 'retry_wait'::text])) OR (next_attempt_at IS NOT NULL))),+ CONSTRAINT "automation_comments_rule_id_fkey" FOREIGN KEY (rule_id) REFERENCES public.automation_rules(id) ON DELETE SET NULL+);++ALTER TABLE "public"."automation_comments"+ ENABLE ROW LEVEL SECURITY;++CREATE INDEX automation_comments_awaiting_reply_idx ON public.automation_comments USING btree (ig_user_id, recipient_id, accepted_at)+ WHERE (gate_status = 'awaiting_reply'::text);++CREATE INDEX automation_comments_claimed_idx ON public.automation_comments USING btree (claimed_at)+ WHERE (status = ANY (ARRAY['processing'::text, 'sending'::text]));++CREATE INDEX automation_comments_created_at_idx ON public.automation_comments USING btree (created_at);++CREATE INDEX automation_comments_due_account_idx ON public.automation_comments USING btree (account_id, next_attempt_at)+ WHERE (status = ANY (ARRAY['queued'::text, 'retry_wait'::text]));++CREATE INDEX automation_comments_due_idx ON public.automation_comments USING btree (next_attempt_at)+ WHERE (status = ANY (ARRAY['queued'::text, 'retry_wait'::text]));++CREATE INDEX automation_comments_needs_review_idx ON public.automation_comments USING btree (review_checked_at NULLS FIRST, updated_at)+ WHERE (status = 'needs_review'::text);++CREATE INDEX automation_comments_rule_id_idx ON public.automation_comments USING btree (rule_id)+ WHERE (rule_id IS NOT NULL);++CREATE INDEX automation_comments_user_id_created_at_idx ON public.automation_comments USING btree (user_id, created_at DESC);++CREATE TRIGGER automation_comments_set_updated_at+ BEFORE UPDATE ON public.automation_comments+ FOR EACH ROW+ EXECUTE FUNCTION public.set_updated_at();++GRANT DELETE, INSERT, MAINTAIN, REFERENCES, SELECT, TRIGGER, TRUNCATE, UPDATE ON TABLE "public"."automation_comments" TO "service_role";++REVOKE ALL ON TABLE "public"."automation_comments" FROM "postgres";++GRANT DELETE, INSERT, MAINTAIN, REFERENCES, SELECT, TRIGGER, TRUNCATE, UPDATE ON TABLE "public"."automation_comments" TO "postgres";++REVOKE ALL ON TABLE "public"."automation_comments" FROM "anon", "authenticated";diff --git a/supabase/schemas/public/tables/automation_followups.sql b/supabase/schemas/public/tables/automation_followups.sqlnew file mode 100644index 0000000..0d475b0--- /dev/null+++ b/supabase/schemas/public/tables/automation_followups.sql@@ -0,0 +1,61 @@+CREATE TABLE "public"."automation_followups" (+ "id" text NOT NULL,+ "user_id" uuid NOT NULL,+ "account_id" text NOT NULL,+ "automation_comment_id" text NOT NULL,+ "ig_user_id" text NOT NULL,+ "recipient_id" text NOT NULL,+ "trigger_message_id" text NOT NULL,+ "status" text NOT NULL,+ "status_reason" text,+ "error_message" text,+ "kind" text,+ "attempts" integer NOT NULL DEFAULT 0,+ "next_attempt_at" timestamp with time zone,+ "claimed_at" timestamp with time zone,+ "message_id" text,+ "accepted_at" timestamp with time zone,+ "window_expires_at" timestamp with time zone NOT NULL,+ "created_at" timestamp with time zone NOT NULL DEFAULT now(),+ "updated_at" timestamp with time zone NOT NULL DEFAULT now(),+ CONSTRAINT "automation_followups_account_fkey" FOREIGN KEY (account_id, user_id) REFERENCES public.accounts(id, user_id) ON DELETE CASCADE,+ CONSTRAINT "automation_followups_attempts_check" CHECK ((attempts >= 0)),+ CONSTRAINT "automation_followups_automation_comment_id_fkey" FOREIGN KEY (automation_comment_id) REFERENCES public.automation_comments(id) ON DELETE CASCADE,+ CONSTRAINT "automation_followups_error_message_check" CHECK (((error_message IS NULL) OR (char_length(error_message) <= 500))),+ CONSTRAINT "automation_followups_kind_check" CHECK (((kind IS NULL) OR (kind = ANY (ARRAY['link'::text, 'reminder'::text])))),+ CONSTRAINT "automation_followups_message_key" UNIQUE (ig_user_id, trigger_message_id),+ CONSTRAINT "automation_followups_pkey" PRIMARY KEY (id),+ CONSTRAINT "automation_followups_status_check"+ CHECK+ ((status = ANY (ARRAY['queued'::text, 'processing'::text, 'retry_wait'::text, 'sending'::text, 'accepted'::text, 'failed'::text, 'needs_review'::text, 'skipped'::text,+ 'expired'::text]))),+ CONSTRAINT "automation_followups_user_id_fkey" FOREIGN KEY (user_id) REFERENCES auth.users(id) ON DELETE CASCADE,+ CONSTRAINT "automation_followups_waiting_check" CHECK (((status <> ALL (ARRAY['queued'::text, 'retry_wait'::text])) OR (next_attempt_at IS NOT NULL)))+);++ALTER TABLE "public"."automation_followups"+ ENABLE ROW LEVEL SECURITY;++CREATE INDEX automation_followups_claimed_idx ON public.automation_followups USING btree (claimed_at)+ WHERE (status = ANY (ARRAY['processing'::text, 'sending'::text]));++CREATE INDEX automation_followups_comment_id_idx ON public.automation_followups USING btree (automation_comment_id, created_at);++CREATE INDEX automation_followups_due_idx ON public.automation_followups USING btree (account_id, next_attempt_at)+ WHERE (status = ANY (ARRAY['queued'::text, 'retry_wait'::text]));++CREATE UNIQUE INDEX automation_followups_open_comment_key ON public.automation_followups USING btree (automation_comment_id)+ WHERE (status = ANY (ARRAY['queued'::text, 'processing'::text, 'retry_wait'::text, 'sending'::text]));++CREATE TRIGGER automation_followups_set_updated_at+ BEFORE UPDATE ON public.automation_followups+ FOR EACH ROW+ EXECUTE FUNCTION public.set_updated_at();++GRANT DELETE, INSERT, MAINTAIN, REFERENCES, SELECT, TRIGGER, TRUNCATE, UPDATE ON TABLE "public"."automation_followups" TO "service_role";++REVOKE ALL ON TABLE "public"."automation_followups" FROM "postgres";++GRANT DELETE, INSERT, MAINTAIN, REFERENCES, SELECT, TRIGGER, TRUNCATE, UPDATE ON TABLE "public"."automation_followups" TO "postgres";++REVOKE ALL ON TABLE "public"."automation_followups" FROM "anon", "authenticated";diff --git a/supabase/schemas/public/tables/automation_public_replies.sql b/supabase/schemas/public/tables/automation_public_replies.sqlnew file mode 100644index 0000000..b8c6657--- /dev/null+++ b/supabase/schemas/public/tables/automation_public_replies.sql@@ -0,0 +1,70 @@+CREATE TABLE "public"."automation_public_replies" (+ "id" text NOT NULL,+ "user_id" uuid NOT NULL,+ "account_id" text NOT NULL,+ "automation_comment_id" text NOT NULL,+ "rule_id" text,+ "ig_user_id" text NOT NULL,+ "comment_id" text NOT NULL,+ "media_id" text,+ "from_id" text,+ "reply_text" text NOT NULL,+ "status" text NOT NULL,+ "status_reason" text,+ "error_message" text,+ "attempts" integer NOT NULL DEFAULT 0,+ "next_attempt_at" timestamp with time zone,+ "claimed_at" timestamp with time zone,+ "reply_id" text,+ "accepted_at" timestamp with time zone,+ "review_checks" integer NOT NULL DEFAULT 0,+ "review_checked_at" timestamp with time zone,+ "expires_at" timestamp with time zone NOT NULL,+ "created_at" timestamp with time zone NOT NULL DEFAULT now(),+ "updated_at" timestamp with time zone NOT NULL DEFAULT now(),+ CONSTRAINT "automation_public_replies_account_fkey" FOREIGN KEY (account_id, user_id) REFERENCES public.accounts(id, user_id) ON DELETE CASCADE,+ CONSTRAINT "automation_public_replies_attempts_check" CHECK ((attempts >= 0)),+ CONSTRAINT "automation_public_replies_automation_comment_id_fkey" FOREIGN KEY (automation_comment_id) REFERENCES public.automation_comments(id) ON DELETE CASCADE,+ CONSTRAINT "automation_public_replies_comment_key" UNIQUE (automation_comment_id),+ CONSTRAINT "automation_public_replies_error_message_check" CHECK (((error_message IS NULL) OR (char_length(error_message) <= 500))),+ CONSTRAINT "automation_public_replies_pkey" PRIMARY KEY (id),+ CONSTRAINT "automation_public_replies_reply_text_check" CHECK (((char_length(reply_text) >= 1) AND (char_length(reply_text) <= 2200))),+ CONSTRAINT "automation_public_replies_review_checks_check" CHECK ((review_checks >= 0)),+ CONSTRAINT "automation_public_replies_status_check"+ CHECK+ ((status = ANY (ARRAY['queued'::text, 'processing'::text, 'retry_wait'::text, 'sending'::text, 'accepted'::text, 'failed'::text, 'needs_review'::text, 'skipped'::text,+ 'expired'::text]))),+ CONSTRAINT "automation_public_replies_user_id_fkey" FOREIGN KEY (user_id) REFERENCES auth.users(id) ON DELETE CASCADE,+ CONSTRAINT "automation_public_replies_waiting_check" CHECK (((status <> ALL (ARRAY['queued'::text, 'retry_wait'::text])) OR (next_attempt_at IS NOT NULL))),+ CONSTRAINT "automation_public_replies_rule_id_fkey" FOREIGN KEY (rule_id) REFERENCES public.automation_rules(id) ON DELETE SET NULL+);++ALTER TABLE "public"."automation_public_replies"+ ENABLE ROW LEVEL SECURITY;++CREATE INDEX automation_public_replies_claimed_idx ON public.automation_public_replies USING btree (claimed_at)+ WHERE (status = ANY (ARRAY['processing'::text, 'sending'::text]));++CREATE INDEX automation_public_replies_due_account_idx ON public.automation_public_replies USING btree (account_id, next_attempt_at)+ WHERE (status = ANY (ARRAY['queued'::text, 'retry_wait'::text]));++CREATE INDEX automation_public_replies_needs_review_idx ON public.automation_public_replies USING btree (review_checked_at NULLS FIRST, updated_at)+ WHERE (status = 'needs_review'::text);++CREATE INDEX automation_public_replies_recipient_idx ON public.automation_public_replies USING btree (account_id, from_id, media_id, created_at)+ WHERE (status = ANY (ARRAY['sending'::text, 'accepted'::text, 'needs_review'::text]));++CREATE INDEX automation_public_replies_user_created_idx ON public.automation_public_replies USING btree (user_id, created_at);++CREATE TRIGGER automation_public_replies_set_updated_at+ BEFORE UPDATE ON public.automation_public_replies+ FOR EACH ROW+ EXECUTE FUNCTION public.set_updated_at();++GRANT DELETE, INSERT, MAINTAIN, REFERENCES, SELECT, TRIGGER, TRUNCATE, UPDATE ON TABLE "public"."automation_public_replies" TO "service_role";++REVOKE ALL ON TABLE "public"."automation_public_replies" FROM "postgres";++GRANT DELETE, INSERT, MAINTAIN, REFERENCES, SELECT, TRIGGER, TRUNCATE, UPDATE ON TABLE "public"."automation_public_replies" TO "postgres";++REVOKE ALL ON TABLE "public"."automation_public_replies" FROM "anon", "authenticated";diff --git a/supabase/schemas/public/tables/automation_rules.sql b/supabase/schemas/public/tables/automation_rules.sqlnew file mode 100644index 0000000..e653631--- /dev/null+++ b/supabase/schemas/public/tables/automation_rules.sql@@ -0,0 +1,67 @@+CREATE TABLE "public"."automation_rules" (+ "id" text NOT NULL,+ "user_id" uuid NOT NULL,+ "account_id" text NOT NULL,+ "name" text NOT NULL,+ "keywords" text[] NOT NULL,+ "match_mode" text NOT NULL DEFAULT 'contains'::text,+ "case_sensitive" boolean NOT NULL DEFAULT false,+ "media_ids" text[] NOT NULL DEFAULT '{}'::text[],+ "reply_text" text NOT NULL,+ "link_url" text,+ "enabled" boolean NOT NULL DEFAULT false,+ "hourly_limit" integer,+ "created_at" timestamp with time zone NOT NULL DEFAULT now(),+ "updated_at" timestamp with time zone NOT NULL DEFAULT now(),+ "require_follow" boolean NOT NULL DEFAULT false,+ "follow_prompt_text" text,+ "not_following_text" text,+ "private_reply_enabled" boolean NOT NULL DEFAULT true,+ "public_reply_enabled" boolean NOT NULL DEFAULT false,+ "public_reply_texts" text[] NOT NULL DEFAULT '{}'::text[],+ CONSTRAINT "automation_rules_account_fkey" FOREIGN KEY (account_id, user_id) REFERENCES public.accounts(id, user_id) ON DELETE CASCADE,+ CONSTRAINT "automation_rules_actions_check" CHECK ((private_reply_enabled OR public_reply_enabled)),+ CONSTRAINT "automation_rules_follow_private_check" CHECK (((NOT require_follow) OR private_reply_enabled)),+ CONSTRAINT "automation_rules_follow_prompt_text_check"+ CHECK (((follow_prompt_text IS NULL) OR ((char_length(follow_prompt_text) >= 1) AND (char_length(follow_prompt_text) <= 1000)))),+ CONSTRAINT "automation_rules_follow_texts_check" CHECK (((NOT require_follow) OR ((follow_prompt_text IS NOT NULL) AND (not_following_text IS NOT NULL)))),+ CONSTRAINT "automation_rules_hourly_limit_check" CHECK (((hourly_limit IS NULL) OR ((hourly_limit >= 1) AND (hourly_limit <= 750)))),+ CONSTRAINT "automation_rules_keywords_check" CHECK (+CASE+ WHEN (match_mode = 'any'::text) THEN (cardinality(keywords) = 0)+ ELSE ((cardinality(keywords) >= 1) AND (cardinality(keywords) <= 10))+END),+ CONSTRAINT "automation_rules_link_url_check" CHECK (((link_url IS NULL) OR (link_url ~ '^https://'::text))),+ CONSTRAINT "automation_rules_match_mode_check" CHECK ((match_mode = ANY (ARRAY['contains'::text, 'exact'::text, 'any'::text]))),+ CONSTRAINT "automation_rules_media_ids_check" CHECK ((cardinality(media_ids) <= 50)),+ CONSTRAINT "automation_rules_name_check" CHECK (((char_length(name) >= 1) AND (char_length(name) <= 80))),+ CONSTRAINT "automation_rules_not_following_text_check"+ CHECK (((not_following_text IS NULL) OR ((char_length(not_following_text) >= 1) AND (char_length(not_following_text) <= 1000)))),+ CONSTRAINT "automation_rules_pkey" PRIMARY KEY (id),+ CONSTRAINT "automation_rules_public_reply_texts_check"+ CHECK (((cardinality(public_reply_texts) <= 5) AND ((NOT public_reply_enabled) OR (cardinality(public_reply_texts) >= 1)))),+ CONSTRAINT "automation_rules_reply_text_check"+ CHECK ((((char_length(reply_text) >= 1) AND (char_length(reply_text) <= 1000)) OR ((NOT private_reply_enabled) AND (reply_text = ''::text)))),+ CONSTRAINT "automation_rules_user_id_fkey" FOREIGN KEY (user_id) REFERENCES auth.users(id) ON DELETE CASCADE+);++ALTER TABLE "public"."automation_rules"+ ENABLE ROW LEVEL SECURITY;++CREATE INDEX automation_rules_enabled_account_idx ON public.automation_rules USING btree (account_id)+ WHERE enabled;++CREATE INDEX automation_rules_user_id_created_at_idx ON public.automation_rules USING btree (user_id, created_at, id);++CREATE TRIGGER automation_rules_set_updated_at+ BEFORE UPDATE ON public.automation_rules+ FOR EACH ROW+ EXECUTE FUNCTION public.set_updated_at();++GRANT DELETE, INSERT, MAINTAIN, REFERENCES, SELECT, TRIGGER, TRUNCATE, UPDATE ON TABLE "public"."automation_rules" TO "service_role";++REVOKE ALL ON TABLE "public"."automation_rules" FROM "postgres";++GRANT DELETE, INSERT, MAINTAIN, REFERENCES, SELECT, TRIGGER, TRUNCATE, UPDATE ON TABLE "public"."automation_rules" TO "postgres";++REVOKE ALL ON TABLE "public"."automation_rules" FROM "anon", "authenticated";diff --git a/supabase/schemas/public/tables/scheduled_posts.sql b/supabase/schemas/public/tables/scheduled_posts.sqlnew file mode 100644index 0000000..6c036d9--- /dev/null+++ b/supabase/schemas/public/tables/scheduled_posts.sql@@ -0,0 +1,43 @@+CREATE TABLE "public"."scheduled_posts" (+ "id" text NOT NULL,+ "user_id" uuid NOT NULL,+ "account_id" text NOT NULL,+ "status" text NOT NULL DEFAULT 'pending'::text,+ "scheduled_at" timestamp with time zone NOT NULL,+ "data" jsonb NOT NULL DEFAULT '{}'::jsonb,+ "created_at" timestamp with time zone NOT NULL DEFAULT now(),+ "claimed_at" timestamp with time zone,+ "attempts" integer NOT NULL DEFAULT 0,+ "updated_at" timestamp with time zone NOT NULL DEFAULT now(),+ CONSTRAINT "scheduled_posts_account_fkey" FOREIGN KEY (account_id, user_id) REFERENCES public.accounts(id, user_id) ON DELETE CASCADE,+ CONSTRAINT "scheduled_posts_attempts_check" CHECK ((attempts >= 0)),+ CONSTRAINT "scheduled_posts_claim_check" CHECK (((status <> 'publishing'::text) OR (claimed_at IS NOT NULL))),+ CONSTRAINT "scheduled_posts_data_check" CHECK ((jsonb_typeof(data) = 'object'::text)),+ CONSTRAINT "scheduled_posts_pkey" PRIMARY KEY (id),+ CONSTRAINT "scheduled_posts_status_check" CHECK ((status = ANY (ARRAY['pending'::text, 'publishing'::text, 'published'::text, 'failed'::text]))),+ CONSTRAINT "scheduled_posts_user_id_fkey" FOREIGN KEY (user_id) REFERENCES auth.users(id) ON DELETE CASCADE+);++ALTER TABLE "public"."scheduled_posts"+ ENABLE ROW LEVEL SECURITY;++CREATE INDEX scheduled_posts_claimed_idx ON public.scheduled_posts USING btree (claimed_at)+ WHERE (status = 'publishing'::text);++CREATE INDEX scheduled_posts_due_idx ON public.scheduled_posts USING btree (scheduled_at)+ WHERE (status = 'pending'::text);++CREATE INDEX scheduled_posts_user_id_scheduled_at_idx ON public.scheduled_posts USING btree (user_id, scheduled_at);++CREATE TRIGGER scheduled_posts_set_updated_at+ BEFORE UPDATE ON public.scheduled_posts+ FOR EACH ROW+ EXECUTE FUNCTION public.set_updated_at();++GRANT DELETE, INSERT, MAINTAIN, REFERENCES, SELECT, TRIGGER, TRUNCATE, UPDATE ON TABLE "public"."scheduled_posts" TO "service_role";++REVOKE ALL ON TABLE "public"."scheduled_posts" FROM "postgres";++GRANT DELETE, INSERT, MAINTAIN, REFERENCES, SELECT, TRIGGER, TRUNCATE, UPDATE ON TABLE "public"."scheduled_posts" TO "postgres";++REVOKE ALL ON TABLE "public"."scheduled_posts" FROM "anon", "authenticated";diff --git a/supabase/schemas/public/tables/settings.sql b/supabase/schemas/public/tables/settings.sqlnew file mode 100644index 0000000..9567f2f--- /dev/null+++ b/supabase/schemas/public/tables/settings.sql@@ -0,0 +1,26 @@+CREATE TABLE "public"."settings" (+ "user_id" uuid NOT NULL,+ "key" text NOT NULL,+ "value" jsonb NOT NULL DEFAULT '{}'::jsonb,+ "created_at" timestamp with time zone NOT NULL DEFAULT now(),+ "updated_at" timestamp with time zone NOT NULL DEFAULT now(),+ CONSTRAINT "settings_pkey" PRIMARY KEY (user_id, key),+ CONSTRAINT "settings_user_id_fkey" FOREIGN KEY (user_id) REFERENCES auth.users(id) ON DELETE CASCADE,+ CONSTRAINT "settings_value_check" CHECK ((jsonb_typeof(value) = 'object'::text))+);++ALTER TABLE "public"."settings"+ ENABLE ROW LEVEL SECURITY;++CREATE TRIGGER settings_set_updated_at+ BEFORE UPDATE ON public.settings+ FOR EACH ROW+ EXECUTE FUNCTION public.set_updated_at();++GRANT DELETE, INSERT, MAINTAIN, REFERENCES, SELECT, TRIGGER, TRUNCATE, UPDATE ON TABLE "public"."settings" TO "service_role";++REVOKE ALL ON TABLE "public"."settings" FROM "postgres";++GRANT DELETE, INSERT, MAINTAIN, REFERENCES, SELECT, TRIGGER, TRUNCATE, UPDATE ON TABLE "public"."settings" TO "postgres";++REVOKE ALL ON TABLE "public"."settings" FROM "anon", "authenticated";diff --git a/supabase/schemas/public/tables/tracked_posts.sql b/supabase/schemas/public/tables/tracked_posts.sqlnew file mode 100644index 0000000..bee54f0--- /dev/null+++ b/supabase/schemas/public/tables/tracked_posts.sql@@ -0,0 +1,36 @@+CREATE TABLE "public"."tracked_posts" (+ "id" text NOT NULL,+ "user_id" uuid NOT NULL,+ "account_id" text,+ "url" text NOT NULL,+ "label" text NOT NULL DEFAULT ''::text,+ "category" text NOT NULL DEFAULT ''::text,+ "created_at" timestamp with time zone NOT NULL DEFAULT now(),+ "updated_at" timestamp with time zone NOT NULL DEFAULT now(),+ "data" jsonb,+ "content_type" text NOT NULL DEFAULT 'reddit'::text,+ CONSTRAINT "tracked_posts_account_check" CHECK (((content_type = 'reddit'::text) OR (account_id IS NULL))),+ CONSTRAINT "tracked_posts_account_fkey" FOREIGN KEY (account_id, user_id) REFERENCES public.accounts(id, user_id) ON DELETE SET NULL (account_id),+ CONSTRAINT "tracked_posts_content_type_check" CHECK ((content_type = ANY (ARRAY['reddit'::text, 'youtube'::text]))),+ CONSTRAINT "tracked_posts_data_check" CHECK (((data IS NULL) OR (jsonb_typeof(data) = 'object'::text))),+ CONSTRAINT "tracked_posts_pkey" PRIMARY KEY (id),+ CONSTRAINT "tracked_posts_user_id_fkey" FOREIGN KEY (user_id) REFERENCES auth.users(id) ON DELETE CASCADE+);++ALTER TABLE "public"."tracked_posts"+ ENABLE ROW LEVEL SECURITY;++CREATE INDEX tracked_posts_user_id_created_at_idx ON public.tracked_posts USING btree (user_id, created_at DESC);++CREATE TRIGGER tracked_posts_set_updated_at+ BEFORE UPDATE ON public.tracked_posts+ FOR EACH ROW+ EXECUTE FUNCTION public.set_updated_at();++GRANT DELETE, INSERT, MAINTAIN, REFERENCES, SELECT, TRIGGER, TRUNCATE, UPDATE ON TABLE "public"."tracked_posts" TO "service_role";++REVOKE ALL ON TABLE "public"."tracked_posts" FROM "postgres";++GRANT DELETE, INSERT, MAINTAIN, REFERENCES, SELECT, TRIGGER, TRUNCATE, UPDATE ON TABLE "public"."tracked_posts" TO "postgres";++REVOKE ALL ON TABLE "public"."tracked_posts" FROM "anon", "authenticated";