Skip to content

Commit 56ce5d8

Browse files
authored
Automatically create the tables for the SqlCatalog (#186)
* ensure tables exist on init * make private * remove unnecessary comment * style
1 parent 2493789 commit 56ce5d8

2 files changed

Lines changed: 13 additions & 7 deletions

File tree

mkdocs/docs/api.md

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -54,12 +54,6 @@ catalog = load_catalog(
5454
)
5555
```
5656

57-
If the catalog has not been initialized before, you need to run:
58-
59-
```python
60-
catalog.create_tables()
61-
```
62-
6357
Let's create a namespace:
6458

6559
```python

pyiceberg/catalog/sql.py

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@
3131
union,
3232
update,
3333
)
34-
from sqlalchemy.exc import IntegrityError
34+
from sqlalchemy.exc import IntegrityError, OperationalError
3535
from sqlalchemy.orm import (
3636
DeclarativeBase,
3737
Mapped,
@@ -98,6 +98,18 @@ def __init__(self, name: str, **properties: str):
9898
raise NoSuchPropertyException("SQL connection URI is required")
9999
self.engine = create_engine(uri_prop, echo=True)
100100

101+
self._ensure_tables_exist()
102+
103+
def _ensure_tables_exist(self) -> None:
104+
with Session(self.engine) as session:
105+
for table in [IcebergTables, IcebergNamespaceProperties]:
106+
stmt = select(1).select_from(table)
107+
try:
108+
session.scalar(stmt)
109+
except OperationalError:
110+
self.create_tables()
111+
return
112+
101113
def create_tables(self) -> None:
102114
SqlCatalogBaseTable.metadata.create_all(self.engine)
103115

0 commit comments

Comments
 (0)