PostgreSQL で複数のテーブルの所有者を変更する方法です。
Ubuntu 21.10 で確認しました。
ライブラリーのインストール
sudo apt install python3-dotenv
.env
user='******'
password='******'
data_base='******'
change_owner.py
#! /usr/bin/python3
# -*- coding: utf-8 -*-
#
# change_owner.py
# Nov/20/2021
#
# --------------------------------------------------------
import os
import sys
import psycopg2
import psycopg2.extras
from dotenv import load_dotenv
#
# --------------------------------------------------------
def display_tables_proc(cursor):
sql_str="select schemaname, tablename, tableowner from pg_tables where schemaname='public' order by tablename"
cursor.execute (sql_str)
rows = cursor.fetchall ()
for row in rows:
print(row['tablename'],row['tableowner'])
#
# --------------------------------------------------------
sys.stderr.write ("*** 開始 ***\n")
dotenv_path = '.env'
load_dotenv(dotenv_path)
USER=os.environ.get("user")
PASSWORD=os.environ.get("user")
DATA_BASE=os.environ.get("data_base")
#
conn = psycopg2.connect("dbname=" + DATA_BASE + " user=" + USER + " password=" + PASSWORD)
cursor = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
#
sql_str="select schemaname, tablename, tableowner from pg_tables where schemaname='public' order by tablename"
cursor.execute (sql_str)
rows = cursor.fetchall ()
owner_new = "scott"
for row in rows:
# print(row)
print(row['tablename'],row['tableowner'])
tablename = row['tablename']
sql_str = "alter table " + tablename + " owner to " + owner_new
print(sql_str)
cursor.execute (sql_str)
conn.commit ()
#
display_tables_proc(cursor)
cursor.close()
conn.close()
#
sys.stderr.write ("*** 終了 ***\n")
#
# --------------------------------------------------------