persistence

package
v1.2.8-44 Latest Latest
Warning

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

Go to latest
Published: Jun 3, 2022 License: MIT Imports: 19 Imported by: 2

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type IPostgresPersistenceOverrides added in v1.2.0

type IPostgresPersistenceOverrides interface {
	DefineSchema()
	ConvertFromPublic(item interface{}) interface{}
	ConvertToPublic(item pgx.Rows) interface{}
	ConvertFromPublicPartial(item interface{}) interface{}
}

type IdentifiableJsonPostgresPersistence

type IdentifiableJsonPostgresPersistence struct {
	IdentifiablePostgresPersistence
}

Abstract persistence component that stores data in PostgreSQL in JSON or JSONB fields and implements a number of CRUD operations over data items with unique ids. The data items must implement IIdentifiable interface.

The JSON table has only two fields: id and data.

In basic scenarios child classes shall only override getPageByFilter, getListByFilter or deleteByFilter operations with specific filter function. All other operations can be used out of the box.

In complex scenarios child classes can implement additional operations by accessing c._collection and c._model properties.

### Configuration parameters ###

- collection: (optional) PostgreSQL collection name - connection(s):

  • discovery_key: (optional) a key to retrieve the connection from IDiscovery
  • host: host name or IP address
  • port: port number (default: 27017)
  • uri: resource URI or connection string with all parameters in it

- credential(s):

  • store_key: (optional) a key to retrieve the credentials from ICredentialStore
  • username: (optional) user name
  • password: (optional) user password

- options:

  • connect_timeout: (optional) number of milliseconds to wait before timing out when connecting a new client (default: 0)

  • idle_timeout: (optional) number of milliseconds a client must sit idle in the pool and not be checked out (default: 10000)

  • max_pool_size: (optional) maximum number of clients the pool should contain (default: 10)

    ### References ###

  • \*:logger:\*:\*:1.0 (optional) ILogger components to pass log messages components to pass log messages

  • \*:discovery:\*:\*:1.0 (optional) IDiscovery services

  • \*:credential-store:\*:\*:1.0 (optional) Credential stores to resolve credentials

    ### Example ###

    class MyPostgresPersistence extends IdentifiablePostgresJsonPersistence<MyData, string> {

    public constructor() { base("mydata", new MyDataPostgresSchema()); }

    private composeFilter(filter: FilterParams): any { filter = filter || new FilterParams(); let criteria = []; let name = filter.getAsNullableString('name'); if (name != null) criteria.push({ name: name }); return criteria.length > 0 ? { $and: criteria } : null; }

    public getPageByFilter(correlationId: string, filter: FilterParams, paging: PagingParams, callback: (err: any, page: DataPage<MyData>) => void): void { base.getPageByFilter(correlationId, c.composeFilter(filter), paging, null, null, callback); }

    }

    let persistence = new MyPostgresPersistence(); persistence.configure(ConfigParams.fromTuples( "host", "localhost", "port", 27017 ));

    persitence.open("123", (err) => { ... });

    persistence.create("123", { id: "1", name: "ABC" }, (err, item) => { persistence.getPageByFilter( "123", FilterParams.fromTuples("name", "ABC"), null, (err, page) => { console.log(page.data); // Result: { id: "1", name: "ABC" }

    persistence.deleteById("123", "1", (err, item) => { ... }); } ) });

func InheritIdentifiableJsonPostgresPersistence added in v1.2.0

func InheritIdentifiableJsonPostgresPersistence(overrides IPostgresPersistenceOverrides, proto reflect.Type, tableName string) *IdentifiableJsonPostgresPersistence

Creates a new instance of the persistence component.

  • overrides References to override virtual methods
  • tableName (optional) a table name.

func (*IdentifiableJsonPostgresPersistence) ConvertFromPublic

func (c *IdentifiableJsonPostgresPersistence) ConvertFromPublic(value interface{}) interface{}

Convert object value from public to internal format.

  • value an object in public format to convert.

Returns converted object in internal format.

func (*IdentifiableJsonPostgresPersistence) ConvertFromPublicPartial

