-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathsync_transaction_example.py
More file actions
37 lines (29 loc) · 1.2 KB
/
sync_transaction_example.py
File metadata and controls
37 lines (29 loc) · 1.2 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
from sqlalchemy import create_engine, Integer, String
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, sessionmaker
# Створення базового класу
class Base(DeclarativeBase):
pass
# Модель User
class User(Base):
__tablename__ = "users"
id: Mapped[int] = mapped_column(Integer, primary_key=True)
username: Mapped[str] = mapped_column(String, nullable=False)
age: Mapped[int] = mapped_column(Integer, nullable=False)
# Налаштування двигуна та сесії
engine = create_engine("sqlite:///:memory:", echo=True)
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
session = Session()
if __name__ == "__main__":
try:
# Початок транзакції
with session.begin():
new_user = User(username="Alice", age=25)
session.add(new_user)
# Виконуємо commit автоматично по завершенні контекстного менеджера
print("Transaction committed successfully.")
except Exception as e:
session.rollback()
print(f"Transaction failed, rolled back. Error: {e}")
finally:
session.close()