reifydb-catalog 0.4.13

Database catalog and metadata management for ReifyDB
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
// SPDX-License-Identifier: Apache-2.0
// Copyright (c) 2025 ReifyDB

use reifydb_core::{
	interface::catalog::{change::CatalogTrackNamespaceChangeOperations, id::NamespaceId, namespace::Namespace},
	internal,
};
use reifydb_transaction::{
	change::TransactionalNamespaceChanges,
	transaction::{Transaction, admin::AdminTransaction},
};
use reifydb_type::{error, fragment::Fragment};
use tracing::{instrument, warn};

use crate::{
	CatalogStore, Result,
	catalog::Catalog,
	error::{CatalogError, CatalogObjectKind},
	store::namespace::create::NamespaceToCreate as StoreNamespaceToCreate,
};

/// Namespace creation specification for the Catalog API.
#[derive(Debug, Clone)]
pub struct NamespaceToCreate {
	pub namespace_fragment: Option<Fragment>,
	pub name: String,
	pub local_name: String,
	pub parent_id: NamespaceId,
	pub grpc: Option<String>,
	pub token: Option<String>,
}

impl From<NamespaceToCreate> for StoreNamespaceToCreate {
	fn from(to_create: NamespaceToCreate) -> Self {
		StoreNamespaceToCreate {
			namespace_fragment: to_create.namespace_fragment,
			name: to_create.name,
			local_name: to_create.local_name,
			parent_id: to_create.parent_id,
			grpc: to_create.grpc,
			token: to_create.token,
		}
	}
}

impl Catalog {
	#[instrument(name = "catalog::namespace::find", level = "trace", skip(self, txn))]
	pub fn find_namespace(&self, txn: &mut Transaction<'_>, id: NamespaceId) -> Result<Option<Namespace>> {
		match txn.reborrow() {
			Transaction::Command(cmd) => {
				// 1. Check MaterializedCatalog
				if let Some(namespace) = self.materialized.find_namespace_at(id, cmd.version()) {
					return Ok(Some(namespace));
				}

				// 2. Fall back to storage as defensive measure
				if let Some(namespace) =
					CatalogStore::find_namespace(&mut Transaction::Command(&mut *cmd), id)?
				{
					warn!(
						"Namespace with ID {:?} found in storage but not in MaterializedCatalog",
						id
					);
					return Ok(Some(namespace));
				}

				Ok(None)
			}
			Transaction::Admin(admin) => {
				// 1. Check transactional changes first
				if let Some(namespace) = TransactionalNamespaceChanges::find_namespace(admin, id) {
					return Ok(Some(namespace.clone()));
				}

				// 2. Check if deleted
				if TransactionalNamespaceChanges::is_namespace_deleted(admin, id) {
					return Ok(None);
				}

				// 3. Check MaterializedCatalog
				if let Some(namespace) = self.materialized.find_namespace_at(id, admin.version()) {
					return Ok(Some(namespace));
				}

				// 4. Fall back to storage as defensive measure
				if let Some(namespace) =
					CatalogStore::find_namespace(&mut Transaction::Admin(&mut *admin), id)?
				{
					warn!(
						"Namespace with ID {:?} found in storage but not in MaterializedCatalog",
						id
					);
					return Ok(Some(namespace));
				}

				Ok(None)
			}
			Transaction::Query(qry) => {
				// 1. Check MaterializedCatalog (skip transactional changes)
				if let Some(namespace) = self.materialized.find_namespace_at(id, qry.version()) {
					return Ok(Some(namespace));
				}

				// 2. Fall back to storage as defensive measure
				if let Some(namespace) =
					CatalogStore::find_namespace(&mut Transaction::Query(&mut *qry), id)?
				{
					warn!(
						"Namespace with ID {:?} found in storage but not in MaterializedCatalog",
						id
					);
					return Ok(Some(namespace));
				}

				Ok(None)
			}
			Transaction::Test(mut t) => {
				if let Some(ns) = TransactionalNamespaceChanges::find_namespace(t.inner, id) {
					return Ok(Some(ns.clone()));
				}
				if TransactionalNamespaceChanges::is_namespace_deleted(t.inner, id) {
					return Ok(None);
				}
				if let Some(ns) = CatalogStore::find_namespace(
					&mut Transaction::Test(Box::new(t.reborrow())),
					id,
				)? {
					return Ok(Some(ns));
				}
				Ok(None)
			}
			Transaction::Replica(rep) => {
				if let Some(namespace) = self.materialized.find_namespace_at(id, rep.version()) {
					return Ok(Some(namespace));
				}
				if let Some(namespace) =
					CatalogStore::find_namespace(&mut Transaction::Replica(&mut *rep), id)?
				{
					warn!(
						"Namespace with ID {:?} found in storage but not in MaterializedCatalog",
						id
					);
					return Ok(Some(namespace));
				}
				Ok(None)
			}
		}
	}

