PostgreSQL is a widely used relational database that supports various CLI and GUI tools. These tools assist us in managing and manipulating databases efficiently. The traditional way of working with Postgres is using a CLI tool.
SQL Shell aka “psql” is an interactive command line tool that helps us access PostgreSQL via the terminal. However, while accessing Postgres via psql, you may encounter the “psql command not found error”. The stated error arises because of various reasons.
This blog post will present a detailed guide on how to resolve the psql command not found error using one of the following fixes:
— Install Postgres
— Set Environment Variable
How to Fix psql Command Not Found Error in Postgres?
In PostgreSQL, the “psql command not found” error or the “psql” is not recognized as an internal or external command arises because of the following reasons:
— Postgres is not installed on the Machine.
— The Path for Postgres tools is not set on our system.
The stated error can be fixed either by installing PostgreSQL or by setting the environment variable for the Postgres tools.
Solution 1: Download and Install Postgres
The very first reason that causes this error is Postgres is not installed on the system. In that case, installing Postgres will rectify the stated problem.
Solution 2: Set Environment Variable
The primary reason which leads to the command not found error is that the path for the Postgres tools is not set on the system. In such a case, you can enforce one of the following solutions:
— Set Path Using Command Prompt
— Set Path Using Edit System Environment Variables
Setting Path Using Command Prompt
Open the windows search menu by pressing the “🪟 + S” button. Search CMD, and launch it as an administrator. Once the CMD terminal is open, execute the “setx” command to set the path for the Postgres tools using CMD:
setx /M path "%PATH%;C:\Program Files\PostgreSQL\15\bin"
In this command:
— “/M” is used to set the variable at the SYSTEM level/scope.
— “15” represents the Postgres version installed on our system. You must replace the with the Postgres version installed on your OS:
The Postgres bin directory’s path has been set successfully. For confirmation, you can re-launch the CMD and type any psql command:
The Postgres version confirms that the stated error has been rectified.
Setting Path Using Edit System Environment Variables
Open the “Edit the System Environment Variables” settings from the Windows search menu:
Click on the “Environment variables…” button to launch the system properties:
Select the path variable available under the system variables and hit the “Edit” button:
Now, copy the “bin directory’s path”, click on the “New” button, and paste the copied path here:
Click on the “OK” button to add the path to the “Edit Environment Variables” window. Next, hit the “OK” button to close the “Environment Variables” Window:
Next, close the “System Properties” Window by clicking on the “OK” button:
Setting the path for the Postgres tools will fix the «psql command not found» error.
Conclusion
In PostgreSQL, the “psql command not found” or “psql is not recognized as an internal or external command” error arises if Postgres is not installed or the path for Postgres tools is not set on your system. Installing Postgres or setting up the environment for Postgres will fix this error. This post explained a couple of solutions to fix the “psql command not found error” in PostgreSQL.
How to Fix «psql Command Not Found» Error in PostgreSQL
Troubleshooting «psql Command Not Found» Error
The «psql: command not found» error occurs when the PostgreSQL command-line tool psql isn’t recognized by the system. This usually means PostgreSQL isn’t installed or the psql executable isn’t in the system’s PATH. Here, we’ll walk through the causes of this error and the steps to resolve it.
Common Causes and Solutions for «psql: command not found»:
1. PostgreSQL Not Installed
- If PostgreSQL isn’t installed, your system won’t have psql. Install it using your OS’s package manager.
Linux Example:
Code:
# For Debian-based systems (like Ubuntu)
sudo apt update
sudo apt install postgresql postgresql-contrib
# For Red Hat-based systems (like CentOS)
sudo yum install postgresql postgresql-server
MacOS:
Code:
brew install postgresql
2. psql Not Added to PATH
- Even if PostgreSQL is installed, psql might not be in the system’s PATH. You can add it manually.
Linux/MacOS:
Code:
# Add PostgreSQL's bin directory to PATH
export PATH=/usr/pgsql-x.y/bin:$PATH # Replace x.y with your PostgreSQL version
# To make it permanent, add it to ~/.bashrc or ~/.zshrc
echo "export PATH=/usr/pgsql-x.y/bin:$PATH" >> ~/.bashrc
source ~/.bashrc
Windows:
1. Find the PostgreSQL installation directory (usually C:\Program Files\PostgreSQL\version\bin).
2. Add this path to the system PATH:
- Go to Control Panel > System > Advanced system settings > Environment Variables.
- Edit the PATH variable and add the path to psql.
3. Incorrect PostgreSQL Version
- Some systems may install an incompatible version. Confirm the installed version matches the expected command syntax.
Code:
# Verify installation and version
psql --version
4. Installing Standalone psql Client
- If you only need psql and not the entire PostgreSQL server, you can install the client tools separately.
Debian/Ubuntu:
Code:
sudo apt install postgresql-client
Example Commands After psql is Set Up
Once psql is set up correctly, you can connect to your PostgreSQL database with:
Code:
# Connect to the default PostgreSQL database
psql -U postgres
For remote connections:
Code:
psql -h remote_host -U username -d database_name
Additional Tips:
- Check PostgreSQL Service: Ensure the PostgreSQL service is running, as psql needs it to connect.
- Database Connection Test: Once psql is working, test your database connection to verify the setup.
Summary:
The «psql: command not found» error is typically due to PostgreSQL not being installed or psql not being in the PATH. By following the steps above, you can ensure psql is properly set up, allowing you to access your PostgreSQL databases seamlessly.
All PostgreSQL Questions, Answers, and Code Snippets Collection.
Table of Contents
- Overview
- Solution 1: Verify PostgreSQL Installation
- Solution 2: Add PostgreSQL to System PATH
- Solution 3: Use Full Path to Run psql
- Solution 4: Install PostgreSQL Client Only
- Conclusion
Overview
When working with PostgreSQL on your development machine, you may encounter the error message ‘psql: command not found’. This error indicates that the PostgreSQL command-line utility psql
is either not installed or not available in the system PATH. Below, we provide several solutions to this common problem, helping you to resume your project development swiftly.
Solution 1: Verify PostgreSQL Installation
Before running psql
, ensure PostgreSQL is installed on your system since psql
is included with the PostgreSQL installation.
- Check if PostgreSQL is installed by running
postgres -V
orpsql -V
in the terminal. - If not installed, download and install the appropriate version of PostgreSQL from the official website.
The process is merely a diagnostic step to ensure the presence of the necessary software.
Solution 2: Add PostgreSQL to System PATH
If PostgreSQL is installed but the system can’t find psql
, you may need to add its bin directory to your system PATH.
- Locate the installation directory of PostgreSQL, often
/usr/local/pgsql/bin
on Unix systems orC:\Program Files\PostgreSQL\\bin
on Windows. - Add the bin directory to the system PATH variable.
- Restart the terminal and try running
psql
again.
TL;DR:
# Unix systems, add the following line to your .profile or .bashrc
export PATH="/usr/local/pgsql/bin:$PATH"
# Windows, set the PATH in Environment Variables
set PATH=C:\Program Files\PostgreSQL\\bin;%PATH%
By adding PostgreSQL to the PATH, terminal sessions can now locate the psql
command.
Solution 3: Use Full Path to Run psql
If you prefer not to alter your PATH variable, you can reference psql
directly with its full path.
- Locate the
psql
executable in your PostgreSQL bin directory. - Run
psql
using the full path in the terminal.
Below are the full paths for each system:
# Unix systems
/usr/local/pgsql/bin/psql
# Windows
"C:\Program Files\PostgreSQL\\bin\psql"
This doesn’t require any permanent changes to your system but necessitates remembering and using the full path each time.
Solution 4: Install PostgreSQL Client Only
If you only require the psql
utility and not the full PostgreSQL server, consider installing only the client tools.
- For Unix-based systems, use a package manager like
apt
orbrew
. - For Windows systems, use the graphical installer and select the client tools component.
Example:
# Unix systems
sudo apt-get install postgresql-client
Note: The command might vary depending on the Unix distribution and package manager you are using.
By installing only the client, you’re minimizing resource usage. However, this is limited by the absence of a local server, which means you can only interact with remote databases.
Conclusion
The ‘psql: command not found’ error usually arises from either a missing PostgreSQL installation or an environment configuration issue. Fixing it can be as straightforward as checking for the installation, updating the PATH, running psql
with the full path, or installing the client-only version. Each solution has its context where it is most appropriate, and choosing the right one depends on the specific development requirements and setup.
Ошибки
psql command not found
Вы хотите запустить Postgres скрипт из bash
andrey@olegovich-10:/mnt/c/Users/olegovich$ psql -h localhost -p 5432 -U andrei
но получаете эту ошибку
-bash: psql: command not found
Это значит, что путь до Postgres не прописан в $PATH
Чтобы узнать, что прописано в $PATH достаточно сделать
echo $PATH
/home/andrei/bin:/home/andrei/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/mnt/c/Program Files (x86)/Common Files/Oracle/Java/javapath_target_1128437:/mnt/c/ProgramData/Oracle/Java/javapath_target_5252250:/mnt/c/Windows/System32:/mnt/c/Windows:/mnt/c/Windows/System32/wbem:/mnt/c/Windows/System32/WindowsPowerShell/v1.0:/mnt/c/Program Files/OpenVPN/bin:/mnt/c/Program Files (x86)/Microsoft SQL Server/Client SDK/ODBC/130/Tools/Binn:/mnt/c/Program Files (x86)/Microsoft SQL Server/140/Tools/Binn:/mnt/c/Program Files (x86)/Microsoft SQL Server/140/DTS/Binn:/mnt/c/Program Files (x86)/Microsoft SQL Server/140/Tools/Binn/ManagementStudio:/mnt/c/Program Files/MiKTeX 2.9/miktex/bin/x64:/mnt/c/Users/andreyolegovich_ru/Documents/Software/axis2-1.6.2:/mnt/c/Users/andreyolegovich_ru/Documents/Software/axis2-1.6.2/bin:/mnt/c/Windows/System32/OpenSSH:/mnt/c/Program Files/TortoiseSVN/bin:/mnt/c/Program Files/Microsoft SQL Server/Client SDK/ODBC/130/Tools/Binn:/mnt/c/Program Files/Microsoft SQL Server/140/Tools/Binn:/mnt/c/Program Files/Microsoft SQL Server/140/DTS/Binn:/mnt/c/Program Files (x86)/Intel/Intel(R) Management Engine Components/DAL:/mnt/c/Program Files/Intel/Intel(R) Management Engine Components/DAL:/mnt/c/Program Files/TortoiseGit/bin:/mnt/c/Program Files/Git/cmd:/mnt/c/Program Files/nodejs:/mnt/c/Program Files/Intel/WiFi/bin:/mnt/c/Program Files/Common Files/Intel/WirelessCommon:/mnt/c/Program Files/PuTTY:/mnt/c/Users/andreyolegovich_ru/AppData/Local/Continuum/anaconda3:/mnt/c/Users/andreyolegovich_ru/AppData/Local/Continuum/anaconda3/Library/mingw-w64/bin:/mnt/c/Users/andreyolegovich_ru/AppData/Local/Continuum/anaconda3/Library/bin:/mnt/c/Users/andreyolegovich_ru/AppData/Local/Continuum/anaconda3/Scripts:/mnt/c/Users/andreyolegovich_ru/AppData/Local/Programs/Python/Python36/Scripts:/mnt/c/Users/andreyolegovich_ru/AppData/Local/Programs/Python/Python36:/mnt/c/Users/andreyolegovich_ru/AppData/Local/Microsoft/WindowsApps:/mnt/c/Users/andreyolegovich_ru/AppData/Local/atom/bin:/mnt/c/Users/andreyolegovich_ru/AppData/Local/Programs/Python/Python36-32:/mnt/c/Users/andreyolegovich_ru/AppData/Local/Programs/Python/Python36-32/Scripts:/mnt/c/Program Files (x86)/Nmap:/mnt/c/Program Files (x86)/Mozilla Firefox:/mnt/c/Users/andreyolegovich_ru/AppData/Local/Microsoft/WindowsApps:/mnt/c/Users/andreyolegovich_ru/AppData/Local/Programs/Fiddler:/mnt/c/Program Files/JetBrains/PyCharm Community Edition 2018.3.2/bin:/mnt/c/Users/andreyolegovich_ru/AppData/Roaming/npm:/mnt/c/Program Files/Intel/WiFi/bin:/mnt/c/Program Files/Common Files/Intel/WirelessCommon:/mnt/c/Users/andreyolegovich_ru/AppData/Local/Programs/Microsoft VS Code/bin:/snap/bin
ERROR: character with byte sequence 0xd0 0x9a in encoding «UTF8»
has no equivalent in encoding «WIN1252»
Скорее всего Вы создали базу данных, и даже смогли туда что-то импортировать, например, из .csv файла.
Но сделать SELECT * FROM table; уже не получается, потому что кодировка базы и кодировка файла не совпадают.
Возможно, Вы уже попробовали явно указать SET CLIENT_ENCODING TO ‘utf8’; при импорте файла. Но так как кодировка WIN1252
— это кодировка БД, способ не сработал.
Нужно привести файл и БД к одной кодировке — пересоздайте БД в utf8, например.
Как проверить кодировки я писал выше —
Проверка кодировок БД
Как указать кодировку при создании БД —
Создание БД
ERROR: database «db» is being accessed by other users
Если Вы делаете DROP DATABASE db; и получаете
ERROR: database «db» is being accessed by other users
DETAIL: There are 2 other sessions using the database.
Значит где-то ещё не закрыто подключение к БД. Например, Вы открывали её через pgAdmin.
Нужно найти это подключение и закрыть
FATAL password authentication failed for user postgres
Если вы логинитесь в pgAdmin, но не помните пароль — его можно поменять через терминал
sudo su — postgres
psql
postgres=# ALTER USER postgres PASSWORD ‘новый_пароль’;
ALTER ROLE
ERROR: could not open file «/home/user…» for reading: Permission denied
Если вы пытаетесь прочитать из файла, а получаете
ERROR: could not open file «/home/user/file.csv» for reading: Permission denied
HINT: COPY FROM instructs the PostgreSQL server process to read a file. You may want a client-side facility such as psql’s \copy. SQL state: 42501
Значит у postgres недостаточно прав для чтения из файла. Простое добавление прав на чтение вроде
chmod +r file.csv
Проблему, скорее всего, не решит.
Как вариант — предлагаю переместить нужный файл в директорию /tmp
cp /home/user/file.csv /tmp
ERROR: COPY quote must be a single one-byte character
Если вы пытаетесь прочитать из файла, а получаете
ERROR: COPY quote must be a single one-byte character
SQL state: 0A000
Скорее всего присутствует какой-то лишний символ в QUOTE, например
QUOTE ‘\»‘
Замените на
QUOTE ‘»‘
ERROR: date/time field value out of range
Если вы пытаетесь прочитать из .csv файла, а получаете
ERROR: date/time field value out of range: «» HINT: Perhaps you need a different «datestyle» setting. CONTEXT: «» SQL state: 22008
Скорее всего ваш текущий datestyle не совпадает с тем, который используется в .csv файле.
datestyle — это порядок записи даты. Может быть День — Месяц — Год (DDMMYYYY), Год — Месяц — День (YYYYMMDD) или,
например американский стиль Месяц — День — Год (MMDDYYYY)
Это всё актуально если тип столбца указан как дата date. Можно изменить тип на char тогда datestyle уже не нужно настраивать.
Стилей много и если они не совпадают — получается что месяц принимает значение больше 12.
Как вариант — можно перед выполнение скрипта временно изменить свой datestyle.
Например, если нужно импортировать данные из .csv с американским стилем — перед импортом добавьте
set datestyle to «US»;
РЕКЛАМА хостинга Beget, которым я пользуюсь более десяти лет
Конец рекламы хостинга Beget, который я всем рекомендую
psql: could not connect to server: No such file or directory
Если вы выполнили
psql
И получили ошибку
psql: could not connect to server: No such file or directory
Is the server running locally and accepting
connections on Unix domain socket «/var/run/postgresql/.s.PGSQL.5432»?
Очень часто данная ошибка возникает вследствии того, что не была инициализирована база
данных.
Выполните
postgresql-setup initdb
Initializing database … OK
pg_basebackup: could not connect to server: could not connect to server: No route to host
Если вы пытаетесь сделать реплику
pg_basebackup -h 192.168.56.109 -U repluser -D /var/lib/pgsql/data —xlog-method=stream
pg_basebackup: could not connect to server: could not connect to server: No route to host
Is the server running on host «192.168.56.109» and accepting
TCP/IP connections on port 5432?
На мастере
sudo firewall-cmd —zone=public —add-port=5432/tcp —permanent
success
sudo firewall-cmd —reload
success
sudo firewall-cmd —list-ports
3389/tcp 5432/tcp
Failed to stop postgresql.service: Unit postgresql.service not loaded
Причин может быть много но среди новичков самая распространённая — попытка остановить postgresql
из под пользователя postges
Например, в моём терминале я по приглашению bash-4.2$ вижу, что зашёл как postgres
Нужно выполнить
exit
Приглашение изменится на
[andrei@localhost ~]$
И затем уже можно останавливать сервер
sudo systemctl stop postgresql
sudo systemctl status postgresql
● postgresql.service — PostgreSQL database server
Loaded: loaded (/usr/lib/systemd/system/postgresql.service; disabled; vendor preset: disabled)
Active: inactive (dead)
Jun 09 12:20:24 localhost.localdomain systemd[1]: Unit postgresql.service entered failed state.
Jun 09 12:20:24 localhost.localdomain systemd[1]: postgresql.service failed.
Jun 09 12:21:59 localhost.localdomain systemd[1]: Starting PostgreSQL database server…
Jun 09 12:22:00 localhost.localdomain systemd[1]: Started PostgreSQL database server.
Jun 10 19:10:02 localhost.localdomain systemd[1]: Stopping PostgreSQL database server…
Jun 10 19:10:03 localhost.localdomain systemd[1]: Stopped PostgreSQL database server.
Jun 10 22:14:18 localhost.localdomain systemd[1]: Starting PostgreSQL database server…
Jun 10 22:14:19 localhost.localdomain systemd[1]: Started PostgreSQL database server.
Jun 11 10:11:15 localhost.localdomain systemd[1]: Stopping PostgreSQL database server…
Jun 11 10:11:16 localhost.localdomain systemd[1]: Stopped PostgreSQL database server.
ERROR: WAL level not sufficient for making an online backup
Вы хотите настроить онлайн бэкап, например с помощью команды
-bash-4.2$ psql -c «SELECT pg_start_backup(‘replbackup’);»
Но получаете ошибку
ERROR: WAL level not sufficient for making an online backup
HINT: wal_level must be set to «archive» or «hot_standby» at server start.
Нужно узнать расположение конфигурационного файла
postgresql.conf
-bash-4.2$ su — postgres -c «psql -c ‘SHOW config_file;'»
Password:
config_file
————————————-
/var/lib/pgsql/data/postgresql.conf
(1 row)
vi /var/lib/pgsql/data/postgresql.conf
Нужно установить wal_level = hot_standby
NOTICE: WAL archiving is not enabled
Вы заканчиваете бэкап, например с помощью команды
psql -c «SELECT pg_stop_backup();»
Но получаете предупреждение
NOTICE: WAL archiving is not enabled; you must ensure that all required WAL segments are copied through other means to complete the backup
Автор статьи: Андрей Олегович
Похожие статьи
Ошибки | |
PostgreSQL | |
psql command not found | |
ERROR: character with byte sequence 0xd0 0x9a in encoding «e;UTF8″e; has no equivalent in encoding «e;WIN1252″e; | |
ERROR: database «e;db»e; is being accessed by other users | |
FATAL password authentication failed for user postgres | |
ERROR: could not open file «e;/home/user…»e; for reading: Permission denied | |
ERROR: COPY quote must be a single one-byte character | |
ERROR: date/time field value out of range | |
psql: could not connect to server: No such file or directory | |
pg_basebackup: could not connect to server: No route to host | |
Failed to stop postgresql.service: Unit postgresql.service not loaded | |
ERROR: WAL level not sufficient for making an online backup | |
NOTICE: WAL archiving is not enabled | |
Job for postgresql.service failed because the control process exited with error code | |
Please configure_the_postgresql_binary_path |
PostgreSQL Errors
↓
Contents
↓
psql command not found |
|
ERROR: character with byte sequence 0xd0 0x9a in encoding «UTF8» has no equivalent in encoding «WIN1252» |
|
ERROR: database «db» is being accessed by other users |
|
FATAL password authentication failed for user postgres |
|
ERROR: could not open file «/home/user…» for reading: Permission denied |
|
ERROR: COPY quote must be a single one-byte character |
|
ERROR: date/time field value out of range |
psql command not found
Вы хотите запустить Postgres скрипт из bash
andrey@olegovich-10:/mnt/c/Users/olegovich$ psql -h localhost -p 5432 -U andrei
но получаете эту ошибку
-bash: psql: command not found
Это значит, что путь до Postgres не прописан в $PATH
To узнать, что прописано в $PATH достаточно сделать
echo $PATH
/home/andrei/bin:/home/andrei/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/mnt/c/Program Files (x86)/Common Files/Oracle/Java/javapath_target_1128437:/mnt/c/ProgramData/Oracle/Java/javapath_target_5252250:/mnt/c/Windows/System32:/mnt/c/Windows:/mnt/c/Windows/System32/wbem:/mnt/c/Windows/System32/WindowsPowerShell/v1.0:/mnt/c/Program Files/OpenVPN/bin:/mnt/c/Program Files (x86)/Microsoft SQL Server/Client SDK/ODBC/130/Tools/Binn:/mnt/c/Program Files (x86)/Microsoft SQL Server/140/Tools/Binn:/mnt/c/Program Files (x86)/Microsoft SQL Server/140/DTS/Binn:/mnt/c/Program Files (x86)/Microsoft SQL Server/140/Tools/Binn/ManagementStudio:/mnt/c/Program Files/MiKTeX 2.9/miktex/bin/x64:/mnt/c/Users/andreyolegovich_ru/Documents/Software/axis2-1.6.2:/mnt/c/Users/andreyolegovich_ru/Documents/Software/axis2-1.6.2/bin:/mnt/c/Windows/System32/OpenSSH:/mnt/c/Program Files/TortoiseSVN/bin:/mnt/c/Program Files/Microsoft SQL Server/Client SDK/ODBC/130/Tools/Binn:/mnt/c/Program Files/Microsoft SQL Server/140/Tools/Binn:/mnt/c/Program Files/Microsoft SQL Server/140/DTS/Binn:/mnt/c/Program Files (x86)/Intel/Intel(R) Management Engine Components/DAL:/mnt/c/Program Files/Intel/Intel(R) Management Engine Components/DAL:/mnt/c/Program Files/TortoiseGit/bin:/mnt/c/Program Files/Git/cmd:/mnt/c/Program Files/nodejs:/mnt/c/Program Files/Intel/WiFi/bin:/mnt/c/Program Files/Common Files/Intel/WirelessCommon:/mnt/c/Program Files/PuTTY:/mnt/c/Users/andreyolegovich_ru/AppData/Local/Continuum/anaconda3:/mnt/c/Users/andreyolegovich_ru/AppData/Local/Continuum/anaconda3/Library/mingw-w64/bin:/mnt/c/Users/andreyolegovich_ru/AppData/Local/Continuum/anaconda3/Library/bin:/mnt/c/Users/andreyolegovich_ru/AppData/Local/Continuum/anaconda3/Scripts:/mnt/c/Users/andreyolegovich_ru/AppData/Local/Programs/Python/Python36/Scripts:/mnt/c/Users/andreyolegovich_ru/AppData/Local/Programs/Python/Python36:/mnt/c/Users/andreyolegovich_ru/AppData/Local/Microsoft/WindowsApps:/mnt/c/Users/andreyolegovich_ru/AppData/Local/atom/bin:/mnt/c/Users/andreyolegovich_ru/AppData/Local/Programs/Python/Python36-32:/mnt/c/Users/andreyolegovich_ru/AppData/Local/Programs/Python/Python36-32/Scripts:/mnt/c/Program Files (x86)/Nmap:/mnt/c/Program Files (x86)/Mozilla Firefox:/mnt/c/Users/andreyolegovich_ru/AppData/Local/Microsoft/WindowsApps:/mnt/c/Users/andreyolegovich_ru/AppData/Local/Programs/Fiddler:/mnt/c/Program Files/JetBrains/PyCharm Community Edition 2018.3.2/bin:/mnt/c/Users/andreyolegovich_ru/AppData/Roaming/npm:/mnt/c/Program Files/Intel/WiFi/bin:/mnt/c/Program Files/Common Files/Intel/WirelessCommon:/mnt/c/Users/andreyolegovich_ru/AppData/Local/Programs/Microsoft VS Code/bin:/snap/bin
ERROR: character with byte sequence 0xd0 0x9a in encoding «UTF8»
has no equivalent in encoding «WIN1252»
Скорее всего Вы создали базу данных, и даже смогли туда что-то импортировать, например, из .csv файла.
Но сделать SELECT * FROM table; уже не получается, потому что кодировка базы и кодировка файла не совпадают.
Возможно, Вы уже попробовали явно указать SET CLIENT_ENCODING TO ‘utf8’; при импорте файла. Но так как кодировка WIN1252
— это кодировка БД, способ не сработал.
Нужно привести файл и БД к одной кодировке — пересоздайте БД в utf8, например.
Как проверить кодировки я писал выше —
Проверка кодировок БД
Как указать кодировку при создании БД —
Создание БД
ERROR: database «db» is being accessed by other users
Если Вы делаете DROP DATABASE db; и получаете
ERROR: database «db» is being accessed by other users
DETAIL: There are 2 other sessions using the database.
Значит где-то ещё не закрыто подключение к БД. Например, Вы открывали её через pgAdmin.
Нужно найти это подключение и закрыть
FATAL password authentication failed for user postgres
Если вы логинитесь в pgAdmin, но не помните пароль — его можно поменять через терминал
sudo su — postgres
psql
postgres=# ALTER USER postgres PASSWORD ‘новый_пароль’;
ALTER ROLE
ERROR: could not open file «/home/user…» for reading: Permission denied
Если вы пытаетесь прочитать из файла, а получаете
ERROR: could not open file «/home/user/file.csv» for reading: Permission denied
HINT: COPY FROM instructs the PostgreSQL server process to read a file. You may want a client-side facility such as psql’s \copy. SQL state: 42501
Значит у postgres недостаточно прав для чтения из файла. Простое добавление прав на чтение вроде
chmod +r file.csv
Проблему, скорее всего, не решит.
Как вариант — предлагаю переместить нужный файл в директорию /tmp
cp /home/user/file.csv /tmp
ERROR: COPY quote must be a single one-byte character
Если вы пытаетесь прочитать из файла, а получаете
ERROR: COPY quote must be a single one-byte character
SQL state: 0A000
Скорее всего присутствует какой-то лишний символ в QUOTE, например
QUOTE ‘\»‘
Замените на
QUOTE ‘»‘
ERROR: date/time field value out of range
Если вы пытаетесь прочитать из .csv файла, а получаете
ERROR: date/time field value out of range: «» HINT: Perhaps you need a different «datestyle» setting. CONTEXT: «» SQL state: 22008
Скорее всего ваш текущий datestyle не совпадает с тем, который используется в .csv файле.
datestyle — это порядок записи даты. Может быть День — Месяц — Год (DDMMYYYY), Год — Месяц — День (YYYYMMDD) или,
например американский стиль Месяц — День — Год (MMDDYYYY)
Это всё актуально если тип столбца указан как дата date. Можно изменить тип на char тогда datestyle уже не нужно настраивать.
Стилей много и если они не совпадают — получается что месяц принимает значение больше 12.
Как вариант — можно перед выполнение скрипта временно изменить свой datestyle.
Например, если нужно импортировать данные из .csv с американским стилем — перед импортом добавьте
set datestyle to «US»;