Skip to main content

TableCreateStatement

Struct TableCreateStatement 

Source
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 PRIMARY KEY AUTO_INCREMENT,"#,
            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" integer GENERATED BY DEFAULT AS IDENTITY 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" varchar 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<C: IntoColumnDef>(&mut self, column: C) -> &mut Self

Add a new table column

Source

pub fn check<T>(&mut self, value: T) -> &mut Self
where T: Into<Check>,

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" varchar 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 partition_by_range<I, T>(&mut self, cols: I) -> &mut Self
where I: IntoIterator<Item = T>, T: IntoIden,

Set partition by range. Postgres and MySQL only.

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

assert_eq!(
    Table::create()
        .table(Glyph::Table)
        .col(ColumnDef::new(Glyph::Id).integer().not_null())
        .partition_by_range([Glyph::Id])
        .to_string(PostgresQueryBuilder),
    r#"CREATE TABLE "glyph" ( "id" integer NOT NULL ) PARTITION BY RANGE ("id")"#
);
Source

pub fn partition_by_list<I, T>(&mut self, cols: I) -> &mut Self
where I: IntoIterator<Item = T>, T: IntoIden,

Set partition by list. Postgres and MySQL only.

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

assert_eq!(
    Table::create()
        .table(Glyph::Table)
        .col(ColumnDef::new(Glyph::Id).integer().not_null())
        .partition_by_list([Glyph::Id])
        .to_string(PostgresQueryBuilder),
    r#"CREATE TABLE "glyph" ( "id" integer NOT NULL ) PARTITION BY LIST ("id")"#
);
Source

pub fn partition_by_hash<I, T>(&mut self, cols: I) -> &mut Self
where I: IntoIterator<Item = T>, T: IntoIden,

Set partition by hash. Postgres and MySQL only.

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

assert_eq!(
    Table::create()
        .table(Glyph::Table)
        .col(ColumnDef::new(Glyph::Id).integer().not_null())
        .partition_by_hash([Glyph::Id])
        .to_string(PostgresQueryBuilder),
    r#"CREATE TABLE "glyph" ( "id" integer NOT NULL ) PARTITION BY HASH ("id")"#
);
Source

pub fn partition_by_key<I, T>(&mut self, cols: I) -> &mut Self
where I: IntoIterator<Item = T>, T: IntoIden,

Set partition by key. MySQL only.

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

assert_eq!(
    Table::create()
        .table(Glyph::Table)
        .col(ColumnDef::new(Glyph::Id).integer().not_null())
        .partition_by_key([Glyph::Id])
        .to_string(MysqlQueryBuilder),
    "CREATE TABLE `glyph` ( `id` int NOT NULL ) PARTITION BY KEY (`id`)"
);
Source

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

Set partition of table. Postgres only.

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

assert_eq!(
    Table::create()
        .table(Alias::new("glyph_1"))
        .partition_of(Glyph::Table)
        .values_from_to([1], [10])
        .to_string(PostgresQueryBuilder),
    r#"CREATE TABLE "glyph_1" PARTITION OF "glyph" FOR VALUES FROM (1) TO (10)"#
);
Source

pub fn values_in<I, T>(&mut self, values: I) -> &mut Self
where I: IntoIterator<Item = T>, T: Into<Expr>,

Set partition values IN. Postgres partition tables only.

MySQL partition definitions can use PartitionValues::In with Self::add_partition.

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

assert_eq!(
    Table::create()
        .table(Alias::new("glyph_1"))
        .partition_of(Glyph::Table)
        .values_in([1, 2, 3])
        .to_string(PostgresQueryBuilder),
    r#"CREATE TABLE "glyph_1" PARTITION OF "glyph" FOR VALUES IN (1, 2, 3)"#
);
Source

pub fn values_from_to<I, T, J, U>(&mut self, from: I, to: J) -> &mut Self
where I: IntoIterator<Item = T>, T: Into<Expr>, J: IntoIterator<Item = U>, U: Into<Expr>,

Set partition values FROM โ€ฆ TO โ€ฆ. Postgres only.

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

