SchemaBuffer class final

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

On a schema buffer, call process with the parsed statement to apply to the schema tracked on it. After adding all statements, definitions returns the transformed CREATE statement for each element.

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;
''';

Constructors

SchemaBuffer()

Properties

definitions Map<String, String>
An iterable of all schema elements currently tracked, mapping from their name to their CREATE statement.
no setter
hashCode int
The hash code for this object.
no setterinherited
runtimeType Type
A representation of the runtime type of the object.
no setterinherited

Methods

noSuchMethod(Invocation invocation) → dynamic
Invoked when a nonexistent method or property is accessed.
inherited
process(Statement statement) List<AnalysisError>
Interpret the schema against the schema managed in this buffer.
toString() String
A string representation of this object.
inherited

Operators

operator ==(Object other) bool
The equality operator.
inherited