Unexpected error running liquibase unterminated dollar quote started at position

Dollar-Quoted Postgres pl/pgsql procedures abort at first semi-colon anonymous [This topic is migrated from our old forums. The original author name has been removed] I’m trying to create pl/pgsql stored procedures in Postgres. They are typically of the format: CREATE FUNCTION sales_tax(subtotal real) RETURNS real AS $$BEGIN RETURN subtotal * 0.06;END;$$ LANGUAGE plpgsql; (This […]

Содержание

  1. Dollar-Quoted Postgres pl/pgsql procedures abort at first semi-colon
  2. anonymous
  3. Dollar-Quoted Postgres pl/pgsql procedures abort at first semi-colon
  4. anonymous
  5. Проблема со знаком доллара при создании функции PSQLException
  6. Ответы (2 шт):
  7. Error: unterminated dollar quote started at position xxx #7460
  8. Comments
  9. System information:
  10. Connection specification:
  11. Describe the problem you’re observing:
  12. Steps to reproduce, if exist:
  13. Include any warning/errors/backtraces from the logs
  14. Dbeaver: Неограниченная долларовая котировка при создании функции PostgreSQL с помощью SQL-Editor
  15. Системная информация:
  16. Спецификация подключения:
  17. Опишите проблему, которую вы наблюдаете:
  18. Действия по воспроизведению, если они существуют:
  19. Все 12 Комментарий

Dollar-Quoted Postgres pl/pgsql procedures abort at first semi-colon

anonymous

[This topic is migrated from our old forums. The original author name has been removed]

I’m trying to create pl/pgsql stored procedures in Postgres.

They are typically of the format:

CREATE FUNCTION sales_tax(subtotal real) RETURNS real AS $$
BEGIN
RETURN subtotal * 0.06;
END;
$$ LANGUAGE plpgsql;

(This example is from http://www.postgresql.org/docs/8.2/interactive/plpgsql-declarations.html)

The dollar-quotes ($$) avoid the need to double-quote enclosed text, a bit like Javascript allows the use of single quotes within double-quotes.

However, when DbVisualizer sends this SQL to Postgres, it returns the error:

13:19:14 [CREATE — 0 row(s), 0.000 secs] [Error Code: 0, SQL State: 42601] ERROR: unterminated dollar-quoted string at or near «$$
BEGIN
RETURN subtotal * 0.06″
13:19:14 [END — 0 row(s), 0.000 secs] Command processed . No rows were affected

From what I can observe, the code is being terminated at the semi-colon after ‘0.06’, rather than being interpreted as an entire block. The example runs fine if the dollar-quotes ($$) are replaced with single quotes (‘).

I have tried changing the Statement Delimiters (no luck) and the Variable Identifers (away from $$) but the above error still happens.

If I execute the same code within another query tool (eg Query Tool for Postgres), it executes fine. Thus, it is something to do with DbVisualizer’s interaction with Postgres.

Oh, and yes — I used the button labelled «Execute the complete buffer as one SQL statement».

Источник

Dollar-Quoted Postgres pl/pgsql procedures abort at first semi-colon

anonymous

[This topic is migrated from our old forums. The original author name has been removed]

I’m trying to create pl/pgsql stored procedures in Postgres.

They are typically of the format:

CREATE FUNCTION sales_tax(subtotal real) RETURNS real AS $$
BEGIN
RETURN subtotal * 0.06;
END;
$$ LANGUAGE plpgsql;

(This example is from http://www.postgresql.org/docs/8.2/interactive/plpgsql-declarations.html)

The dollar-quotes ($$) avoid the need to double-quote enclosed text, a bit like Javascript allows the use of single quotes within double-quotes.

However, when DbVisualizer sends this SQL to Postgres, it returns the error:

13:19:14 [CREATE — 0 row(s), 0.000 secs] [Error Code: 0, SQL State: 42601] ERROR: unterminated dollar-quoted string at or near «$$
BEGIN
RETURN subtotal * 0.06″
13:19:14 [END — 0 row(s), 0.000 secs] Command processed . No rows were affected

From what I can observe, the code is being terminated at the semi-colon after ‘0.06’, rather than being interpreted as an entire block. The example runs fine if the dollar-quotes ($$) are replaced with single quotes (‘).

I have tried changing the Statement Delimiters (no luck) and the Variable Identifers (away from $$) but the above error still happens.

If I execute the same code within another query tool (eg Query Tool for Postgres), it executes fine. Thus, it is something to do with DbVisualizer’s interaction with Postgres.

Oh, and yes — I used the button labelled «Execute the complete buffer as one SQL statement».

Источник

Проблема со знаком доллара при создании функции PSQLException

Столкнулся с проблемой: Есть скрипт инициализации БД в котором создаются функции и триггеры. Функция выглядит примерно так:

При запуске скрипта из идеи скрипт отрабатывает корректно: создаются все таблицы, функции и триггеры, но при инициализации контекста спринга скрипт выбрасывает исключение:

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

Название функции, триггера и тело функции опустил.

Ответы (2 шт):

Твоя функция написана корректно с точки зрения postgres-синтаксиса. Скорее всего у тебя проблема с sql-клиентом (укажи какой используешь). Твой sql-клиент бьёт запрос со своей стороны по знаку точка с запятой, т.е. на выходе он как бы отдаёт в базу два разных sql-запроса. Тебе надо указать в настройках другой символ разделитель. Чтобы не быть голословным приведу тебе пример, воспроизводящий твою ошибку с твоим запросом.

Обрати внимание на то, что в качестве разделителя используется точка с запятой, а ошибка получается точно такая же.

А теперь, после смены знака-разделителя на вертикальную черту пример прекрасно исполняется:

Проблему удалось решить добавив

в инициализатор базы данных файла конфигурации Spring:

а в скрипт инициализации, в конец последнего оператора поставить не одиночную точку с запятой, а двойную:

Работает если поставить в конце любого другого оператора, но мне показалось, что лучше в конце. Если я правильно понял: запрос разбивается куски разделенные «;;» и в данном случае он отправляет скрипт одним куском. А если убрать из запроса «;;» то спринг разбивает запрос непонятным мне образом и вылетает ошибка синтаксиса. Что касается знаков доллара, то они функция где они используются должна быть в одном куске скрипта. Я правильно понял? И грозят ли мне какие-нибудь сайд эффекты?

Источник

Error: unterminated dollar quote started at position xxx #7460

System information:

  • OS: windows 10
  • DBeaver version: 6.3.1
  • Additional extensions: none

Connection specification:

  • PG version: PostgreSQL 9.6.9 on x86_64-pc-linux-gnu (Debian 9.6.9-2.pgdg90+1), compiled by gcc (Debian 6.3.0-18+deb9u1) 6.3.0 20170516, 64-bit
  • Driver name: PostgreSQL standard driver
  • Do you use tunnels or proxies (SSH, SOCKS, etc)? No

Describe the problem you’re observing:

Next error is thrown when executing do block with an if statement inside:
‘Unterminated dollar quote started at position 22 in SQL’. This used to work using DBeaver version 6.3.0.
Actually, when selecting the code prior to running it, the sql is executed correctly. Only when putting cursor inside the do block and hitting ‘ctrl + enter’, the error message appears.

Steps to reproduce, if exist:

This block works:

This does not work:

Include any warning/errors/backtraces from the logs

org.jkiss.dbeaver.model.sql.DBSQLException: SQL Error [42601]: Unterminated dollar quote started at position 22 in SQL — this does not
do
$block$
declare
i integer[] := array[5,10, 11, 21];
tmp_number int;
begin
foreach tmp_number IN array i
loop
if tmp_number = 5
then
raise notice ‘high %!’, tmp_number;
end if;
RAISE NOTICE ‘%’, tmp_number;
END LOOP;
end. Expected terminating $$
at org.jkiss.dbeaver.model.impl.jdbc.exec.JDBCStatementImpl.executeStatement(JDBCStatementImpl.java:134)
at org.jkiss.dbeaver.ui.editors.sql.execute.SQLQueryJob.executeStatement(SQLQueryJob.java:481)
at org.jkiss.dbeaver.ui.editors.sql.execute.SQLQueryJob.lambda$0(SQLQueryJob.java:420)
at org.jkiss.dbeaver.model.exec.DBExecUtils.tryExecuteRecover(DBExecUtils.java:152)
at org.jkiss.dbeaver.ui.editors.sql.execute.SQLQueryJob.executeSingleQuery(SQLQueryJob.java:412)
at org.jkiss.dbeaver.ui.editors.sql.execute.SQLQueryJob.extractData(SQLQueryJob.java:771)
at org.jkiss.dbeaver.ui.editors.sql.SQLEditor$QueryResultsContainer.readData(SQLEditor.java:2843)
at org.jkiss.dbeaver.ui.controls.resultset.ResultSetJobDataRead.lambda$0(ResultSetJobDataRead.java:111)
at org.jkiss.dbeaver.model.exec.DBExecUtils.tryExecuteRecover(DBExecUtils.java:152)
at org.jkiss.dbeaver.ui.controls.resultset.ResultSetJobDataRead.run(ResultSetJobDataRead.java:109)
at org.jkiss.dbeaver.ui.controls.resultset.ResultSetViewer$17.run(ResultSetViewer.java:3434)
at org.jkiss.dbeaver.model.runtime.AbstractJob.run(AbstractJob.java:103)
at org.eclipse.core.internal.jobs.Worker.run(Worker.java:63)
Caused by: org.postgresql.util.PSQLException: Unterminated dollar quote started at position 22 in SQL — this does not
do
$block$
declare
i integer[] := array[5,10, 11, 21];
tmp_number int;
begin
foreach tmp_number IN array i
loop
if tmp_number = 5
then
raise notice ‘high %!’, tmp_number;
end if;
RAISE NOTICE ‘%’, tmp_number;
END LOOP;
end. Expected terminating $$
at org.postgresql.core.Parser.checkParsePosition(Parser.java:1275)
at org.postgresql.core.Parser.parseSql(Parser.java:1174)
at org.postgresql.core.Parser.replaceProcessing(Parser.java:1126)
at org.postgresql.core.CachedQueryCreateAction.create(CachedQueryCreateAction.java:41)
at org.postgresql.core.QueryExecutorBase.createQueryByKey(QueryExecutorBase.java:314)
at org.postgresql.jdbc.PgStatement.executeCachedSql(PgStatement.java:285)
at org.postgresql.jdbc.PgStatement.executeWithFlags(PgStatement.java:270)
at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:266)
at org.jkiss.dbeaver.model.impl.jdbc.exec.JDBCStatementImpl.execute(JDBCStatementImpl.java:338)
at org.jkiss.dbeaver.model.impl.jdbc.exec.JDBCStatementImpl.executeStatement(JDBCStatementImpl.java:131)
. 12 more

The text was updated successfully, but these errors were encountered:

Источник

Dbeaver: Неограниченная долларовая котировка при создании функции PostgreSQL с помощью SQL-Editor

Системная информация:

  • Windows 10 Pro x64, сборка 17763
  • Версия DBeaver 6.2.3.201910211155
  • Без дополнительных расширений

Спецификация подключения:

  • PostgreSQL 10
  • org.postgresql.Driver
  • Никаких туннелей и прокси

Опишите проблему, которую вы наблюдаете:

Выполнение загруженного скрипта в SQL-Editor с парой операторов для создания новой схемы.
В DBeaver версии 6.2.2 работает нормально, в 6.2.3 выдает ошибку:
SQL-Error [42601]: Unterminated dollar quote started at position 121 in SQL CREATE OR REPLACE FUNCTION change_logging_trigger() RETURNS trigger LANGUAGE plpgsql SECURITY DEFINER AS $$ BEGIN .

Действия по воспроизведению, если они существуют:

Создайте функцию и попробуйте разные варианты . AS $xxxx$ .

Эта ошибка является причиной того, что я вернулся к 6.2.2. Весь мой код использует $$. жду исправленную версию.

Все 12 Комментарий

Спасибо за отчет об ошибке. Это побочный эффект недавнего исправления дескриптора строк $$.
Решение: используйте $$ с именем тега для создания функций.
Например, $function$

Извините, но я также пробую этот обходной путь (что я имею в виду под «вариантами $ xxxxx $»).
Выдает ту же ошибку.
Изменить: я использую подчеркивания в именах ‘xxxx’, например ..AS $do_something_useful$

Не могли бы вы попробовать что-нибудь простое?
Например, $ x $. Подчеркивания пока не поддерживаются в именах тегов.

Эта ошибка является причиной того, что я вернулся к 6.2.2. Весь мой код использует $$. жду исправленную версию.

Не могли бы вы попробовать что-нибудь простое?
Например, $ x $. Подчеркивания пока не поддерживаются в именах тегов.

Спасибо за ответ, и я попробовал с . AS $dowhatyouwant$ и текст стал красным. Выполнение работает нормально, без ошибок!
Так что это должно быть допустимое решение.

Эта ошибка является причиной того, что я вернулся к 6.2.2. Весь мой код использует $$. жду исправленную версию.

Означает ли это, что $$ (без тега внутри двух $) больше не будет поддерживаться? У меня есть looootssss кода с $$.

Я проверил самую последнюю версию из раннего доступа.

С последним исправлением котировка доллара в основном работает.

Но когда вы используете $$, то иногда синтаксис тела анонимного блока кода не выделяется. Просто все желтое как нитка. Когда вы используете что-то другое, например, $ f $, все работает так, как ожидалось.

Итак, когда вы входите

подсветка синтаксиса работает. Но если, например, вы удалите «начало» и вернете его обратно, все будет выделено как одна строка.

Я голосую за то, чтобы $$ работал так, как это было до 6.2.3.

Почему это было закрыто? Это остается проблемой в 6.3.0!

Эта проблема отслеживается в # 7183.
Пожалуйста, проверьте комментарии.

для этой проблемы в dbeaver 6.2.5 я мог бы решить проблему, используя $$ с именем тега для создания функций. например, $ name_tag $

но, когда я загружаю новую версию dbeaver (6.3.1), эта проблема возникает снова, и я не могу ее решить, добавив метку между долларами.

Итак, я понижаю версию с 6.3.1 до 6.2.5, потому что я не могу исправить эту проблему в версии 6.3.1

Источник

System information:

  • Windows 10 Pro x64 Build 17763
  • DBeaver Version 6.2.3.201910211155
  • No additional extensions

Connection specification:

  • PostgreSQL 10
  • org.postgresql.Driver
  • No tunnels or proxies

Describe the problem you’re observing:

Executing a loaded script in SQL-Editor with a couple of statements for creating a new schema.
In DBeaver Version 6.2.2 works fine, in 6.2.3 throws error:
SQL-Error [42601]: Unterminated dollar quote started at position 121 in SQL CREATE OR REPLACE FUNCTION change_logging_trigger() RETURNS trigger LANGUAGE plpgsql SECURITY DEFINER AS $$ BEGIN ........

Steps to reproduce, if exist:

Create a function and try different ...AS $xxxx$ variants.

DROP SCHEMA IF EXISTS logging CASCADE;
CREATE SCHEMA logging;
SET search_path = "logging";
CREATE TABLE t_history (
    id serial,
    datetime timestamp DEFAULT now(),
    schemaname text,
    tablename text,
    operation text,
    modifier text DEFAULT current_user,
    new_val json,
    old_val json,
    CONSTRAINT t_history_pk PRIMARY KEY (id)    
);
CREATE INDEX t_history_datetime_idx ON logging.t_history (datetime);
COMMENT ON TABLE t_history IS 'A history for all actions on triggered actions!';
CREATE OR REPLACE FUNCTION change_logging_trigger()
    RETURNS trigger
    LANGUAGE plpgsql
    SECURITY DEFINER
AS $$
    BEGIN
        if TG_OP = 'INSERT' THEN
            INSERT INTO logging.t_history (schemaname, tablename, operation, new_val)
                VALUES (TG_TABLE_SCHEMA, TG_RELNAME, TG_OP, row_to_json(NEW));
            RETURN NEW;
        ELSIF TG_OP = 'UPDATE' THEN
            INSERT INTO logging.t_history (schemaname, tablename, operation, new_val, old_val)
                VALUES (TG_TABLE_SCHEMA, TG_RELNAME, TG_OP, row_to_json(NEW), row_to_json(OLD));
            RETURN NEW;
        ELSIF TG_OP = 'DELETE' THEN
            INSERT INTO logging.t_history (schemaname, tablename, operation, old_val)
                VALUES (TG_TABLE_SCHEMA, TG_RELNAME, TG_OP, row_to_json(OLD));
            RETURN OLD;
        END IF;
    END;
$$;

Start a new topic



anonymous

started a topic
over 15 years ago

[This topic is migrated from our old forums. The original author name has been removed]

I’m trying to create pl/pgsql stored procedures in Postgres.

They are typically of the format:

CREATE FUNCTION sales_tax(subtotal real) RETURNS real AS $$
BEGIN
    RETURN subtotal * 0.06;
END;
$$ LANGUAGE plpgsql;

(This example is from http://www.postgresql.org/docs/8.2/interactive/plpgsql-declarations.html)

The dollar-quotes ($$) avoid the need to double-quote enclosed text, a bit like Javascript allows the use of single quotes within double-quotes.

However, when DbVisualizer sends this SQL to Postgres, it returns the error:

13:19:14  [CREATE — 0 row(s), 0.000 secs]  [Error Code: 0, SQL State: 42601]  ERROR: unterminated dollar-quoted string at or near «$$
    BEGIN
        RETURN subtotal * 0.06″
13:19:14  [END — 0 row(s), 0.000 secs]  Command processed . No rows were affected

From what I can observe, the code is being terminated at the semi-colon after ‘0.06’, rather than being interpreted as an entire block. The example runs fine if the dollar-quotes ($$) are replaced with single quotes (‘).

I have tried changing the Statement Delimiters (no luck) and the Variable Identifers (away from $$) but the above error still happens.

If I execute the same code within another query tool (eg Query Tool for Postgres), it executes fine. Thus, it is something to do with DbVisualizer’s interaction with Postgres.

Oh, and yes — I used the button labelled «Execute the complete buffer as one SQL statement».

Any suggestions?

Thanks!


Hans Bergsten

said
over 15 years ago

[This reply is migrated from our old forums.]

Re: Dollar-Quoted Postgres pl/pgsql procedures abort at first semi-colon

Hi John,

We recently ran into this problem as well. The main problem is that the PostgreSQL JDBC driver did not handle dollar-quoted strings until a version later than 8.1 (not sure exactly when it was fixed). Another problem is that «$$» is used as a variable delimiter within DbVis, but as you have already seen, you can change that to something else, e.g., «$$$» instead of «$$».

If you upgrade your JDBC driver (I’ve tested with PostgreSQL 8.2 JDBC3 with SSL, build 506) set the Variable Delimiter to something other than «$$», and use Execute Buffer (or enclose the statement with block delimiters, «—/» and «/» by default), you should be fine.

Regards,
Hans

anonymous

said
over 15 years ago

[This reply is migrated from our old forums. The original author name has been removed]

Re: Dollar-Quoted Postgres pl/pgsql procedures abort at first semi-colon

Thank you Hans!

I can confirm that updating to a newer postgres driver (I used postgresql-8.2-506.jdbc3.jar) has fixed this problem.

(I also had an additional stray driver in my java classpath that I had to remove to get this new one recognised.)

Thank you!

John.

anonymous

said
almost 15 years ago

[This reply is migrated from our old forums. The original author name has been removed]

Re: Dollar-Quoted Postgres pl/pgsql procedures abort at first semi-colon

hi,

i am facing this issue when I execute functions/procedures from ant so please help me. Srinivas

Roger Bjärevall

said
almost 15 years ago

[This reply is migrated from our old forums.]

Re: Dollar-Quoted Postgres pl/pgsql procedures abort at first semi-colon

Hi,

You say:

«… when I execute functions/procedures from ant»

How does this relate with DbVisualizer?

Regards

Roger

anonymous

said
over 9 years ago

[This reply is migrated from our old forums. The original author name has been removed]

Re: Dollar-Quoted Postgres pl/pgsql procedures abort at first semi-colon

Hello,

I have the exact same problem but the solutions provided don’t seem to work for me. I use a current version of DbVisualizer 9.08. which provides a PostgreSQL JDBC driver version of 9.1 and I double checked the variable settings, there are on ${, }$ and ||, no $$ anywhere. In the debug log window I can clearly see that my CREATE FUNCTION statement gets truncated on the first ;:

12:23:51 [DEBUG pool-3-thread-2 B.?] DefaultEditor14: Jdbc4Statement.execute(«CREATE FUNCTION find_deletable_objects() RETURNS void AS $$
DECLARE
objectId integer»)
org.postgresql.util.PSQLException: FEHLER: Dollar-Quotes nicht abgeschlossen bei »$$
DECLARE
objectId integer«
Position: 58
at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2101)
at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:1834)
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:255)
at org.postgresql.jdbc2.AbstractJdbc2Statement.execute(AbstractJdbc2Statement.java:510)
at org.postgresql.jdbc2.AbstractJdbc2Statement.executeWithFlags(AbstractJdbc2Statement.java:372)
at org.postgresql.jdbc2.AbstractJdbc2Statement.execute(AbstractJdbc2Statement.java:364)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at com.onseven.dbvis.g.B.B.?(Z:1910)
at com.onseven.dbvis.g.B.F$A.call(Z:1474)
at java.util.concurrent.FutureTask$Sync.innerRun(Unknown Source)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
SQLException: SQLState(42601)

The only thing which seems to work is surrounding the complete CREATE FUNCTION statement with —/ and /.

Is this intended behavior or am I doing somethign wrong? Thanks!

Roger Bjärevall

said
over 9 years ago

[This reply is migrated from our old forums.]

Re: Dollar-Quoted Postgres pl/pgsql procedures abort at first semi-colon

Thorsten,

This is the general recommendation when dealing with application objects such as functions:

1) If the only editor contains only the SQL block that should be executed, then use SQL->Execute Buffer

2) Enclose the complete block as an SQL block i.e. between «—/» and «/»:

—/
CREATE …
/

3) Use the @delimiter client side command to temporarily re-define the statement delimiter:

@delimiter ++;
CREATE …
@delimiter ;++

I hope this helps.

Regards

Roger

Peer Törngren

said
over 1 year ago

Error: unterminated dollar quote started at position xxx #7460

Comments

HannesMas commented Dec 23, 2019 •

System information:

  • OS: windows 10
  • DBeaver version: 6.3.1
  • Additional extensions: none

Connection specification:

  • PG version: PostgreSQL 9.6.9 on x86_64-pc-linux-gnu (Debian 9.6.9-2.pgdg90+1), compiled by gcc (Debian 6.3.0-18+deb9u1) 6.3.0 20170516, 64-bit
  • Driver name: PostgreSQL standard driver
  • Do you use tunnels or proxies (SSH, SOCKS, etc)? No

