Impressive code generation by Claude-3.5-sonnet
I was building an app, it has a topic table which is recursive (can have parent topic). Then there's the items table, It will have items that belongs to a topic but can also have a variant. So a distinct topic+variant counts as a conversation (items are part of a conversation).
I wanted to count how many conversation a topic has and also how many conversation it's children have. So whenever a variant is added/deleted I wanted this count to propagate all the way to the top.
Cursor generator with calude-3.5-sonnet generated this complex looking sql/function/trigger etc on one go. Very impressed - I didn't know half of these sql code as I'm frontend focused developer! I run it on supabase and it worked!
In case anyone interested, this is the app -> https://de.srizon.com (Work In Progress but already usable)
-- Function to update conversation_count for a single topic
CREATE OR REPLACE FUNCTION app.update_topic_conversation_count(target_topic_id bigint)
RETURNS void AS $$
BEGIN
-- Update direct conversation count
UPDATE app.topics
SET conversation_count = (
SELECT COUNT(DISTINCT variant)
FROM app.items
WHERE topic_id = topics.id
)
WHERE id = target_topic_id;
-- Update child conversation counts recursively up the tree
WITH RECURSIVE topic_tree AS (
-- Base case: start with the current topic's parent
SELECT id, parent_id
FROM app.topics
WHERE id = (SELECT parent_id FROM app.topics WHERE id = target_topic_id)
UNION
-- Recursive case: get all ancestors
SELECT t.id, t.parent_id
FROM app.topics t
INNER JOIN topic_tree tt ON t.id = tt.parent_id
)
UPDATE app.topics t
SET child_topic_conversation_count = (
SELECT COALESCE(SUM(conversation_count), 0) + COALESCE(SUM(child_topic_conversation_count), 0)
FROM app.topics child
WHERE child.parent_id = t.id
)
WHERE t.id IN (SELECT id FROM topic_tree);
END;
$$ LANGUAGE plpgsql;
-- Initial population of conversation counts for all topics
DO $$
DECLARE
topic_record RECORD;
BEGIN
FOR topic_record IN SELECT id FROM app.topics ORDER BY depth DESC
LOOP
PERFORM app.update_topic_conversation_count(topic_record.id);
END LOOP;
END;
$$;
-- Create trigger to maintain counts
CREATE OR REPLACE FUNCTION app.trigger_update_topic_conversation_count()
RETURNS TRIGGER AS $$
BEGIN
IF TG_OP = 'INSERT' OR TG_OP = 'UPDATE' THEN
PERFORM app.update_topic_conversation_count(NEW.topic_id);
ELSIF TG_OP = 'DELETE' THEN
PERFORM app.update_topic_conversation_count(OLD.topic_id);
END IF;
RETURN NULL;
END;
$$ LANGUAGE plpgsql;
CREATE TRIGGER items_conversation_count_trigger
AFTER INSERT OR UPDATE OR DELETE ON app.items
FOR EACH ROW EXECUTE FUNCTION app.trigger_update_topic_conversation_count();
Posted Jan 4, 2025, 8:35 PM UTC