nitrite/lib.rs
1#![allow(
2 dead_code,
3 unused_imports,
4 clippy::invisible_characters,
5 clippy::approx_constant,
6)]
7//! # Nitrite - Embedded NoSQL Database
8//!
9//! Nitrite is a lightweight, feature-rich, embedded NoSQL database written in Rust.
10//! It provides document and object storage with rich querying capabilities, indexing,
11//! and transaction support.
12//!
13//! ## Key Features
14//!
15//! - **Embedded**: No separate server process required
16//! - **NoSQL**: Document-based and object-oriented storage
17//! - **Rich Querying**: Powerful filter API with support for complex queries
18//! - **Indexing**: Support for unique, non-unique, and full-text indexes
19//! - **Spatial**: Geographic and spatial data support through the `nitrite-spatial` crate
20//! - **Transactions**: ACID transaction support
21//! - **Migration**: Schema migration management
22//! - **Events**: Event listeners for database, collection, and store events
23//! - **Multiple Storage Backends**: In-memory storage and pluggable store providers
24//! - **Clean API**: PIMPL pattern provides stable, encapsulated interface
25//!
26//! ## Quick Start
27//!
28//! ```rust,ignore
29//! use nitrite::nitrite_builder::NitriteBuilder;
30//! use nitrite::collection::Document;
31//!
32//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
33//! // Create or open a database
34//! let db = Nitrite::builder()
35//! .open_or_create(None, None)?;
36//!
37//! // Get or create a collection
38//! let mut collection = db.collection("users")?;
39//!
40//! // Create a document
41//! let mut doc = Document::new();
42//! doc.put("name", "John Doe")?;
43//! doc.put("age", 30i64)?;
44//!
45//! // Insert the document
46//! collection.insert(doc)?;
47//!
48//! // Find documents using filters
49//! let filter = nitrite::filter::all();
50//! let results = collection.find(filter)?;
51//!
52//! // Close the database
53//! db.close()?;
54//! # Ok(())
55//! # }
56//! ```
57//!
58//! ## Design Pattern
59//!
60//! Nitrite uses the **PIMPL (Pointer To IMPLementation)** design pattern to provide:
61//!
62//! - **Encapsulation**: Implementation details are completely hidden
63//! - **API Stability**: Public interface is stable and can evolve independently
64//! - **Implementation Flexibility**: Internal structure can be refactored without affecting users
65//! - **Thread Safety**: All clones share the same underlying state through `Arc<NitriteInner>`
66//!
67//! This design ensures that the Nitrite database provides a clean, stable API while keeping implementation
68//! complexity hidden.
69//!
70//! ## Module Organization
71//!
72//! - [`collection`] - Document collections, repositories, and document operations
73//! - [`common`] - Common types, traits, and utilities
74//! - [`errors`] - Error types and result definitions
75//! - [`filter`] - Query filters and filter providers
76//! - [`index`] - Indexing support (unique, non-unique, full-text)
77//! - [`metadata`] - Database metadata management
78//! - [`migration`] - Schema migration support
79//! - [`nitrite`] - Core database interface
80//! - [`nitrite_builder`] - Database builder for initialization
81//! - [`nitrite_config`] - Database configuration
82//! - [`repository`] - Type-safe object repositories
83//! - [`store`] - Storage backend abstractions
84//! - [`transaction`] - Transaction support
85
86use crate::collection::snowflake::SnowflakeIdGenerator;
87use crate::common::*;
88use std::sync::LazyLock;
89use std::thread::available_parallelism;
90
91pub mod collection;
92pub mod common;
93pub mod errors;
94pub mod filter;
95pub mod index;
96pub mod metadata;
97pub mod migration;
98pub mod nitrite;
99pub mod nitrite_builder;
100pub mod nitrite_config;
101pub mod repository;
102pub mod store;
103pub mod transaction;
104
105pub(crate) static FIELD_SEPARATOR: LazyLock<Atomic<String>> =
106 LazyLock::new(|| atomic(".".to_string()));
107pub(crate) static ID_GENERATOR: LazyLock<SnowflakeIdGenerator> =
108 LazyLock::new(SnowflakeIdGenerator::new);
109
110pub(crate) static SCHEDULER: LazyLock<Scheduler> = LazyLock::new(Scheduler::new);
111
112/// Returns the number of available CPU cores.
113///
114/// This function attempts to detect the number of available processors on the system.
115/// If detection fails, it defaults to 1.
116///
117/// # Returns
118///
119/// A `usize` representing the number of available CPU cores.
120///
121/// # Examples
122///
123/// ```rust
124/// use nitrite::get_cpu_count;
125///
126/// let cpu_count = get_cpu_count();
127/// println!("Available CPUs: {}", cpu_count);
128/// assert!(cpu_count > 0);
129/// ```
130pub fn get_cpu_count() -> usize {
131 available_parallelism()
132 .map(|p| p.get())
133 .unwrap_or_else(|err| {
134 log::warn!(
135 "Failed to detect available parallelism: {}. Defaulting to single thread.",
136 err
137 );
138 1
139 })
140}
141
142#[cfg(test)]
143#[allow(clippy::assertions_on_constants)] // tests use assert!(true) as "reached without panic" markers
144mod tests {
145 use super::*;
146
147 #[test]
148 fn test_get_cpu_count_positive() {
149 // Test that get_cpu_count returns a positive value
150 let count = get_cpu_count();
151 assert!(count > 0);
152 }
153
154 #[test]
155 fn test_scheduler_initialization() {
156 // Test that SCHEDULER initializes successfully
157 let _scheduler = &*SCHEDULER;
158 // If we can access it, initialization was successful
159 assert!(true);
160 }
161}