Skip to content

Commit

Permalink
some enhancement
Browse files Browse the repository at this point in the history
  • Loading branch information
anidotnet committed Dec 19, 2023
1 parent 9efc7af commit 60329ed
Show file tree
Hide file tree
Showing 17 changed files with 144 additions and 123 deletions.
2 changes: 1 addition & 1 deletion melos.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ scripts:
melos run generate &&
melos exec -c 6 --fail-fast --ignore="*generator*" --ignore="*demo*" -- flutter test --coverage --no-pub &&
melos exec -c 6 --fail-fast --scope="*generator*" -- dart pub global run coverage:test_with_coverage &&
melos exec -c 1 --file-exists=coverage/lcov.info --scope="nitrite" -- lcov --remove coverage/lcov.info "lib/src/migration/*" "lib/src/transaction/*" "lib/src/index/fulltext/stop_words.dart" &&
melos exec -c 1 --file-exists=coverage/lcov.info --scope="nitrite" -- lcov --ignore-errors unused --remove coverage/lcov.info "lib/src/migration/*" "lib/src/transaction/*" "lib/src/index/fulltext/stop_words.dart" &&
melos exec --ignore="*demo*" -- genhtml coverage/lcov.info --output-directory=coverage/ &&
melos exec -c 1 --file-exists=coverage/lcov.info -- coverde filter --input ./coverage/lcov.info --output MELOS_ROOT_PATH/coverage/filtered.lcov.info --filters \.g\.dart &&
coverde value -i coverage/filtered.lcov.info > MELOS_ROOT_PATH/coverage/result.txt
Expand Down
23 changes: 7 additions & 16 deletions packages/nitrite/lib/src/common/meta/attributes.dart
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,6 @@ class Attributes {
static final String lastModifiedTime = "last_modified_at";
static final String owner = "owner";
static final String uniqueId = "uuid";
static final String syncLock = "sync_lock";
static final String expiryWait = "expiry_wait";
static final String tombstone = "tombstone";
static final String feedLedger = "feed_ledger";
static final String localCollectionMarker = "local_collection_marker";
static final String remoteCollectionMarker = "remote_collection_marker";
static final String localTombstoneMarker = "local_tombstone_marker";
static final String remoteTombstoneMarker = "remote_tombstone_marker";
static final String replica = "replica";

Map<String, String> _attributes = {};

Expand All @@ -41,10 +32,10 @@ class Attributes {
}

/// Creates an instance of the Attributes class from a [Document] object.
///
///
/// Args:
/// document (Document): The parameter "document" is of type "Document".
///
///
/// Returns:
/// The method is returning an instance of the [Attributes] class.
factory Attributes.fromDocument(Document document) {
Expand All @@ -57,15 +48,15 @@ class Attributes {
return attr;
}

/// Adds a key-value pair to the attributes and returns
/// Adds a key-value pair to the attributes and returns
/// the updated [Attributes] object.
///
///
/// Args:
/// key (String): The key parameter is a string that represents the
/// key (String): The key parameter is a string that represents the
/// name of the attribute.
/// value (String): The value parameter is a string that represents
/// value (String): The value parameter is a string that represents
/// the value to be associated with the given key.
///
///
/// Returns:
/// The method is returning an object of type [Attributes].
Attributes set(String key, String value) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ abstract class DatabaseInstruction implements Instruction {
/// Adds an instruction to set an user authentication to the database.
DatabaseInstruction addUser(String username, String password) {
MigrationStep migrationStep =
MigrationStep(InstructionType.addPassword, (username, password));
MigrationStep(InstructionType.addUser, (username, password));
addStep(migrationStep);
return this;
}
Expand Down
4 changes: 2 additions & 2 deletions packages/nitrite/lib/src/migration/instructions.dart
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ typedef CustomInstruction = Future<void> Function(Nitrite nitrite);

/// Represents an instruction type.
enum InstructionType {
/// The add password instruction.
addPassword,
/// The add user authentication instruction.
addUser,

/// The change password instruction.
changePassword,
Expand Down
2 changes: 1 addition & 1 deletion packages/nitrite/lib/src/migration/migration_manager.dart
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ class MigrationManager {
try {
Command command;
switch (step.instructionType) {
case InstructionType.addPassword:
case InstructionType.addUser:
command = AddPasswordCommand(step.arguments as (String, String));
break;
case InstructionType.changePassword:
Expand Down
17 changes: 13 additions & 4 deletions packages/nitrite/lib/src/nitrite_builder.dart
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,15 @@ class NitriteBuilder {
return this;
}

/// Registers an [EntityConverter] with Nitrite. The converter is used to
/// convert between an entity and a [Document]. This method allows you to
/// register a custom converter for a specific entity.
NitriteBuilder registerEntityConverter(
EntityConverter<dynamic> entityConverter) {
nitriteConfig.registerEntityConverter(entityConverter);
return this;
}

/// Loads a Nitrite module into the Nitrite database. The module can be
/// used to extend the functionality of Nitrite.
NitriteBuilder loadModule(NitriteModule module) {
Expand Down Expand Up @@ -50,18 +59,18 @@ class NitriteBuilder {
/// everytime. If it is configured as a file based database, and if the file
/// does not exist, then it will create a new file store and open the database;
/// otherwise it will open the existing database file.
///
///
/// If the username and password is not provided, then it will open the database
/// without any authentication.
///
///
/// If the username and password both are provided, then it will open the database
/// with authentication. If the database is not already created, then it will
/// create a new database with the given username and password.
///
///
/// If the database is already created, then it will open the database with the
/// given username and password. If the username and password is not valid, then
/// it will throw an exception.
///
///
/// NOTE: Both username and password must be provided or both must be null.
Future<Nitrite> openOrCreate({String? username, String? password}) async {
await nitriteConfig.autoConfigure();
Expand Down
37 changes: 29 additions & 8 deletions packages/nitrite/lib/src/nitrite_config.dart
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ class NitriteConfig {
bool _configured = false;
final List<NitriteModule> _modules = <NitriteModule>[];
late PluginManager _pluginManager;
final List<EntityConverter> _entityConverters = <EntityConverter>[];

/// A map of migrations to be applied to the database.
Map<int, SplayTreeMap<int, Migration>> get migrations => _migrations;
Expand All @@ -30,7 +31,7 @@ class NitriteConfig {
}

/// Sets the field separator for Nitrite database.
///
///
/// Throws [InvalidOperationException] if the database is already initialized.
void setFieldSeparator(String fieldSeparator) {
if (_configured) {
Expand All @@ -42,7 +43,7 @@ class NitriteConfig {

/// Loads [NitritePlugin] instances defined in the [NitriteModule]
/// into the configuration.
///
///
/// Throws [InvalidOperationException] if the database is already initialized.
NitriteConfig loadModule(NitriteModule module) {
if (_configured) {
Expand All @@ -53,10 +54,22 @@ class NitriteConfig {
return this;
}

/// Adds a migration step to the configuration. A migration step is a process
/// of updating the database from one version to another. If the database is
/// Registers an [EntityConverter] with Nitrite. The converter is used to
/// convert between an entity and a [Document].
///
/// Throws [InvalidOperationException] if the database is already initialized.
void registerEntityConverter(EntityConverter<dynamic> entityConverter) {
if (_configured) {
throw InvalidOperationException("Cannot register entity converter after "
"database initialization");
}
_entityConverters.add(entityConverter);
}

/// Adds a migration step to the configuration. A migration step is a process
/// of updating the database from one version to another. If the database is
/// already initialized, then migration steps cannot be added.
///
///
/// Throws [InvalidOperationException] if the database is already initialized.
NitriteConfig addMigration(Migration migration) {
if (_configured) {
Expand All @@ -77,7 +90,7 @@ class NitriteConfig {
}

/// Sets the current schema version of the Nitrite database.
///
///
/// Throws [InvalidOperationException] if the database is already initialized.
NitriteConfig currentSchemaVersion(int version) {
if (_configured) {
Expand All @@ -99,7 +112,7 @@ class NitriteConfig {
}

/// Finds the [NitriteIndexer] for the given index type.
///
///
/// Throws [IndexingException] if no indexer is found for the given index type.
Future<NitriteIndexer> findIndexer(String indexType) async {
var nitriteIndexer = pluginManager.indexerMap[indexType];
Expand All @@ -119,7 +132,7 @@ class NitriteConfig {
return pluginManager.getNitriteStore();
}

/// Closes the [NitriteConfig] instance and releases any resources
/// Closes the [NitriteConfig] instance and releases any resources
/// associated with it.
Future<void> close() {
return pluginManager.close();
Expand All @@ -132,6 +145,14 @@ class NitriteConfig {
}

Future<void> _loadModules() async {
if (_entityConverters.isNotEmpty) {
var mapper = SimpleNitriteMapper();
for (EntityConverter entityConverter in _entityConverters) {
mapper.registerEntityConverter(entityConverter);
}
await _pluginManager.loadModule(module([mapper]));
}

for (NitriteModule module in _modules) {
await _pluginManager.loadModule(module);
}
Expand Down
9 changes: 5 additions & 4 deletions packages/nitrite/lib/src/repository/entity.dart
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,11 @@ class EntityId {
/// Returns true if the entity ID is a [NitriteId].
bool get isNitriteId => _isNitriteId;

/// Returns a list of sub-fields of the id field.
List<String> get subFields => _fields;
/// Returns a list of embedded fields of the id field.
List<String> get embeddedFields => _fields;

/// Returns a list of embedded field names.
List<String> get embeddedFieldNames {
/// Returns a list of encoded field names.
List<String> get encodedFieldNames {
return _fields
.map((field) => "$_fieldName${NitriteConfig.fieldSeparator}$field")
.toList();
Expand Down Expand Up @@ -130,6 +130,7 @@ class EntityIndex {
}

@internal

/// @nodoc
abstract class NitriteEntity {
String? get entityName;
Expand Down
2 changes: 1 addition & 1 deletion packages/nitrite/lib/src/repository/entity_decorator.dart
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ class EntityDecoratorReader<T> {
_objectIdField = _entityDecorator.idField;

var idFieldNames = _entityDecorator.idField!.isEmbedded
? _entityDecorator.idField!.embeddedFieldNames
? _entityDecorator.idField!.encodedFieldNames
: [_entityDecorator.idField!.fieldName];

var hasIndex = await _collection.hasIndex(idFieldNames);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ class NitriteEntityReader<T> {
_objectIdField = entity.entityId;

var idFieldNames = _objectIdField!.isEmbedded
? _objectIdField!.embeddedFieldNames
? _objectIdField!.encodedFieldNames
: [_objectIdField!.fieldName];

var hasIndex = await _nitriteCollection.hasIndex(idFieldNames);
Expand Down
3 changes: 3 additions & 0 deletions packages/nitrite/lib/src/store/user_auth_service.dart
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,9 @@ class UserAuthenticationService {
if (!crypt.match(oldPassword)) {
throw NitriteSecurityException('Username or password is invalid');
}
} else {
// if credential is null, it means the user is not present, so we cannot update
throw NitriteSecurityException('Username or password is invalid');
}
} else {
if (await _nitriteStore.hasMap(userMap)) {
Expand Down
26 changes: 13 additions & 13 deletions packages/nitrite/lib/src/transaction/tx.dart
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,19 @@ import 'dart:collection';
import 'package:nitrite/nitrite.dart';
import 'package:nitrite/src/transaction/tx_store.dart';

/// Represents a transaction in Nitrite database.
/// It provides methods to perform ACID operations on Nitrite database
/// collections and repositories.
///
/// A transaction can be committed or rolled back. Once a transaction is
/// committed, all changes made during the transaction are persisted to
/// the underlying store. If a transaction is rolled back, all changes
/// Represents a transaction in Nitrite database.
/// It provides methods to perform transactional operations on Nitrite database
/// collections and repositories.
///
/// A transaction can be committed or rolled back. Once a transaction is
/// committed, all changes made during the transaction are persisted to
/// the underlying store. If a transaction is rolled back, all changes
/// made during the transaction are discarded.
///
///
/// NOTE: Certain operations are auto-committed in Nitrite database. Those
/// operations are not part of transaction and cannot be rolled back.
/// operations are not part of transaction and cannot be rolled back.
/// The following operations are auto-committed:
///
///
/// * [NitriteCollection.createIndex]
/// * [NitriteCollection.rebuildIndex]
/// * [NitriteCollection.dropIndex]
Expand All @@ -37,17 +37,17 @@ abstract class Transaction {
/// Returns the current state of the transaction.
TransactionState get state;

/// Gets a [NitriteCollection] to perform ACID operations on it.
/// Gets a [NitriteCollection] to perform transactional operations on it.
Future<NitriteCollection> getCollection(String name);

/// Gets an [ObjectRepository] to perform ACID operations on it.
/// Gets an [ObjectRepository] to perform transactional operations on it.
Future<ObjectRepository<T>> getRepository<T>(
{EntityDecorator<T>? entityDecorator, String? key});

/// Completes the transaction and commits the data to the underlying store.
Future<void> commit();

/// Rolls back the transaction, discarding any changes made during
/// Rolls back the transaction, discarding any changes made during
/// the transaction.
Future<void> rollback();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -114,31 +114,29 @@ Future<void> cleanUp() async {
}

Future<void> _openDb() async {
var nitriteBuilder = Nitrite.builder().fieldSeparator('.');
db = await nitriteBuilder.openOrCreate(
username: 'test-user', password: 'test-password');

var mapper = db.config.nitriteMapper as SimpleNitriteMapper;
mapper.registerEntityConverter(CompanyConverter());
mapper.registerEntityConverter(EmployeeConverter());
mapper.registerEntityConverter(NoteConverter());
mapper.registerEntityConverter(MyBookConverter());
mapper.registerEntityConverter(BookIdConverter());
mapper.registerEntityConverter(ClassAConverter());
mapper.registerEntityConverter(ClassBConverter());
mapper.registerEntityConverter(ClassCConverter());
mapper.registerEntityConverter(ElemMatchConverter());
mapper.registerEntityConverter(TextDataConverter());
mapper.registerEntityConverter(SubEmployeeConverter());
mapper.registerEntityConverter(ProductScoreConverter());
mapper.registerEntityConverter(PersonEntityConverter());
mapper.registerEntityConverter(RepeatableIndexTestConverter());
mapper.registerEntityConverter(EncryptedPersonConverter());
mapper.registerEntityConverter(TxDataConverter());
mapper.registerEntityConverter(WithNitriteIdConverter());
mapper.registerEntityConverter(ProductConverter());
mapper.registerEntityConverter(ProductIdConverter());
mapper.registerEntityConverter(ManufacturerConverter());
mapper.registerEntityConverter(MiniProductConverter());
mapper.registerEntityConverter(WithNullIdConverter());
db = await Nitrite.builder()
.registerEntityConverter(CompanyConverter())
.registerEntityConverter(EmployeeConverter())
.registerEntityConverter(NoteConverter())
.registerEntityConverter(MyBookConverter())
.registerEntityConverter(BookIdConverter())
.registerEntityConverter(ClassAConverter())
.registerEntityConverter(ClassBConverter())
.registerEntityConverter(ClassCConverter())
.registerEntityConverter(ElemMatchConverter())
.registerEntityConverter(TextDataConverter())
.registerEntityConverter(SubEmployeeConverter())
.registerEntityConverter(ProductScoreConverter())
.registerEntityConverter(PersonEntityConverter())
.registerEntityConverter(RepeatableIndexTestConverter())
.registerEntityConverter(EncryptedPersonConverter())
.registerEntityConverter(TxDataConverter())
.registerEntityConverter(WithNitriteIdConverter())
.registerEntityConverter(ProductConverter())
.registerEntityConverter(ProductIdConverter())
.registerEntityConverter(ManufacturerConverter())
.registerEntityConverter(MiniProductConverter())
.registerEntityConverter(WithNullIdConverter())
.fieldSeparator('.')
.openOrCreate(username: 'test-user', password: 'test-password');
}
4 changes: 2 additions & 2 deletions packages/nitrite_entity_generator/lib/src/entity_writer.dart
Original file line number Diff line number Diff line change
Expand Up @@ -89,15 +89,15 @@ class EntityWriter {
builder.returns = refer('EntityId');

var isNitriteId = _entityInfo.entityId!.isNitriteId;
if (_entityInfo.entityId!.subFields.isEmpty) {
if (_entityInfo.entityId!.embeddedFields.isEmpty) {
builder.body = Code(
'EntityId("${_entityInfo.entityId!.fieldName}", $isNitriteId)');
} else {
builder.body = Code('''
EntityId(
"${_entityInfo.entityId!.fieldName}",
$isNitriteId,
[${_entityInfo.entityId!.subFields.map((field) => '"$field"').join(', ')}],
[${_entityInfo.entityId!.embeddedFields.map((field) => '"$field"').join(', ')}],
)
''');
}
Expand Down
Loading

0 comments on commit 60329ed

Please sign in to comment.