Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I somehow query all the existing tables in peewee / postgres?

Tags:

python

peewee

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?

like image 850
handris Avatar asked Dec 10 '22 15:12

handris


1 Answers

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:

  • Database.get_tables()
  • Database.get_columns()
  • Database.get_indexes()
  • Database.get_primary_keys()
  • Database.get_foreign_keys()

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.

like image 84
coleifer Avatar answered Jan 12 '23 00:01

coleifer