pq

package module
v0.9.3 Latest Latest
Warning

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

Go to latest
Published: Apr 1, 2020 License: Apache-2.0 Imports: 18 Imported by: 0

README

Neuron Logo

Neuron Postgres Go Report Card GoDoc Build Status License

neuron-pq is the github.com/neuronlabs/neuron-core postgres repository driver.

What is Neuron-PQ

Neuron-PQ is the PostgreSQL ORM Repository driver for the github.com/neuronlabs/neuron-core.

Installation

go get -u github.com/neuronlabs/neuron-pq

Neuron-pq is the extension for the Neuron-Core requires github.com/neuronlabs/neuron-core root package.

QuickStart

  1. Prepare or read the Config Repository - github.com/neuronlabs/neuron-core/config by creating structure or by using viper github.com/spf13/viper and create the neuron controller The DriverName variable (driver_name in config) should be set to pq in order to match the neuron-pq Repository and Factory
 var controllerConfig *config.Controller

 cfg := &config.Repository{
    DriverName: "pq",
    Host: "localhost",
    Port: 5432,
    DBName:"dbname",
    ...
 }

 controllerConfig.Repositories = map[string]*config.Repository{
    "mypostgres": cfg,    
    // Add more custom repository configurations for different models if you 
    // need different connection or credentials
}


... 

c, err = controller.New(cfg)
...

  1. Register the neuron-pq repository for you application by initializing the repository package
import (
    _ "github.com/neuronlabs/neuron-pq"
)

  1. Define the models
// User
type User struct {
    ID      int     `neuron:"type=primary"`
    Name    string  `neuron:"type=attr"`
    Surname string  `neuron:"type=attr"`
    Cars    []*Car  `neuron:"type=relation"`
}
// define the repository if any other would be used

// RepositoryName returns the name of the repository used by the User model
func (u *User) RepositoryName() string {
    return "mypostgres"
}

// Car
type Car struct {
    ID              int     `neuron:"type=primary"`
    RegisterNumber  string  `neuron:"type=attr" db="unique"`
    Owner           *User   `neuron:"type=relation;foreign=OwnerID"`
    OwnerID         string  `neuron:"type=foreign" db="notnull"`
}

// RepositoryName returns the name of the repository used by the Car model
func (c *Car) RepositoryName() string {
    return "mypostgres"
}
  1. Register the models
if err = c.RegisterModels(&User{}, &Car{}); err != nil {
    // handle the error for invalid model definitions
}
  1. Use the models within the Gateway API or just as an ORM models.
user := &User{
    Name: "Mathew",
    Surname: "Smith",
}
s, err := query.NewC(c, user)
if err != nil {
    // handle the error
}

if err = s.Create(); err != nil {
    // handle the error
}

Examples

config.yml

{
    "repositories": {
        "postgres": {
            "driver_name": "pq",
            "host": "localhost",
            "port": "5432",
            "dbname": "testing",
            "username": "testing",
            "password": "testing"
        }
    },
    "default_repository_name": "postgres",
    "models": {
            "car": {
                "repository_name" : "postgres",
                "automigrate": true
            }
        }
    }
}


package main

import (
    "github.com/neuronlabs/neuron-core/config"
    "github.com/neuronlabs/neuron-core/controller"
    "github.com/neuronlabs/neuron-core/query/scope"
    _ "github.com/neuronlabs/neuron-pq"
)

// Car is the model used in our example application
type Car struct {
    ID      int             `neuron:"type=primary"`
    Brand   *Manufacturer   `neuron:"type=relation;foreign=BrandID"`
    BrandID int             `neuron:"type=foreign"`
    VIN     string          `neuron:"type=attr" db:"unique"`
}

// Manufacturer is the model used in our example application defined as a car 
// manufacturer
type Manufacturer struct {
    ID      int     `neuron:"type=primary"`
    Name    string  `neuron:"type=attr"`
    Cars    []*Car  `neuron:"type=relation;foreign=BrandID"`
}