Describe the problem you’re observing:

Next error is thrown when executing do block with an if statement inside:
‘Unterminated dollar quote started at position 22 in SQL’. This used to work using DBeaver version 6.3.0.
Actually, when selecting the code prior to running it, the sql is executed correctly. Only when putting cursor inside the do block and hitting ‘ctrl + enter’, the error message appears.

Steps to reproduce, if exist:

This block works:

This does not work:

Include any warning/errors/backtraces from the logs

org.jkiss.dbeaver.model.sql.DBSQLException: SQL Error [42601]: Unterminated dollar quote started at position 22 in SQL — this does not
do
$block$
declare
i integer[] := array[5,10, 11, 21];
tmp_number int;
begin
foreach tmp_number IN array i
loop
if tmp_number = 5
then
raise notice ‘high %!’, tmp_number;
end if;
RAISE NOTICE ‘%’, tmp_number;
END LOOP;
end. Expected terminating $$
at org.jkiss.dbeaver.model.impl.jdbc.exec.JDBCStatementImpl.executeStatement(JDBCStatementImpl.java:134)
at org.jkiss.dbeaver.ui.editors.sql.execute.SQLQueryJob.executeStatement(SQLQueryJob.java:481)
at org.jkiss.dbeaver.ui.editors.sql.execute.SQLQueryJob.lambda$0(SQLQueryJob.java:420)
at org.jkiss.dbeaver.model.exec.DBExecUtils.tryExecuteRecover(DBExecUtils.java:152)
at org.jkiss.dbeaver.ui.editors.sql.execute.SQLQueryJob.executeSingleQuery(SQLQueryJob.java:412)
at org.jkiss.dbeaver.ui.editors.sql.execute.SQLQueryJob.extractData(SQLQueryJob.java:771)
at org.jkiss.dbeaver.ui.editors.sql.SQLEditor$QueryResultsContainer.readData(SQLEditor.java:2843)
at org.jkiss.dbeaver.ui.controls.resultset.ResultSetJobDataRead.lambda$0(ResultSetJobDataRead.java:111)
at org.jkiss.dbeaver.model.exec.DBExecUtils.tryExecuteRecover(DBExecUtils.java:152)
at org.jkiss.dbeaver.ui.controls.resultset.ResultSetJobDataRead.run(ResultSetJobDataRead.java:109)
at org.jkiss.dbeaver.ui.controls.resultset.ResultSetViewer$17.run(ResultSetViewer.java:3434)
at org.jkiss.dbeaver.model.runtime.AbstractJob.run(AbstractJob.java:103)
at org.eclipse.core.internal.jobs.Worker.run(Worker.java:63)
Caused by: org.postgresql.util.PSQLException: Unterminated dollar quote started at position 22 in SQL — this does not
do
$block$
declare
i integer[] := array[5,10, 11, 21];
tmp_number int;
begin
foreach tmp_number IN array i
loop
if tmp_number = 5
then
raise notice ‘high %!’, tmp_number;
end if;
RAISE NOTICE ‘%’, tmp_number;
END LOOP;
end. Expected terminating $$
at org.postgresql.core.Parser.checkParsePosition(Parser.java:1275)
at org.postgresql.core.Parser.parseSql(Parser.java:1174)
at org.postgresql.core.Parser.replaceProcessing(Parser.java:1126)
at org.postgresql.core.CachedQueryCreateAction.create(CachedQueryCreateAction.java:41)
at org.postgresql.core.QueryExecutorBase.createQueryByKey(QueryExecutorBase.java:314)
at org.postgresql.jdbc.PgStatement.executeCachedSql(PgStatement.java:285)
at org.postgresql.jdbc.PgStatement.executeWithFlags(PgStatement.java:270)
at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:266)
at org.jkiss.dbeaver.model.impl.jdbc.exec.JDBCStatementImpl.execute(JDBCStatementImpl.java:338)
at org.jkiss.dbeaver.model.impl.jdbc.exec.JDBCStatementImpl.executeStatement(JDBCStatementImpl.java:131)
. 12 more

