spring-batch-rs 0.3.4

A toolkit for building enterprise-grade batch applications
Documentation
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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
use sqlx::{MySql, Pool, Postgres, Sqlite};

use super::DatabaseItemBinder;
use super::database_type::DatabaseType;
use super::mysql_writer::MySqlItemWriter;
use super::postgres_writer::PostgresItemWriter;
use super::sqlite_writer::SqliteItemWriter;

/// Unified builder for creating RDBC item writers for any supported database type.
///
/// This builder provides a consistent API for constructing database writers
/// regardless of the underlying database (PostgreSQL, MySQL, or SQLite).
/// Users specify the database type, connection pool, table, and columns,
/// and the builder handles the creation of the appropriate writer implementation.
///
/// # Type Parameters
///
/// * `O` - The item type to write
///
/// # Examples
///
/// ## PostgreSQL
/// ```no_run
/// use spring_batch_rs::item::rdbc::{RdbcItemWriterBuilder, DatabaseItemBinder};
/// use sqlx::{PgPool, query_builder::Separated, Postgres};
/// use serde::Serialize;
///
/// #[derive(Clone, Serialize)]
/// struct User {
///     id: i32,
///     name: String,
/// }
///
/// struct UserBinder;
/// impl DatabaseItemBinder<User, Postgres> for UserBinder {
///     fn bind(&self, item: &User, mut query_builder: Separated<Postgres, &str>) {
///         let _ = (item, query_builder); // Placeholder to avoid unused warnings
///         // In real usage: query_builder.push_bind(item.id);
///         // In real usage: query_builder.push_bind(&item.name);
///     }
/// }
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let pool = PgPool::connect("postgresql://user:pass@localhost/db").await?;
/// let binder = UserBinder;
///
/// let writer = RdbcItemWriterBuilder::<User>::new()
///     .postgres(&pool)
///     .table("users")
///     .add_column("id")
///     .add_column("name")
///     .postgres_binder(&binder)
///     .build_postgres();
/// # Ok(())
/// # }
/// ```
///
/// ## MySQL
/// ```no_run
/// use spring_batch_rs::item::rdbc::{RdbcItemWriterBuilder, DatabaseItemBinder};
/// use sqlx::{MySqlPool, query_builder::Separated, MySql};
/// use serde::Serialize;
///
/// #[derive(Clone, Serialize)]
/// struct Product {
///     id: i32,
///     name: String,
/// }
///
/// struct ProductBinder;
/// impl DatabaseItemBinder<Product, MySql> for ProductBinder {
///     fn bind(&self, item: &Product, mut query_builder: Separated<MySql, &str>) {
///         let _ = (item, query_builder); // Placeholder to avoid unused warnings
///         // In real usage: query_builder.push_bind(item.id);
///         // In real usage: query_builder.push_bind(&item.name);
///     }
/// }
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let pool = MySqlPool::connect("mysql://user:pass@localhost/db").await?;
/// let binder = ProductBinder;
///
/// let writer = RdbcItemWriterBuilder::<Product>::new()
///     .mysql(&pool)
///     .table("products")
///     .add_column("id")
///     .add_column("name")
///     .mysql_binder(&binder)
///     .build_mysql();
/// # Ok(())
/// # }
/// ```
///
/// ## SQLite
/// ```no_run
/// use spring_batch_rs::item::rdbc::{RdbcItemWriterBuilder, DatabaseItemBinder};
/// use sqlx::{SqlitePool, query_builder::Separated, Sqlite};
/// use serde::Serialize;
///
/// #[derive(Clone, Serialize)]
/// struct Task {
///     id: i32,
///     title: String,
/// }
///
/// struct TaskBinder;
/// impl DatabaseItemBinder<Task, Sqlite> for TaskBinder {
///     fn bind(&self, item: &Task, mut query_builder: Separated<Sqlite, &str>) {
///         let _ = (item, query_builder); // Placeholder to avoid unused warnings
///         // In real usage: query_builder.push_bind(item.id);
///         // In real usage: query_builder.push_bind(&item.title);
///     }
/// }
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let pool = SqlitePool::connect("sqlite::memory:").await?;
/// let binder = TaskBinder;
///
/// let writer = RdbcItemWriterBuilder::<Task>::new()
///     .sqlite(&pool)
///     .table("tasks")
///     .add_column("id")
///     .add_column("title")
///     .sqlite_binder(&binder)
///     .build_sqlite();
/// # Ok(())
/// # }
/// ```
pub struct RdbcItemWriterBuilder<'a, O> {
    postgres_pool: Option<&'a Pool<Postgres>>,
    mysql_pool: Option<&'a Pool<MySql>>,
    sqlite_pool: Option<&'a Pool<Sqlite>>,
    table: Option<&'a str>,
    columns: Vec<&'a str>,
    postgres_binder: Option<&'a dyn DatabaseItemBinder<O, Postgres>>,
    mysql_binder: Option<&'a dyn DatabaseItemBinder<O, MySql>>,
    sqlite_binder: Option<&'a dyn DatabaseItemBinder<O, Sqlite>>,
    db_type: Option<DatabaseType>,
}

