relay filter/appview bootstrap
1use chrono::{DateTime, Utc};
2use sqlx::PgPool;
3
4use crate::records::{NewAccount, NewRecord, Record};
5
6pub async fn upsert_account(pool: &PgPool, account: &NewAccount) -> sqlx::Result<()> {
7 sqlx::query!(
8 r#"
9 INSERT INTO account (did, handle, created_at)
10 VALUES ($1, $2, $3)
11 ON CONFLICT (did) DO NOTHING
12 "#,
13 account.did,
14 account.handle,
15 account.created_at
16 )
17 .execute(pool)
18 .await?;
19 Ok(())
20}
21
22pub async fn insert_record(pool: &PgPool, record: &NewRecord) -> sqlx::Result<()> {
23 sqlx::query!(
24 r#"
25 INSERT INTO record (uri, cid, collection, creator_did, created_at, indexed_at, data, target_did, ref_cids)
26 VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
27 ON CONFLICT (uri) DO UPDATE SET
28 cid = EXCLUDED.cid,
29 data = EXCLUDED.data,
30 indexed_at = EXCLUDED.indexed_at
31 "#,
32 record.uri,
33 record.cid,
34 record.collection,
35 record.creator_did,
36 record.created_at,
37 record.indexed_at,
38 record.data,
39 record.target_did,
40 &record.ref_cids
41 )
42 .execute(pool)
43 .await?;
44 Ok(())
45}
46
47pub async fn list_records_by_creator(
48 pool: &PgPool,
49 collection: &str,
50 creator_did: &str,
51 cursor: Option<DateTime<Utc>>,
52 limit: i64,
53) -> sqlx::Result<Vec<Record>> {
54 let cursor = cursor.unwrap_or_else(Utc::now);
55 sqlx::query_as!(
56 Record,
57 r#"
58 SELECT uri, cid, collection, creator_did, created_at, indexed_at, data, target_did, ref_cids
59 FROM record
60 WHERE collection = $1 AND creator_did = $2 AND indexed_at < $3
61 ORDER BY indexed_at DESC
62 LIMIT $4
63 "#,
64 collection,
65 creator_did,
66 cursor,
67 limit
68 )
69 .fetch_all(pool)
70 .await
71}
72
73pub async fn list_records_by_target(
74 pool: &PgPool,
75 collection: &str,
76 target_did: &str,
77 cursor: Option<DateTime<Utc>>,
78 limit: i64,
79) -> sqlx::Result<Vec<Record>> {
80 let cursor = cursor.unwrap_or_else(Utc::now);
81 sqlx::query_as!(
82 Record,
83 r#"
84 SELECT uri, cid, collection, creator_did, created_at, indexed_at, data, target_did, ref_cids
85 FROM record
86 WHERE collection = $1 AND target_did = $2 AND indexed_at < $3
87 ORDER BY indexed_at DESC
88 LIMIT $4
89 "#,
90 collection,
91 target_did,
92 cursor,
93 limit
94 )
95 .fetch_all(pool)
96 .await
97}
98
99pub async fn get_record_by_cid(pool: &PgPool, cid: &str) -> sqlx::Result<Option<Record>> {
100 sqlx::query_as!(
101 Record,
102 r#"
103 SELECT uri, cid, collection, creator_did, created_at, indexed_at, data, target_did, ref_cids
104 FROM record
105 WHERE cid = $1
106 "#,
107 cid
108 )
109 .fetch_optional(pool)
110 .await
111}