reinhardt-db 0.1.2

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
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
/// PostgreSQL-specific schema editor
///
/// This module provides PostgreSQL-specific DDL operations, including:
/// - CONCURRENTLY index operations
/// - IDENTITY column support
/// - Sequence operations
/// - LIKE index auto-creation for varchar/text columns
///
/// # Example
///
/// ```no_run
/// use reinhardt_db::backends::drivers::postgresql::schema::PostgreSQLSchemaEditor;
/// use reinhardt_db::backends::schema::BaseDatabaseSchemaEditor;
/// use sqlx::PgPool;
///
/// # async fn example() -> Result<(), sqlx::Error> {
/// let pool = PgPool::connect("postgresql://localhost/mydb").await?;
/// let editor = PostgreSQLSchemaEditor::new(pool);
/// let sql = editor.create_index_concurrently_sql("idx_email", "users", &["email"], false, None);
/// assert!(sql.contains("CONCURRENTLY"));
/// # Ok(())
/// # }
/// ```
use crate::backends::schema::{BaseDatabaseSchemaEditor, SchemaEditorError, SchemaEditorResult};
use sqlx::PgPool;
use std::sync::Arc;

/// Quote a PostgreSQL identifier by wrapping it in double quotes
///
/// Embedded double quotes are escaped by doubling them to prevent SQL injection.
fn quote_identifier(name: &str) -> String {
	format!("\"{}\"", name.replace('"', "\"\""))
}

/// PostgreSQL-specific schema editor
pub struct PostgreSQLSchemaEditor {
	/// PostgreSQL connection pool
	pool: Arc<PgPool>,
}

impl PostgreSQLSchemaEditor {
	/// Create a new PostgreSQL schema editor from a connection pool
	///
	/// # Example
	///
	/// ```no_run
	/// use reinhardt_db::backends::drivers::postgresql::schema::PostgreSQLSchemaEditor;
	/// use sqlx::PgPool;
	///
	/// # async fn example() -> Result<(), sqlx::Error> {
	/// let pool = PgPool::connect("postgresql://localhost/mydb").await?;
	/// let editor = PostgreSQLSchemaEditor::new(pool);
	/// # Ok(())
	/// # }
	/// ```
	pub fn new(pool: PgPool) -> Self {
		Self {
			pool: Arc::new(pool),
		}
	}

	/// Create from an `Arc<PgPool>`
	///
	/// # Example
	///
	/// ```no_run
	/// use reinhardt_db::backends::drivers::postgresql::schema::PostgreSQLSchemaEditor;
	/// use sqlx::PgPool;
	/// use std::sync::Arc;
	///
	/// # async fn example() -> Result<(), sqlx::Error> {
	/// let pool = Arc::new(PgPool::connect("postgresql://localhost/mydb").await?);
	/// let editor = PostgreSQLSchemaEditor::from_pool_arc(pool);
	/// # Ok(())
	/// # }
	/// ```
	pub fn from_pool_arc(pool: Arc<PgPool>) -> Self {
		Self { pool }
	}

	/// Generate CREATE INDEX CONCURRENTLY SQL
	///
	/// This allows creating indexes without blocking writes to the table.
	///
	/// # Example
	///
	/// ```rust,no_run
	/// # use reinhardt_db::backends::drivers::postgresql::schema::PostgreSQLSchemaEditor;
	/// # use sqlx::PgPool;
	/// let pool = PgPool::connect_lazy("postgresql://localhost/test").expect("Failed to create lazy pool");
	/// let editor = PostgreSQLSchemaEditor::new(pool);
	/// let sql = editor.create_index_concurrently_sql(
	///     "idx_email",
	///     "users",
	///     &["email"],
	///     false,
	///     None
	/// );
	/// assert_eq!(sql, "CREATE INDEX CONCURRENTLY \"idx_email\" ON \"users\" (\"email\")");
	/// ```
	pub fn create_index_concurrently_sql(
		&self,
		name: &str,
		table: &str,
		columns: &[&str],
		unique: bool,
		condition: Option<&str>,
	) -> String {
		let unique_keyword = if unique { "UNIQUE " } else { "" };
		let quoted_columns: Vec<String> = columns
			.iter()
			.map(|c| quote_identifier(c).to_string())
			.collect();

		let mut sql = format!(
			"CREATE {}INDEX CONCURRENTLY {} ON {} ({})",
			unique_keyword,
			quote_identifier(name),
			quote_identifier(table),
			quoted_columns.join(", ")
		);

		if let Some(cond) = condition {
			sql.push_str(&format!(" WHERE {}", cond));
		}

		sql
	}

	/// Generate DROP INDEX CONCURRENTLY SQL
	///
	/// # Example
	///
	/// ```rust,no_run
	/// # use reinhardt_db::backends::drivers::postgresql::schema::PostgreSQLSchemaEditor;
	/// # use sqlx::PgPool;
	/// let pool = PgPool::connect_lazy("postgresql://localhost/test").expect("Failed to create lazy pool");
	/// let editor = PostgreSQLSchemaEditor::new(pool);
	/// let sql = editor.drop_index_concurrently_sql("idx_email");
	/// assert_eq!(sql, "DROP INDEX CONCURRENTLY IF EXISTS \"idx_email\"");
	/// ```
	pub fn drop_index_concurrently_sql(&self, name: &str) -> String {
		format!(
			"DROP INDEX CONCURRENTLY IF EXISTS {}",
			quote_identifier(name)
		)
	}

	/// Generate ALTER SEQUENCE SQL
	///
	/// # Example
	///
	/// ```rust,no_run
	/// # use reinhardt_db::backends::drivers::postgresql::schema::PostgreSQLSchemaEditor;
	/// # use sqlx::PgPool;
	/// let pool = PgPool::connect_lazy("postgresql://localhost/test").expect("Failed to create lazy pool");
	/// let editor = PostgreSQLSchemaEditor::new(pool);
	/// let sql = editor.alter_sequence_type_sql("users_id_seq", "BIGINT");
	/// assert_eq!(sql, "ALTER SEQUENCE IF EXISTS \"users_id_seq\" AS BIGINT");
	/// ```
	pub fn alter_sequence_type_sql(&self, sequence: &str, seq_type: &str) -> String {
		format!(
			"ALTER SEQUENCE IF EXISTS {} AS {}",
			quote_identifier(sequence),
			seq_type
		)
	}

	/// Generate DROP SEQUENCE SQL
	///
	/// # Example
	///
	/// ```rust,no_run
	/// # use reinhardt_db::backends::drivers::postgresql::schema::PostgreSQLSchemaEditor;
	/// # use sqlx::PgPool;
	/// let pool = PgPool::connect_lazy("postgresql://localhost/test").expect("Failed to create lazy pool");
	/// let editor = PostgreSQLSchemaEditor::new(pool);
	/// let sql = editor.drop_sequence_sql("users_id_seq");
	/// assert_eq!(sql, "DROP SEQUENCE IF EXISTS \"users_id_seq\" CASCADE");
	/// ```
	pub fn drop_sequence_sql(&self, sequence: &str) -> String {
		format!(
			"DROP SEQUENCE IF EXISTS {} CASCADE",
			quote_identifier(sequence)
		)
	}

	/// Generate ADD IDENTITY SQL
	///
	/// # Example
	///
	/// ```rust,no_run
	/// # use reinhardt_db::backends::drivers::postgresql::schema::PostgreSQLSchemaEditor;
	/// # use sqlx::PgPool;
	/// let pool = PgPool::connect_lazy("postgresql://localhost/test").expect("Failed to create lazy pool");
	/// let editor = PostgreSQLSchemaEditor::new(pool);
	/// let sql = editor.add_identity_sql("users", "id");
	/// assert_eq!(sql, "ALTER TABLE \"users\" ALTER COLUMN \"id\" ADD GENERATED BY DEFAULT AS IDENTITY");
	/// ```
	pub fn add_identity_sql(&self, table: &str, column: &str) -> String {
		format!(
			"ALTER TABLE {} ALTER COLUMN {} ADD GENERATED BY DEFAULT AS IDENTITY",
			quote_identifier(table),
			quote_identifier(column)
		)
	}

	/// Generate DROP IDENTITY SQL
	///
	/// # Example
	///
	/// ```rust,no_run
	/// # use reinhardt_db::backends::drivers::postgresql::schema::PostgreSQLSchemaEditor;
	/// # use sqlx::PgPool;
	/// let pool = PgPool::connect_lazy("postgresql://localhost/test").expect("Failed to create lazy pool");
	/// let editor = PostgreSQLSchemaEditor::new(pool);
	/// let sql = editor.drop_identity_sql("users", "id");
	/// assert_eq!(sql, "ALTER TABLE \"users\" ALTER COLUMN \"id\" DROP IDENTITY IF EXISTS");
	/// ```
	pub fn drop_identity_sql(&self, table: &str, column: &str) -> String {
		format!(
			"ALTER TABLE {} ALTER COLUMN {} DROP IDENTITY IF EXISTS",
			quote_identifier(table),
			quote_identifier(column)
		)
	}

