Data entry form that writes to Snowflake (Streamlit template)
A validated Streamlit form that writes rows to a Snowflake table safely with bind variables, with the latest entries and a monthly summary.
Click Run to start the app here.
The first start downloads Python for the browser (about 30 MB) and takes 10–30 seconds.
What it answers
Some data has no source system: targets, manual adjustments, expense claims, survey answers. This template is a form that writes validated rows to a Snowflake table, records who entered them and when, and shows the latest entries and a monthly summary.
It is for anyone who maintains a spreadsheet only so it can be loaded into Snowflake later.
What's in it
- Form with validation (date, category, amount, description)
- Writes to Snowflake with bind variables (no SQL injection); records who entered it
- Latest entries, totals this month, chart by month and category
- Works in demo mode without a table (entries kept in the session)
The data it needs
Entries
The table the form writes to (see the CREATE TABLE in the DATA section). Binding usually means pointing both queries at a new or existing table and adjusting CATEGORIES.
| Column | Type | Also matches columns named |
|---|---|---|
ENTRY_ID | number | id, row_id |
ENTRY_DATE | date | date, expense_date, transaction_date |
CATEGORY | text | type, expense_type, kind |
DESCRIPTION | text | note, comment, memo, details |
AMOUNT | number | value, cost, total |
ENTERED_BY | text | created_by, user, submitted_by |
ENTERED_AT | timestamp | created_at, submitted_at, inserted_at |
The query it starts from (ENTRIES_SQL):
SELECT ENTRY_ID, ENTRY_DATE, CATEGORY, DESCRIPTION, AMOUNT, ENTERED_BY, ENTERED_AT
FROM YOUR_DATABASE.YOUR_SCHEMA.ENTRIES
ORDER BY ENTERED_AT DESC
LIMIT 1000
Using it on your data
The DATA section includes the CREATE TABLE statement; create the table (or point the queries at an existing one) and adjust the categories. Values are passed as bind variables, never pasted into the SQL, so the form can't be used for SQL injection.
In StreamGen you don't edit any of this by hand: the agent looks at your tables, matches columns by name and type (including the names above), shows you the mapping, and checks the app on your live data before you deploy it.
Three ways to use it
Try it in StreamGen
Two hours on sample data in a ready-made Snowflake sandbox. No sign-up, nothing to install.
Start the 2-hour tryInstall in your Snowflake
StreamGen is a Snowflake Native App: it runs inside your account, and your data stays there.
Open the Marketplace listingCopy the code
It's a plain Streamlit app. Paste it into Streamlit in Snowflake, set DEMO = False and point the query at your table.
The code
All of it, as it runs in the demo above. The data section at the top is the only part that changes for your tables.
Show all 141 lines
"""Data entry — a validated form that writes rows to a Snowflake table, with
the latest entries and a monthly summary."""
import datetime as dt
import pandas as pd
import plotly.express as px
import streamlit as st
st.set_page_config(page_title="Data entry", layout="wide")
# ── DATA ──────────────────────────────────────────────────────────────────────
# DEMO = True keeps entries in this browser session only. To write to
# Snowflake, create the table once and set DEMO = False:
#
# CREATE TABLE IF NOT EXISTS {{DATABASE}}.{{SCHEMA}}.ENTRIES (
# ENTRY_ID NUMBER AUTOINCREMENT, ENTRY_DATE DATE, CATEGORY STRING,
# DESCRIPTION STRING, AMOUNT NUMBER(18,2), ENTERED_BY STRING,
# ENTERED_AT TIMESTAMP_NTZ DEFAULT CURRENT_TIMESTAMP());
#
DEMO = True
ENTRIES_SQL = """
SELECT ENTRY_ID, ENTRY_DATE, CATEGORY, DESCRIPTION, AMOUNT, ENTERED_BY, ENTERED_AT
FROM {{DATABASE}}.{{SCHEMA}}.ENTRIES
ORDER BY ENTERED_AT DESC
LIMIT 1000
"""
INSERT_SQL = """
INSERT INTO {{DATABASE}}.{{SCHEMA}}.ENTRIES (ENTRY_DATE, CATEGORY, DESCRIPTION, AMOUNT, ENTERED_BY)
SELECT ?, ?, ?, ?, CURRENT_USER()
"""
CATEGORIES = ["Travel", "Equipment", "Software", "Training", "Other"]
MAX_AMOUNT = 100_000.0
# ──────────────────────────────────────────────────────────────────────────────
COLUMNS = ["ENTRY_ID", "ENTRY_DATE", "CATEGORY", "DESCRIPTION", "AMOUNT", "ENTERED_BY", "ENTERED_AT"]
def demo_seed() -> pd.DataFrame:
today = pd.Timestamp.today().normalize()
rows = [(i + 1, (today - pd.Timedelta(days=d)).date(), c, desc, amt, "demo.user", today - pd.Timedelta(days=d))
for i, (d, c, desc, amt) in enumerate([
(2, "Travel", "Client visit Hamburg", 412.50), (5, "Software", "Design tool licence", 59.00),
(9, "Equipment", "Monitor for new hire", 289.00), (16, "Training", "Snowflake course", 650.00),
(31, "Travel", "Conference Berlin", 1180.00), (44, "Other", "Team lunch", 236.40)])]
return pd.DataFrame(rows, columns=COLUMNS)
@st.cache_data(ttl=60, show_spinner=False)
def load_entries() -> pd.DataFrame:
from snowflake.snowpark.context import get_active_session
df = get_active_session().sql(ENTRIES_SQL).to_pandas()
df.columns = [c.upper() for c in df.columns]
return df
def entries() -> pd.DataFrame:
if DEMO:
if "demo_entries" not in st.session_state:
st.session_state.demo_entries = demo_seed()
df = st.session_state.demo_entries.copy()
else:
df = load_entries().copy()
df["ENTRY_DATE"] = pd.to_datetime(df["ENTRY_DATE"], errors="coerce")
df["ENTERED_AT"] = pd.to_datetime(df["ENTERED_AT"], errors="coerce")
df["AMOUNT"] = pd.to_numeric(df["AMOUNT"], errors="coerce")
return df
def save(entry_date: dt.date, category: str, description: str, amount: float) -> None:
if DEMO:
df = st.session_state.demo_entries
new = pd.DataFrame([(int(df["ENTRY_ID"].max() or 0) + 1, entry_date, category, description, amount,
"you (demo)", pd.Timestamp.now())], columns=COLUMNS)
st.session_state.demo_entries = pd.concat([new, df], ignore_index=True)
return
from snowflake.snowpark.context import get_active_session
get_active_session().sql(INSERT_SQL, params=[entry_date.isoformat(), category, description, amount]).collect()
load_entries.clear()
st.title("Data entry")
if DEMO:
st.caption("Demo mode — entries are kept in this session only. Set DEMO = False in the DATA section to write to Snowflake.")
with st.form("entry", clear_on_submit=True):
st.subheader("New entry")
c1, c2, c3 = st.columns([1, 1, 1])
entry_date = c1.date_input("Date", dt.date.today(), max_value=dt.date.today())
category = c2.selectbox("Category", CATEGORIES)
amount = c3.number_input("Amount", min_value=0.0, max_value=MAX_AMOUNT, step=10.0, format="%.2f")
description = st.text_input("Description", max_chars=200, placeholder="What was it for?")
submitted = st.form_submit_button("Save entry", type="primary")
if submitted:
problems = []
if not description.strip():
problems.append("Add a description.")
if amount <= 0:
problems.append("The amount must be greater than 0.")
if problems:
for p in problems:
st.warning(p)
else:
try:
save(entry_date, category, description.strip(), float(amount))
st.success(f"Saved: {category} · {amount:,.2f} · {description.strip()}")
except Exception as e:
st.error(f"Could not save the entry: {e}")
try:
data = entries()
except Exception as e:
st.error(f"Could not load entries: {e}")
st.stop()
if data.empty:
st.info("No entries yet — add the first one above.")
st.stop()
this_month = data[data["ENTRY_DATE"] >= pd.Timestamp.today().normalize().replace(day=1)]
k = st.columns(3)
k[0].metric("Entries", f"{len(data):,}")
k[1].metric("This month", f"{this_month['AMOUNT'].sum():,.2f}")
k[2].metric("Last entry", data["ENTERED_AT"].max().strftime("%d %b %Y %H:%M") if data["ENTERED_AT"].notna().any() else "–")
left, right = st.columns([3, 2])
left.subheader("Latest entries")
left.dataframe(data.head(50).reset_index(drop=True), width="stretch", column_config={
"ENTRY_DATE": st.column_config.DateColumn("Date"),
"AMOUNT": st.column_config.NumberColumn("Amount", format="%.2f"),
"ENTERED_AT": st.column_config.DatetimeColumn("Entered", format="D MMM YYYY, HH:mm"),
})
monthly = (data.assign(MONTH=data["ENTRY_DATE"].dt.to_period("M").dt.to_timestamp())
.groupby(["MONTH", "CATEGORY"], as_index=False)["AMOUNT"].sum())
fig = px.bar(monthly, x="MONTH", y="AMOUNT", color="CATEGORY", color_discrete_sequence=px.colors.qualitative.Safe,
labels={"MONTH": "", "AMOUNT": "Amount"}, title="By month")
fig.update_layout(legend_title_text="", margin=dict(t=50, b=10))
right.plotly_chart(fig, width="stretch")
st.download_button("Download CSV", data.to_csv(index=False), "entries.csv", "text/csv")
Questions
Can people edit or delete rows?
Not in the template, so the table stays an audit trail. Ask StreamGen's agent for an edit form with a reason field if you need corrections.
Whose name is recorded?
In Snowflake, the signed-in user's name (CURRENT_USER()), so you can see who entered each row.
Can I use the code without StreamGen?
Yes. It is a plain Streamlit app. In Snowsight, create a Streamlit app, paste the code, add plotly to its packages, set DEMO = False and point the query at your table. StreamGen does that mapping, the checks and the deploy for you, and keeps the app working afterwards.
Does my data leave Snowflake?
No. In Snowflake the app runs inside your account and queries your tables there. The live demo on this page runs in your browser on generated sample data; nothing is sent anywhere.
Warehouse or container runtime?
Both work. The template only needs pandas, numpy and plotly, which both Streamlit in Snowflake runtimes provide.
Related templates
Forecast
Project a metric forward with trend and seasonality, a 90% range, recent accuracy from a backtest, and unusual periods flagged. A Streamlit template for Snowflake.
Data explorer
Browse the tables in a Snowflake schema, profile columns, filter rows, group and chart, and download what you find. A read-only Streamlit template.
Customer feedback with Cortex AI
Score reviews, tickets or survey answers with Snowflake Cortex AI, sentiment, topics and an AI summary of the complaints. A free Streamlit template.
Build it on your own Snowflake data
In StreamGen you pick this template, the agent matches it to your tables, checks it, and deploys it to Snowflake with roles, approvals and an audit trail. Then ask for changes in plain words.
No sign-up for the 2-hour try. The Native App is free to install, with a free 7-day trial key.