	#[instrument(name = "catalog::namespace::find_by_name", level = "trace", skip(self, txn, name))]
	pub fn find_namespace_by_name(&self, txn: &mut Transaction<'_>, name: &str) -> Result<Option<Namespace>> {
		match txn.reborrow() {
			Transaction::Command(cmd) => {
				// 1. Check MaterializedCatalog
				if let Some(namespace) =
					self.materialized.find_namespace_by_name_at(name, cmd.version())
				{
					return Ok(Some(namespace));
				}

				// 2. Fall back to storage as defensive measure
				if let Some(namespace) = CatalogStore::find_namespace_by_name(
					&mut Transaction::Command(&mut *cmd),
					name,
				)? {
					warn!("Namespace '{}' found in storage but not in MaterializedCatalog", name);
					return Ok(Some(namespace));
				}

				Ok(None)
			}
			Transaction::Admin(admin) => {
				// 1. Check transactional changes first
				if let Some(namespace) =
					TransactionalNamespaceChanges::find_namespace_by_name(admin, name)
				{
					return Ok(Some(namespace.clone()));
				}

				// 2. Check if deleted
				if TransactionalNamespaceChanges::is_namespace_deleted_by_name(admin, name) {
					return Ok(None);
				}

				// 3. Check MaterializedCatalog
				if let Some(namespace) =
					self.materialized.find_namespace_by_name_at(name, admin.version())
				{
					return Ok(Some(namespace));
				}

				// 4. Fall back to storage as defensive measure
				if let Some(namespace) = CatalogStore::find_namespace_by_name(
					&mut Transaction::Admin(&mut *admin),
					name,
				)? {
					warn!("Namespace '{}' found in storage but not in MaterializedCatalog", name);
					return Ok(Some(namespace));
				}

				Ok(None)
			}
			Transaction::Query(qry) => {
				// 1. Check MaterializedCatalog (skip transactional changes)
				if let Some(namespace) =
					self.materialized.find_namespace_by_name_at(name, qry.version())
				{
					return Ok(Some(namespace));
				}

				// 2. Fall back to storage as defensive measure
				if let Some(namespace) =
					CatalogStore::find_namespace_by_name(&mut Transaction::Query(&mut *qry), name)?
				{
					warn!("Namespace '{}' found in storage but not in MaterializedCatalog", name);
					return Ok(Some(namespace));
				}

				Ok(None)
			}
			Transaction::Test(mut t) => {
				if let Some(ns) = TransactionalNamespaceChanges::find_namespace_by_name(t.inner, name) {
					return Ok(Some(ns.clone()));
				}
				if TransactionalNamespaceChanges::is_namespace_deleted_by_name(t.inner, name) {
					return Ok(None);
				}
				if let Some(ns) = CatalogStore::find_namespace_by_name(
					&mut Transaction::Test(Box::new(t.reborrow())),
					name,
				)? {
					return Ok(Some(ns));
				}
				Ok(None)
			}
			Transaction::Replica(rep) => {
				if let Some(namespace) =
					self.materialized.find_namespace_by_name_at(name, rep.version())
				{
					return Ok(Some(namespace));
				}
				if let Some(namespace) = CatalogStore::find_namespace_by_name(
					&mut Transaction::Replica(&mut *rep),
					name,
				)? {
					warn!("Namespace '{}' found in storage but not in MaterializedCatalog", name);
					return Ok(Some(namespace));
				}
				Ok(None)
			}
		}
	}

