Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

TypeORM 0.3 #1

Open
webjay opened this issue Jun 26, 2022 · 1 comment
Open

TypeORM 0.3 #1

webjay opened this issue Jun 26, 2022 · 1 comment

Comments

@webjay
Copy link

webjay commented Jun 26, 2022

This works for TypeORM 0.3:

// Modified for TypeORM 0.3 from @zamarawka/typeorm-explain

import { ObjectLiteral, QueryBuilder } from 'typeorm';

export enum ExplainFormat {
  JSON = 'json',
  TEXT = 'text',
  XML = 'xml',
  YAML = 'yaml',
}

type PostgresExplainParameters = {
  analyze?: boolean;
  verbose?: boolean;
  costs?: boolean;
  buffers?: boolean;
  timing?: boolean;
};

type ExplainParameters = PostgresExplainParameters | undefined;

type ExplainBuilder = (
  query: string,
  explainParameters: ExplainParameters,
  format: ExplainFormat
) => string;

const explainers: { [key: string]: ExplainBuilder } = {
  postgres(
    query: string,
    explainParameters: PostgresExplainParameters = {
      analyze: true,
      verbose: true,
      buffers: true,
    },
    format: ExplainFormat
  ) {
    const boolParameters = Object.entries(explainParameters)
      .filter((argument): argument is [string, boolean] => typeof argument[1] === 'boolean')
      .map(([key, value]) => `${key} ${value}`);

    const explainParametersString = [...boolParameters, `FORMAT ${format}`]
      .join(', ')
      .toUpperCase();

    return `EXPLAIN (${explainParametersString}) ${query}`;
  },
};

const explain = <T extends ObjectLiteral>(
  qb: QueryBuilder<T>,
  format = ExplainFormat.TEXT,
  explainParameters?: ExplainParameters
): Promise<unknown> => {
  const { connection } = qb.clone();
  const explainBuilder = explainers[connection.driver.options.type] as ExplainBuilder | undefined;
  if (explainBuilder === undefined) throw new Error('Unsupported connection driver');
  const [query, queryParameters] = qb.getQueryAndParameters();
  const queryExplain = explainBuilder(query, explainParameters, format);

  return connection.query(queryExplain, queryParameters);
};

// eslint-disable-next-line import/no-default-export
export default explain;
@david-vendel
Copy link

Thanks, this works, I'll add the usage for others:

import explain from 'src/lib/explain';
...
const queryExplained = await explain(query);
console.log('queryExplained', queryExplained);

Where the content of 'src/lib/explain'; is the code you quoted above and query is a standard TypeORM query created with queryBuilder.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants