Modify Table type object

i have helper function that can create SQL from cross database.
function extractKeys<T extends object>(obj: T) {
return Object.keys(obj) as (keyof T)[];
}

type ReturnCrossTable<T extends Table> = {
[Key in keyof T["_"]["columns"]]: string | SQLWrapper;
} & {
table: SQL;
};

export function crossDBTable<T extends Table>(
dbName: string,
data: T,
): ReturnCrossTable<T> {
const columns = getTableColumns(data);

return extractKeys(columns).reduce(
(acc, key) => {
return Object.assign(acc, {
[key]: sql.join([sql.identifier(dbName), columns[key]], sql`.`),
});
},
{
table: sql.join([sql.identifier(dbName), data], sql`.`),
},
) as ReturnCrossTable<T>;
}
function extractKeys<T extends object>(obj: T) {
return Object.keys(obj) as (keyof T)[];
}

type ReturnCrossTable<T extends Table> = {
[Key in keyof T["_"]["columns"]]: string | SQLWrapper;
} & {
table: SQL;
};

export function crossDBTable<T extends Table>(
dbName: string,
data: T,
): ReturnCrossTable<T> {
const columns = getTableColumns(data);

return extractKeys(columns).reduce(
(acc, key) => {
return Object.assign(acc, {
[key]: sql.join([sql.identifier(dbName), columns[key]], sql`.`),
});
},
{
table: sql.join([sql.identifier(dbName), data], sql`.`),
},
) as ReturnCrossTable<T>;
}
then i want to field table can return with type Table from drizzle but with table name modified.
1 Reply
singgih
singgihOP4mo ago
i just thinking maybe if i modify the table name = db_name.table_name then drizzle can automatically parsing the value as table name from cross database. also recognize it as Table then will automatically add Select query in my innerjoin sql query. i found it
export function crossDBTable<T extends MySqlTable>(
dbName: Database,
data: T,
): T {
const tableName = `${dbName}\`.\`${getTableName(data)}`;
const table = new MySqlTable<{
name: string;
schema: undefined;
columns: T["_"]["columns"];
dialect: "mysql";
}>(tableName, undefined, tableName);

const tableColumns = getTableColumns(data);
const columns = extractKeys(tableColumns).reduce(
(acc, key) => {
const column = tableColumns[key];

return {
...acc,
[key]: Object.assign(column, {
table: table,
}),
};
},
{} as Record<string, MySqlColumn>,
);

const newTable = Object.assign(table, columns);

return newTable as unknown as T;
}
export function crossDBTable<T extends MySqlTable>(
dbName: Database,
data: T,
): T {
const tableName = `${dbName}\`.\`${getTableName(data)}`;
const table = new MySqlTable<{
name: string;
schema: undefined;
columns: T["_"]["columns"];
dialect: "mysql";
}>(tableName, undefined, tableName);

const tableColumns = getTableColumns(data);
const columns = extractKeys(tableColumns).reduce(
(acc, key) => {
const column = tableColumns[key];

return {
...acc,
[key]: Object.assign(column, {
table: table,
}),
};
},
{} as Record<string, MySqlColumn>,
);

const newTable = Object.assign(table, columns);

return newTable as unknown as T;
}
Want results from more Discord servers?
Add your server