Меню

1с ошибка субд 42p01

Ошибка — 42p01 error relation pg_temp does not exist

Модератор: Дмитрий Юхтимовский

Ошибка — 42p01 error relation pg_temp does not exist

Windows 7 PRO x64
Postgres 9.6.3 1C x64
1C 8.3.10.2667 x64

Первый запуск теста дает результат. Тут главное не оценка производительности, а то что оба теста при первом запуске завершаются без ошибки (скрин_1).

При втором, третьем и последующем нажатии «Выполнить тест» получаю ошибку (скрин_2)
42p01 error relation pg_temp. does not exist

Вопрос: в какой «стороне» искать причину возникновения ошибки?

Вложения
скрин_2.png
скрин_2.png (15.75 KiB) Просмотров: 3323
скрин_1.png
скрин_1.png (48.45 KiB) Просмотров: 3323
yazuzenko@t-sputnik.ru
 
Сообщений: 2
Зарегистрирован: 21 ноя 2017, 10:17


Re: Ошибка — 42p01 error relation pg_temp does not exist

Сообщение yazuzenko@t-sputnik.ru » 22 ноя 2017, 08:46

1. Нужно установить 1С 8.3.11.2867 х64?
2. Удалить/создать базу в консоли и повторить несколько раз тест?
3. Достаточно использовать Postgres 9.6.3-3.1С? Или нужно повышать до 9.6.5-4.1С?

yazuzenko@t-sputnik.ru
 
Сообщений: 2
Зарегистрирован: 21 ноя 2017, 10:17

видимо да

Сообщение Гилёв Вячеслав » 22 ноя 2017, 18:01

Вам придется это сделать раньше чем мы это сделаем
у нас нет в планах 8.3.11 ставить в ближайшее время, проверить негде
сборку Вам надо ставить только отсюда

https://postgrespro.ru/products/1c_build

, иначе все не имеет смысла

Гилёв Вячеслав
 
Сообщений: 2543
Зарегистрирован: 11 фев 2013, 15:40
Откуда: Россия, Москва


Вернуться в Осуждаем проблемы производительности 1с

Кто сейчас на форуме

Сейчас этот форум просматривают: Yandex [Bot] и гости: 1

What you had originally was a correct syntax — for tables, not for schemas. As you did not have a table (dubbed ‘relation’ in the error message), it threw the not-found error.

I see you’ve already noticed this — I believe there is no better way of learning than to fix our own mistakes 😉

But there is something more. What you are doing above is too much on one hand, and not enough on the other.

Running the script, you

  1. create a schema
  2. create a role
  3. grant SELECT on all tables in the schema created in (1.) to this new role_
  4. and, finally, grant all privileges (CREATE and USAGE) on the new schema to the new role

The problem lies within point (3.) You granted privileges on tables in replays — but there are no tables in there! There might be some in the future, but at this point the schema is completely empty. This way, the GRANT in (3.) does nothing — this way you are doing too much.

But what about the future tables?

There is a command for covering them: ALTER DEFAULT PRIVILEGES. It applies not only to tables, but:

Currently [as of 9.4], only the privileges for tables (including views and foreign tables), sequences, functions, and types (including domains) can be altered.

There is one important limitation, too:

You can change default privileges only for objects that will be created by yourself or by roles that you are a member of.

This means that a table created by alice, who is neither you nor a role than you are a member of (can be checked, for example, by using du in psql), will not take the prescribed access rights. The optional FOR ROLE clause is used for specifying the ‘table creator’ role you are a member of. In many cases, this implies it is a good idea to create all database objects using the same role — like mydatabase_owner.

A small example to show this at work:

CREATE ROLE test_owner; -- cannot log in
CREATE SCHEMA replays AUTHORIZATION test_owner;
GRANT ALL ON SCHEMA replays TO test_owner;

SET ROLE TO test_owner; -- here we change the context, 
                        -- so that the next statement is issued as the owner role

