treleadb


Nametreleadb JSON
Version 0.1.0 PyPI version JSON
download
home_pagehttps://github.com/trelea/TreleaDB
SummaryTreleaDB object database for Python.
upload_time2024-03-10 18:13:16
maintainer
docs_urlNone
authorTrelea Marius
requires_python
license
keywords python python3 database nodql mongodb treleadb object json
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # TreleaDB

TreleaDB is a database, its provides object-oriented database for Python that provides a high-degree of transparency.

Its a very simple Database build for developing mini projects. It provides encryption, hashing and other specifications.

## Downloads

TreleaDB is distributed through the Python Package Index.

You can install the TreleaDB using pip command:

```
pip install treleadb
```

# Database Class

### __Database__ class provides methods for creating, connecting to a database and bonus schema rule validation and migration

__Constructor Parameters:__
- __dbName__ Database Name
- __dbPath__ Optional Datbase Path
- __secretKey__ Optional paraphrase for hashing and encryption

__classMethods__:
- __setupCollection(__ self, collName: str __)__
- __modelSchema(__ self, Schema: dict __)__
- __migrate(__ self, data: list = None __)__
- __dropDatabase(__ self __)__
- __dropCollection(__ self, collName: str __)__

### Creating a mini database with one collection.
```python
# migartion.py
from treleadb import Database
import json

# initialize object
mydb = Database(dbName="MyFirstDb")

# specify schema collection then setup full collection
todoSchema = { 'title': str, 'description': str }
todos = mydb.setupCollection("Todos").modelSchema(todoSchema).migrate()

# preview output
print(json.dumps(todos, indent=4))
```
```bash
# Run this command
python3 ./migration.py
```
```json
{
    "_Database": "MyFirstDb",
    "_DatabasePath": "/some_path/treleadb/MyFirstDb",
    "_Collection": "Todos",
    "_CollectionPath": "/some_path/treleadb/MyFirstDb/Todos.json",
    "_Encryption": false,
    "_Migration_created_at": "Sat Feb 17 19:05:29 2024",
    "_Migration_updated_at": "Sat Feb 17 19:05:29 2024",
    "Schema": {
        "title": "str",
        "description": "str",
        "created_at": "str",
        "updated_at": "str",
        "__id": "str"
    },
    "Data": []
}
```

### Lets develop more complex database (like a mini reddit clone) with encryption layer and data seeds on it.

```python
# migartion.py
from treleadb import Database
import datetime
from faker import Faker     # pip install Faker for seeding fake data
import json


# Optional Parameter For Encryption: secretKey: str = None
mydb = Database(dbName="RedditClone", secretKey="password_for_db")
fake = Faker()


# Generate 3 collections: Users, Posts, Comments

# ----------------------
# Setup Users Collection

userSchema: dict = { 
    'user_name': str,
    'user_email': str,
    'user_dateOfBirth': datetime.date,
    'user_password': str,
    'user_thumbnail': str,
    'user_isVerified': bool
}

userSeeds: list = list()
for _ in range(20):
    user: dict = dict()
    user['user_name'] = str(fake.first_name())
    user['user_email'] = str(fake.email())
    user['user_dateOfBirth'] = datetime.date(int(fake.year()), int(fake.month()), int(fake.random.randint(1, 30)))
    user['user_password'] = str(''.join(fake.words(nb = 2)))
    user['user_thumbnail'] = str(fake.uri())
    user['user_isVerified'] = bool(fake.boolean())
    userSeeds.append(user)

users = mydb.setupCollection('Users').modelSchema(userSchema).migrate(userSeeds)

# preview Users output
print(json.dumps(users, indent=4))


# ----------------------
# Setup Posts Collection

postSchema: dict = {
    'user_name': str,
    'post_title': str,
    'post_description': str,
    'post_thumbnail': str,
    'post_likes': list,
    'post_comments': int
}

postSeeds: list = list()
for _ in range(30):
    post: dict = dict()
    post['user_name'] = str(fake.first_name())
    post['post_title'] = str(" ".join(fake.words(nb = 2)))
    post['post_description'] = str(fake.text(max_nb_chars=1000))
    post['post_thumbnail'] = str(fake.uri())
    post['post_likes'] = list(fake.first_name() for _ in range(100))
    post['post_comments'] = int(fake.random.randint(1, 50))
    postSeeds.append(post)

posts = mydb.setupCollection('Posts').modelSchema(postSchema).migrate(postSeeds)

# preview Posts output
print(json.dumps(posts, indent=4))


# -------------------------
# Setup Comments Collection

commentSchema = {
    'post_id': str,
    'user_name': str,
    'comment_text': str
}

commentSeeds: list = list()
for _ in range(40):
    comment: dict = dict()
    comment['post_id'] = str(fake.uuid4())
    comment['user_name'] = str(fake.first_name())
    comment['comment_text'] = str(fake.text(max_nb_chars=100))
    commentSeeds.append(comment)

comments = mydb.setupCollection('Comments').modelSchema(commentSchema).migrate(commentSeeds)

# preview Comments output
print(json.dumps(comments, indent=4))
```
```bash
# Run this command
python3 ./migration.py
```
```json
{
    "_Database": "RedditClone",
    "_DatabasePath": "/some_path/treleadb/RedditClone",
    "_Collection": "Users",
    "_CollectionPath": "/some_path/treleadb/RedditClone/Users.json",
    "_Encryption": true,
    "_Migration_created_at": "Sat Feb 17 19:39:51 2024",
    "_Migration_updated_at": "Sat Feb 17 19:39:51 2024",
    "Schema": {
        "user_name": "str",
        "user_email": "str",
        "user_dateOfBirth": "date",
        "user_password": "str",
        "user_thumbnail": "str",
        "user_isVerified": "bool",
        "created_at": "str",
        "updated_at": "str",
        "__id": "str"
    },
    "Data": [
        {
            "user_name": "Hannah",
            "user_email": "richardhill@example.org",
            "user_dateOfBirth": "2012-05-05",
            "user_password": "Americanstrategy",
            "user_thumbnail": "http://www.wallace-martin.org/tagfaq.php",
            "user_isVerified": true,
            "created_at": "Sat Feb 17 19:39:51 2024",
            "updated_at": "Sat Feb 17 19:39:51 2024",
            "__id": "14ae9626-02b6-4da5-8a60-1623162ee855"
        },
        {
            "user_name": "Jack",
            "user_email": "jonespatricia@example.org",
            "user_dateOfBirth": "2005-09-05",
            "user_password": "girlshake",
            "user_thumbnail": "http://wade.org/tagmain.html",
            "user_isVerified": false,
            "created_at": "Sat Feb 17 19:39:51 2024",
            "updated_at": "Sat Feb 17 19:39:51 2024",
            "__id": "9d5ed87d-2bc7-4975-bd3a-ab64884df6bd"
        },
        ...
    ]
}
{
    "_Database": "RedditClone",
    "_DatabasePath": "/some_path/treleadb/RedditClone",
    "_Collection": "Posts",
    "_CollectionPath": "/some_path/treleadb/RedditClone/Posts.json",
    "_Encryption": true,
    "_Migration_created_at": "Sat Feb 17 19:39:51 2024",
    "_Migration_updated_at": "Sat Feb 17 19:39:51 2024",
    "Schema": {
        "user_name": "str",
        "post_title": "str",
        "post_description": "str",
        "post_thumbnail": "str",
        "post_likes": "list",
        "post_comments": "int",
        "created_at": "str",
        "updated_at": "str",
        "__id": "str"
    },
    "Data": [
        {
            "user_name": "Thomas",
            "post_title": "final available",
            "post_description": "Six sing free natural hit itself despite big.\nHope talk through tree forward admit none modern. Both Republican participant particularly.\nCourse class business condition. Art forget media firm role. Agent popular head word.\nEverything at gas better raise. Opportunity speak place moment else sure national.\nBed produce author benefit gas nearly begin animal. Itself east knowledge.\nFeeling sing Mr big...",
            "post_thumbnail": "http://miller-wagner.com/categories/categoryprivacy.jsp",
            "post_likes": ["Karen", "Adam", "Laura", "Christopher", "Amber", ... ],
            "post_comments": 24,
            "created_at": "Sat Feb 17 19:39:51 2024",
            "updated_at": "Sat Feb 17 19:39:51 2024",
            "__id": "0614937c-7446-40e2-9f3b-6083d84e2f01"
        },
        {
            "user_name": "Erin",
            "post_title": "impact certainly",
            "post_description": "Realize notice central drug everything whether newspaper. Day democratic message material amount music politics.\nDevelopment subject mind treatment local market. Own general win act network worker student.\nRecognize movie that interesting. Staff page modern director expect support music.\nAgency field remember modern able call next. Past television real area forget call necessary...",
            "post_thumbnail": "https://levy-nelson.com/tag/main/blogregister.jsp",
            "post_likes": [ "Timothy", "Christopher", "Reginald", "Isaiah", "Allen", ... ],
            "post_comments": 2,
            "created_at": "Sat Feb 17 19:39:51 2024",
            "updated_at": "Sat Feb 17 19:39:51 2024",
            "__id": "b65e288b-7268-40b4-8449-0245ac9aab8d"
        }
        ...
    ]
}
{
    "_Database": "RedditClone",
    "_DatabasePath": "/some_path/treleadb/RedditClone",
    "_Collection": "Comments",
    "_CollectionPath": "/some_path/treleadb/RedditClone/Comments.json",
    "_Encryption": true,
    "_Migration_created_at": "Sat Feb 17 19:39:51 2024",
    "_Migration_updated_at": "Sat Feb 17 19:39:51 2024",
    "Schema": {
        "post_id": "str",
        "user_name": "str",
        "comment_text": "str",
        "created_at": "str",
        "updated_at": "str",
        "__id": "str"
    },
    "Data": [
        {
            "post_id": "014911d0-11f1-4beb-af3c-8e8b5c5d1265",
            "user_name": "Matthew",
            "comment_text": "Phone technology hope concern hit he special doctor. Institution international social glass such.",
            "created_at": "Sat Feb 17 19:39:51 2024",
            "updated_at": "Sat Feb 17 19:39:51 2024",
            "__id": "7e5afdbd-292a-418e-a388-336c2f551a5c"
        },
        {
            "post_id": "d0752977-49a4-4ece-9ef0-13a98da42150",
            "user_name": "Monica",
            "comment_text": "Method send process commercial arrive. Exist add south.",
            "created_at": "Sat Feb 17 19:39:51 2024",
            "updated_at": "Sat Feb 17 19:39:51 2024",
            "__id": "1c5d0851-a306-43ea-a4aa-7caf513f5007"
        },
        ...
    ]
}
```

### Analyzing Database Structure

```bash
# Run this command

$: tree <_DatabasePath Value>

/some_path/treleadb/RedditClone
├── Comments.json
├── Posts.json
└── Users.json

1 directory, 3 files
```

### Preview content from a collection file