The text was updated successfully, but these errors were encountered:

Источник

PostgreSQL error 42601- How we fix it

by Sijin George | Sep 12, 2019

Syntax errors are quite common while coding.

But, things go for a toss when it results in website errors.

PostgreSQL error 42601 also occurs due to syntax errors in the database queries.

At Bobcares, we often get requests from PostgreSQL users to fix errors as part of our Server Management Services.

Today, let’s check PostgreSQL error in detail and see how our Support Engineers fix it for the customers.

What causes error 42601 in PostgreSQL?

PostgreSQL is an advanced database engine. It is popular for its extensive features and ability to handle complex database situations.

Applications like Instagram, Facebook, Apple, etc rely on the PostgreSQL database.

But what causes error 42601?

PostgreSQL error codes consist of five characters. The first two characters denote the class of errors. And the remaining three characters indicate a specific condition within that class.

Here, 42 in 42601 represent the class “Syntax Error or Access Rule Violation“.

In short, this error mainly occurs due to the syntax errors in the queries executed. A typical error shows up as:

Here, the syntax error has occurred in position 119 near the value “parents” in the query.

How we fix the error?

Now let’s see how our PostgreSQL engineers resolve this error efficiently.

Recently, one of our customers contacted us with this error. He tried to execute the following code,

But, this ended up in PostgreSQL error 42601. And he got the following error message,