ALTER DEFAULT PRIVILEGES IN SCHEMA replays GRANT SELECT ON TABLES TO alice;

CREATE TABLE replays.replayer (r_id serial PRIMARY KEY);

RESET ROLE; -- changing the context back to the original role

CREATE TABLE replays.replay_event (re_id serial PRIMARY KEY);

-- and now compare the two

dp replays.replayer
                                   Access privileges
 Schema  │   Name   │ Type  │       Access privileges       │ Column access privileges 
─────────┼──────────┼───────┼───────────────────────────────┼──────────────────────────
 replays │ replayer │ table │ alice=r/test_owner           ↵│ 
         │          │       │ test_owner=arwdDxt/test_owner │ 

dp replays.replay_event
                               Access privileges
 Schema  │     Name     │ Type  │ Access privileges │ Column access privileges 
─────────┼──────────────┼───────┼───────────────────┼──────────────────────────
 replays │ replay_event │ table │                   │ 

As you can see, alice has no explicit rights on the latter table. (In this case, she can still SELECT from the table, being a member of the public pseudorole, but I didn’t want to clutter the example by revoking the rights from public.)

What you had originally was a correct syntax — for tables, not for schemas. As you did not have a table (dubbed ‘relation’ in the error message), it threw the not-found error.

I see you’ve already noticed this — I believe there is no better way of learning than to fix our own mistakes 😉

But there is something more. What you are doing above is too much on one hand, and not enough on the other.

Running the script, you

  1. create a schema
  2. create a role
  3. grant SELECT on all tables in the schema created in (1.) to this new role_
  4. and, finally, grant all privileges (CREATE and USAGE) on the new schema to the new role

The problem lies within point (3.) You granted privileges on tables in replays — but there are no tables in there! There might be some in the future, but at this point the schema is completely empty. This way, the GRANT in (3.) does nothing — this way you are doing too much.

But what about the future tables?

There is a command for covering them: ALTER DEFAULT PRIVILEGES. It applies not only to tables, but:

Currently [as of 9.4], only the privileges for tables (including views and foreign tables), sequences, functions, and types (including domains) can be altered.

There is one important limitation, too:

You can change default privileges only for objects that will be created by yourself or by roles that you are a member of.

This means that a table created by alice, who is neither you nor a role than you are a member of (can be checked, for example, by using du in psql), will not take the prescribed access rights. The optional FOR ROLE clause is used for specifying the ‘table creator’ role you are a member of. In many cases, this implies it is a good idea to create all database objects using the same role — like mydatabase_owner.

A small example to show this at work:

CREATE ROLE test_owner; -- cannot log in
CREATE SCHEMA replays AUTHORIZATION test_owner;
GRANT ALL ON SCHEMA replays TO test_owner;

SET ROLE TO test_owner; -- here we change the context, 
                        -- so that the next statement is issued as the owner role

ALTER DEFAULT PRIVILEGES IN SCHEMA replays GRANT SELECT ON TABLES TO alice;

CREATE TABLE replays.replayer (r_id serial PRIMARY KEY);

RESET ROLE; -- changing the context back to the original role

CREATE TABLE replays.replay_event (re_id serial PRIMARY KEY);

-- and now compare the two

dp replays.replayer
                                   Access privileges
 Schema  │   Name   │ Type  │       Access privileges       │ Column access privileges 
─────────┼──────────┼───────┼───────────────────────────────┼──────────────────────────
 replays │ replayer │ table │ alice=r/test_owner           ↵│ 
         │          │       │ test_owner=arwdDxt/test_owner │ 

dp replays.replay_event
                               Access privileges
 Schema  │     Name     │ Type  │ Access privileges │ Column access privileges 
─────────┼──────────────┼───────┼───────────────────┼──────────────────────────
 replays │ replay_event │ table │                   │ 

As you can see, alice has no explicit rights on the latter table. (In this case, she can still SELECT from the table, being a member of the public pseudorole, but I didn’t want to clutter the example by revoking the rights from public.)

