Store.attach constructor

Store.attach(
  1. ModelDefinition? _defs,
  2. String? directoryPath, {
  3. bool queriesCaseSensitiveDefault = true,
})

Attach to a store opened in the directoryPath (or if null the defaultDirectoryPath).

Use this to access an open store from other isolates. This results in each isolate having access to the same underlying native store.

The returned store is a new instance (e.g. different pointer value) with its own lifetime and must also be closed (e.g. before an isolate exits). The actual underlying store is only closed when the last store instance is closed (e.g. when the app exits).

Implementation

Store.attach(this._defs, String? directoryPath,
    {bool queriesCaseSensitiveDefault = true})
    // _weak = false so store can be closed.
    : _weak = false,
      _queriesCaseSensitiveDefault = queriesCaseSensitiveDefault,
      directoryPath = _safeDirectoryPath(directoryPath),
      _absoluteDirectoryPath =
          path.context.canonicalize(_safeDirectoryPath(directoryPath)) {
  try {
    // Do not allow attaching to a store that is already open in the current
    // isolate. While technically possible this is not the intended usage
    // and e.g. transactions would have to be carefully managed to not
    // overlap.
    _checkStoreDirectoryNotOpen();

    final pathCStr = this.directoryPath.toNativeUtf8();
    try {
      if (debugLogs) {
        final isOpen = C.store_is_open(pathCStr.cast());
        print(
            'Attaching to store... path=${this.directoryPath} isOpen=$isOpen');
      }
      _cStore = C.store_attach(pathCStr.cast());
    } finally {
      malloc.free(pathCStr);
    }

    checkObxPtr(_cStore,
        'could not attach to the store at given path - please ensure it was opened before');

    // Not setting _reference as this is a replacement for obtaining a store
    // via reference.

    _attachFinalizer();
  } catch (e) {
    _reader.clear();
    rethrow;
  }
}