machgo

package module
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Mar 20, 2019 License: GPL-3.0 Imports: 13 Imported by: 0

README

machgo

Build Status Coverage Status GoDoc

machgo is a ORM-ish database library for go.

Because I am chronically lazy, this readme is a WIP.

Check out the godocs!

Example Usage

Simple usage

Let's say you have the following table:

CREATE TABLE images (
  id bigint PRIMARY KEY,
  post_id bigint NOT NULL,
  filename text,
  mime_type text,
  created date DEFAULT now(),
  updated date DEFAULT now()
);

Then you might create the following object representation:

import (
    "github.com/daihasso/machgo/database"
)

type Image struct {
  PostID int64 `db:"post_id"`

  MimeType string `db:"mime_type"`
  OriginalFileName string `db:"file_name"`
}

Next you might want to create a database connection:

import (
    "sync"

    "github.com/daihasso/machgo/pool"
    "github.com/daihasso/machgo/pool/config"
)

var MyDBConn *pool.ConnectionPool

func init() {
    once.Do(func() {
        MyDBConn, err := config.PostgresPool(
            config.Username("mypostgresuser"),
            config.Password("mysecretpassword"),
            config.Host("localhost"),
            config.Port(5432),
            config.DatabaseName("mycooldatabase"),
        )
        if err != nil {
            panic(err)
        }

        // This lets us share a connection across further machgo calls.
        SetGlobalConnectionPool(MyDBConn)
    })
}

And to retrieve single image you might do:


import(
    "github.com/daihasso/machgo/pool/ses"
)

func getImage(id int64) *Image {
    session, err := sess.NewSession()
    if err != nil {
        panic(err)
    }
    result := &Image{}
    err := session.GetObject(result, id)
    if err != nil {
        panic(err)
    }

    return result
}
More advanced usage

Let's say you want many images per post so you expand the previous table by using a lookup table:

CREATE TABLE images (
  id bigint PRIMARY KEY,
  filename text,
  mime_type text,
  created date DEFAULT now(),
  updated date DEFAULT now()
);

CREATE TABLE post_images (
  post_id bigint NOT NULL,
  image_id bigint REFERENCES images (id) ON DELETE CASCADE,
  created timestamp with time zone DEFAULT now(),
  updated timestamp with time zone DEFAULT now(),
  PRIMARY KEY(post_id, image_id)
);

Then you might create the following object representation:

// post_image.go
type PostImage struct {
    machgo.DefaultCompositeDBObject

    ID int64 `db:"post_id"`
    ImageID int64 `db:"image_id"`
}

func (self *PostImage) GetTableName() string {
    return "post_images"
}

// GetColumnNames is required for composite objects to define what columns
// matter.
func (s *PostImage) GetColumnNames() []string {
    return []string{"post_id", "image_id"}
}

// image_object.go
type Image struct {
    database.DefaultDBObject

    // Defining the db value as 'foreign' here lets the machgo know that it
    // needs to pull the column from the table specified in the dbforeign tag
    // value.
    PostID int64 `db:"post_id,foreign" dbforeign:"post_images"`

    MimeType string `db:"mime_type"`
    OriginalFileName string `db:"file_name"`
}

func (self *Image) GetTableName() string {
    return "images"
}

// This function defines what relationships with other tables or objects
func (self *Image) Relationships() []machgo.Relationship {
    return []machgo.Relationship{
        machgo.Relationship{
            SelfObject: self,
            SelfColumn:   "id",
            TargetObject: &ImagePost{},
            TargetColumn: "image_id",
        },
    }
}

All the same actions as above will still work the same but in order to get images for a post (or set of posts).

import (
  "github.com/daihasso/machgo/pool/session"
  . "github.com/daihasso/machgo/dsl/dot"
)

