SQLAlchemy
این SQLAlchamy من این یه تیکشا نفهمیدم
SQLAlchemy
این SQLAlchamy من این یه تیکشا نفهمیدم
(ORM)
این ORM هم داره که یعنی تو بیای Class به Database را map کنی و اینجوری Maintain کد را رحت تر کنی. یه چیز دیگه تبدیل Datatype های SQL که اغلب به صورت Integer و Float است به DataType های Python که اغلب به صورت Non Scaler است
databases is an async SQL query builder that works on top of the SQLAlchemy Core expression language.
databases Python package
In addition to SQLAlchemy core queries, you can also perform raw SQL queries
Instead of SQLAlchemy core query:
query = notes.insert()
values = [
{"text": "example2", "completed": False},
{"text": "example3", "completed": True},
]
await database.execute_many(query=query, values=values)
One can write a raw SQL query:
query = "INSERT INTO notes(text, completed) VALUES (:text, :completed)"
values = [
{"text": "example2", "completed": False},
{"text": "example3", "completed": True},
]
await database.execute_many(query=query, values=values)
=================================
The same goes with fetching in SQLAlchemy:
query = notes.select()
rows = await database.fetch_all(query=query)
And doing the same with raw SQL:
query = "SELECT * FROM notes WHERE completed = :completed"
rows = await database.fetch_all(query=query, values={"completed": True})
Use method has() of relationship (more readable)
Use has if can't use join.
session.query(Book.author, Chapter.title).select_from(Book).join(Book.chapters) or session.query(Book).options(load_only("author"), joinedload("chapters").load_only("title"))
Very useful quick guide for how to only load certain foreign key fields.
# scenario-1: delete in session: SA might set category_id of all chilren Products to None c1 = session.query(Category).get(1) session.delete(c1) session.commit() # scenario-2: delete without loading an object into the session: SA will perform no additional logic session.query(Category).filter(Category.id == 2).delete() session.commit()
Weird sqlalchemy behavior but totally an accurate statement. When using postgres and not specifying how to handle deletes, if you delete via object instead of filter.delete, sqlalchemy will set all children with foreignkey id's to None.
flask_sqlalchemy.get_debug_queries()
Dumps out query history-super helpful for debug!
session_options={"autoflush": False, "autocommit": False, "expire_on_commit": False}
Disable autocommit and autoflush in sqlalchemy.
Integration of Naming Conventions into Operations, Autogenerate
Importance of naming conventions for sqlalchemy when running alembic db migrations.
filter_by vs join
Some of the most common operators used in filter() method SQLAlchemy
Validators, like all attribute extensions, are only called by normal userland code; they are not issued when the ORM is populating the object
validates works only during append operation. Not during assignment
listen(User, 'before_insert', generate_license)
Hook into the model creation and save to ElasticSearch from here