inssql

package
v0.10.5 Latest Latest
Warning

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

Go to latest
Published: Dec 19, 2024 License: Apache-2.0 Imports: 7 Imported by: 0

README

SQL Package

This is a simple mockable wrapper for SQL databases. You can help extend add other sql clients here as well.

Usage in Apps

package main

import "github.com/useinsider/go-pkg/inssql"

func main() {
	sqlClient, err := inssql.Init("mysql", "root", "root", "localhost", "demo")
	if err != nil {
		panic(err)
	}

	err := sqlClient.Ping()
	if err != nil {
		panic(err)
	}
}

Usage in Tests

package main

import (
	"github.com/DATA-DOG/go-sqlmock"
	"github.com/stretchr/testify/assert"
	"github.com/useinsider/go-pkg/inssql"
	"gorm.io/gorm"
	"testing"
)

type Data struct {
	gorm.Model
	ID   int
	Name string
}

func Test(t *testing.T) {
	gormDB, sqlMock := inssql.MockGorm()

	sqlQuery := "INSERT INTO `data` (`created_at`,`updated_at`,`deleted_at`,`name`) VALUES (?,?,?,?)"

	sqlMock.ExpectBegin()
	sqlMock.
		ExpectExec(sqlQuery).
		WithArgs(
			inssql.AnyTime{}, inssql.AnyTime{}, nil, "some_name",
		).
		WillReturnResult(sqlmock.NewResult(1, 1))
	sqlMock.ExpectCommit()

	err := insert(gormDB, Data{Name: "some_name"})
	assert.NoError(t, err)

	err = sqlMock.ExpectationsWereMet()
	assert.NoError(t, err)
}

func insert(gormDB *gorm.DB, data Data) error {
	return gormDB.Create(&data).Error
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func GetClient

func GetClient() *sql.DB

GetClient returns globally cached sqlClient.

func GetGormClient

func GetGormClient() *gorm.DB

GetGormClient returns globally cached gormClient.

func Init

func Init(Driver, DBUser, DBPassword, DBHost, DBName string) (*sql.DB, error)

Init creates a client pool for sql connections. Driver must be one of these https://golang.org/s/sqldrivers.

func MockGorm

func MockGorm() (*gorm.DB, sqlmock.Sqlmock)

func MockSql

func MockSql() (*sql.DB, sqlmock.Sqlmock)

func New added in v0.10.5

func New(Driver string, DBUser string, DBPassword string, DBHost string, DBName string) (*sql.DB, error)

New creates brand new sql client

func NewGorm added in v0.10.5

func NewGorm(sqlDB *sql.DB) (*gorm.DB, error)

NewGorm wrap new sql client

func WrapWithGorm

func WrapWithGorm(sqlDB *sql.DB) (*gorm.DB, error)

WrapWithGorm connection

Types

type AnyTime

type AnyTime struct{}

func (AnyTime) Match

func (a AnyTime) Match(v driver.Value) bool

Match satisfies sqlmock.Argument interface

Jump to

Keyboard shortcuts

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