func main() {
    // read the config from file named 'config' in the path './'
    cfg, err := config.ReadControllerConfig("config", "./")
    if err != nil {
        panic(err)
    }

    // create the controller with the config
    c, err := controller.New(cfg)
    if err != nil {
        panic(err)
    }

    // even thought only the car is defined in the model
    // the manufacturer would have the defined repository - taken from the 
    // default
    if err := c.RegisterModels(&Car{}, &Manufacturer{}); err != nil {
        panic(err)
    }


    manufacturer := &Manufacturer{
        Name: "Best Manufacturer",
    }

    s, err := query.NewC(c, manufacturer)
    if err != nil {
        panic(err)
    }

    if err = s.Create(); err != nil {
        panic(err)
    }

    car := &Car{
        VIN: "1HGBH41JXMN109186"
        BrandID: 1,
    }

    s, err = query.NewC(c, car)
    if err != nil {
        panic(err)
    }

    if err = s.Create(); err != nil {
        panic(err)
    }


    // your database should contain now one entry of the manufacturer with 
    // name "Best Manufacturer" and one car with VIN number: 
    // '1HGBH41JXMN109186' and foreign key to brand - brand_id = 1
    ... 
}

Docs

Options

The neuron-pq have an option to AutoMigrate the models. AutoMigration checks the model's table definition on the current database connection. If there is no such table it creates new one. If any column is missing it creates it with all the constraint defined.

In order to set the AutoMigrate for all models within a provided Repository Set it's config.Options with the key AutoMigrateKey to true in:

 var cfg *config.Repository 
 cfg = &config.Repository{Options: map[string]interface{}{AutoMigrateKey: true}

If AutoMigrate should migrate all the models within any neuron-pq.Repositoryinstance the package variable AutoMigrateAll should be set to true

The third option to set the AutoMigrate just for single model is to set it's Config (*config.Model) AutoMigrate variable to true.

Documentation

Overview

Package pq implements the github.com/neuronlabs/neuron-core repository with the modular filter with the support. The package uses github.com/jackc/pgx Postgres driver.

Index

Constants

View Source
const (

	// AutoMigrateKey is the key in the Repository.Options used to get the automigrate option for the whole repository
	AutoMigrateKey = "automigrate"
)
View Source
const FactoryName = "pq"

FactoryName defines the name of the factory.

Variables

View Source
var AutomigrateAll bool

AutomigrateAll defines if all the models should be automigrated.

Functions

This section is empty.

Types

type Factory

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

Factory is the pq.Repository factory.

func (*Factory) Close added in v0.1.2

func (f *Factory) Close(ctx context.Context, done chan<- interface{})

Close closes the connected repositories for given factory type Implements repository.Factory interface.

func (*Factory) DriverName added in v0.2.1

func (f *Factory) DriverName() string

DriverName gets the Factory repository name. Implements repository.Repository interface.

func (*Factory) New

New creates new PQ repository for the provided model.

type Repository

type Repository struct {
	// is the sql connection
	Pool *pgx.ConnPool

	// config for the postgis
	Config pgx.ConnPoolConfig

	// PostgresVersion is the numerical version of the postgres server.
	PostgresVersion int
	// contains filtered or unexported fields
}

Repository is the postgis repository that is used to query the postgis database Implements query.FullRepository

func (*Repository) Begin

func (r *Repository) Begin(ctx context.Context, s *query.Scope) error

Begin starts a transaction for the given scope. Implements Begin method of the query.Transactioner interface.

func (*Repository) Close added in v0.1.2

func (p *Repository) Close(ctx context.Context) error

Close closes the repository connections

func (*Repository) Commit

func (r *Repository) Commit(ctx context.Context, s *query.Scope) error

Commit commits the scope's transaction Implements Commit method from the query.Commiter interface

func (*Repository) Count added in v0.8.1

func (p *Repository) Count(ctx context.Context, s *query.Scope) (int64, error)

Count implements query.Counter interface.

func (*Repository) Create

func (p *Repository) Create(ctx context.Context, s *query.Scope) error

Create creates the value within the query. Implements repository.Creator interface.

func (*Repository) Delete

func (p *Repository) Delete(ctx context.Context, s *query.Scope) error

Delete deletes all the values that matches scope's filters. Implements query.Deleter interface.

func (*Repository) FactoryName added in v0.4.0

func (p *Repository) FactoryName() string

FactoryName returns the name of the factory for this Repository. Implements RepositoryNamer interface.

func (*Repository) Get

func (p *Repository) Get(ctx context.Context, s *query.Scope) error

Get gets the query scope's single value. Implements query.Getter interface.

func (*Repository) List

func (p *Repository) List(ctx context.Context, s *query.Scope) error

List lists all the values that matches scope's filters, sorts and pagination. Implements query.Lister interface.

func (*Repository) Patch

func (p *Repository) Patch(ctx context.Context, s *query.Scope) error

Patch patches all the values that matches scope's filters, sorts and pagination Implements query.Patcher interface

func (*Repository) Rollback

func (r *Repository) Rollback(ctx context.Context, s *query.Scope) error

Rollback rolls back the transaction for given scope

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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