Using PostgreSQL when I connect to a db using c testdb
inside PostgreSQL Database SQL Prompt. I successfully connect to the db but getting the following warning:
postgres-# c testdb
WARNING: Console code page (437) differs from Windows code page (1252)
8-bit characters might not work correctly. See psql reference
page "Notes for Windows users" for details.
You are now connected to database "testdb" as user "postgres".
testdb-#
What does this warning mean? How to resolve it?
asked Dec 27, 2013 at 2:45
Yousuf MemonYousuf Memon
4,58811 gold badges40 silver badges57 bronze badges
1
From the psql documentation:
psql is built as a «console application». Since the Windows console
windows use a different encoding than the rest of the system, you must
take special care when using 8-bit characters within psql. If psql
detects a problematic console code page, it will warn you at startup.To change the console code page, two things are necessary:
Set the code page by entering cmd.exe /c chcp 1252. (1252 is a code
page that is appropriate for German; replace it with your value.) If
you are using Cygwin, you can put this command in /etc/profile.
So to remove that warning you need to execute chcp 1252
before you enterpsql
. Using chcp
without parameters gives you the current codepage.
answered Dec 27, 2013 at 2:57
6
The default codepage for CMD.exe is different than the default for postgres… To change for CMD.exe using the REGISTRY try this:
- Start -> Run -> regedit
- Go to [HKEY_LOCAL_MACHINESoftwareMicrosoftCommand Processor]
- Add new string value named «Autorun» with value «chcp 1252»
Then reopen CMD.exe
answered Jan 10, 2018 at 0:11
user3344137user3344137
3513 silver badges4 bronze badges
3
To make it even more obvious, the file to which @user3423801 is adding the line
cmd.exe /c chcp 1252
is in the scripts
directory where you installed Postgre.
For example, in my case it is
C:Program FilesPostgreSQL9.3scriptsrunpsql.bat
answered Jun 16, 2014 at 21:38
numbers longernumbers longer
3211 gold badge3 silver badges9 bronze badges
1
Open cmd.exe and run regedit
.
Go to ComputerHKEY_LOCAL_MACHINESOFTWAREMicrosoftCommand Processor
New a string value named: Autorun
and change the value to be chcp 1252
Done.
Reference: https://stackoverflow.com/a/30100565/8396969
answered Apr 10, 2018 at 6:02
Please don’t assume that Unix fixes work for Windows Users. For Windows 10, and PostgreSQL 12, combining the answers by «user3423801» and «numbers longer» worked for me. (The Windows Registry hack would not work. I did not try rebooting yet.) It is better to fix it in the PSQL startup script anyway.
The file location C:Program FilesPostgreSQL12scripts
contains the file runpsql.bat
, into which you must insert the cmd.exe /c chcp 1252 command
in the right location. So the top of your edited file should look like the 5 or 6 lines below.
@echo off
REM Copyright (c) 2012-2014, EnterpriseDB Corporation. All rights reserved
REM PostgreSQL server psql runner script for Windows
cmd.exe /c chcp 1252
SET server=localhost
SET /P server="Server [%server%]: "
answered Nov 10, 2019 at 1:10
The answer of dvdgsng is correct but with code example is more obviously.
@echo off
REM Copyright (c) 2012-2014, EnterpriseDB Corporation. All rights reserved
REM PostgreSQL server psql runner script for Windows
cmd.exe /c chcp 1252
SET server=localhost
SET /P server="Server [%server%]: "
Skwal
2,1402 gold badges20 silver badges30 bronze badges
answered Mar 15, 2014 at 17:50
Or you can simply type cmd.exe /c chcp 1252
in the Command Prompt window.
answered Apr 28, 2015 at 12:55
iustingiusting
7,6432 gold badges21 silver badges29 bronze badges
1
you just go to the power-shell or cmd.exe and type the command chcp 1252
or whatever the page number it wants «the one that is the windows code page». If the problem still persists, just open the console properties ‘By clicking the power shell icon on the top left of the console window and choosing properties from the drop-down menu’ and change the font to «Lucida Console». It worked for me, But you have to open power-shell as an Administrator.
answered Nov 5, 2020 at 8:57
The answers above are okay, but don’t mention anywhere that Windows 1252 encoding is good for English language versions of Windows AND the other Western European Languages. This completes the answer for those people who may get confused about the aforementioned application to German language encoding. Yes it works for English without umlauts and other special characters needed for German, Spanish, French, Italian, Romanian, Hungarian, etc.
https://en.m.wikipedia.org/wiki/Windows-1252
What is Windows 1252 encoding?
Windows-1252 or CP-1252 (code page 1252) is a single-byte character encoding of the Latin alphabet, used by default in the legacy components of Microsoft Windows for English and some other Western languages (other languages use different default encodings).
answered Nov 10, 2019 at 0:58
After much digging for an answer that made sense to me, I found this help email chain at the PostgreSQL site which basically says to run chcp 1252
from inside an open command window.
I was then able to run my PostgreSQL commands without the code warning.
NOTE: this change does not persist so you have to run it every time you open a new command window where you plan to use PostgreSQL commands.
answered Jan 23, 2017 at 21:43
amrabyamraby
1,1989 silver badges11 bronze badges
For Postgres 11
«WARNING: Console code page (437) differs from Windows code page
(1252)
8-bit characters might not work correctly. See psql reference
page «Notes for Windows users» for details.»
If you aren’t an administrator on your machine
Add a line «chcp 1252» to the pg_env.bat script found in the base directory of your postgres installation.’
i.e. «C:Program FilesPostgreSQL11»
If you are and Administrator on your machine
you can modify the registry to run the line everytime you run «cmd.exe» as mentioned above.
answered Jan 3, 2019 at 16:54
I couldn’t figure out how to set it for Cygwin globally. This seemed to work though in my bash script
#!/bin/bash
cmd.exe /c chcp 1252 && psql -h myserver.postgres.database.azure.com -U myuser@prod-au -d mydatabase
answered Feb 1, 2019 at 6:41
Damien SawyerDamien Sawyer
5,0923 gold badges47 silver badges53 bronze badges
1
Basically, set your console application encoding from 8-bit to utf-8 Windows 1252.
For git bash users
run the command chcp.com 1252
before running postgres
chcp is a windows console command, so to execute it on git bash you might need to add .com
git bash can’t extend chcp to a full executable on its own, so you need to type the full command.
here
answered Feb 5, 2019 at 4:45
go je jogo je jo
1714 silver badges8 bronze badges
2
- On the terminal screen go to the following directory;
C:Program FilesPostgreSQL14bin
note: whichever database version you are using, go to the bin folder of the db version file.
- Before creating a user or accessing the database user, you must write the following code;
cmd.exe /c chcp 1252
answered Aug 17, 2022 at 12:48
Whenever I access psql, I get the following message:
psql (9.6.2)
WARNING: Console code page (437) differs from Windows code page (1252)
8-bit characters might not work correctly. See psql reference
page "Notes for Windows users" for details.
Type "help" for help.
postgres=#
I tried command
cmd.exe /c chcp 1252
before running runpsql.bat file in command line. And there, it runs fine without the error. But accessing psql again after closing command prompt, throws the same warning. How do I solve this warning within SQL Shell?
I am using windows 10 OS.
Edit:
This is what I did:
Microsoft Windows [Version 10.0.10586]
(c) 2015 Microsoft Corporation. All rights reserved.
C:UsersSarthak Joshi>E:
E:>cd PostgreSQL
E:PostgreSQL>cd scripts
E:PostgreSQLscripts>chcp 1252
Active code page: 1252
E:PostgreSQLscripts>runpsql.bat
Server [localhost]:
Database [postgres]:
Port [5432]:
Username [postgres]:
Password for user postgres:
psql (9.6.2)
Type "help" for help.
postgres=#
But after exiting from cmd, and firing up shell like this:
Server [localhost]:
Database [postgres]:
Port [5432]:
Username [postgres]:
Password for user postgres:
psql (9.6.2)
WARNING: Console code page (437) differs from Windows code page (1252)
8-bit characters might not work correctly. See psql reference
page "Notes for Windows users" for details.
Type "help" for help.
postgres=#
It still throws the same warning…
SUMMARY OF PROBLEM: Postgres notes no errors upon installation, but upon
startup of psql there’s a warning; documentation fix doesn’t eliminate
the warning message.
1. psql says this when I log in:
Server [localhost]:
Database [postgres]:
Port [5432]:
Username [postgres]:
Password for user postgres:
psql (9.4rc1)
WARNING: Console code page (437) differs from Windows code page (1252)
8-bit characters might not work correctly. See psql reference
page «Notes for Windows users» for details.
Type «help» for help.
postgres=#
2. psql ref. pg. says this:
*Notes for Windows Users*
psql is built as a «console application». Since the Windows console
windows use a different encoding than the rest of the system, you must
take special care when using 8-bit characters within psql. If psql
detects a problematic console code page, it will warn you at startup. To
change the console code page, two things are necessary:
* Set the code page by entering cmd.exe /c chcp 1252. (1252 is a code
page that is appropriate for German; replace it with your value.) If
you are using Cygwin, you can put this command in /etc/profile.
Set the console font to Lucida Console, because the raster font does not
work with the ANSI code page.
3. When I enter «cmd.exe /c chcp 1252» into the command prompt, it says
this:
Microsoft Windows [Version 6.1.7600]
Copyright (c) 2009 Microsoft Corporation. All rights reserved.
C:Userszzzzzz>cmd.exe /c chcp 1252
Active code page: 1252
C:Userszzzzzz>
4. Am I supposed to type this at the command prompt: «cmd.exe /c chcp
437″? Because that’s what I did, and now the command prompt says this…
C:Userszzzzzz>cmd.exe /c chcp 437
Active code page: 437
C:Userszzzzzz>
…but I quit and reopened psql, the error message isn’t gone or changed.
5. The instructions to set console font mean nothing to me: «Set the
console font to Lucida Console, because the raster font does not work
with the ANSI code page». Googled it and found nothing that made sense
to me. Set whose console font? PG or Windows? Where and how to set it?
What is a console, anyway? Googled again and again, finally discovered
that the console being referred to is apparently psql itself. By
clicking on the little rectangular icon at the top left of the title bar
of the command prompt (psql), Properties, Font…there it is. «Raster
Fonts» had been selected. I changed this to Lucida Console. Quit psql
and restarted it.
6. psql startup warning has now changed to a different font, no other
change.
7. I changed the console page back to 1252 in the command prompt:
Microsoft Windows [Version 6.1.7600]
Copyright (c) 2009 Microsoft Corporation. All rights reserved.
C:Userszzzzz>cd/
C:>cmd.exe /c chcp 1252
Active code page: 1252
C:>
8. Quit and restarted psql (twice). The warning message has not changed.
Is it possible that pg is wrongly detecting code page 437, and does it
matter? I have a lot of work to do and want a sparkling clean foundation
to start from so I don’t have problems later.
—
stumpednomore(at)gmail(dot)com
—
This email has been checked for viruses by Avast antivirus software.
http://www.avast.com
After you login from the command line through psql, you see the message,
«psql (9.5.1)
WARNING: Console code page (437) differs from Windows code page (1252)
8-bit characters might not work correctly. See psql reference
page «Notes for Windows users» for details.
Type «help» for help.»
This is because Windows console uses a different encoding than the psql console application. To solve this you need to set the code page for your psql before login.
To reset the code page:
database => q //log out of the database
C:Usersdsmith> chcp 1252 //change code page to 1252
Active code page: 1252
C:Usersdsmith> psql -d dbname -h host -p port -U username
Password for user username:
psql (9.5.1)
Type «help» for help.
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one?Read the book free here.
Использование PostgreSQL при подключении к db с помощью c testdb
внутри SQL-запроса PostgreSQL SQL. Я успешно подключаюсь к db, но получаю следующее предупреждение:
postgres-# c testdb
WARNING: Console code page (437) differs from Windows code page (1252)
8-bit characters might not work correctly. See psql reference
page "Notes for Windows users" for details.
You are now connected to database "testdb" as user "postgres".
testdb-#
Что означает это предупреждение? Как его решить?
Ответ 1
Из документации PSQL:
PSQL построен как «консольное приложение». Поскольку окна консоли Windows используют другую кодировку, чем остальная система, вы должны быть особенно осторожны при использовании 8-битных символов в psql. Если psql обнаружит проблемную кодовую страницу консоли, он предупредит вас при запуске.
Чтобы изменить кодовую страницу консоли, необходимо две вещи: установить кодовую страницу, введя cmd.exe/c chcp 1252. (1252 — это кодовая страница, подходящая для немецкого языка; замените ее на свое значение.) Если вы используете Cygwin Вы можете поместить эту команду в /etc/profile.
Таким образом, чтобы удалить это предупреждение, вам нужно выполнить chcp 1252
перед chcp 1252
psql
. Использование chcp
без параметров дает вам текущую кодовую страницу.
Ответ 2
Чтобы сделать это еще более очевидным, файл, к которому @user3423801 добавляет строку
cmd.exe /c chcp 1252
находится в каталоге scripts
, где вы установили Postgre.
Например, в моем случае это
C:Program FilesPostgreSQL9.3scriptsrunpsql.bat
Ответ 3
Или вы можете просто ввести cmd.exe /c chcp 1252
в окне командной строки.
Ответ 4
Кодовая страница по умолчанию для CMD.exe отличается от значения по умолчанию для postgres… Для изменения для CMD.exe с помощью REGISTRY попробуйте следующее:
- Пуск → Выполнить → regedit
- Перейдите к [HKEY_LOCAL_MACHINESoftwareMicrosoftCommand Processor]
- Добавьте новое строковое значение с именем «Autorun» со значением «chcp 1252»
Затем снова запустите CMD.exe
Ответ 5
Ответ dvdgsng верен, но пример кода более явно.
@echo off
REM Copyright (c) 2012-2014, EnterpriseDB Corporation. All rights reserved
REM PostgreSQL server psql runner script for Windows
cmd.exe /c chcp 1252
SET server=localhost
SET /P server="Server [%server%]: "
Ответ 6
Откройте cmd.exe и запустите regedit
.
Перейдите на ComputerHKEY_LOCAL_MACHINESOFTWAREMicrosoftCommand Processor
Новое строковое значение с именем: Autorun
и измените значение на chcp 1252
Готово.
Ссылка: fooobar.com/questions/202329/…
Ответ 7
Я не мог понять, как установить его для Cygwin во всем мире. Похоже, это работает в моем скрипте bash
#!/bin/bash
cmd.exe /c chcp 1252 && psql -h myserver.postgres.database.azure.com -U [email protected] -d mydatabase
Ответ 8
После многократного поиска ответа, который имел для меня смысл, я нашел эту справочную цепочку электронной почты на сайте PostgreSQL, который в основном говорит, что нужно запустить chcp 1252
из открытого командного окна.
Затем я смог запустить мои команды PostgreSQL без предупреждения кода.
ПРИМЕЧАНИЕ. Это изменение не сохраняется, поэтому вы должны запускать его каждый раз, когда вы открываете новое окно команд, в котором вы планируете использовать команды PostgreSQL.
Ответ 9
Для Postgres 11
«ПРЕДУПРЕЖДЕНИЕ. Кодовая страница консоли (437) отличается от кодовой страницы Windows (1252) 8-разрядные символы могут работать неправильно. Дополнительные сведения см. на справочной странице psql» Примечания для пользователей Windows «.»
Если вы не являетесь администратором на своем компьютере, добавьте строку «chcp 1252» в скрипт pg_env.bat, который находится в базовом каталоге вашей установки postgres. ‘ т.е. «C:Program FilesPostgreSQL11»
Если вы являетесь администратором на своем компьютере, вы можете изменить реестр, чтобы он запускал строку при каждом запуске «cmd.exe», как указано выше.
Ответ 10
В основном, установите кодировку консольного приложения с 8-битной на utf-8.
Для пользователей git bash перед запуском postgres выполните команду chcp.com 1252
chcp — консольная команда Windows, поэтому для ее выполнения в git bash может потребоваться добавить .com
git bash не может самостоятельно расширить chcp до полного исполняемого файла, поэтому вам нужно ввести полную команду.
Вот
Ответ 11
Чтобы сохранить свою кодовую страницу в pgsql.cmd(например, 1250), измените строку
chcp 1252 > nul
в
chcp 1250 > nul
After you install PostgreSQL 14 on Windows, there are a few steps to create a sandbox database. This post shows you those steps, including a couple Windows OS tasks you’ll need to complete. You should note that these instructions are for the PostgreSQL psql Command Line Interface (CLI).
Open a Command Prompt with Administrator privileges. It should give you a command prompt like the following:
Microsoft Windows [Version 10.0.19042.1466] (c) Microsoft Corporation. All rights reserved. C:Usersusername>
Type psql to launch the PostgreSQL CLI and then the return or enter key:
Most likely, you’ll get the following error message. It means that your System Path environment variable doesn’t include the directory where the psql executable is found, and that’s why the command is not recognized.
'psql' is not recognized as an internal or external command, operable program or batch file.
You can set it temporarily in your current Windows CLI with the following command:
set PATH=%PATH%;C:Program FilesPostgreSQL14bin;
For those familiar with Windows CLI navigation in prior releases, the convention is to append a semicolon at the end of the item added to the %PATH% environment variable. If you were to put the semicolon between the %PATH% and new directory path there would be two semicolons together. While it won’t do any harm, it’s best to follow the new convention or style.
CRITICAL NOTE: The rest of the post assumes you have set the correct %PATH% environment variable or added it to your System’s Path environment variable and restarted the Windows CLI after adding it through the GUI tool. The reason you need to restart the Windows CLI is that the %PATH% environment variable is inherited at startup and doesn’t change in an open Windows CLI shell.
Another common mistake some users make, at least those who have used an older version of the psql utility on a Linux distribution (or “distro”), is to type psql without any arguments to become the superuser. This error doesn’t occur in Linux because you most likely connected as the postgres user before trying to connect to the PostgreSQL database. A quick demonstration should illustrate the error and support explaining why it occurs on the Windows OS.
Attempting to connect to the PostgreSQL database as a non-postgres user:
You should get the following error:
psql: error: connection to server at "localhost" (::1), port 5432 failed: fe_sendauth: no password supplied
This error occurs because you’re not the postgres user, and all other users must designate that they’re connecting to the superuser account. The correct syntax is:
C:Usersusername>psql -U postgres
Then, you’ll be prompted for the password that you set when you installed PostreSQL database. Enter that password from the installation at the prompt.
Password for user postgres: psql (14.1) WARNING: Console code page (437) differs from Windows code page (1252) 8-bit characters might not work correctly. See psql reference page "Notes for Windows users" for details. Type "help" for help. postgres=#
The warning message is telling you that the character set collation differs between your Windows OS and the PostgreSQL database. We’ll discuss this more later but for the sake of almost all your work, it won’t matter. If the warning message bothers you, you can run the chcp command before launching PostgreSQL when you open your Windows CLI:
The chcp command changes your terminal character set to align with the Latin 1 character set, which enables you to use things like non-English accent characters (the umlaut over an o, or ö). After running the You will see this when you connect after running that command:
psql (14.2) Type "help" for help. postgres#
INFO: The chcp command is used to supplement the international keyboard and character set information, allowing MS-DOS to be used in other countries and with different languages. Before the chcp command can be used, the nlsfunc must be loaded, and the country.sys must be loaded into the OS configuration.
If you are an experienced Windows OS user, you may want to edit your Windows Registry to change this behavior automatically for each Windows CLI session. You can do that by opening the Windows Registry with the regedit command as an Administrator. In regedit, add an Autorun element with a value of chcp 1252 to this part of the registry:
ComputerHKEY_LOCAL_MACHINESOFTWAREMicrosoftCommand Processor
This value automatically sets your Windows CLI to a Latin 1 character set everytime you launch a terminal shell with the cmd.exe utility. You should only do this if you understand it completely.
Now that you’re connected as the superuser, let’s examine the steps to configure your playground or videodb database. There are five steps to configure your database and one step to connect and use the videodb database as the student user
- Create Physical Directory
The directory for the data dictionary changes with PostgreSQL installations. You can find it with the following psql CLI command:
postgres=# show data_directory;
This will return the following:
data_directory ------------------------------------- C:/Program Files/PostgreSQL/14/data (1 row)
While it is possible to store your subdirectory in the data dictionary, it will raise a warning message. It’s actually a better practice to install your local databases in another location on your file system.
Open a new Windows OS CLI to create a subdirectory (or in Windows parlance folder) where you will store your videoDB database. Each new Windows OS CLI opens in your home directory. You need to create a physical video_db subdirectory in your home directory.
HINT: The name of the database inside PostgreSQL should map to the tablespace name and differ from the physical directory. Otherwise there is a chance you might get confused and make an error in the future.
In a new command line shell, you can use the following syntax to create videoDB subdirectory:
- Create Tablespace
Returning to the original Windows CLI shell where you are connected as the postgres superuser, you can create a video_db tablespace with the following syntax:
CREATE TABLESPACE video_db OWNER postgres LOCATION 'C:Usersusernamevideo_db';
This will return the following:
You can query whether you successfully create the video_db tablespace with the following:
SELECT * FROM pg_tablespace;
It should return the following:
oid | spcname | spcowner | spcacl | spcoptions -------+------------+----------+--------+------------ 1663 | pg_default | 10 | | 1664 | pg_global | 10 | | 16395 | video_db | 10 | | (3 rows)
- Create a Database
You need to know the PostgreSQL default collation before you create a new database. You can write the following query to determine the default correlation:
postgres=# SELECT datname, datcollate FROM pg_database WHERE datname = 'postgres';
It should return something like this:
datname | datcollate -----------+---------------------------- postgres | English_United States.1252 (1 row)
The datcollate value of the postgres database needs to the same value for the LC_COLLATE and LC_CTYPE parameters when you create a database. You can create a videodb database with the following syntax provided you’ve made appropriate substitutions for the LC_COLLATE and LC_CTYPE values below:
CREATE DATABASE videodb WITH OWNER = postgres ENCODING = 'UTF8' TABLESPACE = video_db LC_COLLATE = 'English_United States.1252' LC_CTYPE = 'English_United States.1252' CONNECTION LIMIT = -1;
You can verify the creation of the videodb with the following command:
It should show you a display like the following:
List of databases Name | Owner | Encoding | Collate | Ctype | Access privileges -----------+----------+----------+----------------------------+----------------------------+----------------------- postgres | postgres | UTF8 | English_United States.1252 | English_United States.1252 | template0 | postgres | UTF8 | English_United States.1252 | English_United States.1252 | =c/postgres + | | | | | postgres=CTc/postgres template1 | postgres | UTF8 | English_United States.1252 | English_United States.1252 | =c/postgres + | | | | | postgres=CTc/postgres videodb | postgres | UTF8 | English_United States.1252 | English_United States.1252 | (4 rows)
Then, you can assign comment to the database with the following syntax:
COMMENT ON DATABASE videodb IS 'Video Store Database';
- Create a Role, Grant, and User
In this section you create a dba role, grant privileges on a videodb database to a role, and create a user with the role that you created previously with the following three statements. There are three steps in this sections.
- The first step creates a dba role:
CREATE ROLE dba WITH SUPERUSER;
- The second step grants all privileges on the videodb database to both the postgres superuser and the dba role:
GRANT ALL PRIVILEGES ON DATABASE videodb TO postgres; GRANT ALL PRIVILEGES ON DATABASE videodb TO dba;
Any work in pgAdmin4 requires a grant on the videodb database to the postgres superuser. The grant enables visibility of the videodb database in the pgAdmin4 console as shown in the following image.
- The third step creates a student user with the dba role:
CREATE USER student WITH ROLE dba ENCRYPTED PASSWORD 'student';
After this step, you need to disconnect as the postgres superuser with the following command:
- It is possible that you may (and should if this is a new instance you are building) encounter an error when you try to connect as a sandboxed user. The syntax to connect as the student user is:
psql -d videodb -U student -W
All the options, which are preceded with a single dash (–) are case sensitive. The -d option sets the database for the connection. The -U option set user for the connection and the -W option instructs the psql CLI to prompt for the password.
While you shouldn’t encounter the following error during a Windows OS installation,
psql: FATAL: Peer authentication failed for user "student"
You can fix this in PostgreSQL 14 by changing the user access parameters in the pg_hba.conf configuration file. The file is found in the C:Program FilesPostgreSQL14data directory. These are the correct out of the box settings you should see.
# TYPE DATABASE USER ADDRESS METHOD # "local" is for Unix domain socket connections only local all all scram-sha-256 # IPv4 local connections: host all all 127.0.0.1/32 scram-sha-256 # IPv6 local connections: host all all ::1/128 scram-sha-256 # Allow replication connections from localhost, by a user with the # replication privilege. local replication all scram-sha-256 host replication all 127.0.0.1/32 scram-sha-256 host replication all ::1/128 scram-sha-256
If you find something that’s broken, fix it. The values above should ensure you make the changes successfully. You will need to restart the postgres service if you make changes.
If you plan on using the copy command to read external CSV (Comma Separated Value) files, you need to grant as the postgres superuser another privilege to the student user. This grants the pg_read_server_files role to the student user.
GRANT pg_read_server_files TO student;
- Create a Schema
The PostgreSQL database supports multiple schemas inside databases. The default schema for any database is the public schema. You must create separate schemas and refer to them explicitly when accessing them unless you alter the default search path. This section demonstrates how to:
- Create an app schema.
- Create a revision_history table in the app schema.
- Modify the standard search path to include other schemas
The process of creating a schema requires you grant the CREATE ON DATABASE privilege to the user as the postgres user. The initial grant of the create privilege requires the postgres superuser’s privileges. That means you must connect as the postgres user, like:
Then, as the postgres superuser, you use the following syntax to grant the create privilege to the student user on the videodb database:
GRANT CREATE ON DATABASE videodb TO student;
After granting the create privilege, you should exit the postgres superuser’s account, like
Now, you should connect as the student user to the videodb database (syntax introduced earlier but provided again below).
As the student user, create the app schema with the following syntax:
Then, you can query the result as follows:
SELECT * FROM pg_catalog.pg_namespace ORDER BY nspname;
You should see the following:
oid | nspname | nspowner | nspacl -------+--------------------+----------+------------------------------------- 16399 | app | 16398 | 13388 | information_schema | 10 | {postgres=UC/postgres,=U/postgres} 11 | pg_catalog | 10 | {postgres=UC/postgres,=U/postgres} 99 | pg_toast | 10 | 2200 | public | 10 | {postgres=UC/postgres,=UC/postgres} (5 rows)
If you create a table without a schema name, it is automatically placed in the public schema. That means any attempt to describe the table with the d command line option returns without prepending the schema name returns an error, however, this is only true when you are using the default search parameter.
Let’s create a revision_history table in the app schema with a script file. A script file is a set of related SQL commands, like the following example that suppresses notices, drops any pre-existing revision_history table, and create the revision_history table.
-- Set client messages to warning or error, which means any -- notice associated with the if exists clause is suppressed. SET client_min_messages TO warning; -- Conditionally drop an existing revision_history table in -- the app schema. DROP TABLE IF EXISTS revision_history; -- Create a revision_history table. CREATE TABLE app.revision_history ( revision_history_id serial , session_id VARCHAR , table_name VARCHAR , revision_id INTEGER );
You can run a script file by using a relative or absolute file name. An absolute file name includes a full path from a Windows logical driver letter, like C: or a Linux mount point. A relative file name is simply the file name.
If you want to use a relative file name, you must first navigate to the directory where you have saved the file first. This directory becomes your local drive and allows you call any file in it from the psql command prompt by using only its file name.
You should connect as the student user to the videodb database. The i command lets you run a file, assuming you put the preceding script file into a revision_history file in your local directory.
If you try to describe the revision_history table with the d command line option, like
It will show the following:
Did not find any relation named "revision_history".
That’s because there is no revision_history table in the public schema and the default search path only includes the public schema.
You can show the search path with the following:
It should return the following, which is a schema that shares the user’s name and public.
search_path ----------------- "$user", public (1 row)
You reset the search path as follows:
SET search_path TO app, "$user", public;
After you set the search_path, an attempt to describe the table will work because it searches for the table in the app and public schema. That means the following command:
Shows:
Table "app.revision_history" Column | Type | Collation | Nullable | Default ---------------------+-------------------+-----------+----------+--------------------------------------------------------------- revision_history_id | integer | | not null | nextval('revision_history_revision_history_id_seq'::regclass) session_id | character varying | | | table_name | character varying | | | revision_id | integer | | |
- Connect as student to videodb:
As shown in Step #4 above, you can now connect and use to the videodb as the student user with the following syntax:
psql -d videodb -U student -W
If you did everything correctly, you should see the following after correctly providing the student password for the student user:
Password: psql (14.1) WARNING: Console code page (437) differs from Windows code page (1252) 8-bit characters might not work correctly. See psql reference page "Notes for Windows users" for details. Type "help" for help. videodb=>
After connecting to the videodb database, you can query the current database, like
SELECT current_database();
It should return the following:
current_database ------------------ videodb (1 row)
This has shown you how to create a videodb tablespace, a videodb database, a dba role, a student user, an app schema, and connect to your new videodb database as the student user. As always, I hope it lets you get a lot down with little effort and avoiding pages and pages of documentation.
Permalink
Cannot retrieve contributors at this time
Windows
Keep an eye on version numbers and remember to update them if you use another version!
Preparation
- Familiarize yourself with the very basics of the Windows command line1 (5′): https://www.makeuseof.com/tag/a-beginners-guide-to-the-windows-command-line/
- Don’t forget to re-open your shell whenever you update any system environment variables.
- Keep in mind to change the
/
in file paths toaccordingly
1. You might want to use a better console emulator at some point (e.g., cmder or Hyper).
PostgreSQL
-
Install PostgreSQL: Tutorial or Video
- Download: https://www.enterprisedb.com/downloads/postgres-postgresql-downloads
-
Add
C:Program FilesPostgreSQL13bin;
to the PATH (computer => properties => advanced system settings=> Environment Variables => System Variables) as described here -
Run
setx PGCLIENTENCODING UTF8
in your command line -
Start psql shell:
psql postgres postgres
(psql dbname username
) -
Check for any startup warnings. If you see a warning that the console code page differs from Windows code page:
psql (10.2) WARNING: Console code page (437) differs from Windows code page (1252) 8-bit characters might not work correctly. See psql reference page "Notes for Windows users" for details. Type "help" for help. postgres=#
- Change the active console code page respectively using
chcp 1252
(or 65001 for UTF-8)
- Change the active console code page respectively using
-
Check whether
l
lists all your current databases
Start the server
How do I start the PostgreSQL server (e.g., after re-booting)?
set PGDATA=C:Program FilesPostgreSQL13data pg_ctl start
Create postgres superuser
How can I create a postgres superuser if none exists?
- [psql]
CREATE USER postgres WITH SUPERUSER PASSWORD 'postgres'
MongoDB
Server
- Install MongoDB: short (4′) or long (12′) tutorial
- Download the Community Server: https://www.mongodb.com/download-center/community
- Run the installer (choose Complete, you can uncheck the Compass GUI if you wanna speed up installation)
- Setup system variable
MONGO_HOME
pointing to your installation (e.g.,C:Program FilesMongoDBServer4.4
) - Add
%MONGO_HOME%bin
to your Path (don’t forget to click OK, OK)
- Create a data directory:
mkdir -p C:datadb
- Run the daemon
mongod
and keep this shell open (it should finally showNETWORK [initandlisten] waiting for connections on port 27017
) - Start the mongo shell in a new shell:
mongo
- Check whether
show dbs
lists all your current databases (should list admin and local)
Tools
- Download and run the «Database Tools» installer: https://www.mongodb.com/try/download/database-tools
- Add the installed binary directory to your Path (e.g. by default this would be
C:Program FilesMongoDBTools100bin
) - Open a new command prompt and call
mongoimport --version
, if it returns no errors installation was succesful
Detailed steps on how to add a directory to your PATH can be found here.
I have installed two versions of Postgresql, 8.4 and 9.1. When I try to run psql
it only picks up the previous psql
version. For example, when I run the following line to connect to the database, ax_data
:
C:Program Files (x86)PostgreSQL9.1bin>psql ax_data
Password:
psql (9.1.2, server 8.4.8)
WARNING: psql version 9.1, server version 8.4.
Some psql features might not work.
WARNING: Console code page (437) differs from Windows code page (1252)
8-bit characters might not work correctly. See psql reference
page "Notes for Windows users" for details.
Type "help" for help.
ax_data=
It is not finding the more recent psql installation. When using pgAdmin
, if I click on psql
a small command window pops up, but when I type commands in nothing is happening. I’m not very experienced with Postgresql so I could have made some basic mistake somewhere along the way. Any thoughts on what I could be doing wrong?
EDIT:
I am able to login using:
C:>C:"Program Files (x86)"PostgreSQL9.1binpsql.exe -p 5434 -U postgres
psql (9.1.2)
WARNING: Console code page (437) differs from Windows code page (1252)
8-bit characters might not work correctly. See psql reference
page "Notes for Windows users" for details.
Type "help" for help.
postgres=# LS
postgres-#
but none of the commands seem to work. For example, whenever I type anything in after the prompt, there is no response.