impl<'a, O> RdbcItemWriterBuilder<'a, O> {
    /// Creates a new unified writer builder with default configuration.
    pub fn new() -> Self {
        Self {
            postgres_pool: None,
            mysql_pool: None,
            sqlite_pool: None,
            table: None,
            columns: Vec::new(),
            postgres_binder: None,
            mysql_binder: None,
            sqlite_binder: None,
            db_type: None,
        }
    }

    /// Sets the PostgreSQL connection pool and database type.
    ///
    /// # Arguments
    /// * `pool` - The PostgreSQL connection pool
    ///
    /// # Returns
    /// The updated builder instance configured for PostgreSQL
    pub fn postgres(mut self, pool: &'a Pool<Postgres>) -> Self {
        self.postgres_pool = Some(pool);
        self.db_type = Some(DatabaseType::Postgres);
        self
    }

    /// Sets the MySQL connection pool and database type.
    ///
    /// # Arguments
    /// * `pool` - The MySQL connection pool
    ///
    /// # Returns
    /// The updated builder instance configured for MySQL
    pub fn mysql(mut self, pool: &'a Pool<MySql>) -> Self {
        self.mysql_pool = Some(pool);
        self.db_type = Some(DatabaseType::MySql);
        self
    }

    /// Sets the SQLite connection pool and database type.
    ///
    /// # Arguments
    /// * `pool` - The SQLite connection pool
    ///
    /// # Returns
    /// The updated builder instance configured for SQLite
    pub fn sqlite(mut self, pool: &'a Pool<Sqlite>) -> Self {
        self.sqlite_pool = Some(pool);
        self.db_type = Some(DatabaseType::Sqlite);
        self
    }

    /// Sets the table name for the writer.
    ///
    /// # Arguments
    /// * `table` - The database table name
    ///
    /// # Returns
    /// The updated builder instance
    pub fn table(mut self, table: &'a str) -> Self {
        self.table = Some(table);
        self
    }

    /// Adds a column to the writer.
    ///
    /// # Arguments
    /// * `column` - The column name
    ///
    /// # Returns
    /// The updated builder instance
    pub fn add_column(mut self, column: &'a str) -> Self {
        self.columns.push(column);
        self
    }

    /// Sets the item binder for PostgreSQL.
    ///
    /// # Arguments
    /// * `binder` - The PostgreSQL-specific item binder
    ///
    /// # Returns
    /// The updated builder instance
    pub fn postgres_binder(mut self, binder: &'a dyn DatabaseItemBinder<O, Postgres>) -> Self {
        self.postgres_binder = Some(binder);
        self
    }

    /// Sets the item binder for MySQL.
    ///
    /// # Arguments
    /// * `binder` - The MySQL-specific item binder
    ///
    /// # Returns
    /// The updated builder instance
    pub fn mysql_binder(mut self, binder: &'a dyn DatabaseItemBinder<O, MySql>) -> Self {
        self.mysql_binder = Some(binder);
        self
    }

    /// Sets the item binder for SQLite.
    ///
    /// # Arguments
    /// * `binder` - The SQLite-specific item binder
    ///
    /// # Returns
    /// The updated builder instance
    pub fn sqlite_binder(mut self, binder: &'a dyn DatabaseItemBinder<O, Sqlite>) -> Self {
        self.sqlite_binder = Some(binder);
        self
    }

    /// Builds a PostgreSQL writer.
    ///
    /// # Returns
    /// A configured `PostgresItemWriter` instance
    ///
    /// # Panics
    /// Panics if required PostgreSQL-specific configuration is missing
    pub fn build_postgres(self) -> PostgresItemWriter<'a, O> {
        let mut writer = PostgresItemWriter::new();

        if let Some(pool) = self.postgres_pool {
            writer = writer.pool(pool);
        }

        if let Some(table) = self.table {
            writer = writer.table(table);
        }

        for column in self.columns {
            writer = writer.add_column(column);
        }

        if let Some(binder) = self.postgres_binder {
            writer = writer.item_binder(binder);
        }

        writer
    }

    /// Builds a MySQL writer.
    ///
    /// # Returns
    /// A configured `MySqlItemWriter` instance
    ///
    /// # Panics
    /// Panics if required MySQL-specific configuration is missing
    pub fn build_mysql(self) -> MySqlItemWriter<'a, O> {
        let mut writer = MySqlItemWriter::new();

        if let Some(pool) = self.mysql_pool {
            writer = writer.pool(pool);
        }

        if let Some(table) = self.table {
            writer = writer.table(table);
        }

        for column in self.columns {
            writer = writer.add_column(column);
        }

        if let Some(binder) = self.mysql_binder {
            writer = writer.item_binder(binder);
        }

        writer
    }

    /// Builds a SQLite writer.
    ///
    /// # Returns
    /// A configured `SqliteItemWriter` instance
    ///
    /// # Panics
    /// Panics if required SQLite-specific configuration is missing
    pub fn build_sqlite(self) -> SqliteItemWriter<'a, O> {
        let mut writer = SqliteItemWriter::new();

        if let Some(pool) = self.sqlite_pool {
            writer = writer.pool(pool);
        }

        if let Some(table) = self.table {
            writer = writer.table(table);
        }

        for column in self.columns {
            writer = writer.add_column(column);
        }

        if let Some(binder) = self.sqlite_binder {
            writer = writer.item_binder(binder);
        }

        writer
    }
}

