Skip to content

Instantly share code, notes, and snippets.

View AntonAL's full-sized avatar

Anton AntonAL

View GitHub Profile
@bfolkens
bfolkens / postgres_counter_cache.sql
Last active November 8, 2023 17:21
PostgreSQL Counter Cache
-- Courtesy
-- http://shuber.io/porting-activerecord-counter-cache-behavior-to-postgres/
CREATE FUNCTION increment_counter(table_name text, column_name text, id integer, step integer)
RETURNS VOID AS $$
DECLARE
table_name text := quote_ident(table_name);
column_name text := quote_ident(column_name);
conditions text := ' WHERE id = $1';
updates text := column_name || '=' || column_name || '+' || step;