Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 | 56x 1x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 3x 1x 2x 1x 2x 2x 2x 4x 4x 1x 4x 4x 8x 3x 8x 8x 2x 8x 2x 8x 2x 3x 2x 8x 2x 3x 2x 8x 8x 8x 1x 1x 1x | // Data Access Layer for Rooms
import { eq, sql, and, asc, inArray, desc, getTableColumns } from "drizzle-orm";
import type { DrizzleD1Database } from "drizzle-orm/d1";
import * as schema from "../db/schema";
import type { Room, NewRoom } from "../db/schema";
export class RoomsDal {
constructor(private db: DrizzleD1Database<typeof schema>) {}
async findByProjectId(projectId: string): Promise<Room[]> {
return this.db
.select()
.from(schema.rooms)
.where(eq(schema.rooms.projectId, projectId))
.orderBy(asc(schema.rooms.sortOrder));
}
async findByProjectIds(projectIds: string[]): Promise<Room[]> {
if (projectIds.length === 0) return [];
return this.db
.select()
.from(schema.rooms)
.where(inArray(schema.rooms.projectId, projectIds))
.orderBy(asc(schema.rooms.sortOrder));
}
async findById(id: number): Promise<Room | undefined> {
const result = await this.db
.select()
.from(schema.rooms)
.where(eq(schema.rooms.id, id))
.limit(1);
return result[0];
}
async create(data: NewRoom): Promise<Room> {
const result = await this.db.insert(schema.rooms).values(data).returning();
return result[0];
}
async update(
id: number,
data: Partial<Omit<Room, "id" | "dateCreated">>,
): Promise<Room | undefined> {
const result = await this.db
.update(schema.rooms)
.set({ ...data, dateUpdated: new Date() })
.where(eq(schema.rooms.id, id))
.returning();
return result[0];
}
async delete(id: number): Promise<boolean> {
const result = await this.db
.delete(schema.rooms)
.where(eq(schema.rooms.id, id))
.returning();
return result.length > 0;
}
async deleteByProjectId(projectId: string): Promise<number> {
const result = await this.db
.delete(schema.rooms)
.where(eq(schema.rooms.projectId, projectId))
.returning();
return result.length;
}
async countByProjectId(projectId: string): Promise<number> {
const result = await this.db
.select({ count: sql<number>`count(*)` })
.from(schema.rooms)
.where(eq(schema.rooms.projectId, projectId));
return result[0]?.count ?? 0;
}
async getMaxSortOrder(projectId: string): Promise<number> {
const result = await this.db
.select({ maxSort: sql<number>`max(sort_order)` })
.from(schema.rooms)
.where(eq(schema.rooms.projectId, projectId));
return result[0]?.maxSort ?? 0;
}
async updateSortOrder(roomIds: number[]): Promise<void> {
// Batch update sort order using a single CASE WHEN statement
if (roomIds.length === 0) return;
const cases = roomIds.map((id, i) => sql`WHEN ${id} THEN ${i}`);
await this.db
.update(schema.rooms)
.set({
sortOrder: sql`CASE ${schema.rooms.id} ${sql.join(cases, sql` `)} END`,
dateUpdated: new Date(),
})
.where(inArray(schema.rooms.id, roomIds));
}
async findProjectIdsByRoomTypes(roomTypeCodes: string[]): Promise<string[]> {
if (roomTypeCodes.length === 0) return [];
const result = await this.db
.selectDistinct({ projectId: schema.rooms.projectId })
.from(schema.rooms)
.where(inArray(schema.rooms.roomType, roomTypeCodes));
return result.map((r) => r.projectId);
}
async findBySlug(slug: string): Promise<schema.Room | null> {
const result = await this.db
.select()
.from(schema.rooms)
.where(eq(schema.rooms.slug, slug))
.limit(1);
return result[0] || null;
}
async slugExists(slug: string, excludeId?: number): Promise<boolean> {
const conditions = [eq(schema.rooms.slug, slug)];
if (excludeId) {
conditions.push(sql`${schema.rooms.id} != ${excludeId}`);
}
const result = await this.db
.select({ count: sql<number>`count(*)` })
.from(schema.rooms)
.where(and(...conditions));
return (result[0]?.count ?? 0) > 0;
}
/**
* Find published rooms: rooms from published projects of published pros.
* Only includes rooms that have at least one media item.
* Supports filtering by room type, style tags, budget ranges, materials, property types.
* Returns paginated results sorted by room dateCreated desc.
*
* Caller does NOT pass the list of project IDs — the published/visibility
* constraint is resolved server-side via a correlated EXISTS subquery on
* projects INNER JOIN pros. Prior implementations pre-fetched every published
* project ID into an `inArray()` bind list, which combined with the
* `roomType IN (...)` + `budgetSpent IN (...)` filters blew past D1's
* 100-parameter statement limit once the catalog grew. Same predicate
* pattern as homepage.ts Step 6 and projects.dal.ts requirePublishedPro.
*/
async findPublishedRooms(
filters: {
roomTypes?: string[];
styleTags?: string[];
budgetRanges?: string[];
materials?: string[];
propertyTypes?: string[];
},
page: number,
limit: number,
): Promise<{ rooms: Room[]; total: number }> {
const propertyTypeFilter =
filters.propertyTypes && filters.propertyTypes.length > 0
? sql` AND projects.property_type IN (${sql.join(
filters.propertyTypes.map((t) => sql`${t}`),
sql`, `,
)})`
: sql``;
const conditions: ReturnType<typeof and>[] = [
// Constrain rooms to published projects of published pros via a
// correlated EXISTS — no project-ID materialization, so the bind
// count stays bounded by the other filters on this WHERE.
sql`EXISTS (
SELECT 1 FROM projects
INNER JOIN pros ON pros.id = projects.pro_id
WHERE projects.id = ${schema.rooms.projectId}
AND projects.status = 'published'
AND pros.status = 'published'${propertyTypeFilter}
)`,
// Only include rooms that have at least one media item.
sql`EXISTS (SELECT 1 FROM media WHERE media.room_id = ${schema.rooms.id})`,
];
// Room type filter
if (filters.roomTypes && filters.roomTypes.length > 0) {
conditions.push(inArray(schema.rooms.roomType, filters.roomTypes));
}
// Budget range filter (room-level budgetSpent)
if (filters.budgetRanges && filters.budgetRanges.length > 0) {
conditions.push(
inArray(
schema.rooms.budgetSpent,
filters.budgetRanges as NonNullable<schema.Room["budgetSpent"]>[],
),
);
}
// Style tags filter: room-level styleTags JSON array overlap check
if (filters.styleTags && filters.styleTags.length > 0) {
const styleTagCondition = sql`EXISTS (
SELECT 1 FROM json_each(${schema.rooms.styleTags})
WHERE json_each.value IN (${sql.join(
filters.styleTags.map((t) => sql`${t}`),
sql`, `,
)})
)`;
conditions.push(styleTagCondition);
}
// Materials filter: room-level materials JSON array
if (filters.materials && filters.materials.length > 0) {
const materialCondition = sql`EXISTS (
SELECT 1 FROM json_each(${schema.rooms.materials})
WHERE json_each.value IN (${sql.join(
filters.materials.map((m) => sql`${m}`),
sql`, `,
)})
)`;
conditions.push(materialCondition);
}
const whereClause = and(...conditions);
// Count total matching rooms
const countResult = await this.db
.select({ count: sql<number>`count(*)` })
.from(schema.rooms)
.where(whereClause);
/* v8 ignore start -- V8 artifact: ?? fallback never reached */
const total = countResult[0]?.count ?? 0;
/* v8 ignore stop */
if (total === 0) return { rooms: [], total: 0 };
// Fetch paginated rooms.
// 1C+1D: window function provides max-2-per-pro diversity by ranking within
// partitions; outer ORDER BY then sorts by featured > rank > quality > date
// with hour-of-day tiebreaker. Rooms inherit project quality score —
// we sort by the parent project's is_featured and quality_score.
//
// Gemini review #2 + #4: replaced 4 correlated subqueries (one per row)
// with a single innerJoin against projects. Tiebreaker uses the integer
// rooms.id directly instead of unicode(substr(id,1,1)) which had poor
// distribution (every id starting with '1' got the same shuffle bucket).
const offset = (page - 1) * limit;
const rooms = await this.db
.select(getTableColumns(schema.rooms))
.from(schema.rooms)
.innerJoin(schema.projects, eq(schema.rooms.projectId, schema.projects.id))
.where(whereClause)
.orderBy(
desc(schema.projects.isFeatured),
sql`ROW_NUMBER() OVER (
PARTITION BY ${schema.projects.proId}
ORDER BY ${schema.projects.qualityScore} DESC,
${schema.rooms.dateCreated} DESC
)`,
desc(schema.projects.qualityScore),
desc(schema.rooms.dateCreated),
sql`(${schema.rooms.id} + ${new Date().getUTCHours()}) % 1000`,
)
.limit(limit)
.offset(offset);
return { rooms, total };
}
async findByIds(ids: number[]): Promise<Map<number, Room>> {
if (ids.length === 0) return new Map();
const result = await this.db
.select()
.from(schema.rooms)
.where(inArray(schema.rooms.id, ids));
const map = new Map<number, Room>();
for (const room of result) {
map.set(room.id, room);
}
return map;
}
}
|