coleifer / peewee

a small, expressive orm -- supports postgresql, mysql, sqlite and cockroachdb
http://docs.peewee-orm.com/
MIT License
11.06k stars 1.37k forks source link

Bind schema - similar to how we can bind database to a model #2904

Closed mikebski closed 3 months ago

mikebski commented 3 months ago

(note - edited to fix typo in snippet)

How can I dynamically bind a schema, similar to binding a model:

db = PooledPostgresqlExtDatabase(
    cfg_db, max_connections=8,
    stale_timeout=300,
    user=cfg_user, password=cfg_password,
    host=cfg_host, port=cfg_port
)

db.bind([BaseModel])

# How do I set the schema for base model here??
coleifer commented 3 months ago

I don't know what you mean by "set the schema", but if you mean changing it from the default ("public") to something else, you should be able to just:

ModelClass._meta.schema = 'schema_name'

You'll need to do this for all the models you wish to modify.

coleifer commented 3 months ago

You can also use the SubclassAwareMetadata to make this process more simple, e.g.:

class Base(Model):
    class Meta:
        model_metadata_class = SubclassAwareMetadata
        database = db

...

# Apply the schema to all subclasses of `Base`.
def set_schema(name):
    def _update(m):
        m._meta.schema = name
    return _update

Base._meta.map_models(set_schema('schema_name'))