Создаю отношение
create table ПОТРЕБИТЕЛЬ (
ИДЕНТИФИКАТОР serial not null primary key,
НАЗВАНИЕ varchar(50) not null,
"АДРЕС ЖИТЕЛЬСТВА" varchar(255) not null,
"СКИДКА, %" smallint check ("СКИДКА, %" >= 0 and "СКИДКА, %" <= 100) not null
);
Затем пытаюсь заполнить таблицу, используя значения
insert into ПОТРЕБИТЕЛЬ (ИДЕНТИФИКАТОР, НАЗВАНИЕ, "АДРЕС ЖИТЕЛЬСТВА", "СКИДКА, %") values (001, "АО ВАРЯ", "Сормовский", 10);
insert into ПОТРЕБИТЕЛЬ (ИДЕНТИФИКАТОР, НАЗВАНИЕ, "АДРЕС ЖИТЕЛЬСТВА", "СКИДКА, %") values (002, "ГАЗ", "Автозаводский", 7);
insert into ПОТРЕБИТЕЛЬ (ИДЕНТИФИКАТОР, НАЗВАНИЕ, "АДРЕС ЖИТЕЛЬСТВА", "СКИДКА, %") values (003, "МП ВЕРА", "Канавинский", 5);
insert into ПОТРЕБИТЕЛЬ (ИДЕНТИФИКАТОР, НАЗВАНИЕ, "АДРЕС ЖИТЕЛЬСТВА", "СКИДКА, %") values (004, "МП", "Канавинский", 3);
insert into ПОТРЕБИТЕЛЬ (ИДЕНТИФИКАТОР, НАЗВАНИЕ, "АДРЕС ЖИТЕЛЬСТВА", "СКИДКА, %") values (005, "АО СТАЛЬ", "Советский", 0);
Возникает ошибка в каждой строчке, якобы столбец не существует, при этом это даже не столбцы а аргументы

Меня все больше удивляют авторы СУБД PostgreSQL. На моих тестовых серверах и у клиентов установлена ее 11-я версия. Обычно я стараюсь себе на компьютер устанавливать последние версии программного обеспечения. Так же было и с PostgreSQL — когда возникла необходимость ее установить локально, я установил 12-ю версию. Залил дамп базы, запустил свою утилиту и получил ошибку «column pd.adsrc does not exist». Я сразу подумал, что при импорте дампа возникла ошибка и загрузил его снова. Но ошибка повторилась. Установил PostgreSQL на другой компьютер и получил «столбец pd.adsrc не существует».
Гугл быстро дал ответ на мою проблему. Оказалось, что в PostgreSQL 12-й версии из системной таблицы pg_catalog.pg_attrdef разработчики удалили поле «adsrc». Они просто решили, что это поле устаревшее и оно им не нужно… Вот разве так можно? Гора программного обеспечения, которую годами разрабатывали программисты по всему миру, перестанет корректно работать на новой версии СУБД. Может мне везло, но с подобной проблемой я не сталкивался ни у Oracle, ни у MS SQLServer. Например, недавно я узнал, что несколько почтовых сервисов, который я писал примерно 16-18 лет тому назад, успешно работают с базой данных на MS SQLServer 2019. Таким образом в моих глазах СУБД PostgreSQL получает очередной минус.
Все предлагаемые мне гуглом варианты решения этой проблемы были для pgAdmin. А что делать тем, у кого запросы не в скрипте, а в бинарнике? Первая моя мысль была добавить поле adsrc в таблицу pg_catalog.pg_attrdef. Но все же я решил, что это не выход. Правильно решать ее в своей программе. В используемой мной библиотеке для доступа к базам данных «PostgreSQL 12 is supported» только с версии 8.1. То есть для меня путь к 12-й версии PostgreSQL один — «достать кошелек» и обновить UniDac. Эта ситуация с PostgreSQL еще раз подтвердила, что использование open source продуктов, даже если не на прямую, а косвенно, но все равно приводит к лишним затратам.
0
1
При попытке выполнить обновление или удаление строки выдается сообщение об отсутствии поля таблицы. Хотя оно есть. Что я делаю не так?
mgi@mgi-Linux:~$ sudo su postgres
[sudo] пароль для mgi:
postgres@mgi-Linux:/home/mgi$ psql
psql (11.4 (Ubuntu 11.4-1.pgdg18.04+1), сервер 10.9 (Ubuntu 10.9-1.pgdg18.04+1))
Введите «help», чтобы получить справку.
postgres=# c megriv
psql (11.4 (Ubuntu 11.4-1.pgdg18.04+1), сервер 10.9 (Ubuntu 10.9-1.pgdg18.04+1))
Вы подключены к базе данных «megriv» как пользователь «postgres».
megriv=# SELECT * FROM formanpa;
codForma | textForma
———-+——————
11 | Aaaaaaaaaaaaa
22 | Bbbbbbbb
33 | Cccccccccccccccc
(3 строки)
megriv=# UPDATE formanpa SET textForma = ‘B2b2b2b2b2′ WHERE codForma = ’22’;
ОШИБКА: столбец «codforma» не существует
СТРОКА 1: …PDATE formanpa SET textForma = ‘B2b2b2b2b2’ WHERE codForma =…
^
ПОДСКАЗКА: Возможно, предполагалась ссылка на столбец «formanpa.codForma».
megriv=# UPDATE formanpa SET textForma = ‘B2b2b2b2b2′ WHERE formanpa.codForma = ’22’;
ОШИБКА: столбец formanpa.codforma не существует
|
yoimelv 0 / 0 / 0 Регистрация: 16.01.2019 Сообщений: 12 |
||||||||||||
|
1 |
||||||||||||
|
08.10.2022, 21:58. Показов 1015. Ответов 4 Метки postgres sql, sql posrgre (Все метки)
Здравствуйте! Не получается объединить таблицы по внешнему ключу. PGadmin пишет: SQL state: 42703 Таблица hobby:
Таблица users:
Запрос, который не получается произвести:
__________________
0 |
|
4720 / 3928 / 994 Регистрация: 29.08.2013 Сообщений: 25,187 Записей в блоге: 3 |
|
|
08.10.2022, 22:57 |
2 |
|
а ткните пальцем где именно в таблице users колонка fk да и pk я не вижу
0 |
|
yoimelv 0 / 0 / 0 Регистрация: 16.01.2019 Сообщений: 12 |
||||||||
|
08.10.2022, 23:22 [ТС] |
3 |
|||||||
|
Честно говоря, не знаю. Делали задание в классе, там всё получилось, а вот дома — нет, ошибка где-то. Нужно было выполнить запрос:
В классе программа сама предложила дописать запрос в конце, поэтому как раз часть
так и не понял, просто не запомнил, что там написал.
0 |
|
Аватар 1419 / 887 / 339 Регистрация: 31.05.2012 Сообщений: 3,114 |
||||
|
09.10.2022, 09:13 |
4 |
|||
0 |
|
4720 / 3928 / 994 Регистрация: 29.08.2013 Сообщений: 25,187 Записей в блоге: 3 |
|
|
09.10.2022, 17:40 |
5 |
|
Делали задание в классе, там всё получилось так голову нужно включать
0 |
|
IT_Exp Эксперт 87844 / 49110 / 22898 Регистрация: 17.06.2006 Сообщений: 92,604 |
09.10.2022, 17:40 |
|
Помогаю со студенческими работами здесь DataGridView. Существует ли столбец?
База данных — столбец в таблице не существует Как проверить существует ли столбец в DGV
Существует ли в матрице строка или столбец палиндром
Искать еще темы с ответами Или воспользуйтесь поиском по форуму: 5 |
Simple LINQ query produces the following sql:
SELECT «Extent1″.»price» FROM «schema1».»table1″ AS «Extent1»
which fails with «ERROR: 42703: column Extent1.price does not exist»
Another example from modified LINQ query
SELECT «Alias1″.»Id», «Alias1″.»price» FROM «schema1».»table1″ AS «Alias1» LIMIT 1
ERROR: 42703: column Alias1.Id does not exist
Manually running those statements without the quotes works fine.
My setup is Npgsql.EntityFramework 2.2.5.0 / EF 6.1.3.0 / Postgres 9.4.1
When used with quotes, Postgresql is case sensitive regarding identifier names like table names and columns names.
In your case, your column name may have been created with double quotes using a different case of price. Maybe it was created as "Price"? If so, just recreate it without quotes, or using the same case sensitivity of your queries.
I need to check it, but I think those quotes are added by EF when generating the queries.
I hope it helps.
Thanks Francisco, you are right, this issue is caused by case mismatch.
Is there way to switch Npgsql to case-insensitive mode apart from applying data annotations to the model columns ?
Hi, @fatim !
I’m glad you got it working.
Is there way to switch Npgsql to case-insensitive mode apart from applying data annotations to the model columns ?
I don’t know it yet. I need to check if we can make something about those quotes.
@Emill , do you have any idea if it is possible to remove those quotes from EF queries?
Thanks in advance.
Postgresql’s names are case-sensitive but for some strange reason the identifiers put in an sql query are automatically converted to lower case by the lexer unless they are surrounded by quotes.
If the properties of the models don’t match the column names, it is possible by using attributes to use other column names.
If requested, we could have some option to automatically convert CamelCase identifiers to lower_case_with_underlines to better fit the naming conventions used by .net and Postgresql.
You can use EF6’s own API to specify the database names on all classes and properties (some Linq on the model + EF6’s fluent API should do the trick).
As others suggested in comments, this is probably a matter of upper-case versus lower-case, or some whitespace in the column name. (I’m using an answer so I can format some code samples.) To see what the column names really are, try running this query:
SELECT '"' || attname || '"', char_length(attname)
FROM pg_attribute
WHERE attrelid = 'table_name'::regclass AND attnum > 0
ORDER BY attnum;
You should probably also check your PostgreSQL server log if you can, to see what it reports for the statement.
If you quote an identifier, everything in quotes is part of the identifier, including upper-case characters, line endings, spaces, and special characters. The only exception is that two adjacent quote characters are taken as an escape sequence for one quote character. When an identifier is not in quotes, all letters are folded to lower-case. Here’s an example of normal behavior:
test=# create table t (alpha text, Bravo text, "Charlie" text, "delta " text);
CREATE TABLE
test=# select * from t where Alpha is null;
alpha | bravo | Charlie | delta
-------+-------+---------+--------
(0 rows)
test=# select * from t where bravo is null;
alpha | bravo | Charlie | delta
-------+-------+---------+--------
(0 rows)
test=# select * from t where Charlie is null;
ERROR: column "charlie" does not exist
LINE 1: select * from t where Charlie is null;
^
test=# select * from t where delta is null;
ERROR: column "delta" does not exist
LINE 1: select * from t where delta is null;
^
The query I showed at the top yields this:
?column? | char_length
-----------+-------------
"alpha" | 5
"bravo" | 5
"Charlie" | 7
"delta " | 6
(4 rows)
As others suggested in comments, this is probably a matter of upper-case versus lower-case, or some whitespace in the column name. (I’m using an answer so I can format some code samples.) To see what the column names really are, try running this query:
SELECT '"' || attname || '"', char_length(attname)
FROM pg_attribute
WHERE attrelid = 'table_name'::regclass AND attnum > 0
ORDER BY attnum;
You should probably also check your PostgreSQL server log if you can, to see what it reports for the statement.
If you quote an identifier, everything in quotes is part of the identifier, including upper-case characters, line endings, spaces, and special characters. The only exception is that two adjacent quote characters are taken as an escape sequence for one quote character. When an identifier is not in quotes, all letters are folded to lower-case. Here’s an example of normal behavior:
test=# create table t (alpha text, Bravo text, "Charlie" text, "delta " text);
CREATE TABLE
test=# select * from t where Alpha is null;
alpha | bravo | Charlie | delta
-------+-------+---------+--------
(0 rows)
test=# select * from t where bravo is null;
alpha | bravo | Charlie | delta
-------+-------+---------+--------
(0 rows)
test=# select * from t where Charlie is null;
ERROR: column "charlie" does not exist
LINE 1: select * from t where Charlie is null;
^
test=# select * from t where delta is null;
ERROR: column "delta" does not exist
LINE 1: select * from t where delta is null;
^
The query I showed at the top yields this:
?column? | char_length
-----------+-------------
"alpha" | 5
"bravo" | 5
"Charlie" | 7
"delta " | 6
(4 rows)

Ошибка — Не существует в пространстве имен, но оно существует!