$ pip install ormx
Version | Status | Tests and Actions |
---|---|---|
0.1.4.12 |
unstable, first version | ~ |
Now,
ORMX
supports onlySQLITE
databases😁
By importing Database class you can establish a new connection:
from ormx import Database
db = Database(database_file:str)
tables
- returns list of table names in database
tables(Database) -> List
Example:
>> db.tables
# ['posts', 'author']
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)
Types:
str
- string('Linus'...),int
- integer(1,2,3 ...),bool
- boolean(True, False) or 1,0bytes
- bytes, blobfloat
- 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'>
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)
# db : Database
db.create(TABLE:Table)
"""
* TABLE - your class in which you defined your table
"""
db.create(User)
# or
# db.create(User, Post)
# 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`
{
"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)
Foreign Key
Example:
class Post(Table):
title = Column(str)
draft = Column(bool)
author = ForeignKey(User)
- 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 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 |
# ....
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
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
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
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'
Flask + ORMX CRUD app: https://ec099b10e8.pythonanywhere.com/
Photo-Sharing app: https://photo-sharing-ormx.herokuapp.com/
In progress 🔄