temdb 3.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. temdb/alembic.ini +29 -0
  2. temdb/migrations/env.py +66 -0
  3. temdb/migrations/script.py.mako +28 -0
  4. temdb/migrations/versions/.gitkeep +0 -0
  5. temdb/migrations/versions/20260612_0001_initial_schema.py +542 -0
  6. temdb/migrations/versions/20260717_ec4c96d0bf77_add_description_to_block_table.py +32 -0
  7. temdb/migrations/versions/20260721_44f75ed44d66_updated_at_nullable_no_server_default.py +165 -0
  8. temdb/migrations/versions/20260721_bec991e0d0eb_dataset_status_server_default.py +38 -0
  9. temdb/migrations/versions/20260801_a1d2f3e4b5c6_add_sections_run_parameters.py +67 -0
  10. temdb/server/__init__.py +3 -0
  11. temdb/server/api/__init__.py +0 -0
  12. temdb/server/api/v2/__init__.py +0 -0
  13. temdb/server/api/v2/acquisition.py +1094 -0
  14. temdb/server/api/v2/block.py +228 -0
  15. temdb/server/api/v2/cutting_session.py +229 -0
  16. temdb/server/api/v2/dataset.py +139 -0
  17. temdb/server/api/v2/lens_correction.py +121 -0
  18. temdb/server/api/v2/microscope.py +93 -0
  19. temdb/server/api/v2/quality_control.py +185 -0
  20. temdb/server/api/v2/roi.py +372 -0
  21. temdb/server/api/v2/section.py +457 -0
  22. temdb/server/api/v2/specimen.py +246 -0
  23. temdb/server/api/v2/substrate.py +180 -0
  24. temdb/server/api/v2/tasks.py +508 -0
  25. temdb/server/cli.py +48 -0
  26. temdb/server/config.py +46 -0
  27. temdb/server/database.py +75 -0
  28. temdb/server/dependencies.py +24 -0
  29. temdb/server/exception_handlers.py +109 -0
  30. temdb/server/ids.py +12 -0
  31. temdb/server/main.py +172 -0
  32. temdb/server/sqlmodels/__init__.py +29 -0
  33. temdb/server/sqlmodels/acquisition.py +101 -0
  34. temdb/server/sqlmodels/base.py +41 -0
  35. temdb/server/sqlmodels/block.py +18 -0
  36. temdb/server/sqlmodels/cutting_session.py +27 -0
  37. temdb/server/sqlmodels/dataset.py +34 -0
  38. temdb/server/sqlmodels/lens_correction.py +36 -0
  39. temdb/server/sqlmodels/microscope.py +22 -0
  40. temdb/server/sqlmodels/roi.py +55 -0
  41. temdb/server/sqlmodels/section.py +55 -0
  42. temdb/server/sqlmodels/specimen.py +17 -0
  43. temdb/server/sqlmodels/substrate.py +23 -0
  44. temdb/server/sqlmodels/task.py +60 -0
  45. temdb/server/sqlmodels/tile.py +53 -0
  46. temdb/server/sqlmodels/tile_partition.py +147 -0
  47. temdb-3.0.0.dist-info/METADATA +16 -0
  48. temdb-3.0.0.dist-info/RECORD +51 -0
  49. temdb-3.0.0.dist-info/WHEEL +4 -0
  50. temdb-3.0.0.dist-info/entry_points.txt +3 -0
  51. temdb-3.0.0.dist-info/licenses/LICENSE +11 -0
@@ -0,0 +1,228 @@
1
+ from datetime import datetime, timezone
2
+
3
+ from fastapi import APIRouter, Body, Depends, HTTPException, Query, status
4
+ from sqlalchemy import and_, func, select
5
+ from sqlalchemy.ext.asyncio import AsyncSession
6
+
7
+ from temdb.models import BlockCreate, BlockResponse, BlockUpdate, CuttingSessionResponse
8
+ from temdb.server.dependencies import get_async_session
9
+ from temdb.server.sqlmodels import BlockSQLModel, CuttingSessionSQLModel, SpecimenSQLModel
10
+
11
+ block_api = APIRouter(
12
+ tags=["Blocks"],
13
+ )
14
+
15
+
16
+ @block_api.get("/blocks", response_model=list[BlockResponse])
17
+ async def list_blocks(
18
+ specimen_id: str | None = Query(None, description="Filter by human-readable Specimen ID"),
19
+ skip: int = Query(0, ge=0),
20
+ limit: int = Query(10, ge=1, le=100),
21
+ session: AsyncSession = Depends(get_async_session),
22
+ ):
23
+ """Retrieve a list of blocks, optionally filtered by specimen ID."""
24
+ statement = select(BlockSQLModel)
25
+ if specimen_id:
26
+ statement = statement.where(BlockSQLModel.specimen_id == specimen_id)
27
+ return (await session.execute(statement.offset(skip).limit(limit))).scalars().all()
28
+
29
+
30
+ @block_api.get(
31
+ "/blocks/specimens/{specimen_id}/blocks/{block_id}/cut-sessions",
32
+ response_model=list[CuttingSessionResponse],
33
+ )
34
+ async def get_block_cut_sessions(
35
+ specimen_id: str,
36
+ block_id: str,
37
+ skip: int = Query(0, ge=0),
38
+ limit: int = Query(10, ge=1, le=100),
39
+ session: AsyncSession = Depends(get_async_session),
40
+ ):
41
+ """Retrieve cutting sessions associated with a specific block."""
42
+ rows = (
43
+ (
44
+ await session.execute(
45
+ select(CuttingSessionSQLModel)
46
+ .select_from(BlockSQLModel)
47
+ .outerjoin(
48
+ CuttingSessionSQLModel,
49
+ and_(
50
+ CuttingSessionSQLModel.block_id == BlockSQLModel.block_id,
51
+ CuttingSessionSQLModel.specimen_id == BlockSQLModel.specimen_id,
52
+ ),
53
+ )
54
+ .where(
55
+ BlockSQLModel.block_id == block_id,
56
+ BlockSQLModel.specimen_id == specimen_id,
57
+ )
58
+ .offset(skip)
59
+ .limit(limit)
60
+ )
61
+ )
62
+ .scalars()
63
+ .all()
64
+ )
65
+ if not rows:
66
+ raise HTTPException(
67
+ status_code=status.HTTP_404_NOT_FOUND,
68
+ detail=f"Block with ID '{block_id}' for specimen '{specimen_id}' not found",
69
+ )
70
+ cutting_sessions = [c for c in rows if c is not None]
71
+ if not cutting_sessions:
72
+ raise HTTPException(
73
+ status_code=status.HTTP_404_NOT_FOUND,
74
+ detail=f"No cutting sessions found for block '{block_id}' and specimen '{specimen_id}'",
75
+ )
76
+ return cutting_sessions
77
+
78
+
79
+ @block_api.post("/blocks", status_code=status.HTTP_201_CREATED, response_model=BlockResponse)
80
+ async def create_block(
81
+ block_data: BlockCreate,
82
+ session: AsyncSession = Depends(get_async_session),
83
+ ):
84
+ """Create a new block associated with a specimen."""
85
+ specimen = await session.scalars(
86
+ select(SpecimenSQLModel).where(SpecimenSQLModel.specimen_id == block_data.specimen_id)
87
+ )
88
+ specimen_obj = specimen.one_or_none()
89
+ if specimen_obj is None:
90
+ raise HTTPException(
91
+ status_code=status.HTTP_404_NOT_FOUND,
92
+ detail=f"Specimen with ID '{block_data.specimen_id}' not found",
93
+ )
94
+ existing_block = await session.scalars(
95
+ select(BlockSQLModel).where(
96
+ BlockSQLModel.block_id == block_data.block_id,
97
+ BlockSQLModel.specimen_id == block_data.specimen_id,
98
+ )
99
+ )
100
+ if existing_block.one_or_none() is not None:
101
+ raise HTTPException(
102
+ status_code=status.HTTP_400_BAD_REQUEST,
103
+ detail=(f"Block with ID '{block_data.block_id}' already exists for specimen '{block_data.specimen_id}'"),
104
+ )
105
+ new_block = BlockSQLModel(
106
+ block_id=block_data.block_id,
107
+ specimen_id=block_data.specimen_id,
108
+ microCT_info=block_data.microCT_info,
109
+ created_at=block_data.created_at or datetime.now(timezone.utc),
110
+ description=block_data.description,
111
+ )
112
+ session.add(new_block)
113
+ await session.commit()
114
+ await session.refresh(new_block)
115
+ return new_block
116
+
117
+
118
+ @block_api.get("/blocks/specimens/{specimen_id}/blocks/{block_id}", response_model=BlockResponse)
119
+ async def get_block(
120
+ specimen_id: str,
121
+ block_id: str,
122
+ session: AsyncSession = Depends(get_async_session),
123
+ ):
124
+ """Retrieve a specific block by its human-readable ID and specimen ID."""
125
+ block = (
126
+ await session.execute(
127
+ select(BlockSQLModel).where(BlockSQLModel.block_id == block_id, BlockSQLModel.specimen_id == specimen_id)
128
+ )
129
+ ).scalar_one_or_none()
130
+ if block is None:
131
+ raise HTTPException(
132
+ status_code=status.HTTP_404_NOT_FOUND,
133
+ detail=f"Block with ID '{block_id}' for specimen '{specimen_id}' not found",
134
+ )
135
+ return block
136
+
137
+
138
+ @block_api.patch("/blocks/specimens/{specimen_id}/blocks/{block_id}", response_model=BlockResponse)
139
+ async def update_block(
140
+ specimen_id: str,
141
+ block_id: str,
142
+ updated_fields: BlockUpdate = Body(...),
143
+ session: AsyncSession = Depends(get_async_session),
144
+ ):
145
+ """Update details of a specific block."""
146
+ block_obj = (
147
+ await session.execute(
148
+ select(BlockSQLModel).where(BlockSQLModel.block_id == block_id, BlockSQLModel.specimen_id == specimen_id)
149
+ )
150
+ ).scalar_one_or_none()
151
+ if block_obj is None:
152
+ raise HTTPException(
153
+ status_code=status.HTTP_404_NOT_FOUND,
154
+ detail=f"Block with ID '{block_id}' for specimen '{specimen_id}' not found",
155
+ )
156
+ update_data = updated_fields.model_dump(exclude_unset=True)
157
+ if not update_data:
158
+ raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="No update data provided")
159
+ for field, value in update_data.items():
160
+ setattr(block_obj, field, value)
161
+ block_obj.updated_at = datetime.now(timezone.utc)
162
+ session.add(block_obj)
163
+ await session.commit()
164
+ await session.refresh(block_obj)
165
+ return block_obj
166
+
167
+
168
+ @block_api.delete(
169
+ "/blocks/specimens/{specimen_id}/blocks/{block_id}",
170
+ status_code=status.HTTP_204_NO_CONTENT,
171
+ )
172
+ async def delete_block(
173
+ specimen_id: str,
174
+ block_id: str,
175
+ session: AsyncSession = Depends(get_async_session),
176
+ ):
177
+ """Delete a specific block."""
178
+ block = await session.scalars(
179
+ select(BlockSQLModel).where(BlockSQLModel.block_id == block_id, BlockSQLModel.specimen_id == specimen_id)
180
+ )
181
+ block_obj = block.one_or_none()
182
+ if block_obj is None:
183
+ raise HTTPException(
184
+ status_code=status.HTTP_404_NOT_FOUND,
185
+ detail=f"Block with ID '{block_id}' for specimen '{specimen_id}' not found",
186
+ )
187
+ session_count = (
188
+ await session.scalars(
189
+ select(func.count())
190
+ .select_from(CuttingSessionSQLModel)
191
+ .where(
192
+ CuttingSessionSQLModel.block_id == block_id,
193
+ CuttingSessionSQLModel.specimen_id == specimen_id,
194
+ )
195
+ )
196
+ ).one()
197
+ if session_count > 0:
198
+ raise HTTPException(
199
+ status_code=status.HTTP_400_BAD_REQUEST,
200
+ detail=(f"Cannot delete block '{block_id}' as it has {session_count} associated cutting sessions."),
201
+ )
202
+ await session.delete(block_obj)
203
+ await session.commit()
204
+ return None
205
+
206
+
207
+ @block_api.get("/blocks/specimens/{specimen_id}/blocks", response_model=list[BlockResponse])
208
+ async def list_specimen_blocks(
209
+ specimen_id: str,
210
+ skip: int = Query(0, ge=0),
211
+ limit: int = Query(10, ge=1, le=100),
212
+ session: AsyncSession = Depends(get_async_session),
213
+ ):
214
+ """Retrieve blocks associated with a specific specimen using specimen's human-readable ID."""
215
+ specimen_exists = (
216
+ await session.execute(select(SpecimenSQLModel.id).where(SpecimenSQLModel.specimen_id == specimen_id))
217
+ ).scalar_one_or_none()
218
+ if specimen_exists is None:
219
+ raise HTTPException(status_code=404, detail=f"Specimen with ID '{specimen_id}' not found")
220
+ return (
221
+ (
222
+ await session.execute(
223
+ select(BlockSQLModel).where(BlockSQLModel.specimen_id == specimen_id).offset(skip).limit(limit)
224
+ )
225
+ )
226
+ .scalars()
227
+ .all()
228
+ )
@@ -0,0 +1,229 @@
1
+ from datetime import datetime, timezone
2
+
3
+ from fastapi import APIRouter, Body, Depends, HTTPException, Query, status
4
+ from sqlalchemy import select
5
+ from sqlalchemy.ext.asyncio import AsyncSession
6
+
7
+ from temdb.models import CuttingSessionCreate, CuttingSessionResponse, CuttingSessionUpdate, SectionResponse
8
+ from temdb.server.dependencies import get_async_session
9
+ from temdb.server.sqlmodels import BlockSQLModel, CuttingSessionSQLModel, SectionSQLModel
10
+
11
+ cutting_session_api = APIRouter(
12
+ tags=["Cutting Sessions"],
13
+ )
14
+
15
+
16
+ @cutting_session_api.get("/cutting-sessions", response_model=list[CuttingSessionResponse])
17
+ async def list_cutting_sessions(
18
+ specimen_id: str | None = Query(None, description="Filter by human-readable Specimen ID"),
19
+ block_id: str | None = Query(None, description="Filter by human-readable Block ID"),
20
+ operator: str | None = Query(None, description="Filter by operator name"),
21
+ skip: int = Query(0, ge=0),
22
+ limit: int = Query(10, ge=1, le=100),
23
+ session: AsyncSession = Depends(get_async_session),
24
+ ):
25
+ """Retrieve a list of cutting sessions with optional filters and pagination."""
26
+ statement = select(CuttingSessionSQLModel)
27
+ if specimen_id:
28
+ statement = statement.where(CuttingSessionSQLModel.specimen_id == specimen_id)
29
+ if block_id:
30
+ statement = statement.where(CuttingSessionSQLModel.block_id == block_id)
31
+ if operator:
32
+ statement = statement.where(CuttingSessionSQLModel.operator == operator)
33
+ sessions = (await session.scalars(statement.offset(skip).limit(limit))).all()
34
+ return sessions
35
+
36
+
37
+ @cutting_session_api.get(
38
+ "/cutting-sessions/specimens/{specimen_id}/blocks/{block_id}/sessions/{cutting_session_id}/sections",
39
+ response_model=list[SectionResponse],
40
+ )
41
+ async def get_cutting_session_sections(
42
+ specimen_id: str,
43
+ block_id: str,
44
+ cutting_session_id: str,
45
+ skip: int = Query(0, ge=0),
46
+ limit: int = Query(10, ge=1, le=100),
47
+ session: AsyncSession = Depends(get_async_session),
48
+ ):
49
+ """Retrieve sections associated with a specific cutting session."""
50
+ cutting_session = await session.scalars(
51
+ select(CuttingSessionSQLModel).where(
52
+ CuttingSessionSQLModel.cutting_session_id == cutting_session_id,
53
+ CuttingSessionSQLModel.block_id == block_id,
54
+ CuttingSessionSQLModel.specimen_id == specimen_id,
55
+ )
56
+ )
57
+ cutting_session_obj = cutting_session.one_or_none()
58
+ if cutting_session_obj is None:
59
+ raise HTTPException(
60
+ status_code=status.HTTP_404_NOT_FOUND,
61
+ detail=f"Cutting Session '{cutting_session_id}' not found or does not match specimen/block.",
62
+ )
63
+ sections = await session.scalars(
64
+ select(SectionSQLModel)
65
+ .where(SectionSQLModel.cutting_session_id == cutting_session_id)
66
+ .offset(skip)
67
+ .limit(limit)
68
+ )
69
+ return sections.all()
70
+
71
+
72
+ @cutting_session_api.post(
73
+ "/cutting-sessions",
74
+ status_code=status.HTTP_201_CREATED,
75
+ response_model=CuttingSessionResponse,
76
+ )
77
+ async def create_cutting_session(
78
+ session_data: CuttingSessionCreate,
79
+ session: AsyncSession = Depends(get_async_session),
80
+ ):
81
+ """Create a new cutting session."""
82
+ existing = await session.scalars(
83
+ select(CuttingSessionSQLModel).where(
84
+ CuttingSessionSQLModel.cutting_session_id == session_data.cutting_session_id
85
+ )
86
+ )
87
+ if existing.one_or_none() is not None:
88
+ raise HTTPException(
89
+ status_code=status.HTTP_400_BAD_REQUEST,
90
+ detail=f"Cutting Session with ID '{session_data.cutting_session_id}' already exists",
91
+ )
92
+ block_obj = (
93
+ await session.execute(select(BlockSQLModel).where(BlockSQLModel.block_id == session_data.block_id))
94
+ ).scalar_one_or_none()
95
+ if block_obj is None:
96
+ raise HTTPException(
97
+ status_code=status.HTTP_404_NOT_FOUND,
98
+ detail=f"Block with ID '{session_data.block_id}' not found",
99
+ )
100
+ new_session = CuttingSessionSQLModel(
101
+ cutting_session_id=session_data.cutting_session_id,
102
+ block_id=block_obj.block_id,
103
+ specimen_id=block_obj.specimen_id,
104
+ start_time=session_data.start_time,
105
+ end_time=session_data.end_time,
106
+ operator=session_data.operator,
107
+ sectioning_device=session_data.sectioning_device,
108
+ media_type=session_data.media_type,
109
+ knife_id=session_data.knife_id,
110
+ created_at=session_data.created_at or datetime.now(timezone.utc),
111
+ )
112
+ session.add(new_session)
113
+ await session.commit()
114
+ await session.refresh(new_session)
115
+ return new_session
116
+
117
+
118
+ @cutting_session_api.get(
119
+ "/cutting-sessions/specimens/{specimen_id}/blocks/{block_id}/sessions/{cutting_session_id}",
120
+ response_model=CuttingSessionResponse,
121
+ )
122
+ async def get_cutting_session(
123
+ specimen_id: str,
124
+ block_id: str,
125
+ cutting_session_id: str,
126
+ session: AsyncSession = Depends(get_async_session),
127
+ ):
128
+ """Retrieve a specific cutting session by its human-readable ID, ensuring it matches specimen/block context."""
129
+ cutting_session_obj = (
130
+ await session.execute(
131
+ select(CuttingSessionSQLModel).where(
132
+ CuttingSessionSQLModel.cutting_session_id == cutting_session_id,
133
+ CuttingSessionSQLModel.block_id == block_id,
134
+ CuttingSessionSQLModel.specimen_id == specimen_id,
135
+ )
136
+ )
137
+ ).scalar_one_or_none()
138
+ if cutting_session_obj is None:
139
+ raise HTTPException(
140
+ status_code=status.HTTP_404_NOT_FOUND,
141
+ detail=f"Cutting Session '{cutting_session_id}' not found or does not match specimen/block.",
142
+ )
143
+ return cutting_session_obj
144
+
145
+
146
+ @cutting_session_api.patch("/cutting-sessions/{cutting_session_id}", response_model=CuttingSessionResponse)
147
+ async def update_cutting_session(
148
+ cutting_session_id: str,
149
+ updated_fields: CuttingSessionUpdate = Body(...),
150
+ session: AsyncSession = Depends(get_async_session),
151
+ ):
152
+ """Update details of a specific cutting session."""
153
+ cutting_session = await session.scalars(
154
+ select(CuttingSessionSQLModel).where(CuttingSessionSQLModel.cutting_session_id == cutting_session_id)
155
+ )
156
+ cutting_session_obj = cutting_session.one_or_none()
157
+ if cutting_session_obj is None:
158
+ raise HTTPException(
159
+ status_code=status.HTTP_404_NOT_FOUND,
160
+ detail=f"Cutting Session with ID '{cutting_session_id}' not found",
161
+ )
162
+ update_data = updated_fields.model_dump(exclude_unset=True)
163
+ if not update_data:
164
+ raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="No update data provided")
165
+ for field, value in update_data.items():
166
+ setattr(cutting_session_obj, field, value)
167
+ cutting_session_obj.updated_at = datetime.now(timezone.utc)
168
+ session.add(cutting_session_obj)
169
+ await session.commit()
170
+ await session.refresh(cutting_session_obj)
171
+ return cutting_session_obj
172
+
173
+
174
+ @cutting_session_api.delete("/cutting-sessions/{cutting_session_id}", status_code=status.HTTP_204_NO_CONTENT)
175
+ async def delete_cutting_session(
176
+ cutting_session_id: str,
177
+ session: AsyncSession = Depends(get_async_session),
178
+ ):
179
+ """Delete a specific cutting session."""
180
+ cutting_session = await session.scalars(
181
+ select(CuttingSessionSQLModel).where(CuttingSessionSQLModel.cutting_session_id == cutting_session_id)
182
+ )
183
+ cutting_session_obj = cutting_session.one_or_none()
184
+ if cutting_session_obj is None:
185
+ raise HTTPException(
186
+ status_code=status.HTTP_404_NOT_FOUND,
187
+ detail=f"Cutting Session with ID '{cutting_session_id}' not found",
188
+ )
189
+ sections = await session.scalars(
190
+ select(SectionSQLModel).where(SectionSQLModel.cutting_session_id == cutting_session_id)
191
+ )
192
+ if sections.first() is not None:
193
+ raise HTTPException(
194
+ status_code=status.HTTP_400_BAD_REQUEST,
195
+ detail=f"Cannot delete session '{cutting_session_id}' as it has associated sections.",
196
+ )
197
+ await session.delete(cutting_session_obj)
198
+ await session.commit()
199
+ return None
200
+
201
+
202
+ @cutting_session_api.get(
203
+ "/cutting-sessions/specimens/{specimen_id}/blocks/{block_id}/sessions",
204
+ response_model=list[CuttingSessionResponse],
205
+ )
206
+ async def list_block_cutting_sessions(
207
+ specimen_id: str,
208
+ block_id: str,
209
+ skip: int = Query(0, ge=0),
210
+ limit: int = Query(10, ge=1, le=100),
211
+ session: AsyncSession = Depends(get_async_session),
212
+ ):
213
+ """Retrieve cutting sessions associated with a specific block using human-readable IDs."""
214
+ sessions = (
215
+ (
216
+ await session.execute(
217
+ select(CuttingSessionSQLModel)
218
+ .where(
219
+ CuttingSessionSQLModel.block_id == block_id,
220
+ CuttingSessionSQLModel.specimen_id == specimen_id,
221
+ )
222
+ .offset(skip)
223
+ .limit(limit)
224
+ )
225
+ )
226
+ .scalars()
227
+ .all()
228
+ )
229
+ return sessions
@@ -0,0 +1,139 @@
1
+ import uuid
2
+ from datetime import datetime, timezone
3
+
4
+ from fastapi import APIRouter, Body, Depends, HTTPException, Query, status
5
+ from sqlalchemy import select
6
+ from sqlalchemy.ext.asyncio import AsyncSession
7
+
8
+ from temdb.models import DatasetCreate, DatasetResponse, DatasetUpdate
9
+ from temdb.server.dependencies import get_async_session
10
+ from temdb.server.ids import uuid7
11
+ from temdb.server.sqlmodels import DatasetSQLModel
12
+ from temdb.server.sqlmodels.tile_partition import resolve_size_class
13
+
14
+ dataset_api = APIRouter(tags=["Datasets"])
15
+
16
+
17
+ async def _get_by_id(session: AsyncSession, dataset_id: str) -> DatasetSQLModel:
18
+ try:
19
+ key = uuid.UUID(dataset_id)
20
+ except ValueError:
21
+ raise HTTPException(status_code=400, detail=f"Invalid dataset_id '{dataset_id}'")
22
+ ds = (await session.scalars(select(DatasetSQLModel).where(DatasetSQLModel.dataset_id == key))).one_or_none()
23
+ if ds is None:
24
+ raise HTTPException(status_code=404, detail=f"Dataset '{dataset_id}' not found")
25
+ return ds
26
+
27
+
28
+ @dataset_api.post("/datasets", status_code=status.HTTP_201_CREATED, response_model=DatasetResponse)
29
+ async def create_dataset(data: DatasetCreate, session: AsyncSession = Depends(get_async_session)):
30
+ existing = (await session.scalars(select(DatasetSQLModel).where(DatasetSQLModel.name == data.name))).one_or_none()
31
+ if existing is not None:
32
+ raise HTTPException(status_code=400, detail=f"Dataset name '{data.name}' already exists")
33
+ if data.parent_dataset_id is not None:
34
+ parent = (
35
+ await session.scalars(select(DatasetSQLModel).where(DatasetSQLModel.dataset_id == data.parent_dataset_id))
36
+ ).one_or_none()
37
+ if parent is None:
38
+ raise HTTPException(status_code=404, detail=f"Parent dataset '{data.parent_dataset_id}' not found")
39
+ if parent.parent_dataset_id is not None:
40
+ raise HTTPException(
41
+ status_code=400,
42
+ detail=f"Dataset '{parent.dataset_id}' is itself a child; nesting is one level only",
43
+ )
44
+ if data.size_class is not None:
45
+ size_class = data.size_class
46
+ elif data.estimated_tile_count is not None:
47
+ size_class = resolve_size_class(data.estimated_tile_count)
48
+ else:
49
+ raise HTTPException(status_code=400, detail="Provide size_class or estimated_tile_count")
50
+ ds = DatasetSQLModel(
51
+ dataset_id=uuid7(),
52
+ name=data.name,
53
+ description=data.description,
54
+ specimen_id=data.specimen_id,
55
+ parent_dataset_id=data.parent_dataset_id,
56
+ size_class=size_class,
57
+ estimated_tile_count=data.estimated_tile_count,
58
+ metadata_json=data.metadata_json,
59
+ created_at=data.created_at or datetime.now(timezone.utc),
60
+ )
61
+ session.add(ds)
62
+ await session.commit()
63
+ await session.refresh(ds)
64
+ return ds
65
+
66
+
67
+ @dataset_api.get("/datasets", response_model=list[DatasetResponse])
68
+ async def list_datasets(
69
+ specimen_id: str | None = Query(None),
70
+ status_filter: str | None = Query(None, alias="status"),
71
+ parent_dataset_id: uuid.UUID | None = Query(None),
72
+ skip: int = Query(0, ge=0),
73
+ limit: int = Query(50, ge=1, le=200),
74
+ session: AsyncSession = Depends(get_async_session),
75
+ ):
76
+ stmt = select(DatasetSQLModel)
77
+ if specimen_id is not None:
78
+ stmt = stmt.where(DatasetSQLModel.specimen_id == specimen_id)
79
+ if status_filter is not None:
80
+ stmt = stmt.where(DatasetSQLModel.status == status_filter)
81
+ if parent_dataset_id is not None:
82
+ stmt = stmt.where(DatasetSQLModel.parent_dataset_id == parent_dataset_id)
83
+ rows = (await session.scalars(stmt.order_by(DatasetSQLModel.created_at).offset(skip).limit(limit))).all()
84
+ return rows
85
+
86
+
87
+ @dataset_api.get("/datasets/by-name/{name}", response_model=DatasetResponse)
88
+ async def get_dataset_by_name(name: str, session: AsyncSession = Depends(get_async_session)):
89
+ ds = (await session.scalars(select(DatasetSQLModel).where(DatasetSQLModel.name == name))).one_or_none()
90
+ if ds is None:
91
+ raise HTTPException(status_code=404, detail=f"Dataset name '{name}' not found")
92
+ return ds
93
+
94
+
95
+ @dataset_api.get("/datasets/{dataset_id}", response_model=DatasetResponse)
96
+ async def get_dataset(dataset_id: str, session: AsyncSession = Depends(get_async_session)):
97
+ return await _get_by_id(session, dataset_id)
98
+
99
+
100
+ @dataset_api.get("/datasets/{dataset_id}/children", response_model=list[DatasetResponse])
101
+ async def list_dataset_children(dataset_id: str, session: AsyncSession = Depends(get_async_session)):
102
+ parent = await _get_by_id(session, dataset_id)
103
+ rows = (
104
+ await session.scalars(
105
+ select(DatasetSQLModel)
106
+ .where(DatasetSQLModel.parent_dataset_id == parent.dataset_id)
107
+ .order_by(DatasetSQLModel.created_at)
108
+ )
109
+ ).all()
110
+ return rows
111
+
112
+
113
+ @dataset_api.patch("/datasets/{dataset_id}", response_model=DatasetResponse)
114
+ async def update_dataset(
115
+ dataset_id: str,
116
+ updated: DatasetUpdate = Body(...),
117
+ session: AsyncSession = Depends(get_async_session),
118
+ ):
119
+ ds = await _get_by_id(session, dataset_id)
120
+ data = updated.model_dump(exclude_unset=True)
121
+ if not data:
122
+ raise HTTPException(status_code=400, detail="No update data provided")
123
+ now = datetime.now(timezone.utc)
124
+ status_changed = "status" in data and data["status"] != ds.status
125
+ for field, value in data.items():
126
+ if field == "status":
127
+ continue
128
+ setattr(ds, field, value)
129
+ if status_changed:
130
+ ds.status = data["status"]
131
+ if ds.status == "collected" and ds.collected_at is None:
132
+ ds.collected_at = now
133
+ if ds.status == "archived" and ds.archived_at is None:
134
+ ds.archived_at = now
135
+ ds.updated_at = now
136
+ session.add(ds)
137
+ await session.commit()
138
+ await session.refresh(ds)
139
+ return ds