```bash
# Run this command

$: cd <_DatabasePath Value>

$: cat Users.json

gAAAAABl0O9nepF6-e0nEKF_bkg9p_WUzxDLVhAsN_gFCjiifQMWJCQLZjs7K7xk-SMf_nzgIsnWnVx7Bl23_Ou_uG9ddjO7DBDJSl-nmZ-00DkLF99saAtI-zh2Yt_Q5mKClksdDQdi1umoZWkOlB54M8Lx_7pNak1hv1fCZw8iJu2k4DN0xgSlXKbhn1AAo6mh_cVYnfQga6sEf_I7lKpYZcAwQM3-cILajm97wKCindYVc36MkCCU1tqFXntED4w7eAT7lkrLFxgREZGFx30DOamLk4SqOupE3_TQ1YDSp69xzZPNfmq_9D7zBum4tkyDD6Qvb-n78FkIcZon5T-TX9wd9UmlGEohD_vT2tPELabcBPdul8rOt0KORi_52LAWedF1ORVAXtRCa_AWqE607pkra3b_2cv0xIA-QqixMvy071HVyH2xOAL-m5Oh4Rk0mrjx2WhT51vjlz1DGdb93wtRe5wwuWkICAtQmaAAkdP4NOTWzA1GaoyRU6Iepk-tx_Uaj8vrwdT5BlN79ipQpQqzJOx1prLBOpqtDIduOcJV6vQ8QL7sHEO0Ti8kDX0a-CScP2YhOyA4420JruJBAZYx5J_OAR6gOrH9eys0CN-16nHMUIn1GYehe2yHABScFPuoN6uyr2dp2r58LP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ciOJkF0iw9z8dRp9Hy1d0D_RUAdRGaSHTy74DydDWlmJK34OWad1b2-imOpzghujfqAbhXudaV50W1o4gBE4e5fJJVRS_ViPDYTAvfmCS9vUMyjCHNznWyW87T-TW1byn_h-jbUVFLqQfwv6m-V0Fw_6-UYo9DP4Dc7kMgzV0kzpugti79yAqLti6ZoeU0dQwlGD39r2_psFimmnl-wZF9KkZ8TcL3HJqsnfFXKQw1Sane303fdWQt9gJ_z-7wLlL058LANb1rqEGpdaizbih2BotWisOe9zC-c_TLe7VFzvTZMjVQuZWIApTaVEeBAjCttmyxEpmZwjGpC-6xmTD
```

### Drop Collections using .dropCollection() classMethod

```python
# drop.py
from treleadb import Database

# connect to an existent db
mydb = Database(dbName="RedditClone", secretKey="password_for_db")

# drop an existent collection
try:
    mydb.dropCollection("Comments")
    print("Collection Successfully Deleted")
except Exception as e:
    print(e)
```
```bash
# Lets run command drop.py

python3 ./drop.py

# Output Should Be:
# Collection Successfully Deleted
```
```bash
# Lets run another time command drop.py

python3 ./drop.py

# Output Should Be:
# Invalid Collection 'Comments' In Database 'RedditClone'
```

### Drop with wrong secretKey

```python
# modify secretKey parameter and dropCollection parameter in drop.py

# ...

mydb = Database(dbName="RedditClone", secretKey="wrong_pass")

# ...

mydb.dropCollection("Posts")

# ...
```
```bash
# Lets run another time command drop.py

python3 ./drop.py

# Output Should Be:
# Invalid Encrypted secretKey 'U7z0iZuP4pa4OdhUO3ZlB...' For Database 'RedditClone'
```
In conclusion the secretKey can be used like a security layer for your database and collections.
Best practice is to save the content of secretKey into a __.env__ file.

### Drop Database using .dropDatabase() classMethod

```python
# drop.py
from treleadb import Database

# connect to an existent db
mydb = Database(dbName="RedditClone", secretKey="password_for_db")

# drop an existent Database
try:
    mydb.dropDatabase()
    print("Database Successfully Deleted")
except Exception as e:
    print(e)
```
```bash
# Lets run command drop.py

python3 ./drop.py

# Output Should Be:
# Database Successfully Deleted
```
### Lets see if _DatabasePath still exists
```bash
# Run this command

$: tree <_DatabasePath Value>

<_DatabasePath Value>  [error opening dir]

0 directories, 0 files
``` 


# TreleadbClient Class

### TreleadbClient class provides methods for connecting to a database and execute CRUD operations concerning more on collections.

__Constructor Parameters:__
- __dbName__ Database Name
- __dbPath__ Optional Datbase Path
- __secretKey__ Optional paraphrase for hashing and encryption

__classMethods__:
- __getCollections(__ self __)__
- __getCollection(__ self, collName: str, Schema: bool = False __)__
- __select(__ self, collName: str __)__
- __insert(__ self, keys: dict __)__
- __get(__ self, **keys: bool __)__
- __update(__ self, keys: dict __)__
- __delete(__ self, keys: dict, Full: bool = False __)__
- __where(__ self, *keys: dict __)__

### Creating a databse with empty collections, to let TreleadbClient execute CRUD operations on it.

```python
# migration.py
from treleadb import Database
import json

db = Database(dbName='TodoApp', secretKey='todos_key_db')

# setup collections
users = db.setupCollection('Users').modelSchema({
    'user_name': str,
    'user_password': str
}).migrate()
print(json.dumps(users, indent=4))

todos = db.setupCollection('Todos').modelSchema({
    'todo_title': str,
    'todo_description': str,
    'user_id': str
}).migrate()
print(json.dumps(todos, indent=4))
```
```bash
# Run command
python3 ./migration.py
```
### Now that we have set database and collection, we will use TreleadbClient for CRUD.

Useful methods __getCollections()__ and __getCollection()__ for viewing collections from a database.
```python
# client.py
from treleadb import TreleadbClient

db = TreleadbClient(dbName='TodoApp', secretKey='todos_key_db')

# get all collections from database
collections = db.getCollections()
print(collections)

# get data from a specific collection in database
print(db.getCollection(collections[0])) 

# get data and infos from a specific collection in database
print(db.getCollection(collections[0], Schema=True))
```

### Lets insert some users in Users collection.

```python
# client.py
from treleadb import TreleadbClient
import json

db = TreleadbClient(dbName='TodoApp', secretKey='todos_key_db')

# !!! .select() method is like SELECT query in SQL so you must use it everywhere !!!

# inserting method chaining
user_1 = db.select('Users').insert({ 
    'user_name': 'Ann', 
    'user_password': 'ann_password1234' 
})
user_2 = db.select('Users').insert({ 
    'user_name': 'Tom', 
    'user_password': 'secret_pass_for_tom' 
})
user_3 = db.select('Users').insert({ 
    'user_name': 'Maria', 
    'user_password': 'poiuytrewq1234' 
})
user_4 = db.select('Users').insert({ 
    'user_name': 'Timmy', 
    'user_password': 'QPALZ<woskxm1234' 
})

# output
print(json.dumps(user_1, indent=4))
print(json.dumps(user_2, indent=4))
print(json.dumps(user_3, indent=4))
print(json.dumps(user_4, indent=4))
```

