Skip to content

Commit

Permalink
renaming for clarity after review comments
Browse files Browse the repository at this point in the history
  • Loading branch information
LiranCohen committed Apr 23, 2024
1 parent ef4c3f5 commit d9a3fcd
Show file tree
Hide file tree
Showing 8 changed files with 28 additions and 30 deletions.
14 changes: 6 additions & 8 deletions src/dialect/dialect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,27 +39,25 @@ export interface Dialect extends KyselyDialect {
* @param onDeleteAction the action to take when the referenced row is deleted.
*
* The ForeignKey name it creates in `mysql` will be in the following format:
* `${referenceTable}${referenceColumnName}_${tableName}${columnName}`
* `${referenceTable}_${referenceColumnName}__${tableName}_${columnName}`
* ex: if the reference table is `users` and the reference column is `id` and the table is `profiles` and the column is `userId`,
* the resulting name for the foreign key is: `usersid_profilesuserId`
* the resulting name for the foreign key is: `users_id__profiles_userId`
*
* @returns {CreateTableBuilder} the CreateTableBuilder with the added column.
*/
addReferencedColumn<TB extends string>(
builder: CreateTableBuilder<TB & string>,
tableName: TB,
columnName: string,
targetType: ColumnDataType,
columnType: ColumnDataType,
referenceTable: string,
referenceColumnName: string,
onDeleteAction: 'cascade' | 'no action' | 'restrict' | 'set null' | 'set default',
): CreateTableBuilder<TB & string>;

/**
* This is a helper method to return an `insertId` for each dialect.
* We need this method because Postgres does not return an `insertId` with insert an insert.
*
* Since `returning` is supported on both `sqlite` and `postgres`, it will be used on those and ignored on `mysql`.
* This is a helper method to return an `insertId` across all dialects after inserting values.
* `postgres` and `sqlite` both support the `returning` clause, however `mysql` does not and instead returns the last inserted id.
*
* @param db the Kysely DB object or a DB Transaction.
* @param table the table to insert into.
Expand All @@ -72,7 +70,7 @@ export interface Dialect extends KyselyDialect {
*
* @returns {InsertQueryBuilder} object to further modify the query or execute it.
*/
insertIntoReturning<DB, TB extends keyof DB = keyof DB, SE extends SelectExpression<DB, TB & string> = any>(
insertThenReturnId<DB, TB extends keyof DB = keyof DB, SE extends SelectExpression<DB, TB & string> = any>(
db: Transaction<DB> | Kysely<DB>,
table: TB & string,
values: InsertObject<DB, TB & string>,
Expand Down
8 changes: 4 additions & 4 deletions src/dialect/mysql-dialect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,23 +42,23 @@ export class MysqlDialect extends KyselyMysqlDialect implements Dialect {
builder: CreateTableBuilder<TB & string>,
tableName: TB,
columnName: string,
targetType: ColumnDataType,
columnType: ColumnDataType,
referenceTable: string,
referenceColumnName: string,
onDeleteAction: 'cascade' | 'no action' | 'restrict' | 'set null' | 'set default',
): CreateTableBuilder<TB & string> {
return builder
.addColumn(columnName, targetType, (col) => col.notNull())
.addColumn(columnName, columnType, (col) => col.notNull())
.addForeignKeyConstraint(
`${referenceTable}${referenceColumnName}_${tableName}${columnName}`,
`${referenceTable}_${referenceColumnName}__${tableName}_${columnName}`,
[columnName],
referenceTable,
[referenceColumnName],
(constraint) => constraint.onDelete(onDeleteAction)
);
}

insertIntoReturning<DB, TB extends keyof DB = keyof DB, SE extends SelectExpression<DB, TB & string> = AnyColumn<DB, TB>>(
insertThenReturnId<DB, TB extends keyof DB = keyof DB, SE extends SelectExpression<DB, TB & string> = AnyColumn<DB, TB>>(
db: Transaction<DB> | Kysely<DB>,
table: TB & string,
values: InsertObject<DB, TB & string>,
Expand Down
8 changes: 4 additions & 4 deletions src/dialect/postgres-dialect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,17 +33,17 @@ export class PostgresDialect extends KyselyPostgresDialect implements Dialect {

addReferencedColumn<TB extends string>(
builder: CreateTableBuilder<TB & string>,
tableName: TB,
_tableName: TB,
columnName: string,
targetType: ColumnDataType,
columnType: ColumnDataType,
referenceTable: string,
referenceColumnName: string,
onDeleteAction: 'cascade' | 'no action' | 'restrict' | 'set null' | 'set default',
): CreateTableBuilder<TB & string> {
return builder.addColumn(columnName, targetType, (col) => col.notNull().references(`${referenceTable}.${referenceColumnName}`).onDelete(onDeleteAction));
return builder.addColumn(columnName, columnType, (col) => col.notNull().references(`${referenceTable}.${referenceColumnName}`).onDelete(onDeleteAction));
}

insertIntoReturning<DB, TB extends keyof DB = keyof DB, SE extends SelectExpression<DB, TB & string> = any>(
insertThenReturnId<DB, TB extends keyof DB = keyof DB, SE extends SelectExpression<DB, TB & string> = any>(
db: Transaction<DB> | Kysely<DB>,
table: TB & string,
values: InsertObject<DB, TB & string>,
Expand Down
6 changes: 3 additions & 3 deletions src/dialect/sqlite-dialect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,15 +41,15 @@ export class SqliteDialect extends KyselySqliteDialect implements Dialect {
builder: CreateTableBuilder<TB & string>,
_tableName: TB,
columnName: string,
targetType: ColumnDataType,
columnType: ColumnDataType,
referenceTable: string,
referenceColumnName: string,
onDeleteAction: 'cascade' | 'no action' | 'restrict' | 'set null' | 'set default',
): CreateTableBuilder<TB & string> {
return builder.addColumn(columnName, targetType, (col) => col.notNull().references(`${referenceTable}.${referenceColumnName}`).onDelete(onDeleteAction));
return builder.addColumn(columnName, columnType, (col) => col.notNull().references(`${referenceTable}.${referenceColumnName}`).onDelete(onDeleteAction));
}

insertIntoReturning<DB, TB extends keyof DB = keyof DB, SE extends SelectExpression<DB, TB & string> = any>(
insertThenReturnId<DB, TB extends keyof DB = keyof DB, SE extends SelectExpression<DB, TB & string> = any>(
db: Transaction<DB> | Kysely<DB>,
table: TB & string,
values: InsertObject<DB, TB & string>,
Expand Down
4 changes: 2 additions & 2 deletions src/event-log-sql.ts
Original file line number Diff line number Diff line change
Expand Up @@ -125,9 +125,9 @@ export class EventLogSql implements EventLog {
...appendIndexes,
};

// we use the dialect-specific `insertIntoReturning` in order to be able to extract the `insertId`
// we use the dialect-specific `insertThenReturnId` in order to be able to extract the `insertId`
const result = await this.#dialect
.insertIntoReturning(tx, 'eventLog', eventIndexValues, 'watermark as insertId')
.insertThenReturnId(tx, 'eventLog', eventIndexValues, 'watermark as insertId')
.executeTakeFirstOrThrow();

// if tags exist, we execute those within the transaction associating them with the `insertId`.
Expand Down
8 changes: 4 additions & 4 deletions src/message-store-sql.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ export class MessageStoreSql implements MessageStore {
createTable = this.#dialect.addAutoIncrementingColumn(createTable, 'id', (col) => col.primaryKey());
createTable = this.#dialect.addBlobColumn(createTable, 'encodedMessageBytes', (col) => col.notNull());
createRecordsTagsTable = this.#dialect.addAutoIncrementingColumn(createRecordsTagsTable, 'id', (col) => col.primaryKey());
createRecordsTagsTable = this.#dialect.addReferencedColumn(createRecordsTagsTable, 'messageStoreRecordsTags', 'messageStoreId', 'integer', 'messageStore', 'id', 'cascade');
createRecordsTagsTable = this.#dialect.addReferencedColumn(createRecordsTagsTable, 'messageStoreRecordsTags', 'messageInsertId', 'integer', 'messageStore', 'id', 'cascade');
createRecordsTagValuesTable = this.#dialect.addReferencedColumn(createRecordsTagValuesTable, 'messageStoreRecordsTagValues', 'tagId', 'integer', 'messageStoreRecordsTags', 'id', 'cascade');

await createTable.execute();
Expand Down Expand Up @@ -176,9 +176,9 @@ export class MessageStoreSql implements MessageStore {
...putIndexes
};

// we use the dialect-specific `insertIntoReturning` in order to be able to extract the `insertId`
// we use the dialect-specific `insertThenReturnId` in order to be able to extract the `insertId`
const result = await this.#dialect
.insertIntoReturning(tx, 'messageStore', messageIndexValues, 'id as insertId')
.insertThenReturnId(tx, 'messageStore', messageIndexValues, 'id as insertId')
.executeTakeFirstOrThrow();

// if tags exist, we execute those within the transaction associating them with the `insertId`.
Expand Down Expand Up @@ -239,7 +239,7 @@ export class MessageStoreSql implements MessageStore {

let query = this.#db
.selectFrom('messageStore')
.leftJoin('messageStoreRecordsTags', 'messageStoreRecordsTags.messageStoreId', 'messageStore.id')
.leftJoin('messageStoreRecordsTags', 'messageStoreRecordsTags.messageInsertId', 'messageStore.id')
.leftJoin('messageStoreRecordsTagValues', 'messageStoreRecordsTagValues.tagId', 'messageStoreRecordsTags.id')
.select('messageCid')
.distinct()
Expand Down
2 changes: 1 addition & 1 deletion src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ type MessageStoreTable = {
type MessageStoreRecordsTagsTable = {
id: Generated<number>;
tag: string;
messageStoreId: number;
messageInsertId: number;
};

type MessageStoreRecordsTagValuesTable = {
Expand Down
8 changes: 4 additions & 4 deletions src/utils/tags.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,18 +17,18 @@ export class TagTables {
constructor(private dialect: Dialect, private table: 'messageStore' | 'eventLog'){}

/**
* Inserts the given tag and value associates to the parent Id.
* Inserts the given tag and value associates to the foreign column's `insertId` it is associated with.
*/
async executeTagsInsert(
id: number,
foreignInsertId: number,
tags: KeyValues,
tx: Transaction<DwnDatabaseType>,
):Promise<void> {
const tagTable = this.table === 'messageStore' ? 'messageStoreRecordsTags' : 'eventLogRecordsTags';
const tagValue = tagTable === 'messageStoreRecordsTags' ? { messageStoreId: id } : { eventLogWatermark: id };
const tagValue = tagTable === 'messageStoreRecordsTags' ? { messageInsertId: foreignInsertId } : { eventLogWatermark: foreignInsertId };

for (const tag in tags) {
const { insertId } = await this.dialect.insertIntoReturning(tx, tagTable, { ...tagValue, tag }, 'id as insertId').executeTakeFirstOrThrow();
const { insertId } = await this.dialect.insertThenReturnId(tx, tagTable, { ...tagValue, tag }, 'id as insertId').executeTakeFirstOrThrow();
const tagId = Number(insertId);
const tagValues = tags[tag];
const values = Array.isArray(tagValues) ? tagValues : [ tagValues ];
Expand Down

0 comments on commit d9a3fcd

Please sign in to comment.