项目作者: gigaquads

项目描述 :
A transactional in-memory SQL-like object store for long running processes, games, analytics, realtime processing and other applications.
高级语言: Python
项目地址: git://github.com/gigaquads/store.git
创建时间: 2021-05-11T14:28:20Z
项目社区:https://github.com/gigaquads/store

开源协议:

下载


Store

This library provides a Store datatype for Python. Each store looks and feels
like an ORM, but unlike an ORM, there is no database on the other end. Instead,
all data lives in memory, in the form of plain Python dicts and B-tree indices.
Stores support SQL-like select statements in the style of SQLAlchemy,
atomic transactions and multithreading.

The source code aims to be rebustly documented, as we encourage open-source
collaboration on this Project.

Use-cases

  • Long-running interactive applications, like games.
  • Automated trading systems with complex internal state management requirements.
  • Stream-processing applications that perform fast ad hoc queries on stream buffers.

An Example

Imagine a system that generates user input events, like mouse click and key
press
. In the following example, we delete click events created after a
specified time and capitalize the character asssociated with each key press
within a transaction.

  1. from store import Store
  2. events = Store()
  3. # insert fictitious "event" records
  4. events.create_many([
  5. {'event_type': 'press', 'char': 'x', 'time': 1},
  6. {'event_type': 'click', 'button': 'L', 'position': (5, 8), 'time': 2},
  7. {'event_type': 'click', 'button': 'R', 'position': (3, 4), 'time': 3},
  8. {'event_type': 'press', 'char': 'y', 'time': 4},
  9. {'event_type': 'press', 'char': 'p', 'time': 5},
  10. ])
  11. with events.transaction() as transaction:
  12. # delete "click" events after specified time
  13. transaction.select().where(
  14. events.row.event_type == 'click',
  15. events.row.time > 2
  16. ).delete()
  17. # capitalize the "char" for each selected "press" event
  18. get_press_events = transaction.select().where(
  19. x.event_type == 'press',
  20. x.char.one_of(['x', 'y', 'z'])
  21. )
  22. for event in get_press_events(dtype=list):
  23. event['char'] = event['char'].upper()

State Dicts

Store methods, like create and update, return state dicts. Unlike regular
dicts, any change to the keys or values of a state dict results in an update to
the store. For example, suppose that user is a state dict. As such,
user['name'] ='John' generates a call to store.update under the hood. When
this happens, any existing reference to the same user immediately reflect this
change. There is no need to refresh each reference manually (as they are all
actually the same object). The same is true for other methods, like update,
setdefault, etc.

Let’s illustrate with an example:

  1. frank_1 = store.create({'id': 1, 'name': 'frank'})
  2. frank_2 = store.get(1)
  3. # the store manages a singleton reference to frank's StateDict
  4. # in its internal so-called identity set.
  5. assert frank_1 is frank_2
  6. # frank_1 and frank_2 are references to the same object,
  7. # so they should both reflect the same change.
  8. frank_1['name'] = 'Franklin'
  9. assert frank_2['name'] == 'Franklin'
  10. # likewise, any subsequent reference should reflect the same change
  11. frank_3 = store.get(1)
  12. assert frank_3['name'] == 'Franklin'

Stateful Methods

Here is a list of each dict method that has been extended to result in an
update to store as a side-effect. On the lefthand side of each arrow is the
dict method. On the righthand side is the corresponding store call.

  • state.update(mapping)store.update(state, mapping.keys())
  • state.setdefault(key, default)store.update(state, {key})
  • state[key] = valuestore.update(state, {key})
  • del state[key]store.delete(state, {key})

Indexes

By default, all StateDict keys are indexed, including those with non-scalar
values — like lists, sets, dicts, etc. This means that that queries are fast.

Queries

You can query a store like a SQL database, using select, where, order_by,
limit and offset constraints.

Symbols

Select statements are written with the help of a class called Symbol. A symbol
is a variable used to express what you want to select and how. Suppose you had a
store of user records. Then, using a symbol, You could write a query to
selects all users, created after a certain cut-off date.

  1. user = user_store.symbol()
  2. get_users = user_store.select(
  3. user.first_name,
  4. user.email
  5. ).where(
  6. user.created_at > cutoff_date
  7. )
  8. for user in get_users(dtype=list):
  9. send(message=f'Hello, {user["first_name"]}!', email=user['email'])

An alternative to instantiating a new symbol for each query is to use a built-in
property, store.row. The following query is identical to the one above:

  1. get_users = user_store.select(
  2. user_store.row.first_name,
  3. user_store.row.email
  4. ).where(
  5. user_store.row.created_at > cutoff_date
  6. )

