<?php
// $Id: image_attach.install,v 1.1.4.8 2007/11/18 21:27:40 drewish Exp $

function image_attach_install() {
  switch ($GLOBALS['db_type']) {
    case 'mysqli':
    case 'mysql':
      db_query("CREATE TABLE {image_attach} (
        nid int(10) unsigned NOT NULL default '0',
        iid int(10) unsigned NOT NULL default '0',
        PRIMARY KEY  (nid),
        KEY (iid)
      ) /*!40100 DEFAULT CHARACTER SET utf8 */;");
      break;

    case 'pgsql':
      db_query("CREATE TABLE {image_attach} (
        nid integer NOT NULL default '0',
        iid integer NOT NULL default '0',
        PRIMARY KEY (nid)
      )");
      db_query("CREATE INDEX {image_attach}_iid_idx ON {image_attach}(iid)");
      break;
  }
}

function image_attach_uninstall() {
  db_query('DROP TABLE {image_attach}');
  variable_del('image_attach_existing');
  variable_del('image_attach_block_0_size');
}

/**
 * Add an index to the image id field.
 */
function image_attach_update_1() {
  $ret = array();
  switch ($GLOBALS['db_type']) {
    case 'mysql':
    case 'mysqli':
      $ret[] = update_sql("ALTER TABLE {image_attach} ADD KEY (iid)");
      break;

    case 'pgsql':
      $ret[] = update_sql("CREATE INDEX {image_attach}_iid_idx ON {image_attach}(iid)");
      break;
  }
  return $ret;
}

/**
 * Remove attach records that point to a missing image.
 */
function image_attach_update_2() {
  $ret = array();
  switch ($GLOBALS['db_type']) {
    case 'mysqli':
    case 'mysql':
      $ret[] = update_sql("DELETE FROM {image_attach} USING {image_attach} LEFT JOIN {node} n ON {image_attach}.iid = n.nid WHERE n.nid IS NULL OR n.type != 'image'");
      break;

    case 'pgsql':
      $ret[] = update_sql("DELETE FROM {image_attach} USING {node} n WHERE {image_attach}.iid = n.nid AND (n.nid IS NULL OR n.type != 'image')");
      break;
  }
  return $ret;
}
