Skip to content

Commit

Permalink
Version 0.2.0
Browse files Browse the repository at this point in the history
  • Loading branch information
PoshoDev committed Sep 22, 2022
1 parent c91b8a3 commit 5c6ecfd
Show file tree
Hide file tree
Showing 4 changed files with 117 additions and 160 deletions.
105 changes: 96 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,28 +13,115 @@ $ pip install loaf



## Sample Demo
## Examples

### Importing Into Your Project

```python
import loaf
from loaf import Loaf
```



### Setting Up Credentials

```python
# Setup your credentials with a single line.
loaf.bake(port=6969, db="pizzeria")
loaf = Loaf(port=6969, db="pizzeria")
# Or load your credentials from a file.
loaf = Loaf(file="creds.ini")
# Or use a local SQLite file instead.
loaf = Loaf(file="pizzeria.db")
```



### Executing Queries

```python
# Make queries easily.
toppings = loaf.query("SELECT * from toppings")
# Load your quieries directly from files.
clients = loaf.query(file="getHappyClients.sql")
# Prevent disasters by executing multiple queries.
pepperoni_id, client_name = loaf.multi([
"SELECT id FROM toppings WHERE name='Pepperoni'",
"SELECT name FROM clients WHERE id=6"
])
```



### Printing

```python
# Display info using built-in tables!
loaf.print(pepperoni_id)
loaf.print(client_name)
loaf.print(toppings)
```

```powershell
┏━━━━┓
┃ id ┃
┡━━━━┩
│ 1 │
└────┘
┏━━━━━━━━━━━┓
┃ name ┃
┡━━━━━━━━━━━┩
│ 'Alfonso' │
└───────────┘
┏━━━━┳━━━━━━━━━━━━━┳━━━━━━━┓
┃ id ┃ name ┃ price ┃
┡━━━━╇━━━━━━━━━━━━━╇━━━━━━━┩
│ 1 │ 'Pepperoni' │ 1.49 │
│ 2 │ 'Mushrooms' │ 1.99 │
│ 3 │ 'Onions' │ 0.99 │
└────┴─────────────┴───────┘
```



### Data Manipulation

```python
# Manipulate your data with dictionaries, as God intended.
for topping in toppings:
print(topping['name'])
```

````powershell
Pepperoni
Mushrooms
Onions
````



# Make a query easily.
result = loaf.query("SELECT * from toppings")
print(result)
### Utilities

```python
# Not lazy enough? Try some of the pre-built queires.
# Equivalent of: SELECT name FROM client WHERE name='Marco' LIMIT 1
result = loaf.select("name", "clients", "name='Marco'", limit=1)
# Get all values from a table.
result = loaf.all("toppings")
print(result)

# Got stored procedures? No problemo!
result = loaf.call("ProcedureFindClient", 1)
print(result)
```



![](https://github.com/PoshoDev/Loaf/blob/main/loaf.png?raw=true)



```
⚠️ Syntax for the package has changed heavily since version 0.2.0, if your project depends on Loaf and is using an inferior version, I heavily suggest that you use the previous stable version:
```

```
$ pip install loaf==0.1.30
```

23 changes: 12 additions & 11 deletions loaf/__init__.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
# A Python module for effortless database usage.

import pymysql, psycopg2, psycopg2.extras, sqlite3, datetime, socket, configparser
from rich.table import Table
from rich import print as rprint

cursors = ["DEFAULT", "DICTIONARY"]
cursors = ["DICTIONARY", "DEFAULT"]
modes = ["MySQL", "PostgreSQL", "SQLite"]
defaults = {
"host": socket.gethostbyname(socket.gethostname()),
Expand Down Expand Up @@ -176,32 +174,25 @@ def call(self, procedure, args=[], rollback_on_error=None):

# Prints the result of a query as a rich table. The 'data' argument can be a tuple or a dictionary.
def print(self, data, title=None):
# If the data is a dictionary, convert it to a tuple.
if type(data) == dict:
data = tuple(data.items())
# If the data is a tuple, convert it to a list. This is done because the Rich library doesn't support tuples.
if type(data) == tuple:
data = list(data)
# If the data is a list, convert it to a table.
if type(data) == list:
table = Table(title=title)
# If the data is a list of tuples, convert it to a table.
if type(data[0]) == tuple:
for i in range(len(data[0])):
table.add_column(data[0][i])
for i in range(1, len(data)):
table.add_row(*data[i])
# If the data is a list of dictionaries, convert it to a table.
elif type(data[0]) == dict:
for i in data[0].keys():
table.add_column(i)
for i in data:
# Parse the values to strings. Then add the rows.
values = []
for j in i.values():
values.append(parse(j))
values.append(tParse(j))
table.add_row(*values)
# Print the table.
rprint(table)
else:
raise Exception("Invalid data type.")
Expand Down Expand Up @@ -326,3 +317,13 @@ def parse(value):
if isinstance(value, datetime.date):
return value.strftime("%Y-%m-%d")
return "'" + str(value).replace("'", "''") + "'"

# Parses a value to a colored string to be used in tables.
def tParse(value):
if value in [None, "", "NULL"]:
return "[dim]NULL[/]"
if isinstance(value, int):
return "[magenta]" + str(value) + "[/]"
if isinstance(value, datetime.date):
return "[cyan]" + value.strftime("%Y-%m-%d") + "[/]"
return "[green]'" + str(value).replace("'", "''") + "'[/]"
138 changes: 0 additions & 138 deletions loaf/__init__OLD.py

This file was deleted.

11 changes: 9 additions & 2 deletions setup.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from setuptools import setup, find_packages

VERSION = "0.1.30"
VERSION = "0.2.0"
DESCRIPTION = "Effortlessly access your SQL servers and procedures, plus " \
"some other utilities!"
with open('README.md', encoding="utf8") as f:
Expand All @@ -16,7 +16,14 @@
long_description_content_type="text/markdown",
long_description=LONG_DESCRIPTION,
packages=find_packages(),
install_requires=["pymysql", "datetime"], # Excludes "socket"
install_requires=[
"pymysql",
"psycopg2",
"sqlite3",
"datetime",
"socket",
"configparser"
],
keywords=['python', 'SQL', 'MySQL', 'MariaDB', 'PostgreSQL', 'database',
'db', 'easy', 'loaf', 'bread'],
classifiers=[
Expand Down

0 comments on commit 5c6ecfd

Please sign in to comment.