1

есть существующая большая таблица. хочу ее партицировать. ввиду долгого времени дампа хочу делать на боевом сервере. данные постоянно на него приходят

вот функция партицирования

CREATE OR REPLACE FUNCTION "SC_Tag".server_partition_function (
)
RETURNS trigger AS
$body$
DECLARE
  _new_time timestamp;
  _tablename text;
  _startdate text;
  _month text;
  _enddate text;
  _result record;
BEGIN
  --Takes the current inbound "time" value and determines when midnight is for the given date
  _new_time := NEW."F_Date";
  _startdate := _new_time::date;
  _month := to_char(_new_time, 'YYYY-MM');
  _tablename := 'tagdata_'||_month;

  -- Check if the partition needed for the current record exists
  PERFORM 1
  FROM pg_catalog.pg_class c
  JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
  WHERE c.relkind = 'r'
  AND c.relname = _tablename
  AND n.nspname = 'SC_Tag';

  -- If the partition needed does not yet exist, then we create it:
  -- Note that || is string concatenation (joining two strings to make one)
  IF NOT FOUND THEN
    _enddate:=to_char(_startdate::date + INTERVAL '1 month', 'YYYY-MM');

    EXECUTE 'CREATE TABLE "SC_Tag".' || quote_ident(_tablename) || ' (
      CHECK ( to_char("F_Date", ''YYYY-MM'') >= ' || quote_literal(_month)|| '
        AND to_char("F_Date", ''YYYY-MM'') < ' || quote_literal(_enddate) || '
      )
    ) INHERITS ("SC_Tag"."T_TagData")';

  -- Table permissions are not inherited from the parent.
  -- If permissions change on the master be sure to change them on the child also.
  --EXECUTE 'ALTER TABLE "SC_Tag".' || quote_ident(_tablename) || ' OWNER TO postgres';
  --EXECUTE 'GRANT ALL ON TABLE "SC_Tag".' || quote_ident(_tablename) || ' TO my_role';

  -- Indexes are defined per child, so we assign a default index that uses the partition columns
  EXECUTE 'CREATE INDEX ' || quote_ident(_tablename||'_indx1') || ' ON "SC_Tag".' || quote_ident(_tablename) || ' ("F_Date", "ID_TagData")';
END IF;

-- Insert the current record into the correct partition, which we are sure will now exist.
EXECUTE 'INSERT INTO "SC_Tag".' || quote_ident(_tablename) || ' VALUES ($1.*)' USING NEW;
RETURN NULL;
END;
$body$
LANGUAGE 'plpgsql'
VOLATILE
CALLED ON NULL INPUT
SECURITY INVOKER
COST 100;

тригер можно поставить на инзерт. но тогда только новые данные будут идти в партиции.

есть такая хитрая затея - снять дамп и залить его на сервер еще раз. при этом данные будут писаться в партиции. но старые данные останутся в мастер таблице.

как поступить правильно?

UPD

по сути надо перед EXECUTE 'INSERT INTO "SC_Tag".' || quote_ident(_tablename) || ' VALUES ($1.*)' USING NEW; вставить проверку - новая ли запись. и если есть такой ид в базе, то удалять запись.

но вот такой код не проходит

DELETE FROM 
  "SC_Tag"."T_TagData" 
WHERE 
"ID_TagData" = NEW."ID_TagData";
-- Insert the current record into the correct partition, which we are sure will now exist.
EXECUTE 'INSERT INTO "SC_Tag".' || quote_ident(_tablename) || ' VALUES ($1.*)' USING NEW;
1
  • 1. просто напиши инициализирующий скрипт создающий первоначальную структуру. 2. а как на счет апдейтов меняющих поле партицирования?
    – Ivan
    17 июн 2015 в 8:36

1 ответ 1

0

вот так вроде заработало. тупо удаляю записи что есть в мастер таблице и снова их вношу

CREATE OR replace FUNCTION "SC_Tag".server_partition_function ( )
RETURNS TRIGGER AS $body$ DECLARE _new_time timestamp;
_id INTEGER;
_tablename text;
_startdate text;
_month text;
_enddate text;
_result record;
BEGIN
    --Takes the CURRENT inbound "time" VALUE AND determines WHEN midnight IS FOR the given date
    _new_time : = NEW. "F_Date";
_id : = NEW. "ID_TagData";
_startdate : = _new_time::date;
_month : = to_char (
    _new_time,
    'YYYY-MM' );
_tablename : = 'tagdata_' || _month;
-- CHECK IF the PARTITION needed FOR the CURRENT record EXISTS
PERFORM 1
FROM
    pg_catalog.pg_class c
    JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
WHERE
    c.relkind = 'r'
    AND c.relname = _tablename
    AND n.nspname = 'SC_Tag';
-- IF the PARTITION needed does NOT yet exist, THEN we CREATE it:
-- Note that || IS string concatenation (joining two strings TO make one)
IF NOT FOUND THEN _enddate: = to_char (
    _startdate::date + interval '1 month',
    'YYYY-MM' );
EXECUTE 'CREATE TABLE "SC_Tag".' || quote_ident (
    _tablename )
|| ' (
 CONSTRAINT ' || quote_ident (
    _tablename || '_pkey' )
|| ' PRIMARY KEY("ID_TagData"),
 CHECK ( to_char("F_Date", ''YYYY-MM'') >= ' || quote_literal (
    _month )
|| '
 AND to_char("F_Date", ''YYYY-MM'') < ' || quote_literal (
    _enddate )
|| '
 )
 ) INHERITS ("SC_Tag"."T_TagData")';
-- TABLE permissions are NOT inherited FROM the parent.
-- IF permissions CHANGE ON the master be sure TO CHANGE them ON the child ALSO.
--EXECUTE 'ALTER TABLE "SC_Tag".' || quote_ident(_tablename) || ' OWNER TO postgres';
--EXECUTE 'GRANT ALL ON TABLE "SC_Tag".' || quote_ident(_tablename) || ' TO my_role';
-- INDEXES are defined per child, so we assign a DEFAULT INDEX that uses the PARTITION COLUMNS
EXECUTE 'CREATE UNIQUE INDEX ' || quote_ident (
    _tablename || '_indx1' )
|| ' ON "SC_Tag".' || quote_ident (
    _tablename )
|| ' ("F_Date", "ID_TagData")';
END IF;
DELETE
FROM
    "SC_Tag"."T_TagData"
WHERE
    "ID_TagData" = _id;
-- INSERT the CURRENT record INTO the correct PARTITION, which we are sure will now exist.
EXECUTE 'INSERT INTO "SC_Tag".' || quote_ident (
    _tablename )
|| ' VALUES ($1.*)' USING NEW;
RETURN NULL;
END;
$body$ LANGUAGE 'plpgsql' VOLATILE CALLED ON NULL INPUT SECURITY INVOKER COST 100;

на гите https://gist.github.com/des1roer/12f93997d73024ffae5a

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.