Select

By default, an empty select will select everything, like select * from... in
SQL; however, if you’re only interested in a subset of fields, you can
explicitly enumerate them.

Selecting Everything

  1. query = store.select()

Selecting Specific Fields

  1. query = store.select(store.row.name, store.row.email)

Where (Filtering)

You can constrain queries to select only records whose values match a given
logical predicate. Predicates can be arbitrarily nested in compound boolean
expressions. This is similar to the “where” clause in SQL select statements.

Filtering Non-scalars Values

Unlike a SQL database, with a store, you can apply predicate logic not only to
scalar values, like numbers and strings, but also non-scalar types, like dicts,
lists, and sets.

For example, this is possible:

  1. # imagine you have a store with user dicts, and each user dict
  2. # has a nested dog dict with an "age" value.
  3. get_users = store.select().where(store.row.dog <= {'age': 10})
  4. for user in get_users():
  5. assert user['dog']['age'] <= 10

Using a symbol, here are some example:

Conditional Expressions

  1. user = store.symbol()
  2. # equality
  3. predicate = (user.email == 'elon.musk@gmail.com')
  4. predicate = (user.email != 'elon.musk@gmail.com')
  5. # inequality
  6. predicate = (user.age >= 50)
  7. # containment
  8. predicate = (user.favorite_color.in(['red', 'blue'])
  9. # logical conjunction (AND)
  10. predicate = (user.scent == 'smelly') & (user.income <= 20000)
  11. # logical disjunction (OR)
  12. predicate = (user.scent == 'smelly') | (user.income <= 20000)
  13. # logical conjunction and disjunction combined
  14. predicate = (
  15. ((user.scent == 'smelly') | (user.age <= 20)) & (user.name == 'Bob')
  16. )

Moreover, predicates can be built up gradually, like so:

  1. predicate = (user.age <= 20)
  2. if some_condition:
  3. predicate &= (user.income > 100000) # |= also works

Once you have your predicate, you can pass it into a query’s where method:

  1. query = store.select().where(
  2. (user.age <= 20) | (user.is_member == True)
  3. )

Order By

Query results can be sorted by one or more values using the order_by query
method. For example:

  1. # sort results by age (in ascending order) first
  2. # created_at date (in descending order) second.
  3. query = store.select().order_by(
  4. user.age.asc,
  5. user.created_at.desc
  6. )

Ordering By Non-scalar Values

Unlike SQL, the store can sort non-scalar datatypes, like dicts, lists, and sets
— in addition to plain ints and strings. This means that you can do things like
— this:

  1. store.create_many([
  2. {'owner': 'Mohammed', 'dog': {'age': 10}},
  3. {'owner': 'Kang Bo', 'dog': {'age': 6}},
  4. ])
  5. get_users = store.select().order_by(store.row.dog.asc)
  6. users = get_users(dtype=list)
  7. for u1, u2 in zip(users, users[1:]):
  8. assert u1.dog['age'] <= u2.dog['age']

Note that, when sorting a dict, the dict’s items are sorted and compared in the
resulting order.

Limit & Offset

Queries support pagination via limit and offset parameters. The limit
parameter is an int that determines the maximum number of records returned by
the query while the offset parameter determines the starting index of the
returned slice. When using limit and offset, it is important to specify an order, using
order_by.

  1. query = store.select(
  2. user.email
  3. ).order_by(
  4. user.age.desc
  5. ).offset(
  6. 20
  7. ).limit(
  8. 10
  9. )

Transactions

Stores support transactions as well. If, for some reason you don’t already know,
a database transaction is a mechanism that allows you to perform multiple
operations as if they were all performed int a single step. This way, if one
operation fails, then they all fail, and the state of the store remains intact.
The syntax for creating transactions is straight forward:

  1. with user_store.transaction() as user_trans:
  2. # update the name of one user and delete another
  3. users = user_trans.get_many([1, 2])
  4. users[1]['name'] = 'Updated Name'
  5. users[2].delete()

At the end of the with block, the transaction commits; otherwise, if an
exception is raised, the transaction rolls back, clearing its internal state.

Alternate to using the with statement, commit and rollback methods can be
called explicitly.

  1. user_trans = user_store.transaction()
  2. try:
  3. users = user_trans.get_many([1, 2])
  4. users[1]['name'] = 'Updated Name'
  5. users[2].delete()
  6. user_trans.commit()
  7. except Exception:
  8. user_trans.rollback()