database 0.3.0

Pub Package Github Actions CI

Introduction #

This is database.dart, a vendor-agnostic database API for Flutter and other Dart projects.

Features #

  • 👫 Document & SQL database support. The API has been designed to support both SQL databases and document databases. You - or your customers - can always choose the best database without rewriting any code.
  • 🔭 Full-text search engine support. The API supports forwarding specific queries to search engines that can, for example, handle natural language queries better than transaction databases. There are already several search engines already supported (Algolia, ElasticSearch, and a simple search engine written in Dart).
  • 🚚 Used in commercial products. The authors use the package in enterprise applications. The package is also used by open-source projects such as Dint.

Contributing #

Supported products and APIs #

Document databases #

SQL databases #

Search engines #

Other #

Middleware #

Getting started #

1.Add dependency #

In pubspec.yaml, add:

dependencies:
  database: any

2.Choose adapter #

Look at the earlier list of adapters.

For example:

import 'package:database/database.dart';

final Database database = MemoryDatabaseAdapter().database();

Reading/writing documents #

Supported primitives #

Writing #

Upsert, delete #

// Allocate a document with a random 128-bit identifier
final document = database.collection('example').newDocument();

// Upsert, which means "inserting or updating".
await document.upsert({
  'any property': 'any value',
});

// Delete
await document.delete();

Insert, update, delete #

// Insert
final product = database.collection('product').insert({
  'name: 'Coffee mug',
  'price': 8,
})s;

// Update
await product.update(
  {
    'name': 'Coffee mug',
    'price': 12,
  },
);

// Delete
await document.delete(mustExist:true);

Reading data #

get() #

// Read a snapshot from a regional master database.
// If it's acceptable to have a locally cached version, use Reach.local.
final snapshot = await document.get(reach: Reach.regional);

// Use 'exists' to check whether the document exists
if (snapshot.exists) {
  final price = snapshot.data['price'];
  print('price: $price');
}

watch() #

By using watch function, you continue to receive updates to the document. Some databases support this natively. In other databases, watching may be accomplished by polling.

final stream = await document.watch(
  pollingInterval: Duration(seconds:2),
  reach: Reach.server,
);

Searching #

Search products with descriptions containing 'milk' or 'vegetables':

final result = await database.collection('product').search(
  query: Query.parse('description:(bread OR vegetables)'),
  reach: Reach.server,
);

for (var snapshot in result.snapshots) {
  // ...
}

Available filters #

The following logical operations are supported:

  • AndFilter([ValueFilter('f0'), ValueFilter('f1')])
  • OrFilter([ValueFilter('f0'), ValueFilter('f1')])
  • NotFilter(ValueFilter('example'))

The following primitives supported:

  • List
    • ListFilter(items: ValueFilter('value'))
  • Map
    • MapFilter({'key': ValueFilter('value')})
  • Comparisons
    • ValueFilter(3.14)
    • RangeFilter(min:3, max:4)
    • RangeFilter(min:3, max:4, isExclusiveMin:true, isExclusiveMax:true)
    • RangeFilter(min:3, max:4, isExclusiveMin:true, isExclusiveMax:true)
  • Geospatial
    • [GeoPointFilter]
      • Example: GeoPointFilter(near:GeoPoint(1.23, 3.45), maxDistance:1000)

The following special filter types are also supported:

  • SQL query
    • Example: SqlFilter('SELECT * FROM hotels WHERE breakfast = ?, price < ?', [true, 100])
    • Should be only in the root level of the query.
  • Natural language search query
    • Examples:KeywordFilter('example')
    • Keyword queries (KeyFilter) do not usually work unless you have configured a search engine for your application.

Using SQL client #

import 'package:database/sql.dart';
import 'package:database_adapter_postgre/database_adapter_postgre.dart';

Future main() async {
    // In this example, we use PostgreSQL adapter
    final database = Postgre(
      host:         'localhost',
      user:         'database user',
      password:     'database password',
      databaseName: 'example',
    ).database();

    // Construct SQL client.
    final sqlClient = database.sqlClient;

    // Select all pizza products with price less than 10.
    final pizzas = await sqlClient.query(
      'SELECT * FROM product WHERE type = ?, price < ?',
      ['pizza', 10],
    ).toMaps();

    for (var pizza in pizzas) {
      print(pizza['name']);
    }
}

