query_builder.ts 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. export class PostgresQueryBuilder {
  2. constructor(private target, private queryModel) {}
  3. buildSchemaQuery() {
  4. let query = 'SELECT quote_ident(schema_name) FROM information_schema.schemata WHERE';
  5. query += " schema_name NOT LIKE 'pg_%' AND schema_name NOT LIKE '\\_%' AND schema_name <> 'information_schema';";
  6. return query;
  7. }
  8. buildTableQuery() {
  9. let query = 'SELECT quote_ident(table_name) FROM information_schema.tables WHERE ';
  10. query += 'table_schema = ' + this.quoteIdentAsLiteral(this.target.schema);
  11. return query;
  12. }
  13. // quote identifier as literal to use in metadata queries
  14. quoteIdentAsLiteral(value) {
  15. return this.queryModel.quoteLiteral(this.queryModel.unquoteIdentifier(value));
  16. }
  17. buildColumnQuery(type?: string) {
  18. let query = 'SELECT quote_ident(column_name) FROM information_schema.columns WHERE ';
  19. query += 'table_schema = ' + this.quoteIdentAsLiteral(this.target.schema);
  20. query += ' AND table_name = ' + this.quoteIdentAsLiteral(this.target.table);
  21. switch (type) {
  22. case 'time': {
  23. query +=
  24. " AND data_type IN ('timestamp without time zone','timestamp with time zone','bigint','integer','double precision','real')";
  25. break;
  26. }
  27. case 'metric': {
  28. query += " AND data_type IN ('text','char','varchar','integer','bigint')";
  29. break;
  30. }
  31. case 'value': {
  32. query += " AND data_type IN ('bigint','integer','double precision','real')";
  33. break;
  34. }
  35. }
  36. return query;
  37. }
  38. buildValueQuery(column: string) {
  39. let query = 'SELECT DISTINCT quote_literal(' + column + ')';
  40. query += ' FROM ' + this.target.schema + '.' + this.target.table;
  41. query += ' WHERE $__timeFilter(' + this.target.timeColumn + ')';
  42. query += ' ORDER BY 1 LIMIT 100';
  43. return query;
  44. }
  45. buildDatatypeQuery(column: string) {
  46. let query = 'SELECT data_type FROM information_schema.columns WHERE ';
  47. query += ' table_schema = ' + this.quoteIdentAsLiteral(this.target.schema);
  48. query += ' AND table_name = ' + this.quoteIdentAsLiteral(this.target.table);
  49. query += ' AND column_name = ' + this.quoteIdentAsLiteral(column);
  50. return query;
  51. }
  52. buildAggregateQuery() {
  53. let query = 'SELECT DISTINCT proname FROM pg_aggregate ';
  54. query += 'INNER JOIN pg_proc ON pg_aggregate.aggfnoid = pg_proc.oid ';
  55. query += 'INNER JOIN pg_type ON pg_type.oid=pg_proc.prorettype ';
  56. query += "WHERE pronargs=1 AND typname IN ('float8') AND aggkind='n' ORDER BY 1";
  57. return query;
  58. }
  59. }