Issue: Spurious SQL queries when creating tables
Author: acepace
State: closed
Created: 2020-10-08 15:55:08

The following code snippet creates an invalid SELECT query before creating tables, causing create_tables to fail.


```
    psycopg2.extras.register_default_jsonb()
    database = PostgresqlExtDatabase('postgres', user=options.username,
                                     password=options.password, host=options.database_host)
    # hack to handle JSONB properly and handle sqlite DBs :(
    for entity in all_tables:
        # peewee author says this is the best way to iterate over a models fields
        fields = entity._meta.sorted_fields
        for field in fields:
            if isinstance(field, JSONField):
                new_field = BinaryJSONField(null=True)
                entity._meta.add_field(field.name, new_field)

    ext_db.initialize(database)
    database.create_tables([CIRun, Application, ApplicationRun])
```

Before the create table queries are run, the following queries are run, the second causes the transaction to be aborted.

```
peewee.execute_sql: ('SELECT tablename FROM pg_catalog.pg_tables WHERE schemaname = %s ORDER BY tablename', ('public',))
peewee.execute_sql: ('SELECT COUNT(1) FROM (SELECT 1 FROM "application" AS "t1") AS "_wrapped"', [])
peewee.execute_sql: ('SELECT COUNT(1) FROM (SELECT 1 FROM "application" AS "t1") AS "_wrapped"', [])
peewee.execute_sql: ('SELECT COUNT(1) FROM (SELECT 1 FROM "application" AS "t1") AS "_wrapped"', [])
peewee.execute_sql: ('SELECT COUNT(1) FROM (SELECT 1 FROM "application" AS "t1") AS "_wrapped"', [])
```

The query seems to originate from `sort_models`

```
 names = lambda m: (m._meta.name, m._meta.table_name)
    for m in sorted(models, key=names):
```

But I'm not sure why




```python

from peewee import *                                                                                                 

db = SqliteDatabase(':memory:')

import logging
logger = logging.getLogger('peewee')
logger.addHandler(logging.StreamHandler())
logger.setLevel(logging.DEBUG)

class Base(Model):
    class Meta:
        database = db

class A(Base):
    a = TextField()
class B(Base):
    a = ForeignKeyField(A)
    b = TextField()
class C(Base):
    b = ForeignKeyField(B)
    c = TextField()

all_tables = [A, B, C]
for table in all_tables:
    table._meta.sorted_fields
    table._meta.add_field('test', TextField())

db.create_tables(all_tables)
```

Output:

```
('CREATE TABLE IF NOT EXISTS "a" ("id" INTEGER NOT NULL PRIMARY KEY, "a" TEXT NOT NULL, "test" TEXT NOT NULL)', [])  
('CREATE TABLE IF NOT EXISTS "b" ("id" INTEGER NOT NULL PRIMARY KEY, "a_id" INTEGER NOT NULL, "b" TEXT NOT NULL, "test" TEXT NOT NULL, FOREIGN KEY ("a_id") REFERENCES "a" ("id"))', [])
('CREATE INDEX IF NOT EXISTS "b_a_id" ON "b" ("a_id")', [])                                                          
('CREATE TABLE IF NOT EXISTS "c" ("id" INTEGER NOT NULL PRIMARY KEY, "b_id" INTEGER NOT NULL, "c" TEXT NOT NULL, "test" TEXT NOT NULL, FOREIGN KEY ("b_id") REFERENCES "b" ("id"))', [])
('CREATE INDEX IF NOT EXISTS "c_b_id" ON "c" ("b_id")', [])
```