migration

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Nov 20, 2025 License: Apache-2.0 Imports: 15 Imported by: 0

README

Eden Go Migration

Go Report Card License

English | 中文

Eden Go Migration is a lightweight, GORM-based database migration tool for Go. It is designed to simplify database version control and automatic migration processes, supporting automatic execution of SQL script files, version tracking, and checksum verification.

✨ Features

  • Automatic Database Creation: Automatically attempts to create the database if it does not exist (MySQL/PostgreSQL).
  • Multi-Database Support: Supports MySQL, PostgreSQL, SQLite, and MariaDB.
  • Version Control: Automatically maintains the sys_db_version table to track executed migration scripts.
  • Checksum Verification: Prevents tampering with executed scripts.
  • Transaction Support: Each migration script is executed in an independent transaction to ensure atomicity.
  • GORM Integration: Seamlessly integrates with GORM, reusing existing database connection configurations.
  • Easy to Use: Integrate into existing projects with just a few lines of code.

📦 Installation

go get github.com/shiyindaxiaojie/eden-go-migration

🚀 Quick Start

1. Prepare SQL Scripts

Create a directory in your project (e.g., scripts/sql) and place SQL files named in the format V{Version}__{Description}.sql.

Examples:

  • scripts/sql/V1.0.0__Init_Schema.sql
  • scripts/sql/V1.0.1__Add_Users.sql
2. Code Integration
MySQL Example
package main

import (
	"log"
	"github.com/shiyindaxiaojie/eden-go-migration"
)

func main() {
	// Configure MySQL Database
	cfg := &migration.DatabaseConfig{
		Driver:       "mysql",
		Host:         "localhost",
		Port:         3306,
		Username:     "root",
		Password:     "your_password",
		DBName:       "your_dbname",
		MaxIdleConns: 10,
		MaxOpenConns: 100,
	}

	// Initialize Database Connection and run migrations
	migDB, err := migration.InitDB(cfg)
	if err != nil {
		log.Fatalf("Failed to initialize database: %v", err)
	}

	// Create Migration Service
	svc := migration.NewMigrationService(migDB)

	// Execute Migration
	if err := svc.Migrate("scripts/sql"); err != nil {
		log.Fatalf("Database migration failed: %v", err)
	}

	log.Println("Database migration successful!")
}
SQLite Example
cfg := &migration.DatabaseConfig{
	Driver: "sqlite",
	DBName: "app.db", // SQLite database file
}
PostgreSQL Example
cfg := &migration.DatabaseConfig{
	Driver:   "postgres",
	Host:     "localhost",
	Port:     5432,
	Username: "postgres",
	Password: "your_password",
	DBName:   "your_dbname",
}

⚙️ Configuration

The DatabaseConfig struct supports the following options:

Field Type Description Default
Driver string Database driver: mysql, postgres, sqlite mysql
Host string Database host address localhost
Port int Database port (3306 for MySQL, 5432 for PG) -
Username string Database username -
Password string Database password -
DBName string Database name (or file path for SQLite) -
MaxIdleConns int Maximum idle connections 0 (default)
MaxOpenConns int Maximum open connections 0 (unlimited)

📄 License

This project is licensed under the Apache License 2.0. See the LICENSE file for details.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type DB

type DB struct {
	*gorm.DB
}

DB 数据库实例

func InitDB

func InitDB(cfg *DatabaseConfig) (*DB, error)

InitDB 初始化数据库连接

type DatabaseConfig

type DatabaseConfig struct {
	Driver       string `json:"driver" mapstructure:"driver"` // mysql, postgres, sqlite
	Host         string `json:"host" mapstructure:"host"`
	Port         int    `json:"port" mapstructure:"port"`
	Username     string `json:"username" mapstructure:"username"`
	Password     string `json:"password" mapstructure:"password"`
	DBName       string `json:"db_name" mapstructure:"db_name"`
	MaxIdleConns int    `json:"max_idle_conns" mapstructure:"max_idle_conns"`
	MaxOpenConns int    `json:"max_open_conns" mapstructure:"max_open_conns"`
}

DatabaseConfig 数据库配置

func DefaultDatabaseConfig

func DefaultDatabaseConfig() *DatabaseConfig

DefaultDatabaseConfig 默认数据库配置

func (*DatabaseConfig) GetCreateDBDSN

func (c *DatabaseConfig) GetCreateDBDSN() string

GetCreateDBDSN 获取用于创建数据库的连接字符串

func (*DatabaseConfig) GetDSN

func (c *DatabaseConfig) GetDSN() string

GetDSN 获取数据库连接字符串

func (*DatabaseConfig) GetSafeDSN

func (c *DatabaseConfig) GetSafeDSN() string

GetSafeDSN 获取安全的数据库连接字符串(隐藏密码)

type Migration

type Migration struct {
	ID            int64      `json:"id" gorm:"primaryKey"`
	Version       string     `json:"version" gorm:"size:50;not null;unique"`
	Description   string     `json:"description" gorm:"size:200"`
	Script        string     `json:"script" gorm:"size:100;not null"`
	Checksum      string     `json:"checksum" gorm:"size:32;not null"`
	InstalledBy   string     `json:"installedBy" gorm:"size:100;not null"`
	InstalledOn   time.Time  `json:"installedOn" gorm:"not null;default:CURRENT_TIMESTAMP"`
	ExecutionTime int        `json:"executionTime" gorm:"not null"`
	Success       bool       `json:"success" gorm:"not null"`
	CreatedAt     time.Time  `json:"createdAt"`
	UpdatedAt     time.Time  `json:"updatedAt"`
	DeletedAt     *time.Time `json:"deletedAt" gorm:"index"`
}

Migration 数据库版本迁移记录

func (Migration) TableName

func (Migration) TableName() string

TableName 表名

type MigrationService

type MigrationService struct {
	// contains filtered or unexported fields
}

MigrationService 迁移服务

func NewMigrationService

func NewMigrationService(db *DB) *MigrationService

NewMigrationService 创建迁移服务

func (*MigrationService) Migrate

func (s *MigrationService) Migrate(scriptDir string) error

Migrate 执行数据库迁移

Jump to

Keyboard shortcuts

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