mysql

package module
v1.0.0-rc1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 22, 2026 License: MIT Imports: 7 Imported by: 0

README

Compogo MySQL

Адаптер MySQL для фреймворка Compogo.

Предоставляет:

  • Клиент для работы с MySQL
  • Встроенный Limiter для защиты от ошибок соединения
  • Логирование всех SQL-запросов
  • Интеграцию с db-client как драйвер
  • Интеграцию с db-migrator для миграций
  • Интеграцию с db-sql-generator для генерации SQL

Установка

go get github.com/Compogo/mysql

Быстрый старт

package main

import (
    "github.com/Compogo/compogo"
    "github.com/Compogo/mysql/registration/all"
)

func main() {
    app := compogo.NewApp("myapp",
        // Подключаем всё сразу (клиент + мигратор + генератор)
        compogo.WithComponents(&all.Component),
    )

    if err := app.Serve(); err != nil {
        panic(err)
    }
}

Конфигурация

Флаги командной строки
# DSN строка подключения
--db.mysql.dsn="user:pass@tcp(localhost:3306)/dbname?parseTime=true"

# Лимит ошибок соединения (защита от "штурма")
--db.mysql.connection.error.limit=10

# Время блокировки при превышении лимита
--db.mysql.connection.error.timeout=10s
Пример DSN
# Базовая строка
user:password@tcp(localhost:3306)/dbname

# С параметрами
user:password@tcp(localhost:3306)/dbname?charset=utf8mb4&parseTime=true&loc=UTC

# Без пароля
user@tcp(localhost:3306)/dbname

Защита от ошибок соединения

При возникновении ошибок соединения (sql.ErrConnDone, driver.ErrBadConn) клиент:

  1. Увеличивает счётчик ошибок.
  2. При превышении лимита (по умолчанию 10) блокирует запросы на указанное время.
  3. После таймаута восстанавливает работу.

Это защищает БД от "штурма" при сетевых проблемах.

Регистрация компонентов

Всё сразу
import "github.com/Compogo/mysql/registration/all"

app.AddComponents(&all.Component)
По отдельности
import (
    "github.com/Compogo/mysql"
    "github.com/Compogo/mysql/registration/manager"
    "github.com/Compogo/mysql/registration/migrator"
    "github.com/Compogo/mysql/registration/sql_generator"
)

// Только клиент БД
app.AddComponents(&mysql.Component)

// Клиент + регистрация в db-client
app.AddComponents(&manager.Component)

// Клиент + регистрация в db-migrator
app.AddComponents(&migrator.Component)

// Клиент + регистрация в db-sql-generator
app.AddComponents(&sqlGenerator.Component)

Зависимости

Лицензия

MIT License

Copyright (c) 2026 Compogo

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

Documentation

Index

Constants

View Source
const (
	// DsnFieldName — имя поля для DSN строки подключения.
	DsnFieldName = "db.mysql.dsn"

	// ConnectionErrorLimitFieldName — имя поля для лимита ошибок соединения.
	ConnectionErrorLimitFieldName = "db.mysql.connection.error.limit"

	// ConnectionErrorTimeoutFieldName — имя поля для таймаута при ошибках соединения.
	ConnectionErrorTimeoutFieldName = "db.mysql.connection.error.timeout"
)
View Source
const DriverName = "mysql"

DriverName — имя драйвера MySQL.

Variables

View Source
var (
	// ConnectionErrorLimitDefault — лимит ошибок соединения по умолчанию.
	ConnectionErrorLimitDefault = uint64(10)

	// ConnectionErrorTimeoutDefault — таймаут при ошибках соединения по умолчанию.
	ConnectionErrorTimeoutDefault = 10 * time.Second
)
View Source
var Component = compogo.Component{
	Dependencies: compogo.Components{
		&runner.Component,
	},
	Init: compogo.StepFunc(func(container compogo.Container) error {
		return container.Provides(
			NewConfig,
			NewMySQL,
		)
	}),
	BindFlags: compogo.BindFlags(func(flagSet flag.FlagSet, container compogo.Container) error {
		return container.Invoke(func(config *Config) {
			flagSet.StringVar(&config.DSN, DsnFieldName, "", "mysql dsn string connection")
			flagSet.Uint64Var(&config.ErrorLimit, ConnectionErrorLimitFieldName, ConnectionErrorLimitDefault, "")
			flagSet.DurationVar(&config.ErrorTimeout, ConnectionErrorTimeoutFieldName, ConnectionErrorTimeoutDefault, "")
		})
	}),
	Configuration: compogo.StepFunc(func(container compogo.Container) error {
		return container.Invoke(Configuration)
	}),
}

Component — компонент MySQL для Compogo. Регистрирует конфигурацию и клиент в DI-контейнере.

Пример подключения:

app.AddComponents(&mysql.Component)

var client mysql.Client
container.Invoke(func(c mysql.Client) { client = c })
rows, err := client.Query("SELECT * FROM users")

Functions

This section is empty.

Types

type Client

type Client dbClient.Client

Client — интерфейс клиента MySQL (наследует db_client.Client).

func NewMySQL

func NewMySQL(logger compogo.Logger, config *Config, runner runner.Runner) (Client, error)

NewMySQL создаёт новый клиент MySQL. Оборачивает соединение в:

  • Limiter — защита от ошибок соединения
  • Logger — логирование всех SQL-запросов

type Config

type Config struct {
	DSN          string
	ErrorLimit   uint64
	ErrorTimeout time.Duration
}

Config содержит конфигурацию MySQL.

func Configuration

func Configuration(config *Config, configurator compogo.Configurator) *Config

Configuration загружает конфигурацию из Configurator. Если DSN не задан, он должен быть получен из Configurator.

func NewConfig

func NewConfig() *Config

NewConfig создаёт новую конфигурацию.

Directories

Path Synopsis
registration
all

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL