-
Notifications
You must be signed in to change notification settings - Fork 0
feat: add stagingquery quickstart for purchases #375
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
Co-authored-by: Thomas Chow <[email protected]>
WalkthroughA new SQL query is introduced in the purchases module to retrieve purchase data from the database. The query, defined as a multi-line string, selects specific fields from the Changes
Sequence Diagram(s)sequenceDiagram
participant App as Application
participant SQ as StagingQuery
participant DB as Database
App->>SQ: Request purchase data (date range)
SQ->>DB: Execute SQL query with placeholders
DB-->>SQ: Return queried data
SQ-->>App: Deliver purchase results
Suggested reviewers
Poem
Warning Review ran into problems🔥 ProblemsGitHub Actions and Pipeline Checks: Resource not accessible by integration - https://docs.github.com/rest/actions/workflow-runs#list-workflow-runs-for-a-repository. Please grant the required permissions to the CodeRabbit GitHub App under the organization or repository settings. ✨ Finishing Touches
🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 2
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro (Legacy)
📒 Files selected for processing (1)
api/py/test/sample/group_bys/quickstart/purchases.py
(2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
- GitHub Check: non_spark_tests
- GitHub Check: enforce_triggered_workflows
🔇 Additional comments (1)
api/py/test/sample/group_bys/quickstart/purchases.py (1)
18-18
: LGTM!Clean import of required types.
staging_query = StagingQuery( | ||
query=query, | ||
startPartition="2023-10-31", | ||
metaData=MetaData( | ||
name='purchases_staging_query', | ||
outputNamespace="data" | ||
) | ||
) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Avoid hard-coded dates.
Make startPartition configurable.
- startPartition="2023-10-31",
+ startPartition=config.get('STAGING_START_DATE'),
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
staging_query = StagingQuery( | |
query=query, | |
startPartition="2023-10-31", | |
metaData=MetaData( | |
name='purchases_staging_query', | |
outputNamespace="data" | |
) | |
) | |
staging_query = StagingQuery( | |
query=query, | |
startPartition=config.get('STAGING_START_DATE'), | |
metaData=MetaData( | |
name='purchases_staging_query', | |
outputNamespace="data" | |
) | |
) |
query = """ | ||
SELECT | ||
ts, | ||
ds, | ||
purchase_id, | ||
user_id, | ||
product_id, | ||
purchase_price | ||
FROM data.purchases | ||
WHERE ds BETWEEN '{{ start_date }}' AND '{{ end_date }}' | ||
""" |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
💡 Verification agent
🧩 Analysis chain
Add SQL injection protection.
Template variables need proper escaping.
🌐 Web query:
What are the best practices for preventing SQL injection in Python template strings?
💡 Result:
To prevent SQL injection when using Python template strings, follow these best practices informed by database security standards and Python-specific guidelines:
Use Parameterized Queries (Prepared Statements)
Primary defense recommended by OWASP[5] and Python security experts[1][3][4]:
# SAFE: Using query parameters
cursor.execute(
"SELECT * FROM users WHERE username = %s AND password = %s",
(username, password)
)
- Parameters are passed separately from SQL commands[1][4]
- Database drivers handle proper escaping automatically[3][6]
- Supported by all major Python DB APIs (psycopg2, MySQLdb, etc)[6]
Avoid String Interpolation Methods
Never use these for SQL:
# UNSAFE: f-strings[5][9]
cursor.execute(f"SELECT * FROM users WHERE username = '{username}'")
# UNSAFE: .format() or %-formatting[3][8]
query = "SELECT * FROM users WHERE username = '{}'".format(username)
cursor.execute(query)
These allow direct injection of raw SQL through user input[1][4].
Use ORM Libraries
Recommended for complex applications[3][6]:
# SAFE: SQLAlchemy example
from sqlalchemy import text
query = text("SELECT * FROM users WHERE username = :username")
result = session.execute(query, {"username": username})
ORMs provide:
- Automatic parameterization[3]
- Type-safe query construction[6]
- Database abstraction layer[3]
Validate/Sanitize Inputs When Needed
For non-parameterizable elements like table names:
# Validate against allowed values
allowed_tables = {"users", "products"}
if table_name not in allowed_tables:
raise ValueError("Invalid table name")
# Use database-specific identifier quoting
cursor.execute(f"SELECT * FROM {identifier} WHERE id = %s", (user_id,))
Key Security Principles
- Separation of code and data: Treat user input as values never as executable code[1][5]
- Least privilege: Database connections should use restricted accounts[5][6]
- Defense in depth: Combine with input validation and output encoding[2][5]
Modern Python database adapters implement RFC 5427 parameter binding standards[6], making parameterized queries both safe and efficient across PostgreSQL, MySQL, SQLite and other databases[1][4]. For dynamic SQL elements like table names, use allow-list validation rather than blacklist approaches[5][6].
Citations:
- 1: https://realpython.com/prevent-python-sql-injection/
- 2: https://www.appmarq.com/public/tqi,1021044,Avoid-Python-string-interpolations-to-prevent-SQL-injections
- 3: https://go.snyk.io/rs/677-THP-415/images/Python_Cheatsheet_whitepaper.pdf
- 4: https://help.securityjourney.com/en/articles/6719498-python-string-formatting-and-sql-injection-attacks
- 5: https://cheatsheetseries.owasp.org/cheatsheets/SQL_Injection_Prevention_Cheat_Sheet.html
- 6: https://www.youtube.com/watch?v=1cQy9N1Xndk
- 7: https://www.edgeventures.com/kb/post/2021/09/15/python-string-formatting-and-variable-injection
- 8: https://peps.python.org/pep-0501/
SQL Injection Protection: Use Parameterized Queries
- Replace unsafe template interpolation with query placeholders.
- Pass date values as parameters to the execute method.
- For example, update the code to:
query = """
SELECT
ts,
ds,
purchase_id,
user_id,
product_id,
purchase_price
FROM data.purchases
WHERE ds BETWEEN %s AND %s
"""
cursor.execute(query, (start_date, end_date))
Co-authored-by: Thomas Chow <[email protected]>
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
🧹 Nitpick comments (1)
api/py/test/sample/staging_queries/quickstart/purchases.py (1)
19-29
: Consider adding ORDER BY clause.Query might benefit from explicit ordering by timestamp.
FROM data.purchases WHERE ds BETWEEN '{{ start_date }}' AND '{{ end_date }}' +ORDER BY ts ASC
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro (Legacy)
📒 Files selected for processing (1)
api/py/test/sample/staging_queries/quickstart/purchases.py
(1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
- GitHub Check: non_spark_tests
- GitHub Check: enforce_triggered_workflows
🔇 Additional comments (1)
api/py/test/sample/staging_queries/quickstart/purchases.py (1)
31-38
: Hardcoded date needs review.Fixed startPartition date "2023-10-31" might need parameterization.
## Summary ## Checklist - [ ] Added Unit Tests - [ ] Covered by existing CI - [ ] Integration tested - [ ] Documentation update <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit - **New Features** - Introduced a new query to retrieve purchase records with date range filtering. - Enhanced data retrieval by including additional contextual metadata for improved insights. <!-- end of auto-generated comment: release notes by coderabbit.ai --> <!-- av pr metadata This information is embedded by the av CLI when creating PRs to track the status of stacks when using Aviator. Please do not delete or edit this section of the PR. ``` {"parent":"main","parentHead":"","trunk":"main"} ``` --> --------- Co-authored-by: Thomas Chow <[email protected]>
## Summary ## Checklist - [ ] Added Unit Tests - [ ] Covered by existing CI - [ ] Integration tested - [ ] Documentation update <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit - **New Features** - Introduced a new query to retrieve purchase records with date range filtering. - Enhanced data retrieval by including additional contextual metadata for improved insights. <!-- end of auto-generated comment: release notes by coderabbit.ai --> <!-- av pr metadata This information is embedded by the av CLI when creating PRs to track the status of stacks when using Aviator. Please do not delete or edit this section of the PR. ``` {"parent":"main","parentHead":"","trunk":"main"} ``` --> --------- Co-authored-by: Thomas Chow <[email protected]>
## Summary ## Checklist - [ ] Added Unit Tests - [ ] Covered by existing CI - [ ] Integration tested - [ ] Documentation update <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit - **New Features** - Introduced a new query to retrieve purchase records with date range filtering. - Enhanced data retrieval by including additional contextual metadata for improved insights. <!-- end of auto-generated comment: release notes by coderabbit.ai --> <!-- av pr metadata This information is embedded by the av CLI when creating PRs to track the status of stacks when using Aviator. Please do not delete or edit this section of the PR. ``` {"parent":"main","parentHead":"","trunk":"main"} ``` --> --------- Co-authored-by: Thomas Chow <[email protected]>
## Summary ## Checklist - [ ] Added Unit Tests - [ ] Covered by existing CI - [ ] Integration tested - [ ] Documentation update <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit - **New Features** - Introduced a new query to retrieve purchase records with date range filtering. - Enhanced data retrieval by including additional contextual metadata for improved insights. <!-- end of auto-generated comment: release notes by coderabbit.ai --> <!-- av pr metadata This information is embedded by the av CLI when creating PRs to track the status of stacks when using Aviator. Please do not delete or edit this section of the PR. ``` {"parent":"main","parentHead":"","trunk":"main"} ``` --> --------- Co-authored-by: Thomas Chow <[email protected]>
## Summary ## Cheour clientslist - [ ] Added Unit Tests - [ ] Covered by existing CI - [ ] Integration tested - [ ] Documentation update <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit - **New Features** - Introduced a new query to retrieve purchase records with date range filtering. - Enhanced data retrieval by including additional contextual metadata for improved insights. <!-- end of auto-generated comment: release notes by coderabbit.ai --> <!-- av pr metadata This information is embedded by the av CLI when creating PRs to traour clients the status of staour clientss when using Aviator. Please do not delete or edit this section of the PR. ``` {"parent":"main","parentHead":"","trunk":"main"} ``` --> --------- Co-authored-by: Thomas Chow <[email protected]>
Summary
Checklist
Summary by CodeRabbit