larust_orm/introspect.rs
1use crate::pool::{backend, pool, Backend};
2use larust_core::AppError;
3use sqlx::Row;
4
5/// Every real table in the connected database, alphabetical - the one
6/// portable piece of schema introspection this crate needs (`sqlx::Any` has
7/// no catalog API of its own; see `larust-db`'s own `sql::introspect`
8/// module for the fuller browse/edit-oriented introspection built on top of
9/// this same query). SQLite's internal `sqlite_%` tables are excluded;
10/// MySQL/Postgres's `information_schema.tables` query is already scoped to
11/// just the connected database/schema, so nothing internal leaks through.
12///
13/// This includes `_migrations` itself - correct for [`crate::migrate::fresh`],
14/// which wants that table dropped and recreated along with everything else.
15pub async fn table_names() -> Result<Vec<String>, AppError> {
16 let pool = pool()?;
17 let sql = match backend() {
18 Backend::Sqlite => {
19 "SELECT name FROM sqlite_master WHERE type = 'table' \
20 AND name NOT LIKE 'sqlite\\_%' ESCAPE '\\' ORDER BY name"
21 }
22 Backend::MySql => {
23 "SELECT table_name FROM information_schema.tables \
24 WHERE table_schema = DATABASE() ORDER BY table_name"
25 }
26 Backend::Postgres => {
27 "SELECT table_name FROM information_schema.tables \
28 WHERE table_schema = 'public' ORDER BY table_name"
29 }
30 };
31 let rows = sqlx::query(sql)
32 .fetch_all(pool)
33 .await
34 .map_err(|e| AppError::Internal(Box::new(e)))?;
35 Ok(rows.iter().map(|row| row.get::<String, _>(0)).collect())
36}