reinhardt-db 0.1.1

Django-style database layer for Reinhardt framework
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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
//! Configuration for database introspection and code generation.
//!
//! Supports TOML configuration files and CLI argument overrides.

use super::naming::NamingConvention;
use regex::Regex;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::{Path, PathBuf};

/// Main configuration for database introspection.
#[non_exhaustive]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
#[derive(Default)]
pub struct IntrospectConfig {
	/// Database connection configuration
	pub database: DatabaseConfig,

	/// Output configuration
	pub output: OutputConfig,

	/// Code generation configuration
	pub generation: GenerationConfig,

	/// Table filtering configuration
	pub tables: TableFilterConfig,

	/// Type overrides: "table.column" -> "RustType"
	#[serde(default)]
	pub type_overrides: HashMap<String, String>,

	/// Additional imports configuration
	#[serde(default)]
	pub imports: ImportsConfig,
}

impl IntrospectConfig {
	/// Create a new configuration with the given database URL.
	pub fn with_database_url(mut self, url: &str) -> Self {
		self.database.url = url.to_string();
		self
	}

	/// Create a new configuration with the given output directory.
	pub fn with_output_dir(mut self, dir: impl Into<PathBuf>) -> Self {
		self.output.directory = dir.into();
		self
	}

	/// Create a new configuration with the given app label.
	pub fn with_app_label(mut self, label: &str) -> Self {
		self.generation.app_label = label.to_string();
		self
	}

	/// Load configuration from a TOML file.
	///
	/// # Errors
	///
	/// Returns error if file cannot be read or parsed.
	pub fn from_file(path: impl AsRef<Path>) -> Result<Self, ConfigError> {
		let content = std::fs::read_to_string(path.as_ref()).map_err(|e| ConfigError::IoError {
			path: path.as_ref().to_path_buf(),
			source: e,
		})?;

		Self::from_toml(&content)
	}

	/// Parse configuration from TOML string.
	pub fn from_toml(content: &str) -> Result<Self, ConfigError> {
		toml::from_str(content).map_err(|e| ConfigError::ParseError {
			message: e.to_string(),
		})
	}

	/// Check if a table should be included based on filter configuration.
	pub fn should_include_table(&self, table_name: &str) -> bool {
		// Check exclude patterns first
		for pattern in &self.tables.exclude {
			if let Ok(re) = Regex::new(pattern)
				&& re.is_match(table_name)
			{
				return false;
			}
		}

		// Check include patterns
		if self.tables.include.is_empty() {
			return true;
		}

		for pattern in &self.tables.include {
			if let Ok(re) = Regex::new(pattern)
				&& re.is_match(table_name)
			{
				return true;
			}
		}

		false
	}

	/// Get type override for a specific table.column.
	pub fn get_type_override(&self, table: &str, column: &str) -> Option<&str> {
		let key = format!("{}.{}", table, column);
		self.type_overrides.get(&key).map(|s| s.as_str())
	}

	/// Merge CLI arguments into configuration.
	///
	/// CLI arguments take precedence over config file values.
	pub fn merge_cli_args(&mut self, args: &CliArgs) {
		if let Some(ref url) = args.database_url {
			self.database.url = url.clone();
		}

		if let Some(ref dir) = args.output_dir {
			self.output.directory = dir.clone();
		}

		if let Some(ref label) = args.app_label {
			self.generation.app_label = label.clone();
		}

		if let Some(ref pattern) = args.include_tables {
			self.tables.include = vec![pattern.clone()];
		}

		if let Some(ref pattern) = args.exclude_tables {
			self.tables.exclude.push(pattern.clone());
		}
	}
}

/// Database connection configuration.
#[non_exhaustive]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
#[derive(Default)]
pub struct DatabaseConfig {
	/// Database connection URL
	///
	/// Can include environment variable reference: "${DATABASE_URL}"
	pub url: String,
}

