Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Trim AUTO_INCREMENT values from MySQL schema dumps #319

Merged
merged 8 commits into from Sep 23, 2022
13 changes: 12 additions & 1 deletion pkg/driver/mysql/mysql.go
Expand Up @@ -6,6 +6,7 @@ import (
"fmt"
"io"
"net/url"
"regexp"
"strings"

"github.com/amacneil/dbmate/pkg/dbmate"
Expand Down Expand Up @@ -192,7 +193,17 @@ func (drv *Driver) DumpSchema(db *sql.DB) ([]byte, error) {
}

schema = append(schema, migrations...)
return dbutil.TrimLeadingSQLComments(schema)
schema, err = dbutil.TrimLeadingSQLComments(schema)
if err != nil {
return nil, err
}
return trimAutoincrementValues(schema), nil
}

// trimAutoincrementValues removes AUTO_INCREMENT values from MySQL schema dumps
func trimAutoincrementValues(data []byte) []byte {
aiPattern := regexp.MustCompile(" AUTO_INCREMENT=[0-9]*")
return aiPattern.ReplaceAll(data, []byte(""))
}

// DatabaseExists determines whether the database exists
Expand Down
28 changes: 28 additions & 0 deletions pkg/driver/mysql/mysql_test.go
Expand Up @@ -183,6 +183,34 @@ func TestMySQLDumpSchema(t *testing.T) {
require.Contains(t, err.Error(), "Unknown database 'fakedb'")
}

func TestMySQLDumpSchemaContainsNoAutoIncrement(t *testing.T) {
drv := testMySQLDriver(t)

db := prepTestMySQLDB(t)
defer dbutil.MustClose(db)
err := drv.CreateMigrationsTable(db)
require.NoError(t, err)

// create table with AUTO_INCREMENT column
_, err = db.Exec(`create table foo_table (id int not null primary key auto_increment)`)
require.NoError(t, err)

// create a record
_, err = db.Exec(`insert into foo_table values ()`)
require.NoError(t, err)

// AUTO_INCREMENT should appear on the table definition
var tblName, tblCreate string
err = db.QueryRow(`show create table foo_table`).Scan(&tblName, &tblCreate)
require.NoError(t, err)
require.Contains(t, tblCreate, "AUTO_INCREMENT=")

// AUTO_INCREMENT should not appear in the dump
schema, err := drv.DumpSchema(db)
require.NoError(t, err)
require.NotContains(t, string(schema), "AUTO_INCREMENT=")
}

func TestMySQLDatabaseExists(t *testing.T) {
drv := testMySQLDriver(t)

Expand Down