simp

package module
v0.2.4 Latest Latest
Warning

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

Go to latest
Published: Feb 10, 2021 License: MIT Imports: 7 Imported by: 0

README

simp

Simp is a simple SQL operation package. There is nothing flashy. It is a package for those who wish to run mere handwritten queries frankly.

Overview

  • Support transactions
  • Support commit and rollback
  • Support for database open and close
  • Execute query manually
  • Supported Databases.
    • MySQL
    • PostgreSQL

Description

WhiteRaven777/simp - I made this package with the desire to run SQL queries more freely. I know that there are various ORMs. However, I could not do it well because everything was too functional. When I tried treating SQL simply, I felt naturally in this form. People who use only a part of advanced ORM functionality, those who frequently perform complex queries to reduce the number of requests, this package may fit.

Installation

go get -u github.com/WhiteRaven777/simp

Documentation

API document and more examples are available here: http://godoc.org/github.com/WhiteRaven777/simp

Requirement

This package uses the following standard package.

  • database/sql
  • errors
  • sync
  • time

Usage

MySQL

package main

import (
	"fmt"
	"log"

	"github.com/WhiteRaven777/simp"
	_ "github.com/go-sql-driver/mysql"
)

func main() {
	dc := simp.DsnConf{
		UserName: "root",
		Password: "pass",
		DbName:   "sample",
		Params: map[string]string{
			"parseTime":            "true",
			"loc":                  "UTC",
			"charset":              "utf8mb4",
			"autocommit":           "false",
			"clientFoundRows":      "true",
			"allowNativePasswords": "True",
		},
	}
	
	var db *simp.DB
	if dsn, err := dc.DSN(simp.MySQL); err != nil {
		log.Fatal(err.Error())
	} else {
		if db = simp.New(simp.MySQL, dsn); db.Error() != nil {
			panic(db.Error())
		} else {
			if err = db.Ping(); err != nil {
				fmt.Println("MySQL Connect Error", db.Error().Error())
				panic(db.Error())
			} else {
				fmt.Println("*** Open MySQL Connect ***")
				db.SetConnMaxLifetime(60 * time.Second)
				db.SetMaxIdleConns(5)
			}
		}
	}
	
	// ---
	
	type User struct {
		Id   int
		Name string
	}

	defer func() {
		if err := recover(); err != nil {
			db.Rollback()
		} else {
			db.Commit()
		}
	}()
	if err := db.Begin(); err != nil {
		fmt.Println("error - Begin()", err.Error())
		panic(err)
	}

	var query string
	query = `
		INSERT INTO user (
			id,
			name
		) VALUES (
			?, ?
		), (
			?, ?
		)`

	var row int64
	if r, err := db.Exec(
		query,
		1, "Tom",
		2, "Jerry",
	); err != nil {
		fmt.Println("Insert error", err.Error())
		panic(err.Error())
	} else {
		row, _ = r.RowsAffected()
	}
	fmt.Printf("%d row(s) were inserted.\n", row)

	// ---

	query = `
		SELECT
			id,
			name
		FROM
			user`

	var users []User
	if rows, err := db.Query(query); err != nil {
		fmt.Println("Query error", err.Error())
	} else {
		var user User
		for rows.Next() {
			if err = rows.Scan(
				&user.Id,
				&user.Name,
			); err != nil {
				fmt.Println("Scan error", err.Error())
				continue
			}
			users = append(users, user)
		}
	}

	// ---

	query = `
		SELECT
			count(id)
		FROM
			user`

	var cnt int
	if err := db.QueryRow(query).Scan(&cnt); err != nil {
		fmt.Println("Query error", err.Error())
	}
}

License

Simp is licensed under the MIT

Documentation

Index

Constants

View Source
const (
	MySQL      = DriverName("mysql")
	PostgreSQL = DriverName("postgres")
)

Variables

This section is empty.

Functions

This section is empty.

Types

type DB

type DB struct {
	// contains filtered or unexported fields
}

DB is a database object.

func New

func New(dn DriverName, dsn Dsn) *DB

New returns a new *DB. If error, error is set in *DB.err. You can get *DB.err with *DB.Error ().

func (*DB) Begin

func (db *DB) Begin() error

Begin starts transaction.

func (*DB) Close

func (db *DB) Close()

Close closes database.

func (*DB) Commit

func (db *DB) Commit() error

Commit commits the transacrion. Begin needs to be executed before this method is executed.

func (*DB) DB added in v0.2.4

func (db *DB) DB() (ret *sql.DB)

DB returns a *sql.DB bound to the DB.

func (*DB) Error

func (db *DB) Error() error

The error returns *DB.err.

func (*DB) Exec

func (db *DB) Exec(query string, args ...interface{}) (ret sql.Result, err error)

Exec executes a prepared statement with the specified arguments. And this method returns a Result summarizing the effect of the statement.

func (*DB) Ping added in v0.2.0

func (db *DB) Ping() error

Ping will check if it can connect to the specified database.

func (*DB) Prepare

func (db *DB) Prepare(query string, args ...interface{}) (*sql.Stmt, error)

Prepare creates a prepared statement for later queries or executions.

func (*DB) Query

func (db *DB) Query(query string, args ...interface{}) (ret *sql.Rows, err error)

The query executes a prepared query statement with the specified arguments and returns the query result as *sql.Rows.

func (*DB) QueryRow

func (db *DB) QueryRow(query string, args ...interface{}) (ret *sql.Row)

QueryRow executes a prepared query statement with the specified arguments. Scans the first selected line and returns it as *sql.Row. It will be destroyed after that.

func (*DB) Rollback

func (db *DB) Rollback() error

Rollback rolls back transaction. Begin needs to be executed before this method is executed.

func (*DB) SetConnMaxLifetime

func (db *DB) SetConnMaxLifetime(d time.Duration)

SetConnMaxLifetime sets the maximum amount of time a connection may be reused. Expired connections may be closed lazily before reuse. If d <= 0, connections are reused forever.

func (*DB) SetMaxIdleConns

func (db *DB) SetMaxIdleConns(n int)

SetMaxIdleConns sets the maximum number of connections in the idle connection pool. If MaxOpenConns is greater than 0 but less than the new MaxIdleConns then the new MaxIdleConns will be reduced to match the MaxOpenConns limit If n <= 0, no idle connections are retained.

func (*DB) SetMaxOpenConns

func (db *DB) SetMaxOpenConns(n int)

SetMaxOpenConns sets the maximum number of open connections to the database. If MaxIdleConns is greater than 0 and the new MaxOpenConns is less than MaxIdleConns, then MaxIdleConns will be reduced to match the new MaxOpenConns limit If n <= 0, then there is no limit on the number of open connections. The default is 0 (unlimited).

type DriverName added in v0.2.0

type DriverName string

func (DriverName) String added in v0.2.0

func (dn DriverName) String() string

String returns the converted string from of DriverName.

type Dsn added in v0.2.0

type Dsn string

func (Dsn) String added in v0.2.0

func (dsn Dsn) String() string

String returns the converted string from of Dsn.

type DsnConf added in v0.2.0

type DsnConf struct {
	UserName string
	Password string
	Protocol string
	Address  string
	Port     int
	DbName   string
	Params   map[string]string
}

func (DsnConf) DSN added in v0.2.0

func (dc DsnConf) DSN(dn DriverName) (dsn Dsn, err error)

DSN returns Dsn based on DsnConf and DriverName.

Directories

Path Synopsis
sample

Jump to

Keyboard shortcuts

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