Data Definition Language

Examples of using Data Definition Language (DDL) in my ORM system

In my ORM system, Data Definition Language (DDL) operations allow you to define, modify, and manage the structure of your database. Below are examples demonstrating how to use DDL in your ORM system to rename columns, delete tables, and apply these operations in migrations.

  1. Performing a DDL Operation Directly

You can execute DDL operations directly by specifying the necessary parameters. In this example, we rename the email column in the users table to gmail. The false parameter indicates that the SQL query should be executed immediately, rather than just returned as a string.

const renameEmailColumnResponse = await databaseManager.tableManipulation
    .alterTable('users', false)
    .renameColumn({ columnName: 'email', futureColumnName: 'gmail' });

console.log('renameEmailColumnResponse', renameEmailColumnResponse);

2. Generating a DDL SQL query without executing it

Sometimes you may need to generate an SQL query without immediate execution. This can be useful for logging, debugging, or query execution later. In this example, we generate a query to delete the users table, if it exists, with the ability to cascade delete related tables. The true parameter indicates that the query should be returned as a string with no execution.

const dropUserTableQuery = await databaseManager.tableManipulation
    .alterTable('users', true)
    .dropTable({ type: "CASCADE", ifExist: true });

console.log("dropUserTableQuery", dropUserTableQuery);

3. Using DDL in migrations

Migrations are a powerful way to apply changes to the database schema over time. The following example shows how to remove the username column from the users table in a migration. The up method in the migration class generates and executes the SQL query.

export class DeleteColumnMigration implements MigrationInterface {
    async up(databaseManager: DatabaseManagerInterface<DatabasesTypes.POSTGRES>): Promise<string> {
        const sql = await databaseManager.tableManipulation
            .alterTable('users', true)
            .deleteColumn({ columnName: 'username', isCascade: true });

        if (typeof sql === "string") {
            await databaseManager.query(sql);
            return sql;
        }
    }
}

These examples illustrate the flexibility and power of DDL operations in my ORM system, allowing you to efficiently manage and change the structure of your database. Whether you're executing operations immediately, generating queries for later use, or applying changes through migrations, my ORM provides all the tools you need to support your database schema.

Last updated