PostgreSQL error 42P01 actually makes users dumbfounded, especially the newbies.

Usually, this error occurs due to an undefined table in newly created databases.

That’s why at Bobcares, we often get requests to fix PostgreSQL errors, as a part of our Server Management Services.

Today, let’s have a look into the PostgreSQL error 42P01 and see how our Support Engineers fix it.

What is PostgreSQL error 42P01?

PostgreSQL has a well-defined error code description. This helps in identifying the reason for the error.

Today, let’s discuss in detail about PostgreSQL error 42P01. The typical error code in PostgreSQL appears as:

ERROR: relation "[Table name]" does not exist

SQL state:42P01

Here the 42P01 denotes an undefined table.

So, the code description clearly specifies the basic reason for the error.

But what does an undefined table means?

Let’s discuss it in detail.

Causes and fixes for the PostgreSQL error 42P01

Customer query on undefined tables of a database often shows up the 42P01 error.

Now let’s see a few situations when our customers get the 42P01 error. We will also see how our Support Engineers fix this error.

1. Improper database setup

Newbies to Postgres often make mistakes while creating a new database. Mostly, this improper setup ends up in a 42P01 error.

In such situations, our Support Team guides them for easy database setup.

Firstly, we create a new database. Next, we create a new schema and role. We give proper privileges to tables.

Postgres also allows users to ALTER DEFAULT PRIVILEGES.

2. Unquoted identifiers

Some customers create tables with mixed-case letters.

Usually, the unquoted identifiers are folded into lowercase. So, when the customer queries the table name with the mixed case it shows 42P01 error.

The happens as the PostgreSQL has saved the table name in lower case.

To resolve this error, our Support Engineers give mixed case table name in quotes. Also, we highly recommend to NOT use quotes in database names. Thus it would make PostgreSQL behave non-case sensitive.

3. Database query on a non-public schema

Similarly, the PostgreSQL 42P01 error occurs when a user queries a non-public schema.

Usually, this error occurs if the user is unaware of the proper Postgres database query.

For instance, the customer query on table name ‘pgtable‘ was:

SELECT * FROM  pgtable

This query is totally correct in case of a public schema. But, for a non-public schema ‘xx’ the query must be:

SELECT * FROM  "xx"."pgtable"

Hence, our Support Engineers ensure that the query uses the correct schema name.

[Still having trouble in fixing PostgreSQL errors? – We’ll fix it for you.]

Conclusion

In short, PostgreSQL error 42P01 denotes the database query is on an undefined table. This error occurs due to improper database setup, unidentified table name, and so on. Today, we saw how our Support Engineers fix the undefined table error in Postgres.

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»;

I’m having this strange problem using PostgreSQL 9.3 with tables that are created using qoutes. For instance, if I create a table using qoutes:

create table "TEST" ("Col1" bigint);

the table is properly created and I can see that the quotes are preserved when view it in the SQL pane of pgAdminIII. But when I query the DB to find the list of all available tables (using the below query), I see that the result does not contain quotes around the table name.

select table_schema, table_name from information_schema.tables where not table_schema='pg_catalog' and not table_schema='information_schema';

Since the table was created with quotes, I can’t use the table name returned from the above query directly since it is unquoted and throws the error in posted in the title.

I could try surrounding the table names with quotes in all queries but I’m not sure if it’ll work all the time. I’m looking for a way to get the list of table names that are quoted with quotes in the result.

I’m having the same issue with column names as well but I’m hoping that if I can find a solution to the table names issue, a similar solution will work for column names as well.

У меня возникла эта странная проблема с использованием PostgreSQL 9.3 с таблицами, созданными с использованием qoutes. Например, если я создаю таблицу с использованием кавычек:

create table "TEST" ("Col1" bigint);

Таблица создана правильно, и я вижу, что кавычки сохраняются при просмотре ее на панели SQL pgAdminIII. Но когда я запрашиваю БД, чтобы найти список всех доступных таблиц (используя запрос ниже), я вижу, что результат не содержит кавычек вокруг имени таблицы.

