Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions supabase/database/sql/comment_count_migration.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
UPDATE snippets s
SET comment_count = (
SELECT COUNT(*)
FROM comments c
WHERE c.room_id = s.id
and deleted_at is null
);
Comment on lines +1 to +7
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

The SQL logic looks correct but consider adding safety measures.

While the UPDATE query is logically correct, consider these improvements for safer execution:

+ BEGIN;
+
+ -- Log start of migration
+ DO $$
+ BEGIN
+   RAISE NOTICE 'Starting comment count migration...';
+ END $$;
+
 UPDATE snippets s
 SET comment_count = (
     SELECT COUNT(*)
     FROM comments c
     WHERE c.room_id = s.id
     and deleted_at is null
 );
+
+ -- Validate the update
+ DO $$
+ DECLARE
+   invalid_count INTEGER;
+ BEGIN
+   SELECT COUNT(*) INTO invalid_count
+   FROM snippets s
+   WHERE s.comment_count != (
+     SELECT COUNT(*)
+     FROM comments c
+     WHERE c.room_id = s.id
+     AND deleted_at is null
+   );
+   
+   IF invalid_count > 0 THEN
+     RAISE EXCEPTION 'Validation failed: % snippets have incorrect comment counts', invalid_count;
+   END IF;
+   
+   RAISE NOTICE 'Migration completed successfully';
+ END $$;
+
+ COMMIT;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
UPDATE snippets s
SET comment_count = (
SELECT COUNT(*)
FROM comments c
WHERE c.room_id = s.id
and deleted_at is null
);
BEGIN;
-- Log start of migration
DO $$
BEGIN
RAISE NOTICE 'Starting comment count migration...';
END $$;
UPDATE snippets s
SET comment_count = (
SELECT COUNT(*)
FROM comments c
WHERE c.room_id = s.id
and deleted_at is null
);
-- Validate the update
DO $$
DECLARE
invalid_count INTEGER;
BEGIN
SELECT COUNT(*) INTO invalid_count
FROM snippets s
WHERE s.comment_count != (
SELECT COUNT(*)
FROM comments c
WHERE c.room_id = s.id
AND deleted_at is null
);
IF invalid_count > 0 THEN
RAISE EXCEPTION 'Validation failed: % snippets have incorrect comment counts', invalid_count;
END IF;
RAISE NOTICE 'Migration completed successfully';
END $$;
COMMIT;

💡 Codebase verification

Migration needs concurrent update handling

The trigger function update_snippet_comment_count uses simple increment/decrement operations which could lead to race conditions during the migration. The migration's UPDATE query should use a transaction-safe approach to count comments. Consider using:

UPDATE snippets s
SET comment_count = (
    SELECT COUNT(*)
    FROM comments c
    WHERE c.room_id = s.id
    AND deleted_at is null
    FOR UPDATE
);
  • The trigger function in update_snippet_comment_count.sql uses non-atomic comment_count + 1 and comment_count - 1 operations
  • The migration query doesn't use any concurrency control mechanisms like FOR UPDATE
  • Missing trigger creation statement that would bind this function to the comments table
🔗 Analysis chain

Verify concurrent update handling.

Ensure that the trigger function update_snippet_comment_count mentioned in the summary is properly handling concurrent updates during this migration.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if there's proper concurrent update handling in the trigger function

# Look for the trigger function definition and its concurrency controls
ast-grep --pattern 'CREATE OR REPLACE FUNCTION update_snippet_comment_count'

# Check if there are any other triggers or constraints on the comment_count column
rg -A 10 'CREATE TRIGGER.*comment_count'
rg -A 5 'ADD CONSTRAINT.*comment_count'

Length of output: 163


Script:

#!/bin/bash
# Let's try a broader search to find any trigger-related code
rg -i "trigger" supabase/database/sql/

# Search for any function that updates comment_count
rg -i "comment_count" supabase/database/sql/

# Look for any migration files that might contain trigger definitions
fd . supabase/database/sql/ -t f

Length of output: 2462


Script:

#!/bin/bash
# Let's examine the content of the trigger function
cat supabase/database/sql/update_snippet_comment_count.sql

# Also check if there's a trigger creation for this function
rg -A 5 "CREATE TRIGGER.*comment" supabase/database/sql/

Length of output: 575


