Skip to content

murodovazizmurod/ormx

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

73 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

ORMX

ORMX
PyPI version GitHub commit activity GitHub issues
GitHub last commit GitHub top language
GitHub code size in bytes GitHub all releases PyPI - Downloads GitHub license

$ pip install ormx

Status

Version Status Tests and Actions
0.1.4.12 unstable, first version ~

Usage📖

Now, ORMX supports only SQLITE databases😁

Connecting database🔌

By importing Database class you can establish a new connection:

from ormx import Database

db = Database(database_file:str)

Properties

tables - returns list of table names in database

tables(Database) -> List

Example:

>> db.tables

# ['posts', 'author']

Defining Tables ✏

You should import Table, Column from ormx.models:

from ormx.models import (
    Table,
    Column
)

Create any class by naming your table with including Table class:

class User(Table):
    __tablename__ = 'users'
    name = Column(str)
    age = Column(int)
In this code, our table is named as `user` and columns of the table are named as `name` and `age`.

Types:

  • str - string('Linus'...),
  • int - integer(1,2,3 ...),
  • bool - boolean(True, False) or 1,0
  • bytes - bytes, blob
  • float - 3.15 ...
  • datetime - datetime object

Example:

class User(Table):
    __tablename__ = 'users'
    name = Column(str)
    age = Column(int)
    registered_at = Column(datetime)
    online = Column(bool)

    def __repr__(self):
        return f"{self.name}"


db.create(User)

user = User(name='User', age=15, date=datetime.now())

db.save(user)

user = db.get(User, id=1)

print(type(user.name)) # <class 'str'>
print(type(user.age)) # <class 'int'>
print(type(user.date)) # <class 'datetime.datetime'>
print(type(user.online)) # <class 'bool'>

New Feature

Now you can add default values for each column.

Example:

class Post(Table):
    __tablename__ = 'posts'
    title = Column(str, default='some title')
    draft = Column(bool, default=True)

Creating Tables🎉

# db : Database
db.create(TABLE:Table)

"""
* TABLE - your class in which you defined your table
"""

db.create(User)
# or
# db.create(User, Post)

Drop Table

# db : Database

db.drop(User)

# You can add arguments such as `if_exists`
# db.drop(User, if_exists=True) -> SQL request: `DROP TABLE IF EXISTS table_name`

Configuration

Default values

{
    "testing": False
}

Get value

db.config[value]

Example

>> db.config['testing'] # -> False

Set value

db.config.set(key, value)

Example

# Testing mode
>> db.config.set('testing', True)

Simple Relationships✨

Foreign Key

Example:

class Post(Table):
    title = Column(str)
    draft = Column(bool)
    author = ForeignKey(User)
Columns:
  • title - string
  • draft - boolean
  • author - belongs to the User class in the example presented on the top.
# Create all tables

db.create(User)
db.create(Post)

Creating and Selecting Objects🕹

Creating and selecting objects similar to other ORMs:

Database.save()

user = User(name="Linus",age=44)
db.save(user)

For saving objects you should write db.save(object)


For fetching all data:

    def all(self, table: Table,
            order_by: tuple = None,
            limit: list = None,
            where: list = None,
            fields: list = None,
            pretty_table: bool = False) -> List[Table]:
        """
        Returns all rows from `table`
        :params
            table: Table Object that will used
            order_by: name of column and sorting type. ex. ('title', ASC)
            limit: list of integers. ex. [10, 2] -> LIMIT 10 OFFSET 2
            where: list of filters.
                ex: ['column_name', 'condition', 'value']
                    or
                    [
                        ('name', '==', 'title'),
                        AND,
                        ('draft', '!=', 0),
                        OR
                        ('published', '>=', datetime.now())
                    ]
            fields: list of fields which will be returned. ex. ['title', 'published']
            pretty_table: bool. Printing query with PrettyTable
        :return:
            List of Table Objects
        """
users = db.all(User)

or

users = db['user']

PrettyTable usage:

users = db.all(User, pretty_table=True)

# +----+-----+-------+
# | id | age |  name |
# +----+-----+-------+
# | 1  |  99 | Linus |
# | 2  |  99 | Linus |
# | 3  |  99 | Linus |
# | 4  |  99 | Linus |
# ....

Where

Source:

db.all(table: Table, where=['column_name', 'condition', 'value'])
# or
db.all(table: Table, where=[
    ('column_name', 'condition', 'value'),
    ('column_name2', 'condition2', 'value2')
])

SQL code:

SELECT id, draft, title FROM post WHERE title == ?;

Example:

db.all(Post, where=['title', '==', "Programming"])

# or

db.all(Post, where=[('title', '==', "Programming"),
                    ('draft', '>', 0)]
       )

# or

db.all(Post, where=[
             ('title', '==', 'title'),
             AND,
             ('draft', '!=', 0),
             OR,
             ('published', '>=', datetime.now())
             ],
             order_by=['title', DESC]
             limit=[10, 2],
             fields=['title', 'draft']
       )

Conditions:

[
    "<", "<<", "<=",
    ">=", ">>", ">",
    "=", "==", "!=", "<>",
    "IN", "LIKE"
]

Exceptions:

WhereTypeError - given wrong type to where

Order BY

Example:

from ormx.types import ASC, DESC

db.all(User, order_by=('name', ASC))

db.all(Post, order_by=('title', DESC))

Exceptions:

OrderByParamError - order_by parameter must be tuple

OrderByColumnError - column not exists

SortingTypeError - second element of order_by tuple must be ASC or DESC


Limit Offset

Code:

db.all(table: Table, order_by=(column_name, List[ASC, DESC]), limit=List[LIMIT, OFFSET])

Example:

from ormx.types import DESC

db.all(User, limit=[1]) # -> sql: SELECT id, age, name FROM author LIMIT 1

db.all(User, limit=[10, 1]) # -> sql: SELECT id, age, name FROM author LIMIT 10 OFFSET 1

db.all(User, order_by=('id', DESC), limit=[10, 1]) # -> sql: SELECT id, age, name FROM author ORDER BY id DESC LIMIT 10 OFFSET 1

Exceptions:

LimitTooMuchParamsError - given too much values in list


Get count of rows in table or count of tables in Database

Source:

count(self, table: Union[Table] = None) -> int

db.count(Post) # -> int: count of rows in Post table

or

db.count() # -> int: count of tables in database

Update data

Database.update(self, instance: Table)

Example:

post = db.get(Post, id=1)

print(post.title) # Old value

post.title = 'New value'

db.update(post)

print(post.title) # New value

Delete column

author = db.get(Author, id=1)

db.delete(author)

Exceptions:

TableTypeInvalid


For fetching spec. object by their column name

Database.get(TABLE:Table, **kwargs)

Returns List Object

user = db.get(User, id=1, title='C++')

Fetch last data from table
user = db.first(User)

Fetching objects in cases of ForeignKey:

# Create a simple post with related user:
post = Post(title="C++",draft=False,author=user)

# Save it
db.save(post)

# Fetch it!
fetched = db.get(Post, id=1)

print(fetched.author.name)
# >>> 'Linus'

Some Examples:

Flask + ORMX CRUD app: https://ec099b10e8.pythonanywhere.com/

Photo-Sharing app: https://photo-sharing-ormx.herokuapp.com/

Article: https://community.uzbekcoders.uz/post/photo-sharing-dasturini-yaratamiz---flask-ormx-cloud-cdn-612787f94f5a32648e01ccc3


In progress 🔄