func (c *IdentifiableJsonPostgresPersistence) ConvertFromPublicPartial(value interface{}) interface{}

Convert object value from public to internal format.

  • value an object in public format to convert.

Returns converted object in internal format.

func (*IdentifiableJsonPostgresPersistence) ConvertToPublic

func (c *IdentifiableJsonPostgresPersistence) ConvertToPublic(rows pgx.Rows) interface{}

Converts object value from internal to public format.

  • value an object in internal format to convert.

Returns converted object in public format.

func (*IdentifiableJsonPostgresPersistence) EnsureTable

func (c *IdentifiableJsonPostgresPersistence) EnsureTable(idType string, dataType string)

Adds DML statement to automatically create JSON(B) table

  • idType type of the id column (default: TEXT)
  • dataType type of the data column (default: JSONB)

func (*IdentifiableJsonPostgresPersistence) UpdatePartially

func (c *IdentifiableJsonPostgresPersistence) UpdatePartially(correlationId string, id interface{}, data *cdata.AnyValueMap) (result interface{}, err error)

Updates only few selected fields in a data item.

  • correlation_id (optional) transaction id to trace execution through call chain.
  • id an id of data item to be updated.
  • data a map with fields to be updated.

Returns callback function that receives updated item or error.

type IdentifiablePostgresPersistence

type IdentifiablePostgresPersistence struct {
	*PostgresPersistence
}

Abstract persistence component that stores data in PostgreSQL and implements a number of CRUD operations over data items with unique ids. The data items must implement IIdentifiable interface.

In basic scenarios child classes shall only override getPageByFilter, getListByFilter or deleteByFilter operations with specific filter function. All other operations can be used out of the box.

In complex scenarios child classes can implement additional operations by accessing c._collection and c._model properties.

### Configuration parameters ###

- collection: (optional) PostgreSQL collection name - connection(s):

  • discovery_key: (optional) a key to retrieve the connection from IDiscovery
  • host: host name or IP address
  • port: port number (default: 27017)
  • uri: resource URI or connection string with all parameters in it

- credential(s):

  • store_key: (optional) a key to retrieve the credentials from ICredentialStore
  • username: (optional) user name
  • password: (optional) user password

- options:

  • connect_timeout: (optional) number of milliseconds to wait before timing out when connecting a new client (default: 0)
  • idle_timeout: (optional) number of milliseconds a client must sit idle in the pool and not be checked out (default: 10000)
  • max_pool_size: (optional) maximum number of clients the pool should contain (default: 10)

### References ###

  • \*:logger:\*:\*:1.0 (optional) ILogger components to pass log messages components to pass log messages
  • \*:discovery:\*:\*:1.0 (optional) IDiscovery services
  • \*:credential-store:\*:\*:1.0 (optional) Credential stores to resolve credentials *

### Example ###

class MyPostgresPersistence extends IdentifiablePostgresPersistence<MyData, string> {

public constructor() {
    base("mydata", new MyDataPostgresSchema());
}

private composeFilter(filter: FilterParams): any {
    filter = filter || new FilterParams();
    let criteria = [];
    let name = filter.getAsNullableString('name');
    if (name != null)
        criteria.push({ name: name });
    return criteria.length > 0 ? { $and: criteria } : null;
}

public getPageByFilter(correlationId: string, filter: FilterParams, paging: PagingParams,
    callback: (err: any, page: DataPage<MyData>) => void): void {
    base.getPageByFilter(correlationId, c.composeFilter(filter), paging, null, null, callback);
}

}

let persistence = new MyPostgresPersistence();
persistence.configure(ConfigParams.fromTuples(
    "host", "localhost",
    "port", 27017
));

persitence.open("123", (err) => {
    ...
});

persistence.create("123", { id: "1", name: "ABC" }, (err, item) => {
    persistence.getPageByFilter(
        "123",
        FilterParams.fromTuples("name", "ABC"),
        null,
        (err, page) => {
            console.log(page.data);          // Result: { id: "1", name: "ABC" }

            persistence.deleteById("123", "1", (err, item) => {
               ...
            });
        }
    )
});