CREATE INDEX idx_snippets_comment_count ON snippets(comment_count DESC);
14 changes: 10 additions & 4 deletions supabase/database/sql/get_filtering_options_function.sql
Original file line number Diff line number Diff line change
Expand Up @@ -68,13 +68,19 @@ BEGIN

-- Fetch unique radio station codes from the audio_files table
WITH unique_sources AS (
SELECT DISTINCT radio_station_code
FROM public.audio_files
WHERE radio_station_code IS NOT NULL
SELECT DISTINCT
radio_station_code,
radio_station_name
FROM public.audio_files
WHERE radio_station_code IS NOT NULL
)
SELECT jsonb_agg(
jsonb_build_object(
'label', radio_station_code,
'label', CASE
WHEN radio_station_name IS NOT NULL
THEN radio_station_name || ' - ' || radio_station_code
ELSE radio_station_code
END,
'value', radio_station_code
)
) INTO sources
Expand Down
90 changes: 76 additions & 14 deletions supabase/database/sql/get_snippets_function.sql
Original file line number Diff line number Diff line change
@@ -1,10 +1,5 @@
CREATE
OR REPLACE FUNCTION get_snippets (
page INTEGER DEFAULT 0,
page_size INTEGER DEFAULT 10,
p_language TEXT DEFAULT 'english',
p_filter JSONB DEFAULT '{}'::jsonb
) RETURNS jsonb SECURITY DEFINER AS $$
OR REPLACE FUNCTION get_snippets (p_language text,p_filter jsonb,page INTEGER,page_size INTEGER, p_order_by text) RETURNS jsonb SECURITY DEFINER AS $$
DECLARE
current_user_id UUID;
result jsonb;
Expand Down Expand Up @@ -215,7 +210,49 @@ BEGIN
)
)
AND (
-- Exclude snippets with 2 or more dislikes
p_filter IS NULL OR
NOT p_filter ? 'upvotedBy' OR
(
CASE
WHEN jsonb_array_length(p_filter->'upvotedBy') = 0 THEN TRUE
ELSE (
CASE
WHEN (
p_filter->'upvotedBy' ? 'by_me' AND
p_filter->'upvotedBy' ? 'by_others'
) THEN
EXISTS (
SELECT 1
FROM label_upvotes lu
WHERE lu.snippet_label IN (
SELECT id FROM snippet_labels WHERE snippet = s.id
)
)
WHEN p_filter->'upvotedBy' ? 'by_me' THEN
EXISTS (
SELECT 1
FROM label_upvotes lu
WHERE lu.snippet_label IN (
SELECT id FROM snippet_labels WHERE snippet = s.id
)
AND lu.upvoted_by = current_user_id
)
WHEN p_filter->'upvotedBy' ? 'by_others' THEN
EXISTS (
SELECT 1
FROM label_upvotes lu
WHERE lu.snippet_label IN (
SELECT id FROM snippet_labels WHERE snippet = s.id
)
AND lu.upvoted_by != current_user_id
)
ELSE FALSE
END
)
END
)
)
AND (
NOT EXISTS (
SELECT 1
FROM (
Expand All @@ -228,7 +265,32 @@ BEGIN
WHERE dislikes.snippet = s.id
)
)
ORDER BY s.recorded_at DESC;
ORDER BY (
-- Sort by engagement (upvotes + likes)
CASE WHEN p_order_by = 'upvotes'
THEN s.upvote_count + s.like_count
END DESC,

-- Sort by comment count
CASE WHEN p_order_by = 'comments'
THEN s.comment_count
END DESC,

-- Sort by last activity date
CASE WHEN p_order_by = 'activities'
THEN s.updated_at
END DESC,

-- Sort by recording date (default sort)
CASE WHEN p_order_by IS NULL OR
p_order_by = 'latest' OR
p_order_by = ''
THEN s.recorded_at
END DESC,

-- Always sort by recorded_at as final tiebreaker
s.recorded_at DESC;
)

-- Get total count
SELECT COUNT(*) INTO total_count
Expand All @@ -249,11 +311,11 @@ BEGIN
total_pages := CEIL(total_count::FLOAT / page_size);

RETURN jsonb_build_object(
'num_of_snippets', COALESCE(jsonb_array_length(result), 0),
'snippets', COALESCE(result, '[]'::jsonb),
'current_page', page,
'page_size', page_size,
'total_pages', total_pages
);
'num_of_snippets', total_count,
'snippets', COALESCE(result, '[]'::jsonb),
'current_page', page,
'page_size', page_size,
'total_pages', total_pages
);
END;
$$ LANGUAGE plpgsql;
9 changes: 9 additions & 0 deletions supabase/database/sql/like_count_migration.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
UPDATE snippets s
SET like_count = (
SELECT COUNT(*)
FROM user_like_snippets uls
WHERE uls.snippet = s.id
AND uls.value = 1
);