func findImagesForPost(postIDs []string) {
    image := &Image{}
    postImage := &PostImage{}

    session, err := sess.NewSession()
    if err != nil {
        panic(err)
    }
    qs := session.Query(postImage, image).SelectObject(image).Where(
        Eq(ObjectColumn(postImage, "image_id"), ObjectColumn(image, "id")),
        In(ObjectColumn(postImage, "post_id"), Const(postIDs...)),
    )

    results, err := qs.Results()
    if err != nil {
        panic(err)
    }

    images := make([]*Image, 0)
    err = results.WriteAllTo(&images)
    if err != nil {
      panic(err)
    }

    return images
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func SnakeToUpperCamel

func SnakeToUpperCamel(raw string) string

SnakeToUpperCamel converts a string in snake_case to a string in UpperCamelCase.

Types

type AliasObjValMap

type AliasObjValMap map[string]*reflect.Value

type AliasedObjects

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

func NewAliasedObjects

func NewAliasedObjects(objects ...Object) (*AliasedObjects, error)

func NewAliasedObjectsFromExisting

func NewAliasedObjectsFromExisting(
	aliasedObjectMap map[string]Object,
) (*AliasedObjects, error)

NewAliasedObjectsFromExisting takes an oldfashion map-style aliased object and creates a new AliasedObjects struct.

func (AliasedObjects) ObjectAlias

func (self AliasedObjects) ObjectAlias(
	object Object,
) (string, error)

func (AliasedObjects) ObjectIsAliased

func (self AliasedObjects) ObjectIsAliased(object Object) bool

func (AliasedObjects) TableForAlias

func (self AliasedObjects) TableForAlias(alias string) string

func (AliasedObjects) TypeForAlias

func (self AliasedObjects) TypeForAlias(alias string) *reflect.Type

type ColumnAlias

type ColumnAlias struct {
	TableAlias,
	ColumnName string
}

func ColumnAliasFromString

func ColumnAliasFromString(rawColumn string) (*ColumnAlias, bool)

func (ColumnAlias) String

func (self ColumnAlias) String() string

type ColumnAliasField

type ColumnAliasField struct {
	ColumnAlias
	FieldName string
}

type CompositeKey

type CompositeKey interface {
	GetColumnNames() []string
	SetColumnNames([]string)
}

CompositeKey is a composite key made up of one or more columns.

type CompositeObject

type CompositeObject interface {
	Object
	CompositeKey
}

CompositeObject is an object which has an CompositeAttribute.

type DefaultAttributes

type DefaultAttributes interface {
	Update()
	Init()
}

DefaultAttributes are a set of default attributes for an object.

type DefaultCompositeDBObject

type DefaultCompositeDBObject struct {
	JSONExportedDefaultAttributes
	DefaultDiffable
	// contains filtered or unexported fields
}

DefaultCompositeDBObject is a basic object with standard implementations.

func (*DefaultCompositeDBObject) GetColumnNames

func (bo *DefaultCompositeDBObject) GetColumnNames() []string

GetColumnNames retrieves the database column names for the composite key.

func (DefaultCompositeDBObject) IsSaved

func (bo DefaultCompositeDBObject) IsSaved() bool

IsSaved will return a bool encapsulating wether the object has been saved or not.

func (*DefaultCompositeDBObject) PostInsertActions

func (bo *DefaultCompositeDBObject) PostInsertActions() (err error)

PostInsertActions is a NOOP for default UUID object.

func (*DefaultCompositeDBObject) PreInsertActions

func (bo *DefaultCompositeDBObject) PreInsertActions() (err error)

PreInsertActions will initialize the default attributes.

func (*DefaultCompositeDBObject) SetColumnNames

func (bo *DefaultCompositeDBObject) SetColumnNames(columns []string)

SetColumnNames retrieves the database column names for the composite key.

func (*DefaultCompositeDBObject) SetSaved

func (bo *DefaultCompositeDBObject) SetSaved(saved bool)

SetSaved modifies the saved status of the object.

type DefaultDBObject

type DefaultDBObject struct {
	JSONExportedDefaultAttributes
	DefaultDiffable
	ID *IntID `json:"id" db:"id"`
	// contains filtered or unexported fields
}

DefaultDBObject is a basic object with standard implementations.

func (DefaultDBObject) GetID

func (bo DefaultDBObject) GetID() ID

GetID retrieves the ID.

func (DefaultDBObject) GetIDColumn

func (bo DefaultDBObject) GetIDColumn() string

GetIDColumn returns the column the ID lives in.

func (DefaultDBObject) IDIsSet

func (bo DefaultDBObject) IDIsSet() bool

IDIsSet will check if the ID is set and return true if it has been set.

func (*DefaultDBObject) IsSaved

func (bo *DefaultDBObject) IsSaved() bool

IsSaved will return a bool encapsulating wether the object has been saved or not.

func (*DefaultDBObject) NewID

func (bo *DefaultDBObject) NewID() ID

NewID returns nil because it can't generate a new ID without seeing existing IDs.

func (*DefaultDBObject) PostInsertActions

func (bo *DefaultDBObject) PostInsertActions() (err error)

PostInsertActions is a NOOP for default UUID object.

func (*DefaultDBObject) PreInsertActions

func (bo *DefaultDBObject) PreInsertActions() (err error)

PreInsertActions will initialize the default attributes.

func (*DefaultDBObject) SetID

func (bo *DefaultDBObject) SetID(id ID) error

SetID sets the ID.

func (*DefaultDBObject) SetSaved

func (bo *DefaultDBObject) SetSaved(saved bool)

SetSaved sets the saved status for the object.

type DefaultDiffable

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

DefaultDiffable is the basic standard implementation of a diffable.

func (DefaultDiffable) GetLastSavedValue

func (dd DefaultDiffable) GetLastSavedValue(name string) interface{}

GetLastSavedValue will get a given value from the last values map.

func (*DefaultDiffable) SetLastSavedValue

func (dd *DefaultDiffable) SetLastSavedValue(name string, val interface{})

SetLastSavedValue will set a given value in the last values map.

type Diffable

type Diffable interface {
	GetLastSavedValue(string) interface{}
	SetLastSavedValue(string, interface{})
}

Diffable allows something to track changes to the item before saving to optimize inserts.

type ID

ID is a type of attribute for an object that implements some conversion methods. Required conversions:

  • From/To database
  • To string
  • From/To JSON

type IDAttribute

type IDAttribute interface {
	SetID(ID) error
	GetID() ID
	IDIsSet() bool
	NewID() ID
	GetIDColumn() string
}

IDAttribute is an interface for doing common ID operations.

type IDObject

type IDObject interface {
	Object
	IDAttribute
}

IDObject is an object which has an IDAttribute.

type IntID

type IntID struct {
	ID int64
}

IntID is an object with an integer ID.

func (IntID) MarshalJSON

func (ii IntID) MarshalJSON() ([]byte, error)

MarshalJSON returns the JSON representation.

func (*IntID) Scan

func (ii *IntID) Scan(src interface{}) error

Scan reads data from the database into an IntID.

func (IntID) String

func (ii IntID) String() string

String returns the string representation.

func (IntID) UnmarshalJSON

func (ii IntID) UnmarshalJSON(source []byte) error

UnmarshalJSON returns the JSON representation.

func (IntID) Value

func (ii IntID) Value() (driver.Value, error)

Value returns the database value for the IntID.

type JSONExportedDefaultAttributes

type JSONExportedDefaultAttributes struct {
	Created types.Timestamp `db:"created" json:"created,omitempty"`
	Updated types.Timestamp `db:"updated" json:"updated,omitempty"`
}

JSONExportedDefaultAttributes is a set of sensible default attributes that are serialized into json.

func (*JSONExportedDefaultAttributes) Init

Init will initialize the created & updated time.

func (*JSONExportedDefaultAttributes) Update

func (j *JSONExportedDefaultAttributes) Update()

Update will initialize the updated time.

type Object

type Object interface {
	GetTableName() string
	IsSaved() bool
	SetSaved(bool)

	PreInsertActions() error
	PostInsertActions() error
}

Object is a database object able to be written to the DB.

type QueryResult

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

QueryResult is a set of all the results from a query in objects.

func NewQueryResult

func NewQueryResult(
	rows *sqlx.Rows,
	aliasedObjects *AliasedObjects,
	columnAliasFields []ColumnAliasField,
) (*QueryResult, error)

func (QueryResult) WriteTo

func (self QueryResult) WriteTo(objects ...interface{}) error

type QueryResults

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

func NewQueryResults

func NewQueryResults(
	tx *sqlx.Tx,
	rows *sqlx.Rows,
	aliasedObjects *AliasedObjects,
	typeBSFieldMap map[reflect.Type]*refl.GroupedFieldsWithBS,
) *QueryResults

func (*QueryResults) Err

func (self *QueryResults) Err() error

func (*QueryResults) GetResult

func (self *QueryResults) GetResult() *QueryResult

func (*QueryResults) Next

func (self *QueryResults) Next() bool

func (*QueryResults) WriteAllTo

func (self *QueryResults) WriteAllTo(
	objectSlices ...interface{},
) (retErr error)

type Relationship

type Relationship struct {
	SelfObject,
	TargetObject Object
	SelfColumn,
	TargetColumn string
}

Relationship is a representation of how two objects join together.

func (Relationship) Invert

func (self Relationship) Invert() *Relationship

Invert takes the relationship and swaps the self with the target. This essentially has the effect of changing:

foo.bar=baz.fizz

Into:

baz.fizz=foo.bar

func (Relationship) SelfTable

func (self Relationship) SelfTable() string

func (Relationship) TargetTable

func (self Relationship) TargetTable() string

type Relationshipable

type Relationshipable interface {
	Relationships() []Relationship
}

Relationshipable is a type that has at least on relationship.

type SimpleCompositeKey

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

SimpleCompositeKey is a simple composite key implementation.

func (SimpleCompositeKey) GetColumnNames

func (sck SimpleCompositeKey) GetColumnNames() []string

GetColumnNames retrieves the database column names for the composite key.

func (*SimpleCompositeKey) SetColumnNames

func (sck *SimpleCompositeKey) SetColumnNames(columns []string)

SetColumnNames retrieves the database column names for the composite key.

type UnexportedDefaultAttributes

type UnexportedDefaultAttributes struct {
	Created types.Timestamp `db:"created" json:"-"`
	Updated types.Timestamp `db:"updated" json:"-"`
}

UnexportedDefaultAttributes is a set of sensible default attributes for an object that are not exported when serialized.

func (*UnexportedDefaultAttributes) Init

func (j *UnexportedDefaultAttributes) Init()

Init will initialize the created time and updated time.

func (*UnexportedDefaultAttributes) Update

func (j *UnexportedDefaultAttributes) Update()

Update will update the updated time.

Directories

Path Synopsis
dsl
dot
Package dot contains mostly a set of shims for dot importing machgo DSL.
Package dot contains mostly a set of shims for dot importing machgo DSL.

Jump to

Keyboard shortcuts

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