impl<'a, O> Default for RdbcItemWriterBuilder<'a, O> {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::item::ItemWriter;
    use sqlx::query_builder::Separated;

    struct NopBinder;
    impl DatabaseItemBinder<String, Postgres> for NopBinder {
        fn bind(&self, _: &String, _: Separated<Postgres, &str>) {}
    }
    impl DatabaseItemBinder<String, MySql> for NopBinder {
        fn bind(&self, _: &String, _: Separated<MySql, &str>) {}
    }
    impl DatabaseItemBinder<String, Sqlite> for NopBinder {
        fn bind(&self, _: &String, _: Separated<Sqlite, &str>) {}
    }

    #[test]
    fn should_set_table_name_in_postgres_writer() {
        let writer = RdbcItemWriterBuilder::<String>::new()
            .table("users")
            .build_postgres();
        assert_eq!(writer.table, Some("users"));
    }

    #[test]
    fn should_accumulate_columns_in_postgres_writer() {
        let writer = RdbcItemWriterBuilder::<String>::new()
            .add_column("id")
            .add_column("name")
            .build_postgres();
        assert_eq!(writer.columns, vec!["id", "name"]);
    }

    #[test]
    fn should_transfer_table_and_columns_to_mysql_writer() {
        let writer = RdbcItemWriterBuilder::<String>::new()
            .table("orders")
            .add_column("order_id")
            .add_column("total")
            .build_mysql();
        assert_eq!(writer.table, Some("orders"));
        assert_eq!(writer.columns, vec!["order_id", "total"]);
    }

    #[test]
    fn should_transfer_table_and_columns_to_sqlite_writer() {
        use crate::BatchError;
        // No pool configured → validate_config will fail on "pool", not on table/columns.
        // If table or columns were missing the error would mention those instead,
        // so reaching the "pool" error proves both were transferred correctly.
        let binder = NopBinder;
        let writer = RdbcItemWriterBuilder::<String>::new()
            .table("items")
            .add_column("sku")
            .sqlite_binder(&binder)
            .build_sqlite();
        let result = writer.write(&["x".to_string()]);
        match result.err().unwrap() {
            BatchError::ItemWriter(msg) => assert!(
                msg.contains("pool"),
                "table and columns were set so error should be about pool, got: {msg}"
            ),
            e => panic!("expected ItemWriter, got {e:?}"),
        }
    }

    #[test]
    fn should_set_postgres_binder() {
        let binder = NopBinder;
        let writer = RdbcItemWriterBuilder::<String>::new()
            .postgres_binder(&binder)
            .build_postgres();
        assert!(
            writer.item_binder.is_some(),
            "postgres binder should be set"
        );
    }

    #[test]
    fn should_set_mysql_binder() {
        let binder = NopBinder;
        let writer = RdbcItemWriterBuilder::<String>::new()
            .mysql_binder(&binder)
            .build_mysql();
        assert!(writer.item_binder.is_some(), "mysql binder should be set");
    }

    #[test]
    fn should_transfer_sqlite_binder_to_writer() {
        use crate::BatchError;
        // With binder set but no pool, write() should fail on "pool" not on "binder"
        let binder = NopBinder;
        let writer = RdbcItemWriterBuilder::<String>::new()
            .table("t")
            .add_column("v")
            .sqlite_binder(&binder)
            .build_sqlite();
        let result = writer.write(&["x".to_string()]);
        match result.err().unwrap() {
            BatchError::ItemWriter(msg) => assert!(
                msg.contains("pool"),
                "binder was set so error should be about pool, got: {msg}"
            ),
            e => panic!("expected ItemWriter, got {e:?}"),
        }
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn should_transfer_sqlite_pool_to_writer() {
        use crate::BatchError;
        let pool = sqlx::SqlitePool::connect("sqlite::memory:").await.unwrap();
        // Pool set but no binder → error is "binder not configured"
        let writer = RdbcItemWriterBuilder::<String>::new()
            .sqlite(&pool)
            .table("t")
            .add_column("v")
            .build_sqlite();
        let result = writer.write(&["x".to_string()]);
        match result.err().unwrap() {
            BatchError::ItemWriter(msg) => assert!(
                msg.contains("binder"),
                "pool was set so error should be about binder, got: {msg}"
            ),
            e => panic!("expected ItemWriter, got {e:?}"),
        }
    }

    #[test]
    fn should_have_no_table_by_default_in_mysql_writer() {
        let writer = RdbcItemWriterBuilder::<String>::new().build_mysql();
        assert!(writer.table.is_none());
        assert!(writer.columns.is_empty());
    }

    #[test]
    fn should_create_via_default() {
        let _b = RdbcItemWriterBuilder::<String>::default();
    }
}