2020-04-18 20:43:02 +02:00
|
|
|
import { Serializable } from '../classes/Serializable';
|
2020-04-19 18:49:07 +02:00
|
|
|
import { PatchAction } from '../classes/PatchAction';
|
|
|
|
import { Database } from '../classes/Database';
|
2020-04-18 20:43:02 +02:00
|
|
|
|
2020-04-19 18:49:07 +02:00
|
|
|
export class RenameColumn implements Serializable, PatchAction {
|
|
|
|
public table: string;
|
2020-04-18 20:43:02 +02:00
|
|
|
public column: string;
|
|
|
|
public new_name: string;
|
|
|
|
|
2020-04-19 18:49:07 +02:00
|
|
|
public constructor (
|
|
|
|
column: string,
|
|
|
|
new_name: string|null = null,
|
|
|
|
table: string|null = null
|
|
|
|
) {
|
|
|
|
if (new_name === null || table === null) {
|
|
|
|
const regex
|
|
|
|
= /(?<table>[a-z_]+) (?<column>[a-z_]+) (?<new_name>[a-z_]+)/iu;
|
2020-04-18 20:43:02 +02:00
|
|
|
const res = regex.exec (column);
|
|
|
|
if (res === null || typeof res.groups === 'undefined')
|
|
|
|
throw new Error ('invalid string to deserialize');
|
|
|
|
|
|
|
|
this.column = res.groups.column;
|
|
|
|
this.new_name = res.groups.new_name;
|
2020-04-19 18:49:07 +02:00
|
|
|
this.table = res.groups.table;
|
2020-04-18 20:43:02 +02:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
this.column = column;
|
2020-04-19 18:49:07 +02:00
|
|
|
this.table = table;
|
|
|
|
this.new_name = new_name;
|
2020-04-18 20:43:02 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
public serialize (): string {
|
2020-04-19 18:49:07 +02:00
|
|
|
return `${this.table} ${this.column} ${this.new_name}`;
|
|
|
|
}
|
|
|
|
|
|
|
|
public apply (db: Database): void {
|
|
|
|
const table = db.get_table (this.table);
|
2020-04-23 17:51:19 +02:00
|
|
|
if (typeof table === 'undefined' || table === null) {
|
|
|
|
throw new Error (
|
|
|
|
`table ${this.table} not found`
|
|
|
|
);
|
|
|
|
}
|
|
|
|
const column = table.get_column (this.column);
|
|
|
|
if (typeof column === 'undefined' || column === null) {
|
|
|
|
throw new Error (
|
|
|
|
`column ${this.column} not found in table ${this.table}`
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
column.name = this.new_name;
|
2020-04-18 20:43:02 +02:00
|
|
|
}
|
|
|
|
}
|