I tried to run simple SQL command:
select * from site_adzone;
and I got this error
ERROR: permission denied for relation site_adzone
What could be the problem here?
I tried also to do select for other tables and got same issue. I also tried to do this:
GRANT ALL PRIVILEGES ON DATABASE jerry to tom;
but I got this response from console
WARNING: no privileges were granted for «jerry»
Does anyone have any idea what can be wrong?
![]()
Dale K
24.3k15 gold badges43 silver badges71 bronze badges
asked Mar 20, 2013 at 10:00
![]()
5
GRANT on the database is not what you need. Grant on the tables directly.
Granting privileges on the database mostly is used to grant or revoke connect privileges. This allows you to specify who may do stuff in the database if they have sufficient other permissions.
You want instead:
GRANT ALL PRIVILEGES ON TABLE side_adzone TO jerry;
This will take care of this issue.
answered Mar 20, 2013 at 11:41
![]()
Chris TraversChris Travers
24.9k6 gold badges63 silver badges181 bronze badges
15
Posting Ron E answer for grant privileges on all tables as it might be useful to others.
GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO jerry;
3
Connect to the right database first, then run:
GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO jerry;
![]()
BrDaHa
4,8695 gold badges33 silver badges47 bronze badges
answered Jan 1, 2017 at 20:00
user2757813user2757813
1,2491 gold badge8 silver badges3 bronze badges
3
GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public to jerry;
GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public to jerry;
GRANT ALL PRIVILEGES ON ALL FUNCTIONS IN SCHEMA public to jerry;
answered Jul 18, 2018 at 10:36
MeirzaMeirza
1,26010 silver badges15 bronze badges
1
1st and important step is connect to your db:
psql -d yourDBName
2 step, grant privileges
GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO userName;
answered May 2, 2018 at 13:05
zondzond
1,3991 gold badge20 silver badges34 bronze badges
0
To grant permissions to all of the existing tables in the schema use:
GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA <schema> TO <role>
To specify default permissions that will be applied to future tables use:
ALTER DEFAULT PRIVILEGES IN SCHEMA <schema>
GRANT <privileges> ON TABLES TO <role>;
e.g.
ALTER DEFAULT PRIVILEGES IN SCHEMA public
GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO admin;
If you use SERIAL or BIGSERIAL columns then you will probably want to do the same for SEQUENCES, or else your INSERT will fail (Postgres 10’s IDENTITY doesn’t suffer from that problem, and is recommended over the SERIAL types), i.e.
ALTER DEFAULT PRIVILEGES IN SCHEMA <schema> GRANT ALL ON SEQUENCES TO <role>;
See also my answer to PostgreSQL Permissions for Web App for more details and a reusable script.
Ref:
GRANT
ALTER DEFAULT PRIVILEGES
answered Oct 9, 2017 at 18:31
![]()
isapirisapir
19.6k12 gold badges110 silver badges112 bronze badges
2
This frequently happens when you create a table as user postgres and then try to access it as an ordinary user.
In this case it is best to log in as the postgres user and change the ownership of the table with the command:
alter table <TABLE> owner to <USER>;
answered May 22, 2018 at 4:13
BruceBruce
4093 silver badges6 bronze badges
1
Make sure you log into psql as the owner of the tables.
to find out who own the tables use dt
psql -h CONNECTION_STRING DBNAME -U OWNER_OF_THE_TABLES
then you can run the GRANTS
answered May 15, 2018 at 17:30
Brian McCallBrian McCall
1,7131 gold badge16 silver badges31 bronze badges
You should:
- connect to the database by means of the DBeaver with postgres user
- on the left tab open your database
- open Roles tab/dropdown
- select your user
- on the right tab press ‘Permissions tab’
- press your schema tab
- press tables tab/dropdown
- select all tables
- select all required permissions checkboxes (or press Grant All)
- press Save
answered Mar 19, 2020 at 8:03
happydmitryhappydmitry
1012 silver badges5 bronze badges
As you are looking for select permissions, I would suggest you to grant only select rather than all privileges. You can do this by:
GRANT SELECT ON <table> TO <role>;
answered Jan 8, 2020 at 15:33
![]()
I ran into this after switching a user to another user that also needed to have the same rights, I kept getting the error: «must be owner of relation xx»
fix was to simply give all rights from old user to new user:
postgres-# Grant <old user> to <new user>;
answered Aug 20, 2021 at 19:02
Jens TimmermanJens Timmerman
8,9371 gold badge39 silver badges47 bronze badges
For PostgreSQL. On bash terminal, run this:
psql db_name -c "GRANT ALL ON ALL TABLES IN SCHEMA public to db_user;"
psql db_name -c "GRANT ALL ON ALL SEQUENCES IN SCHEMA public to db_user;"
psql db_name -c "GRANT ALL ON ALL FUNCTIONS IN SCHEMA public to db_user;"
answered Nov 18, 2022 at 11:00
![]()
DEFAULT PRIVILEGES do not change permissions for existing objects. They are the default privileges for newly created objects and only for the particular role they belong to. If you do not specify the role when running ALTER DEFAULT PRIVILEGES, it defaults to the current role (when executing the ALTER DEFAULT PRIVILEGES statement.
Also, since you are using a serial column, which creates a SEQUENCE, you’ll want to set default privileges for sequences as well.
Run this on the user you create objects with, before you run the CREATE command:
ALTER DEFAULT PRIVILEGES [ FOR ROLE my_create_role] GRANT ALL ON TABLES TO bspu;
ALTER DEFAULT PRIVILEGES [ FOR ROLE my_create_role] GRANT ALL ON SEQUENCES TO bspu;
A word of caution for pgAdmin users. There is a bug in all versions of pgAdmin III and pgAdmin4 (including v5.3). The reverse engineered SQL script for the database or schema nodes displays DEFAULT PRIVILEGES ignoring the owning user and is therefore incorrect in certain situations. I reported the bug (repeatedly), but the project encountered difficulties fixing it. pgAdmin III was discontinued in favor of pgAdmin4. The bug is still there in pgAdmin4.
For existing objects you may also be interested in this «batch» form of the GRANT command:
GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO bspu;
GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public TO bspu;
More under this related question on SO:
- Grant all on a specific schema in the db to a group role in PostgreSQL
Ever needed to create a bunch of tables for a newly created user to access in PostgreSQL and see the following error message pop up, ‘permission denied for relation some_table_name’? You are in luck, in this tutorial, I am going to guide you guys through it to make the error message goes away.
Let me give you guys an example on how this error message might occur (at least this is how I found out),
Check out this following sql file,
CREATE DATABASE "database";
CREATE USER someuser WITH PASSWORD 'securepassword';
GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO someuser;
CREATE TABLE "some_table_name"(
"id" int NOT NULL,
"data" text NOT NULL
);
INSERT INTO "some_table_name" values(0, "some text");
source code hosted on GitHub
As one can imagine, when you login as ‘someuser’ and try to access the table with the SELECT query, you will likely see the error message pop up. This is because you granted all privileges to the someuser on all tables but no table has been created yet which means that the query has no effect at all. To fix this, you can simply move that GRANT ALL.. query all the way down to the bottom (the point where you created all the necessary table for your database). It should look something similar to the following.
Your someuser should now have access to the table,
CREATE DATABASE "database";
CREATE USER someuser WITH PASSWORD 'securepassword';
CREATE TABLE "some_table_name"(
"id" int NOT NULL,
"data" text NOT NULL
);
INSERT INTO "some_table_name" values(0, "some text");
GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO someuser;
source code hosted on GitHub
As a result, the order is very important. Just remember to do that next time haha!
Tada. This is a fairly short tutorial. Hope that solve your problem. Let me know if it didn’t. I will be happy to help as always.
Wrapping Up
Hopefully you enjoyed this short tutorial. Let me know if this helps you. Thank you for reading!
Resources
I’ll try to keep this list current and up to date. If you know of a great resource you’d like to share or notice a broken link, please let us know.
Getting started
- permission denied for relation.

Author
PoAn (Baron) Chen
Software Engineer at Microsoft. Graduated from @uvic. Previously worked at @illumina, @ACDSee, @AEHelp and @AcePersonnel1. My words are my own.
I’m trying to import a schema-dump into PostgreSQL with ‘psql -U username -W dbname < migrations/schema.psql’, the Schema is imported partly, but the console throws errors like «ERROR: permission denied for relation table_name» and «ERROR: relation table_name does not exist».
I’ve created the database like this: «createdb -O username dbname»
There are only 7 tables to import, and it breaks with just importing 3 of them.
Anybody a hint, what to do?
asked Aug 18, 2010 at 12:52
![]()
1
If the backup was in the «custom» format (-Fc), you could use pg_restore instead so you can tell it to not apply ownership changes:
pg_restore -U username -W --no-owner --dbname=dbname migrations/schema.psql
All the objects will created with «username» as the owner.
Barring that, try to grep out the ALTER OWNER and SET SESSION AUTHORIZATION commands into new file (or through send grep output via pipe to psql). Those commands should always be on a single line in the plain-text output format.
answered Aug 18, 2010 at 17:54
Matthew WoodMatthew Wood
15.6k5 gold badges46 silver badges35 bronze badges
2
Sometimes this kind of problem is caused by case-sensitivity issues. PostgreSQL folds to lowercase all unquoted identifiers; if the tables are created with quoted names containing uppercase letters, later commands that don’t quote the names may fail to find the table.
The permission errors may be related to the same thing, or it may be something else entirely. Hard to tell without seeing the failing commands.
answered Aug 18, 2010 at 17:54
![]()
alvherrealvherre
2,48920 silver badges22 bronze badges
As I work on my websites, I get that error all the time because I’ll be creating a table as me, table that needs to be accessed by the Apache/PHP user that connects later.
There is a table named pg_class that defines your tables. This includes a column named relowner. Changing that with the correct number will give you the correct ownership.
I have details on this page:
http://linux.m2osw.com/table_owner_in_postgresql
The ALTER OWNER … may be a better solution that does the same thing, although in older versions of PostgreSQL it did not exist!
answered Sep 13, 2012 at 17:07
Alexis WilkeAlexis Wilke
18.3k10 gold badges79 silver badges143 bronze badges
3
I’m trying to import a schema-dump into PostgreSQL with ‘psql -U username -W dbname < migrations/schema.psql’, the Schema is imported partly, but the console throws errors like «ERROR: permission denied for relation table_name» and «ERROR: relation table_name does not exist».
I’ve created the database like this: «createdb -O username dbname»
There are only 7 tables to import, and it breaks with just importing 3 of them.
Anybody a hint, what to do?
asked Aug 18, 2010 at 12:52
![]()
1
If the backup was in the «custom» format (-Fc), you could use pg_restore instead so you can tell it to not apply ownership changes:
pg_restore -U username -W --no-owner --dbname=dbname migrations/schema.psql
All the objects will created with «username» as the owner.
Barring that, try to grep out the ALTER OWNER and SET SESSION AUTHORIZATION commands into new file (or through send grep output via pipe to psql). Those commands should always be on a single line in the plain-text output format.
answered Aug 18, 2010 at 17:54
Matthew WoodMatthew Wood
15.6k5 gold badges46 silver badges35 bronze badges
2
Sometimes this kind of problem is caused by case-sensitivity issues. PostgreSQL folds to lowercase all unquoted identifiers; if the tables are created with quoted names containing uppercase letters, later commands that don’t quote the names may fail to find the table.
The permission errors may be related to the same thing, or it may be something else entirely. Hard to tell without seeing the failing commands.
answered Aug 18, 2010 at 17:54
![]()
alvherrealvherre
2,48920 silver badges22 bronze badges
As I work on my websites, I get that error all the time because I’ll be creating a table as me, table that needs to be accessed by the Apache/PHP user that connects later.
There is a table named pg_class that defines your tables. This includes a column named relowner. Changing that with the correct number will give you the correct ownership.
I have details on this page:
http://linux.m2osw.com/table_owner_in_postgresql
The ALTER OWNER … may be a better solution that does the same thing, although in older versions of PostgreSQL it did not exist!
answered Sep 13, 2012 at 17:07
Alexis WilkeAlexis Wilke
18.3k10 gold badges79 silver badges143 bronze badges
3
Postgres databases can handle complex website functions easily.
But, what if you get a permission denied error for database Postgres, frustrating right?
This website error occurs due to the lack of database privileges like CONNECT, CREATE, etc.
At Bobcares, we often receive requests to fix the permission denied error as part of our Server Management Services.
Today, let’s discuss this error in detail and see how our Support Engineers fix it for our customers.
How to fix Permission denied for database Postgres?
Postgres is a powerful database that comes up with vast features to help developers.
But, it often shows up permission denied error. Finding the exact reason for this error can be quite tricky.
The core reason for the permission denied error in Postgres is the lack of several privileges.
Now, let’s see the main causes of this error and its respective fixes.
1. Missing CONNECT privilege
Recently, one of our customers approached us with a permission denied error in the Postgres. He tried to log in to his database using psql command,
psql userdb user --password
Here, userdb and user are the database name and username respectively.
But, after entering the password, he got the following error,
psql: FATAL: permission denied for database "userdb"
DETAIL: User does not have CONNECT privilege.
Our Support Engineers checked and found an error with CONNECT privilege.
Usually, the CONNECT privilege allows the user to connect to a database. And we check this privilege at the connection startup.
So, to grant CONNECT privilege, we followed the command,
GRANT CONNECT ON DATABASE userdb TO user ;
This resolved the error effectively.
2. Grant privileges to a new user
In some cases, users try to grant all privileges of a database to a new Postgres user other than the owner. For that, we use the command,
GRANT ALL PRIVILEGES ON DATABASE userdb TO new_user;
But, when we log in as the new user and try to read data from the table, it ends up showing the error,
ERROR: permission denied for relation table_name
This is because GRANT ALL PRIVILEGES ON DATABASE grants CREATE, CONNECT and TEMPORARY privileges on a database to a user.
But, none of these privileges permit the user to read data from the table.
Therefore, it requires the SELECT privilege. We resolve this permission denied error using the command.
GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO new_user;
The new_user was then able to read data from the table.
Similarly, we can also resolve the permission denied error by setting DEFAULT privileges to the user.
Here, we use the ALTER DEFAULT PRIVILEGES command to define the default access privileges.
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON TABLES TO new_user;
This will be specific to the schema specified in the command. Also, to apply it to the entire database, we use the command,
ALTER DEFAULT PRIVILEGES GRANT ALL ON TABLES TO new_user;
3. Missing Postgres user
In the control panel based servers, permission denied error can happen due to missing users as well. For instance, in control panels like Plesk, if the password for PostgreSQL user postgres does not correspond password in the Plesk database, it shows up errors.
Therefore, to fix it, we update the PostgreSQL user with the proper password and sync it with the Plesk DB. And confirm it from Plesk panel at:

[Stuck with permission denied error in Postgres?- We’ll help you.]
Conclusion
In short, the permission denied for database Postgres occurs due to the lack of certain privileges like CONNECT, CREATE, DEFAULT and so on. In today’s writeup, we discussed how our Support Engineers fix Postgres privileges for our customers.
PREVENT YOUR SERVER FROM CRASHING!
Never again lose customers to poor server speed! Let us help you.
Our server experts will monitor & maintain your server 24/7 so that it remains lightning fast and secure.
GET STARTED
var google_conversion_label = «owonCMyG5nEQ0aD71QM»;
5 ответов
Вот полное решение для PostgreSQL 9+, недавно обновленное.
CREATE USER readonly WITH ENCRYPTED PASSWORD 'readonly';
GRANT USAGE ON SCHEMA public to readonly;
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO readonly;
-- repeat code below for each database:
GRANT CONNECT ON DATABASE foo to readonly;
c foo
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON TABLES TO readonly; --- this grants privileges on new tables generated in new database "foo"
GRANT USAGE ON SCHEMA public to readonly;
GRANT SELECT ON ALL SEQUENCES IN SCHEMA public TO readonly;
GRANT SELECT ON ALL TABLES IN SCHEMA public TO readonly;
Благодаря http://jamie.curle.io/creating-a-read-only-user-in-postgres/ для нескольких важных аспектов
Если кто-то найдет более короткий код и, желательно, тот, который способен выполнить это для всех существующих баз данных, добавляет дополнительные преимущества.
sorin
22 нояб. 2012, в 12:23
Поделиться
Попробуйте добавить
GRANT USAGE ON SCHEMA public to readonly;
Вероятно, вы пропустили, что у вас должны быть разрешения на использование схем в этой схеме.
sufleR
21 нояб. 2012, в 18:36
Поделиться
Это сработало для меня:
Проверьте текущую роль, в которую вы вошли, используя:
SELECT CURRENT_USER, SESSION_USER;
Примечание. Он должен совпадать с владельцем схемы.
Схема | Имя | Тип | Владелец
——— + ——— + ——- + ———-
Если владелец отличается, то предоставите все гранты текущей роли пользователя из роли администратора:
GRANT ‘ROLE_OWNER’ для «ТЕКУЩЕГО РОЛИНАМА»;
Затем попробуйте выполнить запрос, он даст результат, так как теперь он имеет доступ ко всем отношениям.
Dhwani Shah
25 июнь 2015, в 01:01
Поделиться
Вы должны выполнить следующий запрос:
GRANT ALL ON TABLE mytable TO myuser;
Или, если ваша ошибка в представлении, возможно, у таблицы нет разрешения, поэтому вы должны выполнить следующий запрос:
GRANT ALL ON TABLE tbm_grupo TO myuser;
yesy
27 окт. 2015, в 18:09
Поделиться
убедитесь, что ваш пользователь имеет атрибуты своей роли. например:
postgres=# du
List of roles
Role name | Attributes | Member of
-----------+------------------------------------------------+-----------
flux | | {}
postgres | Superuser, Create role, Create DB, Replication | {}
после выполнения следующей команды:
postgres=# ALTER ROLE flux WITH Superuser;
ALTER ROLE
postgres=# du
List of roles
Role name | Attributes | Member of
-----------+------------------------------------------------+-----------
flux | Superuser | {}
postgres | Superuser, Create role, Create DB, Replication | {}
он исправил проблему.
см. учебник для ролей и всего здесь: https://www.digitalocean.com/community/tutorials/how-to-use-roles-and-manage-grant-permissions-in-postgresql-on-a-vps—2
PuN1sh3r
16 июль 2015, в 07:31
Поделиться
Ещё вопросы
- 0angular typeahead $ viewValue не обновляется после переименования
- 0AngularJS и REST: выполнить действие DELETE, отправив массив из множества элементов для удаления
- 0Как изменить порядок внутри углового контроллера? Не используете orderBy в разметке?
- 1Android TextView.setText принудительно закрывается
- 0Эквивалент класса SslStream в C ++
- 1Как мне загрузить переменную ruby через Ajax и Javascript?
- 1Определите ожидаемое время выполнения агента SQL в течение периода
- 0Blurry Nav Bar при прокрутке
- 1ProgressDialog не обновляется после изменения конфигурации (ориентация становится горизонтальной)
- 0C ++ Попытка вернуть строку массива double (вроде)
- 1NInject, NHIbernate и ISession в области запроса
- 1Передайте ветку git в качестве параметра conda environment.yml для пакета pip
- 1Android — ScrollView внутри галереи
- 0использование функций класса c ++ string для создания «подстрок гена» из более длинной исходной строки Genome
- 0Сохраняйте входной контент в модальном режиме при закрытии и открывайте модальный с помощью другого контроллера
- 0Код ошибки MySQL (невозможно добавить или обновить дочернюю строку ..)
- 1Износ содержимого управляемых переменных
- 1Извлеките тело письма Outlook и адрес электронной почты получателя, используя python
- 1Как я могу установить максимальную высоту на ListView?
- 0strtok_s не был объявлен в этой области
- 1Здоровье противников не уменьшается, а ходы не переворачиваются
- 0Вычисления не могут быть выполнены путем передачи значения из двух разных подпрограмм в новую подпрограмму: Perl
- 1Как издеваться над readline.createInterface ()?
- 1Панды: 2 фрейма данных имеют разные формы, но не разные столбцы
- 0AngularJS: по умолчанию для элемента установлен класс
- 1openpyxl — добавление новых строк в файл Excel с существующей объединенной ячейкой
- 1Ошибка Catch 404 с XHR
- 0Изучение Ember.js — Как бы я это сделал?
- 1Стремительное выполнение в пользовательских оценках тензорного потока
- 1Почему мое затмение не может запустить виртуальное устройство Android, когда файлы там?
- 1Как я могу отформатировать строку из 10 цифр и 2 букв в yyyyMMddHHmm, а затем отформатировать ее в другую строку?
- 0Как показывать контент только на страницах с постоянными ссылками, на которых есть знак вопроса
- 0Как сделать отступ в элементе
- 0Каков наилучший метод для глобального var в функции / классе? PHP
- 1Как найти, используя директивы
- 0Проблемы с поворотами при конвертации BST (без рекурсии) в AVL
- 0Как я могу передать аргументы исполняемой программе, которую я вызываю (через CreateProcess)?
- 0Базовый класс не имеет конструктора по умолчанию, когда списки инициализации конструктора производного класса
- 1Попытка добавить значение к баллу в Optaplanner (используя Drools)
- 1Создать атрибут выбора формы из объекта JSON
- 1Как заставить WMQ Explorer работать с WMQ AMS
- 0ссылки в iframe / span не могут быть нажаты
- 0Невозможно установить значение области для поля выбора
- 0делая эти два div рядом друг с другом
- 0Конструктор Parent вызван в списке инициализации конструктора Child
- 1MediaPlayer на Android играет только часть моей песни 🙁
- 0Как добавить ng-модель в шаблон директивы в Angularjs
- 1Включить отключенный Spinner в Android
- 1Настройка цвета фона элемента списка теряет подсветку
- 0Возвращаемое значение для функции внутри функции slideUp ()
1. Предисловие
1.1 Обзор
Эта статья представляет несколько общих проблем PostgreSQL и начинается с явления, постепенно исследуя проблему, анализирует причину проблемы и дает решения.
Проблемы, описанные в этой статье, делятся на две категории: одна — проблема, которую PostgreSQL не может запустить, а другая — проблема, с которой некоторые объекты базы данных не могут быть доступны после запуска PostgreSQL.
1.2 Программная среда
Версия PostgreSQL, используемая в этой статье, составляет 9.2.
1.3 Некоторые согласованные сроки
Postgresql Путь установки: указывает путь установки платформы IVMS-8700 PostgreSQL, по умолчанию «D: Program Files Postgresql 9.6″ «» «»
Папка Bin: папка Bin под пути установки PostgreSQL.
Папка данных: папка данных в рамках пути установки PostgreSQL.
2. Вопросы и решения
2.1 PostgreSQL не может начать
Когда PostgreSQL не начался нормально, он снова потерпел неудачу в «Сервисе».
2.1.1 Портовая занятия
Сначала нам нужно определить, занят ли порт услуги. Порт по умолчанию службы PostgreSQL составляет 5432, поэтому мы выполняем следующие команды в командной строке
netstat -ano | find /i «5432»
Если найдено процесс использования порта 5432, это показывает, что занятие порта вызывает запуск услуги:

PID этого процесса — 2364. Вы хотите посмотреть, какой это процесс, вы можете выполнить:
tasklist | findstr «2364»
Результаты выполнения следующие:

Вы можете положить конец этому процессу на странице Processcess-Process или по следующей команде:
taskkill /f /pid 5432
2.1.2 could not open control file “global/pg_control”:Permission denied
Если порт не занят, то вы можете его использоватьPostgreSQLНативная команда запускает это.
ВойтиpostgresqlПод пути установки bin Папка, откройте командную строку здесь и выполните следующую команду:
.pg_ctl start -D ..data
Если программа сообщает о следующих ошибках:
ERROR: could not open control file “global/pg_control”: Permission denied

Он показывает, что текущие пользователи операционной системы теряют авторитет папки данных и ее контента.
Ниже приведено решение:
1. Во -первых, введите путь установки PostgreSQL, справа -щелкните папку данных, нажмите на атрибуты -Security -Editor, вы можете увидеть разрешения всех пользователей или групп пользователей.

2. Убедитесь, что система и администратор имеют «полное управление» разрешения. Пользовательская группа пользователей имеет только три типа разрешений: «чтение и выполнение», «Список содержимого папки» и «чтение». Когда база данных предлагает «недостаточные разрешения», следует добавлять «модификацию» и «написание».

3. Сохраните и попробуйте снова выступить под папкой бина:
.pg_ctl start -D ..data
Обратите внимание, может ли база данных PostgreSQL начать.
2.1.3 could not locate a valid checkpoint record
Если база данных активирована, ее предложено «запустить процесс сервера» и быть успешным в течение долгого времени. Как показано на рисунке ниже, вам необходимо проверить журнал запуска базы данных. Они расположены в PG_LOG в папке данных Анкет

Откройте журнал запуска базы данных, когда возникает проблема, и проверьте информацию.
Если в журнале есть информация, аналогичная следующим черным телам, это означает, что журнал до -записи (Wal (Wal, также известный как журнал транзакций) в базе данных PostgreSQL поврежден:
LOG: could not open file «pg_xlog/0000000100000000000000E7» (log file 0, segment 231): No such file or directory
LOG: invalid primary checkpoint record
LOG: could not open file «pg_xlog/0000000100000000000000E7» (log file 0, segment 231): No such file or directory
LOG: invalid secondary checkpoint record
PANIC: could not locate a valid checkpoint record
Решение заключается в следующем:
Введите папку Bin, откройте командную строку здесь и выполните следующую команду:
.pg_resetxlog.exe -f ..data
После того, как журнал будет сброшен, попробуйте запустить базу данных.
2.1.4 Описание идентификатора события 0 из источника PostgreSQL не может быть найдено.
Если приведенный выше метод не решает проблему, то нам нужно ввести диспетчер событий, чтобы увидеть, есть ли какой -либо журнал ошибок:
В случае применения журнала зрителей визиторов, посмотрите, есть ли следующие ошибки:
Невозможно найти источник PostgreSQL мероприятие ID 0 описание. Не установлен на локальном компьютере, который вызвал этот инцидент,Или установка повреждена. Вы можете установить или восстановить компоненты на локальном компьютере.

Если такая информация появляется, это означает, что программное обеспечение PostgreSQL было повреждено и должно быть переустановлено. Тем не менее, файл данных не обязательно поврежден, поэтому, если в последний раз, когда он резервен, база данных сгенерировала очень важные данные (например, информация о счетах), вы должны скопировать папку данных в другой каталог, а затем переустановить платформу и и Восстановите данные папки данных.
2.1.5 Could not read from file «pg_clog/000E» at offset 172032
Есть также необычная ситуация. Если в журнале появляется следующая информация:
ERROR: could not access status of transaction 710708
DETAIL: Could not read from file «pg_clog/000E» at offset 172032: No error.
Это находится вdataПод папкойpg_clogИмя 000E Файл журнала был потерян.
Решение заключается в следующем:
существуетlinux В операционной системе выполните следующие команды:
dd if=/dev/zero of=/root/000E bs=256k count=1
Или установите DD в Windows, а затем выполните:
dd if=/dev/zero of=D:00E bs=256k count=1
Затем скопируйте созданный файл 000e вdataПод папкойpg_clog середина.
2.2 После запуска базы данных некоторые базы данных или таблицы нельзя получить
В этом случае вам нужно войти dataПод папкойpg_logПапка, постоянно проверяйте беговые журналы.
2.2.1 permission denied for relation tb_door
Если в журнале есть аналогичная информация, это показывает, что у текущего пользователя доступа нет таблицыtb_doorНекоторые разрешения:
ERROR: permission denied for relation tb_door
Если вы хотите текущего пользователя (чтобыmy_userНапример) наличие конкретных разрешений на доступ (на основеВыберите, вставьте, обновите, удаляйте в качестве примера), Вы можете решить это так:
- Первый проходpostgresПользователь или владетьСоответствующие разрешения TB_DOOR, то есть журналы пользователя в базе данных, которая предоставила разрешения;
- Выполнить следующие команды, чтобы предоставить разрешения пользователям:grant SELECT,INSERT,UPDATE,DELETE on tb_door to my_user
2.2.2 invalid page header in block 120 of relation base/272816/309624
Если в журнале появляется следующая информация:
ERROR: invalid page header in block 120 of relation base/272816/309624
Это означает, что файл таблицы данных поврежден. Обычно это вызвано ненормальным сбоем энергии или недоразумением.Здесь «272816» является идентификатором объекта (OID) базы данных проблемы.
Если количество поврежденных таблиц и количество поврежденных страниц невелико, мы можем восстановить целое за счет жертвоприношения части данных; если количество поврежденных таблиц слишком велика или потеря данных очень важна, мы Нужно восстановить данные из резервной копии.
Когда количество поврежденных таблиц и количество поврежденных страниц невелико, решение следующим образом:
- Определите базу данных проблемы. Подключите любую базу данных и выполните оператор SQL ниже:
select datname from pg_database where oid = 272816;
Результаты запроса следующие:
testdb
Это означает, что название базы данных проблемы является TestDB
2. Найдите поврежденный объект базы данных. База данных задачи подключения выполните следующее оператор SQL:
select relname,relkind from pg_class where relfilenode = 309624
Если relkind = r в результатах запроса, таблица повреждена.
Например:
tb_door, r
Relname = tb_door Это означает, что поврежденная таблица — tb_door.
Если relkind = i в результатах запроса, это индекс, который поврежден.
Например:
dept_number_index, i
или же:
tb_dept_pkey, i
Следует отметить, что ущерб может быть обычным индексами или основным или уникальным ключом. Если имя индекса является «_pkey», оно, вероятно, будет принадлежать первичному ключу, и имя содержит «_key», оно может принадлежать к уникальному ключу.
Также необходимо обратить на это внимание. Предварительным условием для исправления таблицы/индекса является то, что поврежденная таблица — это таблица/индекс, созданная приложением, а не системная таблица PostgreSQL и индекс, созданный на нем. Если системная таблица/индекс, созданный на нем, повреждены, база данных необходимо восстановить из резервной копии. Чтобы определить, является ли таблица системной таблицей, самый простой способ: если имя таблицы «pg_», это означает, что это системная таблица.
чаевые
Значения pgclass.relkind являются следующими:
R: представляет обычную таблицу (обычная таблица);
I: указывает на индекс (индекс);
S: указывает последовательность (последовательность);
V: представляет представление (View);
M: укажите материализованный вид (материализованный вид);
C: представляет композитный тип (композитный тип);
T: представляет Toast Table (Toast Table);
F: представляет иностранную таблицу (внешняя таблица)
3. Исправьте поврежденный объект базы данных. Поврежденная база данных происходит для выполнения команды ремонта.
Если таблица повреждена, возьмите TB_DOOR в качестве примера, затем выполните следующие команды, чтобы завершить ремонт:
set zero_damaged_pages = on;
vacuum full tb_door;
reindex table tb_door;
Если поврежденный является обычным индексом, возьмите dept_number_index в качестве примера, затем выполните его по порядку:
set zero_damaged_pages = on;
reindex index dept_number_index;
Если урон является основным ключом или уникальным ключом, сначала вам нужно найти таблицу, которую он находится. TB_DEPT_PKEY В качестве примера:
Select tablename,indexname from pg_indexes where indexname = ‘tb_dept_pkey’;
результат поиска:
tb_dept, tb_dept_pkey
Затем получите определение индекса:
select pg_get_constraintdef((select oid from pg_constraint where conname = ‘ tb_dept_pkey ‘));
результат поиска:
PRIMARY KEY (dept_id)
Затем повторно измените это ограничение:
Alter table drop constriant tb_dept_pkey;
Alter table add constraint tb_dept_pkey PRIMARY KEY (dept_id);
2.2.3 could not read block 190 in file «base/272816/309624»
Решение и метод этой проблемы2.2.2 Проблема фестиваля точно такая же.
2.2.4 could not open file «base/272816/379923»: No such file or directory
Если в журнале появляется следующая информация:
2019-01-21 14:28:03 HKT ERROR: could not open file «base/272816/379923″: No such file or directory
Объяснять,oidза272816В базе данных,oidза379923Файл, соответствующий таблице, удален.
Решение заключается в следующем:
1. Сначала судите, какая база данных произошла. Подключите любую базу данных и выполните следующим образомsql:
select datname from pg_database where oid = 272816
Результаты запроса следующие:
testdb
2. Восстановите базу данных из резервной копии.