### How to use .get() and .where() methods for reading.

```python
# client.py
from treleadb import TreleadbClient
import json

db = TreleadbClient(dbName='TodoApp', secretKey='todos_key_db')


# Extracting all objects from Users coll
# SELECT * FROM Users;
users = db.select('Users').get() # -> this will return an arr
for _ in users.data:
    print(json.dumps(_, indent=4))


# Extracting all objects with only spefied keys from Users coll
# SELECT coll_1, coll_2, ... FROM Users;
# In this case we are selecting only user_name and __id keys
users = db.select('Users').get(user_name=True, __id=True)
for _ in users.data:
    print(json.dumps(_, indent=4))


# Lets extract only the __id from users that have user_name: Tom and Maria
# SELECT __id FROM Users WHERE user_name='' OR user_name='';
users = db.select('Users').get(__id=True).where(
    { 'user_name': 'Tom' }, 
    { 'user_name': 'Maria'}

    ''' .where() method has arbitrary argumnets that allows us to pass infinite objects parameters
    
    implimentation between OR and AND:

    OR -> { 'user_name': 'Tom' }, { 'user_name': 'Ann' }, { '__id': 'b7971bc0-8e1d-4cd0-bf7d-2606cc610b79' }, ...
    Find multiple objects that contains specified keys and values.

    AND -> { 'user_name': 'Tom', '__id': '089c3e58-c26e-4cc9-b280-2943e52dc55e', ... }
    Finds an object with specified keys and values

    '''
)
for _ in users.data:
    print(json.dumps(_, indent=4))


# Lets find and object with user_name=Tom and __id=1234_poiuytrewq
# SELECT * FROM Users WHERE user_name='Tom' AND __id='1234_poiuytrewq'; 
users = db.select('Users').get().where({ 'user_name': 'Tom', '__id': '1234_poiuytrewq' })
# This should be an inexisted object -> empty arr
for _ in users.data:
    print(json.dumps(_, indent=4))
```
### Update method .update() with .where() method.

```python
# client.py
from treleadb import TreleadbClient
import json

db = TreleadbClient(dbName='TodoApp', secretKey='todos_key_db')

# update user_name=Anton that has user_name=Tom
# UPDATE Users SET user_name='Anton' WHERE user_name='Tom';
db.select('Users').update({ 'user_name': 'Anton' }).where({ 'user_name': 'Tom' })

# Lets see if update query was performed successfully
user = db.select('Users').get().where({ 'user_name': 'Anton' })
print(user.data)
``` 

