MySqlPersistence<T> class

Abstract persistence component that stores data in MySQL using plain driver.

This is the most basic persistence component that is only able to store data items of any type. Specific CRUD operations over the data items must be implemented in child classes by accessing this.connection_ and this.client_ properties.

Configuration parameters

  • table: (optional) MySQL table name

  • schema: (optional) MySQL schema 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: 10000)

    Note: the options below are currently not supported.

    • 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

Example

class MyMySqlPersistence extends MySqlPersistence<MyData> {
  MyMySqlPersistence() : super("mydata", null);

  @override
  void defineSchema_() {
    this.clearSchema();
    this.ensureSchema_('CREATE TABLE `' +
        this.tableName_! +
        '` (id VARCHAR(32) PRIMARY KEY, `key` VARCHAR(50), `content` TEXT)');
    this.ensureIndex_(this.tableName_! + '_key', {'key': 1}, {'unique': true});
  }


  Future<String?> getByName(String? correlationId, String name) async {
    var query = "SELECT * FROM " + this.quotedTableName_() + " WHERE id=?";
    var params = [name];

    var res = await client_!.query(query, params);

    if (res.toList().isEmpty)
      this.logger_.trace(correlationId, "Nothing found from %s with name = %s",
          [this.tableName_, name]);
    else
      this.logger_.trace(correlationId, "Retrieved from %s with name = %s",
          [this.tableName_, name]);

    var resValues = res.toList().isNotEmpty ? res.toList()[0].fields : null;
    var item = this.convertToPublic_(resValues);

    return item;
  }

  Future<MyData?> set(String? correlationId, MyData item) async {
    if (item == null) {
      return null;
    }

    // Assign unique id
    dynamic newItem = item;
    if (newItem.id == null && this.autoGenerateId_) {
      newItem = (newItem as ICloneable).clone();
      newItem.id = IdGenerator.nextLong();
    }

    var row = this.convertFromPublic_(item);
    var columns = this.generateColumns_(row);
    var params = this.generateParameters_(row);
    var setParams = this.generateSetParameters_(row);
    var values = this.generateValues_(row);
    values.addAll(List.from(values));

    var query = "INSERT INTO " +
        this.quotedTableName_() +
        " (" +
        columns +
        ") VALUES (" +
        params +
        ")";
    query += " ON DUPLICATE KEY UPDATE " + setParams;

    var res = await client_!.query(query, values);

    query = "SELECT * FROM " + this.quotedTableName_() + " WHERE id=?";
    res = await client_!.query(query, [item.id]);

    var resValues = res.toList().isNotEmpty ? res.toList()[0].fields : null;
    newItem = this.convertToPublic_(resValues);

    logger_.trace(correlationId, "Set in %s with id = %s",
        [this.quotedTableName_(), newItem.id]);

    return newItem;
  }
}

var persistence = MyMySqlPersistence();
persistence.configure(ConfigParams.fromTuples(["host", "localhost", "port", 27017]));
await persistence.open(null);
var item = await persistence.set(null, MyData());
print(item);
Implementers

Constructors

MySqlPersistence(String? tableName, String? schemaName)
Creates a new instance of the persistence component.

Properties

client_ ↔ MySqlConnection?
getter/setter pair
connection_ MySqlConnection?
getter/setter pair
databaseName_ String?
getter/setter pair
dependencyResolver_ ↔ DependencyResolver
getter/setter pair
hashCode int
The hash code for this object.
no setterinherited
logger_ ↔ CompositeLogger
getter/setter pair
maxPageSize_ int
getter/setter pair
runtimeType Type
A representation of the runtime type of the object.
no setterinherited
schemaName_ String?
getter/setter pair
tableName_ String?
getter/setter pair

Methods

clear(String? correlationId) Future
Clears component state.
clearSchema() → void
Clears all auto-created objects
close(String? correlationId) Future
Closes component and frees used resources.
configure(ConfigParams config) → void
Configures component by passing configuration parameters.
convertFromPublic_(dynamic value) → dynamic
Convert object value from public to internal format.
convertToPublic_(dynamic value) → dynamic
Converts object value from internal to public format.
create(String? correlationId, T item) Future<T?>
Creates a data item.
createSchema_(String? correlationId) Future<void>
defineSchema_() → void
Defines database schema via auto create objects or convenience methods.
deleteByFilter_(String? correlationId, String? filter) Future<void>
Deletes data items that match to a given filter.
ensureIndex_(String name, Map keys, Map? options) → void
Adds index definition to create it on opening
ensureSchema_(String schemaStatement) → void
Adds a statement to schema definition
generateColumns_(dynamic values) String
Generates a list of column names to use in SQL statements like: "column1,column2,column3"
generateParameters_(dynamic values) String
Generates a list of value parameters to use in SQL statements like: "$1,$2,$3"
generateSetParameters_(Map values) String
Generates a list of column sets to use in UPDATE statements like: column1=$1,column2=$2
generateValues_(Map values) List
Generates a list of column parameters
getCountByFilter_(String? correlationId, String? filter) Future<int>
Gets a number of data items retrieved by a given filter.
getListByFilter_(String? correlationId, String? filter, String? sort, String? select) Future<List<T>>
Gets a list of data items retrieved by a given filter and sorted according to sort parameters.
getOneRandom_(String? correlationId, String? filter) Future<T?>
getPageByFilter_(String? correlationId, String? filter, PagingParams? paging, String? sort, String? select) Future<DataPage<T>>
Gets a page of data items retrieved by a given filter and sorted according to sort parameters.
isOpen() bool
Checks if the component is opened.
noSuchMethod(Invocation invocation) → dynamic
Invoked when a nonexistent method or property is accessed.
inherited
open(String? correlationId) Future
Opens the component.
quotedTableName_() String
quoteIdentifier_(String? value) String
setReferences(IReferences references) → void
Sets references to dependent components.
toString() String
A string representation of this object.
inherited
unsetReferences() → void
Unsets (clears) previously set references to dependent components.

Operators

operator ==(Object other) bool
The equality operator.
inherited