select table_schema, table_name from information_schema.tables where not table_schema='pg_catalog' and not table_schema='information_schema';

Поскольку таблица была создана с кавычками, я не могу использовать имя таблицы, возвращенное из приведенного выше запроса, напрямую, поскольку оно не заключено в кавычки и вызывает ошибку, размещенную в заголовке.

Я мог бы попробовать заключить имена таблиц в кавычки во всех запросах, но я не уверен, будет ли это работать все время. Я ищу способ получить список имен таблиц, которые в результате заключены в кавычки.

У меня такая же проблема с именами столбцов, но я надеюсь, что если я смогу найти решение проблемы с именами таблиц, аналогичное решение будет работать и для имен столбцов.

5 ответов

Лучший ответ

У вас есть два варианта: — без кавычек: тогда все будет автоматически вводиться строчными буквами и без учета регистра — с кавычками: теперь все чувствительно к регистру.

Я настоятельно рекомендую НЕ использовать кавычки и заставить PostgreSQL вести себя без учета регистра. это делает жизнь намного проще. как только вы перейдете к цитированию, вам нужно будет использовать его ВЕЗДЕ, поскольку PostgreSQL станет очень точным.

Какой-то пример:

   TEST = test       <-- non case sensitive
   "Test" <> Test    <-- first is precise, second one is turned to lower case
   "Test" = "Test"   <-- will work
   "test" = TEST     <-- should work; but you are just lucky.

Действительно постарайтесь любой ценой избежать подобных уловок. оставайтесь с 7-битным ascii для имен объектов.


42

Hans-Jürgen Schönig
29 Окт 2014 в 16:18

При использовании пакета npg в качестве ORM хранилища данных вы ожидаете, что структура ORM (Entity Framework в нашем случае) сгенерирует оператор sql, вы можете столкнуться с исключением PostgreSQL, отношение « Имя таблицы » не существует

Либо таблица не создана, либо в сгенерированном операторе SQL что-то отсутствует. Попробуйте отладить с помощью Visual Studio, вы увидите, что имя схемы не предшествует имени таблицы.

SELECT "ID", "Name", "CreatedBy", "CreatedDate" 
FROM "TestTable"; 

В то время как PostgreSQL ожидает имя схемы. Решение находится в классе DBContext, переопределите метод OnModelCreating и добавьте modelBuilder.HasDefaultSchema("SchemaName"); и выполните базовый конструктор, который должен выглядеть следующим образом

protected override void OnModelCreating(ModelBuilder modelBuilder)   {             
  modelBuilder.HasDefaultSchema("PartyDataManager");                  
  base.OnModelCreating(modelBuilder);         
}


6

a_horse_with_no_name
17 Фев 2019 в 00:41

Строковая функция, используемая для подходящего цитирования идентификаторов в строке оператора SQL, — это {{X0 }}, который ссылается на хороший пример (используется вместе со связанным quote_literal()).

Чтобы использовать ваш пример и смешать с другими результатами:

select
   quote_ident(table_schema) as table_schema,
   quote_ident(table_name) as table_name
...

 table_schema |    table_name
--------------+------------------
 ...
 public       | good_name
 public       | "table"
 public       | some_table
 public       | "something else"
 public       | "Tom's work"
 public       | "TEST"
 ...


2

Mike T
31 Окт 2014 в 01:14

В моем случае. таблица в базе данных должна быть в нижнем регистре … изменить имя dataTable do datatable help


4

Marcel N
23 Фев 2021 в 12:29

Сохраняйте имя таблицы в нижнем регистре, и это решит проблему.


1

Muhammad Bilal
30 Мар 2022 в 10:58

Доброго дня!

Первая установка. Ошибка 42P01. relation arm.settings does not exist и т.д.
Потом рушится по ошибке.

На форуме только странные намёки и никакой конкретики. Может пора уже выложить HowTo?


Записан


Добрый день!
Опишите свой путь к этой ошибке. В каком конкретно окне Вы это видите?


