首页 > 解决方案 > 使用 COPY 的 PostgresSQLfile 权限错误

问题描述

我正在使用 python 将 csv 数据转储到使用 Psycopg2 的数据库中。我需要授予 Postgres 对特定文件路径的权限才能使用 COPY 命令(文档:https ://www.postgresql.org/docs/10/static/sql-copy.html )。我需要授予特定目录路径路由和文件的权限,以避免出现以下错误:

COPY database.table_name FROM '/home/development_user/Documents/App/CSV/filename.csv' delimiter ',' csv header

ERROR:  could not open file "/home/development_user/Documents/App/CSV/filename.csv" for reading: Permission denied

为了简化事情,想将 postgres 添加到开发用户组。这样,postgres 应该具有开发用户可以轻松地逐个路径定义的组读取权限。我使用以下命令将 postgres 用户添加到 development_user 组并验证它是成功的:

$ sudo usermod -a -G development_user postgres
$ groups postgres
postgres : postgres development_user

这是使用 namei -l [path] 命令的权限路径跟踪的输出

$ namei -l /home/development_user/Documents/App/CSV/filename.csv
drwxr-xr-x root        root        /
drwxr-xr-x root        root        home
drwxr-x--- development_user development_user development_user
drwxr-xr-x development_user development_user Documents
drwxr-xr-x development_user development_user App
drwxrwxr-x development_user development_user CSV
-rw-rw-r-- development_user development_user filename.csv

如您所见,组中的任何人development_user现在都应该对路径中的所有目录具有读取 ( r) 和执行 ( x) 权限,并对最终文件具有读取和写入权限。如果 postgres 试图以用户身份访问同一个文件other,postgres 将受到development_user目录访问能力的限制。

但是,当我尝试访问该文件时,会出现上述权限错误。当我打开development_user具有读取和执行权限的目录时,other例如下面的命令,我能够读取文件是 Postgres:

$ chmod o+rx /home/development

但是,我不想授予otherdevelopment_user 主目录的读取和执行权限,而且我不明白为什么 postgres 用户无法使用上述组权限来访问同一文件,因为我将 postgres 添加到 development_user 帐户.

如果我通过将文件添加到用户组来授予 postgres 读取文件权限的方法是可行的策略,有什么想法吗?我不想使用其他解决方案,例如此处提到的:(PostgreSQL - 不一致的 COPY 权限错误)或此处(Postgres 错误:无法打开文件以读取:权限被拒绝)建议通过将文件所有者设置为 postgres 来打开权限:postgres。或广泛开放目录权限,例如允许所有用户在开发主目录上读取和执行。我也不想在系统目录中创建另一个目录并被迫按照此处的建议将文件保存在那里:(psql 错误:无法打开文件“address.csv”进行阅读:没有这样的文件或目录)。

标签: pythonpostgresqlcsvpsycopg2

解决方案


@jonnyjandles 的回答略有不同,因为这显示了一个谜self._cursor——更典型的调用可能是:

copy_command = f"COPY table_name FROM STDIN CSV HEADER;"
with connection.cursor() as cursor:
    cursor.copy_expert(copy_command, open(some_file_path, "r"))

推荐阅读