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 .shells
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 .enums
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 .composites
179 .read()
180 .keys()
181 .filter(|key| in_schema(key))
182 {
183 types.push((key.clone(), TypeObjectKind::Type));
184 }
185 for key in self
186 .durable
187 .domains
188 .read()
189 .keys()
190 .filter(|key| in_schema(key))
191 {
192 types.push((key.clone(), TypeObjectKind::Domain));
193 }
194 types
195 }
196}
197
198impl SchemaMemberRelocation for Engine {
199 fn relocate_relation(&self, relation: &SchemaRelation, schema: &str) -> Result<(), SQLError> {
200 let from = relation.identity.qualified_name();
201 let to = RelationIdentity::new(schema, &relation.identity.name);
202 match relation.kind {
203 SchemaRelationKind::Table => {
204 let indexes = self.prepare_catalog_index_relocation(&relation.identity, &to)?;
205 let moved = self
206 .try_rename_table_inner(&from, &to.qualified_name())
207 .map_err(|error| {
208 SQLError::Internal(format!(
209 "move table `{from}` to schema `{schema}`: {error}"
210 ))
211 })?;
212 if !moved {
213 return Err(SQLError::Internal(format!(
214 "table `{from}` disappeared while its schema was renamed"
215 )));
216 }
217 indexes.publish(self)
218 }
219 SchemaRelationKind::View => uqa_execution::schema::view_alteration::relocate_view(
220 &self.view_alter_context(),
221 &relation.identity,
222 schema,
223 "view",
224 ),
225 SchemaRelationKind::MaterializedView => {
226 uqa_execution::schema::view_alteration::relocate_view(
227 &self.view_alter_context(),
228 &relation.identity,
229 schema,
230 "materialized view",
231 )
232 }
233 SchemaRelationKind::Sequence => {
234 let persistence =
235 uqa_execution::schema::sequences::dispatch::SequenceCommandCatalog::sequence_persistence(
236 self,
237 &relation.identity,
238 );
239 let alter = AlterSequence {
240 name: from.clone(),
241 if_exists: false,
242 restart: SequenceRestart::default(),
243 increment: None,
244 start: None,
245 data_type: None,
246 min_value: SequenceBound::default(),
247 max_value: SequenceBound::default(),
248 cycle: None,
249 cache_size: None,
250 ownership: SequenceOwnership::default(),
251 persistence: None,
252 role_owner: None,
253 lifecycle: SequenceLifecycle::SetSchema {
254 schema: schema.to_string(),
255 },
256 };
257 uqa_execution::schema::sequences::lifecycle::alter_sequence_lifecycle(
258 &self.sequence_lifecycle_context(),
259 &from,
260 &relation.identity,
261 persistence,
262 &alter,
263 )
264 }
265 SchemaRelationKind::ForeignTable => {
266 uqa_execution::schema::foreign_table_alteration::relocate_foreign_table(
267 &self.foreign_table_alter_context(),
268 &relation.identity,
269 schema,
270 )
271 }
272 }
273 }
274
275 fn relocate_routine(&self, registry_key: &str, schema: &str) -> Result<(), SQLError> {
276 uqa_execution::routines::rename::relocate_sql_routines(
277 &self.routine_rename_context(),
278 registry_key,
279 schema,
280 )
281 }
282
283 fn relocate_type(
284 &self,
285 name: &str,
286 kind: TypeObjectKind,
287 schema: &str,
288 ) -> Result<(), SQLError> {
289 uqa_execution::schema::types::relocate_type_object(
290 &self.type_lifecycle_context(),
291 kind,
292 name,
293 schema,
294 )
295 }
296}
297
298impl SchemaRenamePersistence for Engine {
299 fn save_schema_row(&self, name: &str, security: &BoundSchemaSecurity) -> Result<(), SQLError> {
300 if let Some(catalog) = self.storage.catalog.as_ref() {
301 catalog
302 .save_schema_row(&security.row(name).into())
303 .map_err(|error| {
304 SQLError::Internal(format!("store schema `{name}` for its rename: {error}"))
305 })?;
306 }
307 Ok(())
308 }
309
310 fn drop_schema_row(&self, name: &str) -> Result<(), SQLError> {
311 if let Some(catalog) = self.storage.catalog.as_ref() {
312 catalog.drop_schema(name).map_err(|error| {
313 SQLError::Internal(format!(
314 "remove schema row `{name}` after its rename: {error}"
315 ))
316 })?;
317 }
318 Ok(())
319 }
320}