Skip to content

Commit

Permalink
Merge pull request #1 from JustinFrizzell/handle-db-credentials
Browse files Browse the repository at this point in the history
Handle database credentials
  • Loading branch information
JustinFrizzell authored Nov 14, 2023
2 parents b1c9c78 + 52688f3 commit 2e0f088
Show file tree
Hide file tree
Showing 5 changed files with 107 additions and 48 deletions.
1 change: 1 addition & 0 deletions Pipfile
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ pandas = "*"
sqlalchemy = "*"
pyyaml = "*"
pyodbc = "*"
python-dotenv = "*"

[dev-packages]
setuptools = "*"
Expand Down
81 changes: 47 additions & 34 deletions Pipfile.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

42 changes: 33 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,13 @@ Here's a quick example to get you started:
import SQLconnect as sc

# Establish a connection to the database
connection = sc.SQLconnector("WorldWideImporters")
connection = sc.SQLconnector("Database_PROD")

# Assign the results of a query to a pandas DataFrame
df = connection.query_to_df("query.sql")

# Print the top 5 rows of the DataFrame
print(df.head(5))
print(df.head())

# Print the connection details
print(f"connection_name: {connection.connection_name}")
Expand All @@ -37,28 +37,52 @@ print(f"database_url: {connection.database_url}")

## Configuration

To use SQLconnect, create a `connections.yaml` file in your project directory with the following example structure:
To use SQLconnect, create a `connections.yaml` file in the root of your project directory with the following example structure:

```yaml
connections:
Database_DEV:
sqlalchemy_driver: 'mssql+pyodbc'
odbc_driver: 'SQL Server'
odbc_driver: 'SQL+Server'
server: 'dev-server.database.com'
database: 'DevDB'
database: 'DevDB'
options:
- 'Trusted_Connection=Yes'
Database_TEST:
sqlalchemy_driver: 'mssql+pyodbc'
odbc_driver: 'SQL+Server'
server: 'test-server.database.com'
database: 'TestDB'
username: '${DB_TEST_USERNAME}' # This references the environment variable DB_TEST_USERNAME setup in .env
password: '${DB_TEST_PASSWORD}' # This references the environment variable DB_TEST_PASSWORD setup in .env
options:
- 'Trusted_Connection=No'
Database_PROD:
sqlalchemy_driver: 'mssql+pyodbc'
odbc_driver: 'SQL Server'
odbc_driver: 'SQL+Server'
server: 'prod-server.database.com'
database: 'ProdDB'
username: '${DB_PROD_USERNAME}' # This references the environment variable DB_PROD_USERNAME setup in .env
password: '${DB_PROD_PASSWORD}' # This references the environment variable DB_PROD_PASSWORD setup in .env
options:
- 'Trusted_Connection=Yes'
- 'Trusted_Connection=No'
```
Also create a `.env` file in the root of your project directory with the following example structure:

```bash
# This file should be kept secure and not checked into version control.
# Development Database Credentials
DB_TEST_USERNAME=devUser
DB_TEST_PASSWORD=devPassword
# Production Database Credentials
DB_PROD_USERNAME=prodUser
DB_PROD_PASSWORD=prodPassword
```

Replace the placeholder values with your actual database connection details.
Replace the example values with your actual database connection details.

## License

This project is licensed under the [MIT License](LICENCE).
This project is licensed under the [MIT License](https://raw.githubusercontent.com/JustinFrizzell/SQLconnect/main/LICENCE).
19 changes: 16 additions & 3 deletions SQLconnect/config.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
""" Handles validating and loading the connection configuration file """
import os
from pathlib import Path
import yaml
from dotenv import load_dotenv


def get_connection_config(connection_name: str, config_path: str = None) -> dict:
Expand All @@ -22,7 +24,18 @@ def get_db_url(connection_config: dict) -> str:
odbc_driver = connection_config["odbc_driver"]
server = connection_config["server"]
database = connection_config["database"]
options = "&".join([f"driver={odbc_driver}"] + connection_config["options"])

connection_string = f"{sqlalchemy_driver}://@{server}/{database}?{options}"
options = "&".join([f"driver={odbc_driver}"] + connection_config.get("options", []))

# Check for username and password
auth_details = ""
if "username" in connection_config and "password" in connection_config:
load_dotenv()
username = os.getenv(connection_config["username"].strip("${}"))
password = os.getenv(connection_config["password"].strip("${}"))
auth_details = f"{username}:{password}@"

# Construct the connection string
connection_string = (
f"{sqlalchemy_driver}://{auth_details}{server}/{database}?{options}"
)
return connection_string
12 changes: 10 additions & 2 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,18 @@

setuptools.setup(
name="SQLconnect",
version="0.0.1",
version="0.0.2",
author="Justin Frizzell",
description=""" Package to simplify connections to SQL databases. """,
long_description=Path("README.md").read_text(encoding="utf=8"),
long_description_content_type="text/markdown",
url="https://github.com/JustinFrizzell/SQLconnect",
packages=setuptools.find_packages(),
install_requires=["pandas", "sqlalchemy", "pyyaml", "pyodbc"],
install_requires=["pandas", "sqlalchemy", "pyyaml", "pyodbc", "python-dotenv"],
classifiers=[
"License :: OSI Approved :: MIT License",
"Intended Audience :: Developers",
"Topic :: Database",
],
keywords="SQL database connection configuration data",
)

0 comments on commit 2e0f088

Please sign in to comment.