xppl/test.py

77 lines
2.0 KiB
Python
Raw Normal View History

2018-06-01 20:26:37 +02:00
#!/usr/bin/env python
import argparse
import functools
import logging
import pyrqlite.dbapi2 as dbapi2
#import sqlite3 as dbapi2
2018-05-31 17:30:16 +02:00
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, relationship
2018-06-01 20:26:37 +02:00
from sqlalchemy.orm import Session
from sqlalchemy import Table, Column, Integer, String, ForeignKey, Sequence, create_engine
from sqlalchemy.dialects import registry
registry.register("rqlite.pyrqlite", "sqlalchemy_rqlite.pyrqlite", "dialect")
2018-05-31 17:30:16 +02:00
Base = declarative_base()
2018-06-01 20:26:37 +02:00
books_authors = Table(
"books_authors",
2018-05-31 17:30:16 +02:00
Base.metadata,
2018-06-01 20:26:37 +02:00
Column("book", Integer, ForeignKey("books.id")),
Column("author", Integer, ForeignKey("authors.id")),
2018-05-31 17:30:16 +02:00
)
2018-06-01 20:26:37 +02:00
class Book(Base):
__tablename__ = 'books'
id = Column(Integer, primary_key=True)
title = Column("title", String(50), nullable=False)
authors = relationship(
"Author",
backref="books",
secondary=books_authors
)
def __init__(self, title):
self.title = title
class Author(Base):
__tablename__ = "authors"
id = Column("id", Integer, Sequence("authors_id_seq"), primary_key=True)
2018-05-31 17:30:16 +02:00
name = Column("name", String(50), nullable=False)
2018-06-01 20:26:37 +02:00
def __init__(self, title):
self.name = name
2018-05-31 17:30:16 +02:00
2018-06-01 20:26:37 +02:00
def main():
parser = argparse.ArgumentParser()
parser.add_argument('-v', '--verbose', action='store_true', default=False)
args = parser.parse_args()
2018-05-31 17:30:16 +02:00
2018-06-01 20:26:37 +02:00
if args.verbose:
logging.basicConfig()
logging.getLogger().setLevel(logging.DEBUG)
2018-05-31 17:30:16 +02:00
2018-06-01 20:26:37 +02:00
engine = create_engine('rqlite+pyrqlite://localhost:4001/', echo=args.verbose)
2018-05-31 17:30:16 +02:00
2018-06-01 20:26:37 +02:00
Base.metadata.create_all(engine)
session = Session(engine)
2018-05-31 17:30:16 +02:00
2018-06-01 20:26:37 +02:00
#insert
# for i in range(1):
# book = Book("book about dbs2")
# author = Author("footurist")
# book.authors.append(author)
# session.add(book)
# session.commit()
2018-05-31 17:30:16 +02:00
2018-06-01 20:26:37 +02:00
#delete
desired_book = session.query(Book).filter_by(id=3).delete()
#desired_author = session.query(Author).filter_by(id=2).first()
#desired_book.authors.clear()
#desired_book.authors.append(desired_author)
session.commit()
2018-05-31 17:30:16 +02:00
2018-06-01 20:26:37 +02:00
if __name__ == '__main__':
main()