test_analytics_setup.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. # Copyright Materialize, Inc. and contributors. All rights reserved.
  2. #
  3. # Use of this software is governed by the Business Source License
  4. # included in the LICENSE file at the root of this repository.
  5. #
  6. # As of the Change Date specified in that file, in accordance with
  7. # the Business Source License, use of this software will be governed
  8. # by the Apache License, Version 2.0.
  9. import os
  10. from psycopg import Cursor
  11. from materialize import MZ_ROOT
  12. from materialize.test_analytics.util.mz_sql_util import as_sanitized_literal
  13. def setup_all_structures(cursor: Cursor) -> None:
  14. setup_directory = f"{MZ_ROOT}/misc/python/materialize/test_analytics/setup/"
  15. setup_structures(cursor, f"{setup_directory}/tables")
  16. setup_structures(cursor, f"{setup_directory}/views")
  17. def setup_structures(cursor: Cursor, directory: str) -> None:
  18. if exist_structures(cursor):
  19. return
  20. setup_files = os.listdir(directory)
  21. setup_files.sort()
  22. for file_name in setup_files:
  23. if not file_name.endswith(".sql"):
  24. continue
  25. file_handle = open(f"{directory}/{file_name}")
  26. content = file_handle.read()
  27. sql_commands = content.split(";")
  28. for command in sql_commands:
  29. print(f"> {command}")
  30. cursor.execute(command.encode())
  31. def exist_structures(cursor: Cursor) -> bool:
  32. table_name_to_test = "build"
  33. cursor.execute(
  34. f"SELECT exists(SELECT 1 FROM mz_tables WHERE name = {as_sanitized_literal(table_name_to_test)});".encode()
  35. )
  36. return cursor.fetchall()[0][0]
  37. def drop_structures_and_data(cursor: Cursor) -> None:
  38. cursor.execute("DROP DATABASE test_analytics;")