Skip to content

Commit db36ba3

Browse files
author
Steven Chen
committed
new mapping
1 parent 8858e6e commit db36ba3

3 files changed

Lines changed: 40 additions & 0 deletions

File tree

09_new_mapping/__init__.py

Whitespace-only changes.

09_new_mapping/db_init.py

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
import datetime
2+
3+
from sqlalchemy import create_engine, String
4+
from sqlalchemy.ext.declarative import declarative_base
5+
from sqlalchemy.orm import sessionmaker, Mapped, mapped_column
6+
from sqlalchemy.sql import func
7+
from typing_extensions import Annotated
8+
9+
10+
engine = create_engine('mysql://root:test@localhost/testdb', echo=True)
11+
Base = declarative_base()
12+
13+
14+
int_pk = Annotated[int, mapped_column(primary_key=True)]
15+
required_unique_name = Annotated[str, mapped_column(String(128), unique=True, nullable=False)]
16+
timestamp_default_now = Annotated[datetime.datetime, mapped_column(nullable=False, server_default=func.now())]
17+
18+
19+
class Customer(Base):
20+
__tablename__ = "customers"
21+
22+
id: Mapped[int_pk]
23+
name: Mapped[required_unique_name]
24+
birthday: Mapped[datetime.datetime]
25+
city: Mapped[str] = mapped_column(String(128), nullable=True)
26+
create_time: Mapped[timestamp_default_now]
27+
28+
29+
Base.metadata.create_all(engine)
30+
Session = sessionmaker(bind=engine)

09_new_mapping/query.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
from db_init import Session, Customer
2+
3+
4+
session = Session()
5+
6+
c = Customer(name="Jack", birthday="2000-10-1")
7+
8+
session.add(c)
9+
10+
session.commit()

0 commit comments

Comments
 (0)