impl DatabaseConfig {
	/// Resolve the database URL, expanding environment variables.
	pub fn resolve_url(&self) -> Result<String, ConfigError> {
		if self.url.starts_with("${") && self.url.ends_with('}') {
			let var_name = &self.url[2..self.url.len() - 1];
			std::env::var(var_name).map_err(|_| ConfigError::EnvVarNotFound {
				name: var_name.to_string(),
			})
		} else if self.url.is_empty() {
			// Try DATABASE_URL environment variable as fallback
			std::env::var("DATABASE_URL").map_err(|_| ConfigError::MissingDatabaseUrl)
		} else {
			Ok(self.url.clone())
		}
	}
}

/// Output configuration.
#[non_exhaustive]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct OutputConfig {
	/// Output directory for generated files
	pub directory: PathBuf,

	/// Generate all models in a single file
	#[serde(default)]
	pub single_file: bool,

	/// File name when single_file is true
	#[serde(default = "default_single_file_name")]
	pub single_file_name: String,
}

fn default_single_file_name() -> String {
	"models.rs".to_string()
}

impl Default for OutputConfig {
	fn default() -> Self {
		Self {
			directory: PathBuf::from("src/models/generated"),
			single_file: false,
			single_file_name: default_single_file_name(),
		}
	}
}

/// Code generation configuration.
#[non_exhaustive]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct GenerationConfig {
	/// App label for generated models
	pub app_label: String,

	/// Detect relationships from foreign keys
	#[serde(default = "default_true")]
	pub detect_relationships: bool,

	/// Derive macros to add to generated structs
	#[serde(default = "default_derives")]
	pub derives: Vec<String>,

	/// Include column comments as doc comments
	#[serde(default = "default_true")]
	pub include_column_comments: bool,

	/// Naming convention for struct names
	#[serde(default)]
	pub struct_naming: NamingConventionConfig,

	/// Naming convention for field names
	#[serde(default)]
	pub field_naming: NamingConventionConfig,
}

fn default_true() -> bool {
	true
}

fn default_derives() -> Vec<String> {
	vec![
		"Debug".to_string(),
		"Clone".to_string(),
		"Serialize".to_string(),
		"Deserialize".to_string(),
	]
}

impl Default for GenerationConfig {
	fn default() -> Self {
		Self {
			app_label: "app".to_string(),
			detect_relationships: true,
			derives: default_derives(),
			include_column_comments: true,
			struct_naming: NamingConventionConfig::default(),
			// Rust struct fields should use snake_case by convention
			field_naming: NamingConventionConfig::SnakeCase,
		}
	}
}

impl GenerationConfig {
	/// Get the naming convention for struct names.
	pub fn struct_naming_convention(&self) -> NamingConvention {
		self.struct_naming.to_convention()
	}

	/// Get the naming convention for field names.
	pub fn field_naming_convention(&self) -> NamingConvention {
		self.field_naming.to_convention()
	}
}

/// Naming convention configuration (for serde).
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum NamingConventionConfig {
	#[default]
	PascalCase,
	SnakeCase,
	Preserve,
}

impl NamingConventionConfig {
	/// Convert to NamingConvention enum.
	pub fn to_convention(&self) -> NamingConvention {
		match self {
			NamingConventionConfig::PascalCase => NamingConvention::PascalCase,
			NamingConventionConfig::SnakeCase => NamingConvention::SnakeCase,
			NamingConventionConfig::Preserve => NamingConvention::Preserve,
		}
	}
}

/// Table filtering configuration.
#[non_exhaustive]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct TableFilterConfig {
	/// Include tables matching these patterns (regex)
	pub include: Vec<String>,

	/// Exclude tables matching these patterns (regex)
	pub exclude: Vec<String>,
}

impl Default for TableFilterConfig {
	fn default() -> Self {
		Self {
			include: vec![".*".to_string()],
			exclude: vec![
				"^pg_".to_string(),
				"^reinhardt_migrations".to_string(),
				"^django_".to_string(),
				"^auth_".to_string(),
			],
		}
	}
}

