generateTable method

String generateTable()

Implementation

String generateTable() {
  final Map tables = local2dart['table'] ?? {};
  StringBuffer bufferTable = StringBuffer();

  tables.forEach((tableName, table) {
    final String createTable =
        (table['create_if_not_exists'] as bool? ?? true)
            ? 'CREATE TABLE IF NOT EXISTS'
            : 'CREATE TABLE';
    final Map columns = table['column'] ?? {};
    final Map foreigns = table['foreign'] ?? {};

    List<String> bufferColumn = [];
    columns.forEach((columnName, column) {
      if (column is String) {
        String type = column;
        final isTypeBool = type == 'BOOL';
        if (isTypeBool) {
          type = 'INTEGER';
        }
        bufferColumn
            .add('${columnName.toString().snakeCase} ${type.toUpperCase()}');
      } else if (column is Map) {
        String type = column['type'].toString().toUpperCase();
        final isTypeBool = type == 'BOOL';
        if (isTypeBool) {
          type = 'INTEGER';
        }
        final String constraint = column['constraint'] != null
            ? ' ${column['constraint'].toString().toUpperCase()}'
            : '';
        final String autoincrement =
            (column['autoincrement'] as bool? ?? false) == true
                ? ' AUTOINCREMENT'
                : '';
        final String nullable =
            (column['nullable'] as bool? ?? true) == true ? '' : ' NOT NULL';

        String defaultValue =
            column['default'] != null ? ' DEFAULT ${column['default']}' : '';
        if (isTypeBool && column['default'] != null) {
          final value = column['default'] == true ? 1 : 0;
          defaultValue = ' DEFAULT $value';
        }

        bufferColumn.add(
            '${columnName.toString().snakeCase} $type$constraint$autoincrement$nullable$defaultValue');
      }
    });

    List<String> relation = [];
    foreigns.forEach((foreignKey, foreign) {
      final String toTable = foreign['to_table'].toString().snakeCase;
      final String toColumn = foreign['to_column'].toString().snakeCase;
      final String onUpdate = foreign['on_update'] != null
          ? ' ON UPDATE ${foreign['on_update'].toString().toUpperCase()}'
          : '';
      final String onDelete = foreign['on_delete'] != null
          ? ' ON DELETE ${foreign['on_delete'].toString().toUpperCase()}'
          : '';

      relation.add(
          'FOREIGN KEY (${foreignKey.toString().snakeCase}) REFERENCES $toTable ($toColumn)$onUpdate$onDelete');
    });

    bufferTable.writeln(
        'await db.execute("$createTable ${tableName.toString().snakeCase} (${bufferColumn.join(', ')}${relation.isEmpty ? '' : ', ${relation.join(', ')}'})");');
  });

  return bufferTable.toString();
}