pg_wrapper 0.1.1
pg_wrapper: ^0.1.1 copied to clipboard
A simple wrapper for executing queries using the postgresql package.
pg_wrapper #
A simple wrapper for the postgresql package for dart. Several functions are provided to save time writing boilerplate code to query the database. This library does not aim to do anything amazing, but it should save small projects some time and worry about handling database connections properly.
Multiple Databases #
If you want to communicate with multiple databases, then create multiple instances of the wrapper in your code, each with a different connection string.
Examples #
Add postgresql and pg_wrapper to your pubspec.yaml file, and run pub install.
name: postgresql_example
dependencies:
postgresql: any
pg_wrapper: any
To create a new instance that will automatically connect and execute queries on the database, you will need to initialise. This can be done using a Map:
import 'package:pg_wrapper/pg_wrapper.dart';
import 'package:postgresql/postgresql.dart';
main() {
var map = new Map();
map[Settings.HOST] = "host";
map[Settings.PASSWORD] = "password";
map[Settings.PORT] = 1234;
map[Settings.USER] = "user";
map[Settings.DATABASE] = "db";
var wrapper = new DBWrapper(new Settings.fromMap(map));
}
Alternatively you can load the config from yaml:
import 'dart:io';
import 'package:pg_wrapper/pg_wrapper.dart';
import 'package:postgresql/postgresql.dart';
import 'package:yaml/yaml.dart';
main() {
var map = loadYaml(new File('test_config.yaml').readAsStringSync()),
wrapper = new DBWrapper(new Settings.fromMap(map));
}
Once initialised, the shorthand functions can be used to execute commands on the database. Each function will return a Future and queries are parameterised when necessary. The update and delete functions require you to enter a 'where clause'. If you do actually want to wipe or update a table then the executeNonQuery function will be more suitable.
For specific examples of each function, please refer to the unit tests held in the repository (but everything should be pretty self-explanatory).
Testing #
The following section has been copied directly from the postgresql repository. To run the unit tests you will need to create a database, and edit 'test/config.yaml' accordingly.
Creating a database for testing #
Change to the postgres user and run the administration commands.
sudo su postgres
createuser --pwprompt testdb
Enter password for new role: password
Enter it again: password
Shall the new role be a superuser? (y/n) n
Shall the new role be allowed to create databases? (y/n) n
Shall the new role be allowed to create more new roles? (y/n) n
createdb --owner testdb testdb
exit
Check that it worked by logging in.
psql -h localhost -U testdb -W
Enter "\q" to quit from the psql console.
License : #
The code is available under the MIT license.