	fn find_child_namespace(
		&self,
		txn: &mut Transaction<'_>,
		parent_id: NamespaceId,
		name: &str,
	) -> Result<Option<Namespace>> {
		match txn.reborrow() {
			Transaction::Command(cmd) => {
				if let Some(ns) =
					self.materialized.find_child_namespace_at(parent_id, name, cmd.version())
				{
					return Ok(Some(ns));
				}
				let all = CatalogStore::list_namespaces_all(&mut Transaction::Command(&mut *cmd))?;
				Ok(all.into_iter().find(|ns| ns.local_name() == name && ns.parent_id() == parent_id))
			}
			Transaction::Admin(admin) => {
				if let Some(ns) = admin.changes.namespace.iter().rev().find_map(|change| {
					change.post
						.as_ref()
						.filter(|ns| ns.local_name() == name && ns.parent_id() == parent_id)
				}) {
					return Ok(Some(ns.clone()));
				}
				if let Some(ns) =
					self.materialized.find_child_namespace_at(parent_id, name, admin.version())
				{
					return Ok(Some(ns));
				}
				let all = CatalogStore::list_namespaces_all(&mut Transaction::Admin(&mut *admin))?;
				Ok(all.into_iter().find(|ns| ns.local_name() == name && ns.parent_id() == parent_id))
			}
			Transaction::Query(qry) => {
				if let Some(ns) =
					self.materialized.find_child_namespace_at(parent_id, name, qry.version())
				{
					return Ok(Some(ns));
				}
				let all = CatalogStore::list_namespaces_all(&mut Transaction::Query(&mut *qry))?;
				Ok(all.into_iter().find(|ns| ns.local_name() == name && ns.parent_id() == parent_id))
			}
			Transaction::Test(t) => {
				if let Some(ns) = t.inner.changes.namespace.iter().rev().find_map(|change| {
					change.post
						.as_ref()
						.filter(|ns| ns.local_name() == name && ns.parent_id() == parent_id)
				}) {
					return Ok(Some(ns.clone()));
				}
				if let Some(ns) =
					self.materialized.find_child_namespace_at(parent_id, name, t.inner.version())
				{
					return Ok(Some(ns));
				}
				let all = CatalogStore::list_namespaces_all(&mut Transaction::Admin(&mut *t.inner))?;
				Ok(all.into_iter().find(|ns| ns.local_name() == name && ns.parent_id() == parent_id))
			}
			Transaction::Replica(rep) => {
				if let Some(ns) =
					self.materialized.find_child_namespace_at(parent_id, name, rep.version())
				{
					return Ok(Some(ns));
				}
				let all = CatalogStore::list_namespaces_all(&mut Transaction::Replica(&mut *rep))?;
				Ok(all.into_iter().find(|ns| ns.local_name() == name && ns.parent_id() == parent_id))
			}
		}
	}

	/// Resolve namespace from path segments (e.g. `["system", "config"]`).
	/// Returns the "default" namespace when segments is empty.
	pub fn find_namespace_by_segments(
		&self,
		txn: &mut Transaction<'_>,
		segments: &[&str],
	) -> Result<Option<Namespace>> {
		if segments.is_empty() {
			return self.find_namespace_by_name(txn, "default");
		}

		let mut current = match self.find_namespace_by_name(txn, segments[0])? {
			Some(ns) => ns,
			None => return Ok(None),
		};

		for &segment in &segments[1..] {
			match self.find_child_namespace(txn, current.id(), segment)? {
				Some(ns) => current = ns,
				None => return Ok(None),
			}
		}

		Ok(Some(current))
	}