Advanced usage #

Parsing search query strings #

You can parse search queries from strings. The supported syntax is very similar to other major search engines such as Lucene.

final query = Query.parse('New York Times date:>=2020-01-01');

Examples of supported queries:

  • Norwegian Forest cat
    • Matches keywords "Norwegian", "Forest", and "cat".
  • "Norwegian Forest cat"
    • A quoted keyword ensures that the words must appear as a sequence.
  • cat AND dog
    • Matches keywords "cat" and "dog" (in any order).
  • cat OR dog
    • Matches keyword "cat", "dog", or both.
  • pet -cat
    • Matches keyword "pet", but excludes documents that match keyword "cat".
  • color:brown
    • Color matches keyword "brown".
  • color:="brown"
    • Color is equal to "brown".
  • weight:>=10
    • Weight is greater than or equal to 10.
  • weight:[10 TO 20]
    • Weight is between 10 and 20, inclusive.
  • weight:{10 TO 20}
    • Weight is between 10 and 20, exclusive.
  • (cat OR dog) AND weight:>=10
    • An example of grouping filters.

In equality/range expressions, the parser recognizes patterns such as:

  • null, false, true, 3, 3.14
  • 2020-12-31 (Date)
  • 2020-12-31T00:00:00Z (DateTime)
  • Other values are interpreted as strings

[0.3.0] - January 16, 2020

  • Improves the API. Many breaking changes.

[0.2.7] - January 16, 2020

  • Improves documentation.

[0.2.6] - January 15, 2020

  • Improves the SQL API a bit.

[0.2.5] - January 15, 2020

  • Adds initial API for SQL databases.
  • Adds PostgreSQL support.

[0.2.4] - January 14, 2020

  • Fixes issues spotted during testing.

[0.2.3] - January 14, 2020

  • Fixes various small issues and improves documentation.

[0.2.2] - January 14, 2020

  • Fixes various issues.

[0.2.1] - January 13, 2020

  • Small improvements in documentation.

[0.2.0] - January 13, 2020

  • Initial release

example/example.dart

import 'package:database/database.dart';

void main() async {
  // Choose a database
  final database = MemoryDatabaseAdapter().database();

  // Search
  final response = await database.collection('people').search(
        query: Query.parse(
          '"software developer" (dart OR javascript)',
          take: 10,
        ),
      );

  // Print results
  for (var snapshot in response.snapshots) {
    print('Employee ID: ${snapshot.document.documentId}');
    print('Employee name: ${snapshot.data['name']}');
    print('');
  }
}

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:


dependencies:
  database: ^0.3.0

2. Install it

You can install packages from the command line:

with pub:


$ pub get

with Flutter:


$ flutter pub get

Alternatively, your editor might support pub get or flutter pub get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:


import 'package:database/database.dart';
  
Popularity:
Describes how popular the package is relative to other packages. [more]
67
Health:
Code health derived from static analysis. [more]
100
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
100
Overall:
Weighted score of the above. [more]
83
Learn more about scoring.

We analyzed this package on Feb 11, 2020, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.7.1
  • pana: 0.13.5

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.6.0 <3.0.0
built_collection ^4.0.0 4.3.2
built_value >=5.0.0 <8.0.0 7.0.9
charcode ^1.1.0 1.1.3
collection ^1.14.0 1.14.12
cryptography ^0.1.2 0.1.2
fixnum ^0.10.0 0.10.11
meta ^1.1.0 1.1.8
protobuf >=0.13.0 <2.0.0 1.0.1
universal_html ^1.1.0 1.1.12
universal_io ^0.8.5 0.8.6
Transitive dependencies
async 2.4.0
convert 2.1.1
crypto 2.1.4
csslib 0.16.1
html 0.14.0+3
matcher 0.12.6
path 1.6.4
petitparser 3.0.0
quiver 2.1.2+1
source_span 1.6.0
stack_trace 1.9.3
term_glyph 1.1.0
typed_data 1.1.6
xml 3.7.0
zone_local 0.1.2
Dev dependencies
pedantic ^1.8.0
test ^1.8.0