Записан


Запускаю ярлык «HABBox Admin». Выходит заставка и вместе с ней окно «Ошибка»ERROR: 42P01: relation «arm.setting» does not exist. Потом «Ошибка» Ссылка на объект не указывает на экземпляр объекта и т.д.

Пробовал отдельно запустить HABBox. Выдает:
17.01.17 16:54:12 HelloAsterisk.com — HABBox
17.01.17 16:54:12 Version 3.2017.1.10
17.01.17 16:54:12 Starting Black Box
17.01.17 16:54:13 ERROR: ERROR: 42P01: relation «arm.setting» does not exist
17.01.17 16:54:18 ERROR: ERROR: 42P01: relation «main.queue» does not exist
17.01.17 16:54:19 ERROR: ERROR: 42P01: relation «main.peer» does not exist
17.01.17 16:54:19 ERROR: ERROR: 42P01: relation «main.queue» does not exist
17.01.17 16:54:19 ERROR: ERROR: 42P01: relation «main.peer» does not exist
17.01.17 16:54:19 ERROR: ERROR: 42P01: relation «arm.setting» does not exist

Необработанное исключение: System.ArgumentNullException: Значение не может быть
неопределенным.
Имя параметра: collection
   в System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
   в HelloAsterisk.Common.ThreadSafeList`1..ctor(IEnumerable`1 list)
   в BlackBox.Core.Asterisk..ctor()
   в BlackBox.Core.Asterisk.get_Instance()
   в BlackBox.BlackBox.HABlackBox..ctor(Boolean consoleMode)
   в BlackBox.Program.Main(String[] args)


Записан


Скрин админки с настройками прикрепите плз.


Записан


Вы про какую админку? Если про панель администратора, то она и не запускается.


Записан



Записан


У Вас запускается черное окно? С админки Вы врядли бы скопипастили этот текст. Попробуйте запустить именно админку. Она называется HABBox Admin.


Записан


windows 8 rus
pgsql на linux, utf8
запускал все исполняемые, результат один и тот же.
текст скопипастил из окна HABBox.exe, перед тем как windows его отрубает.

Нашёл HABBox.exe.config с параметрами и HABBoxAdmin.exe.config, внёс в них настройки на свой pgsql с логином паролем и названием БД. Не помогло.


Записан


Во-первых, PGSQL должен быть на Windows.

 Во-вторых, нужно следовать инструкциям. Для настройки серверной части использовать только программу HABBox_Admin.exe

 Редактировать любые файлы без указания технической поддержки строго воспрещается. Иначе о каких ошибках может идти речь?

Рекомендую ознакомиться с инструкциями.


Записан



Записан


Я бы хотел на это взглянуть. Позвоните, пожалуйста, на номер в контактах. Прямо сейчас, пока у меня есть время.


Записан


К сожалению, позвонить не мог.
Вот, записал коротенькое видео.


Записан


Что же, спасибо за видео.

У Вас не запускается админка — и это основная проблема.

Причиной может быть нехватка прав на доступ к файлам самой программы, к папкам для хранения временных файлов.

Также бывало антивирусы блокировали нашу программу.

Еще можете попробовать переустановить Framework 4.5.

Что же касается ошибок, то эти сообщения указывают что в базе данных нет соответствующих полей, столбцов и параметров. Только и всего. Создать базу с нужной архитектурой проще простого — запустить правильно админку. Всё создастся само.

Постгрес на Linux — работа такой связки не гарантирована. Ибо противоречит идеологии проекта и просто не тестировалась.

Я бы рекомендовал поступить следующим образом:
1. Взять любую машину с локальным админом с правами администратора, без антивируса,
2. Поставить постгрес как в инструкциях,
3. Запустить, настроить, проверить работу функционала,
4. И если это ПО — то, что Вам нужно, тогда уже разносить систему на рабочие сервера и машины, экспериментировать с урезанием прав и постгресом на линуксе.
5. Если ПО — это не то, что Вам нужно, то сэкономите время.


