sqladapter

package module
v0.0.0-...-2ce1dc3 Latest Latest
Warning

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

Go to latest
Published: Aug 16, 2022 License: MIT Imports: 8 Imported by: 0

README

go-sql-adapter

Go Reference license Build Status Code Coverage Scrutinizer Code Quality

General

go-sql-adapter it's a muti DB Engine adapter over the GO database/sql package. It provides a set of standard error codes, providing abstraction from the implemented DB engine, allowing change the DB just modifying the configuration and without need adjust or modify the source code. Besides that, provides a very limited cross-engine sql translator.

Another feature included in the package it's the automatic logging of the executed sentences and it's elapsed time, trougth the implementation of the Logger interface: github.com/cdleo/go-commons/logger/logger.go

This package provides a nolog and a basic implementation of that interface, but if you need a more customized and powerful implementation, you can use the following one: github.com/cdleo/go-zla

Supported Engines Currently, the next set of engines are supported:

Usage This example program shows the initialization and the use at basic level:

package sqladapter_test

import (
	"fmt"

	"os"
	"strconv"

	adapter "github.com/cdleo/go-sql-adapter"
	"github.com/cdleo/go-sql-adapter/engines"
	"github.com/cdleo/go-sql-adapter/loggers"
	"github.com/cdleo/go-sql-adapter/translators"
)

type People struct {
	Id       int    `db:"id"`
	Nombre   string `db:"firstname"`
	Apellido string `db:"lastname"`
}

func Example_sqlAdapter() {

	connector := engines.NewSqlite3Connector(":memory:")
	translator := translators.NewNoopTranslator()
	stdoutLogger := loggers.NewBasicLogger()
	sqlAdapter := adapter.NewSQLAdapter(connector, translator, stdoutLogger)

	db, err := sqlAdapter.Open()
	if err != nil {
		fmt.Println("Unable to connect to DB")
		os.Exit(1)
	}
	defer db.Close()

	_, err = db.Exec("CREATE TABLE IF NOT EXISTS people (id INTEGER PRIMARY KEY, firstname TEXT, lastname TEXT)")
	if err != nil {
		fmt.Printf("Unable to execute statement %v\n", err)
		os.Exit(1)
	}

	stmt, err := db.Prepare("INSERT INTO people (firstname, lastname) VALUES (?, ?)")
	if err != nil {
		fmt.Printf("Unable to prepare statement %v\n", err)
		os.Exit(1)
	}
	_, err = stmt.Exec("Gene", "Kranz")
	if err != nil {
		fmt.Printf("Unable to exec statement %v\n", err)
		os.Exit(1)
	}

	rows, err := db.Query("SELECT id, firstname, lastname FROM people")
	if err != nil {
		fmt.Printf("Unable to query data %v\n", err)
		os.Exit(1)
	}

	var p People
	for rows.Next() {
		_ = rows.Scan(&p.Id, &p.Nombre, &p.Apellido)
		fmt.Println(strconv.Itoa(p.Id) + ": " + p.Nombre + " " + p.Apellido)
	}

	// Output:
	// 1: Gene Kranz
}

Sample

You can find a sample of the use of go-sql-adapter project HERE

Contributing

Comments, suggestions and/or recommendations are always welcomed. Please check the Contributing Guide to learn how to get started contributing.

Documentation

Overview

Example (SqlAdapter)
package main

import (
	"fmt"

	"os"
	"strconv"

	adapter "github.com/cdleo/go-sql-adapter"
	"github.com/cdleo/go-sql-adapter/engines"
	"github.com/cdleo/go-sql-adapter/loggers"
	"github.com/cdleo/go-sql-adapter/translators"
)

type People struct {
	Id       int    `db:"id"`
	Nombre   string `db:"firstname"`
	Apellido string `db:"lastname"`
}

func main() {

	connector := engines.NewSqlite3Connector(":memory:")
	translator := translators.NewNoopTranslator()
	stdoutLogger := loggers.NewBasicLogger()
	//stdoutLogger.SetLogLevel(logger.LogLevel_Trace.String())
	sqlAdapter := adapter.NewSQLAdapter(connector, translator, stdoutLogger)

	db, err := sqlAdapter.Open()
	if err != nil {
		fmt.Println("Unable to connect to DB")
		os.Exit(1)
	}
	defer db.Close()

	_, err = db.Exec("CREATE TABLE IF NOT EXISTS people (id INTEGER PRIMARY KEY, firstname TEXT, lastname TEXT)")
	if err != nil {
		fmt.Printf("Unable to execute statement %v\n", err)
		os.Exit(1)
	}

	stmt, err := db.Prepare("INSERT INTO people (firstname, lastname) VALUES (?, ?)")
	if err != nil {
		fmt.Printf("Unable to prepare statement %v\n", err)
		os.Exit(1)
	}
	_, err = stmt.Exec("Gene", "Kranz")
	if err != nil {
		fmt.Printf("Unable to exec statement %v\n", err)
		os.Exit(1)
	}

	rows, err := db.Query("SELECT id, firstname, lastname FROM people")
	if err != nil {
		fmt.Printf("Unable to query data %v\n", err)
		os.Exit(1)
	}

	var p People
	for rows.Next() {
		_ = rows.Scan(&p.Id, &p.Nombre, &p.Apellido)
		fmt.Println(strconv.Itoa(p.Id) + ": " + p.Nombre + " " + p.Apellido)
	}

}
Output:

1: Gene Kranz

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func NewSQLAdapter

func NewSQLAdapter(connector SQLEngineConnector, translator SQLSyntaxTranslator, logger logger.Logger) *sqlAdapter

func Register

func Register(connector SQLEngineConnector, translator SQLSyntaxTranslator, logger logger.Logger)

Types

type MockSQLEngineConnector

type MockSQLEngineConnector interface {
	SQLEngineConnector

	PatchBegin(err error)
	PatchCommit(err error)
	PatchRollback(err error)

	PatchExec(query string, err error, args ...driver.Value)
	PatchQuery(query string, columns []string, values []driver.Value, err error, args ...driver.Value)
	PatchQueryRow(query string, result map[string]string, err error)
}

type SQLEngineConnector

type SQLEngineConnector interface {
	Open() (*sql.DB, error)
	DriverName() string
	Driver() driver.Driver
	ErrorHandler(err error) error
}

type SQLSyntax

type SQLSyntax int
const (
	SQLSyntax_Oracle SQLSyntax = iota
	SQLSyntax_PostgreSQL
	SQLSyntax_SQLite3
)

type SQLSyntaxTranslator

type SQLSyntaxTranslator interface {
	Translate(query string) string
}

Directories

Path Synopsis
mocks
Package translatorsMocks is a generated GoMock package.
Package translatorsMocks is a generated GoMock package.

Jump to

Keyboard shortcuts

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