query_builder.ts 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. export class PostgresQueryBuilder {
  2. constructor(private target, private queryModel) {}
  3. buildSchemaQuery() {
  4. var 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. var 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. var 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')";
  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. var query = 'SELECT DISTINCT quote_literal(' + column + ')';
  40. query += ' FROM ' + this.target.schema + '.' + this.target.table;
  41. query += ' ORDER BY 1 LIMIT 100';
  42. return query;
  43. }
  44. buildDatatypeQuery(column: string) {
  45. var query = 'SELECT data_type FROM information_schema.columns WHERE ';
  46. query += ' table_schema = ' + this.quoteIdentAsLiteral(this.target.schema);
  47. query += ' AND table_name = ' + this.quoteIdentAsLiteral(this.target.table);
  48. query += ' AND column_name = ' + this.quoteIdentAsLiteral(column);
  49. return query;
  50. }
  51. buildAggregateQuery() {
  52. var query = 'SELECT DISTINCT proname FROM pg_aggregate ';
  53. query += 'INNER JOIN pg_proc ON pg_aggregate.aggfnoid = pg_proc.oid ';
  54. query += 'INNER JOIN pg_type ON pg_type.oid=pg_proc.prorettype ';
  55. query += "WHERE pronargs=1 AND typname IN ('int8','float8') AND aggkind='n' ORDER BY 1";
  56. return query;
  57. }
  58. }