Skip to content
This repository has been archived by the owner on May 7, 2023. It is now read-only.

5.0.0 preview : type safe api #26

Closed
synw opened this issue Apr 11, 2020 · 0 comments
Closed

5.0.0 preview : type safe api #26

synw opened this issue Apr 11, 2020 · 0 comments

Comments

@synw
Copy link
Owner

synw commented Apr 11, 2020

A new type safe api has landed in master and will be introduced in version 5.0.0. Instead of dealing with maps it provides DbRow and typed DbRecord objects.

Note: the original api will still work, backward compatibility is guarantied. The example has been updated to use this api. Feel free to post what you think about this

Type safe api

Create a schema:

DbTable category = DbTable("category")..varchar("name", unique: true);
DbTable product = DbTable("product")
   ..varchar("name", unique: true)
   ..integer("price")
   ..text("descripton", nullable: true)
   ..foreignKey("category", onDelete: OnDelete.cascade)
   ..index("name");
List<DbTable> schema = [category, product];

Initialize a database:

final SqlDb db = SqlDb();
String dbpath = "db.sqlite"; // relative to the documents directory
try {
  await db.init(path: dbpath, schema: schema);
} catch(e) {
  rethrow;
}

Insert

try {
  final lastInsertedId = await db.insert(
      table: "product",
      row: DbRow(<DbRecord>[
        DbRecord<String>("name", "Product 2"),
        DbRecord<int>("price", 50),
        DbRecord<int>("category", 1),
      ]));
} catch (e) {
  rethrow;
}

Select

try {
  final List<DbRow> rows = await db.select(
      table: "product",
      limit: 20,
      columns: "id,name",
      where: "name LIKE '%something%'",
      orderBy: "name ASC");
  rows.forEach((row) {
    final int id = row.record<int>("id");
    final String name = row.record<String>("name");
    print("Product : $id $name");
  });
} catch (e) {
  rethrow;
}
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

1 participant