	/// Resolve a `::` separated path (e.g. `"system::config"`) to a `Namespace` by walking
	/// parent → child hierarchically.
	pub fn find_namespace_by_path(&self, txn: &mut Transaction<'_>, path: &str) -> Result<Option<Namespace>> {
		let segments: Vec<&str> = path.split("::").collect();
		self.find_namespace_by_segments(txn, &segments)
	}

	#[instrument(name = "catalog::namespace::get", level = "trace", skip(self, txn))]
	pub fn get_namespace(&self, txn: &mut Transaction<'_>, id: NamespaceId) -> Result<Namespace> {
		self.find_namespace(txn, id)?.ok_or_else(|| {
			error!(internal!(
				"Namespace with ID {} not found in catalog. This indicates a critical catalog inconsistency.",
				id
			))
		})
	}

	#[instrument(name = "catalog::namespace::get_by_name", level = "trace", skip(self, txn, name))]
	pub fn get_namespace_by_name(
		&self,
		txn: &mut Transaction<'_>,
		name: impl Into<Fragment> + Send,
	) -> Result<Namespace> {
		let name = name.into();
		self.find_namespace_by_name(txn, name.text())?.ok_or_else(|| {
			CatalogError::NotFound {
				kind: CatalogObjectKind::Namespace,
				namespace: name.text().to_string(),
				name: name.text().to_string(),
				fragment: name.clone(),
			}
			.into()
		})
	}

	#[instrument(name = "catalog::namespace::create", level = "debug", skip(self, txn, to_create))]
	pub fn create_namespace(&self, txn: &mut AdminTransaction, to_create: NamespaceToCreate) -> Result<Namespace> {
		let namespace = CatalogStore::create_namespace(txn, to_create.into())?;
		txn.track_namespace_created(namespace.clone())?;
		Ok(namespace)
	}

	/// Create a namespace with a specific ID. Used for bootstrapping system namespaces.
	pub fn create_namespace_with_id(
		&self,
		txn: &mut AdminTransaction,
		namespace_id: NamespaceId,
		to_create: NamespaceToCreate,
	) -> Result<Namespace> {
		let namespace = CatalogStore::create_namespace_with_id(txn, namespace_id, to_create.into())?;
		txn.track_namespace_created(namespace.clone())?;
		Ok(namespace)
	}

	#[instrument(name = "catalog::namespace::drop", level = "debug", skip(self, txn))]
	pub fn drop_namespace(&self, txn: &mut AdminTransaction, namespace: Namespace) -> Result<()> {
		CatalogStore::drop_namespace(txn, namespace.id())?;
		txn.track_namespace_deleted(namespace)?;
		Ok(())
	}

	#[instrument(name = "catalog::namespace::list_all", level = "debug", skip(self, txn))]
	pub fn list_namespaces_all(&self, txn: &mut Transaction<'_>) -> Result<Vec<Namespace>> {
		CatalogStore::list_namespaces_all(txn)
	}

	#[instrument(name = "catalog::namespace::update_grpc", level = "debug", skip(self, txn))]
	pub fn update_namespace_grpc(
		&self,
		txn: &mut AdminTransaction,
		namespace_id: NamespaceId,
		grpc: Option<String>,
	) -> Result<()> {
		CatalogStore::update_namespace_grpc(txn, namespace_id, grpc)?;
		// Re-read the updated namespace and track the change
		let updated = CatalogStore::get_namespace(&mut Transaction::Admin(&mut *txn), namespace_id)?;
		txn.track_namespace_created(updated)?;
		Ok(())
	}
}