Skip to content

Commit 43da924

Browse files
author
Steven Chen
committed
session and transaction
1 parent 78ca16b commit 43da924

3 files changed

Lines changed: 77 additions & 0 deletions

File tree

15_session/__init__.py

Whitespace-only changes.

15_session/db_init.py

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
import datetime
2+
3+
from sqlalchemy import create_engine, String, ForeignKey
4+
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, relationship
5+
from typing_extensions import Annotated
6+
from typing import List
7+
8+
9+
class Base(DeclarativeBase):
10+
pass
11+
12+
13+
class Base2(DeclarativeBase):
14+
pass
15+
16+
17+
engine = create_engine('mysql://root:test@localhost/testdb', echo=True)
18+
engine2 = create_engine('mysql://root:test@localhost/myblog_db', echo=True)
19+
20+
21+
int_pk = Annotated[int, mapped_column(primary_key=True)]
22+
required_unique_string = Annotated[str, mapped_column(String(128), unique=True, nullable=False)]
23+
required_string = Annotated[str, mapped_column(String(128), nullable=False)]
24+
timestamp_not_null = Annotated[datetime.datetime, mapped_column(nullable=False)]
25+
26+
27+
class User(Base2):
28+
__tablename__ = "users"
29+
30+
id: Mapped[int_pk]
31+
name: Mapped[required_unique_string]
32+
33+
def __repr__(self):
34+
return f'id: {self.id}, name: {self.name}'
35+
36+
37+
class Department(Base):
38+
__tablename__ = "department"
39+
40+
id: Mapped[int_pk]
41+
name: Mapped[required_unique_string]
42+
43+
employees: Mapped[List["Employee"]] = relationship(back_populates="department")
44+
45+
def __repr__(self):
46+
return f'id: {self.id}, name: {self.name}'
47+
48+
49+
class Employee(Base):
50+
__tablename__ = "employee"
51+
52+
id: Mapped[int_pk]
53+
dep_id: Mapped[int] = mapped_column(ForeignKey("department.id"))
54+
name: Mapped[required_unique_string]
55+
birthday: Mapped[timestamp_not_null]
56+
57+
department: Mapped[Department] = relationship(back_populates="employees")
58+
59+
def __repr__(self):
60+
return f'id: {self.id}, dep_id: {self.dep_id}, name: {self.name}, birthday: {self.birthday}'
61+
62+
63+
Base.metadata.create_all(engine)
64+
Base2.metadata.create_all(engine2)

15_session/query.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
from sqlalchemy import select, insert, update, delete
2+
from sqlalchemy.orm import Session
3+
4+
from db_init import engine, engine2, Department, Employee, User
5+
6+
7+
with Session(engine) as session1, session1.begin(), Session(engine2) as session2, session2.begin():
8+
dep = Department(name="pop2")
9+
session1.add(dep)
10+
11+
user = User(name="hhh2")
12+
session2.add(user)
13+

0 commit comments

Comments
 (0)