4.5. ORM functionalityΒΆ

Sample Code
from simplesqlite import connect_memdb
from simplesqlite.model import Integer, Model, Real, Text


class Sample(Model):
    foo_id = Integer(primary_key=True)
    name = Text(not_null=True, unique=True)
    value = Real()


def main():
    con = connect_memdb()

    Sample.attach(con)
    Sample.create()
    Sample.insert(Sample(name="abc", value=0.1))
    Sample.insert(Sample(name="xyz", value=1.11))
    Sample.insert(Sample(name="bar", value=2.22))

    print(Sample.fetch_schema().dumps())
    print("records:")
    for record in Sample.select():
        print("    {}".format(record))

    return 0


if __name__ == "__main__":
    sys.exit(main())
Output
.. table:: sample

    +---------+-------+-----------+--------+------+-----+
    |Attribute| Type  |PRIMARY KEY|NOT NULL|UNIQUE|Index|
    +=========+=======+===========+========+======+=====+
    |foo_id   |INTEGER|X          |        |      |     |
    +---------+-------+-----------+--------+------+-----+
    |name     |TEXT   |           |X       |X     |     |
    +---------+-------+-----------+--------+------+-----+
    |value    |REAL   |           |        |      |     |
    +---------+-------+-----------+--------+------+-----+


records:
    Sample: foo_id=1, name=abc, value=0.1
    Sample: foo_id=2, name=xyz, value=1.11
    Sample: foo_id=3, name=bar, value=2.22