236
questions
0
votes
0
answers
24
views
SqlAlchemy: Server settings in connection URL
I would like to disable the PostgreSQL JIT to improve ENUM datatype handling (PostgreSQL document:
https://docs.sqlalchemy.org/en/20/dialects/postgresql.html#disabling-the-postgresql-jit-to-improve-...
0
votes
1
answer
28
views
'asyncpg.pgproto.pgproto.UUID' object has no attribute 'replace'
I'm building a fastAPI application. I have a Psotgres DB where i write and read data from. I'm using SQLAlchemy to interact with my Postgres Database. Here is my model:
import uuid
from db.database ...
0
votes
0
answers
23
views
Atomic commit for multiple async sessions?
I have some async sqlalchemy code for working with postgres.
Initially, the code looked like this:
async def f(session: AsyncSession):
...
async def g(session: AsyncSession):
....
await ...
0
votes
0
answers
27
views
Missing Greenlet error in self referencing table
im trying create selfreferencing table to have access to user referals, but on upon getting user_obj im getting error stacktrace in referals property instead of list of users.
sqlalchemy 2.0.32 ...
1
vote
1
answer
90
views
A FastAPI project with asyncpg has dependencies from psycopg2, which causes the error ModuleNotFoundError: No module named 'psycopg2'
I have a FastAPI project that uses asyncpg to connect to PostgreSQL.
I use poetry and the following is my pyproject.toml files.
[tool.poetry]
name = "my_project"
version = "0.1.0"
...
0
votes
0
answers
26
views
Different error codes (23503 vs 23502) when deleting a row in PostgreSQL using asyncpg
I'm encountering an issue when deleting a row in PostgreSQL with foreign key relationships.
Typically, this raises a ForeignKeyViolationError (23503), but when using asyncpg, I receive a ...
0
votes
0
answers
102
views
Race condition using FastAPI, SQLAlchemy and Asyncpg
I am currently having problems solving an issue with writing data in the postgres db due to a race condition.
Basically, I need to insert into the database a "Medico" if it doesn't exists.
...
2
votes
1
answer
683
views
connect_args in SQLAlchemy's create_async_engine
I'm attempting to add connect_args to create_async_engine, the asynchronous version of the create_engine. In the past, I've been able to specify my schema with the following synchronous engine ...
0
votes
0
answers
33
views
Can a SOCKS5 Proxy be Integrated with asyncpg for PostgreSQL Connections?
I'm currently utilizing asyncpg for managing connections to PostgreSQL databases. I'm interested in incorporating a SOCKS5 proxy into this setup. Does asyncpg support the use of SOCKS5 proxies for ...
0
votes
0
answers
55
views
Default values in SQLAlchemy column using an asynchronous function
I'm using FastAPI, SQLAlchemy and asyncpg.
I have a column in my model:
current_location_id = Column(
ForeignKey("location.id"),
default=CarService.get_random_location
)
The ...
0
votes
1
answer
165
views
Prevent asyncpg from processing output from postgres? (return raw data)
I am trying to return raw data, as in string / bytes, from a postgresql query executed with asyncpg, without asyncpg parsing the output data into a Record/dict. In my case I use a cursor, but I think ...
0
votes
0
answers
48
views
Trouble adding users to the database through async endpoint in my FastAPI application
Modules
app/core/config.py:
import os
from pathlib import Path
from dotenv import load_dotenv
from pydantic import BaseModel
from pydantic_settings import BaseSettings
BASE_DIR = Path(__file__)....
1
vote
1
answer
366
views
FastAPI SQLAlchemy Async tests fail without poolclass set to NullPool
I am building an app using FastAPI and SQLAlchemy. Async setup. For some reason I cannot find a proper way to setup async tests. I am running a very basic test setup.
conftest.py:
@pytest_asyncio....
0
votes
0
answers
101
views
Can not connect to postgres with asyncpg - "socket.gaierror"
I am trying to connect to PostgreSQL with asyncpg and SQLAlchemy. PostgreSQL instance is run by Docker.
My error is:
Traceback (most recent call last):
File "<frozen runpy>", line ...
1
vote
0
answers
529
views
How to do parallel select queries sqlalchemy + postgresql + asyncpg?
I have three independet tables: OneTable, TwoTable, ThreeTable.
There is 10k rows in each table. I try select all data from each table in parallel via async sqlalchemy scoped session.
(https://docs....
0
votes
1
answer
78
views
asyncpg DatatypeMismatchError when setting a custom postgres schema
I'm using SQLAlchemy with asyncpg and I have several models defined using Pydantic.
I have one pydantic model named PanAcquisition:
class PanAcquisition(Base):
__tablename__ = "...
0
votes
1
answer
72
views
How can I wrap a coroutine.__await__()?
I want to log every acquire/release query to an asyncpg pool. I have written the following for this purpose
class CntPoolLogger:
def __init__(self) -> None:
self.conn_cnt = 0
...
1
vote
1
answer
55
views
having a trouble with ManyToMany relationship configuration - "sqlalchemy.exc.InvalidRequestError"
I am new to SQLAlchemy and have some errors with ManyToMany relationship configuration.
Before I paste my code here, I would like to give a short description: I have a model UserORM and ProjectORM, ...
0
votes
0
answers
107
views
Creating tables on Heroku server with FastAPI and SQLModel, Alembic and pgasync
I have seen simillar question asked here
but that didn answer my issue unfortunately. Im trying to update DATABASE_URL in my db.py file like this
DATABASE_URL = os.environ.get('DATABASE_URL').replace(&...
0
votes
1
answer
42
views
conn does not have an execute method
import aiogram
from aiogram import Router
import asyncpg
import asyncio
from data.config import Config
Data_base = Router()
@Data_base.message()
async def connenct():
conn = asyncpg.connect(r&...
2
votes
0
answers
97
views
Dynamic columns in asyncpg fetch query
I want to execute a select query with asyncpg where the columns to be selected depends on some variable. For example:
columns=["some_col_12", "another_col_51"] # Set from ...
1
vote
0
answers
201
views
How to dynamically change database in fastapi?
there are different databases for different users. so after I extract the user from the api token, I want to switch my from my public database to the user database like how THREAD_LOCAL.DB = dbname ...
0
votes
0
answers
313
views
How to connect a FastAPI application and a PostgreSQL database on Digital Ocean
For some context, the FastAPI app is running on Ubuntu in a digital ocean droplet, and the database is a digital ocean managed database in a cluster.
I recently restored the database from backup after ...
0
votes
0
answers
36
views
Why do I get a single connection sharing error when opening multiple connections in one pool (in unittest)?
It throw asyncpg.exceptions._base.InterfaceError: cannot perform operation: another operation is in progress
I use an asyncpg, my code:
in the test
import unittest
from models.create import ...
0
votes
1
answer
599
views
Asyncpg.pool creates more connections than its max_size
asyncpg version:0.29.0
PostgreSQL version: "PostgreSQL 16.0 (Debian 16.0-1.pgdg120+1) on aarch64-unknown-linux-gnu, compiled by gcc (Debian 12.2.0-14) 12.2.0, 64-bit"
Do you use a PostgreSQL ...
0
votes
1
answer
488
views
asyncpg DataError: invalid input for query argument expected str, got int
I admittedly don't understand how asyncpg's codecs work, but it seems to work counter to how I'd expect:
import asyncio
import asyncpg
async def main():
conn = await asyncpg.connect('postgresql://...
0
votes
1
answer
253
views
Can't connect to PostgreSQL inside docker container with SQLAlchemy when running pytest
I am creating FastAPI application and trying to setup two database containers with docker (one db is for testing). I successfully connect to the first database, but for some reason can't connect to ...
0
votes
1
answer
472
views
PostgreSQL with asyncpg return a prefix string for a json_agg() select
I'm trying to use a json_agg() function of PostgreSQL with python and asyncpg. The data returned is a list of just one element that begins with <Record jsonb_agg= string and than a correct json.
I'...
0
votes
0
answers
214
views
Adapt Connection Pool Code to Work with Tortoise ORM
Can the following code, which I copied from https://pypi.org/project/cloud-sql-python-connector/, be tailored to use Tortoise ORM?
import asyncio
import asyncpg
import sqlalchemy
from sqlalchemy.ext....
0
votes
0
answers
81
views
Make Connection/Pool Available Outside Main
Using the following code from https://pypi.org/project/cloud-sql-python-connector/:
import asyncio
import asyncpg
import sqlalchemy
from sqlalchemy.ext.asyncio import AsyncEngine, create_async_engine
...
4
votes
0
answers
273
views
Recursive lazy loading in async SQLAlchemy: Greenlet spawn error
I'm trying to load and serialize a deeply nested model using SQLAlchemy into a json response (using pydantic ParentType), which seems difficult using an async engine.
I have a Parent db model, which ...
0
votes
0
answers
152
views
Connecting a Python Sanic App on Cloud Run to PostgreSQL on Cloud SQL
I am able to connect to PostgreSQL on Cloud SQL via pgAdmin and also when running the Python Sanic application locally. But when I deploy the application on Cloud Run and try connecting to PostgreSQL, ...
0
votes
1
answer
402
views
How to use asyncpg with aiogram?
I have trouble with the library asyncpg inside a code that bases on aiogram. DB code:
class DataBase:
def __init__(self):
self.db_pool = None
loop = asyncio.get_event_loop()
...
-1
votes
1
answer
182
views
Looping through a select object causes TypeError despite an example in documentation
I want to get results from a select object and read the documentation carefully to build a working example. However, the example seems to be faulty for some reason and raises TypeError. How should I ...
1
vote
3
answers
498
views
Disabling cache in asyncpg
I want to disable cache in asyncpg+postgresql to get timely results from the database and not outdated ones. However, I encounter an issue that doesn't allow me to do so:
RuntimeWarning: coroutine '...
0
votes
0
answers
33
views
how to find out about transaction state when using asyncpg context manager
The script uses 2 redis transactions over asyncpg. I need to catch whether the asyncpg transaction was successful or not in order to confirm or reset the redis transaction
async with cls.sem:
...
2
votes
1
answer
389
views
'NoneType' object has no attribute 'fetchrow'
I was using MySQL database before, and now I've migrated to PostgreSQL.
Looks like it is very hard to refactor my code for Postgres.
I am experiencing some troubles with find_and_lock_token() method.
...
0
votes
1
answer
168
views
SQLAlchemy throws no exceptions
I am trying to append a child class to a parent class. The problem is even when I make mistakes on purpose, the code throws no exceptions but doesn't work. I have found no errors in IDE as I've tried ...
0
votes
1
answer
217
views
How to integrate except: raise with sqlalchemy's exceptions? SQLAlchemyError not working
I have the session rollback whenever I try to execute the statement in main.py. In db_commands.py I have the except: raise clause that should allow me to catch any errors that caused the rollback, e.g....
0
votes
0
answers
386
views
__enter__ was never awaited: asyncpg+sqlalchemy error
I have troubles with aiogram+asyncpg+postgresql. I have already explicitly written a class for __enter__ to be defined as I received an error of it being undefined, though now I have a problem of it ...
0
votes
0
answers
51
views
SQLAlchemy 2: manually unexpire a row?
Prerequisites:
PostgreSQL 14
SQLAlchemy 2.0.19
Python 3.10
Asyncpg 0.28.0
Please, imagine this script:
async with sessionmaker() as session, session.begin():
person: Person = await session.get(...
1
vote
0
answers
253
views
Make `TSTZRANGE` field in `SQLModel` model compatible with `FastAPI` response serialization
Consider the following model:
from datetime import datetime
from typing import Optional, Tuple
from sqlalchemy.dialects.postgresql import TSTZRANGE
from sqlalchemy import Column
from sqlmodel import ...
2
votes
0
answers
2k
views
Usage of Postgres NOTIFY / LISTEN in SQLALCHEMY with asyncpg
I would like to implement a subsystem where inserts in a certain table in Postgres would triger event and this event would be intercepted by backend on FastAPi with SQLAlchemy and Websockets and would ...
0
votes
1
answer
869
views
Password authentication issue with PostgreSQL in GitHub Actions. Python
I try to run integration tests in GitHub Actions. For this want to create a postgresql database and connect to it. The code for posrtgresql service I took from here. The code which connects to the ...
0
votes
2
answers
210
views
Insert text in braces with asyncpg
I have a follow table:
CREATE TABLE raw_data (
id bigserial NOT NULL,
datetime varchar NOT NULL DEFAULT now(),
param_id int4 NOT NULL,
raw_data varchar NOT NULL)
I'm trying to insert ...
0
votes
1
answer
341
views
aws python 3.8 lambda + async sqlalchemy 2.0.10, asyncpg 0.28.0
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
engine_async = create_async_engine(
"postgresql+asyncpg://postgres:password@host_name.rds.amazonaws.com/postgres")
...
3
votes
1
answer
794
views
PIPENV & pip3 Installation conflict with asyncpg 0.25.0 and other dependencies
I am facing an installation conflict while trying to install asyncpg version 0.25.0 along with other dependencies in a Python 3.8 environment. Here are the steps I've taken so far:
Cloned the ...
1
vote
2
answers
2k
views
How to run asyncpg (Postgresql) multiple queries simultaneously?
I'm using PostgreSQL & asyncpg.
class PgDb:
# noinspection SpellCheckingInspection
def __init__(self, conn: asyncpg.connection.Connection):
self.conn = conn
async def select(...
0
votes
0
answers
133
views
What would be the fastapi-asyncpg session object equivalent to SQLalchemy Session
I have an fastapi application where redis will be used for cache. I am using a package called fastapi_redis_cache. Currently we are moving from SQLalchemy to asyncpg while connecting with the redis ...
1
vote
0
answers
362
views
SQLalchemy Async returns datetime in UTC timezone
I ran into a strange situation where in async mode the SQLAlchemy returns a datetime in the UTC time zone.
I'm using postgreSQL 15 and SQLAclchemy 2.0.7
I change the timezone as:
set local time zone '...