vibesql_executor/
view_ddl.rs1use vibesql_ast::{CreateViewStmt, DropViewStmt};
4use vibesql_catalog::{ViewDefinition, ViewDropBehavior};
5use vibesql_storage::Database;
6
7use crate::errors::ExecutorError;
8
9pub struct ViewExecutor;
11
12impl ViewExecutor {
13 pub fn execute_create_view(
15 stmt: &CreateViewStmt,
16 database: &mut Database,
17 ) -> Result<String, ExecutorError> {
18 if stmt.or_replace {
20 let view_exists = database.catalog.get_view(&stmt.view_name).is_some();
21 if view_exists {
22 database.catalog.drop_view(&stmt.view_name, false).map_err(|e| {
24 ExecutorError::StorageError(format!("Failed to drop existing view: {:?}", e))
25 })?;
26 }
27 }
28
29 let view_def = ViewDefinition::new(
31 stmt.view_name.clone(),
32 stmt.columns.clone(),
33 *stmt.query.clone(),
34 stmt.with_check_option,
35 );
36
37 database
39 .catalog
40 .create_view(view_def)
41 .map_err(|e| ExecutorError::StorageError(format!("Failed to create view: {:?}", e)))?;
42
43 if stmt.or_replace {
44 Ok(format!("View '{}' created or replaced", stmt.view_name))
45 } else {
46 Ok(format!("View '{}' created", stmt.view_name))
47 }
48 }
49
50 pub fn execute_drop_view(
52 stmt: &DropViewStmt,
53 database: &mut Database,
54 ) -> Result<String, ExecutorError> {
55 let drop_behavior = if stmt.cascade {
60 ViewDropBehavior::Cascade
61 } else if stmt.restrict {
62 ViewDropBehavior::Restrict
63 } else {
64 ViewDropBehavior::Silent };
66
67 let result = database.catalog.drop_view_with_behavior(&stmt.view_name, drop_behavior);
69
70 match result {
71 Ok(()) => Ok(format!("View '{}' dropped", stmt.view_name)),
72 Err(e) => {
73 if stmt.if_exists
75 && matches!(e, vibesql_catalog::errors::CatalogError::ViewNotFound(_))
76 {
77 Ok(format!("View '{}' does not exist (skipped)", stmt.view_name))
78 } else {
79 Err(ExecutorError::StorageError(format!("Failed to drop view: {:?}", e)))
80 }
81 }
82 }
83 }
84}