6

I am writing a basic gui for a program which uses Peewee. In the gui, I would like to show all the tables which exist in my database.

Is there any way to get the names of all existing tables, lets say in a list?

handris
  • 1,999
  • 8
  • 27
  • 41
  • 1
    If you already have your connection established, run `SELECT table_name FROM information_schema.tables WHERE table_schema='public'` to get the table names in your schema. That should return a list of 1-element tuples. – Abdou Jul 27 '16 at 17:55

2 Answers2

16

Peewee has the ability to introspect Postgres, MySQL and SQLite for the following types of schema information:

  • Table names
  • Columns (name, data type, null?, primary key?, table)
  • Primary keys (column(s))
  • Foreign keys (column, dest table, dest column, table)
  • Indexes (name, sql*, columns, unique?, table)

You can get this metadata using the following methods on the Database class:

So, instead of using a cursor and writing some SQL yourself, just do:

db = PostgresqlDatabase('my_db')
tables = db.get_tables()

For even more craziness, check out the reflection module, which can actually generate Peewee model classes from an existing database schema.

coleifer
  • 24,887
  • 6
  • 60
  • 75
0

To get a list of the tables in your schema, make sure that you have established your connection and cursor and try the following:

cursor.execute("SELECT table_name FROM information_schema.tables WHERE table_schema='public'")
myables = cursor.fetchall()
mytables = [x[0] for x in mytables]

I hope this helps.

Abdou
  • 12,931
  • 4
  • 39
  • 42
  • This is really not the best way to do this with Peewee. Much better would be to use the "database.get_tables()" function. – coleifer Aug 02 '16 at 08:07
  • @coleifer I understand the change of answers but what's with the downvote? – Abdou Aug 02 '16 at 10:48