mysql.go

 1package dialectquery
 2
 3import "fmt"
 4
 5type Mysql struct{}
 6
 7var _ Querier = (*Mysql)(nil)
 8
 9func (m *Mysql) CreateTable(tableName string) string {
10	q := `CREATE TABLE %s (
11		id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
12		version_id bigint NOT NULL,
13		is_applied boolean NOT NULL,
14		tstamp timestamp NULL default now(),
15		PRIMARY KEY(id)
16	)`
17	return fmt.Sprintf(q, tableName)
18}
19
20func (m *Mysql) InsertVersion(tableName string) string {
21	q := `INSERT INTO %s (version_id, is_applied) VALUES (?, ?)`
22	return fmt.Sprintf(q, tableName)
23}
24
25func (m *Mysql) DeleteVersion(tableName string) string {
26	q := `DELETE FROM %s WHERE version_id=?`
27	return fmt.Sprintf(q, tableName)
28}
29
30func (m *Mysql) GetMigrationByVersion(tableName string) string {
31	q := `SELECT tstamp, is_applied FROM %s WHERE version_id=? ORDER BY tstamp DESC LIMIT 1`
32	return fmt.Sprintf(q, tableName)
33}
34
35func (m *Mysql) ListMigrations(tableName string) string {
36	q := `SELECT version_id, is_applied from %s ORDER BY id DESC`
37	return fmt.Sprintf(q, tableName)
38}
39
40func (m *Mysql) GetLatestVersion(tableName string) string {
41	q := `SELECT MAX(version_id) FROM %s`
42	return fmt.Sprintf(q, tableName)
43}
44
45func (m *Mysql) TableExists(tableName string) string {
46	schemaName, tableName := parseTableIdentifier(tableName)
47	if schemaName != "" {
48		q := `SELECT EXISTS ( SELECT 1 FROM information_schema.tables WHERE table_schema = '%s' AND table_name = '%s' )`
49		return fmt.Sprintf(q, schemaName, tableName)
50	}
51	q := `SELECT EXISTS ( SELECT 1 FROM information_schema.tables WHERE (database() IS NULL OR table_schema = database()) AND table_name = '%s' )`
52	return fmt.Sprintf(q, tableName)
53}