clickhouse.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. # Licensed to the Apache Software Foundation (ASF) under one
  2. # or more contributor license agreements. See the NOTICE file
  3. # distributed with this work for additional information
  4. # regarding copyright ownership. The ASF licenses this file
  5. # to you under the Apache License, Version 2.0 (the
  6. # "License"); you may not use this file except in compliance
  7. # with the License. You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing,
  12. # software distributed under the License is distributed on an
  13. # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  14. # KIND, either express or implied. See the License for the
  15. # specific language governing permissions and limitations
  16. # under the License.
  17. from datetime import datetime
  18. from typing import Optional
  19. from superset.db_engine_specs.base import BaseEngineSpec
  20. class ClickHouseEngineSpec(BaseEngineSpec): # pylint: disable=abstract-method
  21. """Dialect for ClickHouse analytical DB."""
  22. engine = "clickhouse"
  23. time_secondary_columns = True
  24. time_groupby_inline = True
  25. _time_grain_functions = {
  26. None: "{col}",
  27. "PT1M": "toStartOfMinute(toDateTime({col}))",
  28. "PT5M": "toDateTime(intDiv(toUInt32(toDateTime({col})), 300)*300)",
  29. "PT10M": "toDateTime(intDiv(toUInt32(toDateTime({col})), 600)*600)",
  30. "PT15M": "toDateTime(intDiv(toUInt32(toDateTime({col})), 900)*900)",
  31. "PT0.5H": "toDateTime(intDiv(toUInt32(toDateTime({col})), 1800)*1800)",
  32. "PT1H": "toStartOfHour(toDateTime({col}))",
  33. "P1D": "toStartOfDay(toDateTime({col}))",
  34. "P1W": "toMonday(toDateTime({col}))",
  35. "P1M": "toStartOfMonth(toDateTime({col}))",
  36. "P0.25Y": "toStartOfQuarter(toDateTime({col}))",
  37. "P1Y": "toStartOfYear(toDateTime({col}))",
  38. }
  39. @classmethod
  40. def convert_dttm(cls, target_type: str, dttm: datetime) -> Optional[str]:
  41. tt = target_type.upper()
  42. if tt == "DATE":
  43. return f"toDate('{dttm.date().isoformat()}')"
  44. if tt == "DATETIME":
  45. return f"""toDateTime('{dttm.isoformat(sep=" ", timespec="seconds")}')"""
  46. return None