// Copyright 2017 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 main

import (
	"database/sql"
	"flag"
	"fmt"
	"log"

	_ "github.com/go-sql-driver/mysql"
	"github.com/pingcap/tidb-test/util"
)

var (
	testPhase    = flag.String("phase", "", "test phase")
	testHost     = flag.String("host", "127.0.0.1", "test host")
	testPort     = flag.Int("port", 4000, "test port")
	testUser     = flag.String("user", "root", "test user")
	testPassword = flag.String("password", "", "test password")
)

func mustExec(db *sql.DB, query string, args ...interface{}) {
	_, err := db.Exec(query, args...)
	if err != nil {
		log.Fatal(err)
	}
}

func openTestDB() (*sql.DB, error) {
	db, err := util.OpenDBWithRetry("mysql", fmt.Sprintf("%s:%s@(%s:%d)/test?multiStatements=true", *testUser, *testPassword, *testHost, *testPort))
	if err != nil {
		return nil, err
	}

	return db, nil
}

func main() {
	flag.Parse()

	db, err := openTestDB()
	if err != nil {
		log.Fatal(err)
	}

	switch *testPhase {
	case "old":
		mustExec(db, `
			create table if not exists compatible_test (id BIGINT PRIMARY KEY, value VARCHAR(128) NOT NULL);
			delete from compatible_test;
			insert compatible_test(id, value) values (1, "pingcap"); 
		`)
	case "new":
		mustExec(db, `
			insert compatible_test(id, value) values(2, "pingcap");
			select * from compatible_test; 
			update compatible_test set value = "ti" where id = 2;
		`)
	default:
		log.Fatal("wrong phase")
	}

	db.Close()
}
