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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
|
from sqlalchemy.orm import Session, joinedload, selectinload, subqueryload
from sqlalchemy import func, desc, asc, and_, or_, exists, case
from database import SessionLocal, engine, Base
from models import User, Post, Comment
from advanced_models import Category, Tag, AdvancedPost, PostStatus
import random
def create_advanced_sample_data():
"""Create more complex sample data"""
# Create tables first
Base.metadata.create_all(bind=engine)
db = SessionLocal()
try:
# Create categories with hierarchy
tech_category = Category(name="Technology", description="Tech-related posts")
python_category = Category(name="Python", description="Python programming", parent=tech_category)
web_category = Category(name="Web Development", description="Web development topics", parent=tech_category)
db.add_all([tech_category, python_category, web_category])
db.commit()
# Create tags
tags = [
Tag(name="python"),
Tag(name="sqlalchemy"),
Tag(name="database"),
Tag(name="orm"),
Tag(name="tutorial"),
Tag(name="beginner"),
Tag(name="advanced")
]
db.add_all(tags)
db.commit()
# Get existing user
user = db.query(User).first()
if not user:
print("No users found. Please run crud_operations.py first.")
return
# Create advanced posts with relationships
posts_data = [
{
"title": "SQLAlchemy Relationships Explained",
"content": "Deep dive into SQLAlchemy relationships...",
"status": PostStatus.PUBLISHED,
"category": python_category,
"tags": [tags[0], tags[1], tags[4]] # python, sqlalchemy, tutorial
},
{
"title": "Database Design Best Practices",
"content": "Learn how to design efficient databases...",
"status": PostStatus.PUBLISHED,
"category": tech_category,
"tags": [tags[2], tags[6]] # database, advanced
},
{
"title": "ORM vs Raw SQL",
"content": "Comparing ORM and raw SQL approaches...",
"status": PostStatus.DRAFT,
"category": python_category,
"tags": [tags[3], tags[2]] # orm, database
}
]
for post_data in posts_data:
post = AdvancedPost(
title=post_data["title"],
content=post_data["content"],
status=post_data["status"],
author=user,
category=post_data["category"],
tags=post_data["tags"],
view_count=random.randint(10, 1000)
)
db.add(post)
db.commit()
print("✅ Advanced sample data created!")
except Exception as e:
print(f"❌ Error creating advanced data: {e}")
db.rollback()
finally:
db.close()
def demonstrate_advanced_queries():
"""Demonstrate advanced querying techniques"""
db = SessionLocal()
try:
print("=== Eager Loading Examples ===")
# Lazy loading (default) - causes N+1 problem
posts = db.query(AdvancedPost).all()
print("Posts with lazy loading:")
for post in posts:
print(f" - {post.title} by {post.author.username} in {post.category.name if post.category else 'No category'}")
# Eager loading with joinedload (LEFT JOIN)
posts_with_author = db.query(AdvancedPost).options(
joinedload(AdvancedPost.author),
joinedload(AdvancedPost.category),
joinedload(AdvancedPost.tags)
).all()
print("\nPosts with eager loading:")
for post in posts_with_author:
tag_names = [tag.name for tag in post.tags]
print(f" - {post.title} (tags: {', '.join(tag_names)})")
print("\n=== Aggregation Queries ===")
# Count posts by status
status_counts = db.query(
AdvancedPost.status,
func.count(AdvancedPost.id).label('count')
).group_by(AdvancedPost.status).all()
print("Posts by status:")
for status, count in status_counts:
print(f" - {status.value}: {count}")
# Average view count by category
avg_views = db.query(
Category.name,
func.avg(AdvancedPost.view_count).label('avg_views')
).join(AdvancedPost).group_by(Category.name).all()
print("\nAverage views by category:")
for category, avg in avg_views:
print(f" - {category}: {avg:.1f}")
print("\n=== Subqueries and CTEs ===")
# Subquery: Find users with above-average post count
avg_post_count = db.query(func.avg(
db.query(func.count(AdvancedPost.id))
.filter(AdvancedPost.author_id == User.id)
.scalar_subquery()
)).scalar()
prolific_users = db.query(User).filter(
db.query(func.count(AdvancedPost.id))
.filter(AdvancedPost.author_id == User.id)
.scalar_subquery() > avg_post_count
).all()
print(f"Users with above-average post count (avg: {avg_post_count:.1f}):")
for user in prolific_users:
post_count = db.query(func.count(AdvancedPost.id)).filter(
AdvancedPost.author_id == user.id
).scalar()
print(f" - {user.username}: {post_count} posts")
print("\n=== Window Functions ===")
# Rank posts by view count within each category
from sqlalchemy import text
ranked_posts = db.execute(text("""
SELECT
title,
view_count,
c.name as category_name,
RANK() OVER (PARTITION BY category_id ORDER BY view_count DESC) as rank
FROM advanced_posts ap
LEFT JOIN categories c ON ap.category_id = c.id
ORDER BY c.name, rank
""")).fetchall()
print("Posts ranked by views within category:")
current_category = None
for title, views, category, rank in ranked_posts:
if category != current_category:
print(f"\n {category or 'No Category'}:")
current_category = category
print(f" {rank}. {title} ({views} views)")
print("\n=== Complex Filtering ===")
# Posts with specific tags and high view count
popular_python_posts = db.query(AdvancedPost).join(
AdvancedPost.tags
).filter(
and_(
Tag.name.in_(['python', 'sqlalchemy']),
AdvancedPost.view_count > 100,
AdvancedPost.status == PostStatus.PUBLISHED
)
).distinct().all()
print("Popular Python/SQLAlchemy posts:")
for post in popular_python_posts:
print(f" - {post.title} ({post.view_count} views)")
# Posts in categories with subcategories
posts_in_parent_categories = db.query(AdvancedPost).join(
Category
).filter(
exists().where(Category.parent_id == AdvancedPost.category_id)
).all()
print(f"\nPosts in parent categories: {len(posts_in_parent_categories)}")
except Exception as e:
print(f"❌ Error in advanced queries: {e}")
finally:
db.close()
if __name__ == "__main__":
create_advanced_sample_data()
print("\n" + "="*60)
demonstrate_advanced_queries()
|