Where are templates from hook_theme stored in the database I have a module, called "bundles", there I created a file "attached_email.tpl.php" and a hook_theme:

function bundles_theme($existing, $type, $theme, $path)
{
    $path = drupal_get_path('module', 'bundles');

    return array(
        'attached_email' =&gt; array(
            'template' =&gt; 'attached_email',
            'path' =&gt; $path,
            ),
        );
}


I have 2 databases for this website: lwt (default) and lwt_test (for test data). I have written the template, cleared caches and imported test data into lwt_test DB. But the template is unavailable there. When I call:

theme('attached_email', $data);


From lwt database, it gives the output. But when I switch to lwt_test:

db_set_active('lwt_test');


nothing is given. I can only conclude, that there is some piece of data, stored in lwt database, missing in lwt_test database. And that's why Drupal doesn't see my new template.

Update

When I use this code:

print theme('attached_email');
db_set_active('lwt_test');
send_attached_emails($bundle_id, $users);
db_set_active();


It gives the correct result (probably the template is cached after the 1-st call).
Normally, db_set_active() is used to query external data.  I have never heard about it being used to switch between two full Drupal databases from within the same active codebase / website.

I suspect one or two things is happening: you are having cache problems and/or you are having registry problems.

When you clear caches via the UI or drush, the full registry gets rebuilt, which includes theme functions and their template files.  That information will get stored in whatever database is active at the time.

If you switch databases, the cache and registry will be pulled from the newly active database.   In addition, any new cache entries will be written to the new database.

So, I think your problem is that the wrong cache and/or the wrong registry is being queried when you use the Drupal API and you are getting stale data.

The proper way to accomplish this is to set up a dev/staging/live environment, where code goes forward from dev -> staging -> live, and databases go backwards from live -> staging -> dev.  There are lots of articles on the net, and a few questions here, about how to do this.