小编典典

如何确保在要替换的表上进行同步DDL操作?

sql

我有多个进程正在Redshift中不断刷新数据。他们开始一个事务,创建一个新表,COPY将来自S3的所有数据放入新表中,然后删除旧表并将新表重命名为旧表。

伪代码:

start transaction;
create table foo_temp;
copy into foo_temp from S3;
drop table foo;
rename table foo_temp to foo;
commit;

我用这种方式更新了几十个表。这很好用,但我想让多个进程执行这些表更新以达到冗余目的,并确保数据相当新鲜(不同的进程可以同时更新不同表的数据)。

除非一个进程尝试刷新另一个进程正在处理的表,否则它将正常工作。在这种情况下,第二个进程会被第一个进程阻塞,直到它提交为止,而在提交时,第二个进程则会收到错误消息:

错误:并发事务删除了表12345

我是否可以通过一种简单的方法来保证只有一个进程正在刷新表,以使第二个进程不会进入这种情况?

我考虑为每个真实表创建一个特殊的锁定表。在处理LOCK伴随实表之前,该过程将使用特殊锁表。我认为可以,但是我想避免为每个表创建一个特殊的锁定表。


阅读 286

收藏
2021-04-22

共1个答案

小编典典

您需要通过以下方式保护读者,防止其掉落:

  • begin transaction
  • rename main table to old_main_table
  • rename tmp table to main table
  • commit
  • drop table old_main_table
    Conn #1         Conn #2
    --------------  ------------------------------------------
                    > create table bar (id int,id2 int,id3 int);
                    CREATE TABLE
    > begin;
    BEGIN
                    > begin;
                    BEGIN
                    > alter table bar rename to bar2;
                    ALTER TABLE
    > select * from bar;  
                    > create table bar (id int,id2 int,id3 int,id4 int);
                    CREATE TABLE
                    > commit; drop table bar2;
                    COMMIT
    id | id2 | id3 
    ----+-----+-----
    (0 rows)
    > commit;
    COMMIT
                    DROP TABLE
2021-04-22