CREATE INDEX idx_snippets_like_count ON snippets(like_count DESC);
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Perhaps creating index for comment_count and upvote_count as well? 🤔

4 changes: 4 additions & 0 deletions supabase/database/sql/like_count_trigger.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
CREATE TRIGGER update_like_count
AFTER INSERT OR UPDATE OR DELETE ON user_like_snippets
FOR EACH ROW
EXECUTE FUNCTION update_snippet_like_count();
Comment thread
giahung68 marked this conversation as resolved.
14 changes: 14 additions & 0 deletions supabase/database/sql/update_snippet_comment_count.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
CREATE OR REPLACE FUNCTION update_snippet_comment_count()
RETURNS TRIGGER AS $$
BEGIN
UPDATE snippets
SET comment_count = (
SELECT COUNT(*)
FROM comments
WHERE room_id = COALESCE(NEW.room_id, OLD.room_id)
)
WHERE id = COALESCE(NEW.room_id, OLD.room_id);

RETURN NULL;
END;
$$ LANGUAGE plpgsql;
Comment on lines +1 to +14
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Add input validation and error handling

While the recalculation approach is good, the function needs additional safeguards:

 CREATE OR REPLACE FUNCTION update_snippet_comment_count() 
 RETURNS TRIGGER AS $$
 BEGIN
+    -- Validate input
+    IF (TG_OP = 'INSERT' AND NEW.room_id IS NULL) OR 
+       (TG_OP = 'DELETE' AND OLD.room_id IS NULL) THEN
+        RAISE EXCEPTION 'room_id cannot be null';
+    END IF;
+
+    -- Verify snippet exists
+    IF NOT EXISTS (
+        SELECT 1 
+        FROM snippets 
+        WHERE id = COALESCE(NEW.room_id, OLD.room_id)
+    ) THEN
+        RAISE EXCEPTION 'Snippet with id % does not exist', 
+            COALESCE(NEW.room_id, OLD.room_id);
+    END IF;
+
     UPDATE snippets
     SET comment_count = (
         SELECT COUNT(*)
         FROM comments 
-        WHERE room_id = COALESCE(NEW.room_id, OLD.room_id)
+        WHERE room_id = COALESCE(NEW.room_id, OLD.room_id)
+        AND deleted_at IS NULL  -- Only count non-deleted comments
     )
     WHERE id = COALESCE(NEW.room_id, OLD.room_id);
+
+    IF NOT FOUND THEN
+        RAISE EXCEPTION 'Failed to update comment count for snippet %',
+            COALESCE(NEW.room_id, OLD.room_id);
+    END IF;
     
     RETURN NULL;
 END;
 $$ LANGUAGE plpgsql;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
CREATE OR REPLACE FUNCTION update_snippet_comment_count()
RETURNS TRIGGER AS $$
BEGIN
UPDATE snippets
SET comment_count = (
SELECT COUNT(*)
FROM comments
WHERE room_id = COALESCE(NEW.room_id, OLD.room_id)
)
WHERE id = COALESCE(NEW.room_id, OLD.room_id);
RETURN NULL;
END;
$$ LANGUAGE plpgsql;
CREATE OR REPLACE FUNCTION update_snippet_comment_count()
RETURNS TRIGGER AS $$
BEGIN
-- Validate input
IF (TG_OP = 'INSERT' AND NEW.room_id IS NULL) OR
(TG_OP = 'DELETE' AND OLD.room_id IS NULL) THEN
RAISE EXCEPTION 'room_id cannot be null';
END IF;
-- Verify snippet exists
IF NOT EXISTS (
SELECT 1
FROM snippets
WHERE id = COALESCE(NEW.room_id, OLD.room_id)
) THEN
RAISE EXCEPTION 'Snippet with id % does not exist',
COALESCE(NEW.room_id, OLD.room_id);
END IF;
UPDATE snippets
SET comment_count = (
SELECT COUNT(*)
FROM comments
WHERE room_id = COALESCE(NEW.room_id, OLD.room_id)
AND deleted_at IS NULL -- Only count non-deleted comments
)
WHERE id = COALESCE(NEW.room_id, OLD.room_id);
IF NOT FOUND THEN
RAISE EXCEPTION 'Failed to update comment count for snippet %',
COALESCE(NEW.room_id, OLD.room_id);
END IF;
RETURN NULL;
END;
$$ LANGUAGE plpgsql;

