Programmatic node creation, Drupal 6 and the drupal_get_schema() function

June 16, 2008

While working on importing a bunch of content from an old Drupal site to a new one, I discovered a little gotcha with the D6 database schema functionality. The method I was using involved loading a bunch of nodes from the old database via a call to db_set_active(), followed by a series of calls to node_load(). Once I had the nodes in an array, I switch to the new db via another call to db_set_active and store the nodes via node_save().

The problem arose due to the fact that Drupal is caching database schema information. Thus, during the node load phase, CCK attempts to load up information on a table that doesn't exist, and the result is cached. When back in the new database, where the table really does exist, the cached schema thinks it doesn't.

The solution was to clear the database schema cache every time I switched back to a different database:

function import_old_set_db($db = 'default') {
  db_set_active($db);
 
  // clear schema
  drupal_get_schema(NULL, TRUE);
}

The key in the above function, which I used as a wrapper to db_set_active() in my import script, is the call to the drupal_get_schema() function, which clears the cached database schema information.

This was a viable solution because this is a one-time import script where performance really isn't an issue. It would not be recommended for production sites when regularly switching between databases during normal page loads.

Comments

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>. Beside the tag style "<foo>" it is also possible to use "[foo]".
  • Glossary terms will be automatically marked with links to their descriptions. If there are certain phrases or sections of text that should be excluded from glossary marking and linking, use the special markup, [no-glossary] ... [/no-glossary]. Additionally, these HTML elements will not be scanned: a, abbr, acronym, code, pre.

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Copy the characters (respecting upper/lower case) from the image.