Skip to main content

reifydb_engine/bulk_insert/primitive/
table.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
2// Copyright (c) 2025 ReifyDB
3
4//! Builder for inserting into a specific table.
5
6use reifydb_type::params::Params;
7
8use crate::bulk_insert::builder::{BulkInsertBuilder, ValidationMode};
9
10/// Buffered table insert operation
11#[derive(Debug, Clone)]
12pub struct PendingTableInsert {
13	pub namespace: String,
14	pub table: String,
15	pub rows: Vec<Params>,
16}
17
18impl PendingTableInsert {
19	pub fn new(namespace: String, table: String) -> Self {
20		Self {
21			namespace,
22			table,
23			rows: Vec::new(),
24		}
25	}
26
27	pub fn add_row(&mut self, params: Params) {
28		self.rows.push(params);
29	}
30
31	pub fn add_rows<I: IntoIterator<Item = Params>>(&mut self, iter: I) {
32		self.rows.extend(iter);
33	}
34}
35
36/// Builder for inserting rows into a specific table.
37///
38/// Created by calling `table()` on a `BulkInsertBuilder`.
39/// Call `done()` to finish and return to the main builder.
40pub struct TableInsertBuilder<'a, 'e, V: ValidationMode> {
41	parent: &'a mut BulkInsertBuilder<'e, V>,
42	pending: PendingTableInsert,
43}
44
45impl<'a, 'e, V: ValidationMode> TableInsertBuilder<'a, 'e, V> {
46	/// Create a new table insert builder.
47	pub(crate) fn new(parent: &'a mut BulkInsertBuilder<'e, V>, namespace: String, table: String) -> Self {
48		Self {
49			parent,
50			pending: PendingTableInsert::new(namespace, table),
51		}
52	}
53
54	/// Add a single row from named params.
55	///
56	/// # Example
57	///
58	/// ```ignore
59	/// builder.row(params!{ id: 1, name: "Alice" })
60	/// ```
61	pub fn row(mut self, params: Params) -> Self {
62		self.pending.add_row(params);
63		self
64	}
65
66	/// Add multiple rows from an iterator.
67	///
68	/// # Example
69	///
70	/// ```ignore
71	/// let rows = vec![
72	///     params!{ id: 1, name: "Alice" },
73	///     params!{ id: 2, name: "Bob" },
74	/// ];
75	/// builder.rows(rows)
76	/// ```
77	pub fn rows<I>(mut self, iter: I) -> Self
78	where
79		I: IntoIterator<Item = Params>,
80	{
81		self.pending.add_rows(iter);
82		self
83	}
84
85	/// Finish this table insert and return to the main builder.
86	///
87	/// This allows chaining to insert into additional targets.
88	pub fn done(self) -> &'a mut BulkInsertBuilder<'e, V> {
89		self.parent.add_table_insert(self.pending);
90		self.parent
91	}
92}