	/// Generate LIKE index SQL for varchar/text pattern matching
	///
	/// PostgreSQL requires special indexes for LIKE queries outside the C locale.
	///
	/// # Example
	///
	/// ```rust,no_run
	/// # use reinhardt_db::backends::drivers::postgresql::schema::PostgreSQLSchemaEditor;
	/// # use sqlx::PgPool;
	/// let pool = PgPool::connect_lazy("postgresql://localhost/test").expect("Failed to create lazy pool");
	/// let editor = PostgreSQLSchemaEditor::new(pool);
	/// let sql = editor.create_like_index_sql("users", "email", "varchar(255)");
	/// assert!(sql.is_some());
	/// assert!(sql.unwrap().contains("varchar_pattern_ops"));
	/// ```
	pub fn create_like_index_sql(
		&self,
		table: &str,
		column: &str,
		db_type: &str,
	) -> Option<String> {
		// Only create LIKE indexes for varchar and text types
		if db_type.starts_with("varchar") || db_type == "text" {
			// Skip array types
			if db_type.contains('[') {
				return None;
			}

			let pattern_ops = if db_type == "text" {
				"text_pattern_ops"
			} else {
				"varchar_pattern_ops"
			};

			let index_name = format!("{}_{}_like", table, column);

			Some(format!(
				"CREATE INDEX {} ON {} ({} {})",
				quote_identifier(&index_name),
				quote_identifier(table),
				quote_identifier(column),
				pattern_ops
			))
		} else {
			None
		}
	}
}

#[async_trait::async_trait]
impl BaseDatabaseSchemaEditor for PostgreSQLSchemaEditor {
	fn database_type(&self) -> crate::backends::types::DatabaseType {
		crate::backends::types::DatabaseType::Postgres
	}

