Metadata-Version: 2.1
Name: FastSQLModel
Version: 0.1.2
Summary: Simplie and Fast utility for SQLModel/SQLAlchemy and Alembic
Home-page: https://github.com/ndendic/FastSQLModel
Author: Nikola Dendic
Author-email: Nikola Dendic <ndendic@gmail.com>
License: Apache Software License 2.0
Keywords: nbdev jupyter notebook python
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Natural Language :: English
Classifier: Programming Language :: Python :: 3.7
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: License :: OSI Approved :: Apache Software License
Requires-Python: >=3.7
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: alembic>=1.14.0
Requires-Dist: setuptools>=75.6.0
Requires-Dist: sqlmodel>=0.0.22
Requires-Dist: typer[all]>=0.15.1
Provides-Extra: dev

# FastSQLModel


<!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! -->

## Overview

FastSQLModel is a utility for simplifying the process of using
SQLModel/SQLAlchemy and Alembic. It provides a CLI for initializing and
managing Alembic migrations, and a set of tools for working with
SQLModel and SQLAlchemy models.

## Features

- **CLI for Alembic**: FastSQLModel provides a CLI for initializing and
  managing Alembic migrations.
- **SQLModel and SQLAlchemy Models**: FastSQLModel provides a set of
  tools for working with SQLModel and SQLAlchemy models.
- **Database Management**: FastSQLModel provides a set of tools for
  managing the database, including creating, dropping, and querying the
  database.

## Developer Guide

### Install FastSQLModel in Development

