0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

PostgreSQL: テーブルの所有者を変更する (Python3)

Posted at

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")
#
# --------------------------------------------------------
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?