Skip to content

Commit 8de58f6

Browse files
committed
fmt
Signed-off-by: Yuki Kishimoto <[email protected]>
1 parent b0f9fe8 commit 8de58f6

File tree

8 files changed

+82
-52
lines changed

8 files changed

+82
-52
lines changed

crates/nostr-sdk/examples/client.rs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
// Distributed under the MIT software license
44

55
use std::time::Duration;
6+
67
use nostr_sdk::prelude::*;
78

89
#[tokio::main]
@@ -22,14 +23,14 @@ async fn main() -> Result<()> {
2223
println!("Event ID: {}", output.id().to_bech32()?);
2324
println!("Sent to: {:?}", output.success);
2425
println!("Not sent to: {:?}", output.failed);
25-
26+
2627
let events = client
2728
.fetch_events(Filter::new().kind(Kind::TextNote), Duration::from_secs(10))
2829
.await?;
2930

3031
for event in events {
3132
println!("{}", event.as_json())
3233
}
33-
34+
3435
Ok(())
3536
}

database/nostr-sqldb/build.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,4 +4,4 @@
44

55
fn main() {
66
println!("cargo:rerun-if-changed=migrations");
7-
}
7+
}

database/nostr-sqldb/examples/postgres-relay.rs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22
// Copyright (c) 2023-2025 Rust Nostr Developers
33
// Distributed under the MIT software license
44

5-
65
use std::time::Duration;
76

87
use nostr_database::prelude::*;
@@ -20,7 +19,7 @@ async fn main() -> Result<()> {
2019
password: Some(String::from("password")),
2120
database: String::from("nostr"),
2221
};
23-
22+
2423
// Create a nostr db instance and run pending db migrations if any
2524
let db = NostrSql::new(backend).await?;
2625

database/nostr-sqldb/examples/sqlite-relay.rs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22
// Copyright (c) 2023-2025 Rust Nostr Developers
33
// Distributed under the MIT software license
44

5-
65
use std::time::Duration;
76

87
use nostr_database::prelude::*;

database/nostr-sqldb/src/db.rs

Lines changed: 71 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -9,14 +9,14 @@ use std::fmt;
99
use std::path::{Path, PathBuf};
1010
use std::sync::Arc;
1111

12-
#[cfg(feature = "sqlite")]
13-
use sqlx::sqlite::{SqliteConnectOptions, SqlitePool};
14-
#[cfg(feature = "postgres")]
15-
use sqlx::postgres::{PgConnectOptions, PgPool};
12+
use nostr_database::prelude::*;
1613
#[cfg(feature = "mysql")]
1714
use sqlx::mysql::{MySql, MySqlPool};
18-
use sqlx::{Transaction, QueryBuilder};
19-
use nostr_database::prelude::*;
15+
#[cfg(feature = "postgres")]
16+
use sqlx::postgres::{PgConnectOptions, PgPool};
17+
#[cfg(feature = "sqlite")]
18+
use sqlx::sqlite::{SqliteConnectOptions, SqlitePool};
19+
use sqlx::{QueryBuilder, Transaction};
2020
use tokio::sync::Mutex;
2121

2222
use crate::error::Error;
@@ -32,7 +32,7 @@ pub enum NostrSqlBackend {
3232
/// SQLite database path
3333
///
3434
/// If no path is passed, an in-memory database will be created.
35-
path: Option<PathBuf>
35+
path: Option<PathBuf>,
3636
},
3737
/// Postgres
3838
#[cfg(feature = "postgres")]
@@ -47,7 +47,7 @@ pub enum NostrSqlBackend {
4747
password: Option<String>,
4848
/// Database name
4949
database: String,
50-
}
50+
},
5151
}
5252

