Make WordPress Core

Opened 3 weeks ago

Last modified 3 weeks ago

#58344 new enhancement

Connect to database on first query

Reported by: spacedmonkey's profile spacedmonkey Owned by:
Milestone: Awaiting Review Priority: normal
Severity: normal Version:
Component: Database Keywords:
Focuses: performance Cc:


Currently there is the database connection is made in __construct method by calling db_connect method. However with sites with persistent object caching enabled, this connection to the database may not be needed. It is common now for requests to have no database queries at all if persistent object caching is setup.

Moving the db_connect call to the query method like this.

        public function query( $query ) {
                if ( ! $this->has_connected ) {
                if ( ! $this->ready ) {
                        $this->check_current_query = true;
                        return false;

Change History (3)

#1 @spacedmonkey
3 weeks ago

Would love the thoughts of @johnjamesjacoby @johnbillion on this one.

#2 @johnbillion
3 weeks ago

  • Version 0.71 deleted

I pointed this out 11 years ago in #19372 but never followed up :D

If it's simple enough to achieve and has a performance benefit then I'm in favour.

#3 @dd32
3 weeks ago

One edge-case to consider is that currently WordPress will exit with a Site Unavailable type error when the DB is unavailable, with this potential change if the query isn't made until the Footer or mid-post-render the page may partially render before hitting a wp_die() condition (As you don't really want to return empty result-sets in the event of a DB-down scenario).

However, plugins like HyperDB and others do delay the DB connect until a query is made, so this might not be an actual issue that needs consideration.

That being said, If a persistent object cache is not in play, delaying until the first query will have very little change for most sites and scenario's.

Note: See TracTickets for help on using tickets.