pub struct TableCreateStatement { /* private fields */ }
Expand description

Create a table

Examples

use sea_query::{*, tests_cfg::*};

let table = Table::create()
    .table(Char::Table)
    .if_not_exists()
    .comment("table's comment")
    .col(ColumnDef::new(Char::Id).integer().not_null().auto_increment().primary_key())
    .col(ColumnDef::new(Char::FontSize).integer().not_null().comment("font's size"))
    .col(ColumnDef::new(Char::Character).string().not_null())
    .col(ColumnDef::new(Char::SizeW).integer().not_null())
    .col(ColumnDef::new(Char::SizeH).integer().not_null())
    .col(ColumnDef::new(Char::FontId).integer().default(Value::Int(None)))
    .foreign_key(
        ForeignKey::create()
            .name("FK_2e303c3a712662f1fc2a4d0aad6")
            .from(Char::Table, Char::FontId)
            .to(Font::Table, Font::Id)
            .on_delete(ForeignKeyAction::Cascade)
            .on_update(ForeignKeyAction::Cascade)
    )
    .to_owned();

assert_eq!(
    table.to_string(MysqlQueryBuilder),
    [
        r#"CREATE TABLE IF NOT EXISTS `character` ("#,
            r#"`id` int NOT NULL AUTO_INCREMENT PRIMARY KEY,"#,
            r#"`font_size` int NOT NULL COMMENT 'font\'s size',"#,
            r#"`character` varchar(255) NOT NULL,"#,
            r#"`size_w` int NOT NULL,"#,
            r#"`size_h` int NOT NULL,"#,
            r#"`font_id` int DEFAULT NULL,"#,
            r#"CONSTRAINT `FK_2e303c3a712662f1fc2a4d0aad6`"#,
                r#"FOREIGN KEY (`font_id`) REFERENCES `font` (`id`)"#,
                r#"ON DELETE CASCADE ON UPDATE CASCADE"#,
        r#") COMMENT 'table\'s comment'"#,
    ].join(" ")
);
assert_eq!(
    table.to_string(PostgresQueryBuilder),
    [
        r#"CREATE TABLE IF NOT EXISTS "character" ("#,
            r#""id" serial NOT NULL PRIMARY KEY,"#,
            r#""font_size" integer NOT NULL,"#,
            r#""character" varchar NOT NULL,"#,
            r#""size_w" integer NOT NULL,"#,
            r#""size_h" integer NOT NULL,"#,
            r#""font_id" integer DEFAULT NULL,"#,
            r#"CONSTRAINT "FK_2e303c3a712662f1fc2a4d0aad6""#,
                r#"FOREIGN KEY ("font_id") REFERENCES "font" ("id")"#,
                r#"ON DELETE CASCADE ON UPDATE CASCADE"#,
        r#")"#,
    ].join(" ")
);
assert_eq!(
    table.to_string(SqliteQueryBuilder),
    [
       r#"CREATE TABLE IF NOT EXISTS "character" ("#,
           r#""id" integer NOT NULL PRIMARY KEY AUTOINCREMENT,"#,
           r#""font_size" integer NOT NULL,"#,
           r#""character" text NOT NULL,"#,
           r#""size_w" integer NOT NULL,"#,
           r#""size_h" integer NOT NULL,"#,
           r#""font_id" integer DEFAULT NULL,"#,
           r#"FOREIGN KEY ("font_id") REFERENCES "font" ("id") ON DELETE CASCADE ON UPDATE CASCADE"#,
       r#")"#,
    ].join(" ")
);

Implementationsยง

sourceยง

impl TableCreateStatement

source

pub fn new() -> Self

Construct create table statement

source

pub fn if_not_exists(&mut self) -> &mut Self

Create table if table not exists

source

pub fn table<T>(&mut self, table: T) -> &mut Self
where T: IntoTableRef,

Set table name

source

pub fn comment<T>(&mut self, comment: T) -> &mut Self
where T: Into<String>,

Set table comment

source

pub fn col(&mut self, column: &mut ColumnDef) -> &mut Self

Add a new table column

source

pub fn check(&mut self, value: SimpleExpr) -> &mut Self

source

pub fn index(&mut self, index: &mut IndexCreateStatement) -> &mut Self

Add an index. MySQL only.

Examples
use sea_query::{tests_cfg::*, *};

assert_eq!(
    Table::create()
        .table(Glyph::Table)
        .col(ColumnDef::new(Glyph::Id).integer().not_null())
        .index(Index::create().unique().name("idx-glyph-id").col(Glyph::Id))
        .to_string(MysqlQueryBuilder),
    [
        "CREATE TABLE `glyph` (",
        "`id` int NOT NULL,",
        "UNIQUE KEY `idx-glyph-id` (`id`)",
        ")",
    ]
    .join(" ")
);
source

pub fn primary_key(&mut self, index: &mut IndexCreateStatement) -> &mut Self

Add an primary key.

Examples
use sea_query::{tests_cfg::*, *};

let mut statement = Table::create();
statement
    .table(Glyph::Table)
    .col(ColumnDef::new(Glyph::Id).integer().not_null())
    .col(ColumnDef::new(Glyph::Image).string().not_null())
    .primary_key(Index::create().col(Glyph::Id).col(Glyph::Image));
assert_eq!(
    statement.to_string(MysqlQueryBuilder),
    [
        "CREATE TABLE `glyph` (",
        "`id` int NOT NULL,",
        "`image` varchar(255) NOT NULL,",
        "PRIMARY KEY (`id`, `image`)",
        ")",
    ]
    .join(" ")
);
assert_eq!(
    statement.to_string(PostgresQueryBuilder),
    [
        "CREATE TABLE \"glyph\" (",
        "\"id\" integer NOT NULL,",
        "\"image\" varchar NOT NULL,",
        "PRIMARY KEY (\"id\", \"image\")",
        ")",
    ]
    .join(" ")
);
assert_eq!(
    statement.to_string(SqliteQueryBuilder),
    [
        r#"CREATE TABLE "glyph" ("#,
        r#""id" integer NOT NULL,"#,
        r#""image" text NOT NULL,"#,
        r#"PRIMARY KEY ("id", "image")"#,
        r#")"#,
    ]
    .join(" ")
);
source

pub fn foreign_key( &mut self, foreign_key: &mut ForeignKeyCreateStatement ) -> &mut Self

Add a foreign key

source

pub fn engine<T>(&mut self, string: T) -> &mut Self
where T: Into<String>,

Set database engine. MySQL only.

source

pub fn collate<T>(&mut self, string: T) -> &mut Self
where T: Into<String>,

Set database collate. MySQL only.

source

pub fn character_set<T>(&mut self, name: T) -> &mut Self
where T: Into<String>,

Set database character set. MySQL only.

source

pub fn get_table_name(&self) -> Option<&TableRef>

source

pub fn get_columns(&self) -> &Vec<ColumnDef>

source

pub fn get_comment(&self) -> Option<&String>

source

pub fn get_foreign_key_create_stmts(&self) -> &Vec<ForeignKeyCreateStatement>

source

pub fn get_indexes(&self) -> &Vec<IndexCreateStatement>

source

pub fn extra<T>(&mut self, extra: T) -> &mut Self
where T: Into<String>,

Rewriting extra param. You should take care self about concat extra params. Add extra after options. Example for PostgresSQL Citus extension:

use sea_query::{tests_cfg::*, *};
let table = Table::create()
    .table(Char::Table)
    .col(
        ColumnDef::new(Char::Id)
            .uuid()
            .extra("DEFAULT uuid_generate_v4()")
            .primary_key()
            .not_null(),
    )
    .col(
        ColumnDef::new(Char::CreatedAt)
            .timestamp_with_time_zone()
            .extra("DEFAULT NOW()")
            .not_null(),
    )
    .col(ColumnDef::new(Char::UserData).json_binary().not_null())
    .extra("USING columnar")
    .to_owned();
assert_eq!(
    table.to_string(PostgresQueryBuilder),
    [
        r#"CREATE TABLE "character" ("#,
        r#""id" uuid DEFAULT uuid_generate_v4() PRIMARY KEY NOT NULL,"#,
        r#""created_at" timestamp with time zone DEFAULT NOW() NOT NULL,"#,
        r#""user_data" jsonb NOT NULL"#,
        r#") USING columnar"#,
    ]
    .join(" ")
);
source

pub fn get_extra(&self) -> Option<&String>

source

pub fn take(&mut self) -> Self

sourceยง

impl TableCreateStatement

source

pub fn build<T: SchemaBuilder>(&self, schema_builder: T) -> String

source

pub fn build_any(&self, schema_builder: &dyn SchemaBuilder) -> String

source

pub fn to_string<T: SchemaBuilder>(&self, schema_builder: T) -> String

Trait Implementationsยง

sourceยง

impl Clone for TableCreateStatement

sourceยง

fn clone(&self) -> TableCreateStatement

Returns a copy of the value. Read more
1.0.0 ยท sourceยง

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
sourceยง

impl Debug for TableCreateStatement

sourceยง

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
sourceยง

impl Default for TableCreateStatement

sourceยง

fn default() -> TableCreateStatement

Returns the โ€œdefault valueโ€ for a type. Read more
sourceยง

impl SchemaStatementBuilder for TableCreateStatement

sourceยง

fn build<T: SchemaBuilder>(&self, schema_builder: T) -> String

Build corresponding SQL statement for certain database backend and return SQL string
sourceยง

fn build_any(&self, schema_builder: &dyn SchemaBuilder) -> String

Build corresponding SQL statement for certain database backend and return SQL string
sourceยง

fn to_string<T: SchemaBuilder>(&self, schema_builder: T) -> String

Build corresponding SQL statement for certain database backend and return SQL string

Auto Trait Implementationsยง

Blanket Implementationsยง

sourceยง

impl<T> Any for T
where T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for T
where T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for T
where T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

sourceยง

impl<T, U> Into<U> for T
where U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

sourceยง

impl<T> ToOwned for T
where T: Clone,

ยง

type Owned = T

The resulting type after obtaining ownership.
sourceยง

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
sourceยง

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
sourceยง

impl<T, U> TryFrom<U> for T
where U: Into<T>,

ยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

ยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.