Schema
Describe tables and columns as Go values.
You describe a table with dbswitch.Table and dbswitch.Column — plain Go structs, no
struct tags. CreateTable emits CREATE TABLE IF NOT EXISTS for the configured dialect.
users := dbswitch.Table{
Name: "users",
Columns: []dbswitch.Column{
{Name: "id", Type: dbswitch.TypeUUID, PrimaryKey: true, Default: dbswitch.DefaultGenerateUUID},
{Name: "email", Type: dbswitch.TypeText, NotNull: true, Unique: true},
{Name: "active", Type: dbswitch.TypeBool, NotNull: true, Default: dbswitch.DefaultTrue},
{Name: "created_at", Type: dbswitch.TypeTimestamp, NotNull: true, Default: dbswitch.DefaultCurrentTime},
},
}Column fields
| Field | Type | Meaning |
|---|---|---|
Name | string | Column name |
Type | ColumnType | Abstract type (see below) |
PrimaryKey | bool | Mark as PRIMARY KEY |
Unique | bool | Add a UNIQUE constraint |
NotNull | bool | Add NOT NULL |
Default | DefaultValue | Column default (see below) |
Column types
Abstract ColumnType values map to each database's native type:
dbswitch type | PostgreSQL |
|---|---|
TypeUUID | UUID |
TypeText | TEXT |
TypeBool | BOOLEAN |
TypeInt | INTEGER |
TypeTimestamp | TIMESTAMPTZ |
Defaults
DefaultValue | PostgreSQL |
|---|---|
DefaultGenerateUUID | gen_random_uuid() |
DefaultCurrentTime | now() |
DefaultTrue | TRUE |
DefaultFalse | FALSE |
CreateTable is CREATE TABLE IF NOT EXISTS — not a migration system. It won't alter
existing tables, add indexes beyond column constraints, or version your schema. Use a real
migration tool for evolving schemas. See Limitations.
Column types and defaults above are SQL concepts and apply to the PostgreSQL
backend. On MongoDB and DynamoDB (both schemaless) they're ignored — only Unique
(→ unique index / conditional write) and the primary key (→ _id on Mongo, the partition
key on DynamoDB) have an effect. On DynamoDB the PrimaryKey column must additionally be
named "id", and its Type must be TypeUUID/TypeText (→ S) or TypeInt (→ N) —
DynamoDB keys can't be TypeBool or TypeTimestamp. See Backends.