Skip to main content

A lightweight key-value database written in Python, intended for use with Kybra on the Internet Computer (IC)

Project description

Kybra Simple DB

A lightweight key-value database with entity relationships and audit logging capabilities, intended for small to medium-sized applications running on the Internet Computer using Kybra.

Test on IC Test PyPI version Python 3.10 License

Features

  • Persistent Storage: Works with Kybra's StableBTreeMap stable structure for persistent storage on your canister's stable memory so your data persists automatically across canister upgrades.
  • Entity-Relational Database: Create, read and write entities with OneToOne, OneToMany, ManyToOne, and ManyToMany relationships.
  • Audit Logging: Track all changes to your data with created/updated timestamps and who created and updated each entity.
  • Ownership: Assign owners to your data objects to control who can modify them.

Installation

pip install kybra-simple-db

Quick Start

The database storage must be initialized before using Kybra Simple DB. Here's an example of how to do it:

from kybra import StableBTreeMap
from kybra_simple_db import Database

# Initialize storage and database
storage = StableBTreeMap[str, str](memory_id=1, max_key_size=100, max_value_size=1000)  # Use a unique memory ID for each storage instance
Database(storage, audit_enabled=True)

Read Kybra's documentation for more information regarding StableBTreeMap and memory IDs.

Next, define your entities:

from kybra_simple_db import (
    Database, Entity, String, Integer,
    OneToOne, OneToMany, ManyToOne, ManyToMany, TimestampedMixin
)

class Person(Entity, TimestampedMixin):
    name = String(min_length=2, max_length=50)
    age = Integer(min_value=0, max_value=120)
    friends = ManyToMany("Person", "friends")
    mother = ManyToOne("Person", "children")
    children = OneToMany("Person", "mother")
    spouse = OneToOne("Person", "spouse")

Then use the defined entities to store objects:

    # Create and save an object
    john = Person(name="John", age=30)

    # Update an object's property
    john.age = 33  # Type checking and validation happens automatically

    # use the `_id` property to load an entity with the [] operator
    Person(_id="peter", name="Peter")
    peter = Person["peter"]

    # Delete an object
    peter.delete()

    # Create relationships
    alice = Person(name="Alice")
    eva = Person(name="Eva")
    john.mother = alice
    assert john in alice.children
    eva.friends = [alice]
    assert alice in eva.friends
    assert eva in alice.friends

    pprint(alice.to_dict())  # Prints the dictionary representation of an object
    ''' Prints:

    {'_id': '2',
    '_type': 'Person',
    'age': None,
    'creator': 'system',
    'name': 'Alice',
    'owner': 'system',
    'relations': {'children': [{'_id': '1', '_type': 'Person'}],
                'friends': [{'_id': '3', '_type': 'Person'}]},
    'timestamp_created': '2025-04-08 20:45:08.957',
    'timestamp_updated': '2025-04-08 20:45:08.957',
    'updater': 'system'}

    '''

    # Retrieve database contents in JSON format
    print(Database.get_instance().dump_json(pretty=True))

    # Audit log
    audit_records = Database.get_instance().get_audit(id_from=0, id_to=5)
    pprint(audit_records['0'])
    ''' Prints:

    ['save',
    1744138342934,
    'Person@1',
    {'_id': '1',
    '_type': 'Person',
    'age': 30,
    'creator': 'system',
    'name': 'John',
    'owner': 'system',
    'timestamp_created': '2025-04-08 20:52:22.934',
    'timestamp_updated': '2025-04-08 20:52:22.934',
    'updater': 'system'}]

    '''

API Reference

  • Core: Database, Entity
  • Properties: String, Integer, Float, Boolean
  • Relationships: OneToOne, OneToMany, ManyToOne, ManyToMany
  • Mixins: TimestampedMixin (timestamps and ownership tracking)

Development

Setup Development Environment

# Clone the repository
git clone https://github.com/smart-social-contracts/kybra-simple-db.git
cd kybra-simple-db

# Recommended setup
pyenv install 3.10.7
pyenv local 3.10.7
python -m venv venv
source venv/bin/activate

# Install development dependencies
pip install -r requirements-dev.txt

# Running tests
./run_linters.sh && (cd tests && ./run_test.sh && ./run_test_ic.sh)

Contributing

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

License

MIT.

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

kybra_simple_db-0.1.7.tar.gz (18.3 kB view details)

Uploaded Source

Built Distribution

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

kybra_simple_db-0.1.7-py3-none-any.whl (17.9 kB view details)

Uploaded Python 3

File details

Details for the file kybra_simple_db-0.1.7.tar.gz.

File metadata

  • Download URL: kybra_simple_db-0.1.7.tar.gz
  • Upload date:
  • Size: 18.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.10.16

File hashes

Hashes for kybra_simple_db-0.1.7.tar.gz
Algorithm Hash digest
SHA256 a0da1849ca8ed8662b6d14fa2e8b4c5aff2e19f272a4dc4bcb258848e2df9b0b
MD5 9e65d33bced472e4198d8f7c1d84cf4a
BLAKE2b-256 535aa6c02c51a2d3864402ae4c7d93d1290f88ef0bd355f67425504ec64069b4

See more details on using hashes here.

File details

Details for the file kybra_simple_db-0.1.7-py3-none-any.whl.

File metadata

File hashes

Hashes for kybra_simple_db-0.1.7-py3-none-any.whl
Algorithm Hash digest
SHA256 a735cbeecdbfc52126a187b76ecea41d01b3870f87f1ac941bc580c5d9a91491
MD5 d6a696c60ec20e0a58b9e9aaee355419
BLAKE2b-256 17ef24e4051a1ced765c893cbe75ef08591a29eafeea496fc519f7828c711a08

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