meta_query.ts 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. export class PostgresMetaQuery {
  2. constructor(private target, private queryModel) {}
  3. // quote identifier as literal to use in metadata queries
  4. quoteIdentAsLiteral(value) {
  5. return this.queryModel.quoteLiteral(this.queryModel.unquoteIdentifier(value));
  6. }
  7. buildSchemaQuery() {
  8. let query = 'SELECT quote_ident(schema_name) FROM information_schema.schemata WHERE';
  9. query += " schema_name NOT LIKE 'pg_%' AND schema_name NOT LIKE '\\_%' AND schema_name <> 'information_schema';";
  10. return query;
  11. }
  12. buildTableQuery() {
  13. let query = 'SELECT quote_ident(table_name) FROM information_schema.tables WHERE ';
  14. query += 'table_schema = ' + this.quoteIdentAsLiteral(this.target.schema);
  15. return query;
  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')";
  29. break;
  30. }
  31. case 'value': {
  32. query += " AND data_type IN ('bigint','integer','double precision','real')";
  33. query += ' AND column_name <> ' + this.quoteIdentAsLiteral(this.target.timeColumn);
  34. break;
  35. }
  36. case 'groupby': {
  37. query += " AND data_type IN ('text','char','varchar')";
  38. break;
  39. }
  40. }
  41. return query;
  42. }
  43. buildValueQuery(column: string) {
  44. let query = 'SELECT DISTINCT quote_literal(' + column + ')';
  45. query += ' FROM ' + this.target.schema + '.' + this.target.table;
  46. query += ' WHERE $__timeFilter(' + this.target.timeColumn + ')';
  47. query += ' ORDER BY 1 LIMIT 100';
  48. return query;
  49. }
  50. buildDatatypeQuery(column: string) {
  51. let query = 'SELECT data_type FROM information_schema.columns WHERE ';
  52. query += ' table_schema = ' + this.quoteIdentAsLiteral(this.target.schema);
  53. query += ' AND table_name = ' + this.quoteIdentAsLiteral(this.target.table);
  54. query += ' AND column_name = ' + this.quoteIdentAsLiteral(column);
  55. return query;
  56. }
  57. buildAggregateQuery() {
  58. let query = 'SELECT DISTINCT proname FROM pg_aggregate ';
  59. query += 'INNER JOIN pg_proc ON pg_aggregate.aggfnoid = pg_proc.oid ';
  60. query += 'INNER JOIN pg_type ON pg_type.oid=pg_proc.prorettype ';
  61. query += "WHERE pronargs=1 AND typname IN ('float8') AND aggkind='n' ORDER BY 1";
  62. return query;
  63. }
  64. }