Convert Figma logo to code with AI

go-mysql-org logogo-mysql

a powerful mysql toolset with Go

4,634
991
4,634
192

Top Related Projects

14,491

Go MySQL Driver is a MySQL driver for Go's (golang) database/sql package

16,124

general purpose extensions to golang's database/sql

36,742

The fantastic ORM library for Golang, aims to be developer friendly

6,665

Simple and Powerful ORM for Go, support mysql,postgres,tidb,sqlite3,mssql,oracle, Moved to https://gitea.com/xorm/xorm

Quick Overview

The go-mysql project is a Go library that provides a set of tools for working with MySQL databases. It includes a high-performance event-driven MySQL replication client, a MySQL proxy, and a set of utilities for managing and interacting with MySQL databases.

Pros

  • High-performance: The library is designed to be highly performant, with a focus on efficiency and scalability.
  • Comprehensive: The library provides a wide range of tools and utilities for working with MySQL databases, including replication, proxy, and management tools.
  • Actively Maintained: The project is actively maintained and has a large and engaged community of contributors.
  • Flexible: The library is designed to be flexible and extensible, allowing developers to customize and extend its functionality as needed.

Cons

  • Steep Learning Curve: The library can have a steep learning curve, especially for developers who are new to working with MySQL databases or event-driven programming.
  • Limited Documentation: While the project has a good amount of documentation, some areas may be lacking in detail or clarity, which can make it difficult for new users to get started.
  • Potential Performance Issues: Depending on the specific use case and workload, the library may not always provide the best performance, especially for very high-volume or complex database operations.
  • Dependency on MySQL: The library is tightly coupled with MySQL, which means that it may not be suitable for use with other database technologies.

Code Examples

Here are a few examples of how to use the go-mysql library:

  1. Replication Client:
package main

import (
    "fmt"
    "os"

    "github.com/go-mysql-org/go-mysql/mysql"
    "github.com/go-mysql-org/go-mysql/replication"
)

func main() {
    cfg := replication.BinlogSyncerConfig{
        ServerID: 100,
        Flavor:   "mysql",
        Host:     "127.0.0.1",
        Port:     3306,
        User:     "root",
        Password: "root",
    }

    syncer := replication.NewBinlogSyncer(cfg)
    streamer, err := syncer.StartSync(mysql.Position{Name: "mysql-bin.000001", Pos: 4})
    if err != nil {
        fmt.Println("Error starting sync:", err)
        os.Exit(1)
    }

    for {
        ev, err := streamer.GetEvent(context.Background())
        if err != nil {
            fmt.Println("Error getting event:", err)
            os.Exit(1)
        }

        fmt.Println("Event:", ev)
    }
}
  1. MySQL Proxy:
package main

import (
    "fmt"
    "os"

    "github.com/go-mysql-org/go-mysql/mysql"
    "github.com/go-mysql-org/go-mysql/proxy"
)

func main() {
    cfg := proxy.Config{
        Addr:     ":4000",
        User:     "root",
        Password: "root",
        Backend:  "127.0.0.1:3306",
    }

    p := proxy.NewProxy(cfg)
    if err := p.Run(); err != nil {
        fmt.Println("Error running proxy:", err)
        os.Exit(1)
    }
}
  1. MySQL Utilities:
package main

import (
    "fmt"
    "os"

    "github.com/go-mysql-org/go-mysql/mysql"
)

