You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
This proposal outlines the implementation of the moschitta-orm module for the Moschitta Framework. The goal is to create a simple and intuitive ORM that functions similarly to SQLAlchemy but is more lightweight and only uses the Python standard library. The ORM will be asynchronous and will primarily support SQLite, with potential extension to other databases such as Postgres.
Objectives
Create an asynchronous ORM using the Python standard library.
Use Poetry to manage dependencies and the module's folder structure.
Implement a Model class that users can extend to create their own models.
Follow best practices and Pythonic principles, including the use of docstrings, type hints, and decorators.
Folder Structure
The folder structure for the moschitta-orm module will be as follows:
fromtypingimportAny, Dict, Type, TypeVarT=TypeVar('T', bound='BaseModel')
classBaseModel:
"""Base class for all models."""def__init__(self, **kwargs):
forkey, valueinkwargs.items():
setattr(self, key, value)
defto_dict(self) ->Dict[str, Any]:
"""Convert the model instance to a dictionary."""return {key: getattr(self, key) forkeyinself.__annotations__.keys()}
@classmethoddeffrom_dict(cls: Type[T], data: Dict[str, Any]) ->T:
"""Create a model instance from a dictionary."""returncls(**data)
fromtypingimportDictfrommoschitta_orm.databaseimportDatabaseasyncdefcreate_table(db: Database, table_name: str, columns: Dict[str, str]):
"""Create a table with the given name and column definitions."""column_defs=", ".join(f"{name}{dtype}"forname, dtypeincolumns.items())
query=f"CREATE TABLE IF NOT EXISTS {table_name} ({column_defs});"awaitdb.execute(query)
5. Model Registration Decorator
moschitta_orm/decorators.py
fromtypingimportTypemodels_registry= {}
defregister_model(cls: Type):
"""Decorator to register a model class."""models_registry[cls.__name__] =clsreturncls
Example Usage
# example.pyimportasynciofrommoschitta_orm.databaseimportDatabasefrommoschitta_orm.modelsimportUserfrommoschitta_orm.utilsimportcreate_tableasyncdefmain():
db=Database('example.db')
# Create the users tableawaitcreate_table(db, 'users', {
'id': 'INTEGER PRIMARY KEY',
'name': 'TEXT',
'email': 'TEXT'
})
# Create a new user instanceuser=User(id=1, name='John Doe', email='[email protected]')
# Insert user into the databaseawaitdb.execute("INSERT INTO users (id, name, email) VALUES (?, ?, ?)", [user.id, user.name, user.email])
# Fetch all users from the databaseusers=awaitdb.fetchall("SELECT * FROM users")
foruser_datainusers:
user=User.from_dict(user_data)
print(user.to_dict())
# Run the main functionasyncio.run(main())
Testing
Add tests in the tests folder to ensure the ORM works as expected.
tests/test_orm.py
importasyncioimportpytestfrommoschitta_orm.databaseimportDatabasefrommoschitta_orm.modelsimportUserfrommoschitta_orm.utilsimportcreate_table@pytest.mark.asyncioasyncdeftest_create_and_fetch_user():
db=Database(':memory:') # Use in-memory database for testing# Create the users tableawaitcreate_table(db, 'users', {
'id': 'INTEGER PRIMARY KEY',
'name': 'TEXT',
'email': 'TEXT'
})
# Create a new user instanceuser=User(id=1, name='John Doe', email='[email protected]')
# Insert user into the databaseawaitdb.execute("INSERT INTO users (id, name, email) VALUES (?, ?, ?)", [user.id, user.name, user.email])
# Fetch all users from the databaseusers=awaitdb.fetchall("SELECT * FROM users")
assertlen(users) ==1fetched_user=User.from_dict(users[0])
assertfetched_user.id==1assertfetched_user.name=='John Doe'assertfetched_user.email=='[email protected]'
Conclusion
This proposal outlines the basic structure and implementation of the moschitta-orm module. By following this plan, we can create a simple, efficient, and Pythonic ORM for the Moschitta Framework that is easy to use and extend.
The text was updated successfully, but these errors were encountered:
Overview
This proposal outlines the implementation of the
moschitta-orm
module for the Moschitta Framework. The goal is to create a simple and intuitive ORM that functions similarly to SQLAlchemy but is more lightweight and only uses the Python standard library. The ORM will be asynchronous and will primarily support SQLite, with potential extension to other databases such as Postgres.Objectives
Folder Structure
The folder structure for the
moschitta-orm
module will be as follows:Implementation Details
1. BaseModel Class
moschitta_orm/base.py
2. Database Class
moschitta_orm/database.py
3. Sample Model
moschitta_orm/models.py
4. Utility Functions
moschitta_orm/utils.py
5. Model Registration Decorator
moschitta_orm/decorators.py
Example Usage
Testing
Add tests in the
tests
folder to ensure the ORM works as expected.tests/test_orm.py
Conclusion
This proposal outlines the basic structure and implementation of the
moschitta-orm
module. By following this plan, we can create a simple, efficient, and Pythonic ORM for the Moschitta Framework that is easy to use and extend.The text was updated successfully, but these errors were encountered: