database 0.3.0 copy "database: ^0.3.0" to clipboard
database: ^0.3.0 copied to clipboard

outdated

Enables Flutter/Dart developers use many databases. For example, SQLite, Web Storage API, Google Cloud Firestore, PostgreSQL, ElasticSearch, Algolia.

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
108
likes
0
pub points
77%
popularity

Publisher

verified publisherdint.dev

Enables Flutter/Dart developers use many databases. For example, SQLite, Web Storage API, Google Cloud Firestore, PostgreSQL, ElasticSearch, Algolia.

Repository (GitHub)
View/report issues

License

unknown (license)

Dependencies

built_collection, built_value, charcode, collection, cryptography, fixnum, meta, protobuf, universal_html, universal_io

More

Packages that depend on database