orm

package module
v0.0.0-...-6945674 Latest Latest
Warning

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

Go to latest
Published: Jan 11, 2023 License: MIT Imports: 13 Imported by: 0

README

ORM

Documentation License Build Status Coverage Go Report Card

The package facilitates execution of SQL scripts generated by prana. Also it provides a query builder and object relation mapper. Note that it is in BETA. We may introduce breaking changes until we reach version 1.0.

ORM

Installation

$ go get -u github.com/phogolabs/orm

Getting Started

Let's first import all required packages:

import (
  "github.com/phogolabs/orm"
)

and then establish the connection:

gateway, err := orm.Open("sqlite3", "example.db", orm.WithRoutine(routine.Statement))
if err != nil {
 return err
}

SQL Migrations

You can execute the migration generated by prana. For that you have to use either embed package or os package.

if err := gateway.Migrate(resource); err != nil {
	return err
}

SQL Queries

The package provides a way to work with embeddable SQL scripts. It understands predefined files with SQL Scripts.

It executes them as standard SQL queries. Let's define a SQL routines named insert-user and select-all-users:

-- name: insert-user
INSERT INTO users (id, first_name, last_name)
VALUES (:id, :first_name, :last_name);

-- named: select-all-users
SELECT * FROM users;

Then you can execute the desired script by just passing its name:

routine := orm.Routine("select-all-users")
// execute the routine
_, err = gateway.All(context.TODO(), routine, &users)
routine := orm.Routine("insert-user", &user)
// execute the routine
_, err = gateway.Exec(context.TODO(), routine)

Also you can execute raw SQL Scripts from your code:

query := orm.Query("SELECT * FROM users WHERE id = ?", 5432)
// fetch the records as a slice of users
rows, err := gateway.Only(context.TODO(), query, &user)

Example

You can check our Getting Started Example.

For more information, how you can change the default behavior you can read the help documentation by executing:

Contributing

We are open for any contributions. Just fork the project.

logo made by Free Pik

Documentation

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// SQL represents an SQL command
	Query = sql.Query
	// Routine represents an SQL routine
	Routine = sql.Routine
)
View Source
var (
	// NewDelete creates a Mutation that deletes the entity with given primary key.
	NewDelete = sql.NewDelete

	// NewInsert creates a Mutation that will save the entity src into the db
	NewInsert = sql.NewInsert

	// NewUpdate creates a Mutation that updates the entity into the db
	NewUpdate = sql.NewUpdate
)

Functions

func IsConstraintViolation

func IsConstraintViolation(err error) bool

IsConstraintViolation returns a boolean indicating whether the error is a constraint failure.

func IsNotFound

func IsNotFound(err error) bool

IsNotFound returns a boolean indicating whether the error is a not found error.

func IsNotLoaded

func IsNotLoaded(err error) bool

IsNotLoaded returns a boolean indicating whether the error is a not loaded error.

func IsNotSingular

func IsNotSingular(err error) bool

IsNotSingular returns a boolean indicating whether the error is a not singular error.

func MaskNotFound

func MaskNotFound(err error) error

MaskNotFound masks nor found error.

Types

type ConstraintError

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

ConstraintError returns when trying to create/update one or more entities and one or more of their constraints failed. For example, violation of edge or field uniqueness.

func (ConstraintError) Error

func (e ConstraintError) Error() string

Error implements the error interface.

func (ConstraintError) Name

func (e ConstraintError) Name() string

Name returns the constraint name

func (*ConstraintError) Unwrap

func (e *ConstraintError) Unwrap() error

Unwrap implements the errors.Wrapper interface.

type FileSystem

type FileSystem = sql.FileSystem

FileSystem represents the SQL filesystem

type Gateway

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

Gateway is connected to a database and can executes SQL queries against it.

func Connect

func Connect(url string, opts ...Option) (*Gateway, error)

Connect creates a new gateway connecto to the provided URL.

func Open

func Open(name, source string, opts ...Option) (*Gateway, error)

Open creates a new gateway connected to the provided source.

func (*Gateway) All

func (g *Gateway) All(ctx context.Context, q sql.Querier, v interface{}) error

All executes the query and returns a list of entities.

func (*Gateway) Begin

func (g *Gateway) Begin(ctx context.Context) (*GatewayTx, error)

Begin begins a transaction and returns an *Tx

func (*Gateway) Close

func (g *Gateway) Close() error

Close closes the connection to the database.

func (*Gateway) Dialect

func (g *Gateway) Dialect() string

Dialect returns the driver's dialect

func (*Gateway) Exec

func (g *Gateway) Exec(ctx context.Context, q sql.Querier) (sql.Result, error)

Exec executes a query that doesn't return rows. For example, in SQL, INSERT or UPDATE. It scans the result into the pointer v. In SQL, you it's usually sql.Result.

Example
package main

import (
	"context"

	"github.com/phogolabs/orm"
	"github.com/phogolabs/orm/dialect/sql"
)

func main() {
	gateway, err := orm.Open("sqlite3", "example.db")
	if err != nil {
		panic(err)
	}

	query :=
		sql.Insert("users").
			Columns("first_name", "last_name").
			Values("John", "Doe").
			Returning("id")

	if _, err := gateway.Exec(context.TODO(), query); err != nil {
		panic(err)
	}
}
Output:

func (*Gateway) First

func (g *Gateway) First(ctx context.Context, q sql.Querier, v interface{}) error

First returns the first entity in the query. Returns *NotFoundError when no records were found.

Example
gateway, err := orm.Open("sqlite3", "example.db")
if err != nil {
	panic(err)
}

user := &User{}
query := orm.Query("SELECT * FROM users ORDER BY created_at")

if err := gateway.First(context.TODO(), query, user); err != nil {
	panic(err)
}
Output:

func (*Gateway) Migrate

func (g *Gateway) Migrate(storage FileSystem) error

Migrate runs all pending migration

func (*Gateway) Only

func (g *Gateway) Only(ctx context.Context, q sql.Querier, v interface{}) error

Only returns the only entity in the query, returns an error if not exactly one entity was returned.

Example
gateway, err := orm.Open("sqlite3", "example.db")
if err != nil {
	panic(err)
}

user := &User{}
query := orm.Query("SELECT * FROM users WHERE id = ?", "007")

if err := gateway.Only(context.TODO(), query, user); err != nil {
	panic(err)
}
Output:

func (*Gateway) Ping

func (g *Gateway) Ping(ctx context.Context) error

Ping pins the underlying database

func (*Gateway) Query

func (g *Gateway) Query(ctx context.Context, q sql.Querier) (*sql.Rows, error)

Query executes a query that returns rows, typically a SELECT in SQL. It scans the result into the pointer v. In SQL, you it's usually *sql.Rows.

func (*Gateway) RunInTx

func (g *Gateway) RunInTx(ctx context.Context, fn RunTxFunc) error

RunInTx runs a callback function within a transaction. It commits the transaction if succeeds, otherwise rollbacks.

type GatewayTx

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

GatewayTx represents a gateway in transaction

func (*GatewayTx) All

func (g *GatewayTx) All(ctx context.Context, q sql.Querier, v interface{}) error

All executes the query and returns a list of entities.

func (*GatewayTx) Commit

func (g *GatewayTx) Commit() error

Commit commits the transaction

func (*GatewayTx) Exec

func (g *GatewayTx) Exec(ctx context.Context, q sql.Querier) (sql.Result, error)

Exec executes a query that doesn't return rows. For example, in SQL, INSERT or UPDATE. It scans the result into the pointer v. In SQL, you it's usually sql.Result.

func (*GatewayTx) First

func (g *GatewayTx) First(ctx context.Context, q sql.Querier, v interface{}) error

First returns the first entity in the query. Returns *NotFoundError when no user was found.

func (*GatewayTx) Only

func (g *GatewayTx) Only(ctx context.Context, q sql.Querier, v interface{}) error

