chisel 1.2.1
chisel: ^1.2.1 copied to clipboard
A Dart library for managing PostgreSQL databases with ease.
Chisel
Chisel is a Dart library that simplifies database interaction by providing dynamic schema introspection, robust query generation, and model management. This library enables seamless CRUD operations while keeping your database models synchronized and easy to use.
Features #
- Dynamic model generation from database schemas.
- Parameterized and direct query support.
- Comprehensive CRUD operations.
- Flexible logging with contextual information.
- Integration tests for database interactions.
Getting Started #
Installation #
Add Chisel to your pubspec.yaml
:
dependencies:
chisel: ^1.0.0
Install the package:
dart pub get
Usage #
Initialize Chisel #
For the first step you will need initialize the Chisel instance with your database credentials, so for it create a file (e.g., generate_models.dart) and add this code:
import 'package:chisel/chisel.dart';
Future<void> main() async {
try {
// Initialize Chisel
final chisel = Chisel(
host: 'localhost',
port: 5432,
database: 'my_database',
user: 'my_user',
password: 'my_password',
settings: const ChiselConnectionSettings(
sslMode: SslMode.require,
),
);
// Connect to the database and introspect the schema
await chisel.initialize();
// Generate models
await chisel.generateModels(forceUpdate: true);
// Close the connection
await chisel.close();
} catch (e) {
print("Failed to generate models: $e");
}
}
Once you have done, execute the script:
run generate_models.dart
This will connect to your database, introspect the schema, and generate models automatically.
Generating Models #
Chisel can introspect your database schema and generate models for each table. These models are placed in a directory under lib/models/[database_name]
.
await chisel.generateModels();
By default, Chisel checks if models have already been generated to avoid unnecessary regeneration. If you need to force regeneration (e.g., after schema changes), you can use the forceUpdate
parameter:
await chisel.generateModels(forceUpdate: true);
- Default Behavior: If models are already up-to-date, the generation process is skipped.
- Force Update: Setting
forceUpdate
totrue
will regenerate models, even if they already exist.
For example, if your database contains a table auth_user
, Chisel generates a corresponding Dart model AuthUser
. You can then import and use the model as follows:
import 'package:chisel/models/[database_name]/auth_user.dart';
Example Workflow #
Below is a comprehensive example showcasing Chisel’s key functionalities.
Fetch Tables and Schema
final tables = await chisel.getTables();
print('Tables: $tables');
final schema = await chisel.introspectSchema();
print('Schema: $schema');
Use Generated Models
Once models are generated, you can perform CRUD operations using these models.
- IMPORTANT:
- After provide the "Map<String, dynamic> parameters" field, you need provide a field "String fieldIfcreated" to validate if it was really created, preferably a unique field.
- Due to lib dependencies problems it was a temporary workaround.
- The example below used "email".
Create a Record
final user = await AuthUser().create({
'username': 'johndoe',
'email': 'johndoe@example.com',
'password': 'securepassword',
'is_active': true,
'date_joined': DateTime.now().toIso8601String(),
}, "email");
print('Created user: ${user.username}');
Read a Record
final fetchedUser = await AuthUser().read('username', 'johndoe');
print('Fetched user: ${fetchedUser?.email}');
Update a Record
final updatedUser = await AuthUser().update('username', 'johndoe', {
'email': 'newemail@example.com',
});
print('Updated user email: ${updatedUser.email}');
Delete a Record
await AuthUser().delete('username', 'johndoe');
print('User deleted successfully!');
Logging #
Chisel provides robust logging for debugging SQL queries and operations. You can enable or disable logging and set the log level:
chisel.configureLogging(level: LogLevel.info, enable: true);
Limitations and Improvements #
- Insert/Update Without Direct Result: Due to limitations in the Postgres library, the
create
andupdate
methods first execute the query and then retrieve the result by re-reading the table. - Future Enhancements:
- Provide an option for external model generation: Allow users to generate models into their own project directory via
generateModels(outputDirectory: ...)
.
- Provide an option for external model generation: Allow users to generate models into their own project directory via
Testing #
Chisel includes integration tests to ensure correct functionality.
void main() {
group('Chisel Database Integration Tests', () {
late Chisel chisel;
setUp(() async {
chisel = Chisel(
host: 'localhost',
port: 5432,
database: 'test_db',
user: 'test_user',
password: 'test_password',
settings: ConnectionSettings(sslMode: SslMode.require),
);
await chisel.initialize();
});
tearDown(() async {
await chisel.close();
});
test('Fetch tables', () async {
final tables = await chisel.getTables();
expect(tables, isNotEmpty);
});
});
}
Future Plans #
- Provide external model generation to allow users to manage their models independently.
- Enhance support for complex query operations and transactions.
- Introduce support for advanced schema migrations.
Contributions #
Contributions are welcome! Please open an issue or create a pull request on GitHub Repo.
License #
Chisel is open-source and licensed under the MIT License.