Skip to content

Commit 6d8cb04

Browse files
committed
syntax
1 parent 041c89f commit 6d8cb04

File tree

5 files changed

+177
-15
lines changed

5 files changed

+177
-15
lines changed

examples/sqlalchemy_1.6_to_2.0/README.md

Lines changed: 2 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -60,23 +60,10 @@ The migration script handles four key transformations:
6060
addresses: Mapped[List["Address"]] = relationship()
6161
```
6262

63-
## Running the Example
64-
65-
```bash
66-
# Install Codegen
67-
pip install codegen
68-
69-
# Run the migration
70-
python run.py
71-
```
72-
73-
The script will process all Python files in the `repo-before` directory and apply the transformations in the correct order.
74-
7563
## Understanding the Code
7664

77-
- `run.py` - The migration script
78-
- `repo-before/` - Sample SQLAlchemy 1.6 application to migrate
79-
- `guide.md` - Additional notes and explanations
65+
- `input_repo` - Sample SQLAlchemy 1.6 application to migrate
66+
- `output_repo` - Sample SQLAlchemy 2.0 application after migration
8067

8168
## Learn More
8269

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
# database.py
2+
from sqlalchemy import create_engine
3+
from sqlalchemy.orm import sessionmaker
4+
5+
SQLALCHEMY_DATABASE_URL = "postgresql://user:password@localhost/dbname" # Change to your database URL
6+
7+
engine = create_engine(SQLALCHEMY_DATABASE_URL)
8+
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
9+
10+
Base = declarative_base()
Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
# main.py
2+
from fastapi import FastAPI, Depends, HTTPException
3+
from sqlalchemy.orm import Session
4+
import models
5+
import schemas
6+
from database import SessionLocal, engine
7+
from typing import List
8+
9+
# Initialize the app and create database tables
10+
app = FastAPI()
11+
models.Base.metadata.create_all(bind=engine)
12+
13+
# Dependency for the database session
14+
def get_db():
15+
db = SessionLocal()
16+
try:
17+
yield db
18+
finally:
19+
db.close()
20+
21+
# CRUD Operations
22+
23+
@app.post("/books/", response_model=schemas.Book)
24+
def create_book(book: schemas.BookCreate, db: Session = Depends(get_db)):
25+
db_book = models.Book(**book.dict())
26+
db.add(db_book)
27+
db.commit()
28+
db.refresh(db_book)
29+
return db_book
30+
31+
@app.get("/books/", response_model=List[schemas.Book])
32+
def read_books(skip: int = 0, limit: int = 10, db: Session = Depends(get_db)):
33+
books = db.query()(models.Book).offset(skip).limit(limit).scalars().all()
34+
return books
35+
36+
@app.get("/books/{book_id}", response_model=schemas.Book)
37+
def read_book(book_id: int, db: Session = Depends(get_db)):
38+
book = db.query()(models.Book).where(models.Book.id == book_id).first()
39+
if book is None:
40+
raise HTTPException(status_code=404, detail="Book not found")
41+
return book
42+
43+
@app.put("/books/{book_id}", response_model=schemas.Book)
44+
def update_book(book_id: int, book: schemas.BookCreate, db: Session = Depends(get_db)):
45+
db_book = db.query()(models.Book).where(models.Book.id == book_id).first()
46+
if db_book is None:
47+
raise HTTPException(status_code=404, detail="Book not found")
48+
for key, value in book.dict().items():
49+
setattr(db_book, key, value)
50+
db.commit()
51+
db.refresh(db_book)
52+
return db_book
53+
54+
@app.delete("/books/{book_id}", response_model=schemas.Book)
55+
def delete_book(book_id: int, db: Session = Depends(get_db)):
56+
db_book = db.query()(models.Book).where(models.Book.id == book_id).first()
57+
if db_book is None:
58+
raise HTTPException(status_code=404, detail="Book not found")
59+
db.delete(db_book)
60+
db.commit()
61+
return db_book
62+
63+
@app.post("/publishers/", response_model=schemas.Publisher)
64+
def create_publisher(publisher: schemas.PublisherCreate, db: Session = Depends(get_db)):
65+
db_publisher = models.Publisher(**publisher.dict())
66+
db.add(db_publisher)
67+
db.commit()
68+
db.refresh(db_publisher)
69+
return db_publisher
70+
71+
@app.get("/publishers/", response_model=List[schemas.Publisher])
72+
def read_publishers(skip: int = 0, limit: int = 10, db: Session = Depends(get_db)):
73+
publishers = db.query()(models.Publisher).offset(skip).limit(limit).scalars().all()
74+
return publishers
75+
76+
@app.get("/publishers/{publisher_id}", response_model=schemas.Publisher)
77+
def read_publisher(publisher_id: int, db: Session = Depends(get_db)):
78+
publisher = db.query()(models.Publisher).where(models.Publisher.id == publisher_id).first()
79+
if not publisher:
80+
raise HTTPException(status_code=404, detail="Publisher not found")
81+
return publisher
82+
83+
@app.put("/publishers/{publisher_id}", response_model=schemas.Publisher)
84+
def update_publisher(publisher_id: int, publisher: schemas.PublisherCreate, db: Session = Depends(get_db)):
85+
db_publisher = db.query()(models.Publisher).where(models.Publisher.id == publisher_id).first()
86+
if not db_publisher:
87+
raise HTTPException(status_code=404, detail="Publisher not found")
88+
for key, value in publisher.dict().items():
89+
setattr(db_publisher, key, value)
90+
db.commit()
91+
db.refresh(db_publisher)
92+
return db_publisher
93+
94+
@app.delete("/publishers/{publisher_id}", response_model=schemas.Publisher)
95+
def delete_publisher(publisher_id: int, db: Session = Depends(get_db)):
96+
db_publisher = db.query()(models.Publisher).where(models.Publisher.id == publisher_id).first()
97+
if not db_publisher:
98+
raise HTTPException(status_code=404, detail="Publisher not found")
99+
db.delete(db_publisher)
100+
db.commit()
101+
return db_publisher
102+
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
from typing import List, Optional
2+
from sqlalchemy import Integer, String, ForeignKey
3+
from sqlalchemy.orm import relationship, Mapped, mapped_column
4+
from database import Base
5+
6+
class Publisher(Base):
7+
__tablename__ = "publishers"
8+
9+
id: Mapped[int] = mapped_column(Integer, primary_key=True, index=True)
10+
name: Mapped[str] = mapped_column(String, unique=True, index=True)
11+
books: Mapped[List["Book"]] = relationship(
12+
"Book",
13+
back_populates="publisher",
14+
lazy='selectin'
15+
)
16+
17+
class Book(Base):
18+
__tablename__ = "books"
19+
20+
id: Mapped[int] = mapped_column(Integer, primary_key=True, index=True)
21+
title: Mapped[str] = mapped_column(String, index=True)
22+
author: Mapped[str] = mapped_column(String, index=True)
23+
description: Mapped[Optional[str]] = mapped_column(String, nullable=True)
24+
publisher_id: Mapped[Optional[int]] = mapped_column(
25+
Integer,
26+
ForeignKey("publishers.id"),
27+
nullable=True
28+
)
29+
publisher: Mapped[Optional["Publisher"]] = relationship(
30+
"Publisher",
31+
back_populates="books"
32+
)
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
from pydantic import BaseModel
2+
from typing import List, Optional
3+
4+
class PublisherBase(BaseModel):
5+
name: str
6+
7+
class PublisherCreate(PublisherBase):
8+
pass
9+
10+
class Publisher(PublisherBase):
11+
id: int
12+
books: List["Book"] = []
13+
14+
class Config:
15+
orm_mode = True
16+
17+
class BookBase(BaseModel):
18+
title: str
19+
author: str
20+
description: str
21+
publisher_id: Optional[int]
22+
23+
class BookCreate(BookBase):
24+
pass
25+
26+
class Book(BookBase):
27+
id: int
28+
publisher: Optional[Publisher]
29+
30+
class Config:
31+
orm_mode = True

0 commit comments

Comments
 (0)