Only returns the only entity in the query, returns an error if not exactly one entity was returned.

func (*GatewayTx) Query

func (g *GatewayTx) Query(ctx context.Context, q sql.Querier) (*sql.Rows, error)

Query executes a query that returns rows, typically a SELECT in SQL. It scans the result into the pointer v. In SQL, you it's usually *sql.Rows.

func (*GatewayTx) Rollback

func (g *GatewayTx) Rollback() error

Rollback rollbacks the transaction

type NamedArg

type NamedArg = sql.NamedArg

A NamedArg is a named argument. NamedArg values may be used as arguments to Query or Exec and bind to the corresponding named parameter in the SQL statement.

type NamedQuery

type NamedQuery = sql.NamedQuery

NameQuery is a named query that uses named arguments

type NotFoundError

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

NotFoundError returns when trying to fetch a specific entity and it was not found in the database.

func (*NotFoundError) Error

func (e *NotFoundError) Error() string

Error implements the error interface.

type NotLoadedError

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

NotLoadedError returns when trying to get a node that was not loaded by the query.

func (*NotLoadedError) Error

func (e *NotLoadedError) Error() string

Error implements the error interface.

type NotSingularError

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

NotSingularError returns when trying to fetch a singular entity and more then one was found in the database.

func (*NotSingularError) Error

func (e *NotSingularError) Error() string

Error implements the error interface.

type Option

type Option interface {
	Apply(*Gateway) error
}

Option represents a Gateway option

func WithConnMaxLifetime

func WithConnMaxLifetime(duration time.Duration) Option

WithConnMaxLifetime 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 WithLogger

func WithLogger(logger dialect.Logger) Option

WithLogger sets the logger

func WithMaxIdleConns

func WithMaxIdleConns(value int) Option

WithMaxIdleConns 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.

The default max idle connections is currently 2. This may change in a future release.

func WithMaxOpenConns

func WithMaxOpenConns(value int) Option

WithMaxOpenConns 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).

func WithRoutine

func WithRoutine(source FileSystem) Option

WithRoutine creates the gateway with a given routine

type OptionFunc

type OptionFunc func(*Gateway) error

OptionFunc represents a function that can be used to set option

func (OptionFunc) Apply

func (fn OptionFunc) Apply(gateway *Gateway) error

Apply applies the option

type Querier

type Querier interface {
	// All executes the query and returns a list of entities.
	All(ctx context.Context, q sql.Querier, v interface{}) error

	// Only returns the only entity in the query, returns an error if not
	// exactly one entity was returned.
	Only(ctx context.Context, q sql.Querier, v interface{}) error

	// First returns the first entity in the query. Returns *NotFoundError
	// when no records were found.
	First(ctx context.Context, q sql.Querier, v interface{}) error

	// Query executes a query that returns rows, typically a SELECT in SQL.
	// It scans the result into the pointer v. In SQL, you it's usually *sql.Rows.
	Query(ctx context.Context, q sql.Querier) (*sql.Rows, error)

	// Exec executes a query that doesn't return rows. For example, in SQL, INSERT
	// or UPDATE.  It scans the result into the pointer v. In SQL, you it's usually
	// sql.Result.
	Exec(ctx context.Context, q sql.Querier) (sql.Result, error)
}

Querier executes the commands

type RoutineQuery

type RoutineQuery = sql.RoutineQuery

RoutineQuery represents a named routine

type RunTxFunc

type RunTxFunc func(gateway *GatewayTx) error

RunTxFunc is a transaction function

Directories

Path Synopsis
sql
Package sql provides wrappers around the standard database/sql package to allow the generated code to interact with a statically-typed API.
Package sql provides wrappers around the standard database/sql package to allow the generated code to interact with a statically-typed API.
example
database
Package database contains an repository of database schema ” Auto-generated at Fri, 12 Apr 2019 13:09:42 CEST
Package database contains an repository of database schema ” Auto-generated at Fri, 12 Apr 2019 13:09:42 CEST

Jump to

Keyboard shortcuts

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