func InheritIdentifiablePostgresPersistence added in v1.2.0

func InheritIdentifiablePostgresPersistence(overrides IPostgresPersistenceOverrides, proto reflect.Type, tableName string) *IdentifiablePostgresPersistence

Creates a new instance of the persistence component.

  • overrides References to override virtual methods
  • tableName (optional) a table name.

func (*IdentifiablePostgresPersistence) Create

func (c *IdentifiablePostgresPersistence) Create(correlationId string, item interface{}) (result interface{}, err error)

Creates a data item.

  • correlation_id (optional) transaction id to trace execution through call chain.
  • item an item to be created.

Returns (optional) created item or error.

func (*IdentifiablePostgresPersistence) DeleteById

func (c *IdentifiablePostgresPersistence) DeleteById(correlationId string, id interface{}) (result interface{}, err error)

Deleted a data item by it's unique id.

  • correlation_id (optional) transaction id to trace execution through call chain.
  • id an id of the item to be deleted

Returns (optional) deleted item or error.

func (*IdentifiablePostgresPersistence) DeleteByIds

func (c *IdentifiablePostgresPersistence) DeleteByIds(correlationId string, ids []interface{}) error

Deletes multiple data items by their unique ids.

  • correlationId (optional) transaction id to trace execution through call chain.
  • ids ids of data items to be deleted.

Returns (optional) error or null for success.

func (*IdentifiablePostgresPersistence) GetListByIds

func (c *IdentifiablePostgresPersistence) GetListByIds(correlationId string, ids []interface{}) (items []interface{}, err error)

Gets a list of data items retrieved by given unique ids.

  • correlationId (optional) transaction id to trace execution through call chain.
  • ids ids of data items to be retrieved

Returns a data list or error.

func (*IdentifiablePostgresPersistence) GetOneById

func (c *IdentifiablePostgresPersistence) GetOneById(correlationId string, id interface{}) (item interface{}, err error)

Gets a data item by its unique id.

  • correlationId (optional) transaction id to trace execution through call chain.
  • id an id of data item to be retrieved.

Returns data item or error.

func (*IdentifiablePostgresPersistence) Set

func (c *IdentifiablePostgresPersistence) Set(correlationId string, item interface{}) (result interface{}, err error)

Sets a data item. If the data item exists it updates it, otherwise it create a new data item.

  • correlation_id (optional) transaction id to trace execution through call chain.
  • item a item to be set.

Returns (optional) updated item or error.

func (*IdentifiablePostgresPersistence) Update

func (c *IdentifiablePostgresPersistence) Update(correlationId string, item interface{}) (result interface{}, err error)

Updates a data item.

  • correlation_id (optional) transaction id to trace execution through call chain.
  • item an item to be updated.

Returns (optional) updated item or error.

func (*IdentifiablePostgresPersistence) UpdatePartially

func (c *IdentifiablePostgresPersistence) UpdatePartially(correlationId string, id interface{}, data *cdata.AnyValueMap) (result interface{}, err error)

Updates only few selected fields in a data item.

  • correlation_id (optional) transaction id to trace execution through call chain.
  • id an id of data item to be updated.
  • data a map with fields to be updated.

Returns updated item or error.

type PostgresPersistence

type PostgresPersistence struct {
	Overrides IPostgresPersistenceOverrides
	Prototype reflect.Type

	//The dependency resolver.
	DependencyResolver *cref.DependencyResolver
	//The logger.
	Logger *clog.CompositeLogger
	//The PostgreSQL connection component.
	Connection *conn.PostgresConnection
	//The PostgreSQL connection pool object.
	Client *pgxpool.Pool
	//The PostgreSQL database name.
	DatabaseName string
	//The PostgreSQL database schema name. If not set use "public" by default
	SchemaName string
	//The PostgreSQL table object.
	TableName   string
	MaxPageSize int
	// contains filtered or unexported fields
}

func InheritPostgresPersistence added in v1.2.0

func InheritPostgresPersistence(overrides IPostgresPersistenceOverrides, proto reflect.Type, tableName string) *PostgresPersistence