	async fn execute(&mut self, sql: &str) -> SchemaEditorResult<()> {
		// Validate SQL input
		if sql.is_empty() {
			return Err(SchemaEditorError::InvalidOperation(
				"Cannot execute empty SQL".to_string(),
			));
		}

		// Execute SQL via sqlx connection pool
		sqlx::query(sql)
			.execute(self.pool.as_ref())
			.await
			.map_err(|e| SchemaEditorError::ExecutionError(e.to_string()))?;

		Ok(())
	}
}

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

	// Fixture to create a test pool for SQL generation tests
	// These tests don't actually execute SQL, they just test SQL generation
	#[fixture]
	async fn pg_pool() -> PgPool {
		// Create a dummy pool for testing SQL generation methods
		// The pool is never actually used in these tests
		PgPool::connect_lazy("postgresql://localhost/test_db").expect("Failed to create test pool")
	}

	// Helper function to create a test editor from the pool fixture
	fn create_test_editor(pool: PgPool) -> PostgreSQLSchemaEditor {
		PostgreSQLSchemaEditor::new(pool)
	}

	#[rstest]
	#[tokio::test]
	async fn test_create_index_concurrently(#[future] pg_pool: PgPool) {
		let pool = pg_pool.await;
		let editor = create_test_editor(pool);
		let sql =
			editor.create_index_concurrently_sql("idx_email", "users", &["email"], false, None);

		assert_eq!(
			sql,
			"CREATE INDEX CONCURRENTLY \"idx_email\" ON \"users\" (\"email\")"
		);
	}

	#[rstest]
	#[tokio::test]
	async fn test_create_unique_index_concurrently(#[future] pg_pool: PgPool) {
		let pool = pg_pool.await;
		let editor = create_test_editor(pool);
		let sql =
			editor.create_index_concurrently_sql("idx_email", "users", &["email"], true, None);

		assert_eq!(
			sql,
			"CREATE UNIQUE INDEX CONCURRENTLY \"idx_email\" ON \"users\" (\"email\")"
		);
	}

	#[rstest]
	#[tokio::test]
	async fn test_create_partial_index_concurrently(#[future] pg_pool: PgPool) {
		let pool = pg_pool.await;
		let editor = create_test_editor(pool);
		let sql = editor.create_index_concurrently_sql(
			"idx_active_email",
			"users",
			&["email"],
			false,
			Some("active = true"),
		);

		assert_eq!(
			sql,
			"CREATE INDEX CONCURRENTLY \"idx_active_email\" ON \"users\" (\"email\") WHERE active = true"
		);
	}

	#[rstest]
	#[tokio::test]
	async fn test_drop_index_concurrently(#[future] pg_pool: PgPool) {
		let pool = pg_pool.await;
		let editor = create_test_editor(pool);
		let sql = editor.drop_index_concurrently_sql("idx_email");

		assert_eq!(sql, "DROP INDEX CONCURRENTLY IF EXISTS \"idx_email\"");
	}

	#[rstest]
	#[tokio::test]
	async fn test_alter_sequence_type(#[future] pg_pool: PgPool) {
		let pool = pg_pool.await;
		let editor = create_test_editor(pool);
		let sql = editor.alter_sequence_type_sql("users_id_seq", "BIGINT");

		assert_eq!(sql, "ALTER SEQUENCE IF EXISTS \"users_id_seq\" AS BIGINT");
	}

	#[rstest]
	#[tokio::test]
	async fn test_drop_sequence(#[future] pg_pool: PgPool) {
		let pool = pg_pool.await;
		let editor = create_test_editor(pool);
		let sql = editor.drop_sequence_sql("users_id_seq");

		assert_eq!(sql, "DROP SEQUENCE IF EXISTS \"users_id_seq\" CASCADE");
	}

	#[rstest]
	#[tokio::test]
	async fn test_add_identity(#[future] pg_pool: PgPool) {
		let pool = pg_pool.await;
		let editor = create_test_editor(pool);
		let sql = editor.add_identity_sql("users", "id");

		assert_eq!(
			sql,
			"ALTER TABLE \"users\" ALTER COLUMN \"id\" ADD GENERATED BY DEFAULT AS IDENTITY"
		);
	}

	#[rstest]
	#[tokio::test]
	async fn test_drop_identity(#[future] pg_pool: PgPool) {
		let pool = pg_pool.await;
		let editor = create_test_editor(pool);
		let sql = editor.drop_identity_sql("users", "id");

		assert_eq!(
			sql,
			"ALTER TABLE \"users\" ALTER COLUMN \"id\" DROP IDENTITY IF EXISTS"
		);
	}

	#[rstest]
	#[tokio::test]
	async fn test_create_like_index(#[future] pg_pool: PgPool) {
		let pool = pg_pool.await;
		let editor = create_test_editor(pool);

		// varchar should create index
		let varchar_sql = editor.create_like_index_sql("users", "email", "varchar(255)");
		let sql = varchar_sql.unwrap();
		assert!(sql.contains("varchar_pattern_ops"));

		// text should create index
		let text_sql = editor.create_like_index_sql("users", "bio", "text");
		let sql = text_sql.unwrap();
		assert!(sql.contains("text_pattern_ops"));

		// integer should not create index
		let int_sql = editor.create_like_index_sql("users", "id", "integer");
		assert!(int_sql.is_none());

		// varchar array should not create index
		let array_sql = editor.create_like_index_sql("users", "tags", "varchar[100]");
		assert!(array_sql.is_none());
	}

	#[rstest]
	fn test_quote_identifier_simple() {
		// Arrange
		let name = "users";

		// Act
		let result = quote_identifier(name);

		// Assert
		assert_eq!(result, "\"users\"");
	}

	#[rstest]
	fn test_quote_identifier_escapes_double_quotes() {
		// Arrange - identifier containing double quotes (SQL injection attempt)
		let name = "table\"; DROP TABLE users; --";

		// Act
		let result = quote_identifier(name);

		// Assert - double quotes must be escaped by doubling them
		assert_eq!(result, "\"table\"\"; DROP TABLE users; --\"");
		// The injection relies on the unescaped pattern `"` closing the identifier.
		// With escaping, `""` is a literal double-quote inside the identifier, not a delimiter.
	}

	#[rstest]
	fn test_quote_identifier_with_embedded_double_quotes() {
		// Arrange
		let name = "my\"table";

		// Act
		let result = quote_identifier(name);

		// Assert
		assert_eq!(result, "\"my\"\"table\"");
	}
}