If you want to make changes to the package, you can install it in
development mode. This project uses nbdev for development, so you can
make changes to the code and documentation in the notebooks under the
nbs/ directory. To find out more about amazing nbdev, visit the [nbdev
documentation](https://nbdev.fast.ai/index.html).

To make changes to the package, you can install it in development mode.

``` sh
# make sure FastSQLModel package is installed in development mode
$ pip install -e .

# make changes under nbs/ directory
# ...

# compile to have changes apply to FastSQLModel
$ nbdev_prepare
```

## Usage

### Installation

Install latest from the GitHub
[repository](https://github.com/ndendic/FastSQLModel):

``` sh
$ pip install git+https://github.com/ndendic/FastSQLModel.git
```

or from [conda](https://anaconda.org/ndendic/FastSQLModel)

``` sh
$ conda install -c ndendic FastSQLModel
```

or from [pypi](https://pypi.org/project/FastSQLModel/)

``` sh
$ pip install FastSQLModel
```

To establish a connection to the database, please specify the
`DATABASE_URL` in the `.env` file.

### Documentation

Documentation can be found hosted on this GitHub
[repository](https://github.com/ndendic/FastSQLModel)’s
[pages](https://ndendic.github.io/FastSQLModel/). Additionally you can
find package manager specific guidelines on
[conda](https://anaconda.org/ndendic/FastSQLModel) and
[pypi](https://pypi.org/project/FastSQLModel/) respectively.

## How to use

### Create your first model

To create your first model, you can can import the BaseTable class from
the FastSQLModel.db module and create a new model by subclassing it.
BaseTable is a subclass of SQLModel, so it has all the same features,
but it also has a few extra features to help with some standard db
operations and 3 extra fields: - id: primary key, default to a uuid4 -
created_at: datetime, default to now - updated_at: datetime, default to
now, and updated on every save

``` python
class BaseTable(SQLModel):
    model_config = ConfigDict(json_encoders={datetime: lambda dt: dt.isoformat()})
    id: UUID = Field(default_factory=uuid4, primary_key=True)
    created_at: datetime = Field(
        default_factory=utc_now,
        sa_type= sa.DateTime(timezone=True),
        sa_column_kwargs={"server_default": sa.func.now()},
        nullable=False,
        title="Created At",
        schema_extra={"icon": "clock", "input_type": "datetime"},
    )
    updated_at: datetime = Field(
        default_factory=utc_now,
        sa_type=sa.DateTime(timezone=True),
        sa_column_kwargs={
            "server_default": sa.func.now(),
            "server_onupdate": sa.func.now(),
        },
        # onupdate=utc_now,
        nullable=False,
        title="Updated At",
        schema_extra={"icon": "clock", "input_type": "datetime"},
    )
```

Here is an example of how to create a new model using BaseTable

``` python
# users.py
from typing import Optional
from sqlmodel import Field
from datetime import datetime
from FastSQLModel.db import BaseTable

class User(BaseTable, table=True):
    name: Optional[str] = Field(nullable=True)
    email: str = Field(nullable=False)
    password: str = Field(nullable=False)
    joined_at: datetime = Field(nullable=False)
```

Now that you have created your first model, you can use the CLI to
initialize and manage Alembic project.

``` sh
$ fastmodel init
```

This will create a new Alembic project in the current directory, and
create a new .alembic.ini file.

2.  Then make sure to add your models to the migrations/env.py file
    before running migrations.

``` python
# migrations/env.py
from users import User
# ...
```

3.  Now you can run migrations to prepare the database for your models.

``` sh
$ fastmodel migrations
```

4.  And now you can migrate your models to the database.

``` sh
$ fastmodel migrate
```

Let’s see how this works

Initialization:

``` python
# !fastmodel init
```

Making migrations

``` python
!fastmodel migrations
```

    Generating Alembic migration with message: Pushing changes
    DATABASE_URL sqlite:///test.db
    INFO  [alembic.runtime.migration] Context impl SQLiteImpl.
    INFO  [alembic.runtime.migration] Will assume non-transactional DDL.
      Generating /home/ndendic/WebDev/FastSQLModel/nbs/migrations/versions/4d4567890
      1bc_pushing_changes.py ...  done
    Migration created successfully!

Migrating changes

``` python
!fastmodel migrate
```

    Applying database migrations...
    DATABASE_URL sqlite:///test.db
    INFO  [alembic.runtime.migration] Context impl SQLiteImpl.
    INFO  [alembic.runtime.migration] Will assume non-transactional DDL.
    INFO  [alembic.runtime.migration] Running upgrade 5441880ad0e3 -> 4d45678901bc, Pushing changes
    Migrations applied successfully!

Once our table is migrated, we can start adding some data like this.

``` python
user = User(name="Homer Simpson", email="homer@simpson.com", password="password", joined_at=datetime.now())
user.save()
user.model_dump()
```

    {'name': 'Homer Simpson',
     'email': 'homer@simpson.com',
     'password': 'password',
     'joined_at': datetime.datetime(2024, 12, 19, 16, 2, 4, 408489),
     'id': UUID('f4ff6c91-8fcf-44a8-9874-cf2535a8d10c'),
     'created_at': datetime.datetime(2024, 12, 19, 15, 2, 4, 413702, tzinfo=datetime.timezone.utc),
     'updated_at': datetime.datetime(2024, 12, 19, 15, 2, 4, 413744, tzinfo=datetime.timezone.utc)}

Let’s get our user by id

``` python
homer = User.get(user.id)
if homer:
    print(f"Name: {homer.name}, Email: {homer.email}")
else:
    print("User not found")
```

    Name: Homer Simpson, Email: homer@simpson.com

Or by alternative key value

``` python
homer = User.get("homer@simpson.com",alt_key="email")
if homer:
    print(f"Name: {homer.name}, Email: {homer.email}")
else:
    print("User not found")
```

    Name: Homer Simpson, Email: homer@simpson.com

Now let’s modify our record and save it back to our database and
retreive back

``` python
homer.email = "homer.simpson@simpson.com"
homer.save()
homer = User.get("homer.simpson@simpson.com",alt_key="email")
homer.email
```

    'homer.simpson@simpson.com'

Let’s define a bit more Simprons, this time like this

``` python
bart = User()
bart.name = "Bart Simpson"
bart.email = "bart@simpson.com"
bart.password = "password"
bart.joined_at = datetime.now()
bart.save()

bart.name, bart.email
```

    ('Bart Simpson', 'bart@simpson.com')

Let’s retrive records in our table. We can simply do that by calling
`all` function

``` python
User.all()
```

    [User(email='homer.simpson@simpson.com', name='Homer Simpson', joined_at=datetime.datetime(2024, 12, 19, 16, 1, 27, 746940), id=UUID('e1d719e2-21a4-40c1-ab9b-062e0808f101'), updated_at=datetime.datetime(2024, 12, 19, 15, 1, 27, 870936), created_at=datetime.datetime(2024, 12, 19, 15, 1, 27, 783496), password='password'),
     User(email='bart@simpson.com', name='Bart Simpson', joined_at=datetime.datetime(2024, 12, 19, 16, 1, 27, 909419), id=UUID('7aa9cd07-59c4-4f34-8bdd-df9b05453efb'), updated_at=datetime.datetime(2024, 12, 19, 15, 1, 27, 914354), created_at=datetime.datetime(2024, 12, 19, 15, 1, 27, 914332), password='password'),
     User(email='homer.simpson@simpson.com', name='Homer Simpson', joined_at=datetime.datetime(2024, 12, 19, 16, 2, 4, 408489), id=UUID('f4ff6c91-8fcf-44a8-9874-cf2535a8d10c'), updated_at=datetime.datetime(2024, 12, 19, 15, 2, 4, 552857), created_at=datetime.datetime(2024, 12, 19, 15, 2, 4, 434347), password='password'),
     User(email='bart@simpson.com', name='Bart Simpson', joined_at=datetime.datetime(2024, 12, 19, 16, 2, 4, 602805), id=UUID('455cbf7d-b8f6-407a-8ae6-f80f814d9735'), updated_at=datetime.datetime(2024, 12, 19, 15, 2, 4, 606104), created_at=datetime.datetime(2024, 12, 19, 15, 2, 4, 606086), password='password')]

Here we can see that we have forgot to set some `unique` values to our
fields and prevent duplicates. So let’s remove our duplicates manualy
now

First, we can use search to get all the records that contain some
character in some of their string fields. This is usefull for filtering
records where you’re not sure where the value shuld match.

``` python
users = User.search(search_value="Homer")
for user in users:
    print(f"Name: {user.name} , Email: {user.email}, ID: {user.id}")
```

    Name: Homer Simpson , Email: homer.simpson@simpson.com, ID: e1d719e2-21a4-40c1-ab9b-062e0808f101
    Name: Homer Simpson , Email: homer.simpson@simpson.com, ID: f4ff6c91-8fcf-44a8-9874-cf2535a8d10c

You can also set the fields you want to retreive from specific fields
using `fields` argument. This will now not return the instance of the
User rable but a list of tuples.

``` python
users = User.search(search_value="Simpson", fields=['name','email'])
users
```

    [('Bart Simpson', 'bart@simpson.com'),
     ('Bart Simpson', 'bart@simpson.com'),
     ('Homer Simpson', 'homer.simpson@simpson.com'),
     ('Homer Simpson', 'homer.simpson@simpson.com')]

Now let’s retreive our records again

``` python
users = User.search(search_value="bart")
users
```

    [User(email='bart@simpson.com', name='Bart Simpson', joined_at=datetime.datetime(2024, 12, 19, 16, 2, 4, 602805), id=UUID('455cbf7d-b8f6-407a-8ae6-f80f814d9735'), updated_at=datetime.datetime(2024, 12, 19, 15, 2, 4, 606104), created_at=datetime.datetime(2024, 12, 19, 15, 2, 4, 606086), password='password'),
     User(email='bart@simpson.com', name='Bart Simpson', joined_at=datetime.datetime(2024, 12, 19, 16, 1, 27, 909419), id=UUID('7aa9cd07-59c4-4f34-8bdd-df9b05453efb'), updated_at=datetime.datetime(2024, 12, 19, 15, 1, 27, 914354), created_at=datetime.datetime(2024, 12, 19, 15, 1, 27, 914332), password='password')]

..and remove the first two results using the `delete` function

``` python
for user in users[:len(users)-1]:
    user.delete()

for user in User.all():
    print(user.name)
```

    Homer Simpson
    Bart Simpson
    Homer Simpson

we also have the option to filter the records using `filter` function
for a specific model field.

``` python
results = User.filter(name="Homer Simpson")
results
```

    [User(email='homer.simpson@simpson.com', name='Homer Simpson', joined_at=datetime.datetime(2024, 12, 19, 16, 1, 27, 746940), id=UUID('e1d719e2-21a4-40c1-ab9b-062e0808f101'), updated_at=datetime.datetime(2024, 12, 19, 15, 1, 27, 870936), created_at=datetime.datetime(2024, 12, 19, 15, 1, 27, 783496), password='password'),
     User(email='homer.simpson@simpson.com', name='Homer Simpson', joined_at=datetime.datetime(2024, 12, 19, 16, 2, 4, 408489), id=UUID('f4ff6c91-8fcf-44a8-9874-cf2535a8d10c'), updated_at=datetime.datetime(2024, 12, 19, 15, 2, 4, 552857), created_at=datetime.datetime(2024, 12, 19, 15, 2, 4, 434347), password='password')]

``` python
results = User.filter(email="homer.simpson@simpson.com")
results
```

    [User(email='homer.simpson@simpson.com', name='Homer Simpson', joined_at=datetime.datetime(2024, 12, 19, 16, 1, 27, 746940), id=UUID('e1d719e2-21a4-40c1-ab9b-062e0808f101'), updated_at=datetime.datetime(2024, 12, 19, 15, 1, 27, 870936), created_at=datetime.datetime(2024, 12, 19, 15, 1, 27, 783496), password='password'),
     User(email='homer.simpson@simpson.com', name='Homer Simpson', joined_at=datetime.datetime(2024, 12, 19, 16, 2, 4, 408489), id=UUID('f4ff6c91-8fcf-44a8-9874-cf2535a8d10c'), updated_at=datetime.datetime(2024, 12, 19, 15, 2, 4, 552857), created_at=datetime.datetime(2024, 12, 19, 15, 2, 4, 434347), password='password')]

Similar to `search`, `filter` can take the same argumants, like
`fields`, `sorting_field` and other (for full list navigate to the db
section).

``` python
results = User.filter(name="Simp",exact_match=False,fields=["name","email"])
results
```

    []

We can also combine field filters.

``` python
results = User.filter(name="simp",email="hom",exact_match=False,fields=["name","email"])
results
```

    []

For more deatails visit related docs for
[SQLModel](https://sqlmodel.tiangolo.com/) and
[Alembic](https://alembic.sqlalchemy.org/en/latest/)