Our PostgreSQL Engineers checked the issue and found out the syntax error. The statement in Line 5 was a mix of plain and dynamic SQL. In general, the PostgreSQL query should be either fully dynamic or plain. Therefore, we changed the code as,

This resolved the error 42601, and the code worked fine.

[Need more assistance to solve PostgreSQL error 42601?- We’ll help you.]

Conclusion

In short, PostgreSQL error 42601 occurs due to the syntax errors in the code. Today, in this write-up, we have discussed how our Support Engineers fixed this error 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.

10 Comments

SELECT * FROM long_term_prediction_anomaly WHERE + “‘Timestamp’” + ‘”BETWEEN ‘” +
2019-12-05 09:10:00+ ‘”AND’” + 2019-12-06 09:10:00 + “‘;”)

Hello Joe,
Do you still get PostgreSQL errors? If you need help, we’ll be happy to talk to you on chat (click on the icon at right-bottom).

У меня ошибка drop table exists “companiya”;

CREATE TABLE “companiya” (
“compania_id” int4 NOT NULL,
“fio vladelca” text NOT NULL,
“name” text NOT NULL,
“id_operator” int4 NOT NULL,
“id_uslugi” int4 NOT NULL,
“id_reklama” int4 NOT NULL,
“id_tex-specialist” int4 NOT NULL,
“id_filial” int4 NOT NULL,
CONSTRAINT “_copy_8” PRIMARY KEY (“compania_id”)
);

