GithubHelp home page GithubHelp logo

techknowlogick / xormigrate Goto Github PK

View Code? Open in Web Editor NEW
13.0 4.0 6.0 125 KB

Migration helper for Xorm ORM

License: MIT License

Go 100.00%
go xorm databases schema migrations schema-migrations hacktoberfest

xormigrate's Introduction

Xormigrate

Go Report Card GoDoc

Supported databases

It supports any of the databases Xorm supports:

Installing

go get -u src.techknowlogick.com/xormigrate

Usage

package main

import (
	"log"

	"src.techknowlogick.com/xormigrate"

	"xorm.io/xorm"
	_ "github.com/mattn/go-sqlite3"
)

func main() {
	db, err := xorm.NewEngine("sqlite3", "mydb.sqlite3")
	if err != nil {
		log.Fatal(err)
	}

	m := xormigrate.New(db, []*xormigrate.Migration{
		// create persons table
		{
			ID: "201608301400",
			// An optional description to print out to the Xormigrate logger
			Description: "Create the Person table",
			Migrate: func(tx *xorm.Engine) error {
				// it's a good pratice to copy the struct inside the function,
				// so side effects are prevented if the original struct changes during the time
				type Person struct {
					Name string
				}
				return tx.Sync2(&Person{})
			},
			Rollback: func(tx *xorm.Engine) error {
				return tx.DropTables(&Person{})
			},
		},
		// add age column to persons
		{
			ID: "201608301415",
			Migrate: func(tx *xorm.Engine) error {
				// when table already exists, it just adds fields as columns
				type Person struct {
					Age int
				}
				return tx.Sync2(&Person{})
			},
			Rollback: func(tx *xorm.Engine) error {
				// Note: Column dropping in sqlite is not support, and you will need to do this manually
				_, err = tx.Exec("ALTER TABLE person DROP COLUMN age")
				if err != nil {
					return fmt.Errorf("Drop column failed: %v", err)
				}
				return nil
			},
		},
		// add pets table
		{
			ID: "201608301430",
			Migrate: func(tx *xorm.Engine) error {
				type Pet struct {
					Name     string
					PersonID int
				}
				return tx.Sync2(&Pet{})
			},
			Rollback: func(tx *xorm.Engine) error {
				return tx.DropTables(&Pet{})
			},
		},
	})

	if err = m.Migrate(); err != nil {
		log.Fatalf("Could not migrate: %v", err)
	}
	log.Printf("Migration did run successfully")
}

Having a separated function for initializing the schema

If you have a lot of migrations, it can be a pain to run all them, as example, when you are deploying a new instance of the app, in a clean database. To prevent this, you can set a function that will run if no migration was run before (in a new clean database). Remember to create everything here, all tables, foreign keys and what more you need in your app.

type Person struct {
	Name string
	Age int
}

type Pet struct {
	Name     string
	PersonID int
}

m := xormigrate.New(db, []*xormigrate.Migration{
    // your migrations here
})

m.InitSchema(func(tx *xorm.Engine) error {
	err := tx.sync2(
		&Person{},
		&Pet{},
		// all other tables of your app
	)
	if err != nil {
		return err
	}
	return nil
})

Adding migration descriptions to your logging

Xormigrate's logger defaults to stdout, but it can be changed to suit your needs.

m := xormigrate.New(db, []*xormigrate.Migration{
    // your migrations here
})

// Don't log anything
m.NilLogger() 

// This is the default logger
// No need to initialize this unless it was changed
// [xormigrate] message
m.DefaultLogger()

// Or, create a logger with any io.Writer you want
m.NewLogger(os.Stdout)

Credits

xormigrate's People

Contributors

jolheiser avatar kolaente avatar qwerty287 avatar renovate[bot] avatar techknowlogick avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

xormigrate's Issues

Make it context aware

It would be nice to have the option to pass an context into it, witch if canceled either rollback or stop at the next posible position.

In the best case the migrations itselve can decide what to do on context cancel like if it's a bulck migration of data, it stops after a bulck was done and if you restart the migration it starts where it ended. or if it's something atomic either rolback or finish ... and then end

else if context is not canceled we just progress as it is done now

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.