Skip to content

Commit e4f3fc5

Browse files
Read sample document by json id using sql
1 parent de4cb51 commit e4f3fc5

2 files changed

Lines changed: 44 additions & 0 deletions

File tree

app/dao/sample_jsonb_sql_dao.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,12 @@
1111

1212
READ_SAMPLE_DOCUMENT_BY_ID = "select * from sample_documents where id=:id"
1313

14+
READ_SAMPLE_DOCUMENT_BY_JSON_ID = """
15+
SELECT *
16+
FROM sample_documents
17+
WHERE (cast(json_data->>'id' as text)) = :json_id
18+
"""
19+
1420
INSERT_SAMPLE_DOCUMENT = """
1521
INSERT INTO
1622
sample_documents(
@@ -32,6 +38,16 @@ async def read_sample_document_by_id(sample_document_id: UUID) -> SampleDocument
3238
return None
3339

3440

41+
async def read_sample_document_by_json_id(json_id: UUID) -> SampleDocument | None:
42+
row: Record = await database.fetch_one(
43+
query=READ_SAMPLE_DOCUMENT_BY_JSON_ID, values={"json_id": str(json_id)}
44+
)
45+
if row:
46+
return map_from_db_row(row)
47+
else:
48+
return None
49+
50+
3551
async def create_sample_document(input_document: SampleDocumentCreate) -> UUID:
3652
inserted_row: Record = await database.fetch_one(
3753
query=INSERT_SAMPLE_DOCUMENT, values=map_to_db_row(input_document)

tests_integration/dao/test_sample_json_sql_dao.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,34 @@ async def test_sample_document_create_and_read():
7878
assert_that(read_document_by_id.created_datetime).is_between(start_time, end_time)
7979

8080

81+
@pytest.mark.asyncio
82+
async def test_sample_document_read_by_json_id():
83+
sample_id: UUID = await create_random_sample()
84+
85+
create_request: SampleDocumentCreate = SampleDocumentCreate(
86+
sample_id=sample_id,
87+
json_data=DocumentMetadata(id=uuid.uuid4(), tags=("tag-1", "tag-2")),
88+
secondary_json_dict={
89+
"test": "value",
90+
"nested": {"sub": "value"},
91+
"array": [{"key": "test-value"}],
92+
},
93+
)
94+
95+
sample_document_id: UUID = await sample_jsonb_sql_dao.create_sample_document(
96+
create_request
97+
)
98+
read_document_by_id: SampleDocument = (
99+
await sample_jsonb_sql_dao.read_sample_document_by_id(sample_document_id)
100+
)
101+
read_document_by_json_id: SampleDocument = (
102+
await sample_jsonb_sql_dao.read_sample_document_by_json_id(
103+
create_request.json_data.id
104+
)
105+
)
106+
assert_that(read_document_by_json_id).is_equal_to(read_document_by_id)
107+
108+
81109
async def create_random_sample() -> UUID:
82110
create_sample_request: SampleCreate = SampleCreate(
83111
username=f"usr-{uuid.uuid4()}",

0 commit comments

Comments
 (0)