💡 Codebase verification

⚠️ Potential issue

Create trigger to execute the update_snippet_comment_count function

Add the following trigger definition to the same SQL file:

CREATE TRIGGER update_comment_count
AFTER INSERT OR DELETE ON comments
FOR EACH ROW
EXECUTE FUNCTION update_snippet_comment_count();

Based on the verification:

  1. The trigger is indeed missing from the codebase
  2. Similar trigger patterns exist (e.g., update_like_count trigger in like_count_trigger.sql)
  3. The function exists but is not being executed by any trigger
🔗 Analysis chain

Create trigger to execute the function

The trigger function is defined but the corresponding trigger is missing.

Add the following trigger definition:

CREATE TRIGGER update_comment_count
AFTER INSERT OR DELETE ON comments
FOR EACH ROW
EXECUTE FUNCTION update_snippet_comment_count();
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if trigger exists
rg "CREATE TRIGGER.*update_snippet_comment_count"

Length of output: 51


Script:

#!/bin/bash
# Let's search for any trigger definitions in SQL files
fd -e sql -x cat {} | rg -i "CREATE\s+TRIGGER"

# Also search for any files that might contain trigger definitions
fd -e sql | grep -i "trigger"

Length of output: 1997


Script:

#!/bin/bash
# Let's check the content of like_count_trigger.sql as it might have a similar pattern
cat supabase/database/sql/like_count_trigger.sql

# Also let's check for any other files that might contain our function name
fd -e sql -x cat {} | rg -A 5 "update_snippet_comment_count"

Length of output: 417

16 changes: 16 additions & 0 deletions supabase/database/sql/update_snippet_like_count.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
CREATE OR REPLACE FUNCTION update_snippet_like_count()
RETURNS TRIGGER AS $$
BEGIN
-- Update the like count for the affected snippet
UPDATE snippets
SET like_count = (
SELECT COUNT(*)
FROM user_like_snippets
WHERE snippet = COALESCE(NEW.snippet, OLD.snippet)
AND value = 1
)
Comment on lines +6 to +11
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codebase verification

Performance optimization needed for user_like_snippets table

Based on the verification attempts, we couldn't find the table definition or any existing indexes for the user_like_snippets table in the codebase. This suggests that the recommended index on (snippet, value) is indeed missing, which could impact query performance for the COUNT operation.

  • Add an index on (snippet, value) columns in the user_like_snippets table to optimize the COUNT query
  • Consider implementing a materialized count if the table grows significantly
🔗 Analysis chain

Consider optimizing the COUNT query performance.

For large tables, counting all matching rows can become a performance bottleneck. Consider these optimizations:

  1. Add an index on (snippet, value) in the user_like_snippets table
  2. Consider maintaining a materialized count if performance becomes an issue

Let's verify if the required index exists:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if the index exists on user_like_snippets table
rg -A 5 "CREATE.*INDEX.*user_like_snippets.*snippet.*value"

Length of output: 61


Script:

#!/bin/bash
# Let's check for any index definitions in the schema files
fd -e sql | xargs rg -i "CREATE.*INDEX|CREATE TABLE.*user_like_snippets"

Length of output: 3456


Script:

#!/bin/bash
# Let's check for the user_like_snippets table definition and any related indexes
rg -i "CREATE TABLE.*user_like_snippets" -A 10

Length of output: 48


Script:

#!/bin/bash
# Let's search for any mention of user_like_snippets table in migration files
rg -i "user_like_snippets" supabase/migrations/

Length of output: 47

WHERE id = COALESCE(NEW.snippet, OLD.snippet);

