persistence

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Nov 5, 2020 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 IPublicConvertable

type IPublicConvertable interface {
	//  Convert object value from public to internal format.
	ConvertToPublic(value interface{}) interface{}
	//  Updates only few selected fields in a data item.
	ConvertFromPublic(value interface{}) interface{}
	// Converts the given object from the public partial format.
	ConvertFromPublicPartial(value interface{}) interface{}
}

type IdentifiableJsonPostgresPersistence

type IdentifiableJsonPostgresPersistence struct {
	IdentifiablePostgresPersistence
}

### Configuration parameters ###

*

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

- credential(s):

- 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 ###

*

### 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 NewIdentifiableJsonPostgresPersistence

func NewIdentifiableJsonPostgresPersistence(proto reflect.Type, tableName string) *IdentifiableJsonPostgresPersistence

Creates a new instance of the persistence component.

*

- collection (optional) a collection 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{}

Converts the given object from the public partial format. - value the object to convert from the public partial format. Returns the initial object.

func (*IdentifiableJsonPostgresPersistence) ConvertToPublic

func (c *IdentifiableJsonPostgresPersistence) ConvertToPublic(value interface{}) 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):

- credential(s):

- 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 ###

*

### 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 NewIdentifiablePostgresPersistence

func NewIdentifiablePostgresPersistence(proto reflect.Type, tableName string) *IdentifiablePostgresPersistence

Creates a new instance of the persistence component. - collection (optional) a collection 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 PostgresConnection

type PostgresConnection struct {

	// The logger.
	Logger *clog.CompositeLogger
	// The connection resolver.
	ConnectionResolver *pcon.PostgresConnectionResolver
	// The configuration options.
	Options *cconf.ConfigParams
	// The PostgreSQL connection pool object.
	Connection *pgxpool.Pool
	// The PostgreSQL database name.
	DatabaseName string
	// contains filtered or unexported fields
}

*

  • PostgreSQL connection using plain driver. *
  • By defining a connection and sharing it through multiple persistence components
  • you can reduce number of used database connections. *
  • ### Configuration parameters ### *
  • - 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: user name
  • - password: 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
  • - \*:discovery:\*:\*:1.0 (optional) [[ IDiscovery]] services
  • - \*:credential-store:\*:\*:1.0 (optional) Credential stores to resolve credentials *

func NewPostgresConnection

func NewPostgresConnection() *PostgresConnection

NewPostgresConnection creates a new instance of the connection component.

func (*PostgresConnection) Close

func (c *PostgresConnection) Close(correlationId string) error

Closes component and frees used resources.

  • correlationId (optional) transaction id to trace execution through call chain.

Return error or nil no errors occured

func (*PostgresConnection) Configure

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

Configures component by passing configuration parameters.

  • config configuration parameters to be set.

func (*PostgresConnection) GetConnection

func (c *PostgresConnection) GetConnection() *pgxpool.Pool

func (*PostgresConnection) GetDatabaseName

func (c *PostgresConnection) GetDatabaseName() string

func (*PostgresConnection) IsOpen

func (c *PostgresConnection) IsOpen() bool

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

func (*PostgresConnection) Open

func (c *PostgresConnection) Open(correlationId string) error

Opens the component.

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

func (*PostgresConnection) SetReferences

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

Sets references to dependent components.

  • references references to locate the component dependencies.

type PostgresPersistence

type PostgresPersistence struct {
	IPublicConvertable

	//The dependency resolver.
	DependencyResolver *cref.DependencyResolver
	//The logger.
	Logger *clog.CompositeLogger
	//The PostgreSQL connection component.
	Connection *PostgresConnection
	//The PostgreSQL connection pool object.
	Client *pgxpool.Pool
	//The PostgreSQL database name.
	DatabaseName string
	//The PostgreSQL table object.
	TableName   string
	MaxPageSize int
	Prototype   reflect.Type
	// contains filtered or unexported fields
}

func NewPostgresPersistence

func NewPostgresPersistence(proto reflect.Type, tableName string) *PostgresPersistence

Creates a new instance of the persistence component. - tableName (optional) a table name.

func (*PostgresPersistence) AutoCreateObject

func (c *PostgresPersistence) AutoCreateObject(dmlStatement string)

Adds index definition to create it on opening - dmlStatement DML statement to autocreate database object

func (*PostgresPersistence) AutoCreateObjects

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

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) 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) ConvertFromRows

func (c *PostgresPersistence) ConvertFromRows(columns []pgproto3.FieldDescription, rows []interface{}) interface{}

ConvertFromMap method are converts from map[string]interface{} to object, defined by c.Prototype

func (*PostgresPersistence) ConvertResultToPublic

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

func (*PostgresPersistence) ConvertToPublic

func (c *PostgresPersistence) ConvertToPublic(value interface{}) 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) 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) 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) 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{}) (params 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) 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