1use crate::Engine;
10use uqa_core::RelationIdentity;
11use uqa_execution::schema::namespaces::{
12 rename::{
13 SchemaMemberRelocation, SchemaMembers, SchemaRelation, SchemaRelationKind,
14 SchemaRenameContext, SchemaRenamePersistence, SchemaRenameRegistry,
15 },
16 SchemaRegistryWrite,
17};
18use uqa_execution::statement::context::schemas::{SchemaRenameTransactions, SchemaRenameWrite};
19use uqa_sql::{
20 ast::{
21 AlterSequence, SequenceBound, SequenceLifecycle, SequenceOwnership, SequenceRestart,
22 TypeObjectKind,
23 },
24 catalog::{security::BoundSchemaSecurity, view::StoredViewKind},
25 SQLError, SQLResult,
26};
27use uqa_storage::StorageBackendResult;
28
29impl Engine {
30 pub(crate) fn relation_schema_context(
31 &self,
32 ) -> uqa_execution::schema::relation_alteration::relocation::RelationSchemaContext<'_> {
33 uqa_execution::schema::relation_alteration::relocation::RelationSchemaContext {
34 creation: self.relation_creation_context(),
35 names: self,
36 locks: self,
37 indexes: self.index_registry_context(),
38 sequences: self.sequence_lifecycle_context(),
39 }
40 }
41 pub(crate) fn schema_rename_context(&self) -> SchemaRenameContext<'_> {
42 SchemaRenameContext {
43 tuples: self.schema_lock_context(),
44 writer: self,
45 refresh: self,
46 session: self,
47 roles: self,
48 database: self,
49 catalog: self,
50 locks: self,
51 schemas: self,
52 registry: self,
53 members: self,
54 relations: self,
55 relocation: self,
56 persistence: self,
57 changes: self,
58 }
59 }
60
61 fn prepare_catalog_index_relocation(
63 &self,
64 from: &RelationIdentity,
65 to: &RelationIdentity,
66 ) -> Result<uqa_execution::schema::indexes::relocation::PreparedIndexRelocations, SQLError>
67 {
68 uqa_execution::schema::indexes::relocation::prepare_table_indexes(
69 &self.index_registry_context(),
70 &self.relation_creation_context(),
71 self,
72 from,
73 to,
74 )
75 }
76}
77
78impl SchemaRenameTransactions for Engine {
79 fn with_rename_write(&self, operation: SchemaRenameWrite<'_>) -> Result<SQLResult, SQLError> {
80 self.with_implicit_definition_transaction(|engine| {
81 operation(&engine.schema_rename_context())
82 })
83 }
84}
85
86impl SchemaRenameRegistry for Engine {
87 fn schemas_write(&self) -> SchemaRegistryWrite<'_> {
88 Box::new(self.durable.schemas.write())
89 }
90 fn contains_graph(&self, name: &str) -> bool {
91 self.durable.graphs.read().contains_key(name)
92 }
93 fn temporary_schema_name(&self) -> String {
94 Engine::temporary_schema_name(self)
95 }
96}
97
98impl SchemaMembers for Engine {
99 fn relations(&self, schema: &str) -> StorageBackendResult<Vec<SchemaRelation>> {
100 self.synchronize_catalog_registries()?;
101 let mut relations = Vec::new();
102 for relation in self.storage.tables.read().keys() {
103 if relation.schema == schema {
104 relations.push(SchemaRelation {
105 identity: relation.clone(),
106 kind: SchemaRelationKind::Table,
107 });
108 }
109 }
110 for (relation, view) in self.durable.views.read().iter() {
111 if relation.schema == schema {
112 relations.push(SchemaRelation {
113 identity: relation.clone(),
114 kind: match view.definition.kind {
115 StoredViewKind::View => SchemaRelationKind::View,
116 StoredViewKind::Materialized => SchemaRelationKind::MaterializedView,
117 },
118 });
119 }
120 }
121 for relation in self.durable.sequences.read().keys() {
122 if relation.schema == schema {
123 relations.push(SchemaRelation {
124 identity: relation.clone(),
125 kind: SchemaRelationKind::Sequence,
126 });
127 }
128 }
129 for relation in self.durable.foreign_tables.read().keys() {
130 if relation.schema == schema {
131 relations.push(SchemaRelation {
132 identity: relation.clone(),
133 kind: SchemaRelationKind::ForeignTable,
134 });
135 }
136 }
137 Ok(relations)
138 }
139
140 fn routines(&self, schema: &str) -> Vec<String> {
141 self.durable
142 .sql_user_functions
143 .read()
144 .keys()
145 .filter(|key| {
146 RelationIdentity::from_legacy_name(key)
147 .is_ok_and(|identity| identity.schema == schema)
148 })
149 .cloned()
150 .collect()
151 }
152
153 fn types(&self, schema: &str) -> Vec<(String, TypeObjectKind)> {
154 let in_schema = |key: &String| {
155 RelationIdentity::from_legacy_name(key).is_ok_and(|identity| identity.schema == schema)
156 };
157 let mut types = Vec::new();
158 for key in self
159 .durable
160 .enums
161 .read()
162 .keys()
163 .filter(|key| in_schema(key))
164 {
165 types.push((key.clone(), TypeObjectKind::Type));
166 }
167 for key in self
168 .durable
169 .composites
170 .read()
171 .keys()
172 .filter(|key| in_schema(key))
173 {
174 types.push((key.clone(), TypeObjectKind::Type));
175 }
176 for key in self
177 .durable
178 .domains
179 .read()
180 .keys()
181 .filter(|key| in_schema(key))
182 {
183 types.push((key.clone(), TypeObjectKind::Domain));
184 }
185 types
186 }
187}
188
189impl SchemaMemberRelocation for Engine {
190 fn relocate_relation(&self, relation: &SchemaRelation, schema: &str) -> Result<(), SQLError> {
191 let from = relation.identity.qualified_name();
192 let to = RelationIdentity::new(schema, &relation.identity.name);
193 match relation.kind {
194 SchemaRelationKind::Table => {
195 let indexes = self.prepare_catalog_index_relocation(&relation.identity, &to)?;
196 let moved = self
197 .try_rename_table_inner(&from, &to.qualified_name())
198 .map_err(|error| {
199 SQLError::Internal(format!(
200 "move table `{from}` to schema `{schema}`: {error}"
201 ))
202 })?;
203 if !moved {
204 return Err(SQLError::Internal(format!(
205 "table `{from}` disappeared while its schema was renamed"
206 )));
207 }
208 indexes.publish(self)
209 }
210 SchemaRelationKind::View => uqa_execution::schema::view_alteration::relocate_view(
211 &self.view_alter_context(),
212 &relation.identity,
213 schema,
214 "view",
215 ),
216 SchemaRelationKind::MaterializedView => {
217 uqa_execution::schema::view_alteration::relocate_view(
218 &self.view_alter_context(),
219 &relation.identity,
220 schema,
221 "materialized view",
222 )
223 }
224 SchemaRelationKind::Sequence => {
225 let persistence =
226 uqa_execution::schema::sequences::dispatch::SequenceCommandCatalog::sequence_persistence(
227 self,
228 &relation.identity,
229 );
230 let alter = AlterSequence {
231 name: from.clone(),
232 if_exists: false,
233 restart: SequenceRestart::default(),
234 increment: None,
235 start: None,
236 data_type: None,
237 min_value: SequenceBound::default(),
238 max_value: SequenceBound::default(),
239 cycle: None,
240 cache_size: None,
241 ownership: SequenceOwnership::default(),
242 persistence: None,
243 role_owner: None,
244 lifecycle: SequenceLifecycle::SetSchema {
245 schema: schema.to_string(),
246 },
247 };
248 uqa_execution::schema::sequences::lifecycle::alter_sequence_lifecycle(
249 &self.sequence_lifecycle_context(),
250 &from,
251 &relation.identity,
252 persistence,
253 &alter,
254 )
255 }
256 SchemaRelationKind::ForeignTable => {
257 uqa_execution::schema::foreign_table_alteration::relocate_foreign_table(
258 &self.foreign_table_alter_context(),
259 &relation.identity,
260 schema,
261 )
262 }
263 }
264 }
265
266 fn relocate_routine(&self, registry_key: &str, schema: &str) -> Result<(), SQLError> {
267 uqa_execution::routines::rename::relocate_sql_routines(
268 &self.routine_rename_context(),
269 registry_key,
270 schema,
271 )
272 }
273
274 fn relocate_type(
275 &self,
276 name: &str,
277 kind: TypeObjectKind,
278 schema: &str,
279 ) -> Result<(), SQLError> {
280 uqa_execution::schema::types::relocate_type_object(
281 &self.type_lifecycle_context(),
282 kind,
283 name,
284 schema,
285 )
286 }
287}
288
289impl SchemaRenamePersistence for Engine {
290 fn save_schema_row(&self, name: &str, security: &BoundSchemaSecurity) -> Result<(), SQLError> {
291 if let Some(catalog) = self.storage.catalog.as_ref() {
292 catalog
293 .save_schema_row(&security.row(name).into())
294 .map_err(|error| {
295 SQLError::Internal(format!("store schema `{name}` for its rename: {error}"))
296 })?;
297 }
298 Ok(())
299 }
300
301 fn drop_schema_row(&self, name: &str) -> Result<(), SQLError> {
302 if let Some(catalog) = self.storage.catalog.as_ref() {
303 catalog.drop_schema(name).map_err(|error| {
304 SQLError::Internal(format!(
305 "remove schema row `{name}` after its rename: {error}"
306 ))
307 })?;
308 }
309 Ok(())
310 }
311}