CREATE TABLE “filial” (
“id_filial” int4 NOT NULL,
“street” text NOT NULL,
“house” int4 NOT NULL,
“city” text NOT NULL,
CONSTRAINT “_copy_5” PRIMARY KEY (“id_filial”)
);

CREATE TABLE “login” (
“id_name” int4 NOT NULL,
“name” char(20) NOT NULL,
“pass” char(20) NOT NULL,
PRIMARY KEY (“id_name”)
);

CREATE TABLE “operator” (
“id_operator” int4 NOT NULL,
“obrabotka obrasheniya” int4 NOT NULL,
“konsultirovanie” text NOT NULL,
“grafick work” date NOT NULL,
CONSTRAINT “_copy_2” PRIMARY KEY (“id_operator”)
);

CREATE TABLE “polsovateli” (
“id_user” int4 NOT NULL,
“id_companiya” int4 NOT NULL,
“id_obrasheniya” int4 NOT NULL,
“id_oshibka” int4 NOT NULL,
CONSTRAINT “_copy_6” PRIMARY KEY (“id_user”)
);

CREATE TABLE “reklama” (
“id_reklama” int4 NOT NULL,
“tele-marketing” text NOT NULL,
“soc-seti” text NOT NULL,
“mobile” int4 NOT NULL,
CONSTRAINT “_copy_3” PRIMARY KEY (“id_reklama”)
);