Creates a new instance of the persistence component.

  • overrides References to override virtual methods
  • tableName (optional) a table name.

func (*PostgresPersistence) Clear

func (c *PostgresPersistence) Clear(correlationId string) error

Clears component state.

  • correlationId (optional) transaction id to trace execution through call chain.
  • Returns error or nil no errors occured.

func (*PostgresPersistence) ClearSchema added in v1.1.1

func (c *PostgresPersistence) ClearSchema()

Clears all auto-created objects

func (*PostgresPersistence) Close

func (c *PostgresPersistence) Close(correlationId string) (err error)

Closes component and frees used resources.

  • correlationId (optional) transaction id to trace execution through call chain.
  • Returns error or nil no errors occured.

func (*PostgresPersistence) Configure

func (c *PostgresPersistence) Configure(config *cconf.ConfigParams)

Configures component by passing configuration parameters.

  • config configuration parameters to be set.

func (*PostgresPersistence) ConvertFromPublic

func (c *PostgresPersistence) ConvertFromPublic(value interface{}) interface{}

Convert object value from func (c * PostgresPersistence) to internal format.

  • value an object in func (c * PostgresPersistence) format to convert.

Returns converted object in internal format.

func (*PostgresPersistence) ConvertFromPublicPartial

func (c *PostgresPersistence) ConvertFromPublicPartial(value interface{}) interface{}

Converts the given object from the public partial format.

  • value the object to convert from the public partial format.

Returns the initial object.

func (*PostgresPersistence) ConvertToPublic

func (c *PostgresPersistence) ConvertToPublic(rows pgx.Rows) interface{}

Converts object value from internal to func (c * PostgresPersistence) format.

  • value an object in internal format to convert.

Returns converted object in func (c * PostgresPersistence) format.

func (*PostgresPersistence) Create

func (c *PostgresPersistence) Create(correlationId string, item interface{}) (result interface{}, err error)

Creates a data item.

  • correlation_id (optional) transaction id to trace execution through call chain.
  • item an item to be created.
  • Returns (optional) callback function that receives created item or error.

func (*PostgresPersistence) CreateSchema added in v1.1.1

func (c *PostgresPersistence) CreateSchema(correlationId string) (err error)

func (*PostgresPersistence) DefineSchema added in v1.1.1

func (c *PostgresPersistence) DefineSchema()

Defines a database schema for this persistence, have to call in child class

func (*PostgresPersistence) DeleteByFilter

func (c *PostgresPersistence) DeleteByFilter(correlationId string, filter string) (err error)

Deletes data items that match to a given filter. This method shall be called by a func (c * PostgresPersistence) deleteByFilter method from child class that receives FilterParams and converts them into a filter function.

  • correlationId (optional) transaction id to trace execution through call chain.
  • filter (optional) a filter JSON object.
  • Returns error or nil for success.

func (*PostgresPersistence) DereferenceObject added in v1.0.1

func (c *PostgresPersistence) DereferenceObject(docPointer reflect.Value) interface{}

func (*PostgresPersistence) EnsureIndex

func (c *PostgresPersistence) EnsureIndex(name string, keys map[string]string, options map[string]string)

Adds index definition to create it on opening

  • keys index keys (fields)
  • options index options

func (*PostgresPersistence) EnsureSchema added in v1.1.1

func (c *PostgresPersistence) EnsureSchema(schemaStatement string)

Adds a statement to schema definition

  • schemaStatement a statement to be added to the schema

func (*PostgresPersistence) GenerateColumns

func (c *PostgresPersistence) GenerateColumns(values interface{}) string

Generates a list of column names to use in SQL statements like: "column1,column2,column3"

  • values an array with column values or a key-value map

Returns a generated list of column names

func (*PostgresPersistence) GenerateParameters

func (c *PostgresPersistence) GenerateParameters(values interface{}) string

Generates a list of value parameters to use in SQL statements like: "$1,$2,$3"

  • values an array with values or a key-value map

Returns a generated list of value parameters

func (*PostgresPersistence) GenerateSetParameters

