This answer is only for Linux Beginners.
Assuming initially the DB user didn’t have file/folder(directory) permission on the client side.
Let’s constrain ourselves to the following:
User: postgres
Purpose: You wanted to (write to / read from) a specific folder
Tool: psql
Connected to a specific database: YES
FILE_PATH: /home/user/training/sql/csv_example.csv
Query: \copy (SELECT * FROM table_name TO FILE_PATH, DELIMITER ',' CSV HEADER;
Actual Results: After running the query you got an error : Permission Denied
Expected Results: COPY COUNT_OF_ROWS_COPIED
Here are the steps I’d follow to try and resolve it.
- Confirm the FILE_PATH permissions on your File system.
Inside a terminal to view the permissions for a file/folder you need to long list them by entering the command ls -l
.
The output has a section that shows sth like this -> drwxrwxr-x
Which is interpreted in the following way:
TYPE | OWNER RIGHTS | GROUP RIGHTS | USER RIGHTS
rwx
(r: Read, W: Write, X: Execute)
TYPE (1 Char) = d: directory, -: file
OWNER RIGHTS (3 Chars after TYPE)
GROUP RIGHTS (3 Chars after OWNER)
USER RIGHTS (3 Chars after GROUP)
- If permissions are not enough (Ensure that a user can at least enter all folders in the path you wanted path) —
x
.
This means for FILE_PATH, All the directories (home , user, training, sql) should have at least an x
in the USER RIGHTS.
- Change permissions for all parent folders that you need to enter to have a
x
. You can usechmod rights_you_want parent_folder
Assuming /training/
didn’t have an execute permission.
I’d go the user folder and enter chmod a+x training
- Change the destination folder/directory to have a
w
if you want to write to it. or at least ar
if you want to read from it
Assuming /sql
didn’t have a write permission.
I would now chmod a+w sql
- Restart the postgresql server
sudo systemctl restart postgresql
- Try again.
This would most probably help you now get a successful expected result.
This answer is only for Linux Beginners.
Assuming initially the DB user didn’t have file/folder(directory) permission on the client side.
Let’s constrain ourselves to the following:
User: postgres
Purpose: You wanted to (write to / read from) a specific folder
Tool: psql
Connected to a specific database: YES
FILE_PATH: /home/user/training/sql/csv_example.csv
Query: copy (SELECT * FROM table_name TO FILE_PATH, DELIMITER ',' CSV HEADER;
Actual Results: After running the query you got an error : Permission Denied
Expected Results: COPY COUNT_OF_ROWS_COPIED
Here are the steps I’d follow to try and resolve it.
- Confirm the FILE_PATH permissions on your File system.
Inside a terminal to view the permissions for a file/folder you need to long list them by entering the command ls -l
.
The output has a section that shows sth like this -> drwxrwxr-x
Which is interpreted in the following way:
TYPE | OWNER RIGHTS | GROUP RIGHTS | USER RIGHTS
rwx
(r: Read, W: Write, X: Execute)
TYPE (1 Char) = d: directory, -: file
OWNER RIGHTS (3 Chars after TYPE)
GROUP RIGHTS (3 Chars after OWNER)
USER RIGHTS (3 Chars after GROUP)
- If permissions are not enough (Ensure that a user can at least enter all folders in the path you wanted path) —
x
.
This means for FILE_PATH, All the directories (home , user, training, sql) should have at least an x
in the USER RIGHTS.
- Change permissions for all parent folders that you need to enter to have a
x
. You can usechmod rights_you_want parent_folder
Assuming /training/
didn’t have an execute permission.
I’d go the user folder and enter chmod a+x training
- Change the destination folder/directory to have a
w
if you want to write to it. or at least ar
if you want to read from it
Assuming /sql
didn’t have a write permission.
I would now chmod a+w sql
- Restart the postgresql server
sudo systemctl restart postgresql
- Try again.
This would most probably help you now get a successful expected result.
>>Если это текстовый дамп — то надо с помощью psql -f. Если бинарный — с помощью pg_restore.
Совсем необязательно. Запрос прекрасно выполняется из pgAdmin или через нужные библиотеки (psycopg2, jdbc и т.д.) при соблюдении трех важных условий.
1.
Надо понимать, что путь к файлу, который указан после from — это путь на сервере posgress, а не на той машине, с которой вы запускаете запрос. Поэтому файл *.csv должен физически находится на сервере posgress.
2.
К файлу должен быть доступ у процесса posgress. Поэтому, например, для Windows плохая идея располагать *.csv на диске C.
3.
Строго соблюсти формат разделителей *.csv, который поймет posgress. Чтобы не гадать — сделайте сначала выгрузку из таблицы командой copy tableName to 'csv_file_path'
Компьютер: Mac OS X, версия 10.8
База данных: Postgres
Попытка импортировать файл csv в postgres.
pg> copy items_ordered from '/users/darchcruise/desktop/items_ordered.csv' with CSV;
ERROR: could not open file "/users/darchcruise/desktop/items_ordered.csv" for reading: Permission denied
Затем я попробовал
$> chown postgres /users/darchcruise/desktop/items_ordered.csv
chown: /users/darchcruise/desktop/items_ordered.csv: Operation not permitted
Наконец, я попробовал
$> ls -l
-rw-r--r-- 1 darchcruise staff 1016 Oct 18 21:04 items_ordered.csv
Любая помощь очень ценится!
Ответ 1
chmod a+rX /users/darchcruise/ /users/darchcruise/desktop /users/darchcruise/desktop/items_ordered.csv
Это изменит права доступа для вашей папки. Обратите внимание, что каждый сможет прочитать ваш файл.
Вы не можете использовать chown, являющийся пользователем без административных прав.
Также рассмотрите возможность обучения umask, чтобы облегчить создание общих файлов.
Ответ 2
Предполагая инструмент командной строки psql
, вы можете использовать copy
вместо copy
.
copy
открывает файл и передает содержимое на сервер, тогда как copy
указывает серверу открыть сам файл и прочитать его, что может быть проблематичным по разрешению или даже невозможно, если клиент и сервер работают на разные машины без совместного использования файлов.
Под капотом copy
реализуется как COPY FROM stdin
и принимает те же параметры, что и серверная сторона copy
.
Ответ 3
Скопируйте файл CSV в /tmp
Для меня это решило проблему.
Ответ 4
Скопируйте файл CSV в папку /tmp
Файлы, названные в команде COPY, считываются или записываются непосредственно сервером, а не клиентским приложением. Следовательно, они должны находиться на сервере базы данных или быть доступны только ему, а не клиенту. Они должны быть доступны для чтения и записи пользователю PostgreSQL (идентификатор пользователя, на котором выполняется сервер), а не клиенту. КОПИРОВАНИЕ Именование файла разрешено только для суперпользователей баз данных, поскольку оно позволяет читать или записывать любые файлы, на которые у сервера есть права доступа.
Ответ 5
У меня возникла проблема, когда я пытался экспортировать данные с удаленного сервера на локальный диск. Я не понял, что SQL copy
на самом деле выполняется на сервере и что он пытается записать в папку сервера. Вместо этого правильная вещь — использовать copy
, которая является командой psql, и она записывает в локальную файловую систему, как я ожидал. http://www.postgresql.org/message-id/[email protected]om
Возможно, это может быть полезно и для кого-то другого.
Ответ 6
Другой способ сделать это, если у вас есть pgAdmin и удобнее использовать графический интерфейс, — это перейти к таблице в схеме и щелкнуть правой кнопкой мыши по таблице, в которую вы хотите импортировать файл, и выбрать «Импорт» для просмотра вашего компьютера для файл, выберите тип вашего файла, столбцы, в которые вы хотите вставить данные, а затем выберите импорт.
Это было сделано с использованием pgAdmin III и версии PostgreSQL версии 9.4
Ответ 7
Для меня было просто добавить sudo (или запустить как root) для команды chown:
sudo chown postgres/users/darchcruise/desktop/items_ordered.csv
Ответ 8
Я решил ту же проблему с помощью рекурсивного chown для родительской папки:
sudo chown -R postgres:postgres /home/my_user/export_folder
(мой экспорт находится в /home/my_user/export_folder/export_1.csv
)
Ответ 9
просто на случай, если вы столкнетесь с этой проблемой под Windows 10, добавьте группу пользователей «youcomputerUsers» на вкладке безопасности и предоставьте ей полный контроль, что решило мою проблему
Ответ 10
для MacBook сначала я открыл терминал, а затем введите
open /tmp
или в каталоге поиска вы напрямую вводите команду + shift + g, затем набираете /tmp и переходите в папку.
он открывает временную папку в Finder. Затем я вставляю скопированный файл CSV в эту папку. Затем я снова захожу в терминал postgres и набираю команду ниже, а затем она копирует мои данные CSV в таблицу БД.
copy recharge_operator FROM '/private/tmp/operator.csv' DELIMITER ',' CSV;
Ответ 11
Мой случай:
Я сохраняю свой csv
файл в каталог моего хоста. Например: /tmp/geo.csv
.
Но я забыл смонтировать этот том хоста в докер-контейнер, поэтому команда COPY
команды pg
выдает ошибку: No such a file and directory
.
Команда COPY
/tmp/geo.csv
в контейнере /tmp/geo.csv
, но она не существует.
Ответ 12
У меня было то же сообщение об ошибке, но я использовал psycopg2
для связи с PostgreSQL. Я исправил проблемы с разрешениями, используя функции copy_from
и copy_expert
, которые открывают файл на стороне клиента как пользователь, выполняющий скрипт python, и передают данные в базу данных через STDIN
.
Обратитесь к этой ссылке для получения дополнительной информации.
Ответ 13
Вы должны предоставить пользователю разрешение pg_read_server_files
, если вы не используете postgres
superuser
.
Пример:
GRANT pg_read_server_files TO my_user WITH ADMIN OPTION;
Ответ 14
Может быть, вы используете pgadmin, подключая удаленный хост, а затем U пытаетесь обновить его из вашей системы, но он ищет этот файл в удаленной системной файловой системе… его ошибка, с которой я столкнулся, может быть ее также для проверки u это
Этот ответ предназначен только для начинающих пользователей Linux.
Предполагая, что изначально у пользователя БД не было разрешения на файл / папку (каталог) на стороне клиента.
Ограничимся следующим:
Пользователь: postgres
Цель: вы хотели (писать в / читать) конкретную папку
Орудие труда: psql
Подключено к конкретной базе данных: YES
ПУТЬ К ФАЙЛУ: /home/user/training/sql/csv_example.csv
Запрос: copy (SELECT * FROM table_name TO FILE_PATH, DELIMITER ',' CSV HEADER;
Фактические результаты: после выполнения запроса вы получили сообщение об ошибке: Permission Denied
Ожидаемые результаты: COPY COUNT_OF_ROWS_COPIED
Вот шаги, которые я предпринял, чтобы попытаться решить эту проблему.
- Подтвердите разрешения FILE_PATH в вашей файловой системе.
Внутри терминала, чтобы просмотреть разрешения для файла / папки, вам необходимо их длинный список, введя команду ls -l
.
На выходе есть раздел, который показывает что-то вроде этого -> drwxrwxr-x
Что интерпретируется следующим образом:
ТИП | ПРАВА ВЛАДЕЛЬЦА | ПРАВА ГРУППЫ | ПРАВА ПОЛЬЗОВАТЕЛЯ
rwx
(r: чтение, W: запись, X: выполнение)
ТИП (1 символ) = d: каталог, -: файл
ПРАВА ВЛАДЕЛЬЦА (3 символа после ТИПА)
ПРАВА ГРУППЫ (3 символа после ВЛАДЕЛЬЦА)
ПРАВА ПОЛЬЗОВАТЕЛЯ (3 символа после ГРУППЫ)
- Если разрешений недостаточно (убедитесь, что пользователь может, по крайней мере, ввести все папки по указанному вами пути) —
x
.
Это означает, что для FILE_PATH все каталоги (домашний, пользовательский, обучающий, sql) должны иметь как минимум x
в ПРАВАХ ПОЛЬЗОВАТЕЛЯ.
- Измените разрешения для всех родительских папок, которые вам нужно ввести, чтобы иметь
x
. Вы можете использоватьchmod rights_you_want parent_folder
Предполагая /training/
не было разрешения на выполнение.
Я бы пошел в папку пользователя и ввел chmod a+x training
- Измените папку / каталог назначения, чтобы
w
если вы хотите написать ему. или по крайней мереr
если ты хочешь читать оттуда
Предполагая /sql
не было разрешения на запись.
Я бы сейчас chmod a+w sql
- Перезагрузите сервер postgresql
sudo systemctl restart postgresql
- Попробуй снова.
Скорее всего, это поможет вам получить ожидаемый результат.
#postgresql
Вопрос:
14:57:24,484 WARN [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] (bus [5]) SQL Error: 0, SQLState: 42501
14:57:24,484 ERROR [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] (bus [5]) ERROR: could not open file "pg_tblspc/16397/PG_11_201809181/10119411/4698976": Operation not permitted
Where: parallel worker
Caused by: org.postgresql.util.PSQLException: ERROR: could not open file "pg_tblspc/16397/PG_11_201809181/10119411/4698976": Operation not permitted
Where: parallel worker
Скажите мне, что это за ошибка?
Комментарии:
1. Вызвано: org.postgresql.util. Исключение PSQLException: ОШИБКА: не удалось открыть файл «pg_tblspc/16397/PG_11_201809181/10119411/4698976»: Операция не разрешена Где: параллельный рабочий
2. Существует ли этот файл? Принадлежит ли он пользователю PostgreSQL?
3. Да, он существует и принадлежит пользователю postgres, интересно, когда он перезапустил его — проблем не было. Возможно ли, что файл был занят каким-то другим процессом?
4. Наиболее вероятным кандидатом будет антивирусная программа, особенно если вы работаете в Windows. Им никогда не следует разрешать прикасаться к каталогу данных.
5. Спасибо, антивирус установлен на хостах, возможно, проблема в этом!
Ответ №1:
Наиболее вероятным кандидатом будет антивирусная программа, особенно если вы работаете в Windows. Им никогда не следует разрешать прикасаться к каталогу данных.
The error «could not open file for reading: Permission denied» in PostgreSQL is an issue that occurs when the database server is unable to access a file it needs to read. This can be caused by a variety of reasons, including incorrect file permissions or incorrect ownership of the file. The error can prevent you from accessing the database and can cause significant downtime. In this article, we will look at some of the methods you can use to resolve this issue and restore your database to normal operation.
Method 1: Check file permissions
To fix the Postgres ERROR: could not open file for reading: Permission denied, you can check the file permissions of the file that Postgres is trying to access. Here are the steps to check file permissions using the command line:
- Open the terminal or command prompt and navigate to the directory where the file is located.
- Type
ls -l
to list the files in the directory with their permissions. - Find the file that Postgres is trying to access and check its permissions. The permissions are listed in the first column of the output. The permissions are represented by 10 characters: the first character indicates the file type, and the next three characters indicate the owner’s permissions, the next three characters indicate the group’s permissions, and the last three characters indicate everyone else’s permissions.
- If the file permissions do not allow Postgres to read the file, you can change the permissions using the
chmod
command. For example, if you want to give Postgres read permission for the file, you can typechmod +r filename
.
Here is an example of how to check and change file permissions using the command line:
$ cd /path/to/file
$ ls -l
-rw-r--r-- 1 user group 1234 Jan 1 00:00 filename
$ chmod +r filename
$ ls -l
-rw-r--r-- 1 user group 1234 Jan 1 00:00 filename
In this example, the file filename
has read permission for the owner and group, but not for everyone else. To give Postgres read permission for the file, we use the chmod
command to add read permission for everyone. After running chmod +r filename
, we can see that the file permissions have changed to -rw-r--r--
, which gives read permission for everyone.
Method 2: Change ownership of the file
To fix the Postgres ERROR: could not open file for reading: Permission denied, you can change the ownership of the file. Here are the steps to do so:
-
Find the file that is causing the error. For example, let’s say the file is located at /var/lib/postgresql/data/myfile.csv.
-
Check the current ownership of the file. You can do this by running the following command:
ls -l /var/lib/postgresql/data/myfile.csv
This will show you the current ownership of the file. For example, it may show something like this:
-rw-r--r-- 1 user user 12345 Jan 1 00:00 /var/lib/postgresql/data/myfile.csv
In this example, the file is owned by the user «user» and the group «user».
- Change the ownership of the file to the postgres user. You can do this by running the following command:
sudo chown postgres:postgres /var/lib/postgresql/data/myfile.csv
This will change the ownership of the file to the postgres user and group.
- Check the new ownership of the file. You can do this by running the same command as in step 2:
ls -l /var/lib/postgresql/data/myfile.csv
This should show the new ownership of the file. For example, it may show something like this:
-rw-r--r-- 1 postgres postgres 12345 Jan 1 00:00 /var/lib/postgresql/data/myfile.csv
In this example, the file is now owned by the postgres user and group.
- Try to access the file again. You should now be able to access the file without getting the «Permission denied» error.
That’s it! By changing the ownership of the file to the postgres user, you should be able to access it without any issues.
Method 3: Restart the PostgreSQL service
To fix the «Postgresql: how to fix Postgres ERROR: could not open file for reading: Permission denied?» error by restarting the PostgreSQL service, follow the steps below:
- First, stop the PostgreSQL service by running the following command:
sudo systemctl stop postgresql
- Then, change the ownership of the PostgreSQL data directory to the PostgreSQL user by running the following command:
sudo chown -R postgres:postgres /var/lib/postgresql/<version>/main
Replace <version>
with the version of PostgreSQL you are using.
- Next, change the permissions of the PostgreSQL data directory to allow the PostgreSQL user to read and write to it by running the following command:
sudo chmod -R 700 /var/lib/postgresql/<version>/main
- Finally, start the PostgreSQL service by running the following command:
sudo systemctl start postgresql
This should fix the «Postgresql: how to fix Postgres ERROR: could not open file for reading: Permission denied?» error by restarting the PostgreSQL service.
Note: If you still encounter the same error after restarting the PostgreSQL service, you may need to check the file permissions of the specific file that is causing the error and adjust them accordingly.
Method 4: Use the PostgreSQL initdb tool
To fix the «Postgresql: how to fix Postgres ERROR: could not open file for reading: Permission denied?» error using the PostgreSQL initdb tool, you can follow these steps:
-
First, navigate to the directory where your PostgreSQL data files are stored.
-
Then, run the following command to initialize a new database cluster using the initdb tool:
sudo -u postgres /usr/lib/postgresql/{version}/bin/initdb -D /path/to/data/directory
Replace
{version}
with the version of PostgreSQL you are using, and/path/to/data/directory
with the path to your data directory. -
Once the database cluster has been initialized, you can start the PostgreSQL server using the following command:
sudo systemctl start postgresql
-
If you still encounter the «Permission denied» error, you may need to adjust the permissions of your data directory. You can do this using the following command:
sudo chown -R postgres:postgres /path/to/data/directory
This will change the owner and group of the data directory to
postgres
, which is the user that PostgreSQL runs as by default. -
Finally, you can try starting the PostgreSQL server again using the
systemctl
command:sudo systemctl start postgresql
If everything is configured correctly, the server should start up without any errors.
By following these steps, you should be able to fix the «Postgresql: how to fix Postgres ERROR: could not open file for reading: Permission denied?» error using the PostgreSQL initdb tool.
Этот ответ предназначен только для начинающих пользователей Linux.
Предполагая, что изначально у пользователя БД не было разрешения на файл / папку (каталог) на стороне клиента.
Ограничимся следующим:
Пользователь: postgres
Цель: вы хотели (писать в / читать) конкретную папку
Орудие труда: psql
Подключено к конкретной базе данных: YES
ПУТЬ К ФАЙЛУ: /home/user/training/sql/csv_example.csv
Запрос: \copy (SELECT * FROM table_name TO FILE_PATH, DELIMITER ',' CSV HEADER;
Фактические результаты: после выполнения запроса вы получили сообщение об ошибке: Permission Denied
Ожидаемые результаты: COPY COUNT_OF_ROWS_COPIED
Вот шаги, которые я предпринял, чтобы попытаться решить эту проблему.
- Подтвердите разрешения FILE_PATH в вашей файловой системе.
Внутри терминала, чтобы просмотреть разрешения для файла / папки, вам необходимо их длинный список, введя команду ls -l
.
На выходе есть раздел, который показывает что-то вроде этого -> drwxrwxr-x
Что интерпретируется следующим образом:
ТИП | ПРАВА ВЛАДЕЛЬЦА | ПРАВА ГРУППЫ | ПРАВА ПОЛЬЗОВАТЕЛЯ
rwx
(r: чтение, W: запись, X: выполнение)
ТИП (1 символ) = d: каталог, -: файл
ПРАВА ВЛАДЕЛЬЦА (3 символа после ТИПА)
ПРАВА ГРУППЫ (3 символа после ВЛАДЕЛЬЦА)
ПРАВА ПОЛЬЗОВАТЕЛЯ (3 символа после ГРУППЫ)
- Если разрешений недостаточно (убедитесь, что пользователь может, по крайней мере, ввести все папки по указанному вами пути) —
x
.
Это означает, что для FILE_PATH все каталоги (домашний, пользовательский, обучающий, sql) должны иметь как минимум x
в ПРАВАХ ПОЛЬЗОВАТЕЛЯ.
- Измените разрешения для всех родительских папок, которые вам нужно ввести, чтобы иметь
x
. Вы можете использоватьchmod rights_you_want parent_folder
Предполагая /training/
не было разрешения на выполнение.
Я бы пошел в папку пользователя и ввел chmod a+x training
- Измените папку / каталог назначения, чтобы
w
если вы хотите написать ему. или по крайней мереr
если ты хочешь читать оттуда
Предполагая /sql
не было разрешения на запись.
Я бы сейчас chmod a+w sql
- Перезагрузите сервер postgresql
sudo systemctl restart postgresql
- Попробуй снова.
Скорее всего, это поможет вам получить ожидаемый результат.
MurCode
- Форумы
- Поиск
- О проекте
Warlock86
Дата: 06.10.2020 15:32:23
При попытке выполнить следующую команду:
copy schema1.table1 from 'C:\dir1\Файл 123.csv' with (format csv,encoding 'UTF8');
вернуло ошибку:
ОШИБКА: не удалось открыть файл "C:\dir1\Файл 123.csv" для чтения: No such file or directory ПОДСКАЗКА: COPY FROM указывает серверному процессу PostgreSQL прочитать данные из файла. Возможно, на самом деле вам нужно клиентское средство, например, \copy в psql.
При этом файлы, в названии которых нет кириллицы, загружаются без проблем. Есть список из нескольких сотен файлов, у многих из которых наименование содержит кириллицу. На основе списка были сформированы команды copy для выполнения их в psql. Есть ли более простой, чем переименование всех файлов, содержащих кириллицу, способ заставить PostgreSQL обработать эти файлы?
Guzya
Дата: 06.10.2020 16:36:42
Попробуйте убрать пробел в названии файла.
Warlock86
Дата: 06.10.2020 17:05:11
Guzya, не помогло. Ошибка прежняя. Более того, если в имени файла есть пробел, но нет кириллицы, он благополучно загружается.
env
Дата: 06.10.2020 17:25:01
Warlock86,
Сделайте copy to и посмотрите в какой кодировке будет имя файла
упд. проблема в разнице кодовых страниц БД и ОС, довольно старая
Warlock86
Дата: 06.10.2020 19:05:38
env | ↑ |
---|---|
Warlock86,
Сделайте copy to и посмотрите в какой кодировке будет имя файла упд. проблема в разнице кодовых страниц БД и ОС, довольно старая |
После выполнения этой команды:
copy schema1.table1 to 'C:\dir1\Файл 123.csv' delimiter ',' csv header encoding 'UTF8';
Данные выгрузились в файл под названием «Р¤Р°Р№Р» 123.csv».
По вашей ссылке не нашёл информации как решить эту проблему.
fte
Дата: 06.10.2020 19:14:14
Warlock86,
а так ?
copy schema1.table1 to E'C:\dir1\Файл 123.csv' delimiter ',' csv header encoding 'UTF8';
Warlock86
Дата: 06.10.2020 19:28:54
fte | ↑ |
---|---|
Warlock86, а так ? copy schema1.table1 to E'C:\dir1\Файл 123.csv' delimiter ',' csv header encoding 'UTF8'; |
ОШИБКА: при выполнении COPY в файл нельзя указывать относительный путь
UPD: Сделал вот так:
copy schema1.table1 to E'C:\\dir1\\Файл 123.csv' delimiter ',' csv header encoding 'UTF8';
Выгрузило как и прежде в файл «Р¤Р°Р№Р» 123.csv».
НеофитSQL
Дата: 06.10.2020 20:03:41
Warlock86,
«рырыры» говорит о том, что строчка была в UTF-8, a была прочитана как однобайтная кодировка Win1251.
Варианты:
— конвертнуть вашу мультибайтную строку UTF-8 в однобайтную кодировку командного скрипта (1251)
— или настроить исполнителя скрипта на понимание UTF-8 — для cmd.exe это делается через «chcp 65001». У винды в поддержке этой кодировке есть баги, на которые вы можете и не наступить.
— или копировать средствами (библиотечная функция?), где не приходится заботиться о совпадении кодировок.
env
Дата: 07.10.2020 12:36:01
Warlock86,
Собственно там про это и сказано. copy ожидает совпадения кодировки бд и ос. Это не лечится на текущий момент.
Ну а через psql вы и сами справились.
з.ы. можете конечно попробовать заранее сконвертировать имена файлов в «обратные кракозяблы», чтобы перекодировка в copy дала на выходе нужное имя, и попробовать с ними.
fte
Дата: 07.10.2020 14:42:12
Warlock86,
Попробуте так
copy schema1.table1 to convert_to('C:\dir1\Файл 123.csv','CP1251') with (delimiter ',' csv header encoding 'UTF8');