flutterdartdriftflutter-moor

Drift syntax to create an index


Given this table:

class TodoCategories extends Table {
  IntColumn get age => integer()();
  TextColumn get name => text()();
}

how can I add an index to the name column? I see from the documentation there is an Index class, but I'm not clear how to use it.


Solution

  • I found a comment in the source code (index.dart) stating that indexes can be created only in .drift files. In my case, I had to move all of the sql into .drift files to get it to work. There is no mention in the documentation of whether it is possible to create Drift tables in both the dart files and the .drift files, but when I tried it, it failed silently.

    So to answer the question, create a file like

    tables.drift
    
    CREATE TABLE TodoCategories(
       age INTEGER NOT NULL,
       name TEXT NOT NULL);
    
    CREATE INDEX idx on TodoCategories (name);
    

    In the dart source:

    @DriftDatabase(
      include: {'tables.drift'},
    )