Skip to content

Commit

Permalink
restore type safety for queries (#87)
Browse files Browse the repository at this point in the history
* restore type safety for queries

* use unknown instead of any to force callers to specify a type

* Don't use async / await to ignore promise return value.

Note it generates TS80006 suggesting that we use async / await

* Revert "Don't use async / await to ignore promise return value."

This reverts commit 6c3c7c3.

---------

Co-authored-by: Michael Tsang <michael.tsang@jnction.co.uk>
  • Loading branch information
miklcct and Michael Tsang committed May 3, 2024
1 parent 949ac4c commit 6dc5661
Show file tree
Hide file tree
Showing 6 changed files with 26 additions and 17 deletions.
4 changes: 2 additions & 2 deletions src/cli/CleanFaresCommand.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ export class CleanFaresCommand implements CLICommand {
}

private async applyRestrictionDates(): Promise<void> {
const [[current, future]] = await this.db.query<RestrictionDateRow[]>("SELECT * FROM restriction_date ORDER BY cf_mkr");
const [[current, future]] = await this.db.query<RestrictionDateRow>("SELECT * FROM restriction_date ORDER BY cf_mkr");
current.start_date = new Date(current.start_date.getFullYear(), 0, 1);

future.start_date = new Date(future.start_date.getFullYear(), 0, 1);
Expand All @@ -85,7 +85,7 @@ export class CleanFaresCommand implements CLICommand {
}

private async updateRestrictionDatesOnTable(tableName: string, current: RestrictionDateRow, future: RestrictionDateRow): Promise<any> {
const [records] = await this.db.query<RestrictionRow[]>(`SELECT * FROM ${tableName}`);
const [records] = await this.db.query<RestrictionRow>(`SELECT * FROM ${tableName}`);
const promises = records.map(record => {
const date = record.cf_mkr === 'C' ? current : future;
const startDate = this.getFirstDateAfter(date.start_date, record.date_from);
Expand Down
10 changes: 8 additions & 2 deletions src/cli/DownloadCommand.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,12 @@ import {PromiseSFTP} from "../sftp/PromiseSFTP";
import {DatabaseConnection} from "../database/DatabaseConnection";
import { FileEntry } from "ssh2";

interface LogEntry {
id: number,
filename: string | null,
processed: string | null,
}

export class DownloadCommand implements CLICommand {

constructor(
Expand Down Expand Up @@ -46,9 +52,9 @@ export class DownloadCommand implements CLICommand {

private async getLastProcessedFile(): Promise<string | undefined> {
try {
const [[log]] = await this.db.query("SELECT * FROM log ORDER BY id DESC LIMIT 1");
const [[log]] = await this.db.query<LogEntry>("SELECT * FROM log ORDER BY id DESC LIMIT 1");

return log ? log.filename : undefined;
return log.filename !== null ? log.filename : undefined;
}
catch (err) {
return undefined;
Expand Down
10 changes: 5 additions & 5 deletions src/cli/ImportFeedCommand.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,8 +91,8 @@ export class ImportFeedCommand implements CLICommand {
/**
* Create the last_file table (if it doesn't already exist)
*/
private createLastProcessedSchema(): Promise<void> {
return this.db.query(`
private async createLastProcessedSchema(): Promise<void> {
await this.db.query(`
CREATE TABLE IF NOT EXISTS log (
id INT(11) unsigned not null primary key auto_increment,
filename VARCHAR(255),
Expand All @@ -105,7 +105,7 @@ export class ImportFeedCommand implements CLICommand {
* Set the last schedule ID in the CFA record
*/
private async setLastScheduleId(): Promise<void> {
const [[lastSchedule]] = await this.db.query("SELECT id FROM schedule ORDER BY id desc LIMIT 1");
const [[lastSchedule]] = await this.db.query<{id : number}>("SELECT id FROM schedule ORDER BY id desc LIMIT 1");
const lastId = lastSchedule ? lastSchedule.id : 0;
const cfaFile = this.files["CFA"] as MultiRecordFile;
const bsRecord = cfaFile.records["BS"] as RecordWithManualIdentifier;
Expand All @@ -121,8 +121,8 @@ export class ImportFeedCommand implements CLICommand {
}


private updateLastFile(filename: string): Promise<void> {
return this.db.query("INSERT INTO log VALUES (null, ?, NOW())", [filename]);
private async updateLastFile(filename: string): Promise<void> {
await this.db.query("INSERT INTO log VALUES (null, ?, NOW())", [filename]);
}

/**
Expand Down
2 changes: 1 addition & 1 deletion src/database/DatabaseConnection.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@

export interface DatabaseConnection {
getConnection(): Promise<DatabaseConnection>;
query<T = void>(sql: any, parameters?: any[]): any;
query<RowType = unknown>(sql: any, parameters?: any[]): Promise<[RowType[], any]>;
end(): Promise<void>;
release(): Promise<void>;
}
Expand Down
11 changes: 7 additions & 4 deletions src/database/MySQLTable.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,17 +83,20 @@ export class MySQLTable {
}
}

private query(type: RecordAction, rows: ParsedRecord[]): Promise<void> {
private async query(type: RecordAction, rows: ParsedRecord[]): Promise<void> {
const rowValues = rows.map(r => Object.values(r.values));

switch (type) {
case RecordAction.Insert:
case RecordAction.DelayedInsert:
return this.db.query(`INSERT IGNORE INTO \`${this.tableName}\` VALUES ?`, [rowValues]);
await this.db.query(`INSERT IGNORE INTO \`${this.tableName}\` VALUES ?`, [rowValues]);
return;
case RecordAction.Update:
return this.db.query(`REPLACE INTO \`${this.tableName}\` VALUES ?`, [rowValues]);
await this.db.query(`REPLACE INTO \`${this.tableName}\` VALUES ?`, [rowValues]);
return;
case RecordAction.Delete:
return this.db.query(`DELETE FROM \`${this.tableName}\` WHERE (${this.getDeleteSQL(rows)})`, rows.flatMap(row => Object.values(row.keysValues)));
await this.db.query(`DELETE FROM \`${this.tableName}\` WHERE (${this.getDeleteSQL(rows)})`, rows.flatMap(row => Object.values(row.keysValues)));
return;
default:
throw new Error("Unknown record action: " + type);
}
Expand Down
6 changes: 3 additions & 3 deletions src/gtfs/repository/CIFRepository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ export class CIFRepository {
* Return the interchange time between each station
*/
public async getTransfers(): Promise<Transfer[]> {
const [results] = await this.db.query<Transfer[]>(`
const [results] = await this.db.query<Transfer>(`
SELECT
crs_code AS from_stop_id,
crs_code AS to_stop_id,
Expand Down Expand Up @@ -88,7 +88,7 @@ export class CIFRepository {
*/
public async getSchedules(): Promise<ScheduleResults> {
const scheduleBuilder = new ScheduleBuilder();
const [[lastSchedule]] = await this.db.query("SELECT id FROM schedule ORDER BY id desc LIMIT 1");
const [[lastSchedule]] = await this.db.query<{id: number}>("SELECT id FROM schedule ORDER BY id desc LIMIT 1");

await Promise.all([
scheduleBuilder.loadSchedules(this.stream.query(`
Expand Down Expand Up @@ -136,7 +136,7 @@ export class CIFRepository {
* Get associations
*/
public async getAssociations(): Promise<Association[]> {
const [results] = await this.db.query<AssociationRow[]>(`
const [results] = await this.db.query<AssociationRow>(`
SELECT
a.id AS id, base_uid, assoc_uid, crs_code, assoc_date_ind, assoc_cat,
monday, tuesday, wednesday, thursday, friday, saturday, sunday,
Expand Down

0 comments on commit 6dc5661

Please sign in to comment.