axum_sql_viewer/api/
tables.rs

1//! Table listing and schema endpoints
2
3use axum::{
4    extract::{Path, State},
5    http::StatusCode,
6    response::{IntoResponse, Json, Response},
7};
8use std::sync::Arc;
9
10use crate::database::traits::DatabaseProvider;
11use crate::schema::TablesResponse;
12
13/// Handler for GET /api/tables
14///
15/// Returns a list of all tables in the database with row counts.
16///
17/// # Arguments
18///
19/// * `database` - Database provider from state
20///
21/// # Returns
22///
23/// JSON response containing list of tables
24pub async fn list_tables_handler<DB: DatabaseProvider>(
25    State(database): State<Arc<DB>>,
26) -> Response {
27    match database.list_tables().await {
28        Ok(tables) => (StatusCode::OK, Json(TablesResponse { tables })).into_response(),
29        Err(error) => {
30            eprintln!("Failed to list tables: {}", error);
31            (
32                StatusCode::INTERNAL_SERVER_ERROR,
33                Json(serde_json::json!({
34                    "error": error.to_string()
35                })),
36            )
37                .into_response()
38        }
39    }
40}
41
42/// Handler for GET /api/tables/:name
43///
44/// Returns the schema information for a specific table including columns,
45/// primary keys, foreign keys, and indexes.
46///
47/// # Arguments
48///
49/// * `database` - Database provider from state
50/// * `table_name` - Name of the table to get schema for
51///
52/// # Returns
53///
54/// JSON response containing table schema information
55pub async fn get_table_schema_handler<DB: DatabaseProvider>(
56    State(database): State<Arc<DB>>,
57    Path(table_name): Path<String>,
58) -> Response {
59    match database.get_table_schema(&table_name).await {
60        Ok(schema) => (StatusCode::OK, Json(schema)).into_response(),
61        Err(error) => {
62            eprintln!("Failed to get schema for table '{}': {}", table_name, error);
63
64            // Return appropriate status code based on error type
65            let status = if error.to_string().contains("not found") {
66                StatusCode::NOT_FOUND
67            } else {
68                StatusCode::INTERNAL_SERVER_ERROR
69            };
70
71            (
72                status,
73                Json(serde_json::json!({
74                    "error": error.to_string()
75                })),
76            )
77                .into_response()
78        }
79    }
80}