lightorm


Namelightorm JSON
Version 0.0.5 PyPI version JSON
download
home_pagehttps://github.com/sabbiramin113008/tinyorm
SummaryYet another, super lightweight MySQL ORM in Python.
upload_time2023-02-05 17:51:36
maintainer
docs_urlNone
authorSabbir Amin
requires_python
licenseMIT
keywords python database orm mysql
VCS
bugtrack_url
requirements PyMySQL python-dotenv
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # LightORM ๐Ÿ’ก๐Ÿงบ๐Ÿ—„๏ธ
It is what the name means. Light yet Do Stuffs (Almost) .
Yet another, `super` `lightweight` `MySQL` `ORM (Object-Relational Mapping)` in Python.  

## ๐Ÿ’พ How to Install
`pip install lightorm`

If you find this project interesting, you can always star it. :D 

## ๐Ÿ“ท A Background for LightORM
The `Dall-E` prompt was 
```commandline
light yagami from death note is writing  code as darth vader yakuza style
```
![background](/img/background.png)

## ๐Ÿ”Œ Connecting and Querying
`LightORM` is designed to reduce the overhead of doing everything and focus on
doing  things in a very light way. First connect with the database, 

```python
import os
from dotenv import load_dotenv

load_dotenv()

from lightorm import Database, Field, _AND

table_name = 'person_table'
db = Database(
    db_name=os.environ.get('DB_NAME'),
    user=os.environ.get('DB_USER'),
    password=os.environ.get('DB_PASSWORD'),
    host=os.environ.get('DB_HOST'),
    port=int(os.environ.get('DB_PORT'))
)
```
Here, the `database` configs are read from `.env` file. And the db is instantiated.


## ๐Ÿ’‰๐Ÿ—„๏ธ Insert a Record
Inserting a record is quiet simple. 
```python
person = {
    'name': 'John Doe',
    'age': 23,
    'address': 'LA',
    'hobby': 'writing'
    }
row_id = db.table(table_name).insert(**person)
```
If successful, the `insert(**person)` will return the `row-id`


## ๐Ÿ—ƒ๏ธ๐Ÿ—„๏ธ Insert Multiple Records
Inserting multiple record is simply feeding the `insert_many` method with the
list of the dictionary of the records to be inserted. 
```python
persons = [
    {
    'name': 'John Doe',
    'age': 23,
    'address': 'LA',
    'hobby': 'writing'
    },
    {
    'name': 'Jane Doe',
    'age': 27,
    'address': 'Kentucky',
    'hobby': 'sleeping'
    }
]
record_inserted = db.table(table_name).insert_many(rows=persons)
```
Upon successful insertion, `insert_many` returns the number of rows inserted. 

## ๐Ÿ—„๏ธ๐Ÿงฉ Getting Data Back `(SELECT)`
For getting all data back, simply
```python
users = db.table(table_name).select().execute()
```
or simply with empty `where` clause [ not suggested, but it will work]
```python
users = db.table(table_name).select().where().execute()
```
Note, there is an extra method `execute`, required for the operation.



## ๐Ÿฅฃ๐Ÿ—„๏ธ Filtering
`lightorm` is tested with several filtering, and it is simply chaining 
filtering clauses. Let's see

### ๐Ÿฅฃ๐Ÿ—„๏ธ Filtering users by `age` and `hobby`
```python
from lightorm import Field,_AND

...
...

users = db.table(table_name).select().where([
    Field('age').eq(33), _AND,
    Field('hobby').eq('programming')
]).execute()

```
### ๐Ÿฅฃ๐Ÿ—„๏ธ Filtering `users` where `age` is less than 33
```python
users = db.table(table_name).select().where([
    Field('age').lt(35)
]).execute()
print('users:', users)
```
### ๐Ÿฅฃ๐Ÿ—„๏ธ Filtering users where `adress` is in `['Dhaka','Khulna']
```python
users = db.table(table_name).select().where([
    Field('address').find_in(['Dhaka', 'Khulna'])
]).execute()
print('users:', users)
```

