﻿id	summary	reporter	owner	description	type	status	component	version	severity	resolution	keywords	cc	stage	has_patch	needs_docs	needs_tests	needs_better_patch	easy	ui_ux
34874	Add table_exists() to optimize checks for django_migrations table.	Pierre	nobody	"On databases with a lot of tables, even in several schemas (with django-tenant-schema for instance), the `introspection.table_names()` call can take tens of ms to run. For instance on a PG database with 8800 relations, the query takes 21ms.
table_names() is called at least by the migration recorder in order to verify the presence of the django_migrations table. It thus slows down every migration execution uselessly.
Fixing the migrations recorder to keep the information cached would be a quick work around this, but it would still execute the long query at least once, but especially with django-tenant-schema it would end up taking tens of seconds (at least one call per tenant).

I suggest adding an `table_exists(table_name)` function in db.introspection. Its base implementation could be simply a `return table_name in self.table_names()`, but specific DB engines like PostgreSQL could have an optimized variant.
The SQL query from table_names function modified to add a `relname = 'XXX'` criteria uses the index on relname and is thus over 20 times faster."	Cleanup/optimization	closed	Database layer (models, ORM)	4.2	Normal	wontfix			Unreviewed	0	0	0	0	0	0
