corebase 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- corebase/__init__.py +108 -0
- corebase/_async/__init__.py +1 -0
- corebase/_async/auth_client.py +55 -0
- corebase/_async/client.py +398 -0
- corebase/_sync/__init__.py +1 -0
- corebase/_sync/auth_client.py +55 -0
- corebase/_sync/client.py +393 -0
- corebase/auth/__init__.py +20 -0
- corebase/auth/_async/__init__.py +1 -0
- corebase/auth/_async/gotrue_admin_api.py +356 -0
- corebase/auth/_async/gotrue_admin_mfa_api.py +32 -0
- corebase/auth/_async/gotrue_admin_oauth_api.py +93 -0
- corebase/auth/_async/gotrue_base_api.py +78 -0
- corebase/auth/_async/gotrue_client.py +1404 -0
- corebase/auth/_async/gotrue_mfa_api.py +94 -0
- corebase/auth/_async/storage.py +31 -0
- corebase/auth/_sync/__init__.py +1 -0
- corebase/auth/_sync/gotrue_admin_api.py +356 -0
- corebase/auth/_sync/gotrue_admin_mfa_api.py +32 -0
- corebase/auth/_sync/gotrue_admin_oauth_api.py +93 -0
- corebase/auth/_sync/gotrue_base_api.py +78 -0
- corebase/auth/_sync/gotrue_client.py +1394 -0
- corebase/auth/_sync/gotrue_mfa_api.py +94 -0
- corebase/auth/_sync/storage.py +31 -0
- corebase/auth/constants.py +15 -0
- corebase/auth/errors.py +259 -0
- corebase/auth/helpers.py +288 -0
- corebase/auth/py.typed +0 -0
- corebase/auth/timer.py +53 -0
- corebase/auth/types.py +1021 -0
- corebase/auth/version.py +1 -0
- corebase/client.py +12 -0
- corebase/functions/__init__.py +47 -0
- corebase/functions/_async/__init__.py +1 -0
- corebase/functions/_async/functions_client.py +218 -0
- corebase/functions/_sync/__init__.py +1 -0
- corebase/functions/_sync/functions_client.py +218 -0
- corebase/functions/errors.py +62 -0
- corebase/functions/py.typed +0 -0
- corebase/functions/utils.py +33 -0
- corebase/functions/version.py +1 -0
- corebase/lib/__init__.py +3 -0
- corebase/lib/client_options.py +189 -0
- corebase/migrate/__init__.py +374 -0
- corebase/migrate/__main__.py +7 -0
- corebase/postgrest/__init__.py +62 -0
- corebase/postgrest/_async/__init__.py +1 -0
- corebase/postgrest/_async/client.py +206 -0
- corebase/postgrest/_async/request_builder.py +503 -0
- corebase/postgrest/_sync/__init__.py +1 -0
- corebase/postgrest/_sync/client.py +206 -0
- corebase/postgrest/_sync/request_builder.py +503 -0
- corebase/postgrest/base_client.py +61 -0
- corebase/postgrest/base_request_builder.py +787 -0
- corebase/postgrest/constants.py +6 -0
- corebase/postgrest/exceptions.py +115 -0
- corebase/postgrest/py.typed +0 -0
- corebase/postgrest/types.py +72 -0
- corebase/postgrest/utils.py +91 -0
- corebase/postgrest/version.py +1 -0
- corebase/py.typed +0 -0
- corebase/realtime/__init__.py +17 -0
- corebase/realtime/_async/__init__.py +0 -0
- corebase/realtime/_async/channel.py +766 -0
- corebase/realtime/_async/client.py +498 -0
- corebase/realtime/_async/presence.py +185 -0
- corebase/realtime/_async/push.py +162 -0
- corebase/realtime/_async/timer.py +41 -0
- corebase/realtime/_sync/__init__.py +0 -0
- corebase/realtime/_sync/channel.py +30 -0
- corebase/realtime/_sync/client.py +71 -0
- corebase/realtime/_sync/presence.py +10 -0
- corebase/realtime/exceptions.py +38 -0
- corebase/realtime/message.py +176 -0
- corebase/realtime/py.typed +0 -0
- corebase/realtime/transformers.py +9 -0
- corebase/realtime/types.py +246 -0
- corebase/realtime/utils.py +5 -0
- corebase/realtime/version.py +1 -0
- corebase/storage/__init__.py +56 -0
- corebase/storage/_async/__init__.py +1 -0
- corebase/storage/_async/analytics.py +82 -0
- corebase/storage/_async/bucket.py +142 -0
- corebase/storage/_async/client.py +106 -0
- corebase/storage/_async/file_api.py +630 -0
- corebase/storage/_async/request.py +32 -0
- corebase/storage/_async/vectors.py +213 -0
- corebase/storage/_sync/__init__.py +1 -0
- corebase/storage/_sync/analytics.py +80 -0
- corebase/storage/_sync/bucket.py +142 -0
- corebase/storage/_sync/client.py +106 -0
- corebase/storage/_sync/file_api.py +630 -0
- corebase/storage/_sync/request.py +32 -0
- corebase/storage/_sync/vectors.py +199 -0
- corebase/storage/constants.py +16 -0
- corebase/storage/exceptions.py +84 -0
- corebase/storage/py.typed +0 -0
- corebase/storage/types.py +313 -0
- corebase/storage/utils.py +26 -0
- corebase/storage/version.py +1 -0
- corebase/types.py +8 -0
- corebase/version.py +1 -0
- corebase-1.0.0.dist-info/METADATA +78 -0
- corebase-1.0.0.dist-info/RECORD +106 -0
- corebase-1.0.0.dist-info/WHEEL +4 -0
- corebase-1.0.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
import platform
|
|
2
|
+
from dataclasses import dataclass, field
|
|
3
|
+
|
|
4
|
+
from httpx import AsyncClient as AsyncHttpxClient
|
|
5
|
+
from httpx import Client as SyncHttpxClient
|
|
6
|
+
from httpx import Timeout
|
|
7
|
+
from corebase.postgrest.constants import DEFAULT_POSTGREST_CLIENT_TIMEOUT
|
|
8
|
+
from corebase.storage.constants import DEFAULT_TIMEOUT as DEFAULT_STORAGE_CLIENT_TIMEOUT
|
|
9
|
+
from corebase.auth import (
|
|
10
|
+
AsyncMemoryStorage,
|
|
11
|
+
AsyncSupportedStorage,
|
|
12
|
+
AuthFlowType,
|
|
13
|
+
SyncMemoryStorage,
|
|
14
|
+
SyncSupportedStorage,
|
|
15
|
+
)
|
|
16
|
+
from corebase.functions.utils import DEFAULT_FUNCTION_CLIENT_TIMEOUT
|
|
17
|
+
|
|
18
|
+
from corebase.types import RealtimeClientOptions
|
|
19
|
+
|
|
20
|
+
from ..version import __version__
|
|
21
|
+
|
|
22
|
+
DEFAULT_HEADERS = {
|
|
23
|
+
"X-Client-Info": (
|
|
24
|
+
f"corebase-py/{__version__}"
|
|
25
|
+
f"; platform={platform.system()}"
|
|
26
|
+
f"; platform-version={platform.release()}"
|
|
27
|
+
f"; runtime=python"
|
|
28
|
+
f"; runtime-version={platform.python_version()}"
|
|
29
|
+
)
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@dataclass
|
|
34
|
+
class ClientOptions:
|
|
35
|
+
schema: str = "public"
|
|
36
|
+
"""
|
|
37
|
+
The Postgres schema which your tables belong to.
|
|
38
|
+
Must be on the list of exposed schemas in Supabase. Defaults to 'public'.
|
|
39
|
+
"""
|
|
40
|
+
|
|
41
|
+
headers: dict[str, str] = field(default_factory=DEFAULT_HEADERS.copy)
|
|
42
|
+
"""Optional headers for initializing the client."""
|
|
43
|
+
|
|
44
|
+
auto_refresh_token: bool = True
|
|
45
|
+
"""Automatically refreshes the token for logged in users."""
|
|
46
|
+
|
|
47
|
+
persist_session: bool = True
|
|
48
|
+
"""Whether to persist a logged in session to storage."""
|
|
49
|
+
|
|
50
|
+
realtime: RealtimeClientOptions | None = None
|
|
51
|
+
"""Options passed to the realtime-py instance"""
|
|
52
|
+
|
|
53
|
+
postgrest_client_timeout: int | float | Timeout = DEFAULT_POSTGREST_CLIENT_TIMEOUT
|
|
54
|
+
"""Timeout passed to the SyncPostgrestClient instance."""
|
|
55
|
+
|
|
56
|
+
postgrest_client_retry: bool = True
|
|
57
|
+
"""Automatically retry transient PostgREST errors. Passed to the SyncPostgrestClient instance."""
|
|
58
|
+
|
|
59
|
+
storage_client_timeout: int = DEFAULT_STORAGE_CLIENT_TIMEOUT
|
|
60
|
+
"""Timeout passed to the SyncStorageClient instance"""
|
|
61
|
+
|
|
62
|
+
function_client_timeout: int = DEFAULT_FUNCTION_CLIENT_TIMEOUT
|
|
63
|
+
"""Timeout passed to the SyncFunctionsClient instance."""
|
|
64
|
+
|
|
65
|
+
flow_type: AuthFlowType = "pkce"
|
|
66
|
+
"""flow type to use for authentication"""
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
@dataclass
|
|
70
|
+
class AsyncClientOptions(ClientOptions):
|
|
71
|
+
storage: AsyncSupportedStorage = field(default_factory=AsyncMemoryStorage)
|
|
72
|
+
"""A storage provider. Used to store the logged in session."""
|
|
73
|
+
|
|
74
|
+
httpx_client: AsyncHttpxClient | None = None
|
|
75
|
+
"""httpx client instance to be used by the PostgREST, functions, auth and storage clients."""
|
|
76
|
+
|
|
77
|
+
def replace(
|
|
78
|
+
self,
|
|
79
|
+
schema: str | None = None,
|
|
80
|
+
headers: dict[str, str] | None = None,
|
|
81
|
+
auto_refresh_token: bool | None = None,
|
|
82
|
+
persist_session: bool | None = None,
|
|
83
|
+
storage: AsyncSupportedStorage | None = None,
|
|
84
|
+
realtime: RealtimeClientOptions | None = None,
|
|
85
|
+
httpx_client: AsyncHttpxClient | None = None,
|
|
86
|
+
postgrest_client_timeout: int | float | Timeout | None = None,
|
|
87
|
+
postgrest_client_retry: bool | None = None,
|
|
88
|
+
storage_client_timeout: int | None = None,
|
|
89
|
+
flow_type: AuthFlowType | None = None,
|
|
90
|
+
function_client_timeout: int | None = None,
|
|
91
|
+
) -> "AsyncClientOptions":
|
|
92
|
+
"""Create a new SupabaseClientOptions with changes"""
|
|
93
|
+
client_options = AsyncClientOptions()
|
|
94
|
+
client_options.schema = schema or self.schema
|
|
95
|
+
client_options.headers = headers or self.headers
|
|
96
|
+
client_options.auto_refresh_token = (
|
|
97
|
+
auto_refresh_token
|
|
98
|
+
if auto_refresh_token is not None
|
|
99
|
+
else self.auto_refresh_token
|
|
100
|
+
)
|
|
101
|
+
client_options.persist_session = (
|
|
102
|
+
persist_session if persist_session is not None else self.persist_session
|
|
103
|
+
)
|
|
104
|
+
client_options.storage = storage or self.storage
|
|
105
|
+
client_options.realtime = realtime or self.realtime
|
|
106
|
+
client_options.httpx_client = httpx_client or self.httpx_client
|
|
107
|
+
client_options.postgrest_client_timeout = (
|
|
108
|
+
postgrest_client_timeout
|
|
109
|
+
if postgrest_client_timeout is not None
|
|
110
|
+
else self.postgrest_client_timeout
|
|
111
|
+
)
|
|
112
|
+
client_options.postgrest_client_retry = (
|
|
113
|
+
postgrest_client_retry
|
|
114
|
+
if postgrest_client_retry is not None
|
|
115
|
+
else self.postgrest_client_retry
|
|
116
|
+
)
|
|
117
|
+
client_options.storage_client_timeout = (
|
|
118
|
+
storage_client_timeout
|
|
119
|
+
if storage_client_timeout is not None
|
|
120
|
+
else self.storage_client_timeout
|
|
121
|
+
)
|
|
122
|
+
client_options.flow_type = flow_type or self.flow_type
|
|
123
|
+
client_options.function_client_timeout = (
|
|
124
|
+
function_client_timeout
|
|
125
|
+
if function_client_timeout is not None
|
|
126
|
+
else self.function_client_timeout
|
|
127
|
+
)
|
|
128
|
+
return client_options
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
@dataclass
|
|
132
|
+
class SyncClientOptions(ClientOptions):
|
|
133
|
+
storage: SyncSupportedStorage = field(default_factory=SyncMemoryStorage)
|
|
134
|
+
"""A storage provider. Used to store the logged in session."""
|
|
135
|
+
httpx_client: SyncHttpxClient | None = None
|
|
136
|
+
"""httpx client instance to be used by the PostgREST, functions, auth and storage clients."""
|
|
137
|
+
|
|
138
|
+
def replace(
|
|
139
|
+
self,
|
|
140
|
+
schema: str | None = None,
|
|
141
|
+
headers: dict[str, str] | None = None,
|
|
142
|
+
auto_refresh_token: bool | None = None,
|
|
143
|
+
persist_session: bool | None = None,
|
|
144
|
+
storage: SyncSupportedStorage | None = None,
|
|
145
|
+
realtime: RealtimeClientOptions | None = None,
|
|
146
|
+
httpx_client: SyncHttpxClient | None = None,
|
|
147
|
+
postgrest_client_timeout: int | float | Timeout | None = None,
|
|
148
|
+
postgrest_client_retry: bool | None = None,
|
|
149
|
+
storage_client_timeout: int | None = None,
|
|
150
|
+
flow_type: AuthFlowType | None = None,
|
|
151
|
+
function_client_timeout: int | None = None,
|
|
152
|
+
) -> "SyncClientOptions":
|
|
153
|
+
"""Create a new SupabaseClientOptions with changes"""
|
|
154
|
+
client_options = SyncClientOptions()
|
|
155
|
+
client_options.schema = schema or self.schema
|
|
156
|
+
client_options.headers = headers or self.headers
|
|
157
|
+
client_options.auto_refresh_token = (
|
|
158
|
+
auto_refresh_token
|
|
159
|
+
if auto_refresh_token is not None
|
|
160
|
+
else self.auto_refresh_token
|
|
161
|
+
)
|
|
162
|
+
client_options.persist_session = (
|
|
163
|
+
persist_session if persist_session is not None else self.persist_session
|
|
164
|
+
)
|
|
165
|
+
client_options.storage = storage or self.storage
|
|
166
|
+
client_options.realtime = realtime or self.realtime
|
|
167
|
+
client_options.httpx_client = httpx_client or self.httpx_client
|
|
168
|
+
client_options.postgrest_client_timeout = (
|
|
169
|
+
postgrest_client_timeout
|
|
170
|
+
if postgrest_client_timeout is not None
|
|
171
|
+
else self.postgrest_client_timeout
|
|
172
|
+
)
|
|
173
|
+
client_options.postgrest_client_retry = (
|
|
174
|
+
postgrest_client_retry
|
|
175
|
+
if postgrest_client_retry is not None
|
|
176
|
+
else self.postgrest_client_retry
|
|
177
|
+
)
|
|
178
|
+
client_options.storage_client_timeout = (
|
|
179
|
+
storage_client_timeout
|
|
180
|
+
if storage_client_timeout is not None
|
|
181
|
+
else self.storage_client_timeout
|
|
182
|
+
)
|
|
183
|
+
client_options.flow_type = flow_type or self.flow_type
|
|
184
|
+
client_options.function_client_timeout = (
|
|
185
|
+
function_client_timeout
|
|
186
|
+
if function_client_timeout is not None
|
|
187
|
+
else self.function_client_timeout
|
|
188
|
+
)
|
|
189
|
+
return client_options
|
|
@@ -0,0 +1,374 @@
|
|
|
1
|
+
"""Moving an existing Postgres database, a Supabase project's above all, into a
|
|
2
|
+
Corebase project. Corebase's own addition to the `corebase` package (not
|
|
3
|
+
from upstream; added by scripts/corebase_additions.py).
|
|
4
|
+
|
|
5
|
+
The project's server does the work. It connects to the source itself,
|
|
6
|
+
copies the schema, the rows and the users inside one transaction (a
|
|
7
|
+
migration that fails leaves the project as it was), and reports how far it
|
|
8
|
+
has come. These functions start it and follow it. They need the project's
|
|
9
|
+
address and a migration token, made on the project's dashboard (Database →
|
|
10
|
+
Migrate data → SDK); the project's API keys cannot start a migration.
|
|
11
|
+
|
|
12
|
+
from corebase import migrate_from_postgres
|
|
13
|
+
|
|
14
|
+
job = migrate_from_postgres(
|
|
15
|
+
url="https://<project>.corebase.so",
|
|
16
|
+
token=os.environ["COREBASE_MIGRATION_TOKEN"],
|
|
17
|
+
source=os.environ["SOURCE_DATABASE_URL"],
|
|
18
|
+
on_progress=lambda job, percent: print(percent, job["phase"]),
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
A migration does not depend on the program that started it. When that
|
|
22
|
+
program ends, or loses its connection, the migration goes on in the project;
|
|
23
|
+
follow_migration takes it up again from anywhere.
|
|
24
|
+
|
|
25
|
+
From a shell, with a progress bar (the command is __main__.py beside this
|
|
26
|
+
file: a module of its own, so that running it does not load this one twice):
|
|
27
|
+
|
|
28
|
+
python -m corebase.migrate --from "postgres://..." --url ... --token ...
|
|
29
|
+
python -m corebase.migrate --follow --url ... --token ...
|
|
30
|
+
"""
|
|
31
|
+
|
|
32
|
+
from __future__ import annotations
|
|
33
|
+
|
|
34
|
+
import argparse
|
|
35
|
+
import os
|
|
36
|
+
import shutil
|
|
37
|
+
import sys
|
|
38
|
+
import time
|
|
39
|
+
from typing import Any, Callable, Optional
|
|
40
|
+
|
|
41
|
+
import httpx
|
|
42
|
+
|
|
43
|
+
__all__ = (
|
|
44
|
+
"MigrationError",
|
|
45
|
+
"check_migration",
|
|
46
|
+
"start_migration",
|
|
47
|
+
"get_migration",
|
|
48
|
+
"cancel_migration",
|
|
49
|
+
"migration_percent",
|
|
50
|
+
"migrate_from_postgres",
|
|
51
|
+
"follow_migration",
|
|
52
|
+
)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class MigrationError(Exception):
|
|
56
|
+
"""Why a migration did not happen or did not finish. `code` names it;
|
|
57
|
+
`job` is the job when one was started, `report` the check's report when
|
|
58
|
+
the check stopped it."""
|
|
59
|
+
|
|
60
|
+
def __init__(self, failure: dict, job: Optional[dict] = None, report: Optional[dict] = None):
|
|
61
|
+
super().__init__(failure.get("message", "the migration failed"))
|
|
62
|
+
self.code: str = failure.get("code", "failed")
|
|
63
|
+
self.hint: Optional[str] = failure.get("hint")
|
|
64
|
+
self.detail: Optional[str] = failure.get("detail")
|
|
65
|
+
self.object: Optional[str] = failure.get("object")
|
|
66
|
+
self.statement: Optional[str] = failure.get("statement")
|
|
67
|
+
self.blockers: list = failure.get("blockers") or []
|
|
68
|
+
self.job = job
|
|
69
|
+
self.report = report
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _options(auth: Optional[bool], sample_rows: Optional[int], schemas: Optional[list]) -> dict:
|
|
73
|
+
out: dict[str, Any] = {}
|
|
74
|
+
if auth is not None:
|
|
75
|
+
out["auth"] = auth
|
|
76
|
+
if sample_rows:
|
|
77
|
+
out["sample_rows"] = int(sample_rows)
|
|
78
|
+
if schemas:
|
|
79
|
+
out["schemas"] = list(schemas)
|
|
80
|
+
return out
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _call(url: str, token: str, method: str, path: str, body: Optional[dict] = None, timeout: float = 120) -> dict:
|
|
84
|
+
res = httpx.request(
|
|
85
|
+
method,
|
|
86
|
+
url.rstrip("/") + "/migrate/v1/" + path,
|
|
87
|
+
headers={"Authorization": "Bearer " + token},
|
|
88
|
+
json=body,
|
|
89
|
+
timeout=timeout,
|
|
90
|
+
)
|
|
91
|
+
try:
|
|
92
|
+
payload = res.json()
|
|
93
|
+
except ValueError:
|
|
94
|
+
payload = None
|
|
95
|
+
if res.status_code == 401:
|
|
96
|
+
raise MigrationError({
|
|
97
|
+
"code": "unauthorized",
|
|
98
|
+
"message": "the migration token was refused: make a new one on the project dashboard (Database → Migrate data → SDK)",
|
|
99
|
+
})
|
|
100
|
+
if res.status_code >= 400:
|
|
101
|
+
if isinstance(payload, dict) and isinstance(payload.get("message"), str):
|
|
102
|
+
raise MigrationError(payload)
|
|
103
|
+
raise MigrationError({"code": "failed", "message": f"the project answered {res.status_code}"})
|
|
104
|
+
return payload
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def check_migration(url: str, token: str, source: str, *, auth: Optional[bool] = None,
|
|
108
|
+
sample_rows: Optional[int] = None, schemas: Optional[list] = None) -> dict:
|
|
109
|
+
"""Works out what a migration from the source would do, and changes nothing."""
|
|
110
|
+
return _call(url, token, "POST", "check", {"source": source, "options": _options(auth, sample_rows, schemas)})
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def start_migration(url: str, token: str, source: str, *, auth: Optional[bool] = None,
|
|
114
|
+
sample_rows: Optional[int] = None, schemas: Optional[list] = None) -> dict:
|
|
115
|
+
"""Starts a migration and returns at once; follow it with get_migration."""
|
|
116
|
+
return _call(url, token, "POST", "jobs", {"source": source, "options": _options(auth, sample_rows, schemas)})
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def get_migration(url: str, token: str, job_id: str = "latest") -> dict:
|
|
120
|
+
"""Reads a job; "latest" is the project's last one."""
|
|
121
|
+
return _call(url, token, "GET", "jobs/" + job_id)
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def cancel_migration(url: str, token: str, job_id: str) -> dict:
|
|
125
|
+
"""Stops a running job. Its transaction is rolled back: the project stays as it was."""
|
|
126
|
+
return _call(url, token, "POST", "jobs/" + job_id + "/cancel")
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
# The phases of a job, in order, and how much of the whole each one is.
|
|
130
|
+
_PHASES = [
|
|
131
|
+
("connecting", 2), ("planning", 5), ("creating_schema", 8), ("choosing_rows", 5),
|
|
132
|
+
("copying_data", 65), ("creating_indexes", 10), ("finishing", 3), ("committing", 2),
|
|
133
|
+
]
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def migration_percent(job: dict) -> int:
|
|
137
|
+
"""How far a job has come, 0 to 100."""
|
|
138
|
+
if job.get("status") == "succeeded":
|
|
139
|
+
return 100
|
|
140
|
+
sampled = (job.get("options") or {}).get("sample_rows", 0) > 0
|
|
141
|
+
phases = [(p, w) for p, w in _PHASES if p != "choosing_rows" or sampled]
|
|
142
|
+
total = sum(w for _, w in phases)
|
|
143
|
+
done = 0.0
|
|
144
|
+
for phase, weight in phases:
|
|
145
|
+
if phase == job.get("phase"):
|
|
146
|
+
inside = 0.0
|
|
147
|
+
if phase == "copying_data":
|
|
148
|
+
if job.get("rows_estimate"):
|
|
149
|
+
inside = job["rows_done"] / job["rows_estimate"]
|
|
150
|
+
elif job.get("tables_total"):
|
|
151
|
+
inside = job["tables_done"] / job["tables_total"]
|
|
152
|
+
elif phase == "creating_schema" and job.get("objects_pre"):
|
|
153
|
+
inside = job["objects_done"] / job["objects_pre"]
|
|
154
|
+
elif phase == "creating_indexes":
|
|
155
|
+
after = job.get("objects_total", 0) - job.get("objects_pre", 0)
|
|
156
|
+
if after > 0:
|
|
157
|
+
inside = (job["objects_done"] - job["objects_pre"]) / after
|
|
158
|
+
done += weight * max(0.0, min(1.0, inside))
|
|
159
|
+
break
|
|
160
|
+
done += weight
|
|
161
|
+
return max(0, min(99, int(done / total * 100)))
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
# Reading the job may fail while the migration is doing fine: this program's
|
|
165
|
+
# network, or the project's API service restarting. Reads are tried again for
|
|
166
|
+
# this long before the job is given up as out of reach.
|
|
167
|
+
_OUT_OF_REACH_AFTER = 10 * 60.0
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def _follow(url: str, token: str, job: dict, on_progress: Optional[Callable[..., None]], poll_interval: float) -> dict:
|
|
171
|
+
failing_since = 0.0
|
|
172
|
+
if on_progress:
|
|
173
|
+
on_progress(job, migration_percent(job))
|
|
174
|
+
while job["status"] == "running":
|
|
175
|
+
time.sleep(poll_interval)
|
|
176
|
+
try:
|
|
177
|
+
job = get_migration(url, token, job["id"])
|
|
178
|
+
failing_since = 0.0
|
|
179
|
+
except (httpx.HTTPError, MigrationError) as e:
|
|
180
|
+
# What the project itself answers (no such job, a refused token)
|
|
181
|
+
# is final; the network, or a gateway answering in its place, is not.
|
|
182
|
+
if isinstance(e, MigrationError) and e.code != "failed":
|
|
183
|
+
raise
|
|
184
|
+
failing_since = failing_since or time.monotonic()
|
|
185
|
+
if time.monotonic() - failing_since > _OUT_OF_REACH_AFTER:
|
|
186
|
+
raise MigrationError({
|
|
187
|
+
"code": "out_of_reach",
|
|
188
|
+
"message": "the project has not answered for ten minutes. The migration runs on its server and may well be "
|
|
189
|
+
"going on: follow it again (follow_migration, or python -m corebase.migrate --follow), or look at the project dashboard",
|
|
190
|
+
}, job=job)
|
|
191
|
+
continue
|
|
192
|
+
if on_progress:
|
|
193
|
+
on_progress(job, migration_percent(job))
|
|
194
|
+
return job
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def _finished(job: dict, report: Optional[dict] = None) -> dict:
|
|
198
|
+
if job["status"] not in ("succeeded", "running"):
|
|
199
|
+
raise MigrationError(job.get("error") or {"code": job["status"], "message": "the migration " + job["status"]}, job=job, report=report)
|
|
200
|
+
return job
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def follow_migration(url: str, token: str, job_id: str = "latest", *,
|
|
204
|
+
on_progress: Optional[Callable[..., None]] = None, poll_interval: float = 1.0) -> dict:
|
|
205
|
+
"""Follows a migration that was started before, the project's last one by
|
|
206
|
+
default, until it is over. Returns the finished job; raises MigrationError
|
|
207
|
+
when it failed or was canceled. A KeyboardInterrupt stops following and
|
|
208
|
+
returns the job as it is, still running: the migration itself goes on."""
|
|
209
|
+
job = get_migration(url, token, job_id)
|
|
210
|
+
try:
|
|
211
|
+
job = _follow(url, token, job, on_progress, poll_interval)
|
|
212
|
+
except KeyboardInterrupt:
|
|
213
|
+
return get_migration(url, token, job["id"])
|
|
214
|
+
return _finished(job)
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def migrate_from_postgres(url: str, token: str, source: str, *, auth: Optional[bool] = None,
|
|
218
|
+
sample_rows: Optional[int] = None, schemas: Optional[list] = None,
|
|
219
|
+
check: bool = True, on_check: Optional[Callable[[dict], None]] = None,
|
|
220
|
+
on_progress: Optional[Callable[..., None]] = None,
|
|
221
|
+
poll_interval: float = 1.0) -> dict:
|
|
222
|
+
"""Migrates a Postgres database into the project and waits until it is
|
|
223
|
+
done. Returns the finished job; raises MigrationError when the check
|
|
224
|
+
finds a problem, or the migration fails or is canceled.
|
|
225
|
+
|
|
226
|
+
sample_rows copies at most that many rows of each table, plus every row
|
|
227
|
+
they refer to. on_progress is called with (job, percent) each time the
|
|
228
|
+
job is read; a KeyboardInterrupt cancels the migration.
|
|
229
|
+
|
|
230
|
+
The migration runs on the project's server. If this program ends before
|
|
231
|
+
it is done, it goes on all the same: take it up again with follow_migration."""
|
|
232
|
+
report = None
|
|
233
|
+
if check:
|
|
234
|
+
report = check_migration(url, token, source, auth=auth, sample_rows=sample_rows, schemas=schemas)
|
|
235
|
+
if on_check:
|
|
236
|
+
on_check(report)
|
|
237
|
+
if not report.get("ready"):
|
|
238
|
+
first = (report.get("blockers") or [{}])[0]
|
|
239
|
+
raise MigrationError({"code": "blocked", "message": "the migration cannot start: " + first.get("message", "the check found a problem"),
|
|
240
|
+
"blockers": report.get("blockers")}, report=report)
|
|
241
|
+
job = start_migration(url, token, source, auth=auth, sample_rows=sample_rows, schemas=schemas)
|
|
242
|
+
try:
|
|
243
|
+
job = _follow(url, token, job, on_progress, poll_interval)
|
|
244
|
+
except KeyboardInterrupt:
|
|
245
|
+
cancel_migration(url, token, job["id"])
|
|
246
|
+
job = _follow(url, token, get_migration(url, token, job["id"]), None, 0.5)
|
|
247
|
+
return _finished(job, report)
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
# -- python -m corebase.migrate ---------------------------------------------
|
|
251
|
+
|
|
252
|
+
_PHASE_TEXT = {
|
|
253
|
+
"connecting": "connecting", "planning": "reading the schema", "creating_schema": "creating tables",
|
|
254
|
+
"choosing_rows": "choosing rows", "copying_data": "copying rows", "creating_indexes": "keys and indexes",
|
|
255
|
+
"finishing": "finishing", "committing": "committing", "done": "done",
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
def _n(v) -> str:
|
|
260
|
+
return f"{int(v or 0):,}"
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
def _size(b) -> str:
|
|
264
|
+
v, i = float(b or 0), 0
|
|
265
|
+
units = ["B", "kB", "MB", "GB", "TB"]
|
|
266
|
+
while v >= 1024 and i < len(units) - 1:
|
|
267
|
+
v, i = v / 1024, i + 1
|
|
268
|
+
return f"{v:.1f} {units[i]}" if v < 10 and i else f"{v:.0f} {units[i]}"
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
def main(argv: Optional[list] = None) -> int:
|
|
272
|
+
p = argparse.ArgumentParser(prog="python -m corebase.migrate", description=(
|
|
273
|
+
"Moves a Postgres database (a Supabase project's above all) into a Corebase project: schema, rows and "
|
|
274
|
+
"users, inside one transaction. The project's server does the work; it must be able to reach the source. "
|
|
275
|
+
"Once started the migration does not need this command: if the terminal closes or the network drops it "
|
|
276
|
+
"goes on, and --follow shows it again."))
|
|
277
|
+
p.add_argument("--from", dest="source", default=os.environ.get("SOURCE_DATABASE_URL"), help="the database to migrate from (or SOURCE_DATABASE_URL)")
|
|
278
|
+
p.add_argument("--url", default=os.environ.get("COREBASE_URL"), help="the Corebase project's address (or COREBASE_URL)")
|
|
279
|
+
p.add_argument("--token", default=os.environ.get("COREBASE_MIGRATION_TOKEN"), help="a migration token from the dashboard (or COREBASE_MIGRATION_TOKEN)")
|
|
280
|
+
p.add_argument("--sample-rows", type=int, help="copy at most n rows of each table, plus every row they refer to")
|
|
281
|
+
p.add_argument("--schema", action="append", help="only this schema of the source (repeatable)")
|
|
282
|
+
p.add_argument("--no-auth", action="store_true", help="leave the users (auth.users) behind")
|
|
283
|
+
p.add_argument("--check", action="store_true", help="only check, migrate nothing")
|
|
284
|
+
p.add_argument("--detach", action="store_true", help="start the migration and return at once")
|
|
285
|
+
p.add_argument("--follow", action="store_true", help="follow the project's last migration, started here or on the dashboard; Ctrl-C stops following, not the migration")
|
|
286
|
+
p.add_argument("-y", "--yes", action="store_true", help="start without asking")
|
|
287
|
+
a = p.parse_args(argv)
|
|
288
|
+
if not (a.url and a.token and (a.source or a.follow)):
|
|
289
|
+
p.error("--url and --token (or their environment variables) are both needed" if a.follow
|
|
290
|
+
else "--from, --url and --token (or their environment variables) are all needed")
|
|
291
|
+
opts = {"auth": False if a.no_auth else None, "sample_rows": a.sample_rows, "schemas": a.schema}
|
|
292
|
+
tty = sys.stdout.isatty()
|
|
293
|
+
last = {"line": ""}
|
|
294
|
+
|
|
295
|
+
def draw(job, percent):
|
|
296
|
+
width = 30
|
|
297
|
+
filled = round(percent / 100 * width)
|
|
298
|
+
bar = "█" * filled + "░" * (width - filled)
|
|
299
|
+
count = f"{_n(job['rows_done'])}/{_n(job['rows_estimate'])} rows" if job.get("rows_estimate") else f"{_n(job['rows_done'])} rows"
|
|
300
|
+
what = _PHASE_TEXT.get(job["phase"], job["phase"])
|
|
301
|
+
if tty:
|
|
302
|
+
cols = shutil.get_terminal_size().columns
|
|
303
|
+
again = (f" attempt {job['attempt']}" if job.get("attempt", 1) > 1 else "") + (f" {job['retries']} tables read again" if job.get("retries") else "")
|
|
304
|
+
line = f"[{bar}] {percent:3d}% {what:<17} {count} {_size(job['bytes_done'])}{again}" + (f" {job['current']}" if job.get("current") else "")
|
|
305
|
+
sys.stdout.write("\r" + line[: cols - 1].ljust(min(cols - 1, len(last["line"]))))
|
|
306
|
+
sys.stdout.flush()
|
|
307
|
+
last["line"] = line[: cols - 1]
|
|
308
|
+
elif what != last["line"]:
|
|
309
|
+
print(f"{percent:3d}% {what} {count}")
|
|
310
|
+
last["line"] = what
|
|
311
|
+
|
|
312
|
+
def done(job):
|
|
313
|
+
if tty:
|
|
314
|
+
print()
|
|
315
|
+
print(f"\nmigrated {_n(len(job['tables']))} tables, {_n(job['rows_done'])} rows")
|
|
316
|
+
for t in job["tables"]:
|
|
317
|
+
print(f" {t['name']:<48} {_n(t['rows']):>12} rows")
|
|
318
|
+
|
|
319
|
+
try:
|
|
320
|
+
if a.follow:
|
|
321
|
+
first = get_migration(a.url, a.token)
|
|
322
|
+
print(f"migration {first['id']} from {first['source']}, started {first['started_at']}\n")
|
|
323
|
+
job = follow_migration(a.url, a.token, first["id"], on_progress=draw)
|
|
324
|
+
if job["status"] == "running":
|
|
325
|
+
print("\n\nstopped following; the migration goes on in the project. See it again with --follow.")
|
|
326
|
+
return 0
|
|
327
|
+
done(job)
|
|
328
|
+
return 0
|
|
329
|
+
r = check_migration(a.url, a.token, a.source, **opts)
|
|
330
|
+
rows = sum(t["rows_estimate"] for t in r["tables"])
|
|
331
|
+
print(f"source: {r['source']['address']}")
|
|
332
|
+
print(f" {'Supabase, ' if r['source']['supabase'] else ''}Postgres {r['source']['version'].split(' ')[0]}, {_size(r['source']['size_bytes'])}")
|
|
333
|
+
print(f"schemas: {', '.join(r['schemas']) or '-'}")
|
|
334
|
+
print(f"tables: {_n(len(r['tables']))} (about {_n(rows)} rows)" + (f", at most {_n(r['sample_rows'])} rows each plus what they refer to" if r["sample_rows"] else ""))
|
|
335
|
+
if r["auth"]["present"]:
|
|
336
|
+
print(f"users: {_n(r['auth']['users'])}" + ("" if r["auth"]["migrate"] else " (left behind)"))
|
|
337
|
+
room = r.get("capacity") or {}
|
|
338
|
+
if room.get("disk_bytes"):
|
|
339
|
+
print(f"room: needs about {_size(room['needed_bytes'])}; {_size(room['free_bytes'])} of the project server's {_size(room['disk_bytes'])} disk is free")
|
|
340
|
+
for w in r["warnings"]:
|
|
341
|
+
print(f"warning: {w['message']}" + (f" ({_n(w['count'])})" if w.get("count") else ""))
|
|
342
|
+
for b in r["blockers"]:
|
|
343
|
+
print(f"PROBLEM: {b['message']}")
|
|
344
|
+
for o in (b.get("objects") or [])[:10]:
|
|
345
|
+
print(f" {o}")
|
|
346
|
+
if not r["ready"]:
|
|
347
|
+
return 1
|
|
348
|
+
if a.check:
|
|
349
|
+
return 0
|
|
350
|
+
if not a.yes:
|
|
351
|
+
if not sys.stdin.isatty():
|
|
352
|
+
print("\nadd --yes to start without asking", file=sys.stderr)
|
|
353
|
+
return 2
|
|
354
|
+
if input("\nStart the migration? [y/N] ").strip().lower() not in ("y", "yes"):
|
|
355
|
+
return 1
|
|
356
|
+
print()
|
|
357
|
+
if a.detach:
|
|
358
|
+
job = start_migration(a.url, a.token, a.source, **opts)
|
|
359
|
+
print(f"migration {job['id']} started; it runs in the project. Follow it with: python -m corebase.migrate --follow")
|
|
360
|
+
return 0
|
|
361
|
+
print("The migration runs in the project: if this terminal closes it goes on (see it again with --follow). Ctrl-C cancels it.\n")
|
|
362
|
+
done(migrate_from_postgres(a.url, a.token, a.source, check=False, on_progress=draw, **opts))
|
|
363
|
+
return 0
|
|
364
|
+
except MigrationError as e:
|
|
365
|
+
print(f"\nfailed: {e}", file=sys.stderr)
|
|
366
|
+
for label, value in (("at", e.object), ("detail", e.detail), ("hint", e.hint)):
|
|
367
|
+
if value:
|
|
368
|
+
print(f" {label}: {value}", file=sys.stderr)
|
|
369
|
+
for b in e.blockers:
|
|
370
|
+
print(f" {b.get('message')}", file=sys.stderr)
|
|
371
|
+
if e.job and e.code != "out_of_reach":
|
|
372
|
+
print("nothing was changed in the project.", file=sys.stderr)
|
|
373
|
+
return 1
|
|
374
|
+
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from httpx import Timeout
|
|
4
|
+
|
|
5
|
+
from ._async.client import AsyncPostgrestClient
|
|
6
|
+
from ._async.request_builder import (
|
|
7
|
+
AsyncFilterRequestBuilder,
|
|
8
|
+
AsyncMaybeSingleRequestBuilder,
|
|
9
|
+
AsyncQueryRequestBuilder,
|
|
10
|
+
AsyncRequestBuilder,
|
|
11
|
+
AsyncRPCFilterRequestBuilder,
|
|
12
|
+
AsyncSelectRequestBuilder,
|
|
13
|
+
AsyncSingleRequestBuilder,
|
|
14
|
+
)
|
|
15
|
+
from ._sync.client import SyncPostgrestClient
|
|
16
|
+
from ._sync.request_builder import (
|
|
17
|
+
SyncFilterRequestBuilder,
|
|
18
|
+
SyncMaybeSingleRequestBuilder,
|
|
19
|
+
SyncQueryRequestBuilder,
|
|
20
|
+
SyncRequestBuilder,
|
|
21
|
+
SyncRPCFilterRequestBuilder,
|
|
22
|
+
SyncSelectRequestBuilder,
|
|
23
|
+
SyncSingleRequestBuilder,
|
|
24
|
+
)
|
|
25
|
+
from .base_request_builder import APIResponse
|
|
26
|
+
from .constants import DEFAULT_POSTGREST_CLIENT_HEADERS
|
|
27
|
+
from .exceptions import APIError
|
|
28
|
+
from .types import (
|
|
29
|
+
CountMethod,
|
|
30
|
+
Filters,
|
|
31
|
+
RequestMethod,
|
|
32
|
+
ReturnMethod,
|
|
33
|
+
)
|
|
34
|
+
from .version import __version__
|
|
35
|
+
|
|
36
|
+
__all__ = [
|
|
37
|
+
"AsyncPostgrestClient",
|
|
38
|
+
"AsyncFilterRequestBuilder",
|
|
39
|
+
"AsyncQueryRequestBuilder",
|
|
40
|
+
"AsyncRequestBuilder",
|
|
41
|
+
"AsyncRPCFilterRequestBuilder",
|
|
42
|
+
"AsyncSelectRequestBuilder",
|
|
43
|
+
"AsyncSingleRequestBuilder",
|
|
44
|
+
"AsyncMaybeSingleRequestBuilder",
|
|
45
|
+
"SyncPostgrestClient",
|
|
46
|
+
"SyncFilterRequestBuilder",
|
|
47
|
+
"SyncMaybeSingleRequestBuilder",
|
|
48
|
+
"SyncQueryRequestBuilder",
|
|
49
|
+
"SyncRequestBuilder",
|
|
50
|
+
"SyncRPCFilterRequestBuilder",
|
|
51
|
+
"SyncSelectRequestBuilder",
|
|
52
|
+
"SyncSingleRequestBuilder",
|
|
53
|
+
"APIResponse",
|
|
54
|
+
"DEFAULT_POSTGREST_CLIENT_HEADERS",
|
|
55
|
+
"APIError",
|
|
56
|
+
"CountMethod",
|
|
57
|
+
"Filters",
|
|
58
|
+
"RequestMethod",
|
|
59
|
+
"ReturnMethod",
|
|
60
|
+
"Timeout",
|
|
61
|
+
"__version__",
|
|
62
|
+
]
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
from __future__ import annotations
|