我想使用bash脚本将数据库的所有权从postgres更改为其他用户。
我通过stackoverflow中的链接找到了以下命令:
$result = str_replace('function ()', 'function []', '( ( function () (');
我使用以下函数调用该命令:
# Change owner of tables and views.
for tbl in $(pgexec "SELECT table_name FROM information_schema.tables WHERE table_schema='$schema';" $database) \
$(pgexec "SELECT table_name FROM information_schema.views WHERE table_schema='$schema';" $database)
do
pgexec "ALTER TABLE \"$schema\".\"$tbl\" OWNER TO $role;" $database
done
我收到以下错误:
function pgexec() {
local cmd=$1
local database=$2
sudo -u postgres psql -d $database --record-separator=\0 -c $cmd
我使用其他多个SQL查询测试了 relation public.table_name doesn't exist
,并且可以正常工作。
答案 0 :(得分:1)
首先,表{strong>和的视图在information_schema.tables
中列出,因此,由于您也在查询information_schema.views
,因此将视图更改为两次 >
您无需借助shell即可轻松地在SQL中实现此目标(执行时除外)。像这样:
/* Create a function as you would likely reuse this action */
CREATE OR REPLACE FUNCTION public.set_owner (in_schema TEXT, in_role TEXT)
RETURNS VOID
AS $$
DECLARE object_name TEXT;
BEGIN
FOR object_name IN (
SELECT
table_schema || '.' || table_name AS object_name
FROM
information_schema.tables
WHERE
schema = in_schema
)
LOOP
EXECUTE FORMAT('ALTER TABLE %s OWNER TO %s', object_name, in_role);
END LOOP;
END;
$$ LANGUAGE PLPGSQL VOLATILE;
像SELECT public.set_owner('public', 'tbl_owner');