1

In project there is gonna to be more than 100 millions users and i want to partition it by range and list (composite) in other hand partition tables create by rails when our rows are more than 5 millions (any app id has 5 millions of user). and also create a partition table automatically every month.

I'm using postgresql for these purpose

there is any good gem for this not like pgslice and pgparty

I've tried a lot of gems but none of them work for me.

CREATE TABLE public.admins (
id int not null,
name varchar,
firstname varchar,
app_id int not null,
created_at date not null
) PARTITION BY RANGE(created_at);

CREATE INDEX ON admins(created_at); 

This is postgres code for table

CREATE OR REPLACE FUNCTION new_partition_creator() RETURNS trigger AS 
$BODY$
DECLARE
  partition_date TEXT;
  partition TEXT;
  partition_day int;
  startdate date;
  enddate date;
BEGIN
  partition_day := to_char(NEW.logdate,'DD');
  partition_date := to_char(NEW.logdate,'YYYY_MM');

     IF partition_day < 15 THEN
  partition := TG_RELNAME || '_' || partition_date || '_p1';
  startdate := to_char(NEW.logdate,'YYYY-MM-01');
  enddate := date_trunc('MONTH', NEW.logdate) + INTERVAL '1 MONTH - 1 day';
  ELSE
  partition := TG_RELNAME || '_' || partition_date || '_p2';
  startdate := to_char(NEW.logdate,'YYYY-MM-15');
  enddate := date_trunc('MONTH', NEW.logdate) + INTERVAL '1 MONTH - 1 day';
  END IF;
  
  IF NOT EXISTS(SELECT relname FROM pg_class WHERE relname=partition) THEN
    RAISE NOTICE 'A partition has been created %',partition;
    EXECUTE 'CREATE TABLE ' || partition || ' ( CHECK ( logdate >= DATE ''' || startdate || '''  AND logdate <=  DATE ''' ||  enddate || ''' )) INHERITS (' || TG_RELNAME || ');';
    EXECUTE 'CREATE INDEX ' || partition || '_logdate ON '  || partition || '(logdate)';
    EXECUTE 'ALTER TABLE ' || partition || ' add primary key(city_id);';       
    END IF;
    EXECUTE 'INSERT INTO ' || partition || ' SELECT(' || TG_RELNAME || ' ' || quote_literal(NEW) || ').* RETURNING city_id;';
  RETURN NULL;
END;
$BODY$
LANGUAGE plpgsql VOLATILE
COST 100;

This is a sample of code in postgres but all of these and handy I want it automatically

Pafjo
  • 4,979
  • 3
  • 23
  • 31
uamin
  • 36
  • 3
  • i want a system in rails create tables automatically every month and any time user gonna be more than 5m in any table – uamin Sep 27 '20 at 09:57

0 Answers0