athena.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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 AthenaEngineSpec(BaseEngineSpec):
  21. engine = "awsathena"
  22. _time_grain_functions = {
  23. None: "{col}",
  24. "PT1S": "date_trunc('second', CAST({col} AS TIMESTAMP))",
  25. "PT1M": "date_trunc('minute', CAST({col} AS TIMESTAMP))",
  26. "PT1H": "date_trunc('hour', CAST({col} AS TIMESTAMP))",
  27. "P1D": "date_trunc('day', CAST({col} AS TIMESTAMP))",
  28. "P1W": "date_trunc('week', CAST({col} AS TIMESTAMP))",
  29. "P1M": "date_trunc('month', CAST({col} AS TIMESTAMP))",
  30. "P0.25Y": "date_trunc('quarter', CAST({col} AS TIMESTAMP))",
  31. "P1Y": "date_trunc('year', CAST({col} AS TIMESTAMP))",
  32. "P1W/1970-01-03T00:00:00Z": "date_add('day', 5, date_trunc('week', \
  33. date_add('day', 1, CAST({col} AS TIMESTAMP))))",
  34. "1969-12-28T00:00:00Z/P1W": "date_add('day', -1, date_trunc('week', \
  35. date_add('day', 1, CAST({col} AS TIMESTAMP))))",
  36. }
  37. @classmethod
  38. def convert_dttm(cls, target_type: str, dttm: datetime) -> Optional[str]:
  39. tt = target_type.upper()
  40. if tt == "DATE":
  41. return f"from_iso8601_date('{dttm.date().isoformat()}')"
  42. if tt == "TIMESTAMP":
  43. return f"""from_iso8601_timestamp('{dttm.isoformat(timespec="microseconds")}')""" # pylint: disable=line-too-long
  44. return None
  45. @classmethod
  46. def epoch_to_dttm(cls) -> str:
  47. return "from_unixtime({col})"
  48. @staticmethod
  49. def _mutate_label(label: str) -> str:
  50. """
  51. Athena only supports lowercase column names and aliases.
  52. :param label: Expected expression label
  53. :return: Conditionally mutated label
  54. """
  55. return label.lower()