RETURN NULL;
END;
$$ LANGUAGE plpgsql;
25 changes: 25 additions & 0 deletions supabase/database/sql/update_snippet_upvote_count.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
CREATE OR REPLACE FUNCTION update_snippet_upvote_count()
RETURNS TRIGGER AS $$
DECLARE
snippet_id UUID;
BEGIN
Comment on lines +1 to +5
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Add trigger creation statement

The trigger function is defined but the corresponding trigger creation statement (CREATE TRIGGER) is missing. This should specify when the trigger executes (BEFORE/AFTER) and for which operations (INSERT/UPDATE/DELETE).

Add the trigger creation statement. Example:

CREATE TRIGGER update_snippet_upvote_count_trigger
AFTER INSERT OR DELETE OR UPDATE ON label_upvotes
FOR EACH ROW
EXECUTE FUNCTION update_snippet_upvote_count();

-- Get the snippet_id from snippet_labels
SELECT snippet INTO snippet_id
FROM snippet_labels
WHERE id = COALESCE(NEW.snippet_label, OLD.snippet_label);
Comment on lines +7 to +9
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Add error handling for invalid snippet_label

The query silently continues if the snippet_label is invalid. Consider adding explicit error handling to maintain data integrity.

    SELECT snippet INTO snippet_id
    FROM snippet_labels
    WHERE id = COALESCE(NEW.snippet_label, OLD.snippet_label);
+   IF NOT FOUND THEN
+       RAISE EXCEPTION 'Invalid snippet_label: %', COALESCE(NEW.snippet_label, OLD.snippet_label);
+   END IF;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
SELECT snippet INTO snippet_id
FROM snippet_labels
WHERE id = COALESCE(NEW.snippet_label, OLD.snippet_label);
SELECT snippet INTO snippet_id
FROM snippet_labels
WHERE id = COALESCE(NEW.snippet_label, OLD.snippet_label);
IF NOT FOUND THEN
RAISE EXCEPTION 'Invalid snippet_label: %', COALESCE(NEW.snippet_label, OLD.snippet_label);
END IF;


-- Update the upvote count for the affected snippet
IF snippet_id IS NOT NULL THEN
UPDATE snippets
SET upvote_count = (
SELECT COUNT(*)
FROM label_upvotes lu
JOIN snippet_labels sl ON lu.snippet_label = sl.id
WHERE sl.snippet = snippet_id
)
WHERE id = snippet_id;
Comment on lines +13 to +20
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codebase verification

Add indexes to optimize label upvote queries

Based on the codebase analysis, the tables are frequently joined and queried, but only one index (idx_snippets_like_count) exists. The following indexes should be added to optimize the upvote count calculation and related queries:

  • snippet_labels(snippet): Used in multiple JOIN operations and WHERE clauses
  • label_upvotes(snippet_label): Used in JOIN operations and COUNT queries
  • label_upvotes(upvoted_by, snippet_label): Used in unique constraint and filtering
CREATE INDEX IF NOT EXISTS idx_snippet_labels_snippet ON snippet_labels(snippet);
CREATE INDEX IF NOT EXISTS idx_label_upvotes_snippet_label ON label_upvotes(snippet_label);
CREATE UNIQUE INDEX IF NOT EXISTS idx_label_upvotes_user_label ON label_upvotes(upvoted_by, snippet_label);
🔗 Analysis chain

Optimize query performance with appropriate indexes

The COUNT subquery with JOIN could be performance-intensive. Ensure proper indexes exist on the join columns and frequently queried fields.

Let's verify the existing indexes:

Consider adding these indexes if not present:

CREATE INDEX IF NOT EXISTS idx_snippet_labels_snippet ON snippet_labels(snippet);
CREATE INDEX IF NOT EXISTS idx_label_upvotes_snippet_label ON label_upvotes(snippet_label);
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for existing indexes on relevant columns

# Search for index definitions
rg -A 3 'CREATE.*INDEX' supabase/database/sql/

# Search for table definitions to verify primary keys
rg -A 10 'CREATE TABLE (snippet_labels|label_upvotes|snippets)' supabase/database/sql/

Length of output: 251


Script:

#!/bin/bash
# Let's search for table definitions in all SQL files
rg -A 10 'CREATE TABLE' supabase/database/sql/

# Also search for any foreign key constraints that might imply indexes
rg -B 2 -A 2 'FOREIGN KEY' supabase/database/sql/

# Search specifically for label_upvotes and snippet_labels related definitions
rg -A 10 '(label_upvotes|snippet_labels)' supabase/database/sql/

