0

Consider the following piece of code

import peewee

SQL_CONN = peewee.MySQLDatabase(database=SQL_DATA,
                                host=SQL_HOST,
                                port=SQL_PORT,
                                user=SQL_USER,
                                passwd=SQL_PASS)

class User(peewee.Model):
    name = peewee.CharField(max_length=100, primary_key=True)

    born = peewee.DateTimeField()

print(SQL_CONN.is_closed()) # True

print(User.select().where(User.name == "Jack").execute()) # Silently opens a connection w/o letting me know

print(SQL_CONN.is_closed()) # False

This will automatically perform SQL_CONN.connect() under the hood.

How do I disable this functionality - force peewee to just throw exceptions if the database is not connected - as opposed to automatically connecting to it without letting me know.

AlanSTACK
  • 5,525
  • 3
  • 40
  • 99

1 Answers1

0

First off, your example is fake and wrong. Peewee does not open a connection when you merely create a query object. Check it out:

In [1]: from peewee import *                                                                    

In [2]: db = SqliteDatabase(':memory:')                                                         

In [3]: class User(Model): 
   ...:     username = TextField() 
   ...:     class Meta: 
   ...:         database = db 
   ...:                                                                                         

In [4]: db.is_closed()  # Should be True.                                                       
Out[4]: True

In [5]: query = User.select().where(User.username == 'charlie')                                 

In [6]: db.is_closed()  # Still TRUE, we haven't evaluated anything yet!
Out[6]: True

So, first off, your example is not even correct. You would have to evaluate the query for it to execute.

To answer the rest of this question:

Peewee doesn't provide a mechanism to disallow implicit connections. If you attempt to execute a query, Peewee will open the connection if it does not exist.

I'd suggest that it should be very clear when you execute a query, and hence - when you need to open a connection. If that's not enough, then subclass and override the Database.cursor() method.


EDIT:

Even though nobody has asked for this before, it's such a simple thing to implement that I've added this functionality to Peewee. Will be contained in the next release.

coleifer
  • 24,887
  • 6
  • 60
  • 75
  • Thanks for the help! I have modified the faulty example to include `.execute()`. – AlanSTACK Jun 24 '19 at 03:29
  • "Even though nobody has asked for this before". not true - we argued extensively about this exact feature circa 2015. but glad to see it! =D doc link: https://docs.peewee-orm.com/en/latest/peewee/database.html#using-autoconnect – keredson May 28 '21 at 20:19