assert_eq!(
    Table::create()
        .table(Alias::new("glyph_1"))
        .partition_of(Glyph::Table)
        .values_from_to([1], [10])
        .to_string(PostgresQueryBuilder),
    r#"CREATE TABLE "glyph_1" PARTITION OF "glyph" FOR VALUES FROM (1) TO (10)"#
);
Source

pub fn values_less_than<I, T>(&mut self, values: I) -> &mut Self
where I: IntoIterator<Item = T>, T: Into<Expr>,

Set partition values LESS THAN. MySQL partition definitions only.

Use PartitionValues::LessThan with Self::add_partition for MySQL table partition definitions.

Source

pub fn values_with(&mut self, modulus: u32, remainder: u32) -> &mut Self

Set partition values WITH (modulus, remainder). Postgres only.

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

assert_eq!(
    Table::create()
        .table(Alias::new("glyph_p1"))
        .partition_of(Glyph::Table)
        .values_with(4, 0)
        .to_string(PostgresQueryBuilder),
    r#"CREATE TABLE "glyph_p1" PARTITION OF "glyph" FOR VALUES WITH (MODULUS 4, REMAINDER 0)"#
);
Source

pub fn add_partition<T>( &mut self, name: T, values: Option<PartitionValues>, ) -> &mut Self
where T: IntoIden,

Add a partition definition. MySQL only.

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

assert_eq!(
    Table::create()
        .table(Glyph::Table)
        .col(ColumnDef::new(Glyph::Id).integer().not_null())
        .partition_by_range([Glyph::Id])
        .add_partition(
            Alias::new("p0"),
            Some(PartitionValues::LessThan(vec![10.into()]))
        )
        .to_string(MysqlQueryBuilder),
    "CREATE TABLE `glyph` ( `id` int NOT NULL ) PARTITION BY RANGE (`id`) ( PARTITION `p0` VALUES LESS THAN (10) )"
);
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")
    .take();
assert_eq!(
    table.to_string(PostgresQueryBuilder),
    [
        r#"CREATE TABLE "character" ("#,
        r#""id" uuid NOT NULL PRIMARY KEY DEFAULT uuid_generate_v4(),"#,
        r#""created_at" timestamp with time zone NOT NULL DEFAULT NOW(),"#,
        r#""user_data" jsonb NOT NULL"#,
        r#") USING columnar"#,
    ]
    .join(" ")
);
Source

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

Source

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

Create temporary table

Ref:

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

let statement = Table::create()
    .table(Font::Table)
    .temporary()
    .col(
        ColumnDef::new(Font::Id)
            .integer()
            .not_null()
            .primary_key()
            .auto_increment(),
    )
    .col(ColumnDef::new(Font::Name).string().not_null())
    .take();

assert_eq!(
    statement.to_string(MysqlQueryBuilder),
    [
        "CREATE TEMPORARY TABLE `font` (",
        "`id` int NOT NULL PRIMARY KEY AUTO_INCREMENT,",
        "`name` varchar(255) NOT NULL",
        ")",
    ]
    .join(" ")
);
assert_eq!(
    statement.to_string(PostgresQueryBuilder),
    [
        r#"CREATE TEMPORARY TABLE "font" ("#,
        r#""id" integer GENERATED BY DEFAULT AS IDENTITY NOT NULL PRIMARY KEY,"#,
        r#""name" varchar NOT NULL"#,
        r#")"#,
    ]
    .join(" ")
);
assert_eq!(
    statement.to_string(SqliteQueryBuilder),
    [
        r#"CREATE TEMPORARY TABLE "font" ("#,
        r#""id" integer NOT NULL PRIMARY KEY AUTOINCREMENT,"#,
        r#""name" varchar NOT NULL"#,
        r#")"#,
    ]
    .join(" ")
);
Source

pub fn take(&mut self) -> Self

Sourceยง

impl TableCreateStatement

Source

pub fn build<T: SchemaBuilder>(&self, schema_builder: T) -> 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 duplicate of the value. Read more
1.0.0 (const: unstable) ยท 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 to_string<T>(&self, schema_builder: T) -> String
where T: SchemaBuilder,

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> CloneToUninit for T
where T: Clone,

Sourceยง

unsafe fn clone_to_uninit(&self, dest: *mut u8)

๐Ÿ”ฌThis is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. 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,

Sourceยง

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>,

Sourceยง

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>,

Sourceยง

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.