1use crate::schema::{
2 CompositeField, CompositeType, Grant, Index, Role, StoredFunction, StoredProcedure, Table,
3 Trigger, View,
4};
5use anyhow::Result;
6use sqlx::{PgPool, Row};
7use std::collections::HashMap;
8
9pub struct DatabaseIntrospector {
11 pool: PgPool,
12}
13
14impl DatabaseIntrospector {
15 pub fn new(pool: PgPool) -> Self {
17 Self { pool }
18 }
19
20 pub async fn introspect_tables(&self) -> Result<Vec<Table>> {
22 let query = r#"
23 SELECT
24 t.table_name,
25 c.column_name,
26 c.data_type,
27 c.is_nullable = 'YES' as is_nullable,
28 c.column_default,
29 c.character_maximum_length,
30 c.numeric_precision,
31 c.numeric_scale
32 FROM information_schema.tables t
33 JOIN information_schema.columns c ON t.table_name = c.table_name
34 WHERE t.table_schema = 'public'
35 AND t.table_type = 'BASE TABLE'
36 ORDER BY t.table_name, c.ordinal_position
37 "#;
38
39 let rows = sqlx::query(query).fetch_all(&self.pool).await?;
40
41 let mut tables = Vec::new();
43 let mut current_table: Option<Table> = None;
44 let mut current_columns = Vec::new();
45
46 for row in rows {
47 let table_name: String = row.get("table_name");
48 let column_name: String = row.get("column_name");
49 let data_type: String = row.get("data_type");
50 let is_nullable: bool = row.get("is_nullable");
51 let column_default: Option<String> = row.get("column_default");
52 let max_length: Option<i32> = row.get("character_maximum_length");
53 let precision: Option<i32> = row.get("numeric_precision");
54 let scale: Option<i32> = row.get("numeric_scale");
55
56 if let Some(ref table) = current_table {
57 if table.name != table_name {
58 let mut table = table.clone();
60 for column in current_columns.drain(..) {
61 table = table.add_column(column);
62 }
63 tables.push(table);
64
65 current_table = Some(Table::new(&table_name));
67 }
68 } else {
69 current_table = Some(Table::new(&table_name));
70 }
71
72 let column_type = self.map_pg_type_to_ignis_type(
74 &data_type,
75 is_nullable,
76 max_length,
77 precision,
78 scale,
79 );
80
81 let mut column = crate::schema::Column::new(&column_name, column_type);
82 if !is_nullable {
83 column = column.not_null();
84 }
85 if let Some(default) = column_default {
86 column = column.default(default);
87 }
88
89 current_columns.push(column);
90 }
91
92 if let Some(table) = current_table {
94 let mut table = table;
95 for column in current_columns.drain(..) {
96 table = table.add_column(column);
97 }
98 tables.push(table);
99 }
100
101 let primary_keys = self.get_primary_keys().await?;
103
104 for table in &mut tables {
106 if let Some(pk) = primary_keys.get(&table.name) {
107 *table = table.clone().set_primary_key(pk);
108 }
109 }
110
111 Ok(tables)
112 }
113
114 async fn get_primary_keys(&self) -> Result<HashMap<String, String>> {
116 let query = r#"
117 SELECT
118 tc.table_name,
119 string_agg(kcu.column_name, ', ' ORDER BY kcu.ordinal_position) as primary_key_columns
120 FROM information_schema.table_constraints tc
121 JOIN information_schema.key_column_usage kcu
122 ON tc.constraint_name = kcu.constraint_name
123 AND tc.table_schema = kcu.table_schema
124 WHERE tc.constraint_type = 'PRIMARY KEY'
125 AND tc.table_schema = 'public'
126 GROUP BY tc.table_name
127 "#;
128
129 let rows = sqlx::query(query).fetch_all(&self.pool).await?;
130 let mut primary_keys = HashMap::new();
131
132 for row in rows {
133 let table_name: String = row.get("table_name");
134 let pk_columns: String = row.get("primary_key_columns");
135 primary_keys.insert(table_name, pk_columns);
136 }
137
138 Ok(primary_keys)
139 }
140
141 pub async fn introspect_tables_old(&self) -> Result<Vec<Table>> {
143 let query = r#"
144 SELECT
145 t.table_name,
146 c.column_name,
147 c.data_type,
148 c.is_nullable = 'YES' as is_nullable,
149 c.column_default,
150 c.character_maximum_length,
151 c.numeric_precision,
152 c.numeric_scale
153 FROM information_schema.tables t
154 JOIN information_schema.columns c ON t.table_name = c.table_name
155 WHERE t.table_schema = 'public'
156 AND t.table_type = 'BASE TABLE'
157 ORDER BY t.table_name, c.ordinal_position
158 "#;
159
160 let rows = sqlx::query(query).fetch_all(&self.pool).await?;
161
162 let mut tables = Vec::new();
164 let mut current_table: Option<Table> = None;
165 let mut current_columns = Vec::new();
166
167 for row in rows {
168 let table_name: String = row.get("table_name");
169 let column_name: String = row.get("column_name");
170 let data_type: String = row.get("data_type");
171 let is_nullable: bool = row.get("is_nullable");
172 let column_default: Option<String> = row.get("column_default");
173 let max_length: Option<i32> = row.get("character_maximum_length");
174 let precision: Option<i32> = row.get("numeric_precision");
175 let scale: Option<i32> = row.get("numeric_scale");
176
177 if let Some(ref table) = current_table {
178 if table.name != table_name {
179 let mut table = table.clone();
181 for column in current_columns.drain(..) {
182 table = table.add_column(column);
183 }
184 tables.push(table);
185
186 current_table = Some(Table::new(&table_name));
188 }
189 } else {
190 current_table = Some(Table::new(&table_name));
191 }
192
193 let column_type = self.map_pg_type_to_ignis_type(
195 &data_type,
196 is_nullable,
197 max_length,
198 precision,
199 scale,
200 );
201
202 let mut column = crate::schema::Column::new(&column_name, column_type);
203 if !is_nullable {
204 column = column.not_null();
205 }
206 if let Some(default) = column_default {
207 column = column.default(default);
208 }
209
210 current_columns.push(column);
211 }
212
213 if let Some(table) = current_table {
215 let mut table = table;
216 for column in current_columns {
217 table = table.add_column(column);
218 }
219 tables.push(table);
220 }
221
222 Ok(tables)
223 }
224
225 pub async fn introspect_views(&self) -> Result<Vec<View>> {
227 let mut views = Vec::new();
228
229 let regular_views_query = r#"
231 SELECT
232 viewname as name,
233 definition
234 FROM pg_views
235 WHERE schemaname = 'public'
236 ORDER BY viewname
237 "#;
238
239 let regular_rows = sqlx::query(regular_views_query)
240 .fetch_all(&self.pool)
241 .await?;
242 for row in regular_rows {
243 let name: String = row.get("name");
244 let definition: String = row.get("definition");
245
246 let mut view = crate::schema::View::new(&name);
247 view.set_ddl(&definition);
248 view.set_materialized(false);
249 views.push(view);
250 }
251
252 let materialized_views_query = r#"
254 SELECT
255 matviewname as name,
256 definition
257 FROM pg_matviews
258 WHERE schemaname = 'public'
259 ORDER BY matviewname
260 "#;
261
262 let materialized_rows = sqlx::query(materialized_views_query)
263 .fetch_all(&self.pool)
264 .await?;
265 for row in materialized_rows {
266 let name: String = row.get("name");
267 let definition: String = row.get("definition");
268
269 let mut view = crate::schema::View::new(&name);
270 view.set_ddl(&definition);
271 view.set_materialized(true);
272 views.push(view);
273 }
274
275 Ok(views)
276 }
277
278 pub async fn introspect_indexes(&self) -> Result<Vec<Index>> {
280 let query = r#"
281 SELECT
282 indexname as name,
283 tablename as table_name,
284 indexdef as definition
285 FROM pg_indexes
286 WHERE schemaname = 'public'
287 ORDER BY indexname
288 "#;
289
290 let rows = sqlx::query(query).fetch_all(&self.pool).await?;
291 let mut indexes = Vec::new();
292
293 for row in rows {
294 let name: String = row.get("name");
295 let table_name: String = row.get("table_name");
296 let definition: String = row.get("definition");
297
298 let is_unique = definition.contains("UNIQUE");
300 let columns = vec![table_name]; let index = crate::schema::Index::new(&name, columns, is_unique);
303
304 indexes.push(index);
305 }
306
307 Ok(indexes)
308 }
309
310 pub async fn introspect_composite_types(&self) -> Result<Vec<CompositeType>> {
312 let query = r#"
313 SELECT
314 t.typname as name,
315 a.attname as field_name,
316 pg_catalog.format_type(a.atttypid, a.atttypmod) as field_type,
317 a.attnotnull as is_not_null
318 FROM pg_type t
319 JOIN pg_class c ON c.oid = t.typrelid
320 JOIN pg_attribute a ON a.attrelid = c.oid
321 WHERE t.typtype = 'c'
322 AND c.relkind = 'c'
323 AND a.attnum > 0
324 AND a.attisdropped = false
325 ORDER BY t.typname, a.attnum
326 "#;
327
328 let rows = sqlx::query(query).fetch_all(&self.pool).await?;
329 let mut composite_types = Vec::new();
330 let mut current_type: Option<CompositeType> = None;
331 let mut current_fields: Vec<CompositeField> = Vec::new();
332
333 for row in rows {
334 let type_name: String = row.get("name");
335 let field_name: String = row.get("field_name");
336 let field_type: String = row.get("field_type");
337 let is_not_null: bool = row.get("is_not_null");
338
339 if let Some(ref composite_type) = current_type {
340 if composite_type.name != type_name {
341 let mut composite_type = composite_type.clone();
343 for field in current_fields.drain(..) {
344 composite_type =
345 composite_type.with_field(field.name, field.field_type, field.nullable);
346 }
347 composite_types.push(composite_type);
348
349 current_type = Some(CompositeType::new(&type_name));
351 }
352 } else {
353 current_type = Some(CompositeType::new(&type_name));
354 }
355
356 let field = crate::schema::CompositeField {
358 name: field_name,
359 field_type,
360 nullable: !is_not_null,
361 };
362
363 current_fields.push(field);
364 }
365
366 if let Some(composite_type) = current_type {
368 let mut composite_type = composite_type;
369 for field in current_fields {
370 composite_type =
371 composite_type.with_field(field.name, field.field_type, field.nullable);
372 }
373 composite_types.push(composite_type);
374 }
375
376 Ok(composite_types)
377 }
378
379 pub async fn introspect_functions(&self) -> Result<Vec<StoredFunction>> {
381 let query = r#"
382 SELECT
383 p.proname as name,
384 n.nspname as schema_name,
385 pg_get_function_arguments(p.oid) as parameters,
386 pg_get_function_result(p.oid) as return_type,
387 l.lanname as language,
388 p.prosrc as body,
389 CASE p.provolatile
390 WHEN 'i' THEN 'IMMUTABLE'
391 WHEN 's' THEN 'STABLE'
392 WHEN 'v' THEN 'VOLATILE'
393 END as volatility,
394 CASE p.prosecdef
395 WHEN true THEN 'DEFINER'
396 WHEN false THEN 'INVOKER'
397 END as security,
398 p.proisstrict as is_strict
399 FROM pg_proc p
400 JOIN pg_namespace n ON p.pronamespace = n.oid
401 JOIN pg_language l ON p.prolang = l.oid
402 WHERE n.nspname = 'public'
403 AND p.prokind = 'f'
404 ORDER BY p.proname
405 "#;
406
407 let rows = sqlx::query(query).fetch_all(&self.pool).await?;
408 let mut functions = Vec::new();
409
410 for row in rows {
411 let name: String = row.get("name");
412 let schema_name: Option<String> = row.get("schema_name");
413 let parameters_str: String = row.get("parameters");
414 let return_type: Option<String> = row.get("return_type");
415 let language: String = row.get("language");
416 let body: String = row.get("body");
417 let volatility: String = row.get("volatility");
418 let security: String = row.get("security");
419 let is_strict: bool = row.get("is_strict");
420
421 let function = StoredFunction {
422 name,
423 schema: schema_name,
424 parameters: self.parse_function_parameters(¶meters_str),
425 return_type,
426 language: self.map_language(&language),
427 body,
428 volatility: self.map_volatility(&volatility),
429 security: self.map_security(&security),
430 strict: is_strict,
431 };
432
433 functions.push(function);
434 }
435
436 Ok(functions)
437 }
438
439 pub async fn introspect_procedures(&self) -> Result<Vec<StoredProcedure>> {
441 let query = r#"
442 SELECT
443 p.proname as name,
444 n.nspname as schema_name,
445 pg_get_function_arguments(p.oid) as parameters,
446 l.lanname as language,
447 p.prosrc as body,
448 CASE p.prosecdef
449 WHEN true THEN 'DEFINER'
450 WHEN false THEN 'INVOKER'
451 END as security
452 FROM pg_proc p
453 JOIN pg_namespace n ON p.pronamespace = n.oid
454 JOIN pg_language l ON p.prolang = l.oid
455 WHERE n.nspname = 'public'
456 AND p.prokind = 'p'
457 ORDER BY p.proname
458 "#;
459
460 let rows = sqlx::query(query).fetch_all(&self.pool).await?;
461 let mut procedures = Vec::new();
462
463 for row in rows {
464 let name: String = row.get("name");
465 let schema_name: Option<String> = row.get("schema_name");
466 let parameters_str: String = row.get("parameters");
467 let language: String = row.get("language");
468 let body: String = row.get("body");
469 let security: String = row.get("security");
470
471 let procedure = StoredProcedure {
472 name,
473 schema: schema_name,
474 parameters: self.parse_function_parameters(¶meters_str),
475 language: self.map_language(&language),
476 body,
477 security: self.map_security(&security),
478 };
479
480 procedures.push(procedure);
481 }
482
483 Ok(procedures)
484 }
485
486 pub async fn introspect_triggers(&self) -> Result<Vec<Trigger>> {
488 let query = r#"
489 SELECT
490 t.tgname as name,
491 n.nspname as schema_name,
492 c.relname as table_name,
493 tn.nspname as table_schema,
494 CASE t.tgtype::int & 66
495 WHEN 2 THEN 'BEFORE'
496 WHEN 64 THEN 'AFTER'
497 ELSE 'INSTEAD OF'
498 END as timing,
499 CASE
500 WHEN t.tgtype::int & 4 != 0 THEN 'INSERT'
501 WHEN t.tgtype::int & 8 != 0 THEN 'DELETE'
502 WHEN t.tgtype::int & 16 != 0 THEN 'UPDATE'
503 ELSE 'OTHER'
504 END as event,
505 CASE t.tgtype::int & 1
506 WHEN 0 THEN 'STATEMENT'
507 WHEN 1 THEN 'ROW'
508 END as orientation,
509 p.proname as function_name,
510 fn.nspname as function_schema,
511 pg_get_triggerdef(t.oid) as condition
512 FROM pg_trigger t
513 JOIN pg_class c ON t.tgrelid = c.oid
514 JOIN pg_namespace n ON c.relnamespace = n.oid
515 LEFT JOIN pg_namespace tn ON c.relnamespace = tn.oid
516 JOIN pg_proc p ON t.tgfoid = p.oid
517 LEFT JOIN pg_namespace fn ON p.pronamespace = fn.oid
518 WHERE n.nspname = 'public'
519 AND NOT t.tgisinternal
520 ORDER BY t.tgname
521 "#;
522
523 let rows = sqlx::query(query).fetch_all(&self.pool).await?;
524 let mut triggers = Vec::new();
525
526 for row in rows {
527 let name: String = row.get("name");
528 let schema_name: Option<String> = row.get("schema_name");
529 let table_name: String = row.get("table_name");
530 let table_schema: Option<String> = row.get("table_schema");
531 let timing: String = row.get("timing");
532 let event: String = row.get("event");
533 let orientation: String = row.get("orientation");
534 let function_name: String = row.get("function_name");
535 let function_schema: Option<String> = row.get("function_schema");
536 let condition: Option<String> = row.get("condition");
537
538 let trigger = Trigger {
539 name,
540 schema: schema_name,
541 table_name,
542 table_schema,
543 timing: self.map_trigger_timing(&timing),
544 events: vec![self.map_trigger_event(&event)],
545 orientation: self.map_trigger_orientation(&orientation),
546 function_name,
547 function_schema,
548 condition,
549 update_columns: None, referencing: None, };
552
553 triggers.push(trigger);
554 }
555
556 Ok(triggers)
557 }
558
559 pub async fn introspect_permissions(&self) -> Result<(Vec<Role>, Vec<Grant>)> {
561 let roles_query = r#"
563 SELECT
564 rolname as name,
565 rolcanlogin as can_login,
566 rolsuper as is_superuser,
567 rolcreatedb as can_create_db,
568 rolcreaterole as can_create_role
569 FROM pg_roles
570 WHERE rolname NOT IN ('postgres', 'pg_signal_backend')
571 ORDER BY rolname
572 "#;
573
574 let role_rows = sqlx::query(roles_query).fetch_all(&self.pool).await?;
575 let mut roles = Vec::new();
576
577 for row in role_rows {
578 let name: String = row.get("name");
579 let can_login: bool = row.get("can_login");
580 let is_superuser: bool = row.get("is_superuser");
581 let can_create_db: bool = row.get("can_create_db");
582 let can_create_role: bool = row.get("can_create_role");
583
584 let role = crate::schema::Role::new(&name)
585 .with_login(can_login)
586 .with_superuser(is_superuser)
587 .with_createdb(can_create_db)
588 .with_createrole(can_create_role);
589
590 roles.push(role);
591 }
592
593 let grants_query = r#"
595 SELECT
596 grantee,
597 table_name,
598 privilege_type,
599 is_grantable
600 FROM information_schema.role_table_grants
601 WHERE table_schema = 'public'
602 ORDER BY grantee, table_name, privilege_type
603 "#;
604
605 let grant_rows = sqlx::query(grants_query).fetch_all(&self.pool).await?;
606 let mut grants = Vec::new();
607
608 for row in grant_rows {
609 let grantee: String = row.get("grantee");
610 let table_name: String = row.get("table_name");
611 let privilege: String = row.get("privilege_type");
612 let is_grantable: String = row.get("is_grantable");
613
614 let privilege_enum = match privilege.as_str() {
615 "SELECT" => crate::schema::Privilege::Select,
616 "INSERT" => crate::schema::Privilege::Insert,
617 "UPDATE" => crate::schema::Privilege::Update,
618 "DELETE" => crate::schema::Privilege::Delete,
619 "ALL" => crate::schema::Privilege::All,
620 _ => crate::schema::Privilege::Select, };
622
623 let grant = crate::schema::Grant::new(
624 privilege_enum,
625 crate::schema::GrantTarget::Table {
626 table: table_name,
627 schema: None,
628 },
629 &grantee,
630 )
631 .with_grant_option(is_grantable == "YES");
632
633 grants.push(grant);
634 }
635
636 Ok((roles, grants))
637 }
638
639 fn parse_function_parameters(
641 &self,
642 params_str: &str,
643 ) -> Vec<crate::schema::ProcedureParameter> {
644 if params_str.is_empty() {
646 return Vec::new();
647 }
648
649 params_str
651 .split(',')
652 .map(|param| {
653 let param = param.trim();
654 let parts: Vec<&str> = param.split_whitespace().collect();
655
656 if parts.len() >= 2 {
657 crate::schema::ProcedureParameter {
658 name: parts[0].to_string(),
659 data_type: parts[1].to_string(),
660 mode: crate::schema::ParameterMode::In, default_value: None,
662 }
663 } else {
664 crate::schema::ProcedureParameter {
666 name: "param".to_string(),
667 data_type: param.to_string(),
668 mode: crate::schema::ParameterMode::In,
669 default_value: None,
670 }
671 }
672 })
673 .collect()
674 }
675
676 fn map_language(&self, lang: &str) -> crate::schema::ProcedureLanguage {
678 match lang.to_lowercase().as_str() {
679 "sql" => crate::schema::ProcedureLanguage::Sql,
680 "plpgsql" => crate::schema::ProcedureLanguage::PlPgSql,
681 "c" => crate::schema::ProcedureLanguage::C,
682 "python" | "plpython3u" | "plpythonu" => crate::schema::ProcedureLanguage::PlPython3,
683 "javascript" | "plv8" => {
684 crate::schema::ProcedureLanguage::Custom("javascript".to_string())
685 }
686 _ => crate::schema::ProcedureLanguage::Sql, }
688 }
689
690 fn map_volatility(&self, volatility: &str) -> crate::schema::FunctionVolatility {
692 match volatility.to_uppercase().as_str() {
693 "IMMUTABLE" => crate::schema::FunctionVolatility::Immutable,
694 "STABLE" => crate::schema::FunctionVolatility::Stable,
695 "VOLATILE" => crate::schema::FunctionVolatility::Volatile,
696 _ => crate::schema::FunctionVolatility::Volatile, }
698 }
699
700 fn map_security(&self, security: &str) -> crate::schema::FunctionSecurity {
702 match security.to_uppercase().as_str() {
703 "DEFINER" => crate::schema::FunctionSecurity::Definer,
704 "INVOKER" => crate::schema::FunctionSecurity::Invoker,
705 _ => crate::schema::FunctionSecurity::Invoker, }
707 }
708
709 fn map_trigger_timing(&self, timing: &str) -> crate::schema::TriggerTiming {
711 match timing.to_uppercase().as_str() {
712 "BEFORE" => crate::schema::TriggerTiming::Before,
713 "AFTER" => crate::schema::TriggerTiming::After,
714 "INSTEAD OF" => crate::schema::TriggerTiming::InsteadOf,
715 _ => crate::schema::TriggerTiming::Before, }
717 }
718
719 fn map_trigger_event(&self, event: &str) -> crate::schema::TriggerEvent {
721 match event.to_uppercase().as_str() {
722 "INSERT" => crate::schema::TriggerEvent::Insert,
723 "UPDATE" => crate::schema::TriggerEvent::Update,
724 "DELETE" => crate::schema::TriggerEvent::Delete,
725 "TRUNCATE" => crate::schema::TriggerEvent::Truncate,
726 _ => crate::schema::TriggerEvent::Insert, }
728 }
729
730 fn map_trigger_orientation(&self, orientation: &str) -> crate::schema::TriggerOrientation {
732 match orientation.to_uppercase().as_str() {
733 "ROW" => crate::schema::TriggerOrientation::Row,
734 "STATEMENT" => crate::schema::TriggerOrientation::Statement,
735 _ => crate::schema::TriggerOrientation::Row, }
737 }
738
739 fn map_pg_type_to_ignis_type(
741 &self,
742 pg_type: &str,
743 _is_nullable: bool,
744 max_length: Option<i32>,
745 precision: Option<i32>,
746 scale: Option<i32>,
747 ) -> crate::schema::ColumnType {
748 match pg_type.to_lowercase().as_str() {
749 "integer" | "int" | "int4" => crate::schema::ColumnType::Int4,
750 "bigint" | "int8" => crate::schema::ColumnType::Int8,
751 "smallint" | "int2" => crate::schema::ColumnType::Int2,
752 "text" => crate::schema::ColumnType::Text,
753 "varchar" | "character varying" => {
754 if let Some(length) = max_length {
755 crate::schema::ColumnType::Varchar(Some(length as usize))
756 } else {
757 crate::schema::ColumnType::Varchar(None)
758 }
759 }
760 "char" | "character" => crate::schema::ColumnType::Char,
761 "boolean" | "bool" => crate::schema::ColumnType::Bool,
762 "timestamp with time zone" | "timestamptz" => crate::schema::ColumnType::Timestamptz,
763 "timestamp without time zone" | "timestamp" => crate::schema::ColumnType::Timestamptz,
764 "date" => crate::schema::ColumnType::Date,
765 "time" => crate::schema::ColumnType::Time,
766 "uuid" => crate::schema::ColumnType::Uuid,
767 "numeric" | "decimal" => match (precision, scale) {
768 (Some(p), Some(s)) => {
769 crate::schema::ColumnType::Numeric(Some(p as usize), Some(s as usize))
770 }
771 (Some(p), None) => crate::schema::ColumnType::Numeric(Some(p as usize), None),
772 (None, Some(s)) => crate::schema::ColumnType::Numeric(None, Some(s as usize)),
773 (None, None) => crate::schema::ColumnType::Numeric(None, None),
774 },
775 "jsonb" => crate::schema::ColumnType::Jsonb,
776 "json" => crate::schema::ColumnType::Json,
777 "bytea" => crate::schema::ColumnType::Text, "real" | "float4" => crate::schema::ColumnType::Numeric(None, None), "double precision" | "float8" => crate::schema::ColumnType::Numeric(None, None), array_type if array_type.ends_with("[]") => {
782 let base_type = &array_type[..array_type.len() - 2];
783 let base_column_type =
784 self.map_pg_type_to_ignis_type(base_type, false, None, None, None);
785 crate::schema::ColumnType::Array(Box::new(base_column_type))
786 }
787 custom => crate::schema::ColumnType::Custom(custom.to_string()),
789 }
790 }
791}
792
793#[cfg(test)]
794mod tests {
795 use super::*;
796
797 #[test]
798 fn test_pg_type_mapping() {
799 let int_type = map_pg_type_to_ignis_type_direct("integer", false, None, None, None);
804 assert!(matches!(int_type, crate::schema::ColumnType::Int4));
805
806 let varchar_type =
807 map_pg_type_to_ignis_type_direct("varchar", false, Some(255), None, None);
808 assert!(matches!(
809 varchar_type,
810 crate::schema::ColumnType::Varchar(Some(255))
811 ));
812
813 let array_type = map_pg_type_to_ignis_type_direct("integer[]", false, None, None, None);
814 assert!(matches!(array_type, crate::schema::ColumnType::Array(_)));
815 }
816
817 fn map_pg_type_to_ignis_type_direct(
819 pg_type: &str,
820 is_nullable: bool,
821 max_length: Option<i32>,
822 precision: Option<i32>,
823 scale: Option<i32>,
824 ) -> crate::schema::ColumnType {
825 match pg_type.to_lowercase().as_str() {
826 "integer" | "int" | "int4" => crate::schema::ColumnType::Int4,
827 "bigint" | "int8" => crate::schema::ColumnType::Int8,
828 "smallint" | "int2" => crate::schema::ColumnType::Int2,
829 "text" => crate::schema::ColumnType::Text,
830 "varchar" | "character varying" => {
831 if let Some(length) = max_length {
832 crate::schema::ColumnType::Varchar(Some(length as usize))
833 } else {
834 crate::schema::ColumnType::Varchar(None)
835 }
836 }
837 "char" | "character" => crate::schema::ColumnType::Char,
838 "boolean" | "bool" => crate::schema::ColumnType::Bool,
839 "timestamp with time zone" | "timestamptz" => crate::schema::ColumnType::Timestamptz,
840 "timestamp without time zone" | "timestamp" => crate::schema::ColumnType::Timestamptz,
841 "date" => crate::schema::ColumnType::Date,
842 "time" => crate::schema::ColumnType::Time,
843 "uuid" => crate::schema::ColumnType::Uuid,
844 "numeric" | "decimal" => match (precision, scale) {
845 (Some(p), Some(s)) => {
846 crate::schema::ColumnType::Numeric(Some(p as usize), Some(s as usize))
847 }
848 (Some(p), None) => crate::schema::ColumnType::Numeric(Some(p as usize), None),
849 (None, Some(s)) => crate::schema::ColumnType::Numeric(None, Some(s as usize)),
850 (None, None) => crate::schema::ColumnType::Numeric(None, None),
851 },
852 "jsonb" => crate::schema::ColumnType::Jsonb,
853 "json" => crate::schema::ColumnType::Json,
854 "bytea" => crate::schema::ColumnType::Text, "real" | "float4" => crate::schema::ColumnType::Numeric(None, None), "double precision" | "float8" => crate::schema::ColumnType::Numeric(None, None), array_type if array_type.ends_with("[]") => {
859 let base_type = &array_type[..array_type.len() - 2];
860 let base_column_type =
861 map_pg_type_to_ignis_type_direct(base_type, false, None, None, None);
862 crate::schema::ColumnType::Array(Box::new(base_column_type))
863 }
864 custom => crate::schema::ColumnType::Custom(custom.to_string()),
866 }
867 }
868}