Skip to content

dica-dev/dica-orm

Repository files navigation

Dica ORM

A lightweight Python ORM (Object-Relational Mapping) framework that automatically generates RESTful API routes from your entity definitions.

Features

  • Simple Entity Definition: Define your database entities with validation rules using Python dictionaries
  • Automatic CRUD Operations: Get create, read, update, and delete operations out of the box
  • Built-in Validation: Email validation, length constraints, required fields, and data type checking
  • Automatic API Generation: Flask routes are automatically created for all entities
  • Password Encryption: Built-in support for encrypted fields
  • Multiple Database Support: Currently supports SQLite with extensibility for MySQL and MongoDB
  • Thread-Safe: Uses thread-local storage for database connections

Quick Start

Prerequisites

  • Python 3.8 or higher
  • uv (recommended) or pip

Installation

Using the setup script (recommended):

chmod +x setup.sh
./setup.sh

Manual installation:

# Install uv if you haven't already
curl -LsSf https://astral.sh/uv/install.sh | sh

# Create virtual environment
uv venv

# Activate virtual environment
# On Windows:
.venv\Scripts\activate
# On macOS/Linux:
source .venv/bin/activate

# Install dependencies
uv pip install -r requirements.txt

Usage

Basic Example

import Dica as dica_db

# Initialize Dica
dica = dica_db.Dica()

# Create a database
db = dica.Database(1, "sqlite", "my_database")

# Define an entity with validation rules
users = db.create_entity("users", {
    "nombre": {
        "required": [True, "User must have a name"],
        "data_type": [str, "Must be a string"],
        "min_length": [1, "Name must be at least 1 character"],
        "max_length": [50, "Name must be less than 50 characters"]
    },
    "email": {
        "data_type": [str, "Must be a string"],
        "required": [True, "User must have an email"],
        "email": [True, "Invalid email format"]
    },
    "password": {
        "encrypt": True,
        "min_length": [8, "Password must be at least 8 characters"]
    }
})

# Create records
users.create({
    "nombre": "John Doe",
    "email": "john@example.com",
    "password": "secretpass123"
})

# Start the API server
db.run()

Entity Configuration

Each entity is defined with a dictionary where keys are column names and values are configuration objects:

{
    "column_name": {
        "required": [bool, "error_message"],      # Field is required
        "data_type": [type, "error_message"],     # Python type (str, int, float, bool)
        "min_length": [int, "error_message"],     # Minimum length for strings
        "max_length": [int, "error_message"],     # Maximum length for strings
        "encrypt": bool,                           # Encrypt this field (for passwords)
        "email": [bool, "error_message"]          # Validate email format
    }
}

Available Methods

Entity Methods

# Create a new record
entity.create({"field": "value"})

# Find all records
entity.find()

# Find with filters
entity.find({"nombre": "John"})

# Find with regex
entity.find({"nombre": {"re": "Joh"}})

# Find by ID
entity.findById(1)

# Update by ID
entity.findByIdAndUpdate(1, {"nombre": "Jane Doe"})

# Delete by ID
entity.findByIdAndDelete(1)

Auto-Generated API Routes

When you run db.run(), the following REST endpoints are automatically created for each entity:

  • POST /{entity_name}/create - Create a new record
  • GET /{entity_name}/get - Get all records
  • GET /{entity_name}/getById/:id - Get a record by ID
  • PUT /{entity_name}/update - Update a record
  • DELETE /{entity_name}/delete/:id - Delete a record by ID

Example API Calls

# Create a user
curl -X POST http://localhost:5000/users/create \
  -H "Content-Type: application/json" \
  -d '{"nombre": "Jane", "email": "jane@example.com", "password": "password123"}'

# Get all users
curl http://localhost:5000/users/get

# Get user by ID
curl http://localhost:5000/users/getById/1

# Update user
curl -X PUT http://localhost:5000/users/update?id=1 \
  -H "Content-Type: application/json" \
  -d '{"nombre": "Jane Smith"}'

# Delete user
curl -X DELETE http://localhost:5000/users/delete/1

Project Structure

dica-orm/
├── Dica.py              # Main ORM class
├── Entities/
│   ├── Entity.py        # Entity class with CRUD operations
│   └── Column.py        # Column definition and validation
├── databases/
│   ├── Database.py      # Database abstraction layer
│   ├── sqlite.py        # SQLite implementation
│   ├── MySQL.py         # MySQL implementation (in progress)
│   └── MongoDb.py       # MongoDB implementation (in progress)
├── auth/
│   └── auth.py          # Authentication utilities
├── tests/               # Test suite
│   ├── __init__.py
│   ├── conftest.py      # Test fixtures and configuration
│   ├── test_database.py # Database connection tests
│   ├── test_entity.py   # Entity definition tests
│   ├── test_validations.py # Validation system tests
│   ├── test_crud.py     # CRUD operations tests
│   └── test_api.py      # API generation tests
├── Ejemplo.py           # Example usage
├── requirements.txt     # Project dependencies
├── pyproject.toml       # Project configuration and tool settings
├── setup.sh             # Setup script
├── run_tests.sh         # Test runner script
├── .gitignore           # Git ignore rules
└── README.md            # This file

Development

Running the Example

python Ejemplo.py

This will:

  1. Create a SQLite database named "prueba"
  2. Define user and product entities
  3. Create sample records
  4. Start a Flask server on http://localhost:5000

Viewing Available Routes

Once the server is running, visit http://localhost:5000 to see all available API endpoints.

Testing and Quality Assurance

Dica ORM includes a comprehensive test suite with 48+ unit tests covering all functional requirements.

Running Tests

# Activate your virtual environment first
source .venv/bin/activate  # macOS/Linux
# or
.venv\Scripts\activate  # Windows

# Run all tests
pytest

# Run tests with verbose output
pytest -v

# Run tests with coverage report
pytest --cov=. --cov-report=html

# Run tests for a specific module
pytest tests/test_database.py
pytest tests/test_crud.py

Test Coverage

The test suite covers the following functional requirements:

RF1 - Database Connection Management (8 tests)

  • Creating single and multiple database connections
  • Preventing duplicate database names
  • SQLite database support
  • Retrieving databases by name
  • Listing all databases
  • Database metadata validation

RF2 - Entity Definition (6 tests)

  • Creating entities with declarative schemas
  • Multiple entities per database
  • Entity column validation
  • Listing entities
  • Entity dictionary representation

RF3 - Validation System (11 tests)

  • Required field validation
  • Data type validation (str, int, float, bool)
  • Min/max length validation
  • Email format validation
  • Field encryption configuration
  • Custom error messages
  • Combined validations

RF4 - CRUD Operations (13 tests)

  • Creating single and multiple records
  • Reading all records and by ID
  • Filtering and regex search
  • Updating records by ID
  • Deleting records by ID
  • SQL query generation for all operations

RF5 - API Generation (10 tests)

  • Automatic route generation
  • POST, GET, PUT, DELETE endpoint creation
  • Route listing functionality
  • Flask app integration
  • REST conventions compliance

Coverage Reports

After running tests with coverage, open the HTML report:

# Generate coverage report
pytest --cov=. --cov-report=html

# Open the report (the command depends on your OS)
# macOS
open htmlcov/index.html

# Linux
xdg-open htmlcov/index.html

# Windows
start htmlcov/index.html

Code Quality with Ruff

Dica ORM uses Ruff for linting and code quality checks.

# Check code quality
ruff check .

# Auto-fix issues
ruff check --fix .

# Check specific files
ruff check Dica.py
ruff check databases/

# Format code (if needed)
ruff format .

Continuous Integration

The project includes configuration for:

  • pytest: Unit testing framework
  • pytest-cov: Coverage reporting
  • ruff: Linting and code quality
  • PEP8 compliance checking

Test Structure

tests/
├── __init__.py
├── conftest.py           # Shared fixtures and configuration
├── test_database.py      # RF1 - Connection management tests
├── test_entity.py        # RF2 - Entity definition tests
├── test_validations.py   # RF3 - Validation system tests
├── test_crud.py          # RF4 - CRUD operations tests
└── test_api.py           # RF5 - API generation tests

Database Support

Currently Supported

  • SQLite: Fully implemented with all CRUD operations

Planned Support

  • MySQL: Implementation in progress
  • MongoDB: Implementation in progress

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

This project is licensed under the MIT License.

Authors

  • ITESO - Software Quality Project

About

Librería de uso libre para manejo de bases de datos y bases de datos vectoriales

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published