func (c *PostgresPersistence) GenerateSetParameters(values interface{}) (setParams string, columns string)

Generates a list of column sets to use in UPDATE statements like: column1=$1,column2=$2

  • values a key-value map with columns and values

Returns a generated list of column sets

func (*PostgresPersistence) GenerateValues

func (c *PostgresPersistence) GenerateValues(columns string, values interface{}) []interface{}

Generates a list of column parameters

  • values a key-value map with columns and values

Returns a generated list of column values

func (*PostgresPersistence) GetCountByFilter

func (c *PostgresPersistence) GetCountByFilter(correlationId string, filter interface{}) (count int64, err error)

Gets a number of data items retrieved by a given filter. This method shall be called by a func (c * PostgresPersistence) getCountByFilter method from child class that receives FilterParams and converts them into a filter function.

  • correlationId (optional) transaction id to trace execution through call chain.
  • filter (optional) a filter JSON object
  • Returns data page or error.

func (*PostgresPersistence) GetListByFilter

func (c *PostgresPersistence) GetListByFilter(correlationId string, filter interface{}, sort interface{}, sel interface{}) (items []interface{}, err error)

Gets a list of data items retrieved by a given filter and sorted according to sort parameters. This method shall be called by a func (c * PostgresPersistence) getListByFilter method from child class that receives FilterParams and converts them into a filter function.

  • correlationId (optional) transaction id to trace execution through call chain.
  • filter (optional) a filter JSON object
  • paging (optional) paging parameters
  • sort (optional) sorting JSON object
  • select (optional) projection JSON object
  • Returns data list or error.

func (*PostgresPersistence) GetOneRandom

func (c *PostgresPersistence) GetOneRandom(correlationId string, filter interface{}) (item interface{}, err error)

Gets a random item from items that match to a given filter. This method shall be called by a func (c * PostgresPersistence) getOneRandom method from child class that receives FilterParams and converts them into a filter function.

  • correlationId (optional) transaction id to trace execution through call chain.
  • filter (optional) a filter JSON object
  • Returns random item or error.

func (*PostgresPersistence) GetPageByFilter

func (c *PostgresPersistence) GetPageByFilter(correlationId string, filter interface{}, paging *cdata.PagingParams,
	sort interface{}, sel interface{}) (page *cdata.DataPage, err error)

Gets a page of data items retrieved by a given filter and sorted according to sort parameters. This method shall be called by a func (c * PostgresPersistence) getPageByFilter method from child class that receives FilterParams and converts them into a filter function.

  • correlationId (optional) transaction id to trace execution through call chain.
  • filter (optional) a filter JSON object
  • paging (optional) paging parameters
  • sort (optional) sorting JSON object
  • select (optional) projection JSON object
  • Returns receives a data page or error.

func (*PostgresPersistence) IsOpen

func (c *PostgresPersistence) IsOpen() bool

Checks if the component is opened. Returns true if the component has been opened and false otherwise.

func (*PostgresPersistence) NewObjectByPrototype

func (c *PostgresPersistence) NewObjectByPrototype() reflect.Value

service function for return pointer on new prototype object for unmarshaling

func (*PostgresPersistence) Open

func (c *PostgresPersistence) Open(correlationId string) (err error)

Opens the component.

  • correlationId (optional) transaction id to trace execution through call chain.
  • Returns error or nil no errors occured.

func (*PostgresPersistence) QuoteIdentifier

func (c *PostgresPersistence) QuoteIdentifier(value string) string

func (*PostgresPersistence) QuotedTableName added in v1.2.8

func (c *PostgresPersistence) QuotedTableName() string

Return quoted SchemaName with TableName ("schema"."table")

func (*PostgresPersistence) SetReferences

func (c *PostgresPersistence) SetReferences(references cref.IReferences)

Sets references to dependent components.

  • references references to locate the component dependencies.

func (*PostgresPersistence) UnsetReferences

func (c *PostgresPersistence) UnsetReferences()

Unsets (clears) previously set references to dependent components.

Jump to

Keyboard shortcuts

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