Записан


The issue

When I run this sql in one command I get Npgsql.PostgresException : 42P01: relation "public.system_settings" does not exist


drop schema if exists public cascade;
create schema public;

create table system_settings (
  setting_id    serial,

  setting_name  text not null unique,
  setting_value text not null,

  primary key (setting_id)
);
 
INSERT into public.system_settings(setting_name, setting_value) VALUES
  ('HttpClientUserAgent', 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.81 Safari/537.36'),
  ('FetcherCyclePause', '60'),
  ('HttpClientRequestTimeout', '120'),
  ('ParallelFeedFetching', 'true')
  ;


Npgsql.PostgresException : 42P01: relation "public.system_settings" does not exist
   at Npgsql.NpgsqlConnector.<>c__DisplayClass160_0.<<DoReadMessage>g__ReadMessageLong|0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at Npgsql.NpgsqlConnector.<>c__DisplayClass160_0.<<DoReadMessage>g__ReadMessageLong|0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at Npgsql.NpgsqlCommand.<>c__DisplayClass74_0.<<Prepare>g__PrepareLong|0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at PgNet.ConnectionExtensions.ExecuteNonQuery(NpgsqlConnection connection, String sql, IEnumerable`1 parameters, CancellationToken cancellationToken)
   at Newsgirl.Fetcher.Tests.Infrastructure.DatabaseTest.InitializeAsync() in /work/projects/Newsgirl/server/Newsgirl.Fetcher.Tests/Infrastructure/TestHelper.cs:line 361

Further technical details

Npgsql version: 4.1.3.1
PostgreSQL version: DBMS: PostgreSQL (ver. 12.2 (Debian 12.2-1.pgdg100+1))
Operating system: Linux hristo-ws 5.3.0-40-generic #32~18.04.1-Ubuntu SMP Mon Feb 3 14:05:59 UTC 2020 x86_64 x86_64 x86_64 GNU/Linux

The issue

When I run this sql in one command I get Npgsql.PostgresException : 42P01: relation "public.system_settings" does not exist


drop schema if exists public cascade;
create schema public;

create table system_settings (
  setting_id    serial,

  setting_name  text not null unique,
  setting_value text not null,

  primary key (setting_id)
);
 
INSERT into public.system_settings(setting_name, setting_value) VALUES
  ('HttpClientUserAgent', 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.81 Safari/537.36'),
  ('FetcherCyclePause', '60'),
  ('HttpClientRequestTimeout', '120'),
  ('ParallelFeedFetching', 'true')
  ;


Npgsql.PostgresException : 42P01: relation "public.system_settings" does not exist
   at Npgsql.NpgsqlConnector.<>c__DisplayClass160_0.<<DoReadMessage>g__ReadMessageLong|0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at Npgsql.NpgsqlConnector.<>c__DisplayClass160_0.<<DoReadMessage>g__ReadMessageLong|0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at Npgsql.NpgsqlCommand.<>c__DisplayClass74_0.<<Prepare>g__PrepareLong|0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at PgNet.ConnectionExtensions.ExecuteNonQuery(NpgsqlConnection connection, String sql, IEnumerable`1 parameters, CancellationToken cancellationToken)
   at Newsgirl.Fetcher.Tests.Infrastructure.DatabaseTest.InitializeAsync() in /work/projects/Newsgirl/server/Newsgirl.Fetcher.Tests/Infrastructure/TestHelper.cs:line 361

Further technical details

Npgsql version: 4.1.3.1
PostgreSQL version: DBMS: PostgreSQL (ver. 12.2 (Debian 12.2-1.pgdg100+1))
Operating system: Linux hristo-ws 5.3.0-40-generic #32~18.04.1-Ubuntu SMP Mon Feb 3 14:05:59 UTC 2020 x86_64 x86_64 x86_64 GNU/Linux

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • 1с ошибка совместного доступа к файлу e1cib tempstorage
  • 1с ошибка совместного доступа к файлу depot dat new