func main() {
    cfg := mysql.Config{
        User:     "root",
        Password: "root",
        Net:      "tcp",
        Addr:     "127.0.0.1:3306",
        DBName:   "test",
    }

    db, err := mysql.Connect(cfg)
    if err != nil {
        fmt.Println("Error connecting to database:", err)
        os.Exit(1)
    }
    defer db.Close()

    rows, err := db.Query("SELECT * FROM users

Competitor Comparisons

14,491

Go MySQL Driver is a MySQL driver for Go's (golang) database/sql package

Pros of go-sql-driver/mysql

  • Widely used and well-maintained MySQL driver for Go, with a large community and extensive documentation.
  • Supports a wide range of MySQL features, including prepared statements, transactions, and connection pooling.
  • Provides a simple and straightforward API for interacting with MySQL databases.

Cons of go-sql-driver/mysql

  • Primarily focused on MySQL, and may not provide the same level of support for other database engines as go-mysql-org/go-mysql.
  • May not offer the same level of abstraction and higher-level functionality as go-mysql-org/go-mysql, which is designed to be a more comprehensive MySQL client.

Code Comparison

go-sql-driver/mysql:

db, err := sql.Open("mysql", "user:password@/dbname")
if err != nil {
    // handle error
}
defer db.Close()

rows, err := db.Query("SELECT * FROM users")
if err != nil {
    // handle error
}
defer rows.Close()

for rows.Next() {
    var name string
    var age int
    if err := rows.Scan(&name, &age); err != nil {
        // handle error
    }
    // process data
}

go-mysql-org/go-mysql:

cfg := mysql.DefaultConfig()
cfg.Addr = "127.0.0.1:3306"
cfg.User = "root"
cfg.Password = "password"

c, err := mysql.Connect(context.Background(), cfg)
if err != nil {
    // handle error
}
defer c.Close()

r, err := c.Execute("SELECT * FROM users")
if err != nil {
    // handle error
}
defer r.Close()

for r.Next() {
    var name string
    var age int
    if err := r.Scan(&name, &age); err != nil {
        // handle error
    }
    // process data
}
16,124

general purpose extensions to golang's database/sql

Pros of sqlx

  • Provides a higher-level abstraction over the standard database/sql package, making it easier to work with.
  • Supports automatic struct mapping, reducing boilerplate code.
  • Offers additional functionality like named queries and batch operations.

Cons of sqlx

  • May be overkill for simple use cases where the standard database/sql package is sufficient.
  • Adds an additional dependency to your project, which may not be desirable in some cases.
  • The learning curve may be steeper compared to the standard database/sql package.

Code Comparison

go-mysql-org/go-mysql

db, err := sql.Open("mysql", "user:password@tcp(127.0.0.1:3306)/test")
if err != nil {
    // handle error
}
defer db.Close()

rows, err := db.Query("SELECT id, name FROM users")
if err != nil {
    // handle error
}
defer rows.Close()

for rows.Next() {
    var id int
    var name string
    if err := rows.Scan(&id, &name); err != nil {
        // handle error
    }
    // do something with id and name
}

jmoiron/sqlx

db, err := sqlx.Open("mysql", "user:password@tcp(127.0.0.1:3306)/test")
if err != nil {
    // handle error
}
defer db.Close()

var users []struct {
    ID   int    `db:"id"`
    Name string `db:"name"`
}
if err := db.Select(&users, "SELECT id, name FROM users"); err != nil {
    // handle error
}

for _, user := range users {
    // do something with user.ID and user.Name
}
36,742

The fantastic ORM library for Golang, aims to be developer friendly

Pros of go-gorm/gorm

  • Abstraction and Simplicity: go-gorm/gorm provides a higher-level abstraction over the database, making it easier to work with and reducing boilerplate code.
  • Automatic Migrations: go-gorm/gorm can automatically create and update database schemas based on your Go struct definitions, simplifying database management.
  • Powerful Querying: go-gorm/gorm offers a rich set of querying capabilities, including support for complex queries, eager loading, and transactions.

Cons of go-gorm/gorm

  • Performance: go-gorm/gorm may have slightly lower performance compared to go-mysql-org/go-mysql, as the abstraction layer can introduce some overhead.
  • Limited Database Support: go-gorm/gorm primarily focuses on MySQL, PostgreSQL, and SQLite, while go-mysql-org/go-mysql supports a wider range of databases.
  • Steeper Learning Curve: go-gorm/gorm has a more complex API and requires more time to learn compared to the more straightforward go-mysql-org/go-mysql.

Code Comparison

go-mysql-org/go-mysql:

conn, err := mysql.Connect("user:password@tcp(127.0.0.1:3306)/database")
if err != nil {
    panic(err)
}
defer conn.Close()

result, err := conn.Execute("SELECT * FROM users WHERE id = ?", 1)
if err != nil {
    panic(err)
}

go-gorm/gorm:

db, err := gorm.Open(mysql.Open("user:password@tcp(127.0.0.1:3306)/database"), &gorm.Config{})
if err != nil {
    panic(err)
}

var user User
db.First(&user, 1)
6,665

Simple and Powerful ORM for Go, support mysql,postgres,tidb,sqlite3,mssql,oracle, Moved to https://gitea.com/xorm/xorm

Pros of go-xorm/xorm

  • Provides a more comprehensive ORM (Object-Relational Mapping) solution, supporting multiple databases including MySQL, PostgreSQL, SQLite, and more.
  • Offers a rich set of features, such as automatic table creation, data caching, and transaction management.
  • Includes a powerful code generation tool that can generate models and CRUD (Create, Read, Update, Delete) code based on database schemas.

Cons of go-xorm/xorm

  • May have a steeper learning curve compared to go-mysql-org/go-mysql, as it provides a more complex and feature-rich API.
  • The performance of go-xorm/xorm may be slightly lower than go-mysql-org/go-mysql, as it has to handle the additional abstraction layer of the ORM.
  • The documentation and community support for go-xorm/xorm may not be as extensive as go-mysql-org/go-mysql, which is a more focused and specialized library.

Code Comparison

go-mysql-org/go-mysql:

conn, err := mysql.Connect("user:password@tcp(host:port)/database")
if err != nil {
    // handle error
}
defer conn.Close()

// execute a query
rows, err := conn.Query("SELECT * FROM users")
if err != nil {
    // handle error
}
defer rows.Close()

go-xorm/xorm:

engine, err := xorm.NewEngine("mysql", "user:password@tcp(host:port)/database")
if err != nil {
    // handle error
}
defer engine.Close()

// define a model
type User struct {
    ID   int64
    Name string
}

// execute a query
users := make([]User, 0)
err = engine.Find(&users)
if err != nil {
    // handle error
}

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

go-mysql

A pure go library to handle MySQL network protocol and replication as used by MySQL and MariaDB.

semver example workflow gomod version Go Reference

Changelog

This repo uses Changelog.


Content

Examples

The cmd directory contains example applications that can be build by running make build in the root of the project. The resulting binaries will be places in bin/.

  • go-binlogparser: parses a binlog file at a given offset
  • go-canal: streams binlog events from a server to canal
  • go-mysqlbinlog: streams binlog events
  • go-mysqldump: like mysqldump, but in Go
  • go-mysqlserver: fake MySQL server

Replication

Replication package handles MySQL replication protocol like python-mysql-replication.

You can use it as a MySQL replica to sync binlog from master then do something, like updating cache, etc...

Example

import (
	"github.com/go-mysql-org/go-mysql/replication"
	"os"
)
// Create a binlog syncer with a unique server id, the server id must be different from other MySQL's. 
// flavor is mysql or mariadb
cfg := replication.BinlogSyncerConfig {
	ServerID: 100,
	Flavor:   "mysql",
	Host:     "127.0.0.1",
	Port:     3306,
	User:     "root",
	Password: "",
}
syncer := replication.NewBinlogSyncer(cfg)

// Start sync with specified binlog file and position
streamer, _ := syncer.StartSync(mysql.Position{binlogFile, binlogPos})

// or you can start a gtid replication like
// gtidSet, _ := mysql.ParseGTIDSet(mysql.MySQLFlavor, "de278ad0-2106-11e4-9f8e-6edd0ca20947:1-2")
// streamer, _ := syncer.StartSyncGTID(gtidSet)
// the mysql GTID set is like this "de278ad0-2106-11e4-9f8e-6edd0ca20947:1-2" and uses mysql.MySQLFlavor
// the mariadb GTID set is like this "0-1-100" and uses mysql.MariaDBFlavor

for {
	ev, _ := streamer.GetEvent(context.Background())
	// Dump event
	ev.Dump(os.Stdout)
}

// or we can use a timeout context
for {
	ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
	ev, err := streamer.GetEvent(ctx)
	cancel()

	if err == context.DeadlineExceeded {
		// meet timeout
		continue
	}

	ev.Dump(os.Stdout)
}

The output looks:

=== RotateEvent ===
Date: 1970-01-01 08:00:00
Log position: 0
Event size: 43
Position: 4
Next log name: mysql.000002

=== FormatDescriptionEvent ===
Date: 2014-12-18 16:36:09
Log position: 120
Event size: 116
Version: 4
Server version: 5.6.19-log
Create date: 2014-12-18 16:36:09

=== QueryEvent ===
Date: 2014-12-18 16:38:24
Log position: 259
Event size: 139
Salve proxy ID: 1
Execution time: 0
Error code: 0
Schema: test
Query: DROP TABLE IF EXISTS `test_replication` /* generated by server */

Canal

Canal is a package that can sync your MySQL into everywhere, like Redis, Elasticsearch.

First, canal will dump your MySQL data then sync changed data using binlog incrementally.

You must use ROW format for binlog, full binlog row image is preferred, because we may meet some errors when primary key changed in update for minimal or noblob row image.

A simple example:

package main

import (
	"github.com/go-mysql-org/go-mysql/canal"
	"github.com/siddontang/go-log/log"
)

type MyEventHandler struct {
	canal.DummyEventHandler
}

func (h *MyEventHandler) OnRow(e *canal.RowsEvent) error {
	log.Infof("%s %v\n", e.Action, e.Rows)
	return nil
}

func (h *MyEventHandler) String() string {
	return "MyEventHandler"
}

func main() {
	cfg := canal.NewDefaultConfig()
	cfg.Addr = "127.0.0.1:3306"
	cfg.User = "root"
	// We only care table canal_test in test db
	cfg.Dump.TableDB = "test"
	cfg.Dump.Tables = []string{"canal_test"}

	c, err := canal.NewCanal(cfg)
	if err != nil {
		log.Fatal(err)
	}

	// Register a handler to handle RowsEvent
	c.SetEventHandler(&MyEventHandler{})

	// Start canal
	c.Run()
}

You can see go-mysql-elasticsearch for how to sync MySQL data into Elasticsearch.

Client

Client package supports a simple MySQL connection driver which you can use it to communicate with MySQL server.

Example

import (
	"github.com/go-mysql-org/go-mysql/client"
)

// Connect MySQL at 127.0.0.1:3306, with user root, an empty password and database test
conn, _ := client.Connect("127.0.0.1:3306", "root", "", "test")

// Or to use SSL/TLS connection if MySQL server supports TLS
//conn, _ := client.Connect("127.0.0.1:3306", "root", "", "test", func(c *Conn) {c.UseSSL(true)})

// Or to set your own client-side certificates for identity verification for security
//tlsConfig := NewClientTLSConfig(caPem, certPem, keyPem, false, "your-server-name")
//conn, _ := client.Connect("127.0.0.1:3306", "root", "", "test", func(c *Conn) {c.SetTLSConfig(tlsConfig)})

conn.Ping()

// Insert
r, _ := conn.Execute(`insert into table (id, name) values (1, "abc")`)

// Get last insert id
println(r.InsertId)
// Or affected rows count
println(r.AffectedRows)

// Select
r, err := conn.Execute(`select id, name from table where id = 1`)

// Close result for reuse memory (it's not necessary but very useful)
defer r.Close()

// Handle resultset
v, _ := r.GetInt(0, 0)
v, _ = r.GetIntByName(0, "id")

// Direct access to fields
for _, row := range r.Values {
	for _, val := range row {
		_ = val.Value() // interface{}
		// or
		if val.Type == mysql.FieldValueTypeFloat {
			_ = val.AsFloat64() // float64
		}
	}   
}

Tested MySQL versions for the client include:

  • 5.5.x
  • 5.6.x
  • 5.7.x
  • 8.0.x

Example for SELECT streaming (v1.1.1)

You can use also streaming for large SELECT responses. The callback function will be called for every result row without storing the whole resultset in memory. result.Fields will be filled before the first callback call.

// ...
var result mysql.Result
err := conn.ExecuteSelectStreaming(`select id, name from table LIMIT 100500`, &result, func(row []mysql.FieldValue) error {
    for idx, val := range row {
    	field := result.Fields[idx]
    	// You must not save FieldValue.AsString() value after this callback is done.
    	// Copy it if you need.
    	// ...
    }
    return nil
}, nil)

// ...

Example for connection pool (v1.3.0)

import (
    "github.com/go-mysql-org/go-mysql/client"
)

pool := client.NewPool(log.Debugf, 100, 400, 5, "127.0.0.1:3306", `root`, ``, `test`)
// ...
conn, _ := pool.GetConn(ctx)
defer pool.PutConn(conn)

conn.Execute() / conn.Begin() / etc...

Server

Server package supplies a framework to implement a simple MySQL server which can handle the packets from the MySQL client. You can use it to build your own MySQL proxy. The server connection is compatible with MySQL 5.5, 5.6, 5.7, and 8.0 versions, so that most MySQL clients should be able to connect to the Server without modifications.

Example

Minimalistic MySQL server implementation:

package main

import (
	"log"
	"net"

	"github.com/go-mysql-org/go-mysql/server"
)

func main() {
	// Listen for connections on localhost port 4000
	l, err := net.Listen("tcp", "127.0.0.1:4000")
	if err != nil {
		log.Fatal(err)
	}

	// Accept a new connection once
	c, err := l.Accept()
	if err != nil {
		log.Fatal(err)
	}

	// Create a connection with user root and an empty password.
	// You can use your own handler to handle command here.
	conn, err := server.NewConn(c, "root", "", server.EmptyHandler{})
	if err != nil {
		log.Fatal(err)
	}

	// as long as the client keeps sending commands, keep handling them
	for {
		if err := conn.HandleCommand(); err != nil {
			log.Fatal(err)
		}
	}
}

Another shell

$ mysql -h127.0.0.1 -P4000 -uroot
Your MySQL connection id is 10001
Server version: 5.7.0

MySQL [(none)]>
// Since EmptyHandler implements no commands, it will throw an error on any query that you will send

NewConn() will use default server configurations:

  1. automatically generate default server certificates and enable TLS/SSL support.
  2. support three mainstream authentication methods 'mysql_native_password', 'caching_sha2_password', and 'sha256_password' and use 'mysql_native_password' as default.
  3. use an in-memory user credential provider to store user and password.

To customize server configurations, use NewServer() and create connection via NewCustomizedConn().

Driver

Driver is the package that you can use go-mysql with go database/sql like other drivers. A simple example:

package main

import (
	"database/sql"

	_ "github.com/go-mysql-org/go-mysql/driver"
)

func main() {
	// dsn format: "user:password@addr?dbname"
	dsn := "root@127.0.0.1:3306?test"
	db, _ := sql.Open("mysql", dsn)
	db.Close()
}

Driver Options

Configuration options can be provided by the standard DSN (Data Source Name).

[user[:password]@]addr[/db[?param=X]]

collation

Set a collation during the Auth handshake.

TypeDefaultExample
stringutf8_general_ciuser:pass@localhost/mydb?collation=latin1_general_ci

compress

Enable compression between the client and the server. Valid values are 'zstd','zlib','uncompressed'.

TypeDefaultExample
stringuncompresseduser:pass@localhost/mydb?compress=zlib

readTimeout

I/O read timeout. The time unit is specified in the argument value using golang's ParseDuration format.

0 means no timeout.

TypeDefaultExample
duration0user:pass@localhost/mydb?readTimeout=10s

ssl

Enable TLS between client and server. Valid values are true or custom. When using custom, the connection will use the TLS configuration set by SetCustomTLSConfig matching the host.

TypeDefaultExample
stringuser:pass@localhost/mydb?ssl=true

timeout

Timeout is the maximum amount of time a dial will wait for a connect to complete. The time unit is specified in the argument value using golang's ParseDuration format.

0 means no timeout.

TypeDefaultExample
duration0user:pass@localhost/mydb?timeout=1m

writeTimeout

I/O write timeout. The time unit is specified in the argument value using golang's ParseDuration format.

0 means no timeout.

TypeDefaultExample
duration0user:pass@localhost/mydb?writeTimeout=1m30s

retries

Allows disabling the golang database/sql default behavior to retry errors when ErrBadConn is returned by the driver. When retries are disabled this driver will not return ErrBadConn from the database/sql package.

Valid values are on (default) and off.

TypeDefaultExample
stringonuser:pass@localhost/mydb?retries=off

Custom Driver Options

The driver package exposes the function SetDSNOptions, allowing for modification of the connection by adding custom driver options. It requires a full import of the driver (not by side-effects only).

Example of defining a custom option:

import (
 "database/sql"

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

func main() {
 driver.SetDSNOptions(map[string]DriverOption{
  "no_metadata": func(c *client.Conn, value string) error {
   c.SetCapability(mysql.CLIENT_OPTIONAL_RESULTSET_METADATA)
   return nil
  },
 })

 // dsn format: "user:password@addr/dbname?"
 dsn := "root@127.0.0.1:3306/test?no_metadata=true"
 db, _ := sql.Open(dsn)
 db.Close()
}

Custom Driver Name

A custom driver name can be set via build options: -ldflags '-X "github.com/go-mysql-org/go-mysql/driver.driverName=gomysql"'.

This can be useful when using GORM:

import (
  _ "github.com/go-mysql-org/go-mysql/driver"
  "gorm.io/driver/mysql"
  "gorm.io/gorm"
)

db, err := gorm.Open(mysql.New(mysql.Config{
  DriverName: "gomysql",
  DSN: "gorm:gorm@127.0.0.1:3306/test",
}))

Custom NamedValueChecker

Golang allows for custom handling of query arguments before they are passed to the driver with the implementation of a NamedValueChecker. By doing a full import of the driver (not by side-effects only), a custom NamedValueChecker can be implemented.

import (
 "database/sql"

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

func main() {
 driver.AddNamedValueChecker(func(nv *sqlDriver.NamedValue) error {
  rv := reflect.ValueOf(nv.Value)
  if rv.Kind() != reflect.Uint64 {
   // fallback to the default value converter when the value is not a uint64
   return sqlDriver.ErrSkip
  }

  return nil
 })

 conn, err := sql.Open("mysql", "root@127.0.0.1:3306/test")
 defer conn.Close()

 stmt, err := conn.Prepare("select * from table where id = ?")
 defer stmt.Close()
 var val uint64 = math.MaxUint64
 // without the NamedValueChecker this query would fail
 result, err := stmt.Query(val)
}

We pass all tests in https://github.com/bradfitz/go-sql-test using go-mysql driver. :-)

Logging

Logging by default is send to stdout.

To disable logging completely:

import "github.com/siddontang/go-log/log"
...
        nullHandler, _ := log.NewNullHandler()
        cfg.Logger = log.NewDefault(nullHandler)

To write logging to any io.Writer:

import "github.com/siddontang/go-log/log"
...
        w := ...
        streamHandler, _ := log.NewStreamHandler(w)
        cfg.Logger = log.NewDefault(streamHandler)

Or you can implement your own log.Handler.

How to migrate to this repo

To change the used package in your repo it's enough to add this replace directive to your go.mod:

replace github.com/siddontang/go-mysql => github.com/go-mysql-org/go-mysql v1.10.0

This can be done by running this command:

go mod edit -replace=github.com/siddontang/go-mysql=github.com/go-mysql-org/go-mysql@v1.10.0

v1.10.0 - is the last tag in repo, feel free to choose what you want.

Credits

go-mysql was started by @siddontang and has many contributors