Skip to content

Commit

Permalink
Remove unused code (#266)
Browse files Browse the repository at this point in the history
* chore: remove unused code

This enables tslint no-unused-variable options to check for unused
parameters, imports, and variables.

Ideally we'd use TypeScript's native `noUnusedLocals` and
`noUnusedParameters`, but unfortunately antlr4ts generates code that
violates this. There's an open issue about this
tunnelvisionlabs/antlr4ts#412 so if it's
eventually fixed we can swap to `noUnusedLocals`.

* Keep wire helper types

* Revert generated files

Co-authored-by: Adel <adel.m.salah@gmail.com>
  • Loading branch information
bradleyayers and adelsz committed Sep 16, 2021
1 parent c215fa9 commit 382bdb8
Show file tree
Hide file tree
Showing 16 changed files with 17 additions and 72 deletions.
4 changes: 2 additions & 2 deletions packages/cli/src/generator.ts
Expand Up @@ -62,7 +62,7 @@ export async function queryToTypeDeclarations(
queryData = processSQLQueryAST(parsedQuery.ast);
}

const typeData = await getTypes(queryData, queryName, connection);
const typeData = await getTypes(queryData, connection);
const interfaceName = pascalCase(queryName);

if ('errorCode' in typeData) {
Expand Down Expand Up @@ -210,7 +210,7 @@ async function generateTypedecsFromFile(
const { queries, events } =
mode === 'ts'
? parseTypeScriptFile(contents, fileName)
: parseSQLFile(contents, fileName);
: parseSQLFile(contents);
if (events.length > 0) {
prettyPrintEvents(contents, events);
if (events.find((e) => 'critical' in e)) {
Expand Down
2 changes: 1 addition & 1 deletion packages/cli/src/index.ts
Expand Up @@ -33,7 +33,7 @@ class FileProcessor {

constructor(private connection: any, private config: ParsedConfig) {
this.connection = connection;
this.emptyQueue = new Promise((resolve, reject) => {
this.emptyQueue = new Promise((resolve) => {
this.resolveDone = resolve;
});
}
Expand Down
6 changes: 0 additions & 6 deletions packages/cli/src/types.ts
Expand Up @@ -108,12 +108,6 @@ function declareStringUnion(name: string, values: string[]) {
return declareAlias(name, values.sort().map((v) => `'${v}'`).join(' | '));
}

function declareEnum(name: string, values: string[]) {
return `export const enum ${name} {\n${values.sort()
.map((v) => ` ${v} = '${v}',`)
.join('\n')}\n}\n`;
}

/** Wraps a TypeMapping to track which types have been used, to accumulate errors,
* and emit necessary type definitions. */
export class TypeAllocator {
Expand Down
6 changes: 0 additions & 6 deletions packages/cli/src/util.ts
@@ -1,8 +1,2 @@
import debugBase from 'debug';
export const debug = debugBase('pg-typegen');

export function assert(condition: any): asserts condition {
if (!condition) {
throw new Error('Assertion Failed');
}
}
4 changes: 1 addition & 3 deletions packages/query/src/actions.ts
Expand Up @@ -139,7 +139,6 @@ type TypeData =
*/
export async function getTypeData(
query: string,
name: string,
queue: AsyncQueue,
): Promise<TypeData> {
const uniqueName = crypto.createHash('md5').update(query).digest('hex');
Expand Down Expand Up @@ -251,10 +250,9 @@ WHERE pt.oid IN (${typeOIDs.join(',')});

export async function getTypes(
queryData: IInterpolatedQuery,
name: string,
queue: AsyncQueue,
): Promise<IQueryTypes | IParseError> {
const typeData = await getTypeData(queryData.query, name, queue);
const typeData = await getTypeData(queryData.query, queue);
if ('errorCode' in typeData) {
return typeData;
}
Expand Down
9 changes: 3 additions & 6 deletions packages/query/src/loader/sql/index.ts
Expand Up @@ -207,7 +207,7 @@ class ParseListener implements SQLParserListener {
const b = ctx.stop!.stopIndex - statement.loc.a + 1;
const body = statement.body;
assert(b);
const [partA, ignored, partB] = [
const [partA, , partB] = [
body.slice(0, a),
body.slice(a, b),
body.slice(b),
Expand Down Expand Up @@ -252,11 +252,8 @@ class ParseListener implements SQLParserListener {

export type SQLParseResult = { queries: Query[]; events: ParseEvent[] };

function parseText(
text: string,
fileName: string = 'undefined.sql',
): SQLParseResult {
const logger = new Logger(text);
function parseText(text: string): SQLParseResult {
const logger = new Logger();
const inputStream = CharStreams.fromString(text);
const lexer = new SQLLexer(inputStream);
lexer.removeErrorListeners();
Expand Down
11 changes: 2 additions & 9 deletions packages/query/src/loader/sql/logger.ts
Expand Up @@ -52,15 +52,13 @@ function styleIntervals(
intervals.sort((x, y) => x.a - y.a);
let offset = 0;
let colored = '';
let i = 0;
for (const interval of intervals) {
const a = str.slice(0, interval.a + offset);
const b = str.slice(interval.a + offset, interval.b + offset + 1);
const c = str.slice(interval.b + offset + 1, str.length);
colored = a + interval.style(b) + c;
offset += colored.length - str.length;
str = colored;
i++;
}
return colored;
}
Expand Down Expand Up @@ -114,23 +112,18 @@ export function prettyPrintEvents(text: string, parseEvents: ParseEvent[]) {

export class Logger implements ANTLRErrorListener<any> {
public parseEvents: ParseEvent[] = [];
private text: string;

constructor(text: string) {
this.text = text;
}

logEvent(event: ParseEvent) {
this.parseEvents.push(event);
}

syntaxError(
recognizer: any,
_recognizer: any,
symbol: any,
line: number,
col: number,
msg: string,
e: RecognitionException | undefined,
_e: RecognitionException | undefined,
) {
this.logEvent({
type: ParseEventType.Error,
Expand Down
9 changes: 2 additions & 7 deletions packages/query/src/loader/typescript/query.ts
Expand Up @@ -11,12 +11,7 @@ import {
QueryParser,
ScalarParamNameContext,
} from './parser/QueryParser';
import {
Logger,
ParseEvent,
ParseEventType,
ParseWarningType,
} from '../sql/logger';
import { Logger, ParseEvent } from '../sql/logger';
import { Interval } from 'antlr4ts/misc';

export enum ParamType {
Expand Down Expand Up @@ -164,7 +159,7 @@ function parseText(
text: string,
queryName: string = 'query',
): { query: Query; events: ParseEvent[] } {
const logger = new Logger(text);
const logger = new Logger();
const inputStream = CharStreams.fromString(text);
const lexer = new QueryLexer(inputStream);
lexer.removeErrorListeners();
Expand Down
7 changes: 0 additions & 7 deletions packages/query/src/preprocessor-ts.test.ts
Expand Up @@ -120,13 +120,6 @@ test('(TS) single value list parameter interpolation', () => {
'INSERT INTO users (name, age) VALUES $user(name, age) RETURNING id';
const parsedQuery = parseTSQuery(query);

const parameters = {
user: {
name: 'Bob',
age: 12,
},
};

const expectedResult = {
query: 'INSERT INTO users (name, age) VALUES ($1, $2) RETURNING id',
mapping: [
Expand Down
1 change: 0 additions & 1 deletion packages/query/src/preprocessor.ts
Expand Up @@ -72,7 +72,6 @@ export function replaceIntervals(
let result = '';
for (const interval of intervals) {
const a = str.slice(0, interval.a + offset);
const b = str.slice(interval.a + offset, interval.b + offset + 1);
const c = str.slice(interval.b + offset + 1, str.length);
result = a + interval.sub + c;
offset += result.length - str.length;
Expand Down
1 change: 0 additions & 1 deletion packages/query/src/tag.ts
Expand Up @@ -2,7 +2,6 @@ import { processTSQueryAST } from './preprocessor-ts';
import { processSQLQueryAST } from './preprocessor-sql';
import { Query as QueryAST } from './loader/sql';
import { parseTSQuery, TSQueryAST } from './loader/typescript';
import { parseTypeScriptFile } from './index';

export interface IDatabaseConnection {
query: (query: string, bindings: any[]) => Promise<{ rows: any[] }>;
Expand Down
2 changes: 0 additions & 2 deletions packages/wire/src/helpers.ts
@@ -1,5 +1,3 @@
import { SSL_OP_TLS_D5_BUG } from 'constants';

interface ISized {
length: number;
}
Expand Down
10 changes: 0 additions & 10 deletions packages/wire/src/messages.ts
Expand Up @@ -407,13 +407,3 @@ export const messages = {
},
} as IServerMessage<{ commandTag: string }>,
};

export type TMessage =
| IServerMessage<{ commandTag: string }>
| IServerMessage<{
/** Row columns array */
columns: Array<{
/** The value of the column, in the format indicated by the associated format code. n is the above length. */
value: Buffer;
}>;
}>;
10 changes: 2 additions & 8 deletions packages/wire/src/protocol.test.ts
@@ -1,12 +1,6 @@
import {
buildMessage,
IMessagePayload,
parseMessage,
parseOneOf,
ParseResult,
} from '../src/protocol';
import { buildMessage, parseMessage, parseOneOf } from '../src/protocol';

import { messages, IServerMessage } from '../src/messages';
import { messages } from '../src/messages';

test('buildMessage for StartupMessage works', () => {
const base = buildMessage(messages.startupMessage, {
Expand Down
3 changes: 1 addition & 2 deletions packages/wire/src/queue.ts
@@ -1,5 +1,4 @@
import * as net from 'net';
import * as util from 'util';
import * as tls from 'tls';

import {
Expand All @@ -9,7 +8,7 @@ import {
ParseResult,
} from './protocol';

import { IClientMessage, TMessage, IServerMessage, messages } from './messages';
import { IClientMessage, IServerMessage, messages } from './messages';

import debugBase from 'debug';
const debug = debugBase('pg-wire:socket');
Expand Down
4 changes: 3 additions & 1 deletion tslint.json
Expand Up @@ -13,7 +13,8 @@
"arrow-parens": false,
"array-type": false,
"max-line-length": false,
"max-classes-per-file": false
"max-classes-per-file": false,
"no-unused-variable": true
},
"rulesDirectory": [],
"linterOptions": {
Expand All @@ -25,6 +26,7 @@
"**/*ParserVisitor.ts",
"**/*queries.ts",
"packages/example/**/*.ts",
"packages/query/src/loader/*/{index,query}.ts",
"packages/query/src/loader/*/parser/**/*.ts"
]
}
Expand Down

1 comment on commit 382bdb8

@vercel
Copy link

@vercel vercel bot commented on 382bdb8 Sep 16, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.