migrator

package module
v0.0.0-...-cb18453 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 1, 2023 License: MIT Imports: 19 Imported by: 0

README

Migrator

Migrator is a database migration tool, that automates schema migration.

It scans Schema/Model changes and generate SQL migration scripts automatically to reconcile those changes with the Database.

Table of Contents

Features

  • Supports MySQL, PostgreSQL, SQLite, SQL Server.
  • Uses plain SQL for writing schema migrations.
  • Migrations are timestamp-versioned, to avoid version number conflicts with multiple developers.
  • Migrations are run atomically inside a transaction.
  • Supports creating and dropping databases (handy in development/test).
  • Easily plugable to your existing workflows that uses GORM.

Installation

To install Gin package, you need to install Go and set your Go workspace first.

  1. You first need Go installed, then you can use the below Go command to install Migrator.
go get -u github.com/alob-mtc/migrator
  1. Import it in your code:
import "github.com/alob-mtc/migrator"

Usage

Register Model
package main

import (
	"fmt"
	migrator "github.com/alob-mtc/migrator/lib"
	"gorm.io/driver/postgres"
	"gorm.io/gorm"
	"time"
)

type User struct {
	ID        string `gorm:"primaryKey;"`
	Username  string `gorm:"index; not null"`
	Active    *bool  `gorm:"index; not null; default:false"`
	CreatedAt time.Time
	UpdatedAt time.Time
	DeletedAt gorm.DeletedAt `gorm:"index"`
}

type Product struct {
	ID        string `gorm:"primaryKey;"`
	Name      string `gorm:"index; not null"`
	CreatedAt time.Time
	DeletedAt gorm.DeletedAt `gorm:"index"`
}


func main() {
	// Connecting to postgres
	dns := "postgres://test:test@localhost:54312/test_db"
	db, err := gorm.Open(postgres.Open(dns), &gorm.Config{})
	if err != nil {
		log.Fatal(err)
	}

	// Register Model
	newMigrator := migrator.New(db, "migrations/sql/")
	newMigrator.RegisterModel(&User{}, &Product{})

}

Creating Migrations
//.....

func main() {

	//.....

	err = newMigrator.Run(db, "create", "add_username_column")
	if err != nil {
		log.Fatal(err)
	}

}

Running Migrations
//.....

func main() {

	//.....

	err = newMigrator.Run(db, "up")
	if err != nil {
		log.Fatal(err)
	}

}

Rolling Back Migrations
//.....

func main() {

	//.....

	err = newMigrator.Run(db, "down")
	if err != nil {
		log.Fatal(err)
	}

}

Internals

TODO:

Contributing

Migrator is written in Go, pull requests are welcome.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type BuildIndexOptionsInterface

type BuildIndexOptionsInterface interface {
	BuildIndexOptions([]schema.IndexOption, *gorm.Statement) []interface{}
}

BuildIndexOptionsInterface build index options interface

type ColumnType

type ColumnType struct {
	SQLColumnType      *sql.ColumnType
	NameValue          sql.NullString
	DataTypeValue      sql.NullString
	ColumnTypeValue    sql.NullString
	PrimaryKeyValue    sql.NullBool
	UniqueValue        sql.NullBool
	AutoIncrementValue sql.NullBool
	LengthValue        sql.NullInt64
	DecimalSizeValue   sql.NullInt64
	ScaleValue         sql.NullInt64
	NullableValue      sql.NullBool
	ScanTypeValue      reflect.Type
	CommentValue       sql.NullString
	DefaultValueValue  sql.NullString
}

ColumnType column type implements ColumnType interface

func (ColumnType) AutoIncrement

func (ct ColumnType) AutoIncrement() (isAutoIncrement bool, ok bool)

AutoIncrement returns the column is auto increment or not.

func (ColumnType) ColumnType

func (ct ColumnType) ColumnType() (columnType string, ok bool)

ColumnType returns the database type of the column. like `varchar(16)`

func (ColumnType) Comment

func (ct ColumnType) Comment() (value string, ok bool)

Comment returns the comment of current column.

func (ColumnType) DatabaseTypeName

func (ct ColumnType) DatabaseTypeName() string

DatabaseTypeName returns the database system name of the column type. If an empty string is returned, then the driver type name is not supported. Consult your driver documentation for a list of driver data types. Length specifiers are not included. Common type names include "VARCHAR", "TEXT", "NVARCHAR", "DECIMAL", "BOOL", "INT", and "BIGINT".

func (ColumnType) DecimalSize

func (ct ColumnType) DecimalSize() (precision int64, scale int64, ok bool)

DecimalSize returns the scale and precision of a decimal type.

func (ColumnType) DefaultValue

func (ct ColumnType) DefaultValue() (value string, ok bool)

DefaultValue returns the default value of current column.

func (ColumnType) Length

func (ct ColumnType) Length() (length int64, ok bool)

Length returns the column type length for variable length column types

func (ColumnType) Name

func (ct ColumnType) Name() string

Name returns the name or alias of the column.