Length of output: 22235

END IF;

RETURN NULL;
END;
$$ LANGUAGE plpgsql;
Comment on lines +1 to +25
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codebase verification

Missing trigger definition for upvote count updates

The function update_snippet_upvote_count() is defined but there's no corresponding trigger to execute it. The function needs to be triggered after INSERT, UPDATE, or DELETE operations on the label_upvotes table to maintain accurate upvote counts.

  • Add a trigger definition similar to the like count trigger:
CREATE TRIGGER update_upvote_count
AFTER INSERT OR UPDATE OR DELETE ON label_upvotes
FOR EACH ROW
EXECUTE FUNCTION update_snippet_upvote_count();
🔗 Analysis chain

Verify trigger execution order with related triggers

This trigger function is part of a set of related triggers (comment_count, like_count). Ensure proper trigger execution order to maintain data consistency.


Let me gather more information about the trigger definitions for all these functions.


Let me try one more search to find the trigger definition for the upvote count function and table definitions using a different pattern.


Let me try one final search with a different approach to find all SQL files and their content.


Let me check the content of the relevant files for trigger definitions and table relationships.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for related triggers and their execution order

# Search for other trigger definitions
rg -A 5 'CREATE TRIGGER' supabase/database/sql/

# Search for related trigger functions
rg -A 5 'update_snippet.*_count\(\)' supabase/database/sql/

Length of output: 2003


Script:

#!/bin/bash
# Search for trigger definitions for all count-related functions
rg -A 3 'CREATE TRIGGER.*update_.*_count' supabase/database/sql/

# Search for table definitions to understand the relationships
rg -A 10 'CREATE TABLE (snippets|snippet_labels|label_upvotes)' supabase/database/sql/

Length of output: 482


Script:

#!/bin/bash
# Search for trigger definition for upvote count
rg -A 3 'CREATE TRIGGER' supabase/database/sql/update_snippet_upvote_count.sql

# Search for table definitions with a broader pattern
rg -A 10 'CREATE TABLE' supabase/database/sql/schema.sql

Length of output: 212


Script:

#!/bin/bash
# Find all SQL files in the database directory
fd -e sql . supabase/database/

# Search for trigger definition in all SQL files
rg -A 3 'CREATE TRIGGER.*upvote' supabase/database/

# Search for table definitions in all SQL files
rg -A 5 'CREATE TABLE' supabase/database/

Length of output: 1670


Script:

#!/bin/bash
# Check content of upvote-related files
cat supabase/database/sql/update_snippet_upvote_count.sql
cat supabase/database/sql/toggle_upvote_label_function.sql

# Check content of table definitions in migration files
cat supabase/database/sql/comment_count_migration.sql
cat supabase/database/sql/like_count_migration.sql

Length of output: 3621

13 changes: 13 additions & 0 deletions supabase/database/sql/upvote_count_migration.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
WITH upvote_counts AS (
SELECT sl.snippet AS snippet_id,
COUNT(lu.id) AS total_upvotes
FROM snippet_labels sl
LEFT JOIN label_upvotes lu ON lu.snippet_label = sl.id
GROUP BY sl.snippet
)
UPDATE snippets s
SET upvote_count = COALESCE(uc.total_upvotes, 0)
FROM upvote_counts uc
WHERE s.id = uc.snippet_id;
Comment on lines +8 to +11
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Consider RIGHT JOIN to update all snippets

The current UPDATE might miss snippets that have no entries in snippet_labels. Consider modifying the CTE to start from the snippets table to ensure all snippets get their upvote_count updated.

 WITH upvote_counts AS (
-    SELECT sl.snippet AS snippet_id,
+    SELECT s.id AS snippet_id,
            COUNT(lu.id) AS total_upvotes
-    FROM snippet_labels sl
-    LEFT JOIN label_upvotes lu ON lu.snippet_label = sl.id
-    GROUP BY sl.snippet
+    FROM snippets s
+    LEFT JOIN snippet_labels sl ON sl.snippet = s.id
+    LEFT JOIN label_upvotes lu ON lu.snippet_label = sl.id
+    GROUP BY s.id
 )

Committable suggestion skipped: line range outside the PR's diff.


CREATE INDEX idx_snippets_upvote_count ON snippets(upvote_count DESC);