Search code examples
pythonpeewee

With peewee how connect to existing SQLite db for reading only


I have a silly question.

This my code:

  from peewee import *

   db = SqliteDatabase(None)

   class Base(Model):
       class Meta:
           database = db

   class Table(Base):
       a_date = DateField()
       url = CharField()

   def __main()__
       parser = argparse.ArgumentParser()
       parser.add_argument('--db-dir', action='store')
       args = parser.parse_args()
       db_path = os.path.join(args.db_dir, 'data.db')
       try:
           db.init(db_path)
           db.connect()
           query = Table.select().order_by(Table.a_date.desc()).get()   
       except Exception:
           sys.exit(1)
       else:
           print(query.url)

       sys.exit(0)


   if __name__ == '__main__':
       main()

This code is working fine, but if the file db not exist db.connect always create it. How I can prevent this ?

Another question is , How can query table database for this field without declare the peewee Model?

Thanks


Solution

  • If I understand correctly peewee doc (http://docs.peewee-orm.com/en/latest/peewee/database.html), they use the api provided by python in order to connect to sqlite.

    Which means you have to deal with this api (https://docs.python.org/2/library/sqlite3.html#sqlite3.connect), and the connect method always create the database beforehand.

    I however believe that you can pass a custom Connection class to this method (parameter factory), you could define your behaviour in this custom class.

    import os
    
    from sqlite3 import Connection
    from peewee import *
    
    class CustomConnection(Connection):
        def __init__(self, dbname, *args, **kwargs):
            # Check if db already exists or not
            if not os.path.exists(dbname):
                raise ValueError('DB {} does not exist'.format(dbname))
            super(CustomConnection, self).__init__(dbname, *args, **kwargs)
    
    db = SqliteDatabase('mydatabase', factory=CustomConnection)