Skip to content

Commit

Permalink
add custom mysql rename for version below 8
Browse files Browse the repository at this point in the history
  • Loading branch information
invisal committed Oct 14, 2024
1 parent f4b83e2 commit c25f46b
Showing 1 changed file with 65 additions and 0 deletions.
65 changes: 65 additions & 0 deletions src/connections/mysql.ts
Original file line number Diff line number Diff line change
Expand Up @@ -265,8 +265,73 @@ export class MySQLConnection extends SqlConnection {
});
}

async renameColumn(
schemaName: string | undefined,
tableName: string,
columnName: string,
newColumnName: string
): Promise<void> {
// Check the MySQL version
const { data: version } = await this.query<{ version: string }>({
query: 'SELECT VERSION() AS version',
});

const fullTableName = this.dialect.escapeId(
schemaName ? `${schemaName}.${tableName}` : tableName
);

const versionNumber = parseInt(version[0].version.split('.')[0]);
if (versionNumber < 8) {
// We cannot rename column in MySQL version less than 8 using RENAME COLUMN
// We need to get the CREATE SCRIPT of the table
const { data: createTableResponse } = await this.query<{
Create_Table: string;
}>({
query: `SHOW CREATE TABLE ${fullTableName}`,
});

// Cannot rename column if the table does not exist
if (createTableResponse.length === 0) return;

// Get the line of the column
const createTable = createTableResponse[0].Create_Table;
const lists = createTable.split('\n');
const columnLine = lists.find((line) =>
line
.trim()
.toLowerCase()
.startsWith(this.dialect.escapeId(columnName).toLowerCase())
);

if (!columnLine) return;
const [columnNamePart, ...columnDefinitions] =
columnLine.split(' ');

const query = `ALTER TABLE ${fullTableName} CHANGE ${columnNamePart} ${this.dialect.escapeId(newColumnName)} ${columnDefinitions.join(' ')}`;
await this.query({ query });
}

return super.renameColumn(
schemaName,
tableName,
columnName,
newColumnName
);
}

async connect(): Promise<any> {}
async disconnect(): Promise<any> {
this.conn.destroy();
}
}

/*
CREATE TABLE `album` (
`AlbumId` int NOT NULL,
`Title` varchar(160) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
`ArtistId` int NOT NULL,
PRIMARY KEY (`AlbumId`),
KEY `IFK_AlbumArtistId` (`ArtistId`),
CONSTRAINT `FK_AlbumArtistId` FOREIGN KEY (`ArtistId`) REFERENCES `artist` (`ArtistId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci
*/

0 comments on commit c25f46b

Please sign in to comment.