use crate::builders::traits::{
ConditionalBuilder, InspectableBuilder, SchemaBuilder, ValidatableBuilder,
};
use crate::builders::validation::SequenceBuildError;
use crate::schema::Sequence;
#[derive(Debug, Clone)]
pub struct SequenceBuilder {
name: Option<String>,
schema: Option<String>,
data_type: Option<String>,
start_value: Option<i64>,
minimum_value: Option<i64>,
maximum_value: Option<i64>,
increment: Option<i64>,
cycle: Option<bool>,
cache: Option<i64>,
owner: Option<String>,
comment: Option<String>,
}
impl SequenceBuilder {
pub fn new() -> Self {
Self {
name: None,
schema: None,
data_type: None,
start_value: None,
minimum_value: None,
maximum_value: None,
increment: None,
cycle: None,
cache: None,
owner: None,
comment: None,
}
}
pub fn name(mut self, name: impl Into<String>) -> Self {
self.name = Some(name.into());
self
}
pub fn set_name(&mut self, name: impl Into<String>) {
self.name = Some(name.into());
}
pub fn in_schema(mut self, schema: impl Into<String>) -> Self {
self.schema = Some(schema.into());
self
}
pub fn set_schema(&mut self, schema: impl Into<String>) {
self.schema = Some(schema.into());
}
pub fn data_type(mut self, data_type: impl Into<String>) -> Self {
self.data_type = Some(data_type.into());
self
}
pub fn set_data_type(&mut self, data_type: impl Into<String>) {
self.data_type = Some(data_type.into());
}
pub fn start_value(mut self, start: i64) -> Self {
self.start_value = Some(start);
self
}
pub fn set_start_value(&mut self, start: i64) {
self.start_value = Some(start);
}
pub fn minimum_value(mut self, min: i64) -> Self {
self.minimum_value = Some(min);
self
}
pub fn set_minimum_value(&mut self, min: i64) {
self.minimum_value = Some(min);
}
pub fn maximum_value(mut self, max: i64) -> Self {
self.maximum_value = Some(max);
self
}
pub fn set_maximum_value(&mut self, max: i64) {
self.maximum_value = Some(max);
}
pub fn increment(mut self, increment: i64) -> Self {
self.increment = Some(increment);
self
}
pub fn set_increment(&mut self, increment: i64) {
self.increment = Some(increment);
}
pub fn cycle(mut self, cycle: bool) -> Self {
self.cycle = Some(cycle);
self
}
pub fn set_cycle(&mut self, cycle: bool) {
self.cycle = Some(cycle);
}
pub fn cache(mut self, cache: i64) -> Self {
self.cache = Some(cache);
self
}
pub fn set_cache(&mut self, cache: i64) {
self.cache = Some(cache);
}
pub fn owner(mut self, owner: impl Into<String>) -> Self {
self.owner = Some(owner.into());
self
}
pub fn set_owner(&mut self, owner: impl Into<String>) {
self.owner = Some(owner.into());
}
pub fn comment(mut self, comment: impl Into<String>) -> Self {
self.comment = Some(comment.into());
self
}
pub fn set_comment(&mut self, comment: impl Into<String>) {
self.comment = Some(comment.into());
}
pub fn simple() -> Self {
Self::new()
}
pub fn auto_increment() -> Self {
Self::new()
.data_type("BIGINT")
.start_value(1)
.increment(1)
.minimum_value(1)
.cycle(false)
}
pub fn small_auto_increment() -> Self {
Self::new()
.data_type("INTEGER")
.start_value(1)
.increment(1)
.minimum_value(1)
.cycle(false)
}
pub fn large_auto_increment() -> Self {
Self::new()
.data_type("BIGINT")
.start_value(1)
.increment(1)
.minimum_value(1)
.maximum_value(9223372036854775807)
.cycle(false)
}
pub fn timestamp() -> Self {
Self::new()
.data_type("BIGINT")
.start_value(0)
.increment(1)
.cycle(false)
}
pub fn counter() -> Self {
Self::new()
.data_type("INTEGER")
.start_value(0)
.increment(1)
.minimum_value(0)
.cycle(false)
}
pub fn cycling() -> Self {
Self::new()
.data_type("INTEGER")
.start_value(1)
.increment(1)
.minimum_value(1)
.maximum_value(1000)
.cycle(true)
}
pub fn cached() -> Self {
Self::new()
.data_type("BIGINT")
.start_value(1)
.increment(1)
.cache(10)
}
#[inline]
pub fn get_name(&self) -> Option<&str> {
self.name.as_deref()
}
#[inline]
pub fn get_schema(&self) -> Option<&str> {
self.schema.as_deref()
}
#[inline]
pub fn get_data_type(&self) -> Option<&str> {
self.data_type.as_deref()
}
pub fn get_start_value(&self) -> Option<i64> {
self.start_value
}
pub fn get_minimum_value(&self) -> Option<i64> {
self.minimum_value
}
pub fn get_maximum_value(&self) -> Option<i64> {
self.maximum_value
}
pub fn get_increment(&self) -> Option<i64> {
self.increment
}
pub fn get_cycle(&self) -> Option<bool> {
self.cycle
}
pub fn get_cache(&self) -> Option<i64> {
self.cache
}
pub fn get_owner(&self) -> Option<&str> {
self.owner.as_deref()
}
pub fn get_comment(&self) -> Option<&str> {
self.comment.as_deref()
}
pub fn has_name(&self) -> bool {
self.name.is_some()
}
pub fn has_schema(&self) -> bool {
self.schema.is_some()
}
pub fn has_data_type(&self) -> bool {
self.data_type.is_some()
}
pub fn has_start_value(&self) -> bool {
self.start_value.is_some()
}
pub fn has_minimum_value(&self) -> bool {
self.minimum_value.is_some()
}
pub fn has_maximum_value(&self) -> bool {
self.maximum_value.is_some()
}
pub fn has_increment(&self) -> bool {
self.increment.is_some()
}
pub fn has_cycle(&self) -> bool {
self.cycle.is_some()
}
pub fn has_cache(&self) -> bool {
self.cache.is_some()
}
pub fn has_owner(&self) -> bool {
self.owner.is_some()
}
pub fn has_comment(&self) -> bool {
self.comment.is_some()
}
}
impl SchemaBuilder for SequenceBuilder {
type Output = Sequence;
type Error = SequenceBuildError;
fn build(self) -> Result<Self::Output, Self::Error> {
if !self.is_valid() {
let errors = self.validation_errors();
return Err(SequenceBuildError::ValidationError(errors.join("; ")));
}
let sequence = Sequence {
name: self.name.unwrap_or_else(|| "sequence".to_string()),
schema: self.schema,
data_type: self.data_type.unwrap_or_else(|| "BIGINT".to_string()),
start_value: self.start_value,
minimum_value: self.minimum_value,
maximum_value: self.maximum_value,
increment: self.increment,
cycle: self.cycle,
cache: self.cache,
owner: self.owner,
comment: self.comment,
};
Ok(sequence)
}
}
impl ValidatableBuilder for SequenceBuilder {
fn is_valid(&self) -> bool {
self.validation_errors().is_empty()
}
fn validation_errors(&self) -> Vec<String> {
let mut errors = Vec::new();
if self.name.is_none() {
errors.push("Sequence must have a name".to_string());
}
if let Some(ref name) = self.name {
if name.trim().is_empty() {
errors.push("Sequence name cannot be empty".to_string());
}
}
if let Some(ref schema) = self.schema {
if schema.trim().is_empty() {
errors.push("Schema name cannot be empty".to_string());
}
}
if let Some(ref data_type) = self.data_type {
if data_type.trim().is_empty() {
errors.push("Data type cannot be empty".to_string());
}
}
if let Some(ref owner) = self.owner {
if owner.trim().is_empty() {
errors.push("Owner cannot be empty".to_string());
}
}
if let Some(ref comment) = self.comment {
if comment.trim().is_empty() {
errors.push("Comment cannot be empty".to_string());
}
}
if let (Some(min), Some(max)) = (self.minimum_value, self.maximum_value) {
if min >= max {
errors.push("Minimum value must be less than maximum value".to_string());
}
}
if let Some(increment) = self.increment {
if increment == 0 {
errors.push("Increment cannot be zero".to_string());
}
}
if let Some(cache) = self.cache {
if cache <= 0 {
errors.push("Cache size must be positive".to_string());
}
}
errors
}
}
impl ConditionalBuilder for SequenceBuilder {
fn when<F>(mut self, condition: bool, config_fn: F) -> Self
where
F: FnOnce(&mut Self),
Self: Sized,
{
if condition {
config_fn(&mut self);
}
self
}
}
impl InspectableBuilder for SequenceBuilder {
fn debug_info(&self) -> String {
format!(
"SequenceBuilder {{ name: {:?}, schema: {:?}, data_type: {:?}, start_value: {:?}, increment: {:?}, cycle: {:?} }}",
self.name, self.schema, self.data_type, self.start_value, self.increment, self.cycle
)
}
fn summary(&self) -> String {
let mut parts = Vec::new();
parts.push("Sequence".to_string());
if let Some(ref name) = self.name {
if let Some(ref schema) = self.schema {
parts.push(format!("{}.{}", schema, name));
} else {
parts.push(format!("'{}'", name));
}
}
if let Some(ref data_type) = self.data_type {
parts.push(format!("type: {}", data_type));
}
if let Some(start) = self.start_value {
parts.push(format!("starts at {}", start));
}
if let Some(increment) = self.increment {
parts.push(format!("increments by {}", increment));
}
let mut range_parts = Vec::new();
if let Some(min) = self.minimum_value {
range_parts.push(format!("min: {}", min));
}
if let Some(max) = self.maximum_value {
range_parts.push(format!("max: {}", max));
}
if !range_parts.is_empty() {
parts.push(format!("range: {}", range_parts.join(", ")));
}
if let Some(cycle) = self.cycle {
if cycle {
parts.push("cycles".to_string());
} else {
parts.push("no cycle".to_string());
}
}
if let Some(cache) = self.cache {
parts.push(format!("cache: {}", cache));
}
if let Some(ref owner) = self.owner {
parts.push(format!("owned by {}", owner));
}
if let Some(ref comment) = self.comment {
parts.push(format!("with comment: {}", comment));
}
parts.join(", ")
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_basic_sequence() {
let sequence = SequenceBuilder::new()
.name("user_id_seq")
.data_type("BIGINT")
.start_value(1)
.increment(1)
.build()
.unwrap();
assert_eq!(sequence.name, "user_id_seq");
assert_eq!(sequence.data_type, "BIGINT");
assert_eq!(sequence.start_value, Some(1));
assert_eq!(sequence.increment, Some(1));
}
#[test]
fn test_sequence_with_schema() {
let sequence = SequenceBuilder::new()
.name("order_id_seq")
.in_schema("public")
.data_type("INTEGER")
.start_value(1000)
.increment(10)
.build()
.unwrap();
assert_eq!(sequence.name, "order_id_seq");
assert_eq!(sequence.schema, Some("public".to_string()));
assert_eq!(sequence.data_type, "INTEGER");
assert_eq!(sequence.start_value, Some(1000));
assert_eq!(sequence.increment, Some(10));
}
#[test]
fn test_convenience_methods() {
let auto_seq = SequenceBuilder::auto_increment()
.name("auto_seq")
.build()
.unwrap();
let small_seq = SequenceBuilder::small_auto_increment()
.name("small_seq")
.build()
.unwrap();
let large_seq = SequenceBuilder::large_auto_increment()
.name("large_seq")
.build()
.unwrap();
let timestamp_seq = SequenceBuilder::timestamp()
.name("timestamp_seq")
.build()
.unwrap();
let counter_seq = SequenceBuilder::counter()
.name("counter_seq")
.build()
.unwrap();
let cycling_seq = SequenceBuilder::cycling()
.name("cycling_seq")
.build()
.unwrap();
let cached_seq = SequenceBuilder::cached()
.name("cached_seq")
.build()
.unwrap();
assert_eq!(auto_seq.data_type, "BIGINT");
assert_eq!(auto_seq.start_value, Some(1));
assert_eq!(auto_seq.increment, Some(1));
assert_eq!(auto_seq.minimum_value, Some(1));
assert_eq!(auto_seq.cycle, Some(false));
assert_eq!(small_seq.data_type, "INTEGER");
assert_eq!(small_seq.start_value, Some(1));
assert_eq!(large_seq.data_type, "BIGINT");
assert_eq!(large_seq.maximum_value, Some(9223372036854775807));
assert_eq!(timestamp_seq.data_type, "BIGINT");
assert_eq!(timestamp_seq.start_value, Some(0));
assert_eq!(counter_seq.data_type, "INTEGER");
assert_eq!(counter_seq.start_value, Some(0));
assert_eq!(counter_seq.minimum_value, Some(0));
assert_eq!(cycling_seq.data_type, "INTEGER");
assert_eq!(cycling_seq.maximum_value, Some(1000));
assert_eq!(cycling_seq.cycle, Some(true));
assert_eq!(cached_seq.data_type, "BIGINT");
assert_eq!(cached_seq.cache, Some(10));
}
#[test]
fn test_sequence_with_all_properties() {
let sequence = SequenceBuilder::new()
.name("comprehensive_seq")
.in_schema("public")
.data_type("BIGINT")
.start_value(100)
.minimum_value(1)
.maximum_value(10000)
.increment(5)
.cycle(true)
.cache(20)
.owner("postgres")
.comment("Comprehensive test sequence")
.build()
.unwrap();
assert_eq!(sequence.name, "comprehensive_seq");
assert_eq!(sequence.schema, Some("public".to_string()));
assert_eq!(sequence.data_type, "BIGINT");
assert_eq!(sequence.start_value, Some(100));
assert_eq!(sequence.minimum_value, Some(1));
assert_eq!(sequence.maximum_value, Some(10000));
assert_eq!(sequence.increment, Some(5));
assert_eq!(sequence.cycle, Some(true));
assert_eq!(sequence.cache, Some(20));
assert_eq!(sequence.owner, Some("postgres".to_string()));
assert_eq!(
sequence.comment,
Some("Comprehensive test sequence".to_string())
);
}
#[test]
fn test_validation_errors() {
let result = SequenceBuilder::new().data_type("BIGINT").build();
assert!(result.is_err());
assert!(matches!(
result.unwrap_err(),
SequenceBuildError::ValidationError(_)
));
let result = SequenceBuilder::new().name("").data_type("BIGINT").build();
assert!(result.is_err());
assert!(matches!(
result.unwrap_err(),
SequenceBuildError::ValidationError(_)
));
let result = SequenceBuilder::new()
.name("test_seq")
.data_type("INTEGER")
.minimum_value(100)
.maximum_value(50)
.build();
assert!(result.is_err());
assert!(matches!(
result.unwrap_err(),
SequenceBuildError::ValidationError(_)
));
let result = SequenceBuilder::new()
.name("test_seq")
.data_type("INTEGER")
.increment(0)
.build();
assert!(result.is_err());
assert!(matches!(
result.unwrap_err(),
SequenceBuildError::ValidationError(_)
));
let result = SequenceBuilder::new()
.name("test_seq")
.data_type("INTEGER")
.cache(-5)
.build();
assert!(result.is_err());
assert!(matches!(
result.unwrap_err(),
SequenceBuildError::ValidationError(_)
));
}
#[test]
fn test_conditional_builder() {
let condition = true;
let sequence = SequenceBuilder::new()
.when(condition, |s| {
s.set_name("sequence_when_true");
s.set_data_type("INTEGER");
s.set_start_value(100);
s.set_increment(5);
})
.build()
.unwrap();
assert_eq!(sequence.name, "sequence_when_true");
assert_eq!(sequence.data_type, "INTEGER");
assert_eq!(sequence.start_value, Some(100));
assert_eq!(sequence.increment, Some(5));
}
#[test]
fn test_inspection_methods() {
let builder = SequenceBuilder::new()
.name("test_sequence")
.in_schema("public")
.data_type("BIGINT")
.start_value(1)
.minimum_value(1)
.maximum_value(1000)
.increment(1)
.cycle(false)
.cache(10)
.owner("postgres")
.comment("This is a test sequence");
assert_eq!(builder.get_name(), Some("test_sequence"));
assert_eq!(builder.get_schema(), Some("public"));
assert_eq!(builder.get_data_type(), Some("BIGINT"));
assert_eq!(builder.get_start_value(), Some(1));
assert_eq!(builder.get_minimum_value(), Some(1));
assert_eq!(builder.get_maximum_value(), Some(1000));
assert_eq!(builder.get_increment(), Some(1));
assert_eq!(builder.get_cycle(), Some(false));
assert_eq!(builder.get_cache(), Some(10));
assert_eq!(builder.get_owner(), Some("postgres"));
assert_eq!(builder.get_comment(), Some("This is a test sequence"));
assert!(builder.has_name());
assert!(builder.has_schema());
assert!(builder.has_data_type());
assert!(builder.has_start_value());
assert!(builder.has_minimum_value());
assert!(builder.has_maximum_value());
assert!(builder.has_increment());
assert!(builder.has_cycle());
assert!(builder.has_cache());
assert!(builder.has_owner());
assert!(builder.has_comment());
}
#[test]
fn test_debug_info_and_summary() {
let builder = SequenceBuilder::new()
.name("user_id_seq")
.in_schema("public")
.data_type("BIGINT")
.start_value(1)
.increment(1)
.minimum_value(1)
.maximum_value(1000000)
.cycle(false)
.cache(10)
.comment("User ID sequence");
let debug_info = builder.debug_info();
let summary = builder.summary();
assert!(debug_info.contains("SequenceBuilder"));
assert!(debug_info.contains("user_id_seq"));
assert!(debug_info.contains("public"));
assert!(summary.contains("Sequence"));
assert!(summary.contains("public.user_id_seq"));
assert!(summary.contains("type: BIGINT"));
assert!(summary.contains("starts at 1"));
assert!(summary.contains("increments by 1"));
assert!(summary.contains("range: min: 1, max: 1000000"));
assert!(summary.contains("no cycle"));
assert!(summary.contains("cache: 10"));
assert!(summary.contains("with comment: User ID sequence"));
}
#[test]
fn test_sequence_with_complex_constraints() {
let sequence = SequenceBuilder::new()
.name("complex_seq")
.data_type("INTEGER")
.start_value(-1000)
.minimum_value(-10000)
.maximum_value(10000)
.increment(100)
.cycle(true)
.cache(50)
.build()
.unwrap();
assert_eq!(sequence.name, "complex_seq");
assert_eq!(sequence.data_type, "INTEGER");
assert_eq!(sequence.start_value, Some(-1000));
assert_eq!(sequence.minimum_value, Some(-10000));
assert_eq!(sequence.maximum_value, Some(10000));
assert_eq!(sequence.increment, Some(100));
assert_eq!(sequence.cycle, Some(true));
assert_eq!(sequence.cache, Some(50));
}
#[test]
fn test_sequence_with_owner() {
let sequence = SequenceBuilder::new()
.name("owned_seq")
.data_type("BIGINT")
.owner("app_user")
.build()
.unwrap();
assert_eq!(sequence.name, "owned_seq");
assert_eq!(sequence.owner, Some("app_user".to_string()));
}
#[test]
fn test_sequence_with_comment() {
let sequence = SequenceBuilder::new()
.name("commented_seq")
.data_type("INTEGER")
.comment("This sequence is used for generating unique IDs")
.build()
.unwrap();
assert_eq!(sequence.name, "commented_seq");
assert_eq!(
sequence.comment,
Some("This sequence is used for generating unique IDs".to_string())
);
}
}