How to tell which Rails task is running, or hook specific tasks

I have some code I want to run when the Rails server starts, and also when running any task that requires a database. So for example, this code should run on rails server and rails db:create, but not on rails assets:precompile.

Currently I’m doing this in configuration, which runs on all tasks.

Is there a way to detect from the vantage point of configuration, or initializers, if a task is being run and if so which task it is?

Alternatively, is there a better way to “hook” tasks to run some other code before they run?

Edit: Or, seeing as this is database-specific, is there a way to hook ActiveRecord and do something before it connects to a database for the first time?