bernardopires / django-tenant-schemas

Tenant support for Django using PostgreSQL schemas.
https://django-tenant-schemas.readthedocs.org/en/latest/
MIT License
1.45k stars 425 forks source link

Is there a way to get the schema being executed in migrate_schemas? #653

Closed andyp05 closed 3 years ago

andyp05 commented 3 years ago

I am trying to create a trigger and I have added the raw sql to the migration file.

migrations.RunSQL('CREATE TRIGGER audit_table AFTER INSERT OR UPDATE OR DELETE ON...')

This runs fine when I run migrate_schemas. The problem is that postgreSQL has an issue during manual update of the tables such as in pgAdmin because the trigger does not have the schema name defined with it. PostgreSQL wants:

CREATE TRIGGER SCHEMA.audit_table AFTER INSERT OR UPDATE OR DELETE ON...

How do I get the schema name to be visible in the migration.py file so I can append it to the SQL?

Thanks for any suggestions.

jeroenbrouwer commented 3 years ago

You could use migrations.RunPython. Then you can use the schema_editor.connection to get the current connection, grab the schema name with connection.schema_name, format your raw sql and use connection.cursor().execute(raw_sql) to run your sql.

Just pass in the function like the forwards_func as in the docs: https://docs.djangoproject.com/en/3.1/ref/migration-operations/#runpython

andyp05 commented 3 years ago

Forgot to close. Thanks for the answer.