5353
impl NostrSqlBackend {
@@ -56,9 +56,11 @@ impl NostrSqlBackend {
5656
#[cfg(feature = "sqlite")]
5757
pub fn sqlite<P>(path: P) -> Self
5858
where
59-
P: AsRef<Path>
59+
P: AsRef<Path>,
6060
{
61-
Self::Sqlite { path: Some(path.as_ref().to_path_buf()) }
61+
Self::Sqlite {
62+
path: Some(path.as_ref().to_path_buf()),
63+
}
6264
}
6365

6466
/// New in-memory SQLite database
@@ -99,25 +101,34 @@ impl NostrSql {
99101
pub async fn new(backend: NostrSqlBackend) -> Result<Self, Error> {
100102
let pool = match backend {
101103
#[cfg(feature = "sqlite")]
102-
NostrSqlBackend::Sqlite {path} => {
103-
let mut opts: SqliteConnectOptions = SqliteConnectOptions::new().create_if_missing(true);
104-
104+
NostrSqlBackend::Sqlite { path } => {
105+
let mut opts: SqliteConnectOptions =
106+
SqliteConnectOptions::new().create_if_missing(true);
107+
105108
match path {
106109
Some(path) => opts = opts.filename(path),
107110
None => opts = opts.in_memory(true),
108111
};
109-
110-
112+
111113
let pool: SqlitePool = SqlitePool::connect_with(opts).await?;
112114

113115
sqlx::migrate!("migrations/sqlite").run(&pool).await?;
114116

115117
Db::Sqlite(pool)
116118
}
117119
#[cfg(feature = "postgres")]
118-
NostrSqlBackend::Postgres {host, port, username, password, database } => {
119-
let mut opts: PgConnectOptions = PgConnectOptions::new_without_pgpass().host(&host).port(port).database(&database);
120-
120+
NostrSqlBackend::Postgres {
121+
host,
122+
port,
123+
username,
124+
password,
125+
database,
126+
} => {
127+
let mut opts: PgConnectOptions = PgConnectOptions::new_without_pgpass()
128+
.host(&host)
129+
.port(port)
130+
.database(&database);
131+
121132
if let Some(username) = username {
122133
opts = opts.username(&username);
123134
}
@@ -141,7 +152,11 @@ impl NostrSql {
141152
}
142153

143154
/// Returns true if successfully inserted
144-
async fn insert_event_tx(&self, tx: &mut Transaction<'_, Any>, event: &EventDb) -> Result<bool, Error> {
155+
async fn insert_event_tx(
156+
&self,
157+
tx: &mut Transaction<'_, Any>,
158+
event: &EventDb,
159+
) -> Result<bool, Error> {
145160
let sql: &str = match self.kind {
146161
#[cfg(feature = "sqlite")]
147162
PoolKind::Sqlite => {
@@ -170,7 +185,11 @@ impl NostrSql {
170185
Ok(result.rows_affected() > 0)
171186
}
172187

173-
async fn insert_tags_tx(&self, tx: &mut Transaction<'_, Any>, tags: &[EventTagDb]) -> Result<(), Error> {
188+
async fn insert_tags_tx(
189+
&self,
190+
tx: &mut Transaction<'_, Any>,
191+
tags: &[EventTagDb],
192+
) -> Result<(), Error> {
174193
let sql: &str = match self.kind {
175194
#[cfg(feature = "sqlite")]
176195
PoolKind::Sqlite => {
@@ -198,7 +217,6 @@ impl NostrSql {
198217
Ok(())
199218
}
200219

201-
202220
async fn _save_event(&self, event: &Event) -> Result<SaveEventStatus, Error> {
203221
if event.kind.is_ephemeral() {
204222
return Ok(SaveEventStatus::Rejected(RejectedReason::Ephemeral));
@@ -260,7 +278,9 @@ impl NostrDatabase for NostrSql {
260278
event: &'a Event,
261279
) -> BoxedFuture<'a, Result<SaveEventStatus, DatabaseError>> {
262280
Box::pin(async move {
263-
self._save_event(event).await.map_err(DatabaseError::backend)
281+
self._save_event(event)
282+
.await
283+
.map_err(DatabaseError::backend)
264284
})
265285
}
266286

@@ -269,7 +289,11 @@ impl NostrDatabase for NostrSql {
269289
event_id: &'a EventId,
270290
) -> BoxedFuture<'a, Result<DatabaseEventStatus, DatabaseError>> {
271291
Box::pin(async move {
272-
match self.get_event_by_id(event_id).await.map_err(DatabaseError::backend)? {
292+
match self
293+
.get_event_by_id(event_id)
294+
.await
295+
.map_err(DatabaseError::backend)?
296+
{
273297
Some(e) if e.deleted => Ok(DatabaseEventStatus::Deleted),
274298
Some(_) => Ok(DatabaseEventStatus::Saved),
275299
None => Ok(DatabaseEventStatus::NotExistent),
@@ -282,19 +306,21 @@ impl NostrDatabase for NostrSql {
282306
event_id: &'a EventId,
283307
) -> BoxedFuture<'a, Result<Option<Event>, DatabaseError>> {
284308
Box::pin(async move {
285-
match self.get_event_by_id(event_id).await.map_err(DatabaseError::backend)? {
286-
Some(e) if !e.deleted => {
287-
Ok(Some(Event::decode(&e.payload).map_err(DatabaseError::backend)?))
288-
}
309+
match self
310+
.get_event_by_id(event_id)
311+
.await
312+
.map_err(DatabaseError::backend)?
313+
{
314+
Some(e) if !e.deleted => Ok(Some(
315+
Event::decode(&e.payload).map_err(DatabaseError::backend)?,
316+
)),
289317
_ => Ok(None),
290318
}
291319
})
292320
}
293321

294322
fn count(&self, filter: Filter) -> BoxedFuture<Result<usize, DatabaseError>> {
295-
Box::pin(async move {
296-
Ok(self.query(filter).await?.len())
297-
})
323+
Box::pin(async move { Ok(self.query(filter).await?.len()) })
298324
}
299325

300326
fn query(&self, filter: Filter) -> BoxedFuture<Result<Events, DatabaseError>> {
@@ -306,7 +332,10 @@ impl NostrDatabase for NostrSql {
306332

307333
let sql = build_filter_query(filter);
308334

309-
let payloads: Vec<(Vec<u8>,)> = sqlx::query_as(&sql).fetch_all(&self.pool).await.map_err(DatabaseError::backend)?;
335+
let payloads: Vec<(Vec<u8>,)> = sqlx::query_as(&sql)
336+
.fetch_all(&self.pool)
337+
.await
338+
.map_err(DatabaseError::backend)?;
310339

311340
for (payload,) in payloads.into_iter() {
312341
if let Ok(event) = Event::decode(&payload) {
@@ -330,11 +359,11 @@ impl NostrDatabase for NostrSql {
330359
//
331360
// Ok(())
332361
// })
333-
Box::pin(async move { Err(DatabaseError::NotSupported )})
362+
Box::pin(async move { Err(DatabaseError::NotSupported) })
334363
}
335364

336365
fn wipe(&self) -> BoxedFuture<Result<(), DatabaseError>> {
337-
Box::pin(async move { Err(DatabaseError::NotSupported )})
366+
Box::pin(async move { Err(DatabaseError::NotSupported) })
338367
}
339368
}
340369

@@ -343,7 +372,7 @@ fn build_filter_query(filter: Filter) -> String {
343372
"SELECT DISTINCT e.payload
344373
FROM events e
345374
INNER JOIN event_tags et ON e.id = et.event_id
346-
WHERE e.deleted = 0"
375+
WHERE e.deleted = 0",
347376
);
348377

349378
// Add filters
@@ -393,10 +422,12 @@ fn build_filter_query(filter: Filter) -> String {
393422
if !filter.generic_tags.is_empty() {
394423
for (tag, values) in filter.generic_tags {
395424
if !values.is_empty() {
396-
query_builder.push(" AND EXISTS (
425+
query_builder.push(
426+
" AND EXISTS (
397427
SELECT 1 FROM event_tags et2
398428
WHERE et2.event_id = e.id
399-
AND et2.tag = ");
429+
AND et2.tag = ",
430+
);
400431
query_builder.push_bind(tag.to_string());
401432
query_builder.push(" AND et2.tag_value IN (");
402433

@@ -492,13 +523,13 @@ mod tests {
492523
EventBuilder::metadata(
493524
&Metadata::new().name("account-a").display_name("Account A"),
494525
)
495-
.sign_with_keys(&keys_a)
496-
.unwrap(),
526+
.sign_with_keys(&keys_a)
527+
.unwrap(),
497528
EventBuilder::metadata(
498529
&Metadata::new().name("account-b").display_name("Account B"),
499530
)
500-
.sign_with_keys(&keys_b)
501-
.unwrap(),
531+
.sign_with_keys(&keys_b)
532+
.unwrap(),
502533
EventBuilder::new(Kind::Custom(33_333), "")
503534
.tag(Tag::identifier("my-id-a"))
504535
.sign_with_keys(&keys_a)

database/nostr-sqldb/src/error.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ impl fmt::Display for Error {
2525
Self::Sqlx(e) => write!(f, "{e}"),
2626
Self::Migrate(e) => write!(f, "{e}"),
2727
}
28-
}
28+
}
2929
}
3030

3131
impl From<sqlx::Error> for Error {
@@ -38,4 +38,4 @@ impl From<MigrateError> for Error {
3838
fn from(e: MigrateError) -> Self {
3939
Self::Migrate(e)
4040
}
41-
}
41+
}

database/nostr-sqldb/src/lib.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,8 @@
1313
#[cfg(not(any(feature = "sqlite", feature = "postgres", feature = "mysql")))]
1414
compile_error!("At least one database backend must be enabled");
1515

16-
mod model;
17-
pub mod error;
1816
pub mod db;
17+
pub mod error;
18+
mod model;
1919

20-
pub use self::db::{NostrSql, NostrSqlBackend};
20+
pub use self::db::{NostrSql, NostrSqlBackend};

database/nostr-sqldb/src/model.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,9 @@
22
// Copyright (c) 2023-2025 Rust Nostr Developers
33
// Distributed under the MIT software license
44

5-
use sqlx::FromRow;
65
use nostr::event::Event;
76
use nostr_database::{FlatBufferBuilder, FlatBufferEncode};
7+
use sqlx::FromRow;
88

99
#[derive(Debug, Clone, FromRow)]
1010
pub(crate) struct EventDb {

0 commit comments

Comments
 (0)