-
Notifications
You must be signed in to change notification settings - Fork 114
Expand file tree
/
Copy pathschema_cache.rs
More file actions
108 lines (93 loc) · 2.96 KB
/
schema_cache.rs
File metadata and controls
108 lines (93 loc) · 2.96 KB
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
use sqlx::postgres::PgPool;
use crate::columns::Column;
use crate::functions::Function;
use crate::policies::Policy;
use crate::schemas::Schema;
use crate::tables::Table;
use crate::types::PostgresType;
use crate::versions::Version;
use crate::{Role, Trigger};
#[derive(Debug, Default)]
pub struct SchemaCache {
pub schemas: Vec<Schema>,
pub tables: Vec<Table>,
pub functions: Vec<Function>,
pub types: Vec<PostgresType>,
pub versions: Vec<Version>,
pub columns: Vec<Column>,
pub policies: Vec<Policy>,
pub triggers: Vec<Trigger>,
pub roles: Vec<Role>,
}
impl SchemaCache {
pub async fn load(pool: &PgPool) -> Result<SchemaCache, sqlx::Error> {
let (schemas, tables, functions, types, versions, columns, policies, triggers, roles) = futures_util::try_join!(
Schema::load(pool),
Table::load(pool),
Function::load(pool),
PostgresType::load(pool),
Version::load(pool),
Column::load(pool),
Policy::load(pool),
Trigger::load(pool),
Role::load(pool)
)?;
Ok(SchemaCache {
schemas,
tables,
functions,
types,
versions,
columns,
policies,
triggers,
roles,
})
}
/// Applies an AST node to the repository
///
/// For example, alter table add column will add the column to the table if it does not exist
/// yet
pub fn mutate(&mut self) {
unimplemented!();
}
pub fn find_table(&self, name: &str, schema: Option<&str>) -> Option<&Table> {
self.tables
.iter()
.find(|t| t.name == name && schema.is_none() || Some(t.schema.as_str()) == schema)
}
pub fn find_type(&self, name: &str, schema: Option<&str>) -> Option<&PostgresType> {
self.types
.iter()
.find(|t| t.name == name && schema.is_none() || Some(t.schema.as_str()) == schema)
}
pub fn find_col(&self, name: &str, table: &str, schema: Option<&str>) -> Option<&Column> {
self.columns.iter().find(|c| {
c.name.as_str() == name
&& c.table_name.as_str() == table
&& schema.is_none_or(|s| s == c.schema_name.as_str())
})
}
pub fn find_types(&self, name: &str, schema: Option<&str>) -> Vec<&PostgresType> {
self.types
.iter()
.filter(|t| t.name == name && schema.is_none() || Some(t.schema.as_str()) == schema)
.collect()
}
}
pub trait SchemaCacheItem {
type Item;
async fn load(pool: &PgPool) -> Result<Vec<Self::Item>, sqlx::Error>;
}
#[cfg(test)]
mod tests {
use pgt_test_utils::test_database::get_new_test_db;
use crate::SchemaCache;
#[tokio::test]
async fn it_loads() {
let test_db = get_new_test_db().await;
SchemaCache::load(&test_db)
.await
.expect("Couldnt' load Schema Cache");
}
}