// +build !integration

/*
 * Copyright 2021 PingCAP, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package model

import (
	"testing"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"

	"github.com/stretchr/testify/require"
	"gopkg.in/DATA-DOG/go-sqlmock.v1"
)

func TestMigrateCreateJobMock(t *testing.T) {
	assert := require.New(t)
	conn, mock, err := sqlmock.New()
	assert.Nil(err)
	assert.NotNil(conn)
	db, err := gorm.Open(mysql.New(mysql.Config{
		SkipInitializeWithVersion: true,
		Conn:                      conn,
	}), &gorm.Config{})
	assert.Nil(err)

	mock.ExpectExec("CREATE TABLE `job` \\(`id` int\\(11\\) unsigned NOT NULL AUTO_INCREMENT,`user_id` varchar\\(64\\) NOT NULL DEFAULT '',`job_id` varchar\\(64\\) NOT NULL DEFAULT '',`jm_endpoint` varchar\\(128\\) NOT NULL DEFAULT '',`namespace` varchar\\(64\\) NOT NULL DEFAULT '',`job_type` tinyint\\(4\\) NOT NULL DEFAULT 0,`input_type` tinyint\\(4\\) NOT NULL DEFAULT 0,`input_key` varchar\\(128\\) NOT NULL DEFAULT '',`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,`updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,PRIMARY KEY \\(`id`\\),UNIQUE INDEX .+ \\(`job_id`,`user_id`\\)\\)").
		WillReturnResult(sqlmock.NewResult(1, 1))

	assert.Nil(db.Migrator().CreateTable(&Job{}))
}

func TestMigrateCreateSavepointMock(t *testing.T) {
	assert := require.New(t)
	conn, mock, err := sqlmock.New()
	assert.Nil(err)
	assert.NotNil(conn)
	db, err := gorm.Open(mysql.New(mysql.Config{
		SkipInitializeWithVersion: true,
		Conn:                      conn,
	}), &gorm.Config{})
	assert.Nil(err)

	mock.ExpectExec("CREATE TABLE `savepoint` \\(`id` int\\(11\\) unsigned NOT NULL AUTO_INCREMENT,`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,`updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,`job_ref` int\\(11\\) NOT NULL,`path` text DEFAULT NULL,PRIMARY KEY \\(`id`\\),CONSTRAINT .+ FOREIGN KEY \\(`job_ref`\\) REFERENCES `job`\\(`id`\\) ON DELETE CASCADE\\)").
		WillReturnResult(sqlmock.NewResult(1, 1))

	assert.Nil(db.Migrator().CreateTable(&Savepoint{}))
}
