ts-sql-query
ts-sql-query copied to clipboard
extract table name
Hi. It is possible to extract table name from instance?
Something like extractTableName(tCustomer) // 'customer' ?
Thanks
I've been thinking about adding some functions that allow us to get information about tables and columns, but I'm unsure what kind of situation it will be used for. Can you describe your use case or ideas about it? How can you take advantage of this information in your application?
I'm really interested in this, but I don't want to go over a theoretical idea; I would like to contrast it to real use cases.
I use union from multiple tables, and write the result of a common select to another table. The problem is that there may be many unions and I may forget to replace a table when "copy/pasting" a "union part" and it will not cause an error. For example:
const valuesFromSelect = connection
.selectFrom(ordersTableOne)
.select({
amount: ordersTableOne.amount
})
.union(connection.selectFrom(ordersTableTwo)
.select({
amount: ordersTableTwo.total
}))
.union(connection.selectFrom(ordersTableTwo)
.select({
amount: ordersTableTwo.total
}))
// another tables
await connection.insertInto(commonOrders).from(valuesFromSelect).executeInsert()
In this example, I can "copy/paste" a "part of union" and forget to change the table, so I don't get the full dataset.
For these cases, I would like to have a "helper class" that, when a union is called, checks if this table has been used before. Somethig like this:
type UnionPart<TTable extends ITableOrViewOf<DB<'Connection'>, any>> =
DynamicWhereExecutableSelectExpression<
DB<'Connection'>,
TTable,
any,
any,
NoTableOrViewRequiredView<any>,
never
>;
class WithPreventUnionDuplicate {
static create() {
return new WithPreventUnionDuplicate();
}
constructor() {
this.usedTables = new Set();
}
callUnionPart<TTable extends ITableOrViewOf<DB<'Connection'>, any>>(callpartFn: () => UnionPart<TTable>, tableName: TTable) {
return this.withRestrictPartDuplicate(callpartFn, tableName);
}
private withRestrictPartDuplicate<TTable extends ITableOrViewOf<DB<'Connection'>, any>>(cb: () => UnionPart<TTable>, tableName: TTable): UnionPart<TTable> {
const stringedTableName = extractTableName(tableName);
assert(
!this.usedTables.has(stringedTableName),
`Fields from ${stringedTableName} already exist on union. Please, check the query`
);
this.usedTables.add(stringedTableName);
return cb();
}
private usedTables: Set<string>;
}
Thanks