The built-in memory database implementation can be used as a stand-in for a real MySQL server in Go test environments. You can start the server by configuring a server.Config and initializing the engine and session using the memory package.
Once the server is running, you can connect to it using any MySQL-compatible client (e.g., the mysql shell or Go MySQL connectors).
package main
import (
"context"
"fmt"
"time"
"github.com/dolthub/vitess/go/vt/proto/query"
sqle "github.com/dolthub/go-mysql-server"
"github.com/dolthub/go-mysql-server/memory"
"github.com/dolthub/go-mysql-server/server"
"github.com/dolthub/go-mysql-server/sql"
"github.com/dolthub/go-mysql-server/sql/types"
)
var (
dbName = "mydb"
tableName = "mytable"
address = "localhost"
port = 3306
)
func main() {
pro := createTestDatabase()
engine := sqle.NewDefault(pro)
session := memory.NewSession(sql.NewBaseSession(), pro)
ctx := sql.NewContext(context.Background(), sql.WithSession(session))
ctx.SetCurrentDatabase(dbName)
config := server.Config{
Protocol: "tcp",
Address: fmt.Sprintf("%s:%d", address, port),
}
s, err := server.NewServer(config, engine, sql.NewContext, memory.NewSessionBuilder(pro), nil)
if err != nil {
panic(err)
}
if err = s.Start(); err != nil {
panic(err)
}
}
func createTestDatabase() *memory.DbProvider {
db := memory.NewDatabase(dbName)
pro := memory.NewDBProvider(db)
session := memory.NewSession(sql.NewBaseSession(), pro)
ctx := sql.NewContext(context.Background(), sql.WithSession(session))
table := memory.NewTable(ctx, db, tableName, sql.NewPrimaryKeySchema(sql.Schema{
{Name: "name", Type: types.Text, Nullable: false, Source: tableName, PrimaryKey: true},
{Name: "email", Type: types.Text, Nullable: false, Source: tableName, PrimaryKey: true},
{Name: "phone_numbers", Type: types.JSON, Nullable: false, Source: tableName},
{Name: "created_at", Type: types.MustCreateDatetimeType(query.Type_DATETIME, 6), Nullable: false, Source: tableName},
}), db.GetForeignKeyCollection())
db.AddTable(tableName, table)
creationTime := time.Unix(0, 1667304000000001000).UTC()
_ = table.Insert(ctx, sql.NewRow("Jane Deo", "janedeo@gmail.com", types.MustJSON(`["556-565-566","777-777-777"]`), creationTime))
_ = table.Insert(ctx, sql.NewRow("Jane Doe", "jane@doe.com", types.MustJSON(`[]`), creationTime))
_ = table.Insert(ctx, sql.NewRow("John Doe", "john@doe.com", types.MustJSON(`["555-555-555"]`), creationTime))
_ = table.Insert(ctx, sql.NewRow("John Doe", "johnalt@doe.com", types.MustJSON(`[]`), creationTime))
return pro
}