mysql

package module
v0.0.4 Latest Latest
Warning

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

Go to latest
Published: Jan 31, 2023 License: MIT Imports: 9 Imported by: 0

README

Jeefo MySQL

This is a very simple and lightweight MySQL library top of github.com/go-sql-driver/mysql. It was written in my first three days of learning Go programming language.

Getting started

Installation
import "github.com/je3f0o/go-jeefo-mysql"

Then execute $ go mod tidy. Or Go command to install the package.

$ go get -u github.com/je3f0o/go-jeefo-mysql
Example

config.yml

database:
  # Default values when using `mysql.NewConfig()`
  #host: 127.0.0.1
  #port: 3306
  socket: /var/lib/mysql/mysql.sock # for Unix socket connection
  name: my_database
  user: jeefo
  pass: 123

main.go

package main

import (
  "os"
  
  "github.com/je3f0o/go-jeefo-mysql"
  "gopkg.in/yaml.v3"
)

type _json map[string]interface{}

type Config struct {
  Database *mysql.Config
}

func readFile(filepath string) *Config {
  f, err := os.Open(filepath)
  if err != nil {
    panic(err)
  }
  defer f.Close()
  
  cfg := &Config{Database: mysql.NewConfig()}
  err = yaml.NewDecoder(f).Decode(cfg)
  if err != nil {
    panic(err)
  }
  return cfg
}

func main() {
  cfg := readFile("config.yml")
  mysql.Init(cfg.Database)
  // and ready to go...

  // If you want to see logging query string with values before executing
  mysql.Debug = true

  // Some examples...
  //
  // insert single row
  mysql.InsertRow("users", _json{"email": "[email protected]"})

  // Select single row
  user := mysql.First("users", _json{"email": "[email protected]"})

  // Update single row
  data  := _json{ "email": "[email protected]" }
  where := _json{ "user_id": user["id"] }
  mysql.UpdateFirst("users", data, where)

  // Delete single row
  mysql.DeleteFirst("users", _json{ "id": user["id"] })

  // more, look at the documentation...
}
Documentation

See full API for more documantation.

LICENSE

MIT

Documentation

Overview

This is a very simple and lightweight MySQL library for learning the Go programming language. It was written in my first three days of learning Go.

Please note that this library currently does not support multiple different database connections. Most microservices typically only have one database, but for projects that require multiple different database connections, this library may be updated in the future to support them.

Index

Constants

This section is empty.

Variables

View Source
var Debug = false

Set to `true` will be logging every query with values before executing.

Functions

func Delete

func Delete(
	table string,
	where map[string]interface{},
	args ...map[string]interface{},
) sql.Result

Deletes data from a specified table.

Parameters:

  • `table`: The name of the table
  • `where`: The conditions to specify which records to delete
  • `options`: Additional options, such as "order" or "limit"

Returns:

  • sql.Result: Result of the delete operation

func DeleteFirst

func DeleteFirst(
	table string,
	where map[string]interface{},
	options ...map[string]interface{},
) sql.Result

Same api with `Delete(...)` method except it will override `options["limit"]` to set 1.

func EscapeId

func EscapeId(id string, ignore_dot ...bool) string

Escapes a SQL identifier for safe use in a query.

Parameters:

  • `id`: SQL identifier a table or column name to be escaped
  • `ignore_dot`: Optional Boolean value, which when set to `true` the dot (.) character is not escaped

Returns:

  • string : the escaped identifier

Example:

EscapeId("INFORMATION_SCHEMA.COLUMNS")       // output: `INFORMATION_SCHEMA`.`COLUMNS`
EscapeId("some.weird.table.or.column", true) // output: `some.weird.table.or.column`

func Exec

func Exec(query string, values ...interface{}) sql.Result

Executes an user defined query.

Parameters:

  • `query`: the query to be executed
  • `values`: parameters to be passed to the query

Returns:

  • sql.Result: A Result summarizes an executed SQL query

func ExecQuery

func ExecQuery(query string, values ...interface{}) *sql.Rows

Executes an user defined query with values. Which is useful when user wants to use `sql.Rows.Scan(...)` method to convert datatypes.

Parameters:

  • `query`: the query to be executed
  • `values`: parameters to be passed to the query

Returns:

  • *sql.Rows: SQL rows cursor

func First

func First(
	table string,
	where map[string]interface{},
	options ...map[string]interface{},
) map[string]interface{}

Same api with `Select(...)` method except it will override `options["limit"]` to set 1 and returns a single row if found.

func Init

func Init(cfg *Config)

Initialize database connection with given configuration.

func Insert

func Insert(table string, data map[string]interface{}) sql.Result

Inserts data into a table.

Parameters:

  • `table`: The name of the table to insert into
  • `data`: A map of the column names and values to be inserted into the table

Returns:

  • sql.Result: Result of the insert statement execution

TODO: update this method to support multiple rows

func InsertRow

func InsertRow(table string, data map[string]interface{}) sql.Result

Insert a single row data into a table.

Parameters:

  • `table`: The name of the table to insert into
  • `data`: A map of the column names and values to be inserted into the table

Returns:

  • sql.Result: Result of the insert statement execution

func ParseDatetime

func ParseDatetime(value interface{}) time.Time

Parse a SQL datetime string in the format "2006-01-02 15:04:05.000" and convert to a `time.Time`.

Parameters:

  • `value`: a string representation of a date and time

Returns:

  • `time.Time`: representation of the input string. If the input string is not in the expected format, it will panic.

Example:

type _json map[string]interface{}

where := _json{ "access_token": access_token }
data  := mysql.First(oauth2.TokensTable, where, _json{
  "columns": []string{
    "user_id",
    "access_token_expires_at",
    "refresh_token_expires_at",
  },
})
if data == nil { return }
expires_at := mysql.ParseDatetime(data["access_token_expires_at"])
// code...

func ParseUint32

func ParseUint32(value interface{}) uint32

Converts a string to uint32

Parameters:

  • `value`: representation of an integer

Returns:

  • `uint32`: converted integer as uint32

func Select

func Select(
	table string,
	where map[string]interface{},
	args ...map[string]interface{},
) []map[string]interface{}

Retrieve data from specified `table` with the given `where` condition and options.

Parameters:

  • `table`: name of the table to perform the SELECT query on
  • `where`: conditions to be used in the WHERE clause of the query
  • `options`: Optional map specify additional options

Options:

  • `column`: string, specify single column to return
  • `columns`: string array for multiple columns to return
  • `order`: string, order of the results
  • `offset`: int, this option will be discarded without limit
  • `limit`: int, maximum number of results

Returns:

  • []map[string]interface{}: rows data returned by the query

Example:

type _json map[string]interface{}

where   := _json{"user_id": user_id}
options := _json{"order": "created_at DESC", "limit": 30}
rows    := mysql.Select("producst", where, optioins)

func Update

func Update(
	table string,
	data, where map[string]interface{},
	args ...map[string]interface{},
) sql.Result

Updates the data in a table with specified conditions.

Parameters:

  • `table`: The name of the table to update
  • `data`: A map of field names and new values to update in the table
  • `where`: A map of conditions to determine which rows to update in the table
  • `options`: An optional set of options to specify order and limit for the update query

Returns:

  • sql.Result: Result of the update query

func UpdateFirst

func UpdateFirst(
	table string,
	data, where map[string]interface{},
	options ...map[string]interface{},
) sql.Result

Same api with `Update(...)` method except it will override `options["limit"]` to set 1.

Types

type Config

type Config struct {
	Host     string `yaml:"host,omitempty"`
	Port     int16  `yaml:"port,omitempty"`
	Socket   string `yaml:"socket,omitempty"`
	DBName   string `yaml:"name"`
	Username string `yaml:"user"`
	Password string `yaml:"pass"`
}

func NewConfig

func NewConfig() *Config

Returns a pointer to a newly allocated `Config` struct with default values for:

  • `Host` "127.0.0.1"
  • `Port` 3306

type Error added in v0.0.4

type Error struct {
	Query      string
	Values     []interface{}
	MySQLError *m.MySQLError
}

Jump to

Keyboard shortcuts

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