1use sea_query::{Condition, Expr, Iden, Query, SelectStatement, SimpleExpr};
2
3pub trait SchemaProbe {
4 fn get_current_schema() -> SimpleExpr;
5
6 fn query_tables(&self) -> SelectStatement;
7
8 fn has_table<T>(&self, table: T) -> SelectStatement
9 where
10 T: AsRef<str>,
11 {
12 let mut subquery = self.query_tables();
13 subquery.cond_where(Expr::col(Schema::TableName).eq(table.as_ref()));
14 Query::select()
15 .expr_as(Expr::cust("COUNT(*) > 0"), Has::Table)
16 .from_subquery(subquery, Subquery)
17 .take()
18 }
19
20 fn has_column<T, C>(&self, table: T, column: C) -> SelectStatement
21 where
22 T: AsRef<str>,
23 C: AsRef<str>,
24 {
25 Query::select()
26 .expr_as(Expr::cust("COUNT(*) > 0"), Has::Column)
27 .from((Schema::Info, Schema::Columns))
28 .cond_where(
29 Condition::all()
30 .add(
31 Expr::expr(Self::get_current_schema())
32 .equals((Schema::Columns, Schema::TableSchema)),
33 )
34 .add(Expr::col(Schema::TableName).eq(table.as_ref()))
35 .add(Expr::col(Schema::ColumnName).eq(column.as_ref())),
36 )
37 .take()
38 }
39
40 fn has_index<T, C>(&self, table: T, index: C) -> SelectStatement
41 where
42 T: AsRef<str>,
43 C: AsRef<str>;
44}
45
46#[derive(Debug, Iden)]
47pub enum Has {
48 #[iden = "has_table"]
49 Table,
50 #[iden = "has_column"]
51 Column,
52 #[iden = "has_index"]
53 Index,
54}
55
56#[allow(clippy::enum_variant_names)]
57#[derive(Debug, Iden)]
58pub(crate) enum Schema {
59 #[iden = "information_schema"]
60 Info,
61 Columns,
62 TableName,
63 ColumnName,
64 TableSchema,
65}
66
67#[derive(Debug, Iden)]
68struct Subquery;