Skip to content

Commit 5410539

Browse files
committed
fix: get the tenant_id from the host config
1 parent d84cbd9 commit 5410539

6 files changed

Lines changed: 198 additions & 154 deletions

File tree

examples/eav_example.py

Lines changed: 13 additions & 62 deletions
Original file line numberDiff line numberDiff line change
@@ -5,74 +5,25 @@
55

66
def main() -> None:
77
cvec = CVec(
8-
host=os.environ.get("CVEC_HOST", "your-subdomain.cvector.dev"),
8+
host=os.environ.get(
9+
"CVEC_HOST", "https://your-subdomain.cvector.dev"
10+
), # Replace with your API host
911
api_key=os.environ.get("CVEC_API_KEY", "your-api-key"),
1012
)
1113

12-
tenant_id = 1 # Replace with your tenant ID
13-
14-
# Example: List available EAV tables
15-
print("\nListing EAV tables...")
16-
tables = cvec.get_eav_tables(tenant_id)
17-
print(f"Found {len(tables)} tables")
18-
for table in tables:
19-
print(f"- {table.name} (id: {table.id})")
20-
21-
if not tables:
22-
print("No tables found. Exiting.")
23-
return
24-
25-
# Use the first table for demonstration
26-
table_name = tables[0].name
27-
28-
# Example: List columns for the table
29-
print(f"\nListing columns for '{table_name}'...")
30-
columns = cvec.get_eav_columns(tables[0].id)
31-
print(f"Found {len(columns)} columns")
32-
for column in columns:
33-
print(f"- {column.name} ({column.type})")
34-
35-
# Example: Query all rows from the table
36-
print(f"\nQuerying '{table_name}' (all columns, no filters)...")
37-
rows = cvec.select_from_eav(
38-
tenant_id=tenant_id,
39-
table_name=table_name,
14+
# Example: Query with numeric range filter
15+
print("\nQuerying with numeric range filter...")
16+
rows = cvec.select_from_eav_id(
17+
table_id="00000000-0000-0000-0000-000000000000",
18+
column_ids=["abcd", "defg", "hijk"],
19+
filters=[
20+
EAVFilter(column_id="abcd", numeric_min=45992, numeric_max=45993),
21+
],
4022
)
41-
print(f"Found {len(rows)} rows")
42-
for row in rows[:5]: # Show first 5 rows
23+
print(f"Found {len(rows)} rows with abcd in range [45992, 45993)")
24+
for row in rows:
4325
print(f"- {row}")
4426

45-
# Example: Query with numeric range filter (if there's a numeric column)
46-
numeric_columns = [c for c in columns if c.type == "number"]
47-
if numeric_columns:
48-
col_name = numeric_columns[0].name
49-
print(f"\nQuerying with numeric filter on '{col_name}'...")
50-
rows = cvec.select_from_eav(
51-
tenant_id=tenant_id,
52-
table_name=table_name,
53-
filters=[
54-
EAVFilter(column_name=col_name, numeric_min=0),
55-
],
56-
)
57-
print(f"Found {len(rows)} rows with {col_name} >= 0")
58-
59-
# Example: Query with string filter (if there's a string column)
60-
string_columns = [c for c in columns if c.type == "string"]
61-
if string_columns and rows:
62-
col_name = string_columns[0].name
63-
# Get a sample value from the first row
64-
sample_value = rows[0].get(col_name) if rows else None
65-
if sample_value:
66-
print(f"\nQuerying with string filter on '{col_name}'...")
67-
rows = cvec.select_from_eav(
68-
tenant_id=tenant_id,
69-
table_name=table_name,
70-
filters=[
71-
EAVFilter(column_name=col_name, string_value=str(sample_value)),
72-
],
73-
)
74-
print(f"Found {len(rows)} rows with {col_name}='{sample_value}'")
75-
7627

7728
if __name__ == "__main__":
7829
main()

examples/show_eav_schema.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
#!/usr/bin/env python3
2+
"""Show EAV tables and columns."""
3+
4+
import os
5+
6+
from cvec import CVec
7+
8+
9+
def main() -> None:
10+
cvec = CVec(
11+
host=os.environ.get("CVEC_HOST", ""),
12+
api_key=os.environ.get("CVEC_API_KEY", ""),
13+
)
14+
15+
tables = cvec.get_eav_tables()
16+
print(f"Found {len(tables)} EAV tables\n")
17+
18+
for table in tables:
19+
print(f"{table.name} (id: {table.id})")
20+
columns = cvec.get_eav_columns(table.id)
21+
for column in columns:
22+
print(f" - {column.name} ({column.type}, id: {column.eav_column_id})")
23+
print()
24+
25+
26+
if __name__ == "__main__":
27+
main()

src/cvec/cvec.py

Lines changed: 22 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ class CVec:
3333
_refresh_token: Optional[str]
3434
_publishable_key: Optional[str]
3535
_api_key: Optional[str]
36+
_tenant_id: int
3637

3738
def __init__(
3839
self,
@@ -64,8 +65,8 @@ def __init__(
6465
"CVEC_API_KEY must be set either as an argument or environment variable"
6566
)
6667

67-
# Fetch publishable key from host config
68-
self._publishable_key = self._fetch_publishable_key()
68+
# Fetch config (publishable key and tenant ID)
69+
self._publishable_key = self._fetch_config()
6970

7071
# Handle authentication
7172
email = self._construct_email_from_api_key()
@@ -485,15 +486,17 @@ def _refresh_supabase_token(self) -> None:
485486
self._access_token = data["access_token"]
486487
self._refresh_token = data["refresh_token"]
487488

488-
def _fetch_publishable_key(self) -> str:
489+
def _fetch_config(self) -> str:
489490
"""
490-
Fetch the publishable key from the host's config endpoint.
491+
Fetch configuration from the host's config endpoint.
492+
493+
Sets the tenant_id on the instance and returns the publishable key.
491494
492495
Returns:
493496
The publishable key from the config response
494497
495498
Raises:
496-
ValueError: If the config endpoint is not accessible or doesn't contain the key
499+
ValueError: If the config endpoint is not accessible or doesn't contain required fields
497500
"""
498501
try:
499502
config_url = f"{self.host}/config"
@@ -504,10 +507,14 @@ def _fetch_publishable_key(self) -> str:
504507
config_data = json.loads(response_data.decode("utf-8"))
505508

506509
publishable_key = config_data.get("supabasePublishableKey")
510+
tenant_id = config_data.get("tenantId")
507511

508512
if not publishable_key:
509513
raise ValueError(f"Configuration fetched from {config_url} is invalid")
514+
if tenant_id is None:
515+
raise ValueError(f"tenantId not found in config from {config_url}")
510516

517+
self._tenant_id = int(tenant_id)
511518
return str(publishable_key)
512519

513520
except (HTTPError, URLError) as e:
@@ -646,19 +653,16 @@ def make_query_request() -> Any:
646653
raise e
647654
raise
648655

649-
def get_eav_tables(self, tenant_id: int) -> List[EAVTable]:
656+
def get_eav_tables(self) -> List[EAVTable]:
650657
"""
651-
Get all EAV tables for a tenant.
652-
653-
Args:
654-
tenant_id: The tenant ID to query tables for
658+
Get all EAV tables for the tenant.
655659
656660
Returns:
657661
List of EAVTable objects
658662
"""
659663
response_data = self._query_table(
660664
"eav_tables",
661-
{"tenant_id": f"eq.{tenant_id}", "order": "name"},
665+
{"tenant_id": f"eq.{self._tenant_id}", "order": "name"},
662666
)
663667
return [EAVTable.model_validate(table) for table in response_data]
664668

@@ -680,7 +684,6 @@ def get_eav_columns(self, table_id: str) -> List[EAVColumn]:
680684

681685
def select_from_eav_id(
682686
self,
683-
tenant_id: int,
684687
table_id: str,
685688
column_ids: Optional[List[str]] = None,
686689
filters: Optional[List[EAVFilter]] = None,
@@ -692,7 +695,6 @@ def select_from_eav_id(
692695
interface using names, see select_from_eav().
693696
694697
Args:
695-
tenant_id: The tenant ID to query data for
696698
table_id: The UUID of the EAV table to query
697699
column_ids: Optional list of column IDs to include in the result.
698700
If None, all columns are returned.
@@ -715,7 +717,6 @@ def select_from_eav_id(
715717
... EAVFilter(column_id="z09PL", string_value="ACTIVE"),
716718
... ]
717719
>>> rows = client.select_from_eav_id(
718-
... tenant_id=1,
719720
... table_id="550e8400-e29b-41d4-a716-446655440000",
720721
... column_ids=["MTnaC", "z09PL", "ZNAGI"],
721722
... filters=filters,
@@ -742,7 +743,7 @@ def select_from_eav_id(
742743
filters_json.append(filter_dict)
743744

744745
params: Dict[str, Any] = {
745-
"tenant_id": tenant_id,
746+
"tenant_id": self._tenant_id,
746747
"table_id": table_id,
747748
"column_ids": column_ids,
748749
"filters": filters_json,
@@ -753,7 +754,6 @@ def select_from_eav_id(
753754

754755
def select_from_eav(
755756
self,
756-
tenant_id: int,
757757
table_name: str,
758758
column_names: Optional[List[str]] = None,
759759
filters: Optional[List[EAVFilter]] = None,
@@ -765,7 +765,6 @@ def select_from_eav(
765765
select_from_eav_id(). For direct ID access, use select_from_eav_id().
766766
767767
Args:
768-
tenant_id: The tenant ID to query data for
769768
table_name: The name of the EAV table to query
770769
column_names: Optional list of column names to include in the result.
771770
If None, all columns are returned.
@@ -788,7 +787,6 @@ def select_from_eav(
788787
... EAVFilter(column_name="Status", string_value="ACTIVE"),
789788
... ]
790789
>>> rows = client.select_from_eav(
791-
... tenant_id=1,
792790
... table_name="BT/Scrap Entry",
793791
... column_names=["Weight", "Status", "Is Verified"],
794792
... filters=filters,
@@ -797,10 +795,14 @@ def select_from_eav(
797795
# Look up the table ID from the table name
798796
tables_response = self._query_table(
799797
"eav_tables",
800-
{"tenant_id": f"eq.{tenant_id}", "name": f"eq.{table_name}", "limit": "1"},
798+
{
799+
"tenant_id": f"eq.{self._tenant_id}",
800+
"name": f"eq.{table_name}",
801+
"limit": "1",
802+
},
801803
)
802804
if not tables_response:
803-
raise ValueError(f"Table '{table_name}' not found for tenant {tenant_id}")
805+
raise ValueError(f"Table '{table_name}' not found")
804806
table_id = tables_response[0]["id"]
805807

806808
# Get all columns for the table to build name <-> id mappings
@@ -846,7 +848,6 @@ def select_from_eav(
846848

847849
# Call the ID-based method
848850
response_data = self.select_from_eav_id(
849-
tenant_id=tenant_id,
850851
table_id=table_id,
851852
column_ids=column_ids,
852853
filters=id_filters,

0 commit comments

Comments
 (0)