1use std::fmt;
7use thiserror::Error;
8
9#[derive(Error, Debug, Clone)]
11pub enum TableBuildError {
12 #[error("Table must have at least one column")]
13 NoColumns,
14
15 #[error("Table must have exactly one primary key, found {0}")]
16 MultiplePrimaryKeys(usize),
17
18 #[error("Table must have a primary key")]
19 NoPrimaryKey,
20
21 #[error("Duplicate column name: {0}")]
22 DuplicateColumnName(String),
23
24 #[error("Invalid table name: {0}")]
25 InvalidTableName(String),
26
27 #[error("Invalid schema name: {0}")]
28 InvalidSchemaName(String),
29
30 #[error("Column build error: {0}")]
31 ColumnError(#[from] ColumnBuildError),
32
33 #[error("Constraint build error: {0}")]
34 ConstraintError(#[from] ConstraintBuildError),
35
36 #[error("Index build error: {0}")]
37 IndexError(#[from] IndexBuildError),
38
39 #[error("Validation error: {0}")]
40 ValidationError(String),
41}
42
43#[derive(Error, Debug, Clone)]
45pub enum ColumnBuildError {
46 #[error("Invalid column name: {0}")]
47 InvalidColumnName(String),
48
49 #[error("Generated column cannot have a default value")]
50 GeneratedColumnWithDefault,
51
52 #[error("Generated column cannot be a primary key")]
53 GeneratedColumnAsPrimaryKey,
54
55 #[error("Generated column cannot have a foreign key")]
56 GeneratedColumnWithForeignKey,
57
58 #[error("Invalid check constraint: {0}")]
59 InvalidCheckConstraint(String),
60
61 #[error("Invalid default value: {0}")]
62 InvalidDefaultValue(String),
63
64 #[error("Invalid collation: {0}")]
65 InvalidCollation(String),
66
67 #[error("Foreign key error: {0}")]
68 ForeignKeyError(#[from] ForeignKeyBuildError),
69
70 #[error("Validation error: {0}")]
71 ValidationError(String),
72}
73
74#[derive(Error, Debug, Clone)]
76pub enum ConstraintBuildError {
77 #[error("Constraint must specify columns")]
78 NoColumns,
79
80 #[error("Check constraint must have an expression")]
81 MissingExpression,
82
83 #[error("Invalid constraint name: {0}")]
84 InvalidConstraintName(String),
85
86 #[error("Invalid check expression: {0}")]
87 InvalidCheckExpression(String),
88
89 #[error("Foreign key error: {0}")]
90 ForeignKeyError(#[from] ForeignKeyBuildError),
91
92 #[error("Validation error: {0}")]
93 ValidationError(String),
94}
95
96#[derive(Error, Debug, Clone)]
98pub enum IndexBuildError {
99 #[error("Index must have at least one column")]
100 NoColumns,
101
102 #[error("Empty WHERE clause")]
103 EmptyWhereClause,
104
105 #[error("Invalid index name: {0}")]
106 InvalidIndexName(String),
107
108 #[error("Invalid column specification: {0}")]
109 InvalidColumnSpec(String),
110
111 #[error("Invalid WHERE clause: {0}")]
112 InvalidWhereClause(String),
113
114 #[error("Validation error: {0}")]
115 ValidationError(String),
116}
117
118#[derive(Error, Debug, Clone)]
120pub enum ViewBuildError {
121 #[error("View must have a SELECT statement")]
122 NoSelectStatement,
123
124 #[error("Invalid view name: {0}")]
125 InvalidViewName(String),
126
127 #[error("Invalid schema name: {0}")]
128 InvalidSchemaName(String),
129
130 #[error("Invalid SQL in view definition: {0}")]
131 InvalidSql(String),
132
133 #[error("Validation error: {0}")]
134 ValidationError(String),
135}
136
137#[derive(Error, Debug, Clone)]
139pub enum CompositeTypeBuildError {
140 #[error("Composite type must have at least one field")]
141 NoFields,
142
143 #[error("Invalid type name: {0}")]
144 InvalidTypeName(String),
145
146 #[error("Invalid field name: {0}")]
147 InvalidFieldName(String),
148
149 #[error("Invalid field type: {0}")]
150 InvalidFieldType(String),
151
152 #[error("Duplicate field name: {0}")]
153 DuplicateFieldName(String),
154
155 #[error("Validation error: {0}")]
156 ValidationError(String),
157}
158
159#[derive(Error, Debug, Clone)]
161pub enum FunctionBuildError {
162 #[error("Validation error: {0}")]
163 ValidationError(String),
164}
165
166#[derive(Error, Debug, Clone)]
168pub enum ProcedureBuildError {
169 #[error("Validation error: {0}")]
170 ValidationError(String),
171}
172
173#[derive(Error, Debug, Clone)]
175pub enum TriggerBuildError {
176 #[error("Validation error: {0}")]
177 ValidationError(String),
178}
179
180#[derive(Error, Debug, Clone)]
182pub enum SequenceBuildError {
183 #[error("Validation error: {0}")]
184 ValidationError(String),
185}
186
187#[derive(Error, Debug, Clone)]
189pub enum RoleBuildError {
190 #[error("Role name is required")]
191 MissingName,
192
193 #[error("Login role must have a password")]
194 LoginWithoutPassword,
195
196 #[error("Invalid connection limit: {0}")]
197 InvalidConnectionLimit(i32),
198
199 #[error("Invalid role name: {0}")]
200 InvalidRoleName(String),
201
202 #[error("Invalid password format")]
203 InvalidPasswordFormat,
204
205 #[error("Invalid valid_until date: {0}")]
206 InvalidValidUntil(String),
207
208 #[error("Circular role dependency detected")]
209 CircularDependency,
210
211 #[error("Validation error: {0}")]
212 ValidationError(String),
213}
214
215#[derive(Error, Debug, Clone)]
217pub enum GrantBuildError {
218 #[error("Grant must specify at least one privilege")]
219 NoPrivileges,
220
221 #[error("Grant must specify a target (ON clause)")]
222 NoTarget,
223
224 #[error("Grant must specify a grantee (TO clause)")]
225 NoGrantee,
226
227 #[error("Cannot specify ALL privilege with other privileges")]
228 AllWithOtherPrivileges,
229
230 #[error("Invalid privilege: {0}")]
231 InvalidPrivilege(String),
232
233 #[error("Invalid target: {0}")]
234 InvalidTarget(String),
235
236 #[error("Invalid grantee: {0}")]
237 InvalidGrantee(String),
238
239 #[error("Validation error: {0}")]
240 ValidationError(String),
241}
242
243#[derive(Error, Debug, Clone)]
245pub enum EventBuildError {
246 #[error("Event name is required")]
247 MissingName,
248
249 #[error("Event schedule is required")]
250 MissingSchedule,
251
252 #[error("Event command is required")]
253 MissingCommand,
254
255 #[error("Invalid cron schedule format")]
256 InvalidScheduleFormat,
257
258 #[error("Invalid port number: {0}")]
259 InvalidPort(u16),
260
261 #[error("Invalid event name: {0}")]
262 InvalidEventName(String),
263
264 #[error("Invalid command: {0}")]
265 InvalidCommand(String),
266
267 #[error("Validation error: {0}")]
268 ValidationError(String),
269}
270
271#[derive(Error, Debug, Clone)]
273pub enum PolicyBuildError {
274 #[error("Policy name is required")]
275 MissingName,
276
277 #[error("Table name is required")]
278 MissingTable,
279
280 #[error("Policy command is required")]
281 MissingCommand,
282
283 #[error("USING expression is required")]
284 MissingExpression,
285
286 #[error("USING expression cannot be empty")]
287 EmptyExpression,
288
289 #[error("WITH CHECK expression cannot be empty")]
290 EmptyCheckExpression,
291
292 #[error("Invalid policy name: {0}")]
293 InvalidPolicyName(String),
294
295 #[error("Invalid table name: {0}")]
296 InvalidTableName(String),
297
298 #[error("Invalid schema name: {0}")]
299 InvalidSchemaName(String),
300
301 #[error("Invalid role name: {0}")]
302 InvalidRoleName(String),
303
304 #[error("Validation error: {0}")]
305 ValidationError(String),
306}
307
308#[derive(Error, Debug, Clone)]
310pub enum ExtensionBuildError {
311 #[error("Extension name is required")]
312 MissingName,
313
314 #[error("Extension name cannot be empty")]
315 EmptyName,
316
317 #[error("Invalid extension name: {0}")]
318 InvalidName(String),
319
320 #[error("Invalid schema name: {0}")]
321 InvalidSchemaName(String),
322
323 #[error("Invalid version: {0}")]
324 InvalidVersion(String),
325
326 #[error("Validation error: {0}")]
327 ValidationError(String),
328}
329
330#[derive(Error, Debug, Clone)]
332pub enum GucBuildError {
333 #[error("GUC setting name is required")]
334 MissingName,
335
336 #[error("GUC setting value is required")]
337 MissingValue,
338
339 #[error("GUC context is required")]
340 MissingContext,
341
342 #[error("GUC setting name cannot be empty")]
343 EmptyName,
344
345 #[error("GUC setting value cannot be empty")]
346 EmptyValue,
347
348 #[error("Invalid GUC setting name: {0}")]
349 InvalidName(String),
350
351 #[error("Invalid GUC setting value: {0}")]
352 InvalidValue(String),
353
354 #[error("Invalid GUC context: {0}")]
355 InvalidContext(String),
356
357 #[error("Validation error: {0}")]
358 ValidationError(String),
359}
360
361#[derive(Error, Debug, Clone)]
363pub enum ForeignKeyBuildError {
364 #[error("Invalid referenced table: {0}")]
365 InvalidReferencedTable(String),
366
367 #[error("Invalid referenced column: {0}")]
368 InvalidReferencedColumn(String),
369
370 #[error("Invalid ON DELETE action: {0}")]
371 InvalidOnDeleteAction(String),
372
373 #[error("Invalid ON UPDATE action: {0}")]
374 InvalidOnUpdateAction(String),
375
376 #[error("Validation error: {0}")]
377 ValidationError(String),
378}
379
380#[derive(Error, Debug, Clone)]
382pub enum CustomSqlBuildError {
383 #[error("Migration ID is required")]
384 MissingId,
385
386 #[error("Migration name is required")]
387 MissingName,
388
389 #[error("Up migration SQL is required")]
390 MissingUpSql,
391
392 #[error("Migration ID cannot be empty")]
393 EmptyId,
394
395 #[error("Migration name cannot be empty")]
396 EmptyName,
397
398 #[error("Up migration SQL cannot be empty")]
399 EmptyUpSql,
400
401 #[error("Invalid migration ID: {0}")]
402 InvalidId(String),
403
404 #[error("Invalid migration name: {0}")]
405 InvalidName(String),
406
407 #[error("Invalid SQL: {0}")]
408 InvalidSql(String),
409
410 #[error("Circular dependency detected: {0}")]
411 CircularDependency(String),
412
413 #[error("Validation error: {0}")]
414 ValidationError(String),
415}
416
417#[derive(Debug, Clone)]
419pub enum BuilderValidationError {
420 RequiredFieldMissing(String),
421 InvalidValue(String, String),
422 InvalidFormat(String, String),
423 OutOfRange(String, String),
424 ConflictingConfiguration(String),
425 CircularDependency(String),
426 Generic(String),
427}
428
429impl fmt::Display for BuilderValidationError {
430 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
431 match self {
432 BuilderValidationError::RequiredFieldMissing(field) => {
433 write!(f, "Required field missing: {}", field)
434 }
435 BuilderValidationError::InvalidValue(field, value) => {
436 write!(f, "Invalid value for field {}: {}", field, value)
437 }
438 BuilderValidationError::InvalidFormat(field, format) => {
439 write!(f, "Field {} has invalid format: {}", field, format)
440 }
441 BuilderValidationError::OutOfRange(field, range) => {
442 write!(f, "Field {} is out of range: {}", field, range)
443 }
444 BuilderValidationError::ConflictingConfiguration(conflict) => {
445 write!(f, "Conflicting configuration: {}", conflict)
446 }
447 BuilderValidationError::CircularDependency(dependency) => {
448 write!(f, "Circular dependency detected: {}", dependency)
449 }
450 BuilderValidationError::Generic(message) => {
451 write!(f, "Validation error: {}", message)
452 }
453 }
454 }
455}
456
457impl std::error::Error for BuilderValidationError {}
458
459pub type BuilderResult<T> = Result<T, Box<dyn std::error::Error + Send + Sync>>;
461
462#[derive(Debug, Clone)]
464pub struct ValidationContext {
465 pub table_name: Option<String>,
466 pub schema_name: Option<String>,
467 pub column_name: Option<String>,
468 pub constraint_name: Option<String>,
469 pub index_name: Option<String>,
470 pub view_name: Option<String>,
471 pub type_name: Option<String>,
472}
473
474impl ValidationContext {
475 pub fn new() -> Self {
477 Self {
478 table_name: None,
479 schema_name: None,
480 column_name: None,
481 constraint_name: None,
482 index_name: None,
483 view_name: None,
484 type_name: None,
485 }
486 }
487
488 pub fn with_table_name(mut self, name: impl Into<String>) -> Self {
490 self.table_name = Some(name.into());
491 self
492 }
493
494 pub fn with_schema_name(mut self, name: impl Into<String>) -> Self {
496 self.schema_name = Some(name.into());
497 self
498 }
499
500 pub fn with_column_name(mut self, name: impl Into<String>) -> Self {
502 self.column_name = Some(name.into());
503 self
504 }
505
506 pub fn with_constraint_name(mut self, name: impl Into<String>) -> Self {
508 self.constraint_name = Some(name.into());
509 self
510 }
511
512 pub fn with_index_name(mut self, name: impl Into<String>) -> Self {
514 self.index_name = Some(name.into());
515 self
516 }
517
518 pub fn with_view_name(mut self, name: impl Into<String>) -> Self {
520 self.view_name = Some(name.into());
521 self
522 }
523
524 pub fn with_type_name(mut self, name: impl Into<String>) -> Self {
526 self.type_name = Some(name.into());
527 self
528 }
529
530 pub fn summary(&self) -> String {
532 let mut parts = Vec::new();
533
534 if let Some(ref schema) = self.schema_name {
535 parts.push(format!("schema: {}", schema));
536 }
537
538 if let Some(ref table) = self.table_name {
539 parts.push(format!("table: {}", table));
540 }
541
542 if let Some(ref column) = self.column_name {
543 parts.push(format!("column: {}", column));
544 }
545
546 if let Some(ref constraint) = self.constraint_name {
547 parts.push(format!("constraint: {}", constraint));
548 }
549
550 if let Some(ref index) = self.index_name {
551 parts.push(format!("index: {}", index));
552 }
553
554 if let Some(ref view) = self.view_name {
555 parts.push(format!("view: {}", view));
556 }
557
558 if let Some(ref type_name) = self.type_name {
559 parts.push(format!("type: {}", type_name));
560 }
561
562 if parts.is_empty() {
563 "unknown context".to_string()
564 } else {
565 parts.join(", ")
566 }
567 }
568}
569
570impl Default for ValidationContext {
571 fn default() -> Self {
572 Self::new()
573 }
574}
575
576pub trait ValidationRule {
578 type Input;
579 type Error;
580
581 fn validate(&self, input: &Self::Input) -> Result<(), Self::Error>;
583
584 fn description(&self) -> String;
586}
587
588pub mod rules {
590 use super::*;
591
592 pub struct TableNameRule;
594
595 impl ValidationRule for TableNameRule {
596 type Input = String;
597 type Error = TableBuildError;
598
599 fn validate(&self, input: &Self::Input) -> Result<(), Self::Error> {
600 if input.is_empty() {
601 return Err(TableBuildError::InvalidTableName(input.clone()));
602 }
603
604 if input.len() > 63 {
605 return Err(TableBuildError::InvalidTableName(input.clone()));
606 }
607
608 if !input.chars().next().unwrap().is_ascii_alphabetic() {
610 return Err(TableBuildError::InvalidTableName(input.clone()));
611 }
612
613 if !input.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') {
614 return Err(TableBuildError::InvalidTableName(input.clone()));
615 }
616
617 Ok(())
618 }
619
620 fn description(&self) -> String {
621 "Table name must be 1-63 characters, start with a letter, and contain only alphanumeric characters and underscores".to_string()
622 }
623 }
624
625 pub struct ColumnNameRule;
627
628 impl ValidationRule for ColumnNameRule {
629 type Input = String;
630 type Error = ColumnBuildError;
631
632 fn validate(&self, input: &Self::Input) -> Result<(), Self::Error> {
633 if input.is_empty() {
634 return Err(ColumnBuildError::InvalidColumnName(input.clone()));
635 }
636
637 if input.len() > 63 {
638 return Err(ColumnBuildError::InvalidColumnName(input.clone()));
639 }
640
641 if !input.chars().next().unwrap().is_ascii_alphabetic() {
643 return Err(ColumnBuildError::InvalidColumnName(input.clone()));
644 }
645
646 if !input.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') {
647 return Err(ColumnBuildError::InvalidColumnName(input.clone()));
648 }
649
650 Ok(())
651 }
652
653 fn description(&self) -> String {
654 "Column name must be 1-63 characters, start with a letter, and contain only alphanumeric characters and underscores".to_string()
655 }
656 }
657
658 pub struct SchemaNameRule;
660
661 impl ValidationRule for SchemaNameRule {
662 type Input = String;
663 type Error = TableBuildError;
664
665 fn validate(&self, input: &Self::Input) -> Result<(), Self::Error> {
666 if input.is_empty() {
667 return Err(TableBuildError::InvalidSchemaName(input.clone()));
668 }
669
670 if input.len() > 63 {
671 return Err(TableBuildError::InvalidSchemaName(input.clone()));
672 }
673
674 if !input.chars().next().unwrap().is_ascii_alphabetic() {
676 return Err(TableBuildError::InvalidSchemaName(input.clone()));
677 }
678
679 if !input.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') {
680 return Err(TableBuildError::InvalidSchemaName(input.clone()));
681 }
682
683 Ok(())
684 }
685
686 fn description(&self) -> String {
687 "Schema name must be 1-63 characters, start with a letter, and contain only alphanumeric characters and underscores".to_string()
688 }
689 }
690}
691
692#[derive(Debug, Clone)]
694pub struct ValidationResult {
695 pub is_valid: bool,
696 pub errors: Vec<String>,
697 pub warnings: Vec<String>,
698 pub context: ValidationContext,
699}
700
701impl ValidationResult {
702 pub fn new() -> Self {
704 Self {
705 is_valid: true,
706 errors: Vec::new(),
707 warnings: Vec::new(),
708 context: ValidationContext::new(),
709 }
710 }
711
712 pub fn add_error(&mut self, error: impl Into<String>) {
714 self.errors.push(error.into());
715 self.is_valid = false;
716 }
717
718 pub fn add_warning(&mut self, warning: impl Into<String>) {
720 self.warnings.push(warning.into());
721 }
722
723 pub fn has_errors(&self) -> bool {
725 !self.errors.is_empty()
726 }
727
728 pub fn has_warnings(&self) -> bool {
730 !self.warnings.is_empty()
731 }
732
733 pub fn summary(&self) -> String {
735 if self.is_valid {
736 if self.warnings.is_empty() {
737 "Valid".to_string()
738 } else {
739 format!("Valid with {} warnings", self.warnings.len())
740 }
741 } else {
742 format!("Invalid with {} errors", self.errors.len())
743 }
744 }
745}
746
747impl Default for ValidationResult {
748 fn default() -> Self {
749 Self::new()
750 }
751}