Schema Builder

The schema builder provides a programmatic way to create and alter tables. Use database/schema instead of raw SQL for readable, database-agnostic migrations.

Overview

The schema package exposes:

  • schema.New(db) — Create a schema instance
  • CreateTable(name, fn) — Define a new table with a callback
  • DropTable(name) — Remove a table
  • AlterTable(name, fn) — Add columns to an existing table

CreateTable

import "github.com/CodeSyncr/nimbus/database/schema"

err := schema.New(db).CreateTable("posts", func(t *schema.Table) {
    t.Increments("id")
    t.String("title", 255)
    t.Text("content")
    t.String("status", 50).Default("'draft'")
    t.Timestamps()
    t.SoftDeletes()
})

DropTable

schema.New(db).DropTable("posts")

AlterTable

Add columns to an existing table:

schema.New(db).AlterTable("posts", func(t *schema.Table) {
    t.String("slug", 255)
    t.Integer("view_count")
})

In a migration

Up: func(db *gorm.DB) error {
    return schema.New(db).CreateTable("posts", func(t *schema.Table) {
        t.Increments("id")
        t.String("title", 255)
        t.Text("content")
        t.Timestamps()
    })
},
Down: func(db *gorm.DB) error {
    return schema.New(db).DropTable("posts")
}