In my python code using asyncpg, I am passing in a tuple (‘PENDING’,) into a where-in query, which is logged as:
args=('TYPE_1', ('PENDING',))
query=SELECT * FROM actions where type = $1 AND status IN $2
It seems like the sql query should finally be
SELECT * FROM actions where type = TYPE_1 AND status in ('PENDING',);
but the above code results in:
asyncpg.exceptions.PostgresSyntaxError: syntax error at or near "$2"
I think it probably is because of the trailing comma in the tuple, but I don’t know how to get rid of it..
Hello!
If you execute a simple parameterized query using AsyncSession, like:
# db_session is instance of AsyncSession
stmt = text('SET local statement_timeout = :value').bindparams(value=500)
await db_session.execute(stmt)
you end up with:
E sqlalchemy.exc.ProgrammingError: (sqlalchemy.dialects.postgresql.asyncpg.ProgrammingError) <class 'asyncpg.exceptions.PostgresSyntaxError'>: syntax error at or near "$1"
E [SQL: SET local statement_timeout = %s]
E [parameters: (500,)]
E (Background on this error at: https://sqlalche.me/e/14/f405)
But it perfectly works if you just use an f-string, but using f-string does not sound cool.
I’ve found some explanations from asyncpg side (MagicStack/asyncpg#605 (comment)):
asyncpg does not do query argument interpolation in any form. The query you write gets passed directly to PostgreSQL. This is unlike psycopg2 which has extensive query rewriting/interpolation mechanisms.
Is it maybe fixable on SQLAlchemy side? Like SQLAlchemy passes asyncpg queries with parameter values already placed.
Hi,
The same error happens if you run the same query with asyncpg:
>>> async def go(): ... conn = await asyncpg.connect('postgresql://scott:tiger@localhost:5432/test') ... await conn.execute('SET local statement_timeout = $1', 1000) >>> asyncio.run(go()) Traceback (most recent call last): ... File "asyncpgprotocolprotocol.pyx", line 168, in prepare asyncpg.exceptions.PostgresSyntaxError: syntax error at or near "$1"
The issue here seems of asyncpg and in part of postgresql that does not accept parameters in that query. My suggestion is to ask for advice in the asyncpg repository.
Is it maybe fixable on SQLAlchemy side? Like SQLAlchemy passes asyncpg queries with parameter values already placed.
No, this is not something SQLAlchemy does, and in general not something we are interested in doing, since it has a lot of security implications
3 replies
Thanks for suggestions.
My suggestion is to ask for advice in the asyncpg repository.
Somebody already asked some time ago -> MagicStack/asyncpg#605
and unfortunately their answer is:
This is outside of scope and can be solved by a wrapper library.
Somebody already asked some time ago -> MagicStack/asyncpg#605
It was for a different case ,a create table compared to a set, but I guess the answer should be similar also for this query.
Я все еще изучаю PostgreSQL. Во время тестирования я использовал оператор INSERT только в psycopg2, а теперь и в asyncpg. Теперь мне нужно ОБНОВЛЯТЬ данные в моей тестовой базе данных вместо того, чтобы заменять их все.
В настоящее время я пытаюсь выполнить простой тест замены в таблице тестирования, прежде чем перейти к таблице разработки с дополнительными данными.
Я хочу заменить любое имя $ 1, находящееся в CONFLICT, на имя, которое уже есть в таблице users. Я пробую код запроса, который передается в БД через asyncpg. Я продолжаю получать синтаксические ошибки, поэтому я немного не понимаю, как исправить эти ошибки.
Каков правильный синтаксис этого запроса?
'''INSERT INTO users(name, dob)
VALUES($1, $2)
ON CONFLICT (name)
DO
UPDATE "users"
SET name = 'TEST'
WHERE name = excluded.name '''
Обновлено:
Я получаю это сообщение об ошибке при использовании asyncpg:
asyncpg.exceptions.PostgresSyntaxError: syntax error at or near ""users""
Я получаю это сообщение об ошибке при использовании psycopg2:
psycopg2.ProgrammingError: syntax error at or near ""users""
Это код asyncpg, который я использовал для вставки INSERT:
async def insert_new_records(self, sql_command, data):
print (sql_command)
async with asyncpg.create_pool(**DB_CONN_INFO, command_timeout=60) as pool:
async with pool.acquire() as conn:
try:
stmt = await conn.prepare(sql_command)
async with conn.transaction():
for value in data:
async for item in stmt.cursor(*value):
pass
finally:
await pool.release(conn)
test_sql_command = '''
INSERT INTO users(name, dob)
VALUES($1, $2)
ON CONFLICT (name)
DO
UPDATE "users"
SET name = 'TEST'
WHERE name = excluded.name '''
# The name 'HELLO WORLD' exists in the table, but the other name does not.
params = [('HELLO WORLD', datetime.date(1984, 3, 1)),
('WORLD HELLO', datetime.date(1984, 3, 1))]
loop = asyncio.get_event_loop()
loop.run_until_complete(db.insert_new_records(test_sql_command, params))
из таблицы?
info = await db.connection.fetch(«SELECT * FROM users») это не работает, бьет ошибку
asyncpg.exceptions.PostgresSyntaxError: ошибка синтаксиса (примерное положение: «)»)
python
russian
programming
20:35 18.06.2022
3
ответов
Во-первых, фетчолл. Во-вторых, это не похоже на тот код, в котором такая ошибка.
20:44 18.06.2022
𝓐𝓶𝓪𝓻𝓸 𝓥𝓲𝓽𝓪 ☕️
Во-первых, фетчолл. Во-вторых, это не похоже на то…
разобрался уже, спсаибо
20:44 18.06.2022
xtemple
разобрался уже, спсаибо
И вообще,
где экзекьют? =)
20:45 18.06.2022
Похожие вопросы
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
