Class CodeGenerator
Base class for code generators that produce SQL scripts for database schema and data export. This class implements the visitor pattern to traverse the database schema and generate appropriate SQL statements. Derived classes should override the visit methods to provide provider-specific SQL generation logic. The class also manages output writing and supports options for controlling the export process, such as whether to include schema, data, foreign keys, etc. The class implements IDisposable to allow for proper resource management of the output stream, especially when writing to files.
public abstract class CodeGenerator : IVisitor, IDisposable
- Inheritance
-
CodeGenerator
- Implements
- Derived
- Inherited Members
Constructors
CodeGenerator()
Initializes a new instance of the CodeGenerator class that writes output to the console.
protected CodeGenerator()
CodeGenerator(TextWriter)
Initializes a new instance of the CodeGenerator class with the specified TextWriter for output.
protected CodeGenerator(TextWriter output)
Parameters
outputTextWriterThe TextWriter to which the generated SQL will be written. Must not be null.
CodeGenerator(string)
Initializes a new instance of the CodeGenerator class that writes output to a file at the specified path.
protected CodeGenerator(string path)
Parameters
pathstringThe file path where the generated SQL will be written. The file will be created if it does not exist, or appended to if it does. Must not be null or empty.
Properties
ExportOptions
Gets or sets the export options that control the behavior of the code generation process, such as whether to include schema, data, foreign keys, identities, etc.
public ExportOptions ExportOptions { get; set; }
Property Value
GeneratesRowVersion
Gets a value indicating whether this code generator generates row version columns as part of the data export process.
protected virtual bool GeneratesRowVersion { get; }
Property Value
Output
Gets the TextWriter to which the generated SQL will be written. This property is initialized through the constructor and is used by the code generator to output the generated SQL statements.
public TextWriter Output { get; }
Property Value
ProviderName
Gets the name of the database provider for which this code generator is designed to generate SQL scripts.
public abstract string ProviderName { get; }
Property Value
RequireInlineConstraints
Gets a value indicating whether this code generator requires foreign key constraints to be included inline within the CREATE TABLE statements, as opposed to being generated as separate ALTER TABLE statements after the tables are created.
protected virtual bool RequireInlineConstraints { get; }
Property Value
SupportsDbCreation
Gets a value indicating whether this code generator supports generating a CREATE DATABASE statement as part of the export process.
protected virtual bool SupportsDbCreation { get; }
Property Value
Methods
Dispose()
Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
public void Dispose()
Dispose(bool)
Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
protected virtual void Dispose(bool disposing)
Parameters
disposingboolA value indicating whether the method has been called directly or indirectly by a user's code. If true, both managed and unmanaged resources can be disposed; if false, only unmanaged resources should be released.
Escape(string)
Escapes the given name (e.g., table name, column name) according to the syntax rules of the target database provider.
protected virtual string Escape(string name)
Parameters
namestringThe name to be escaped. This could be a table name, column name, or any identifier that may require escaping to avoid conflicts with reserved keywords or special characters.
Returns
- string
A string representing the escaped name, formatted according to the conventions of the target database provider.
Format(object, ColumnType)
Formats a value for inclusion in a SQL statement, taking into account the value's type and the corresponding column type.
protected virtual string Format(object value, ColumnType columnType)
Parameters
valueobjectThe value to be formatted for inclusion in a SQL statement. This could be a default value for a column, a value being inserted into a table, or any other value that needs to be represented as a literal in the generated SQL. The method will determine how to format this value based on its type and the specified column type, ensuring that it is correctly represented in the SQL syntax for the target database provider.
columnTypeColumnTypeThe column type that corresponds to the value being formatted. This information is used to determine how to format the value, such as whether to quote it, how to format dates and times, how to represent binary data, etc., according to the conventions of the target database provider.
Returns
- string
A string representing the formatted value, ready to be included as a literal in a SQL statement, formatted according to the conventions of the target database provider.
Get(string, TextWriter)
Factory method to create an instance of a CodeGenerator subclass based on the provided database provider name.
public static CodeGenerator Get(string providerName, TextWriter output)
Parameters
providerNamestringThe name of the database provider for which to create a code generator. Supported values include: "Microsoft.Data.SqlClient" for SQL Server, "Oracle.ManagedDataAccess.Client" for Oracle, "MySqlConnector" for MySQL, "Npgsql" for PostgreSQL, "FirebirdSql.Data.FirebirdClient" for Firebird, and "System.Data.SQLite" for SQLite. Must not be null or empty.
outputTextWriterThe TextWriter to which the generated SQL will be written. Must not be null.
Returns
- CodeGenerator
A CodeGenerator instance specific to the given provider name, initialized with the provided output TextWriter.
Exceptions
- ArgumentException
When the providerName is not recognized as a supported database provider.
GetForeignKeyRuleText(ForeignKeyRule)
Gets the text representation of a foreign key rule (such as ON UPDATE or ON DELETE actions) based on the specified rule.
protected virtual string GetForeignKeyRuleText(ForeignKeyRule rule)
Parameters
ruleForeignKeyRuleThe foreign key rule for which to get the text representation.
Returns
- string
A string representing the text of the foreign key rule, such as "CASCADE", "SET NULL", "RESTRICT", etc., formatted according to the conventions of the target database provider.
GetKeyName(Key)
Gets the name to be used for a key (such as an index or foreign key constraint) in the generated SQL.
protected virtual string GetKeyName(Key key)
Parameters
keyKeyThe key for which to get the name. This method is called when generating SQL for indexes and foreign key constraints, and it determines how to name these keys in the generated SQL. The default implementation returns the escaped name of the key, but derived classes can override this method to provide different naming conventions or to include additional information in the key name as needed by the target database provider.
Returns
- string
A string representing the name to be used for the key in the generated SQL, formatted according to the conventions of the target database provider.
GetTypeName(Column)
Gets the SQL type name for the given column, taking into account the column's data type and any provider-specific type mappings.
protected virtual string GetTypeName(Column column)
Parameters
columnColumnThe column for which to determine the SQL type name. The method will consider the column's ColumnType and, if it is a user-defined type, its associated DataType to determine the appropriate SQL type name.
Returns
- string
A string representing the SQL type name for the column, formatted according to the conventions of the target database provider.
GetTypeName(IDataItem)
Gets the SQL type name for the given data item, which could be a column or a user-defined data type.
protected virtual string GetTypeName(IDataItem item)
Parameters
itemIDataItemThe data item for which to determine the SQL type name. This could be a column or a user-defined data type. The method will use the properties of the data item, such as ColumnType, Size, Precision, and Scale, to determine the appropriate SQL type name, potentially using provider-specific type mappings and formatting rules.
Returns
- string
A string representing the SQL type name for the data item, formatted according to the conventions of the target database provider.
GetTypeReference(DataType)
Gets the SQL type reference for a user-defined data type, which may involve referencing the data type by name or using a specific syntax depending on the target database provider.
protected virtual string GetTypeReference(DataType dataType)
Parameters
dataTypeDataTypeThe user-defined data type for which to get the SQL type reference. This method is called when a column has a ColumnType of UserDefined, and the column's DataType property is not null. The method will determine how to reference this user-defined data type in the generated SQL, which may involve using the data type's name or a specific syntax depending on the conventions of the target database provider.
Returns
- string
A string representing the SQL type reference for the user-defined data type, formatted according to the conventions of the target database provider.
Indent()
Increases the indentation level for the generated SQL output. This method is typically called when entering a new block of SQL statements, such as after a CREATE TABLE statement, to ensure that the generated SQL is properly indented for readability. The indentation level is managed internally, and the Write methods will use this indentation level to prefix lines with the appropriate number of tabs or spaces according to the conventions of the target database provider. The Unindent method should be called when exiting a block to decrease the indentation level accordingly.
protected void Indent()
Unindent()
Decreases the current indentation level by one, ensuring it does not fall below zero.
protected void Unindent()
VisitColumn(Column)
Visits a Column object, allowing the visitor to perform operations on the column schema.
public virtual void VisitColumn(Column column)
Parameters
columnColumnThe Column object to be visited.
VisitDataType(DataType)
Visits a DataType object, allowing the visitor to perform operations on the data type schema.
public virtual void VisitDataType(DataType dataType)
Parameters
dataTypeDataTypeThe DataType object to be visited.
VisitDatabase(Database)
Visits a Database object, allowing the visitor to perform operations on the database schema. This method is the entry point for traversing the database structure.
public virtual void VisitDatabase(Database database)
Parameters
databaseDatabaseThe Database object to be visited.
VisitForeignKey(ForeignKey)
Visits a ForeignKey object, allowing the visitor to perform operations on the foreign key schema.
public virtual void VisitForeignKey(ForeignKey foreignKey)
Parameters
foreignKeyForeignKeyThe ForeignKey object to be visited.
VisitIndex(Index)
Visits an Index object, allowing the visitor to perform operations on the index schema.
public virtual void VisitIndex(Index index)
Parameters
indexIndexThe Index object to be visited.
VisitPrimaryKey(PrimaryKey)
Visits a PrimaryKey object, allowing the visitor to perform operations on the primary key schema.
public virtual void VisitPrimaryKey(PrimaryKey primaryKey)
Parameters
primaryKeyPrimaryKeyThe PrimaryKey object to be visited.
VisitTable(Table)
Visits a Table object, allowing the visitor to perform operations on the table schema.
public virtual void VisitTable(Table table)
Parameters
tableTableThe Table object to be visited.
Write(char)
Writes a single character to the output, respecting the current indentation level.
protected void Write(char c)
Parameters
ccharThe character to write. Carriage return characters are ignored.
Write(string)
Writes the specified string to the underlying output.
protected void Write(string s)
Parameters
sstringThe string to write. Must not be null.
Write(string, params object[])
Writes a formatted string to the output stream.
protected void Write(string format, params object[] values)
Parameters
formatstringA composite format string.
valuesobject[]An array of objects to format and write to the output stream.
WriteComment(string, params object[])
Writes a comment line to the output, formatted according to the conventions of the target database provider.
protected virtual void WriteComment(string format, params object[] args)
Parameters
formatstringA format string that describes the content of the comment. This string can include placeholders for arguments, which will be replaced by the corresponding values in the args parameter.
argsobject[]The arguments to be formatted into the comment string. These values will replace the placeholders in the format string, allowing for dynamic content to be included in the comment based on the context of the code generation process, such as database name, generation timestamp, author, etc.
WriteDataMigrationPrefix()
Writes any necessary SQL statements or directives that should be included before the data migration (INSERT statements) for the tables.
protected virtual void WriteDataMigrationPrefix()
WriteDataMigrationSuffix()
Writes any necessary SQL statements or directives that should be included after the data migration (INSERT statements) for the tables.
protected virtual void WriteDataMigrationSuffix()
WriteDbCreationDirective(Database)
Writes a CREATE DATABASE statement for the given database, according to the syntax rules of the target database provider.
protected virtual void WriteDbCreationDirective(Database database)
Parameters
databaseDatabaseThe database for which to write the CREATE DATABASE statement. This method will generate the appropriate SQL to create the database, including the database name and any necessary syntax according to the conventions of the target database provider. This method is called if the code generator supports database creation and if the export options indicate that the schema should be exported.
WriteDeleteRule(ForeignKeyRule)
Writes the syntax for the ON DELETE clause of a foreign key constraint, based on the specified delete rule.
protected virtual void WriteDeleteRule(ForeignKeyRule deleteRule)
Parameters
deleteRuleForeignKeyRuleThe foreign key rule that specifies the action to be taken when a referenced row is deleted. This method will generate the appropriate SQL syntax for the ON DELETE clause of a foreign key constraint, based on the value of the deleteRule parameter, which can indicate actions such as CASCADE, SET NULL, SET DEFAULT, etc., according to the conventions of the target database provider.
WriteDelimiter()
Writes a statement delimiter (such as a semicolon) to the output, according to the syntax rules of the target database provider.
protected virtual void WriteDelimiter()
WriteIdentitySpecification(Column)
Writes the identity specification for the specified column.
protected virtual void WriteIdentitySpecification(Column column)
Parameters
columnColumnThe column for which the identity specification is being written.
WriteInsertDirective(Table, DbDataReader)
Writes an INSERT statement for the given table and data reader, generating the appropriate SQL syntax to insert a row of data into the table.
protected virtual void WriteInsertDirective(Table table, DbDataReader dr)
Parameters
tableTableThe table into which the data will be inserted. This method will generate an INSERT statement that targets this table, including the table name and the columns for which data will be inserted.
drDbDataReaderA DbDataReader that contains the data to be inserted into the table. This method will read values from this data reader to generate the VALUES clause of the INSERT statement, formatting each value according to its type and the corresponding column type, and ensuring that the generated SQL correctly represents the data for insertion into the target database.
WriteLine()
Writes a new line to the current output stream.
protected void WriteLine()
WriteLine(string)
Writes a string followed by a line terminator to the output.
protected void WriteLine(string s)
Parameters
sstringThe string to write. If null, only a line terminator is written.
WriteLine(string, params object[])
Writes a formatted line, followed by a line termination string, to the output.
protected void WriteLine(string format, params object[] values)
Parameters
formatstringThe composite format string. Cannot be null or empty.
valuesobject[]An array of objects to format using the specified format string. Can be null if no formatting is required.
WriteTableCreationSuffix(Table)
Writes any additional SQL syntax that should be included at the end of a CREATE TABLE statement for the given table.
protected virtual void WriteTableCreationSuffix(Table table)
Parameters
tableTableThe table for which to write the table creation suffix. This method can be overridden by derived classes to include additional syntax after the closing parenthesis of a CREATE TABLE statement, such as table options, storage engine specifications, or other provider-specific syntax that should be included when creating a table.
WriteUpdateRule(ForeignKeyRule)
Writes the syntax for the ON UPDATE clause of a foreign key constraint, based on the specified update rule.
protected virtual void WriteUpdateRule(ForeignKeyRule updateRule)
Parameters
updateRuleForeignKeyRuleThe foreign key rule that specifies the action to be taken when a referenced row is updated. This method will generate the appropriate SQL syntax for the ON UPDATE clause of a foreign key constraint, based on the value of the updateRule parameter, which can indicate actions such as CASCADE, SET NULL, SET DEFAULT, etc., according to the conventions of the target database provider.