## ๐Ÿšฅ๐Ÿ—„๏ธ Updating the Records
`update()` method receivers `key-val` dict for fields to be changed. Simply,
```python
v_set = {
    'age': 65,
    'hobby': 'sleeping'
}
user_count = db.table(table_name).update(**v_set).where([
    Field('address').eq('Dhaka')
]).execute()
print('Affected Row:', user_count)
```
`v_set` is the `dict` that is the followed by `SET` value in `sql` query. 
After successful query, it returns rows affected. 

## โœ๏ธ๐Ÿ—„๏ธ Deleting Records
`delete()` works just like the `select()` method. It returns `boolean` `True` if 
is the query is successfully executed. 
```python
delete_flag = self.db.table(self.table_name).delete().where([
    Field('hobby').eq('sleeping')
]).execute()
print('Delete-Flag:', delete_flag)
```

### ๐Ÿ“œ Almost Full Example
```python
import os
import random
import unittest
from dotenv import load_dotenv
from lightorm import Database, Field, _AND

load_dotenv()


class TestTinyOrm(unittest.TestCase):
    table_name = os.environ.get('TABLE_NAME')
    db = Database(
        db_name=os.environ.get('DB_NAME'),
        user=os.environ.get('DB_USER'),
        password=os.environ.get('DB_PASSWORD'),
        host=os.environ.get('DB_HOST'),
        port=int(os.environ.get('DB_PORT'))
    )
    first_name = ['John', 'Jane', 'Jason', 'Guido', 'Martin', 'Rob']
    last_name = ['Doe', 'Dee', 'Mraz', 'Van Russom', 'Fowler', 'Pike']
    addresses = ['Dhaka', 'LA', 'Kentucky', 'Madrid', 'Khulna', 'Sylhet']
    hobbies = ['singing', 'art', ' gaming', 'programming', 'writing', 'sleeping']

    def get_name(self):
        name = '{} {}'.format(random.choice(self.first_name),
                              random.choice(self.last_name))
        return name

    def get_age(self):
        return random.choice([i for i in range(25, 60)])

    def get_address(self):
        return random.choice(self.addresses)

    def get_hobby(self):
        return random.choice(self.hobbies)

    def test_insert(self):
        person = {
            'name': self.get_name(),
            'age': self.get_age(),
            'address': self.get_address(),
            'hobby': self.get_hobby()
        }
        row_id = self.db.table(self.table_name).insert(**person)
        print('row-id:', row_id)

    def test_insert_many(self):
        persons = []
        for i in range(1, 50):
            person = {
                'name': self.get_name(),
                'age': self.get_age(),
                'address': self.get_address(),
                'hobby': self.get_hobby()
            }
            persons.append(person)
        count = self.db.table(self.table_name).insert_many(rows=persons)
        print('recored created:', count)

    def test_get_users(self):
        users = self.db.table(self.table_name).select().where().execute()
        print('users:', users)

    def test_get_user_by_age_and_hobby(self):
        users = self.db.table(self.table_name).select().where([
            Field('age').eq(33), _AND,
            Field('hobby').eq('art')
        ]).execute()
        print('users:', users)

    def test_get_users_where_age_lt_33(self):
        users = self.db.table(self.table_name).select().where([
            Field('age').lt(35)
        ]).execute()
        print('users:', users)

    def test_get_users_where_age_is_in_list_33(self):
        users = self.db.table(self.table_name).select().where([
            Field('age').find_in([33])
        ]).execute()
        print('users:', users)

    def test_get_user_where_address_is_in_dhaka_or_sylhet(self):
        users = self.db.table(self.table_name).select().where([
            Field('address').find_in(['Dhaka', 'Khulna'])
        ]).execute()
        print('users:', users)

    def test_update_users_age_to_50_if_address_is_dhaka(self):
        v_set = {
            'age': 65,
            'hobby': 'sleeping'
        }
        user_count = self.db.table(self.table_name).update(**v_set).where([
            Field('address').eq('Dhaka')
        ]).execute()
        print('Affected Row:', user_count)

    def test_delete_users_where_hobby_eq_art(self):
        delete_flag = self.db.table(self.table_name).delete().where([
            Field('hobby').eq('sleeping')
        ]).execute()
        print('Delete-Flag:', delete_flag)


if __name__ == '__main__':
    unittest.main()

```
## ๐Ÿ”ฎ Upcoming Features
1. Raw `SQL` execution.
2. Adding Pagination and Sorting
3. Adding proper Logging and debugging messages.
4. Adding `Aggregate Function` function in the ORM. 


