Skip to content

Commit 5593b95

Browse files
committed
Update Streamlit OLTP docs
1 parent b0c7df4 commit 5593b95

File tree

2 files changed

+41
-19
lines changed

2 files changed

+41
-19
lines changed

docs/docs/streamlit/tables/oltp_database_connect.mdx

Lines changed: 40 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ sidebar_position: 1
44

55
# Connect an OLTP database
66

7-
This app connects to a [Databricks Lakebase](https://docs.databricks.com/aws/en/oltp/) OLTP database instance. Provide the instance name, database, schema, and table.
7+
This app connects to a [Databricks Lakebase](https://docs.databricks.com/aws/en/oltp/) OLTP database instance for reads and writes, e.g., of an App state. Provide the instance name, database, schema, and state table.
88

99
## Code snippet
1010

@@ -14,26 +14,20 @@ import streamlit as st
1414
import pandas as pd
1515

1616
from databricks.sdk import WorkspaceClient
17-
1817
import psycopg
1918
from psycopg_pool import ConnectionPool
2019

2120

2221
w = WorkspaceClient()
2322

2423

25-
def _generate_token(instance_name: str) -> str:
26-
cred = w.database.generate_database_credential(
27-
request_id=str(uuid.uuid4()), instance_names=[instance_name]
28-
)
29-
return cred.token
30-
31-
3224
class RotatingTokenConnection(psycopg.Connection):
3325
@classmethod
3426
def connect(cls, conninfo: str = "", **kwargs):
35-
instance_name = kwargs.pop("_instance_name")
36-
kwargs["password"] = _generate_token(instance_name)
27+
kwargs["password"] = w.database.generate_database_credential(
28+
request_id=str(uuid.uuid4()),
29+
instance_names=[kwargs.pop("_instance_name")]
30+
).token
3731
kwargs.setdefault("sslmode", "require")
3832
return super().connect(conninfo, **kwargs)
3933

@@ -45,29 +39,57 @@ def build_pool(instance_name: str, host: str, user: str, database: str) -> Conne
4539
connection_class=RotatingTokenConnection,
4640
kwargs={"_instance_name": instance_name},
4741
min_size=1,
48-
max_size=10,
42+
max_size=5,
4943
open=True,
5044
)
5145

52-
46+
5347
def query_df(pool: ConnectionPool, sql: str) -> pd.DataFrame:
5448
with pool.connection() as conn:
5549
with conn.cursor() as cur:
5650
cur.execute(sql)
51+
if cur.description is None:
52+
return pd.DataFrame()
5753
cols = [d.name for d in cur.description]
5854
rows = cur.fetchall()
59-
6055
return pd.DataFrame(rows, columns=cols)
6156

57+
58+
session_id = str(uuid.uuid4())
59+
if "session_id" not in st.session_state:
60+
st.session_state["session_id"] = session_id
61+
6262

6363
instance_name = "dbase_instance"
64-
database = "customer_database"
65-
table = "customer_core.customers_oltp"
64+
database = "databricks_postgres"
65+
schema = "public"
66+
table = "app_state"
6667
user = w.current_user.me().user_name
6768
host = w.database.get_database_instance(name=instance_name).read_write_dns
6869

6970
pool = build_pool(instance_name, host, user, database)
70-
df = query_df(pool, f'SELECT * FROM {table} LIMIT 100')
71+
72+
with pool.connection() as conn:
73+
with conn.cursor() as cur:
74+
cur.execute(f"""
75+
CREATE TABLE IF NOT EXISTS {schema}.{table} (
76+
session_id TEXT,
77+
key TEXT,
78+
value TEXT,
79+
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
80+
PRIMARY KEY (session_id, key)
81+
)
82+
""")
83+
84+
cur.execute(f"""
85+
INSERT INTO app_state (session_id, key, value, updated_at)
86+
VALUES ('{session_id}', 'feedback_message', 'true', CURRENT_TIMESTAMP)
87+
ON CONFLICT (session_id, key) DO UPDATE
88+
SET value = EXCLUDED.value,
89+
updated_at = CURRENT_TIMESTAMP
90+
""")
91+
92+
df = query_df(pool, f"SELECT * FROM {schema}.{table} WHERE session_id = '{session_id}'")
7193
st.dataframe(df)
7294
```
7395

@@ -90,7 +112,7 @@ Then, your [app service principal](https://docs.databricks.com/aws/en/dev-tools/
90112

91113
GRANT CONNECT ON DATABASE databricks_postgres TO "099f0306-9e29-4a87-84c0-3046e4bcea02";
92114
GRANT USAGE ON SCHEMA public TO "099f0306-9e29-4a87-84c0-3046e4bcea02";
93-
GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE quotes_history TO "099f0306-9e29-4a87-84c0-3046e4bcea02";
115+
GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE app_state TO "099f0306-9e29-4a87-84c0-3046e4bcea02";
94116

95117
See [this guide](https://docs.databricks.com/aws/en/oltp/pg-roles?language=PostgreSQL#create-postgres-roles-and-grant-privileges-for-databricks-identities) for more information.
96118

streamlit/views/oltp_database_connect.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
st.header("OLTP Database", divider=True)
1212
st.subheader("Connect a table")
1313
st.write(
14-
"This app connects to a [Databricks Lakebase](https://docs.databricks.com/aws/en/oltp/) OLTP database instance for reads and writes, e.g., of App state. "
14+
"This app connects to a [Databricks Lakebase](https://docs.databricks.com/aws/en/oltp/) OLTP database instance for reads and writes, e.g., of an App state. "
1515
"Provide the instance name, database, schema, and state table."
1616
)
1717

0 commit comments

Comments
 (0)