Reflection

The reflection module contains helpers for introspecting existing databases.This module is used internally by several other modules in the playhouse,including DataSet and pwiz, a model generator.

  • generatemodels(_database[, schema=None[, **options]])

Parameters:

  • database (Database) – database instance to introspect.
  • schema (str) – optional schema to introspect.
  • options – arbitrary options, see Introspector.generate_models() for details.Returns:a dict mapping table names to model classes.

Generate models for the tables in the given database. For an example of howto use this function, see the section Using Peewee Interactively.

Example:

  1. >>> from peewee import *
  2. >>> from playhouse.reflection import generate_models
  3. >>> db = PostgresqlDatabase('my_app')
  4. >>> models = generate_models(db)
  5. >>> list(models.keys())
  6. ['account', 'customer', 'order', 'orderitem', 'product']
  7.  
  8. >>> globals().update(models) # Inject models into namespace.
  9. >>> for cust in customer.select(): # Query using generated model.
  10. ... print(cust.name)
  11. ...
  12.  
  13. Huey Kitty
  14. Mickey Dog
  • printmodel(_model)

Parameters:model (Model) – model class to printReturns:no return value

Print a user-friendly description of a model class, useful for debugging orinteractive use. Currently this prints the table name, and all fields alongwith their data-types. The Using Peewee Interactively section contains an example.

Example output:

  1. >>> from playhouse.reflection import print_model
  2. >>> print_model(User)
  3. user
  4. id AUTO PK
  5. email TEXT
  6. name TEXT
  7. dob DATE
  8.  
  9. index(es)
  10. email UNIQUE
  11.  
  12. >>> print_model(Tweet)
  13. tweet
  14. id AUTO PK
  15. user INT FK: User.id
  16. title TEXT
  17. content TEXT
  18. timestamp DATETIME
  19. is_published BOOL
  20.  
  21. index(es)
  22. user_id
  23. is_published, timestamp
  • printtable_sql(_model)

Parameters:model (Model) – model to printReturns:no return value

Prints the SQL CREATE TABLE for the given model class, which may beuseful for debugging or interactive use. See the Using Peewee Interactively sectionfor example usage. Note that indexes and constraints are not included inthe output of this function.

Example output:

  1. >>> from playhouse.reflection import print_table_sql
  2. >>> print_table_sql(User)
  3. CREATE TABLE IF NOT EXISTS "user" (
  4. "id" INTEGER NOT NULL PRIMARY KEY,
  5. "email" TEXT NOT NULL,
  6. "name" TEXT NOT NULL,
  7. "dob" DATE NOT NULL
  8. )
  9.  
  10. >>> print_table_sql(Tweet)
  11. CREATE TABLE IF NOT EXISTS "tweet" (
  12. "id" INTEGER NOT NULL PRIMARY KEY,
  13. "user_id" INTEGER NOT NULL,
  14. "title" TEXT NOT NULL,
  15. "content" TEXT NOT NULL,
  16. "timestamp" DATETIME NOT NULL,
  17. "is_published" INTEGER NOT NULL,
  18. FOREIGN KEY ("user_id") REFERENCES "user" ("id")
  19. )
  • class Introspector(metadata[, schema=None])
  • Metadata can be extracted from a database by instantiating anIntrospector. Rather than instantiating this class directly, itis recommended to use the factory methodfrom_database().

    • classmethod fromdatabase(_database[, schema=None])

Parameters:

  1. - **database** a [<code>Database</code>]($91d5d4e449d7d4b4.md#Database) instance.
  2. - **schema** (_str_) an optional schema (supported by some databases).

Creates an Introspector instance suitable for use with thegiven database.

Usage:

  1. db = SqliteDatabase('my_app.db')
  2. introspector = Introspector.from_database(db)
  3. models = introspector.generate_models()
  4.  
  5. # User and Tweet (assumed to exist in the database) are
  6. # peewee Model classes generated from the database schema.
  7. User = models['user']
  8. Tweet = models['tweet']
  • generatemodels([_skip_invalid=False[, table_names=None[, literal_column_names=False[, bare_fields=False[, include_views=False]]]]])

Parameters:

  1. - **skip_invalid** (_bool_) Skip tables whose names are invalid pythonidentifiers.
  2. - **table_names** (_list_) List of table names to generate. Ifunspecified, models are generated for all tables.
  3. - **literal_column_names** (_bool_) Use column-names as-is. By default,column names are python-ized”, i.e. mixed-case becomes lower-case.
  4. - **bare_fields** **SQLite-only**. Do not specify data-types forintrospected columns.
  5. - **include_views** generate models for VIEWs as well.Returns:

A dictionary mapping table-names to model classes.

Introspect the database, reading in the tables, columns, and foreignkey constraints, then generate a dictionary mapping each database tableto a dynamically-generated Model class.