## ๐Ÿงš Inspiration
`Peewee`, `SQLalchemy` `djangoORM` and all the other ORMs out there, making `Developers` life easier. 



            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/sabbiramin113008/tinyorm",
    "name": "lightorm",
    "maintainer": "",
    "docs_url": null,
    "requires_python": "",
    "maintainer_email": "",
    "keywords": "python,Database,ORM,MySQL",
    "author": "Sabbir Amin",
    "author_email": "sabbiramin.cse11ruet@gmail.com",
    "download_url": "https://files.pythonhosted.org/packages/85/61/efe70f6b74a80e9dbc989e666b13092e269cbdcc5a8c5abb1e0c8b2d0a39/lightorm-0.0.5.tar.gz",
    "platform": null,
    "description": "# LightORM \ud83d\udca1\ud83e\uddfa\ud83d\uddc4\ufe0f\nIt is what the name means. Light yet Do Stuffs (Almost) .\nYet another, `super` `lightweight` `MySQL` `ORM (Object-Relational Mapping)` in Python.  \n\n## \ud83d\udcbe How to Install\n`pip install lightorm`\n\nIf you find this project interesting, you can always star it. :D \n\n## \ud83d\udcf7 A Background for LightORM\nThe `Dall-E` prompt was \n```commandline\nlight yagami from death note is writing  code as darth vader yakuza style\n```\n![background](/img/background.png)\n\n## \ud83d\udd0c Connecting and Querying\n`LightORM` is designed to reduce the overhead of doing everything and focus on\ndoing  things in a very light way. First connect with the database, \n\n```python\nimport os\nfrom dotenv import load_dotenv\n\nload_dotenv()\n\nfrom lightorm import Database, Field, _AND\n\ntable_name = 'person_table'\ndb = Database(\n    db_name=os.environ.get('DB_NAME'),\n    user=os.environ.get('DB_USER'),\n    password=os.environ.get('DB_PASSWORD'),\n    host=os.environ.get('DB_HOST'),\n    port=int(os.environ.get('DB_PORT'))\n)\n```\nHere, the `database` configs are read from `.env` file. And the db is instantiated.\n\n\n## \ud83d\udc89\ud83d\uddc4\ufe0f Insert a Record\nInserting a record is quiet simple. \n```python\nperson = {\n    'name': 'John Doe',\n    'age': 23,\n    'address': 'LA',\n    'hobby': 'writing'\n    }\nrow_id = db.table(table_name).insert(**person)\n```\nIf successful, the `insert(**person)` will return the `row-id`\n\n\n## \ud83d\uddc3\ufe0f\ud83d\uddc4\ufe0f Insert Multiple Records\nInserting multiple record is simply feeding the `insert_many` method with the\nlist of the dictionary of the records to be inserted. \n```python\npersons = [\n    {\n    'name': 'John Doe',\n    'age': 23,\n    'address': 'LA',\n    'hobby': 'writing'\n    },\n    {\n    'name': 'Jane Doe',\n    'age': 27,\n    'address': 'Kentucky',\n    'hobby': 'sleeping'\n    }\n]\nrecord_inserted = db.table(table_name).insert_many(rows=persons)\n```\nUpon successful insertion, `insert_many` returns the number of rows inserted. \n\n## \ud83d\uddc4\ufe0f\ud83e\udde9 Getting Data Back `(SELECT)`\nFor getting all data back, simply\n```python\nusers = db.table(table_name).select().execute()\n```\nor simply with empty `where` clause [ not suggested, but it will work]\n```python\nusers = db.table(table_name).select().where().execute()\n```\nNote, there is an extra method `execute`, required for the operation.\n\n\n\n## \ud83e\udd63\ud83d\uddc4\ufe0f Filtering\n`lightorm` is tested with several filtering, and it is simply chaining \nfiltering clauses. Let's see\n\n### \ud83e\udd63\ud83d\uddc4\ufe0f Filtering users by `age` and `hobby`\n```python\nfrom lightorm import Field,_AND\n\n...\n...\n\nusers = db.table(table_name).select().where([\n    Field('age').eq(33), _AND,\n    Field('hobby').eq('programming')\n]).execute()\n\n```\n### \ud83e\udd63\ud83d\uddc4\ufe0f Filtering `users` where `age` is less than 33\n```python\nusers = db.table(table_name).select().where([\n    Field('age').lt(35)\n]).execute()\nprint('users:', users)\n```\n### \ud83e\udd63\ud83d\uddc4\ufe0f Filtering users where `adress` is in `['Dhaka','Khulna']\n```python\nusers = db.table(table_name).select().where([\n    Field('address').find_in(['Dhaka', 'Khulna'])\n]).execute()\nprint('users:', users)\n```\n\n## \ud83d\udea5\ud83d\uddc4\ufe0f Updating the Records\n`update()` method receivers `key-val` dict for fields to be changed. Simply,\n```python\nv_set = {\n    'age': 65,\n    'hobby': 'sleeping'\n}\nuser_count = db.table(table_name).update(**v_set).where([\n    Field('address').eq('Dhaka')\n]).execute()\nprint('Affected Row:', user_count)\n```\n`v_set` is the `dict` that is the followed by `SET` value in `sql` query. \nAfter successful query, it returns rows affected. \n\n## \u270f\ufe0f\ud83d\uddc4\ufe0f Deleting Records\n`delete()` works just like the `select()` method. It returns `boolean` `True` if \nis the query is successfully executed. \n```python\ndelete_flag = self.db.table(self.table_name).delete().where([\n    Field('hobby').eq('sleeping')\n]).execute()\nprint('Delete-Flag:', delete_flag)\n```\n\n### \ud83d\udcdc Almost Full Example\n```python\nimport os\nimport random\nimport unittest\nfrom dotenv import load_dotenv\nfrom lightorm import Database, Field, _AND\n\nload_dotenv()\n\n\nclass TestTinyOrm(unittest.TestCase):\n    table_name = os.environ.get('TABLE_NAME')\n    db = Database(\n        db_name=os.environ.get('DB_NAME'),\n        user=os.environ.get('DB_USER'),\n        password=os.environ.get('DB_PASSWORD'),\n        host=os.environ.get('DB_HOST'),\n        port=int(os.environ.get('DB_PORT'))\n    )\n    first_name = ['John', 'Jane', 'Jason', 'Guido', 'Martin', 'Rob']\n    last_name = ['Doe', 'Dee', 'Mraz', 'Van Russom', 'Fowler', 'Pike']\n    addresses = ['Dhaka', 'LA', 'Kentucky', 'Madrid', 'Khulna', 'Sylhet']\n    hobbies = ['singing', 'art', ' gaming', 'programming', 'writing', 'sleeping']\n\n    def get_name(self):\n        name = '{} {}'.format(random.choice(self.first_name),\n                              random.choice(self.last_name))\n        return name\n\n    def get_age(self):\n        return random.choice([i for i in range(25, 60)])\n\n    def get_address(self):\n        return random.choice(self.addresses)\n\n    def get_hobby(self):\n        return random.choice(self.hobbies)\n\n    def test_insert(self):\n        person = {\n            'name': self.get_name(),\n            'age': self.get_age(),\n            'address': self.get_address(),\n            'hobby': self.get_hobby()\n        }\n        row_id = self.db.table(self.table_name).insert(**person)\n        print('row-id:', row_id)\n\n    def test_insert_many(self):\n        persons = []\n        for i in range(1, 50):\n            person = {\n                'name': self.get_name(),\n                'age': self.get_age(),\n                'address': self.get_address(),\n                'hobby': self.get_hobby()\n            }\n            persons.append(person)\n        count = self.db.table(self.table_name).insert_many(rows=persons)\n        print('recored created:', count)\n\n    def test_get_users(self):\n        users = self.db.table(self.table_name).select().where().execute()\n        print('users:', users)\n\n    def test_get_user_by_age_and_hobby(self):\n        users = self.db.table(self.table_name).select().where([\n            Field('age').eq(33), _AND,\n            Field('hobby').eq('art')\n        ]).execute()\n        print('users:', users)\n\n    def test_get_users_where_age_lt_33(self):\n        users = self.db.table(self.table_name).select().where([\n            Field('age').lt(35)\n        ]).execute()\n        print('users:', users)\n\n    def test_get_users_where_age_is_in_list_33(self):\n        users = self.db.table(self.table_name).select().where([\n            Field('age').find_in([33])\n        ]).execute()\n        print('users:', users)\n\n    def test_get_user_where_address_is_in_dhaka_or_sylhet(self):\n        users = self.db.table(self.table_name).select().where([\n            Field('address').find_in(['Dhaka', 'Khulna'])\n        ]).execute()\n        print('users:', users)\n\n    def test_update_users_age_to_50_if_address_is_dhaka(self):\n        v_set = {\n            'age': 65,\n            'hobby': 'sleeping'\n        }\n        user_count = self.db.table(self.table_name).update(**v_set).where([\n            Field('address').eq('Dhaka')\n        ]).execute()\n        print('Affected Row:', user_count)\n\n    def test_delete_users_where_hobby_eq_art(self):\n        delete_flag = self.db.table(self.table_name).delete().where([\n            Field('hobby').eq('sleeping')\n        ]).execute()\n        print('Delete-Flag:', delete_flag)\n\n\nif __name__ == '__main__':\n    unittest.main()\n\n```\n## \ud83d\udd2e Upcoming Features\n1. Raw `SQL` execution.\n2. Adding Pagination and Sorting\n3. Adding proper Logging and debugging messages.\n4. Adding `Aggregate Function` function in the ORM. \n\n\n## \ud83e\uddda Inspiration\n`Peewee`, `SQLalchemy` `djangoORM` and all the other ORMs out there, making `Developers` life easier. \n\n\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "Yet another, super lightweight MySQL ORM in Python.",
    "version": "0.0.5",
    "split_keywords": [
        "python",
        "database",
        "orm",
        "mysql"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "8b2871d6330a1c4a38fe2681925ee7c015dd85092617b7029305ef960149a38f",
                "md5": "88d25cafca3443c5a5f60b9ae1f7f0c0",
                "sha256": "1577a3eafdf92b7c391f7ff781cec1a4233b471a8c40555b09b2e5b1c72f7b04"
            },
            "downloads": -1,
            "filename": "lightorm-0.0.5-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "88d25cafca3443c5a5f60b9ae1f7f0c0",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": null,
            "size": 5687,
            "upload_time": "2023-02-05T17:51:33",
            "upload_time_iso_8601": "2023-02-05T17:51:33.900892Z",
            "url": "https://files.pythonhosted.org/packages/8b/28/71d6330a1c4a38fe2681925ee7c015dd85092617b7029305ef960149a38f/lightorm-0.0.5-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "8561efe70f6b74a80e9dbc989e666b13092e269cbdcc5a8c5abb1e0c8b2d0a39",
                "md5": "5a2241c1a23220a5e0247a6a7973dfe5",
                "sha256": "a81139e1037d8e0d696881854b6434cbc82e73dbf61e5bf2dbbf654d83ab844e"
            },
            "downloads": -1,
            "filename": "lightorm-0.0.5.tar.gz",
            "has_sig": false,
            "md5_digest": "5a2241c1a23220a5e0247a6a7973dfe5",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": null,
            "size": 7206,
            "upload_time": "2023-02-05T17:51:36",
            "upload_time_iso_8601": "2023-02-05T17:51:36.387464Z",
            "url": "https://files.pythonhosted.org/packages/85/61/efe70f6b74a80e9dbc989e666b13092e269cbdcc5a8c5abb1e0c8b2d0a39/lightorm-0.0.5.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2023-02-05 17:51:36",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "github_user": "sabbiramin113008",
    "github_project": "tinyorm",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": false,
    "requirements": [
        {
            "name": "PyMySQL",
            "specs": [
                [
                    "==",
                    "1.0.2"
                ]
            ]
        },
        {
            "name": "python-dotenv",
            "specs": [
                [
                    "==",
                    "0.20.0"
                ]
            ]
        }
    ],
    "lcname": "lightorm"
}
        
Elapsed time: 0.03873s