utils/schema_buffer library

Provides SchemaBuffer, a utility to patch CREATE statements with AlterTableStatements.

Example

This Dart program will parse a number of schema-altering statements and print the resulting schema (as a single CREATE TABLE statement) in the end.

import 'package:source_span/source_span.dart';
import 'package:sqlparser/sqlparser.dart';
import 'package:sqlparser/utils/schema_buffer.dart';
void main() {
  final engine = SqlEngine();
  final buffer = SchemaBuffer();

  // Parse a list of statements to apply to the schema.
  final parseResults =
      engine.parseMultiple(SourceFile.fromString(statements).span(0));
  if (parseResults.errors.isNotEmpty) {
    throw ArgumentError('Syntax error in statements: ${parseResults.errors}');
  }
  // Apply to schema
  for (final statement in parseResults.rootNode.childNodes) {
    final schemaErrors = buffer.process(statement as Statement);
    if (schemaErrors.isNotEmpty) {
      throw ArgumentError(schemaErrors.join(', '));
    }
  }
  // Print results. Note that this preserves the formatting of the original
  // CREATE TABLE statements
  for (final stmt in buffer.definitions.values) {
    print(stmt);
  }
}

const statements = '''
CREATE TABLE users (
  id INTEGER NOT NULL PRIMARY KEY,
  name TEXT NOT NULL
) STRICT;

CREATE TABLE "groups" (
  name TEXT NOT NULL
);

ALTER TABLE users RENAME TO accounts;
DROP TABLE "groups";
ALTER TABLE accounts ADD COLUMN birthdate TEXT;
ALTER TABLE accounts RENAME COLUMN name TO username;
''';

Classes

SchemaBuffer
Utility to infer a schema across multiple CREATE, DROP and ALTER TABLE statements.