-
Notifications
You must be signed in to change notification settings - Fork 453
/
endpoint.py
80 lines (60 loc) · 2.2 KB
/
endpoint.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# Copyright Materialize, Inc. and contributors. All rights reserved.
#
# Use of this software is governed by the Business Source License
# included in the LICENSE file at the root of this repository.
#
# As of the Change Date specified in that file, in accordance with
# the Business Source License, use of this software will be governed
# by the Apache License, Version 2.0.
from typing import Any
import psycopg
class Endpoint:
_version: str | None = None
def __init__(self, specified_target: str):
self._specified_target = specified_target
def sql_connection(
self, quiet: bool = False
) -> psycopg.connection.Connection[tuple[Any, ...]]:
if not quiet:
print(f"Connecting to URL: {self.url()}")
conn = psycopg.connect(self.url())
conn.autocommit = True
return conn
def url(self) -> str:
return (
f"postgresql://{self.user()}:{self.password()}@{self.host()}:{self.port()}"
)
def specified_target(self) -> str:
return self._specified_target
def resolved_target(self) -> str:
return self.specified_target()
def host(self) -> str:
raise NotImplementedError
def user(self) -> str:
raise NotImplementedError
def password(self) -> str:
raise NotImplementedError
def port(self) -> int:
raise NotImplementedError
def up(self) -> None:
raise NotImplementedError
def sql(self, sql: str) -> None:
conn = self.sql_connection()
cursor = conn.cursor()
cursor.execute(sql.encode("utf8"))
def try_load_version(self) -> str:
"""
Tries to load the version from the database or returns 'unknown' otherwise.
This first invocation requires the endpoint to be up; subsequent invocations will use the cached information.
"""
if self._version is not None:
return self._version
try:
cursor = self.sql_connection().cursor()
cursor.execute(b"SELECT mz_version()")
row = cursor.fetchone()
assert row is not None
self._version = str(row[0])
return self._version
except:
return "unknown"