stress_at_work_analysis/config/ORMtutorial.py

126 lines
2.2 KiB
Python
Raw Normal View History

2021-05-07 12:53:10 +02:00
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: percent
# format_version: '1.3'
# jupytext_version: 1.11.2
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# %%
import sqlalchemy
2021-05-07 12:53:10 +02:00
print(sqlalchemy.__version__)
# %%
from sqlalchemy import create_engine
engine = create_engine("sqlite:///:memory:", echo=True)
2021-05-07 12:53:10 +02:00
# %%
from sqlalchemy.ext.declarative import declarative_base
2021-05-07 12:53:10 +02:00
Base = declarative_base()
# %%
from sqlalchemy import Column, Integer, String
2021-05-07 12:53:10 +02:00
class User(Base):
__tablename__ = "users"
2021-05-07 12:53:10 +02:00
id = Column(Integer, primary_key=True)
name = Column(String)
fullname = Column(String)
nickname = Column(String)
def __repr__(self):
return "<User(name='%s', fullname='%s', nickname='%s')>" % (
self.name,
self.fullname,
self.nickname,
)
2021-05-07 12:53:10 +02:00
# %%
print(User.__table__)
# %%
Base.metadata.create_all(engine)
# %%
ed_user = User(name="ed", fullname="Ed Jones", nickname="edsnickname")
2021-05-07 12:53:10 +02:00
print(ed_user.name)
print(ed_user.nickname)
print(str(ed_user.id))
# %%
from sqlalchemy.orm import sessionmaker
2021-05-07 12:53:10 +02:00
Session = sessionmaker(bind=engine)
session = Session()
# %% [markdown]
# # Adding and Updating Objects
# %%
ed_user = User(name="ed", fullname="Ed Jones", nickname="edsnickname")
2021-05-07 12:53:10 +02:00
session.add(ed_user)
# %%
our_user = session.query(User).filter_by(name="ed").first()
2021-05-07 12:53:10 +02:00
print(our_user)
# %%
print(ed_user is our_user)
# %%
session.add_all(
[
User(name="wendy", fullname="Wendy Williams", nickname="windy"),
User(name="mary", fullname="Mary Contrary", nickname="mary"),
User(name="fred", fullname="Fred Flintstone", nickname="freddy"),
]
)
2021-05-07 12:53:10 +02:00
# %%
ed_user.nickname = "eddie"
2021-05-07 12:53:10 +02:00
# %%
print(session.dirty)
# %%
print(session.new)
# %%
session.commit()
# %%
print(ed_user.id)
# %% [markdown]
# # Rolling back
# %%
ed_user.name = "Edwardo"
2021-05-07 12:53:10 +02:00
# %%
fake_user = User(name="fakeuser", fullname="Invalid", nickname="12345")
2021-05-07 12:53:10 +02:00
session.add(fake_user)
# %%
session.query(User).filter(User.name.in_(["Edwardo", "fakeuser"])).all()
2021-05-07 12:53:10 +02:00
# %%
session.rollback()
print(ed_user.name)
print(fake_user in session)
# %%
session.query(User).filter(User.name.in_(["ed", "fakeuser"])).all()