forked from fastapi/sqlmodel
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtutorial005_py310.py
More file actions
50 lines (34 loc) · 1.25 KB
/
tutorial005_py310.py
File metadata and controls
50 lines (34 loc) · 1.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
from sqlalchemy.exc import IntegrityError
from sqlmodel import Field, Session, SQLModel, create_engine
class Hero(SQLModel, table=True):
id: int | None = Field(default=None, primary_key=True)
name: str = Field(unique=True)
age: int
secret_name: str
sqlite_file_name = "database.db"
sqlite_url = f"sqlite:///{sqlite_file_name}"
engine = create_engine(sqlite_url, echo=True)
def create_db_and_tables():
SQLModel.metadata.create_all(engine)
def create_heroes():
hero_1 = Hero(name="Deadpond", age=48, secret_name="Dive Wilson")
with Session(engine) as session:
session.add(hero_1)
session.commit()
session.refresh(hero_1)
print("✅ Created hero:", hero_1)
# Now try to create another hero with the same name
duplicate_hero = Hero(name="Deadpond", age=25, secret_name="Wade Wilson")
session.add(duplicate_hero)
try:
session.commit()
print("❌ This shouldn't happen - duplicate was allowed!")
except IntegrityError as e:
session.rollback()
print("🚫 Constraint violation caught:")
print(f" Error: {e}")
def main():
create_db_and_tables()
create_heroes()
if __name__ == "__main__":
main()