CREATE TABLE “tex-specialist” (
“id_tex-specialist” int4 NOT NULL,
“grafik” date NOT NULL,
“zarplata” int4 NOT NULL,
“ispravlenie oshibok” int4 NOT NULL,
CONSTRAINT “_copy_7” PRIMARY KEY (“id_tex-specialist”)
);

CREATE TABLE “uslugi” (
“id_uslugi” int4 NOT NULL,
“vostanavlenia parola” int4 NOT NULL,
“poterya acaunta” int4 NOT NULL,
CONSTRAINT “_copy_4” PRIMARY KEY (“id_uslugi”)
);

ALTER TABLE “companiya” ADD CONSTRAINT “fk_companiya_operator_1” FOREIGN KEY (“id_operator”) REFERENCES “operator” (“id_operator”);
ALTER TABLE “companiya” ADD CONSTRAINT “fk_companiya_uslugi_1” FOREIGN KEY (“id_uslugi”) REFERENCES “uslugi” (“id_uslugi”);
ALTER TABLE “companiya” ADD CONSTRAINT “fk_companiya_filial_1” FOREIGN KEY (“id_filial”) REFERENCES “filial” (“id_filial”);
ALTER TABLE “companiya” ADD CONSTRAINT “fk_companiya_reklama_1” FOREIGN KEY (“id_reklama”) REFERENCES “reklama” (“id_reklama”);
ALTER TABLE “companiya” ADD CONSTRAINT “fk_companiya_tex-specialist_1” FOREIGN KEY (“id_tex-specialist”) REFERENCES “tex-specialist” (“id_tex-specialist”);
ALTER TABLE “polsovateli” ADD CONSTRAINT “fk_polsovateli_companiya_1” FOREIGN KEY (“id_companiya”) REFERENCES “companiya” (“compania_id”);

ERROR: ОШИБКА: ошибка синтаксиса (примерное положение: “”companiya””)
LINE 1: drop table exists “companiya”;
^

Источник

Проблема со знаком доллара при создании функции PSQLException

Столкнулся с проблемой: Есть скрипт инициализации БД в котором создаются функции и триггеры. Функция выглядит примерно так:

При запуске скрипта из идеи скрипт отрабатывает корректно: создаются все таблицы, функции и триггеры, но при инициализации контекста спринга скрипт выбрасывает исключение:

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

Название функции, триггера и тело функции опустил.

Ответы (2 шт):

