Questions tagged [sqlalchemy]
SQLAlchemy is a Python SQL toolkit and Object Relational Mapper that gives application developers the full power and flexibility of SQL.
23,055
questions
0
votes
0
answers
8
views
Chaining joinedloads in sqlalchemy
I need to dynamically adjust depths of joined loads of objects in SQLAlchemy.
@staticmethod
def _get(session, identifier: int, depth=5):
return session.get(
Node, ...
0
votes
0
answers
28
views
How to extend SQLAlchemy generated classes in declarative model outside of the model?
I am using SQLAlchemy + sqlacodegen in my python project.
I have succesfully generated declarative model from my database, which looks like this:
DB_Model.py
from sqlalchemy import Column, DateTime, ...
0
votes
0
answers
11
views
Why does this SQL Alchemy CASE statement give me an error
I have the following statement in my python
case(
[
(Table.c.start_date > "2023-10-04")
| (Table.c.end_date < "...
0
votes
0
answers
7
views
The with_loader_criteria is not filtering out correctly in a join dominated query
I have 4 models, 2 out of which do not have the mixin class inherited on which the do_orm_Execute gets called and filters out the active rows, and 2 models where it is inherited. On joining these four,...
0
votes
0
answers
24
views
Is there a way I can check type of database in the property/method of sqlalchemy model?
My sqlalchemy table model has a hybrid property of the form:
@hybrid_property
def age_in_seconds(self) -> float:
return (datetime.utcnow() - self.generated_at).total_seconds()
@age_in_seconds....
-1
votes
0
answers
10
views
Can't get jsonable_encoder() to work with a tree of SQLAlchemy objects
I have a chain of objects with relationships like the code below (which is not complete and so does not run). One object has another, which has another, which has another and that last one has a list. ...
0
votes
1
answer
23
views
sqlalchemy.exc.ProgrammingError: (psycopg2.errors.UndefinedFunction) function st_asewkb(point) does not exist
Postgres flexible server running on Azure. Postgis extension was installed to the dbo schema using
create extension postgis schema dbo;
which also contains the core data tables. Under extensions in ...
0
votes
0
answers
20
views
using column_property with SqlAlchemy and Oracle DB
I need to create a virtual column in my sqlalchemy model that can be loaded along with all other column-mapped attributes at load time. SQLAlchemy docs shows how, using column_property().
This works ...
0
votes
0
answers
8
views
how to fix an pyodbc operational error while connecting with test server, but working fine with local server
import pyodbc
cnxn = pyodbc.connect(
driver='{SQL Server}',
host='####',
database='HR_Git',
user='sa',
password='####'
)
print(cnxn)
cursor = cnxn.cursor()
cursor.execute('...
0
votes
0
answers
28
views
Can't find solution for insert many with using cte
Hi I have next sql code:
with cte as (select max(idmilityattache)
from dopinfo.milityattaches)
insert
into dopinfo.milityattaches
values ((select * from cte) + 1, 1, 'a', '2023-03-02'::...
0
votes
0
answers
23
views
parse db result by pydantic
Hi i have function that renders template and I want to populate it with data so i query the db and i get list of
*sqlalchemy*
[<src.utils.models.case object at 0x22BF6850> , <src.utils.models....
-1
votes
0
answers
33
views
langchain SQLDatabase, using GCP BigQuery, querying a dataset in another project
I've been playing around with the langchain library and trying to create a sql agent. i.e. asking the model a question, and it returning both the query + the result
I've started out by following the ...
0
votes
1
answer
28
views
Take the last entry of each row when Flag is a specific value in SQL
I have a data source that looks something like this:
Signal Value
Power value
1
-100
2
99
3
95
4
-64
5
-55
6
92
7
-80
8
23
9
-66
10
-56
11
-46
The signal values are actually random, not ...
-2
votes
0
answers
19
views
Python ORM for only reading data [closed]
I am currently setting up a project and have to choose a Python ORM to read data from an existing database. The database is primarily written to and maintained from a C# project, so in Python I am ...
0
votes
0
answers
14
views
Delete many-to-many in MySQL database with FastAPI SQLAlchemy [ Internal Server Error:'int' object has no attribute 'query'"]
I want to make test CRUD app for study, but I have problem with delete opperaction, because I have many-to-many relationship,I think.
Models:
class Book(Base):
tablename = 'books'
id = Column(INTEGER(...
0
votes
0
answers
15
views
InvalidRequestError when reading view but not SQL query
I have an SQLAlchemy engine (type(engine) outputs <class 'sqlalchemy.engine.base.Engine'>), when I run this snippet I get an error:
with engine.connect() as connexion:
pd.read_sql_table(&...
0
votes
2
answers
35
views
Designing Polymorphic One-to-many relationship database. Flask
I am looking to create polymorphic one-to-many relationship like for example here It's hard for me to explain, so let me use example:
Let's say we have three tables Books, Magazines, Newspapers, all ...
0
votes
1
answer
21
views
Define a one to one relationship on same model with an association model between using SQLAlchemy
Using sqlalchemy, I want to define a one to one relationship between two instances of the same model linked by an association model.
Here is what I have so far:
from sqlalchemy import Column, Integer, ...
0
votes
0
answers
28
views
SQLAlchemy "Table already exists" but "checkfirst=True" is defined
im working on a Flask app which uses SQLAlchemy for DB handling.
When testing locally with sqlite everything works as expected. The Production config is MySQL (MariaDB 11). When i deploy it to my ...
0
votes
0
answers
19
views
Sqlalchemy automatically deletes objects in list
I'm writing simple app using FastAPI and SqlAlchemy. I have written function to get a list
of users:
async def get_users(
db: sqlalchemy.ext.AsyncSession,
start_id: int = ...,
...
0
votes
1
answer
34
views
flask error with sqlalchemy when doing rollback
My error handler for 500 is throwing an error at db.session.rollback.
@bp.app_errorhandler(500)
def internal_error(error):
db.session.rollback()
return render_template('errors/500.html'), 500
...
0
votes
0
answers
20
views
FASTAPI SQLAlchemy PSQL How to Post data with relationships
migrations
src
src/__pycache__
src/auth
src/auth/__pycache__
src/auth/base_config.py
src/auth/manager.py > incapsulated funcs like create
src/auth/models.py > user
src/auth/schemas.py > ...
-1
votes
0
answers
31
views
How to get username in Discord Py 2.0.1?
await client.change_presence(status=discord.Status.online, activity=activity)
for guild in client.guilds:
for member in guild.members:
exists = session.query(User.id).filter_by(id=member....
0
votes
1
answer
25
views
Update field metadata using llama index and sqlalchemy
How do you set the metadata on a query engine? The data field is a JSON field with specific fields that I want the agent to use to improve the query.
metadata_dict = {
"...
1
vote
1
answer
34
views
How to perform selectinload behind many-to-many?
With code below:
import logging
from faker import Faker
from sqlalchemy import create_engine, ForeignKey, select
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, relationship, ...
1
vote
1
answer
26
views
Airflow Snowflake Operator Error - AttributeError: 'dict' object has no attribute 'sfqid'
I've recently upgraded our MWAA instance from Airflow 2.2.2 to 2.4.3 but i'm now getting the below error whenever I use the SnowflakeCheckOperator or get_first function (which the Snowflake python ...
0
votes
1
answer
28
views
Add column to existing SQL table usig sqlalcehmy
I have a sqlalchemy connection and an existing table
database_con = f'mssql://@{server}/{database}?driver={driver}'
engine = create_engine(database_con)
con = engine.connect()
tbl = '#temp'
df = pd....
0
votes
1
answer
29
views
container can't connect to MySQL server on 192.168.0.9
I have a python function inside docker that uses sqlalchemy to connect to a MySQL database, and even tough this function works in my machine - and used to work inside airflow as well, it stopped ...
0
votes
1
answer
26
views
Alembic - Attempting to autogenerate revision throws "sqlalchemy.exc.NoSuchModuleError: Can't load plugin: sqlalchemy.dialects:postgresql.psycopg"
Edit: The outputs below were run on Windows with Git bash.
I am new to Alembic and SQLAlchemy.
I have been tasked with adding Alembic support to an existing FastAPI + SQLAlchemy application. To this ...
1
vote
1
answer
44
views
How to create a relation between a SQLAlchemy model and a table with no model
I am working on micro-services, the base service is in Django and other services are in FastAPI.
All the services will share the same PostgreSQL database, the Employee model is in Django and and I ...
0
votes
1
answer
29
views
How do you connect a .SQL Database to Jupyter Notebook?
As you need to connect a database for using SQL and I don´t want to use pg Admin due to lack of visualization, I prefer to use Jupyter Notebook or Visual Studio Code.
With this said, I want to connect ...
0
votes
1
answer
35
views
Can't convert response from Sqlalchemy to Pydantic model
I'm trying to return a schema that inherits from Pydantic's BaseModel but I'm getting an error
Models:
class Project(Base):
__tablename__ = 'projects'
id: Mapped[int] = mapped_column(...
-2
votes
0
answers
48
views
Copy a 50GB table from sql server to sqlite using Python [closed]
I'm trying to export a 50gb table from a microsoft sql server database to a local sqlite database. The mssql table does not have a primary key or an index and I can't make any changes to that table.
...
0
votes
0
answers
14
views
Sqlalchemy python package for pagination that supports nulls and filters [closed]
My code is currently using a package called sqlakeyset for pagination during sqlalchemy queries.
It has one limitation that is also mentioned in it's documentation - it doesn't work well with null ...
0
votes
0
answers
18
views
Pytest throws a DetachedInstanceError: Instance <User> is not bound to a Session; attribute refresh operation cannot proceed
I'm trying to test the deletion of a user, however, although the returned status for the API call is correct after that I'd like to check if the field 'deleted' in the database is actually changed to ...
1
vote
0
answers
108
views
pandas.to_xml() with nested xml blocks
I create table in PostgreSQL and insert to table nested XML(xml_part column):
CREATE TABLE text_xml (
id numeric,
xml_part XML
);
insert into text_xml
values (1, '<note><to>Tove&...
0
votes
0
answers
31
views
Can multiprocessing decrease latency of a sqlalchemy writing to server
I have a sqlalchemy session, and want to input a 300k row 24 col (~300MB) of data
database_con = f'mssql://@{server}/{database}?driver={driver}'
engine = create_engine(database_con)
con = engine....
1
vote
1
answer
59
views
Getting ODBC Driver 17 error while connecting to azure SQL
I'm getting the following error while connection my code to azure SQL from local machine (windows) and also when deployed to azure function (python/linux)
sqlalchemy.exc.OperationalError: (pyodbc....
0
votes
0
answers
19
views
MySQLdb.OperationalError: (2026, 'SSL connection error: error:0A000086:SSL routines::certificate verify failed')
I am interacting with a MySQL database locally and I am making a connection as show below:
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy....
0
votes
1
answer
31
views
Can I parameterise tables using Pandas read_sql function?
I got a database with multiple projects which follows a similar structure to the following:
Schemas for our client Bob: bob_legal, bob_docs, bob_misc
Schemas for our client Jess: jess_legal, ...
0
votes
1
answer
23
views
How to create a string sequence in SQLAlchemy
I am currently developing an API for invoices. And I want to create an Invoice table with invoiceNumber field that would be auto incrementing but as a string. Something like this:
INV00001
INV00002
...
0
votes
1
answer
27
views
Apply migrations in MySQL docker container. Can't find database
I am using alembic and sqlalchemy to migrate the database.
The container is running and working, as I am able to use phpmyadmin to apply manual changes.
Using alembic upgrade head locally in my ...
0
votes
1
answer
39
views
SQLAlchemy Only Returns List Line if there are Carriage Returns in the Row (SQL Server)
I have an SQL query that generates the DDL to create tables based on the existing schema. I am running this to copy the schema to another database for backup purposes. I do not have permission to do ...
0
votes
0
answers
24
views
Efficient to way to check if user_id is present in User and either match or queue?
I am using sqlalchemy 2.0. I have 3 table User, Match, Queue.
class User(Base, TableNameMixin):
user_id: Mapped[int] = mapped_column(BIGINT, primary_key=True, autoincrement=False)
premium: ...
0
votes
0
answers
8
views
Scoped_session has no attribute cursor: Flask-SQLAlchemy session in pd.read_sql
I am switching from the standalone SQLAlchemy package in my Flask app to Flask-SQLAlchemy. Everything went smoothly except for one problem. I cannot use the database session provided by Flask-...
0
votes
0
answers
42
views
Ascync python server/client with post method to write to DB
First time asking here, if you think, that i should add something or can clarify in any other way, please tell me.
I am trying to write two files in Python: the first file is the server, the second is ...
0
votes
1
answer
42
views
To_sql fails to update mysql table
I am trying to insert a dataframe to a table in mysql:
sql = """
select MakeID, MakeName brand FROM Makes m
"""
sql_d = pd.read_sql(sql, conn)
mycursor = mydb.cursor()
...
0
votes
0
answers
18
views
python sqlalchemy how to change column type between table define and execute Base.metadata.create_all(self.engine)
from sqlalchemy import Column, Integer, TEXT, create_engine, String
from sqlalchemy.orm import DeclarativeBase
class SqlalchemyBase(DeclarativeBase):
pass
class ListPage(SqlalchemyBase):
...
-1
votes
0
answers
45
views
Scoped session doesn't see changes in fixtures. SQLAlchemy with Pytest [closed]
I have a problem with a async_scoped_session in sqlalchemy. I'm doing crud tests on a database model, but the session doesn't show changes made in fixtures.
I use sqlalchemy 1.4
That's class for ...
0
votes
1
answer
45
views
SQLAlchemy + Alembic: How to create full text search index for column with weights using Alembic revision
I am trying to use Alembic to generate a revision that will create full text search indices for some columns in my tables. I've recently upgraded to SQLAlchemy 2.0 as well as PG15. Whenever I try to ...