/// Additional imports configuration.
#[non_exhaustive]
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct ImportsConfig {
	/// Additional use statements to include
	pub additional: Vec<String>,
}

/// CLI arguments that can override config file values.
#[non_exhaustive]
#[derive(Debug, Clone, Default)]
pub struct CliArgs {
	/// The database url.
	pub database_url: Option<String>,
	/// The output dir.
	pub output_dir: Option<PathBuf>,
	/// The app label.
	pub app_label: Option<String>,
	/// The include tables.
	pub include_tables: Option<String>,
	/// The exclude tables.
	pub exclude_tables: Option<String>,
	/// The config file.
	pub config_file: Option<PathBuf>,
	/// The dry run.
	pub dry_run: bool,
	/// The force.
	pub force: bool,
	/// The verbose.
	pub verbose: bool,
}

/// Configuration errors.
#[non_exhaustive]
#[derive(Debug, thiserror::Error)]
pub enum ConfigError {
	#[error("IO error reading {path}: {source}")]
	IoError {
		path: PathBuf,
		#[source]
		source: std::io::Error,
	},

	#[error("Failed to parse configuration: {message}")]
	ParseError { message: String },

	#[error("Environment variable not found: {name}")]
	EnvVarNotFound { name: String },

	#[error(
		"Database URL not specified. Set DATABASE_URL environment variable or use --database option"
	)]
	MissingDatabaseUrl,

	#[error("Invalid regex pattern: {pattern}")]
	InvalidPattern { pattern: String },
}

#[cfg(test)]
mod tests {
	use super::*;

	#[test]
	fn test_default_config() {
		let config = IntrospectConfig::default();

		assert_eq!(
			config.output.directory,
			PathBuf::from("src/models/generated")
		);
		assert!(config.generation.detect_relationships);
		assert!(!config.output.single_file);
	}

	#[test]
	fn test_parse_toml_config() {
		let toml = r#"
[database]
url = "postgres://localhost/test"

[output]
directory = "src/generated"

[generation]
app_label = "myapp"
detect_relationships = true

[tables]
include = ["users", "posts"]
exclude = ["^pg_"]

[type_overrides]
"users.status" = "UserStatus"
"#;

		let config = IntrospectConfig::from_toml(toml).unwrap();

		assert_eq!(config.database.url, "postgres://localhost/test");
		assert_eq!(config.output.directory, PathBuf::from("src/generated"));
		assert_eq!(config.generation.app_label, "myapp");
		assert_eq!(config.tables.include, vec!["users", "posts"]);
		assert_eq!(
			config.type_overrides.get("users.status"),
			Some(&"UserStatus".to_string())
		);
	}

	#[test]
	fn test_table_filtering() {
		let config = IntrospectConfig {
			tables: TableFilterConfig {
				include: vec!["users".to_string(), "posts".to_string()],
				exclude: vec!["^pg_".to_string()],
			},
			..Default::default()
		};

		assert!(config.should_include_table("users"));
		assert!(config.should_include_table("posts"));
		assert!(!config.should_include_table("comments"));
		assert!(!config.should_include_table("pg_tables"));
	}

	#[test]
	fn test_cli_args_merge() {
		let mut config = IntrospectConfig::default();
		let args = CliArgs {
			database_url: Some("postgres://cli/db".to_string()),
			app_label: Some("cli_app".to_string()),
			..Default::default()
		};

		config.merge_cli_args(&args);

		assert_eq!(config.database.url, "postgres://cli/db");
		assert_eq!(config.generation.app_label, "cli_app");
	}

	#[test]
	fn test_builder_pattern() {
		let config = IntrospectConfig::default()
			.with_database_url("postgres://localhost/test")
			.with_output_dir("./output")
			.with_app_label("test_app");

		assert_eq!(config.database.url, "postgres://localhost/test");
		assert_eq!(config.output.directory, PathBuf::from("./output"));
		assert_eq!(config.generation.app_label, "test_app");
	}
}