Твоя функция написана корректно с точки зрения postgres-синтаксиса. Скорее всего у тебя проблема с sql-клиентом (укажи какой используешь). Твой sql-клиент бьёт запрос со своей стороны по знаку точка с запятой, т.е. на выходе он как бы отдаёт в базу два разных sql-запроса. Тебе надо указать в настройках другой символ разделитель. Чтобы не быть голословным приведу тебе пример, воспроизводящий твою ошибку с твоим запросом.

Обрати внимание на то, что в качестве разделителя используется точка с запятой, а ошибка получается точно такая же.

А теперь, после смены знака-разделителя на вертикальную черту пример прекрасно исполняется:

Проблему удалось решить добавив

в инициализатор базы данных файла конфигурации Spring:

а в скрипт инициализации, в конец последнего оператора поставить не одиночную точку с запятой, а двойную:

Работает если поставить в конце любого другого оператора, но мне показалось, что лучше в конце. Если я правильно понял: запрос разбивается куски разделенные «;;» и в данном случае он отправляет скрипт одним куском. А если убрать из запроса «;;» то спринг разбивает запрос непонятным мне образом и вылетает ошибка синтаксиса. Что касается знаков доллара, то они функция где они используются должна быть в одном куске скрипта. Я правильно понял? И грозят ли мне какие-нибудь сайд эффекты?

Источник

Dbeaver: Неограниченная долларовая котировка при создании функции PostgreSQL с помощью SQL-Editor

Системная информация:

  • Windows 10 Pro x64, сборка 17763
  • Версия DBeaver 6.2.3.201910211155
  • Без дополнительных расширений

Спецификация подключения:

  • PostgreSQL 10
  • org.postgresql.Driver
  • Никаких туннелей и прокси

Опишите проблему, которую вы наблюдаете:

Выполнение загруженного скрипта в SQL-Editor с парой операторов для создания новой схемы.
В DBeaver версии 6.2.2 работает нормально, в 6.2.3 выдает ошибку:
SQL-Error [42601]: Unterminated dollar quote started at position 121 in SQL CREATE OR REPLACE FUNCTION change_logging_trigger() RETURNS trigger LANGUAGE plpgsql SECURITY DEFINER AS $$ BEGIN .

Действия по воспроизведению, если они существуют:

Создайте функцию и попробуйте разные варианты . AS $xxxx$ .

Эта ошибка является причиной того, что я вернулся к 6.2.2. Весь мой код использует $$. жду исправленную версию.

Все 12 Комментарий

Спасибо за отчет об ошибке. Это побочный эффект недавнего исправления дескриптора строк $$.
Решение: используйте $$ с именем тега для создания функций.
Например, $function$

Извините, но я также пробую этот обходной путь (что я имею в виду под «вариантами $ xxxxx $»).
Выдает ту же ошибку.
Изменить: я использую подчеркивания в именах ‘xxxx’, например ..AS $do_something_useful$

Не могли бы вы попробовать что-нибудь простое?
Например, $ x $. Подчеркивания пока не поддерживаются в именах тегов.

Эта ошибка является причиной того, что я вернулся к 6.2.2. Весь мой код использует $$. жду исправленную версию.

Не могли бы вы попробовать что-нибудь простое?
Например, $ x $. Подчеркивания пока не поддерживаются в именах тегов.

Спасибо за ответ, и я попробовал с . AS $dowhatyouwant$ и текст стал красным. Выполнение работает нормально, без ошибок!
Так что это должно быть допустимое решение.

Эта ошибка является причиной того, что я вернулся к 6.2.2. Весь мой код использует $$. жду исправленную версию.

Означает ли это, что $$ (без тега внутри двух $) больше не будет поддерживаться? У меня есть looootssss кода с $$.

Я проверил самую последнюю версию из раннего доступа.

С последним исправлением котировка доллара в основном работает.

Но когда вы используете $$, то иногда синтаксис тела анонимного блока кода не выделяется. Просто все желтое как нитка. Когда вы используете что-то другое, например, $ f $, все работает так, как ожидалось.

Итак, когда вы входите

подсветка синтаксиса работает. Но если, например, вы удалите «начало» и вернете его обратно, все будет выделено как одна строка.

Я голосую за то, чтобы $$ работал так, как это было до 6.2.3.

Почему это было закрыто? Это остается проблемой в 6.3.0!

Эта проблема отслеживается в # 7183.
Пожалуйста, проверьте комментарии.

для этой проблемы в dbeaver 6.2.5 я мог бы решить проблему, используя $$ с именем тега для создания функций. например, $ name_tag $

но, когда я загружаю новую версию dbeaver (6.3.1), эта проблема возникает снова, и я не могу ее решить, добавив метку между долларами.

Итак, я понижаю версию с 6.3.1 до 6.2.5, потому что я не могу исправить эту проблему в версии 6.3.1

Источник

Понравилась статья? Поделить с друзьями:
  • Unexpected error running liquibase error no schema has been selected to create in
  • Underverse ost error sans theme
  • Underverse fatal error sans
  • Underverse error sans wiki
  • Underverse error sans vs ink sans