func (ColumnType) Nullable

func (ct ColumnType) Nullable() (nullable bool, ok bool)

Nullable reports whether the column may be null.

func (ColumnType) PrimaryKey

func (ct ColumnType) PrimaryKey() (isPrimaryKey bool, ok bool)

PrimaryKey returns the column is primary key or not.

func (ColumnType) ScanType

func (ct ColumnType) ScanType() reflect.Type

ScanType returns a Go type suitable for scanning into using Rows.Scan.

func (ColumnType) Unique

func (ct ColumnType) Unique() (unique bool, ok bool)

Unique reports whether the column may be unique.

type Config

type Config struct {
	CreateIndexAfterCreateTable bool
	DB                          *gorm.DB
	NamingStrategy              namingStrategy
	DownMigrationsEnabled       bool
	gorm.Dialector
}

Config schema config

type GormDataTypeInterface

type GormDataTypeInterface interface {
	GormDBDataType(*gorm.DB, *schema.Field) string
}

GormDataTypeInterface gorm data type interface

type Migrator

type Migrator struct {
	Config
	Models []interface{}
	// contains filtered or unexported fields
}

Migrator m struct

func New

func New(db *gorm.DB, migrationFolder ...string) *Migrator

func (*Migrator) AddColumn

func (m *Migrator) AddColumn(value interface{}, name string) string

AddColumn create `name` column for value

func (*Migrator) AlterColumn

func (m *Migrator) AlterColumn(value interface{}, field string) string

AlterColumn alter value's `field` column' type based on schema definition

func (*Migrator) AutoMigrate

func (m *Migrator) AutoMigrate() (string, string, error)

AutoMigrate auto migrate values

func (*Migrator) BuildIndexOptions

func (m *Migrator) BuildIndexOptions(opts []schema.IndexOption, stmt *gorm.Statement) (results []interface{})

BuildIndexOptions build index options

func (*Migrator) ColumnTypes

func (m *Migrator) ColumnTypes(value interface{}) ([]ColumnType, error)

ColumnTypes return columnTypes []gorm.ColumnType and execErr error TODO: rewrite this function

func (*Migrator) CreateIndex

func (m *Migrator) CreateIndex(value interface{}, name string) (string, string)

CreateIndex create index `name`

func (*Migrator) CreateTable

func (m *Migrator) CreateTable(values ...interface{}) (string, string)

CreateTable create table in database for values

func (*Migrator) CreateView

func (m *Migrator) CreateView(name string, option gorm.ViewOption) error

CreateView create view

func (*Migrator) CurrentDatabase

func (m *Migrator) CurrentDatabase() (name string)

CurrentDatabase returns current database name

func (*Migrator) CurrentSchema

func (m *Migrator) CurrentSchema(stmt *gorm.Statement, table string) (interface{}, interface{})

func (*Migrator) CurrentTable

func (m *Migrator) CurrentTable(stmt *gorm.Statement) interface{}

CurrentTable returns current statement's table expression

func (*Migrator) DataTypeOf

func (m *Migrator) DataTypeOf(field *schema.Field) string

DataTypeOf return field's db data type

func (*Migrator) DropColumn

func (m *Migrator) DropColumn(stmt *gorm.Statement, name string) string

DropColumn drop value's `name` column

func (*Migrator) DropView

func (m *Migrator) DropView(name string) error

DropView drop view

func (*Migrator) ExcludedTable

func (m *Migrator) ExcludedTable(values []interface{}) []string

ExcludedTable returns list of excluded tables in the database.

func (*Migrator) GuessConstraintAndTable

func (m *Migrator) GuessConstraintAndTable(stmt *gorm.Statement, name string) (_ *schema.Constraint, _ *schema.Check, table string)

GuessConstraintAndTable guess statement's constraint and it's table based on name

func (*Migrator) HasColumn

func (m *Migrator) HasColumn(value interface{}, field string) bool

HasColumn check has column `field` for value or not

func (*Migrator) HasIndex

func (m *Migrator) HasIndex(value interface{}, name string) bool

HasIndex check has index `name` or not

func (*Migrator) HasTable

func (m *Migrator) HasTable(value interface{}) bool

HasTable returns table exists or not for value, value could be a struct or string

func (*Migrator) MigrateColumn

func (m *Migrator) MigrateColumn(value interface{}, field *schema.Field, columnType gorm.ColumnType, stmt *gorm.Statement) string

MigrateColumn migrate column

func (*Migrator) RegisterModel

func (m *Migrator) RegisterModel(values ...interface{})

RegisterModel run migration with statement value

func (*Migrator) ReorderModels

func (m *Migrator) ReorderModels(values []interface{}, autoAdd bool) (results []interface{})

ReorderModels reorder models according to constraint dependencies

func (*Migrator) Run

func (mg *Migrator) Run(db *gorm.DB, command string, migrationname ...string) error

func (*Migrator) RunWithValue

func (m *Migrator) RunWithValue(value interface{}, fc func(*gorm.Statement) error) error

RunWithValue run migration with statement value

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL