createTable method

Future<void> createTable({
  1. List<String>? constraints,
  2. List<String>? options,
})

Implementation

Future<void> createTable({List<String>? constraints, List<String>? options}) async {
  SpaceBuffer buf = SpaceBuffer();
  buf << "CREATE TABLE IF NOT EXISTS $schemaTable (";
  buf << fields.joinMap(", ", (e) => defineField(e));

  final pks = fields.filter((e) => e.proto.primaryKey);
  if (pks.isNotEmpty) {
    buf << ", " << "PRIMARY KEY (${pks.map((e) => e.nameSQL).join(", ")})";
  }
  final uniqeList = fields.filter((e) => e.proto.unique || e.proto.uniqueName != null);
  if (uniqeList.isNotEmpty) {
    Map<String, List<TableColumn>> map = uniqeList.groupBy((e) => e.proto.uniqueName | "");
    for (var e in map.entries) {
      if (e.key == "") {
        for (var c in e.value) {
          buf << ", " << "UNIQUE (${c.nameSQL})";
        }
      } else {
        buf << ", " << "CONSTRAINT " << e.key.escapeSQL << " UNIQUE (${e.value.map((f) => f.nameSQL).join(", ")})";
      }
    }
  }

  if (constraints != null && constraints.isNotEmpty) {
    for (var s in constraints) {
      buf << ", " << s;
    }
  }
  buf << ")";
  if (options != null && options.isNotEmpty) {
    buf << options.join(", ");
  }
  await execute(buf.toString());

  final col = fields.firstOr((e) => e.proto.autoInc > 0);
  if (col != null) {
    await autoIncChangeBase(col, col.proto.autoInc);
  }

  for (var f in fields) {
    if (f.proto.primaryKey || f.proto.unique || notBlank(f.proto.uniqueName)) {
      continue;
    }
    if (f.proto.index) {
      await createIndex([f.columnName]);
    }
  }
}