toasty_sql/stmt/
create_table.rs

1use super::{ColumnDef, Statement};
2
3use toasty_core::{
4    driver::Capability,
5    schema::db::{Table, TableId},
6    stmt,
7};
8
9/// A `CREATE TABLE` statement.
10#[derive(Debug, Clone)]
11pub struct CreateTable {
12    /// Name of the table
13    pub table: TableId,
14
15    /// Column definitions
16    pub columns: Vec<ColumnDef>,
17
18    /// Primary key clause
19    pub primary_key: Option<Box<stmt::Expr>>,
20}
21
22impl Statement {
23    /// Creates a `CREATE TABLE` statement from a schema [`Table`].
24    pub fn create_table(table: &Table, capability: &Capability) -> Self {
25        CreateTable {
26            table: table.id,
27            columns: table
28                .columns
29                .iter()
30                .map(|column| ColumnDef::from_schema(column, &capability.storage_types))
31                .collect(),
32            primary_key: Some(Box::new(stmt::Expr::record(
33                table
34                    .primary_key
35                    .columns
36                    .iter()
37                    .map(|col| stmt::Expr::column(*col)),
38            ))),
39        }
40        .into()
41    }
42}
43
44impl From<CreateTable> for Statement {
45    fn from(value: CreateTable) -> Self {
46        Self::CreateTable(value)
47    }
48}