package main

import (
	"errors"
	"testing"

	"github.com/go-sql-driver/mysql"
)

func TestSplitSQLKeepsForwardMigrationStatements(t *testing.T) {
	statements := splitSQL("-- migration\nCREATE TABLE x (id INT);\n\nINSERT INTO x VALUES (1);\n")
	if len(statements) != 2 || statements[0] != "CREATE TABLE x (id INT)" || statements[1] != "INSERT INTO x VALUES (1)" {
		t.Fatalf("unexpected statements: %#v", statements)
	}
}

func TestSplitSQLIgnoresSemicolonsInFullLineComments(t *testing.T) {
	statements := splitSQL("-- first clause; second clause\nCREATE TABLE x (id INT);\n-- trailing; note\n")
	if len(statements) != 1 || statements[0] != "CREATE TABLE x (id INT)" {
		t.Fatalf("comment punctuation became executable SQL: %#v", statements)
	}
}

func TestOnlyDuplicateForwardDDLIsIgnoredForMigrationResume(t *testing.T) {
	duplicate := &mysql.MySQLError{Number: 1060, Message: "Duplicate column"}
	if !isResumableMigrationDDL(duplicate, "ALTER TABLE x ADD COLUMN y INT") {
		t.Fatal("duplicate ADD COLUMN should be resumable")
	}
	if isResumableMigrationDDL(duplicate, "CREATE TABLE x (y INT)") || isResumableMigrationDDL(errors.New("duplicate"), "ALTER TABLE x ADD COLUMN y INT") {
		t.Fatal("unrelated migration errors must not be ignored")
	}
	duplicateIndex := &mysql.MySQLError{Number: 1061, Message: "Duplicate key name"}
	if !isResumableMigrationDDL(duplicateIndex, "CREATE INDEX idx_x ON x(y)") || isResumableMigrationDDL(duplicateIndex, "DROP INDEX idx_x ON x") {
		t.Fatal("only duplicate CREATE INDEX should be resumable")
	}
}
