Skip to content

Commit d778131

Browse files
committed
✨ Add (module): SQLAlchemy ORM example
1 parent 84c3ca7 commit d778131

File tree

1 file changed

+129
-0
lines changed

1 file changed

+129
-0
lines changed

introduction/sa_orm.py

Lines changed: 129 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,129 @@
1+
"""
2+
This module demonstrates the use of SQLAlchemy as a full Object Relational
3+
Mapper (ORM) for interacting with a SQL database. It defines classes
4+
representing database tables and includes functionality to add players to
5+
teams, leveraging the ORM capabilities for database operations.
6+
"""
7+
8+
from typing import Optional, Type
9+
10+
from sqlalchemy import (
11+
Column,
12+
Engine,
13+
ForeignKey,
14+
Integer,
15+
String,
16+
create_engine,
17+
)
18+
from sqlalchemy.orm import (
19+
DeclarativeBase,
20+
declarative_base,
21+
relationship,
22+
sessionmaker,
23+
)
24+
25+
Base: Type[DeclarativeBase] = declarative_base()
26+
url: str = "mssql+pyodbc://user:[email protected]"
27+
engine: Engine = create_engine(
28+
url,
29+
pool_pre_ping=True,
30+
future=True,
31+
echo=True,
32+
)
33+
Session = sessionmaker(
34+
bind=engine,
35+
)
36+
session = Session()
37+
38+
39+
class Team(Base): # type: ignore
40+
"""
41+
Represents a team in the database with its name and list of players.
42+
"""
43+
44+
__tablename__ = "teams"
45+
46+
id = Column(
47+
Integer,
48+
primary_key=True,
49+
)
50+
name = Column(
51+
String,
52+
)
53+
players = relationship(
54+
"Player",
55+
backref="team",
56+
)
57+
58+
59+
class Player(Base): # type: ignore
60+
"""
61+
Represents a player in the database with the name of the player and the
62+
jersey.
63+
"""
64+
65+
__tablename__ = "players"
66+
67+
id = Column(
68+
Integer,
69+
primary_key=True,
70+
)
71+
name = Column(
72+
String,
73+
)
74+
number = Column(
75+
Integer,
76+
)
77+
team_id = Column(
78+
Integer,
79+
ForeignKey("teams.id"),
80+
)
81+
82+
83+
Base.metadata.create_all(
84+
engine,
85+
)
86+
87+
88+
def add_player_to_team(
89+
player_name: str,
90+
player_number: int,
91+
team_name: str,
92+
) -> None:
93+
"""
94+
Adds a player to a team in the database, creating the team if it does not
95+
exist.
96+
:param player_name: Name of the player to be added.
97+
:type player_name: str
98+
:param player_number: Jersey number of the player.
99+
:type player_number: int
100+
:param team_name: Name of the team to which the player will be added.
101+
:type team_name: str
102+
:return: None
103+
:rtype: NoneType
104+
"""
105+
team: Optional[Type[Team]] | Team = (
106+
session.query(Team).filter_by(name=team_name).first()
107+
)
108+
if not team:
109+
team = Team(
110+
name=team_name,
111+
)
112+
session.add(team)
113+
session.commit()
114+
new_player = Player(
115+
team.id,
116+
player_name,
117+
player_number,
118+
)
119+
session.add(new_player)
120+
session.commit()
121+
122+
123+
add_player_to_team(
124+
"Juan Carlos",
125+
9,
126+
"FC Pythonistas",
127+
)
128+
if fcp_team := (session.query(Team).filter_by(name="FC Pythonistas").first()):
129+
print(f"Team: {fcp_team.name}")

0 commit comments

Comments
 (0)