Postgres 运行 数据维护 'scripts' 可以吗?

Can Postgres run data maintenance 'scripts'?

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

我需要使用 pgplsql 函数为新 table 创建数据。

因为每个函数都是一个事务,所以我假设用一个函数调用来做这件事是行不通的。

我正在考虑做的是:

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

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

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

您还有其他建议吗?

谢谢你的想法!

另一种选择是使用 Powershell 重复调用使用 psql 的函数。

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

逻辑上函数是这样工作的:

  • 创建一个 table(如果它不存在)并用控制函数调用次数的元数据填充它

  • 读取控件table以确定是否还有剩余工作,如果没有剩余工作return 0

  • 如果还有工作,做一个批处理,更新控件 table 和 return 1

这是脚本和函数签名:

PowerShell 脚本:

Clear-Host;
Set-Location 'C:\Program Files\PostgreSQL\bin\';
$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
*/