### Delete method .delete()
```python
# client.py
from treleadb import TreleadbClient

db = TreleadbClient(dbName='TodoApp', secretKey='todos_key_db')

# delte objects that has user_name='Anton'
# DELETE FROM Users WHERE user_name='Anton';
# .delete() method works like .where() OR and AND are available 
res = db.select('Users').delete({ 'user_name': 'Anton' }) # -> return an arr
print(res.data)


# delte more objects
# DELETE FROM Users WHERE user_name='Ann' OR user_name='Maria' ...;
objs = db.select('Users').delete({ 'user_name': 'Ann' }, { 'user_name': 'Maria' })
for _ in objs.data:
    print(json.dumps(_, indent=4))


# delete all objects from collection
# DELETE FROM Users;
# ouput will preview entire deleted objects
del_all = db.select('Users').delete(Full=True)
for _ in del_all.data:
    print(json.dumps(_, indent=4))

``` 

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/trelea/TreleaDB",
    "name": "treleadb",
    "maintainer": "",
    "docs_url": null,
    "requires_python": "",
    "maintainer_email": "",
    "keywords": "python,python3,database,nodql,mongodb,treleadb,object,json",
    "author": "Trelea Marius",
    "author_email": "treleamarius76@gmail.com",
    "download_url": "",
    "platform": null,
    "description": "# TreleaDB\n\nTreleaDB is a database, its provides object-oriented database for Python that provides a high-degree of transparency.\n\nIts a very simple Database build for developing mini projects. It provides encryption, hashing and other specifications.\n\n## Downloads\n\nTreleaDB is distributed through the Python Package Index.\n\nYou can install the TreleaDB using pip command:\n\n```\npip install treleadb\n```\n\n# Database Class\n\n### __Database__ class provides methods for creating, connecting to a database and bonus schema rule validation and migration\n\n__Constructor Parameters:__\n- __dbName__ Database Name\n- __dbPath__ Optional Datbase Path\n- __secretKey__ Optional paraphrase for hashing and encryption\n\n__classMethods__:\n- __setupCollection(__ self, collName: str __)__\n- __modelSchema(__ self, Schema: dict __)__\n- __migrate(__ self, data: list = None __)__\n- __dropDatabase(__ self __)__\n- __dropCollection(__ self, collName: str __)__\n\n### Creating a mini database with one collection.\n```python\n# migartion.py\nfrom treleadb import Database\nimport json\n\n# initialize object\nmydb = Database(dbName=\"MyFirstDb\")\n\n# specify schema collection then setup full collection\ntodoSchema = { 'title': str, 'description': str }\ntodos = mydb.setupCollection(\"Todos\").modelSchema(todoSchema).migrate()\n\n# preview output\nprint(json.dumps(todos, indent=4))\n```\n```bash\n# Run this command\npython3 ./migration.py\n```\n```json\n{\n    \"_Database\": \"MyFirstDb\",\n    \"_DatabasePath\": \"/some_path/treleadb/MyFirstDb\",\n    \"_Collection\": \"Todos\",\n    \"_CollectionPath\": \"/some_path/treleadb/MyFirstDb/Todos.json\",\n    \"_Encryption\": false,\n    \"_Migration_created_at\": \"Sat Feb 17 19:05:29 2024\",\n    \"_Migration_updated_at\": \"Sat Feb 17 19:05:29 2024\",\n    \"Schema\": {\n        \"title\": \"str\",\n        \"description\": \"str\",\n        \"created_at\": \"str\",\n        \"updated_at\": \"str\",\n        \"__id\": \"str\"\n    },\n    \"Data\": []\n}\n```\n\n### Lets develop more complex database (like a mini reddit clone) with encryption layer and data seeds on it.\n\n```python\n# migartion.py\nfrom treleadb import Database\nimport datetime\nfrom faker import Faker     # pip install Faker for seeding fake data\nimport json\n\n\n# Optional Parameter For Encryption: secretKey: str = None\nmydb = Database(dbName=\"RedditClone\", secretKey=\"password_for_db\")\nfake = Faker()\n\n\n# Generate 3 collections: Users, Posts, Comments\n\n# ----------------------\n# Setup Users Collection\n\nuserSchema: dict = { \n    'user_name': str,\n    'user_email': str,\n    'user_dateOfBirth': datetime.date,\n    'user_password': str,\n    'user_thumbnail': str,\n    'user_isVerified': bool\n}\n\nuserSeeds: list = list()\nfor _ in range(20):\n    user: dict = dict()\n    user['user_name'] = str(fake.first_name())\n    user['user_email'] = str(fake.email())\n    user['user_dateOfBirth'] = datetime.date(int(fake.year()), int(fake.month()), int(fake.random.randint(1, 30)))\n    user['user_password'] = str(''.join(fake.words(nb = 2)))\n    user['user_thumbnail'] = str(fake.uri())\n    user['user_isVerified'] = bool(fake.boolean())\n    userSeeds.append(user)\n\nusers = mydb.setupCollection('Users').modelSchema(userSchema).migrate(userSeeds)\n\n# preview Users output\nprint(json.dumps(users, indent=4))\n\n\n# ----------------------\n# Setup Posts Collection\n\npostSchema: dict = {\n    'user_name': str,\n    'post_title': str,\n    'post_description': str,\n    'post_thumbnail': str,\n    'post_likes': list,\n    'post_comments': int\n}\n\npostSeeds: list = list()\nfor _ in range(30):\n    post: dict = dict()\n    post['user_name'] = str(fake.first_name())\n    post['post_title'] = str(\" \".join(fake.words(nb = 2)))\n    post['post_description'] = str(fake.text(max_nb_chars=1000))\n    post['post_thumbnail'] = str(fake.uri())\n    post['post_likes'] = list(fake.first_name() for _ in range(100))\n    post['post_comments'] = int(fake.random.randint(1, 50))\n    postSeeds.append(post)\n\nposts = mydb.setupCollection('Posts').modelSchema(postSchema).migrate(postSeeds)\n\n# preview Posts output\nprint(json.dumps(posts, indent=4))\n\n\n# -------------------------\n# Setup Comments Collection\n\ncommentSchema = {\n    'post_id': str,\n    'user_name': str,\n    'comment_text': str\n}\n\ncommentSeeds: list = list()\nfor _ in range(40):\n    comment: dict = dict()\n    comment['post_id'] = str(fake.uuid4())\n    comment['user_name'] = str(fake.first_name())\n    comment['comment_text'] = str(fake.text(max_nb_chars=100))\n    commentSeeds.append(comment)\n\ncomments = mydb.setupCollection('Comments').modelSchema(commentSchema).migrate(commentSeeds)\n\n# preview Comments output\nprint(json.dumps(comments, indent=4))\n```\n```bash\n# Run this command\npython3 ./migration.py\n```\n```json\n{\n    \"_Database\": \"RedditClone\",\n    \"_DatabasePath\": \"/some_path/treleadb/RedditClone\",\n    \"_Collection\": \"Users\",\n    \"_CollectionPath\": \"/some_path/treleadb/RedditClone/Users.json\",\n    \"_Encryption\": true,\n    \"_Migration_created_at\": \"Sat Feb 17 19:39:51 2024\",\n    \"_Migration_updated_at\": \"Sat Feb 17 19:39:51 2024\",\n    \"Schema\": {\n        \"user_name\": \"str\",\n        \"user_email\": \"str\",\n        \"user_dateOfBirth\": \"date\",\n        \"user_password\": \"str\",\n        \"user_thumbnail\": \"str\",\n        \"user_isVerified\": \"bool\",\n        \"created_at\": \"str\",\n        \"updated_at\": \"str\",\n        \"__id\": \"str\"\n    },\n    \"Data\": [\n        {\n            \"user_name\": \"Hannah\",\n            \"user_email\": \"richardhill@example.org\",\n            \"user_dateOfBirth\": \"2012-05-05\",\n            \"user_password\": \"Americanstrategy\",\n            \"user_thumbnail\": \"http://www.wallace-martin.org/tagfaq.php\",\n            \"user_isVerified\": true,\n            \"created_at\": \"Sat Feb 17 19:39:51 2024\",\n            \"updated_at\": \"Sat Feb 17 19:39:51 2024\",\n            \"__id\": \"14ae9626-02b6-4da5-8a60-1623162ee855\"\n        },\n        {\n            \"user_name\": \"Jack\",\n            \"user_email\": \"jonespatricia@example.org\",\n            \"user_dateOfBirth\": \"2005-09-05\",\n            \"user_password\": \"girlshake\",\n            \"user_thumbnail\": \"http://wade.org/tagmain.html\",\n            \"user_isVerified\": false,\n            \"created_at\": \"Sat Feb 17 19:39:51 2024\",\n            \"updated_at\": \"Sat Feb 17 19:39:51 2024\",\n            \"__id\": \"9d5ed87d-2bc7-4975-bd3a-ab64884df6bd\"\n        },\n        ...\n    ]\n}\n{\n    \"_Database\": \"RedditClone\",\n    \"_DatabasePath\": \"/some_path/treleadb/RedditClone\",\n    \"_Collection\": \"Posts\",\n    \"_CollectionPath\": \"/some_path/treleadb/RedditClone/Posts.json\",\n    \"_Encryption\": true,\n    \"_Migration_created_at\": \"Sat Feb 17 19:39:51 2024\",\n    \"_Migration_updated_at\": \"Sat Feb 17 19:39:51 2024\",\n    \"Schema\": {\n        \"user_name\": \"str\",\n        \"post_title\": \"str\",\n        \"post_description\": \"str\",\n        \"post_thumbnail\": \"str\",\n        \"post_likes\": \"list\",\n        \"post_comments\": \"int\",\n        \"created_at\": \"str\",\n        \"updated_at\": \"str\",\n        \"__id\": \"str\"\n    },\n    \"Data\": [\n        {\n            \"user_name\": \"Thomas\",\n            \"post_title\": \"final available\",\n            \"post_description\": \"Six sing free natural hit itself despite big.\\nHope talk through tree forward admit none modern. Both Republican participant particularly.\\nCourse class business condition. Art forget media firm role. Agent popular head word.\\nEverything at gas better raise. Opportunity speak place moment else sure national.\\nBed produce author benefit gas nearly begin animal. Itself east knowledge.\\nFeeling sing Mr big...\",\n            \"post_thumbnail\": \"http://miller-wagner.com/categories/categoryprivacy.jsp\",\n            \"post_likes\": [\"Karen\", \"Adam\", \"Laura\", \"Christopher\", \"Amber\", ... ],\n            \"post_comments\": 24,\n            \"created_at\": \"Sat Feb 17 19:39:51 2024\",\n            \"updated_at\": \"Sat Feb 17 19:39:51 2024\",\n            \"__id\": \"0614937c-7446-40e2-9f3b-6083d84e2f01\"\n        },\n        {\n            \"user_name\": \"Erin\",\n            \"post_title\": \"impact certainly\",\n            \"post_description\": \"Realize notice central drug everything whether newspaper. Day democratic message material amount music politics.\\nDevelopment subject mind treatment local market. Own general win act network worker student.\\nRecognize movie that interesting. Staff page modern director expect support music.\\nAgency field remember modern able call next. Past television real area forget call necessary...\",\n            \"post_thumbnail\": \"https://levy-nelson.com/tag/main/blogregister.jsp\",\n            \"post_likes\": [ \"Timothy\", \"Christopher\", \"Reginald\", \"Isaiah\", \"Allen\", ... ],\n            \"post_comments\": 2,\n            \"created_at\": \"Sat Feb 17 19:39:51 2024\",\n            \"updated_at\": \"Sat Feb 17 19:39:51 2024\",\n            \"__id\": \"b65e288b-7268-40b4-8449-0245ac9aab8d\"\n        }\n        ...\n    ]\n}\n{\n    \"_Database\": \"RedditClone\",\n    \"_DatabasePath\": \"/some_path/treleadb/RedditClone\",\n    \"_Collection\": \"Comments\",\n    \"_CollectionPath\": \"/some_path/treleadb/RedditClone/Comments.json\",\n    \"_Encryption\": true,\n    \"_Migration_created_at\": \"Sat Feb 17 19:39:51 2024\",\n    \"_Migration_updated_at\": \"Sat Feb 17 19:39:51 2024\",\n    \"Schema\": {\n        \"post_id\": \"str\",\n        \"user_name\": \"str\",\n        \"comment_text\": \"str\",\n        \"created_at\": \"str\",\n        \"updated_at\": \"str\",\n        \"__id\": \"str\"\n    },\n    \"Data\": [\n        {\n            \"post_id\": \"014911d0-11f1-4beb-af3c-8e8b5c5d1265\",\n            \"user_name\": \"Matthew\",\n            \"comment_text\": \"Phone technology hope concern hit he special doctor. Institution international social glass such.\",\n            \"created_at\": \"Sat Feb 17 19:39:51 2024\",\n            \"updated_at\": \"Sat Feb 17 19:39:51 2024\",\n            \"__id\": \"7e5afdbd-292a-418e-a388-336c2f551a5c\"\n        },\n        {\n            \"post_id\": \"d0752977-49a4-4ece-9ef0-13a98da42150\",\n            \"user_name\": \"Monica\",\n            \"comment_text\": \"Method send process commercial arrive. Exist add south.\",\n            \"created_at\": \"Sat Feb 17 19:39:51 2024\",\n            \"updated_at\": \"Sat Feb 17 19:39:51 2024\",\n            \"__id\": \"1c5d0851-a306-43ea-a4aa-7caf513f5007\"\n        },\n        ...\n    ]\n}\n```\n\n### Analyzing Database Structure\n\n```bash\n# Run this command\n\n$: tree <_DatabasePath Value>\n\n/some_path/treleadb/RedditClone\n\u251c\u2500\u2500 Comments.json\n\u251c\u2500\u2500 Posts.json\n\u2514\u2500\u2500 Users.json\n\n1 directory, 3 files\n```\n\n### Preview content from a collection file\n\n```bash\n# Run this command\n\n$: cd <_DatabasePath Value>\n\n$: cat Users.json\n\ngAAAAABl0O9nepF6-e0nEKF_bkg9p_WUzxDLVhAsN_gFCjiifQMWJCQLZjs7K7xk-SMf_nzgIsnWnVx7Bl23_Ou_uG9ddjO7DBDJSl-nmZ-00DkLF99saAtI-zh2Yt_Q5mKClksdDQdi1umoZWkOlB54M8Lx_7pNak1hv1fCZw8iJu2k4DN0xgSlXKbhn1AAo6mh_cVYnfQga6sEf_I7lKpYZcAwQM3-cILajm97wKCindYVc36MkCCU1tqFXntED4w7eAT7lkrLFxgREZGFx30DOamLk4Sq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ztrT7Ng7kZHVnelLODwYQyXCi_7v7BRNefIOzweuhTsiUTyAFE6fh6rBzdT-T1zizz0o23qtBjqbAgSHsstOxF2reMEbXt4pV6bwnXgB4hvCSVYcUobXeOSLp3Xoy5SsyQnYzjVU94pVrVJqiTIh2tCwMto0FB4ibEOqhURFA0exbR6aEMCzQDoB3v5PqnFuugptTT6k0ceq7_jXTvkn69tECH16pA7H5MAr_opgkfxW0pR2P8zBiyBAlLNiJWNnALBH0Cvdhc74sDWCnGaCKLNQWEnQDPiu-gCrL1w9y2mlw0QicsiTiFdnUdWc9WtrJxcCUdDfiS3-45QRDObXVU5foHfUAb_5a-xv2PP_UsUY7P-I1ciOJkF0iw9z8dRp9Hy1d0D_RUAdRGaSHTy74DydDWlmJK34OWad1b2-imOpzghujfqAbhXudaV50W1o4gBE4e5fJJVRS_ViPDYTAvfmCS9vUMyjCHNznWyW87T-TW1byn_h-jbUVFLqQfwv6m-V0Fw_6-UYo9DP4Dc7kMgzV0kzpugti79yAqLti6ZoeU0dQwlGD39r2_psFimmnl-wZF9KkZ8TcL3HJqsnfFXKQw1Sane303fdWQt9gJ_z-7wLlL058LANb1rqEGpdaizbih2BotWisOe9zC-c_TLe7VFzvTZMjVQuZWIApTaVEeBAjCttmyxEpmZwjGpC-6xmTD\n```\n\n### Drop Collections using .dropCollection() classMethod\n\n```python\n# drop.py\nfrom treleadb import Database\n\n# connect to an existent db\nmydb = Database(dbName=\"RedditClone\", secretKey=\"password_for_db\")\n\n# drop an existent collection\ntry:\n    mydb.dropCollection(\"Comments\")\n    print(\"Collection Successfully Deleted\")\nexcept Exception as e:\n    print(e)\n```\n```bash\n# Lets run command drop.py\n\npython3 ./drop.py\n\n# Output Should Be:\n# Collection Successfully Deleted\n```\n```bash\n# Lets run another time command drop.py\n\npython3 ./drop.py\n\n# Output Should Be:\n# Invalid Collection 'Comments' In Database 'RedditClone'\n```\n\n### Drop with wrong secretKey\n\n```python\n# modify secretKey parameter and dropCollection parameter in drop.py\n\n# ...\n\nmydb = Database(dbName=\"RedditClone\", secretKey=\"wrong_pass\")\n\n# ...\n\nmydb.dropCollection(\"Posts\")\n\n# ...\n```\n```bash\n# Lets run another time command drop.py\n\npython3 ./drop.py\n\n# Output Should Be:\n# Invalid Encrypted secretKey 'U7z0iZuP4pa4OdhUO3ZlB...' For Database 'RedditClone'\n```\nIn conclusion the secretKey can be used like a security layer for your database and collections.\nBest practice is to save the content of secretKey into a __.env__ file.\n\n### Drop Database using .dropDatabase() classMethod\n\n```python\n# drop.py\nfrom treleadb import Database\n\n# connect to an existent db\nmydb = Database(dbName=\"RedditClone\", secretKey=\"password_for_db\")\n\n# drop an existent Database\ntry:\n    mydb.dropDatabase()\n    print(\"Database Successfully Deleted\")\nexcept Exception as e:\n    print(e)\n```\n```bash\n# Lets run command drop.py\n\npython3 ./drop.py\n\n# Output Should Be:\n# Database Successfully Deleted\n```\n### Lets see if _DatabasePath still exists\n```bash\n# Run this command\n\n$: tree <_DatabasePath Value>\n\n<_DatabasePath Value>  [error opening dir]\n\n0 directories, 0 files\n``` \n\n\n# TreleadbClient Class\n\n### TreleadbClient class provides methods for connecting to a database and execute CRUD operations concerning more on collections.\n\n__Constructor Parameters:__\n- __dbName__ Database Name\n- __dbPath__ Optional Datbase Path\n- __secretKey__ Optional paraphrase for hashing and encryption\n\n__classMethods__:\n- __getCollections(__ self __)__\n- __getCollection(__ self, collName: str, Schema: bool = False __)__\n- __select(__ self, collName: str __)__\n- __insert(__ self, keys: dict __)__\n- __get(__ self, **keys: bool __)__\n- __update(__ self, keys: dict __)__\n- __delete(__ self, keys: dict, Full: bool = False __)__\n- __where(__ self, *keys: dict __)__\n\n### Creating a databse with empty collections, to let TreleadbClient execute CRUD operations on it.\n\n```python\n# migration.py\nfrom treleadb import Database\nimport json\n\ndb = Database(dbName='TodoApp', secretKey='todos_key_db')\n\n# setup collections\nusers = db.setupCollection('Users').modelSchema({\n    'user_name': str,\n    'user_password': str\n}).migrate()\nprint(json.dumps(users, indent=4))\n\ntodos = db.setupCollection('Todos').modelSchema({\n    'todo_title': str,\n    'todo_description': str,\n    'user_id': str\n}).migrate()\nprint(json.dumps(todos, indent=4))\n```\n```bash\n# Run command\npython3 ./migration.py\n```\n### Now that we have set database and collection, we will use TreleadbClient for CRUD.\n\nUseful methods __getCollections()__ and __getCollection()__ for viewing collections from a database.\n```python\n# client.py\nfrom treleadb import TreleadbClient\n\ndb = TreleadbClient(dbName='TodoApp', secretKey='todos_key_db')\n\n# get all collections from database\ncollections = db.getCollections()\nprint(collections)\n\n# get data from a specific collection in database\nprint(db.getCollection(collections[0])) \n\n# get data and infos from a specific collection in database\nprint(db.getCollection(collections[0], Schema=True))\n```\n\n### Lets insert some users in Users collection.\n\n```python\n# client.py\nfrom treleadb import TreleadbClient\nimport json\n\ndb = TreleadbClient(dbName='TodoApp', secretKey='todos_key_db')\n\n# !!! .select() method is like SELECT query in SQL so you must use it everywhere !!!\n\n# inserting method chaining\nuser_1 = db.select('Users').insert({ \n    'user_name': 'Ann', \n    'user_password': 'ann_password1234' \n})\nuser_2 = db.select('Users').insert({ \n    'user_name': 'Tom', \n    'user_password': 'secret_pass_for_tom' \n})\nuser_3 = db.select('Users').insert({ \n    'user_name': 'Maria', \n    'user_password': 'poiuytrewq1234' \n})\nuser_4 = db.select('Users').insert({ \n    'user_name': 'Timmy', \n    'user_password': 'QPALZ<woskxm1234' \n})\n\n# output\nprint(json.dumps(user_1, indent=4))\nprint(json.dumps(user_2, indent=4))\nprint(json.dumps(user_3, indent=4))\nprint(json.dumps(user_4, indent=4))\n```\n\n### How to use .get() and .where() methods for reading.\n\n```python\n# client.py\nfrom treleadb import TreleadbClient\nimport json\n\ndb = TreleadbClient(dbName='TodoApp', secretKey='todos_key_db')\n\n\n# Extracting all objects from Users coll\n# SELECT * FROM Users;\nusers = db.select('Users').get() # -> this will return an arr\nfor _ in users.data:\n    print(json.dumps(_, indent=4))\n\n\n# Extracting all objects with only spefied keys from Users coll\n# SELECT coll_1, coll_2, ... FROM Users;\n# In this case we are selecting only user_name and __id keys\nusers = db.select('Users').get(user_name=True, __id=True)\nfor _ in users.data:\n    print(json.dumps(_, indent=4))\n\n\n# Lets extract only the __id from users that have user_name: Tom and Maria\n# SELECT __id FROM Users WHERE user_name='' OR user_name='';\nusers = db.select('Users').get(__id=True).where(\n    { 'user_name': 'Tom' }, \n    { 'user_name': 'Maria'}\n\n    ''' .where() method has arbitrary argumnets that allows us to pass infinite objects parameters\n    \n    implimentation between OR and AND:\n\n    OR -> { 'user_name': 'Tom' }, { 'user_name': 'Ann' }, { '__id': 'b7971bc0-8e1d-4cd0-bf7d-2606cc610b79' }, ...\n    Find multiple objects that contains specified keys and values.\n\n    AND -> { 'user_name': 'Tom', '__id': '089c3e58-c26e-4cc9-b280-2943e52dc55e', ... }\n    Finds an object with specified keys and values\n\n    '''\n)\nfor _ in users.data:\n    print(json.dumps(_, indent=4))\n\n\n# Lets find and object with user_name=Tom and __id=1234_poiuytrewq\n# SELECT * FROM Users WHERE user_name='Tom' AND __id='1234_poiuytrewq'; \nusers = db.select('Users').get().where({ 'user_name': 'Tom', '__id': '1234_poiuytrewq' })\n# This should be an inexisted object -> empty arr\nfor _ in users.data:\n    print(json.dumps(_, indent=4))\n```\n### Update method .update() with .where() method.\n\n```python\n# client.py\nfrom treleadb import TreleadbClient\nimport json\n\ndb = TreleadbClient(dbName='TodoApp', secretKey='todos_key_db')\n\n# update user_name=Anton that has user_name=Tom\n# UPDATE Users SET user_name='Anton' WHERE user_name='Tom';\ndb.select('Users').update({ 'user_name': 'Anton' }).where({ 'user_name': 'Tom' })\n\n# Lets see if update query was performed successfully\nuser = db.select('Users').get().where({ 'user_name': 'Anton' })\nprint(user.data)\n``` \n\n### Delete method .delete()\n```python\n# client.py\nfrom treleadb import TreleadbClient\n\ndb = TreleadbClient(dbName='TodoApp', secretKey='todos_key_db')\n\n# delte objects that has user_name='Anton'\n# DELETE FROM Users WHERE user_name='Anton';\n# .delete() method works like .where() OR and AND are available \nres = db.select('Users').delete({ 'user_name': 'Anton' }) # -> return an arr\nprint(res.data)\n\n\n# delte more objects\n# DELETE FROM Users WHERE user_name='Ann' OR user_name='Maria' ...;\nobjs = db.select('Users').delete({ 'user_name': 'Ann' }, { 'user_name': 'Maria' })\nfor _ in objs.data:\n    print(json.dumps(_, indent=4))\n\n\n# delete all objects from collection\n# DELETE FROM Users;\n# ouput will preview entire deleted objects\ndel_all = db.select('Users').delete(Full=True)\nfor _ in del_all.data:\n    print(json.dumps(_, indent=4))\n\n``` \n",
    "bugtrack_url": null,
    "license": "",
    "summary": "TreleaDB object database for Python.",
    "version": "0.1.0",
    "project_urls": {
        "Homepage": "https://github.com/trelea/TreleaDB"
    },
    "split_keywords": [
        "python",
        "python3",
        "database",
        "nodql",
        "mongodb",
        "treleadb",
        "object",
        "json"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "430a31d4c8d135ea4d5c44ec12d63d855554800ca9ad300da36d8c241ab76be9",
                "md5": "08757096247d97e5a1c5e94a527f2f63",
                "sha256": "35339f0bd8bd7c5c3196003a2cd82fbabbd414723a92754feef77be92439873e"
            },
            "downloads": -1,
            "filename": "treleadb-0.1.0-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "08757096247d97e5a1c5e94a527f2f63",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": null,
            "size": 13597,
            "upload_time": "2024-03-10T18:13:16",
            "upload_time_iso_8601": "2024-03-10T18:13:16.030668Z",
            "url": "https://files.pythonhosted.org/packages/43/0a/31d4c8d135ea4d5c44ec12d63d855554800ca9ad300da36d8c241ab76be9/treleadb-0.1.0-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-03-10 18:13:16",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "trelea",
    "github_project": "TreleaDB",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": false,
    "lcname": "treleadb"
}
        
Elapsed time: 0.24198s