put method
Future<int?>
put(
- String key,
- AtData value, {
- bool skipCommit = false,
- AtAssertedTimestamps? assertedTimestamps,
override
hive does not support directly storing emoji characters, therefore keys
are encoded in HiveKeyStoreHelper.prepareKey using utf7 before storing.
Implementation
@override
Future<int?> put(String key, AtData value,
{bool skipCommit = false,
AtAssertedTimestamps? assertedTimestamps}) async {
key = key.toLowerCase();
final atKey = AtKey.getKeyType(key, enforceNameSpace: false);
if (atKey == KeyType.invalidKey) {
logger.warning('Key $key is invalid');
throw InvalidAtKeyException('Key $key is invalid');
}
int? result;
CommitOp commitOp = CommitOp.UPDATE_ALL;
try {
// If does not exist, create a new key,
// else update existing key.
if (!await exists(key)) {
result = await create(key, value,
skipCommit: skipCommit, assertedTimestamps: assertedTimestamps);
} else {
AtData? existingData = await get(key);
String hive_key = HiveKeyStoreHelper.prepareKey(key);
var hive_value = HiveKeyStoreHelper.prepareDataForKeystoreOperation(
value,
existingAtData: existingData!,
atSign: atSign,
asserted: assertedTimestamps);
logger.finest('hive key:$hive_key');
logger.finest('hive value:$hive_value');
await getBox().put(hive_key, hive_value);
_updateMetadataCache(key, hive_value.metaData);
if (skipCommit) {
// A skipCommit write leaves no trace in the commit log: as
// well as writing no entry, purge the key's previous entry —
// sync would otherwise keep serving a stale entry for a
// record whose latest change was deliberately uncommitted.
// (No-op on a commit-log-free keystore.)
await _commitLog?.removeEntryFor(hive_key);
result = -1;
} else {
// `_commitLog` is null on a commit-log-free keystore — the
// write still succeeds, it just produces no sequence number.
result = await _commitLog?.commit(hive_key, commitOp,
opTime: assertedTimestamps?.updatedAt);
}
_changesController.add(KeyUpdated(key));
}
} on DataStoreException {
rethrow;
} on Exception catch (exception) {
logger.severe('HiveAtKeyValueStore put exception: $exception');
throw DataStoreException('exception in put: ${exception.toString()}');
} on HiveError catch (error) {
await _restartHiveBox(error);
logger.severe('HiveAtKeyValueStore error: $error');
throw DataStoreException(error.message);
}
return result;
}