query_builder.ts 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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.quoteLiteral(this.target.schema);
  11. return query;
  12. }
  13. quoteLiteral(value) {
  14. return this.queryModel.quoteLiteral(this.queryModel.unquoteIdentifier(value));
  15. }
  16. buildColumnQuery(type?: string) {
  17. var query = 'SELECT quote_ident(column_name) FROM information_schema.columns WHERE ';
  18. query += 'table_schema = ' + this.quoteLiteral(this.target.schema);
  19. query += ' AND table_name = ' + this.quoteLiteral(this.target.table);
  20. switch (type) {
  21. case 'time': {
  22. query +=
  23. " AND data_type IN ('timestamp without time zone','timestamp with time zone','bigint','integer','double precision','real')";
  24. break;
  25. }
  26. case 'metric': {
  27. query += " AND data_type IN ('text','char','varchar')";
  28. break;
  29. }
  30. case 'value': {
  31. query += " AND data_type IN ('bigint','integer','double precision','real')";
  32. break;
  33. }
  34. }
  35. return query;
  36. }
  37. buildValueQuery(column: string) {
  38. var query = 'SELECT DISTINCT quote_literal(' + column + ')';
  39. query += ' FROM ' + this.target.schema + '.' + this.target.table;
  40. query += ' ORDER BY 1 LIMIT 100';
  41. return query;
  42. }
  43. buildDatatypeQuery(column: string) {
  44. var query = 'SELECT data_type FROM information_schema.columns WHERE ';
  45. query += ' table_schema = ' + this.quoteLiteral(this.target.schema);
  46. query += ' AND table_name = ' + this.quoteLiteral(this.target.table);
  47. query += ' AND column_name = ' + this.quoteLiteral(column);
  48. return query;
  49. }
  50. buildAggregateQuery() {
  51. var query = 'SELECT DISTINCT proname FROM pg_aggregate ';
  52. query += 'INNER JOIN pg_proc ON pg_aggregate.aggfnoid = pg_proc.oid ';
  53. query += 'INNER JOIN pg_type ON pg_type.oid=pg_proc.prorettype ';
  54. query += "WHERE pronargs=1 AND typname IN ('int8','float8') AND aggkind='n' ORDER BY 1";
  55. return query;
  56. }
  57. }