Skip to main content

The missing SQLAlchemy ORM service layer

Project description

version travis coveralls license

The missing SQLAlchemy ORM service layer.

Introduction

So what exactly is sqlservice and what does “the missing SQLAlchemy ORM service layer” even mean? The “service layer” in this context is that part of your application that forms your core domain logic. This is where your ORM models meet your database session and all the magic happens.

Features

This library is meant to enhanced your usage of SQLAlchemy. SQLAlchemy is great and this library tries to build upon that by providing useful abstractions on top of it.

  • Database client similar to Flask-SQLAlchemy and alchy.DatabaseManager that helps manage an ORM scoped session.

  • Base class for a declarative ORM Model that makes updating model columns and relationships easier and convert to a dictionary a breeze.

  • A decorator based event registration for SQLAlchemy ORM events that can be used at the model class level. No need to register the event handler outside of the class definition.

  • A base service class that provides a unified way to save database records as either ORM models or plain dictionaries.

  • An application-side nestable transaction context-manager that helps implement pseudo-subtransactions for those that want implicit transaction demarcation, i.e. autocommit=False, without the use of subtransactions=True.

  • And more!

History

This library’s direct predecessor is alchy which itself started as a drop-in replacement for Flask-SQLAlchemy combined with new functionality centering around the “fat-model” style. This library takes a different approach and encourages a “fat-service” style. As such, it is primarily a rewrite of alchy with some of its features ported over and improved, some of its features removed, and other features added. With alchy, one’s primary interface with the database was through a model class. Whereas with sqlservice, one’s primary interface with the database is through a service class.

Requirements

Quickstart

First, install using pip:

pip install sqlservice

Then, define some ORM models:

import re

from sqlalchemy import Column, ForeignKey, orm, types

from sqlservice import ModelBase, declarative_base, event


Model = declarative_base(ModelBase)

class User(Model):
    __tablename__ = 'user'

    id = Column(types.Integer(), primary_key=True)
    name = Column(types.String(100))
    email = Column(types.String(100))
    phone = Column(types.String(10))

    roles = orm.relation('UserRole')

    @event.on_set('phone', retval=True)
    def on_set_phone(self, value, oldvalue, initator):
        # Strip non-numeric characters from phone number.
        return re.sub('[^0-9]', '', value)

class UserRole(Model):
    __tablename__ = 'user_role'

    id = Column(types.Integer(), primary_key=True)
    user_id = Column(types.Integer(), ForeignKey('user.id'), nullable=False)
    role = Column(types.String(25), nullable=False)

Next, configure a database client:

from sqlservice import SQLClient

config = {
    'SQL_DATABASE_URI': 'sqlite:///db.sql',
    'SQL_ECHO': True,
    'SQL_POOL_SIZE': 5,
    'SQL_POOL_TIMEOUT': 30,
    'SQL_POOL_RECYCLE': 3600,
    'SQL_MAX_OVERFLOW': 10,
    'SQL_AUTOCOMMIT': False,
    'SQL_AUTOFLUSH': True
}

db = SQLClient(config, Model=Model)

Create a service class for our models:

from sqlservice import SQLService


class UserService(SQLService):
    model_class = User

Prepare the database by creating all tables:

db.create_all()

Finally (whew!), start interacting with the database:

user_service = UserService(db)

# Insert a new record in the database.
data = {'name': 'Jenny', 'email': 'jenny@example.com', 'phone': '555-867-5309'}
user = user_service.save(data)


# Fetch records.
assert user is user_service.get(data.id)
assert user is user_service.find_one(id=user.id)
assert user is user_service.find(User.id == user.id)[0]

# Serialize to a dict.
assert user.to_dict() == {'id': 1,
                          'name': 'Jenny',
                          'email': 'jenny@example.com',
                          'phone': '5558675309'}

assert dict(user) == user.to_dict()

# Update the record and save.
user.phone = '222-867-5309'
user_service.save(user)

# Upsert on primary key automatically.
assert user is user_service({'id': 1,
                             'name': 'Jenny',
                             'email': 'jenny@example.com',
                             'phone': '5558675309'})

# Delete the model.
user_service.delete(user)
# OR user_service.delete([user])
# OR user_service.delete(user.id)
# OR user_service.delete(dict(user))

For more details, please see the full documentation at http://sqlservice.readthedocs.org.

Changelog

v0.1.0 (2016-05-24)

  • First release.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

sqlservice-0.1.0.tar.gz (31.8 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

sqlservice-0.1.0-py2.py3-none-any.whl (21.7 kB view details)

Uploaded Python 2Python 3

File details

Details for the file sqlservice-0.1.0.tar.gz.

File metadata

  • Download URL: sqlservice-0.1.0.tar.gz
  • Upload date:
  • Size: 31.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No

File hashes

Hashes for sqlservice-0.1.0.tar.gz
Algorithm Hash digest
SHA256 85f505f4c191a38149608223bd3799df03f0ab6dae6057376e9a3c0d8b46d008
MD5 1775ab9b334d808dc01fac1cb2c77005
BLAKE2b-256 5d43bef3a73eade3c6492681e96aa5f2e5b08698b1778cd202af9f0e1224df9b

See more details on using hashes here.

File details

Details for the file sqlservice-0.1.0-py2.py3-none-any.whl.

File metadata

File hashes

Hashes for sqlservice-0.1.0-py2.py3-none-any.whl
Algorithm Hash digest
SHA256 66e6ef361ce32e57a54a8e0623752cc4b23aa190ee33e843dffa549c04194f3d
MD5 92f2e125b901c43b599024e7b9ce2459
BLAKE2b-256 e0ace21fb6cce659f5215b90df887f365da68720b4af3b961c9b898b94dcfb03

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page