Skip to content

Tables

The Table class in Weasel.MySql.Tables provides a fluent API for defining MySQL tables with columns, primary keys, foreign keys, indexes, and partitioning.

Defining a Table

cs
var table = new Table("users");

table.AddColumn<int>("id").AsPrimaryKey().AutoNumber();
table.AddColumn<string>("name").NotNull();
table.AddColumn<string>("email").NotNull().AddIndex(idx => idx.IsUnique = true);
table.AddColumn<DateTime>("created_at");

snippet source | anchor

Table Options

MySQL tables support engine, character set, and collation configuration:

cs
table.Engine = "InnoDB";       // default
table.Charset = "utf8mb4";
table.Collation = "utf8mb4_unicode_ci";

snippet source | anchor

Column Configuration

The AddColumn method returns a ColumnExpression with these options:

  • AsPrimaryKey() -- marks the column as part of the primary key
  • AutoNumber() -- adds AUTO_INCREMENT to the column
  • NotNull() / AllowNulls() -- controls nullability
  • DefaultValue(value) -- sets a default value
  • DefaultValueByExpression(expr) -- sets a default using a SQL expression
  • AddIndex(configure?) -- adds a standard index
  • AddFulltextIndex(configure?) -- adds a FULLTEXT index
  • AddSpatialIndex(configure?) -- adds a SPATIAL index
  • ForeignKeyTo(table, column) -- adds a foreign key constraint

Partitioning

MySQL tables support Range, Hash, List, and Key partitioning:

cs
table.PartitionByRange("created_at");
table.PartitionByHash("id");
table.PartitionByList("region");
table.PartitionByKey("id");
table.PartitionCount = 4;  // for Hash or Key strategies

snippet source | anchor

Delta Detection

cs
await using var conn = new MySqlConnection(connectionString);
await conn.OpenAsync();

var delta = await table.FindDeltaAsync(conn);

snippet source | anchor

Generating DDL

cs
var migrator = new MySqlMigrator();
var writer = new StringWriter();
table.WriteCreateStatement(migrator, writer);

snippet source | anchor

The output uses CREATE TABLE IF NOT EXISTS with backtick-quoted identifiers.

Released under the MIT License.