Postgres可以运行数据维护"脚本"吗?



在我们的Aurora RDS Postgres生产数据库中,我需要使用20亿行源表中的数据创建一个新表。

我需要使用pgplsql函数来创建新表的数据。

由于每个函数都是一个事务,我认为用一个函数调用这样做是行不通的。

我正在考虑做的是:

  1. 创建一个函数,该函数将创建并插入一小批数据
  2. 使用java服务或lambda重复调用函数,直到所有创建数据
    -不幸的是,使用pg_cron不是一个选项,因为Aurora Postgres不支持它

创建java服务或lambda(或任何其他只调用函数的东西(是我想避免的事情。

对于我们的MS SQL数据库,我们只需从SSMS运行一个脚本,该脚本将在循环中以小批量创建和提交数据。类似的东西在Postgres中似乎不是一个选项。

你还有其他选择吗?

谢谢你的想法!

另一个选项是使用Powershell使用psql重复调用函数。

我创建了一个postgres函数,该函数返回一个状态id,该id告诉调用者它是否已完成。它总是返回一条状态消息,以便跟踪功能的进度。

从逻辑上讲,该功能的工作方式如下:

  • 创建一个表(如果它不存在(,并用元数据填充它,该元数据控制函数应被调用的次数

  • 读取控制表以确定是否有剩余工作,如果没有剩余工作,则返回0

  • 如果还有剩余的工作,则进行批量处理,更新控制表并返回1个

这是脚本和函数签名:

PowerShell脚本:

Clear-Host;
Set-Location 'C:Program FilesPostgreSQL10bin';
$status_id = 1;
$env:PGPASSWORD = 'password';
While ($status_id -eq 1) {
# call the function
$results = & .psql --% -h end-point.rds.amazonaws.com -p 5432 -U postgres -d dbname-t -q -c "select o_status_id, o_status from maint.maintainence_function();"
# split the return value that contains a status id and an array of messages
$status_id, $status = $results.split("|",2)
# trim the status id so -eq can properly evaluate it
$status_id = $status_id.Trim()
# remove the double quote and curly braces from the array of messages.  The array of one or more messages is returned as a string in this standard postgres format:
# {"07/18/2018 11:07:01: Message 1"}
# {"07/18/2018 11:07:01: Message 1","07/18/2018 11:07:01: Message 2"}
$status = $status.Replace('"','');
$status = $status.Replace("}","");
$status = $status.Replace("{","");
$status = $status.Trim();
# split the messages and output to console
$status.Split(",");
Start-Sleep -Seconds 2;
}

Postgres函数签名:

CREATE OR REPLACE FUNCTION maint.maintainence_function (
OUT o_status_id SMALLINT,
OUT o_status VARCHAR(300)[]
)
RETURNS RECORD
AS $$
/*
RETURNS
o_status_id
0: SUCCESS: Function called successfully, all work is completed.  Service should NOT call function again.
1: IN PROGRESS: Function called successfully, all work is NOT completed.  Service should call function again.
2: Failed: Function called failed.  Service should NOT call function again.
o_status
Array of progress messages to be displayed in console
*/

最新更新