/*
 * The contents of this file are subject to the Mozilla Public License Version 1.1
 * (the "License"); you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
 * 
 * Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
 * WARRANTY OF ANY KIND, either express or implied. See the License for the specific
 * language governing rights and limitations under the License.
 * 
 * The Original Code is the Venice Web Communities System.
 * 
 * The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
 * for Silverwrist Design Studios.  Portions created by Eric J. Bowersox are
 * Copyright (C) 2003 Eric J. Bowersox/Silverwrist Design Studios.  All Rights Reserved.
 * 
 * Contributor(s): 
 */
package com.silverwrist.dynamo.unistore;

import java.io.*;
import java.sql.*;
import java.util.*;
import com.silverwrist.util.*;
import com.silverwrist.dynamo.except.*;
import com.silverwrist.dynamo.iface.*;
import com.silverwrist.dynamo.util.*;

class MessageOps_mysql extends MessageOps
{
  /*--------------------------------------------------------------------------------
   * Attributes
   *--------------------------------------------------------------------------------
   */

  private PropertySerializer m_psz;        // reference to property serializer
  private DBUtilities m_utils;

  /*--------------------------------------------------------------------------------
   * Constructor
   *--------------------------------------------------------------------------------
   */

  MessageOps_mysql(DBConnectionPool pool)
  {
    super(pool);
    m_psz = (PropertySerializer)(pool.queryService(PropertySerializer.class));
    m_utils = (DBUtilities)(pool.queryService(DBUtilities.class));

  } // end constructor

  /*--------------------------------------------------------------------------------
   * Overrides from class MessageOps
   *--------------------------------------------------------------------------------
   */

  public void dispose()
  {
    m_psz = null;
    m_utils = null;
    super.dispose();

  } // end dispose

  /*--------------------------------------------------------------------------------
   * Abstract operations
   *--------------------------------------------------------------------------------
   */

  protected TextPartOps createTextPartOps(DBConnectionPool pool)
  {
    return new TextPartOps_mysql(pool);

  } // end createTextPartOps

  protected BinaryPartOps createBinaryPartOps(DBConnectionPool pool)
  {
    return new BinaryPartOps_mysql(pool);

  } // end createBinaryPartOps

  Object getProperty(long msgid, PropertyKey key) throws DatabaseException
  {
    Connection conn = null;
    PreparedStatement stmt = null;
    ResultSet rs = null;
    String rc_str = null;
    try
    { // get a connection
      conn = getConnection();

      // look up the property
      stmt = conn.prepareStatement("SELECT prop_value FROM us_prop WHERE msgid = ? AND nsid = ? AND prop_name = ?;");
      stmt.setLong(1,msgid);
      stmt.setInt(2,key.getNamespaceID());
      stmt.setString(3,key.getName());
      rs = stmt.executeQuery();
      if (!(rs.next()))
	return null;  // property not found

      rc_str = rs.getString(1);

    } // end try
    catch (SQLException e)
    { // translate to a general DatabaseException
      throw generalException(e);

    } // end catch
    finally
    { // shut everything down
      SQLUtils.shutdown(rs);
      SQLUtils.shutdown(stmt);
      SQLUtils.shutdown(conn);

    } // end finally

    // Deserialize the property value.
    Object rc = m_psz.deserializeProperty(rc_str);
    if (rc!=null)
      return rc;

    // deserialization exception - throw it
    DatabaseException de = new DatabaseException(MessageOps_mysql.class,"UniStoreMessages","property.deserialize");
    de.setParameter(0,key.getName());
    throw de;

  } // end getProperty

  Object setProperty(long msgid, PropertyKey key, Object value) throws DatabaseException
  {
    String serialized_value = m_psz.serializeProperty(value);
    if (serialized_value==null)
    { // serialization exception - throw it
      DatabaseException de = new DatabaseException(MessageOps_mysql.class,"UniStoreMessages","property.serialize");
      de.setParameter(0,key.getName());
      throw de;

    } // end if

    String old_value = null;
    Connection conn = null;
    PreparedStatement stmt = null;
    Statement stmt2 = null;
    ResultSet rs = null;
    try
    { // get a connection
      conn = getConnection();

      // lock the table
      stmt2 = conn.createStatement();
      stmt2.executeUpdate("LOCK TABLES us_prop WRITE;");

      // look to see if the property value is already there
      stmt = conn.prepareStatement("SELECT prop_value FROM us_prop WHERE msgid = ? AND nsid = ? AND prop_name = ?;");
      stmt.setLong(1,msgid);
      stmt.setInt(2,key.getNamespaceID());
      stmt.setString(3,key.getName());
      rs = stmt.executeQuery();
      if (rs.next())
	old_value = rs.getString(1);
      SQLUtils.shutdown(rs);
      rs = null;
      SQLUtils.shutdown(stmt);

      if (old_value!=null)
      { // prepare the statement to update the existing record
	stmt = conn.prepareStatement("UPDATE us_prop SET prop_value = ? WHERE msgid = ? AND nsid = ? "
				     + "AND prop_name = ?;");
	stmt.setString(1,serialized_value);
	stmt.setLong(2,msgid);
	stmt.setInt(3,key.getNamespaceID());
	stmt.setString(4,key.getName());

      } // end if
      else
      { // prepare the statement to insert a new record
	stmt = conn.prepareStatement("INSERT INTO us_prop (msgid, nsid, prop_name, prop_value) VALUES (?, ?, ?, ?);");
	stmt.setLong(1,msgid);
	stmt.setInt(2,key.getNamespaceID());
	stmt.setString(3,key.getName());
	stmt.setString(4,serialized_value);

      } // end else

      stmt.executeUpdate();  // execute it!

    } // end try
    catch (SQLException e)
    { // translate to a general DatabaseException
      throw generalException(e);

    } // end catch
    finally
    { // shut everything down
      MySQLUtils.unlockTables(conn);
      SQLUtils.shutdown(rs);
      SQLUtils.shutdown(stmt);
      SQLUtils.shutdown(stmt2);
      SQLUtils.shutdown(conn);

    } // end finally

    if (old_value==null)
      return null;  // no previous value

    // Deserialize the property value.
    Object rc = m_psz.deserializeProperty(old_value);
    if (rc!=null)
      return rc;

    // deserialization exception - throw it
    DatabaseException de = new DatabaseException(MessageOps_mysql.class,"UniStoreMessages","property.deserialize");
    de.setParameter(0,key.getName());
    throw de;

  } // end setProperty

  Object removeProperty(long msgid, PropertyKey key) throws DatabaseException
  {
    String old_value = null;
    Connection conn = null;
    PreparedStatement stmt = null;
    Statement stmt2 = null;
    ResultSet rs = null;
    try
    { // get a connection
      conn = getConnection();

      // lock the table
      stmt2 = conn.createStatement();
      stmt2.executeUpdate("LOCK TABLES us_prop WRITE;");

      // look to see if the property value is already there
      stmt = conn.prepareStatement("SELECT prop_value FROM us_prop WHERE msgid = ? AND nsid = ? AND prop_name = ?;");
      stmt.setLong(1,msgid);
      stmt.setInt(2,key.getNamespaceID());
      stmt.setString(3,key.getName());
      rs = stmt.executeQuery();
      if (rs.next())
	old_value = rs.getString(1);
      else
	return null;  // no need to remove anything
      SQLUtils.shutdown(rs);
      rs = null;
      SQLUtils.shutdown(stmt);

      // delete the database row
      stmt = conn.prepareStatement("DELETE FROM us_prop WHERE msgid = ? AND nsid = ? AND prop_name = ?;");
      stmt.setLong(1,msgid);
      stmt.setInt(2,key.getNamespaceID());
      stmt.setString(3,key.getName());
      stmt.executeUpdate();

    } // end try
    catch (SQLException e)
    { // translate to a general DatabaseException
      throw generalException(e);

    } // end catch
    finally
    { // shut everything down
      MySQLUtils.unlockTables(conn);
      SQLUtils.shutdown(rs);
      SQLUtils.shutdown(stmt);
      SQLUtils.shutdown(stmt2);
      SQLUtils.shutdown(conn);

    } // end finally

    // Deserialize the property value.
    Object rc = m_psz.deserializeProperty(old_value);
    if (rc!=null)
      return rc;

    // deserialization exception - throw it
    DatabaseException de = new DatabaseException(MessageOps_mysql.class,"UniStoreMessages","property.deserialize");
    de.setParameter(0,key.getName());
    throw de;

  } // end removeProperty

  int[] getPropertyNamespaceIDs(long msgid) throws DatabaseException
  {
    Connection conn = null;
    PreparedStatement stmt = null;
    ResultSet rs = null;
    try
    { // get a connection
      conn = getConnection();

      // execute the query!
      stmt = conn.prepareStatement("SELECT DISTINCT nsid FROM us_prop WHERE msgid = ?;");
      stmt.setLong(1,msgid);
      rs = stmt.executeQuery();

      // read out a list of the namespace IDs
      ArrayList tmp = new ArrayList();
      while (rs.next())
	tmp.add(new Integer(rs.getInt(1)));

      // create and return the array
      int[] rc = new int[tmp.size()];
      for (int i=0; i<tmp.size(); i++)
	rc[i] = ((Integer)(tmp.get(i))).intValue();
      tmp.clear();
      return rc;

    } // end try
    catch (SQLException e)
    { // translate to a general DatabaseException
      throw generalException(e);

    } // end catch
    finally
    { // shut everything down
      SQLUtils.shutdown(rs);
      SQLUtils.shutdown(stmt);
      SQLUtils.shutdown(conn);

    } // end finally

  } // end getPropertyNamespaceIDs

  Map getAllProperties(long msgid, int namespace) throws DatabaseException
  {
    Connection conn = null;
    PreparedStatement stmt = null;
    ResultSet rs = null;
    try
    { // get a connection
      conn = getConnection();

      // execute the query!
      stmt = conn.prepareStatement("SELECT prop_name, prop_value FROM us_prop WHERE msgid = ? AND nsid = ?;");
      stmt.setLong(1,msgid);
      stmt.setInt(2,namespace);
      rs = stmt.executeQuery();

      // prepare the return value
      HashMap rc = new HashMap();
      while (rs.next())
      { // copy data out, deserializing properties as we go
	String key = rs.getString(1);
	Object value = m_psz.deserializeProperty(rs.getString(2));
	if (value==null)
	{ // deserialization exception - throw it
	  DatabaseException de = new DatabaseException(MessageOps_mysql.class,"UniStoreMessages",
                                                       "property.deserialize");
	  de.setParameter(0,key);
	  throw de;

	} // end if

	rc.put(key,value);

      } // end while

      return rc;

    } // end try
    catch (SQLException e)
    { // translate to a general DatabaseException
      throw generalException(e);

    } // end catch
    finally
    { // shut everything down
      SQLUtils.shutdown(rs);
      SQLUtils.shutdown(stmt);
      SQLUtils.shutdown(conn);

    } // end finally

  } // end getAllProperties

  void setParentMessageID(long msgid, long parent) throws DatabaseException
  {
    Connection conn = null;
    PreparedStatement stmt = null;
    Statement stmt2 = null;
    ResultSet rs = null;
    try
    { // get a connection
      conn = getConnection();

      // lock the table
      stmt2 = conn.createStatement();
      stmt2.executeUpdate("LOCK TABLES us_head WRITE;");

      // update the parent field
      stmt = conn.prepareStatement("UPDATE us_head SET parent = ? WHERE msgid = ?;");
      stmt.setLong(1,parent);
      stmt.setLong(2,msgid);
      stmt.executeUpdate();

    } // end try
    catch (SQLException e)
    { // translate to a general DatabaseException
      throw generalException(e);

    } // end catch
    finally
    { // shut everything down
      MySQLUtils.unlockTables(conn);
      SQLUtils.shutdown(rs);
      SQLUtils.shutdown(stmt);
      SQLUtils.shutdown(stmt2);
      SQLUtils.shutdown(conn);

    } // end finally

  } // end try

  void setSequence(long msgid, int seq) throws DatabaseException
  {
    Connection conn = null;
    PreparedStatement stmt = null;
    Statement stmt2 = null;
    ResultSet rs = null;
    try
    { // get a connection
      conn = getConnection();

      // lock the table
      stmt2 = conn.createStatement();
      stmt2.executeUpdate("LOCK TABLES us_head WRITE;");

      // update the sequence field
      stmt = conn.prepareStatement("UPDATE us_head SET seq = ? WHERE msgid = ?;");
      stmt.setInt(1,seq);
      stmt.setLong(2,msgid);
      stmt.executeUpdate();

    } // end try
    catch (SQLException e)
    { // translate to a general DatabaseException
      throw generalException(e);

    } // end catch
    finally
    { // shut everything down
      MySQLUtils.unlockTables(conn);
      SQLUtils.shutdown(rs);
      SQLUtils.shutdown(stmt);
      SQLUtils.shutdown(stmt2);
      SQLUtils.shutdown(conn);

    } // end finally

  } // end setSequence

  void setAclID(long msgid, int aclid) throws DatabaseException
  {
    Connection conn = null;
    PreparedStatement stmt = null;
    Statement stmt2 = null;
    ResultSet rs = null;
    try
    { // get a connection
      conn = getConnection();

      // lock the table
      stmt2 = conn.createStatement();
      stmt2.executeUpdate("LOCK TABLES us_head WRITE;");

      // update the ACL ID field
      stmt = conn.prepareStatement("UPDATE us_head SET aclid = ? WHERE msgid = ?;");
      if (aclid<=0)
	stmt.setNull(1,Types.INTEGER);
      else
	stmt.setInt(1,aclid);
      stmt.setLong(2,msgid);
      stmt.executeUpdate();

    } // end try
    catch (SQLException e)
    { // translate to a general DatabaseException
      throw generalException(e);

    } // end catch
    finally
    { // shut everything down
      MySQLUtils.unlockTables(conn);
      SQLUtils.shutdown(rs);
      SQLUtils.shutdown(stmt);
      SQLUtils.shutdown(stmt2);
      SQLUtils.shutdown(conn);

    } // end finally

  } // end setAclID

  int getNumTextParts(long msgid) throws DatabaseException
  {
    Connection conn = null;
    PreparedStatement stmt = null;
    ResultSet rs = null;
    try
    { // get a connection
      conn = getConnection();

      // create and execute the statement
      stmt = conn.prepareStatement("SELECT COUNT(*) FROM us_text WHERE msgid = ?;");
      stmt.setLong(1,msgid);
      rs = stmt.executeQuery();
      return SQLUtils.getReturnCountInt(rs,1);

    } // end try
    catch (SQLException e)
    { // translate to a general DatabaseException
      throw generalException(e);

    } // end catch
    finally
    { // shut everything down
      SQLUtils.shutdown(rs);
      SQLUtils.shutdown(stmt);
      SQLUtils.shutdown(conn);

    } // end finally

  } // end getNumTextParts

  int getNumBinaryParts(long msgid) throws DatabaseException
  {
    Connection conn = null;
    PreparedStatement stmt = null;
    ResultSet rs = null;
    try
    { // get a connection
      conn = getConnection();

      // create and execute the statement
      stmt = conn.prepareStatement("SELECT COUNT(*) FROM us_binary WHERE msgid = ?;");
      stmt.setLong(1,msgid);
      rs = stmt.executeQuery();
      return SQLUtils.getReturnCountInt(rs,1);

    } // end try
    catch (SQLException e)
    { // translate to a general DatabaseException
      throw generalException(e);

    } // end catch
    finally
    { // shut everything down
      SQLUtils.shutdown(rs);
      SQLUtils.shutdown(stmt);
      SQLUtils.shutdown(conn);

    } // end finally

  } // end getNumBinaryParts

  Map loadTextPart(long msgid, int part) throws DatabaseException
  {
    Connection conn = null;
    PreparedStatement stmt = null;
    ResultSet rs = null;
    try
    { // get a connection
      conn = getConnection();

      // create and execute the statement
      stmt = conn.prepareStatement("SELECT ident_nsid, ident_name, mimetype, charcount, linecount, reads, last_read "
				   + "FROM us_text WHERE msgid = ? AND part = ?;");
      stmt.setLong(1,msgid);
      stmt.setInt(2,part);
      rs = stmt.executeQuery();
      if (!(rs.next()))
      { // could not find the part
	DatabaseException de = new DatabaseException(MessageOps_mysql.class,"UniStoreMessages","bad.loadText.part");
	de.setParameter(0,String.valueOf(part));
	de.setParameter(1,String.valueOf(msgid));
	throw de;

      } // end if

      // Prepare the return value.
      HashMap rc = new HashMap();
      rc.put(PARAM_PART,new Integer(part));
      rc.put(PARAM_IDENTITY,new PropertyKey(rs.getInt(1),rs.getString(2)));
      String s = rs.getString(3);
      if (!(rs.wasNull()))
	rc.put(PARAM_MIMETYPE,s);
      int tmp = rs.getInt(4);
      if (!(rs.wasNull()))
	rc.put(PARAM_SIZE,new Integer(tmp));
      tmp = rs.getInt(5);
      if (!(rs.wasNull()))
	rc.put(PARAM_LINECOUNT,new Integer(tmp));
      rc.put(PARAM_READS,new Integer(rs.getInt(6)));
      java.util.Date dt = m_utils.getDateTime(rs,7);
      if (!(rs.wasNull()))
	rc.put(PARAM_LASTREAD,dt);
      return rc;

    } // end try
    catch (SQLException e)
    { // translate to a general DatabaseException
      throw generalException(e);

    } // end catch
    finally
    { // shut everything down
      SQLUtils.shutdown(rs);
      SQLUtils.shutdown(stmt);
      SQLUtils.shutdown(conn);

    } // end finally

  } // end loadTextPart

  Map loadTextPart(long msgid, PropertyKey identity) throws DatabaseException
  {
    Connection conn = null;
    PreparedStatement stmt = null;
    ResultSet rs = null;
    try
    { // get a connection
      conn = getConnection();

      // create and execute the statement
      stmt = conn.prepareStatement("SELECT part, mimetype, charcount, linecount, reads, last_read "
				   + "FROM us_text WHERE msgid = ? AND ident_nsid = ? AND ident_name = ?;");
      stmt.setLong(1,msgid);
      stmt.setInt(2,identity.getNamespaceID());
      stmt.setString(3,identity.getName());
      rs = stmt.executeQuery();
      if (!(rs.next()))
      { // could not find the part
	DatabaseException de = new DatabaseException(MessageOps_mysql.class,"UniStoreMessages","bad.loadText.id");
	de.setParameter(0,String.valueOf(identity.getNamespaceID()));
	de.setParameter(1,identity.getName());
	de.setParameter(2,String.valueOf(msgid));
	throw de;

      } // end if

      // Prepare the return value.
      HashMap rc = new HashMap();
      rc.put(PARAM_PART,new Integer(rs.getInt(1)));
      rc.put(PARAM_IDENTITY,identity);
      String s = rs.getString(2);
      if (!(rs.wasNull()))
	rc.put(PARAM_MIMETYPE,s);
      int tmp = rs.getInt(3);
      if (!(rs.wasNull()))
	rc.put(PARAM_SIZE,new Integer(tmp));
      tmp = rs.getInt(4);
      if (!(rs.wasNull()))
	rc.put(PARAM_LINECOUNT,new Integer(tmp));
      rc.put(PARAM_READS,new Integer(rs.getInt(5)));
      java.util.Date dt = m_utils.getDateTime(rs,6);
      if (!(rs.wasNull()))
	rc.put(PARAM_LASTREAD,dt);
      return rc;

    } // end try
    catch (SQLException e)
    { // translate to a general DatabaseException
      throw generalException(e);

    } // end catch
    finally
    { // shut everything down
      SQLUtils.shutdown(rs);
      SQLUtils.shutdown(stmt);
      SQLUtils.shutdown(conn);

    } // end finally

  } // end loadTextPart

  Map loadBinaryPart(long msgid, int part) throws DatabaseException
  {
    Connection conn = null;
    PreparedStatement stmt = null;
    ResultSet rs = null;
    try
    { // get a connection
      conn = getConnection();

      // create and execute the statement
      stmt = conn.prepareStatement("SELECT ident_nsid, ident_name, mimetype, datalen, filename, reads, last_read "
				   + "FROM us_binary WHERE msgid = ? AND part = ?;");
      stmt.setLong(1,msgid);
      stmt.setInt(2,part);
      rs = stmt.executeQuery();
      if (!(rs.next()))
      { // could not find the part
	DatabaseException de = new DatabaseException(MessageOps_mysql.class,"UniStoreMessages","bad.loadBinary.part");
	de.setParameter(0,String.valueOf(part));
	de.setParameter(1,String.valueOf(msgid));
	throw de;

      } // end if

      // Prepare the return value.
      HashMap rc = new HashMap();
      rc.put(PARAM_PART,new Integer(part));
      rc.put(PARAM_IDENTITY,new PropertyKey(rs.getInt(1),rs.getString(2)));
      String s = rs.getString(3);
      if (!(rs.wasNull()))
	rc.put(PARAM_MIMETYPE,s);
      int tmp = rs.getInt(4);
      if (!(rs.wasNull()))
	rc.put(PARAM_SIZE,new Integer(tmp));
      s = rs.getString(5);
      if (!(rs.wasNull()))
	rc.put(PARAM_FILENAME,s);
      rc.put(PARAM_READS,new Integer(rs.getInt(6)));
      java.util.Date dt = m_utils.getDateTime(rs,7);
      if (!(rs.wasNull()))
	rc.put(PARAM_LASTREAD,dt);
      return rc;

    } // end try
    catch (SQLException e)
    { // translate to a general DatabaseException
      throw generalException(e);

    } // end catch
    finally
    { // shut everything down
      SQLUtils.shutdown(rs);
      SQLUtils.shutdown(stmt);
      SQLUtils.shutdown(conn);

    } // end finally

  } // end loadBinaryPart

  Map loadBinaryPart(long msgid, PropertyKey identity) throws DatabaseException
  {
    Connection conn = null;
    PreparedStatement stmt = null;
    ResultSet rs = null;
    try
    { // get a connection
      conn = getConnection();

      // create and execute the statement
      stmt = conn.prepareStatement("SELECT part, mimetype, datalen, filename, reads, last_read "
				   + "FROM us_binary WHERE msgid = ? AND ident_nsid = ? AND ident_name = ?;");
      stmt.setLong(1,msgid);
      stmt.setInt(2,identity.getNamespaceID());
      stmt.setString(3,identity.getName());
      rs = stmt.executeQuery();
      if (!(rs.next()))
      { // could not find the part
	DatabaseException de = new DatabaseException(MessageOps_mysql.class,"UniStoreMessages","bad.loadBinary.id");
	de.setParameter(0,String.valueOf(identity.getNamespaceID()));
	de.setParameter(1,identity.getName());
	de.setParameter(2,String.valueOf(msgid));
	throw de;

      } // end if

      // Prepare the return value.
      HashMap rc = new HashMap();
      rc.put(PARAM_PART,new Integer(rs.getInt(1)));
      rc.put(PARAM_IDENTITY,identity);
      String s = rs.getString(2);
      if (!(rs.wasNull()))
	rc.put(PARAM_MIMETYPE,s);
      int tmp = rs.getInt(3);
      if (!(rs.wasNull()))
	rc.put(PARAM_SIZE,new Integer(tmp));
      s = rs.getString(4);
      if (!(rs.wasNull()))
	rc.put(PARAM_FILENAME,s);
      rc.put(PARAM_READS,new Integer(rs.getInt(5)));
      java.util.Date dt = m_utils.getDateTime(rs,6);
      if (!(rs.wasNull()))
	rc.put(PARAM_LASTREAD,dt);
      return rc;

    } // end try
    catch (SQLException e)
    { // translate to a general DatabaseException
      throw generalException(e);

    } // end catch
    finally
    { // shut everything down
      SQLUtils.shutdown(rs);
      SQLUtils.shutdown(stmt);
      SQLUtils.shutdown(conn);

    } // end finally

  } // end loadBinaryPart

  int createTextPart(long msgid, int nsid, String name, String mimetype, int charcount, int linecount, String data)
      throws DatabaseException
  {
    Connection conn = null;
    PreparedStatement stmt = null;
    Statement stmt2 = null;
    ResultSet rs = null;
    try
    { // get a connection
      conn = getConnection();

      // lock the table
      stmt2 = conn.createStatement();
      stmt2.executeUpdate("LOCK TABLES us_text WRITE;");

      // start by seeing if the identity already exists
      stmt = conn.prepareStatement("SELECT part FROM us_text WHERE msgid = ? AND ident_nsid = ? AND ident_name = ?;");
      stmt.setLong(1,msgid);
      stmt.setInt(2,nsid);
      stmt.setString(3,name);
      rs = stmt.executeQuery();
      if (rs.next())
      { // identity already exists, throw exception
	DatabaseException de = new DatabaseException(MessageOps_mysql.class,"UniStoreMessages","part.exists");
	de.setParameter(0,String.valueOf(msgid));
	throw de;

      } // end if

      SQLUtils.shutdown(rs);
      rs = null;
      SQLUtils.shutdown(stmt);

      // get the part number for this part
      stmt = conn.prepareStatement("SELECT IFNULL(MAX(part),0) FROM us_text WHERE msgid = ?;");
      stmt.setLong(1,msgid);
      rs = stmt.executeQuery();
      int partnum = SQLUtils.getReturnCountInt(rs,1) + 1;

      SQLUtils.shutdown(rs);
      rs = null;
      SQLUtils.shutdown(stmt);

      // perform the insert!
      stmt = conn.prepareStatement("INSERT INTO us_text (msgid, part, ident_nsid, ident_name, mimetype, charcount, "
				   + "linecount, data) VALUES (?, ?, ?, ?, ?, ?, ?, ?);");
      stmt.setLong(1,msgid);
      stmt.setInt(2,partnum);
      stmt.setInt(3,nsid);
      stmt.setString(4,name);
      stmt.setString(5,mimetype);
      stmt.setInt(6,charcount);
      stmt.setInt(7,linecount);
      stmt.setString(8,data);
      stmt.executeUpdate();

      return partnum;

    } // end try
    catch (SQLException e)
    { // translate to a general DatabaseException
      throw generalException(e);

    } // end catch
    finally
    { // shut everything down
      MySQLUtils.unlockTables(conn);
      SQLUtils.shutdown(rs);
      SQLUtils.shutdown(stmt);
      SQLUtils.shutdown(stmt2);
      SQLUtils.shutdown(conn);

    } // end finally

  } // end createTextPart

  int createBinaryPart(long msgid, int nsid, String name, String mimetype, String filename, int length,
		       InputStream data) throws DatabaseException
  {
    Connection conn = null;
    PreparedStatement stmt = null;
    Statement stmt2 = null;
    ResultSet rs = null;
    try
    { // get a connection
      conn = getConnection();

      // lock the table
      stmt2 = conn.createStatement();
      stmt2.executeUpdate("LOCK TABLES us_binary WRITE;");

      // start by seeing if the identity already exists
      stmt = conn.prepareStatement("SELECT part FROM us_binary WHERE msgid = ? AND ident_nsid = ? "
				   + "AND ident_name = ?;");
      stmt.setLong(1,msgid);
      stmt.setInt(2,nsid);
      stmt.setString(3,name);
      rs = stmt.executeQuery();
      if (rs.next())
      { // identity already exists, throw exception
	DatabaseException de = new DatabaseException(MessageOps_mysql.class,"UniStoreMessages","part.exists");
	de.setParameter(0,String.valueOf(msgid));
	throw de;

      } // end if

      SQLUtils.shutdown(rs);
      rs = null;
      SQLUtils.shutdown(stmt);

      // get the part number for this part
      stmt = conn.prepareStatement("SELECT IFNULL(MAX(part),0) FROM us_binary WHERE msgid = ?;");
      stmt.setLong(1,msgid);
      rs = stmt.executeQuery();
      int partnum = SQLUtils.getReturnCountInt(rs,1) + 1;

      SQLUtils.shutdown(rs);
      rs = null;
      SQLUtils.shutdown(stmt);

      // perform the insert!
      stmt = conn.prepareStatement("INSERT INTO us_binary (msgid, part, ident_nsid, ident_name, mimetype, datalen, "
				   + "filename, data) VALUES (?, ?, ?, ?, ?, ?, ?, ?);");
      stmt.setLong(1,msgid);
      stmt.setInt(2,partnum);
      stmt.setInt(3,nsid);
      stmt.setString(4,name);
      stmt.setString(5,mimetype);
      stmt.setInt(6,length);
      stmt.setString(7,filename);
      stmt.setBinaryStream(8,data,length);
      stmt.executeUpdate();

      return partnum;

    } // end try
    catch (SQLException e)
    { // translate to a general DatabaseException
      throw generalException(e);

    } // end catch
    finally
    { // shut everything down
      MySQLUtils.unlockTables(conn);
      SQLUtils.shutdown(rs);
      SQLUtils.shutdown(stmt);
      SQLUtils.shutdown(stmt2);
      SQLUtils.shutdown(conn);

    } // end finally

  } // end createBinaryPart

  void delete(long msgid) throws DatabaseException
  {
    Connection conn = null;
    PreparedStatement stmt = null;
    Statement stmt2 = null;
    try
    { // get a connection
      conn = getConnection();

      // lock the tables
      stmt2 = conn.createStatement();
      stmt2.executeUpdate("LOCK TABLES us_head WRITE, us_prop WRITE, us_text WRITE, us_text_prop WRITE, "
			  + "us_binary WRITE, us_binary_prop WRITE;");

      // delete all data from the tables
      stmt = conn.prepareStatement("DELETE FROM us_head WHERE msgid = ?;");
      stmt.setLong(1,msgid);
      stmt.executeUpdate();
      stmt.close();
      stmt = conn.prepareStatement("DELETE FROM us_prop WHERE msgid = ?;");
      stmt.setLong(1,msgid);
      stmt.executeUpdate();
      stmt.close();
      stmt = conn.prepareStatement("DELETE FROM us_text WHERE msgid = ?;");
      stmt.setLong(1,msgid);
      stmt.executeUpdate();
      stmt.close();
      stmt = conn.prepareStatement("DELETE FROM us_text_prop WHERE msgid = ?;");
      stmt.setLong(1,msgid);
      stmt.executeUpdate();
      stmt.close();
      stmt = conn.prepareStatement("DELETE FROM us_binary WHERE msgid = ?;");
      stmt.setLong(1,msgid);
      stmt.executeUpdate();
      stmt.close();
      stmt = conn.prepareStatement("DELETE FROM us_binary_prop WHERE msgid = ?;");
      stmt.setLong(1,msgid);
      stmt.executeUpdate();

    } // end try
    catch (SQLException e)
    { // translate to a general DatabaseException
      throw generalException(e);

    } // end catch
    finally
    { // shut everything down
      MySQLUtils.unlockTables(conn);
      SQLUtils.shutdown(stmt);
      SQLUtils.shutdown(stmt2);
      SQLUtils.shutdown(conn);

    } // end finally

  } // end delete

  Map listTextParts(long msgid) throws DatabaseException
  {
    Connection conn = null;
    PreparedStatement stmt = null;
    ResultSet rs = null;
    try
    { // get a connection
      conn = getConnection();

      // run the statement that lists the parts
      stmt = conn.prepareStatement("SELECT part, ident_nsid, ident_name FROM us_text WHERE msgid = ? ORDER BY part;");
      stmt.setLong(1,msgid);
      rs = stmt.executeQuery();

      // create and return the listing
      TreeMap rc = new TreeMap();
      while (rs.next())
	rc.put(new Integer(rs.getInt(1)),new PropertyKey(rs.getInt(2),rs.getString(3)));
      return rc;

    } // end try
    catch (SQLException e)
    { // translate to a general DatabaseException
      throw generalException(e);

    } // end catch
    finally
    { // shut everything down
      SQLUtils.shutdown(rs);
      SQLUtils.shutdown(stmt);
      SQLUtils.shutdown(conn);

    } // end finally

  } // end listTextParts

  Map listBinaryParts(long msgid) throws DatabaseException
  {
    Connection conn = null;
    PreparedStatement stmt = null;
    ResultSet rs = null;
    try
    { // get a connection
      conn = getConnection();

      // run the statement that lists the parts
      stmt = conn.prepareStatement("SELECT part, ident_nsid, ident_name FROM us_binary WHERE msgid = ? "
				   + "ORDER BY part;");
      stmt.setLong(1,msgid);
      rs = stmt.executeQuery();

      // create and return the listing
      TreeMap rc = new TreeMap();
      while (rs.next())
	rc.put(new Integer(rs.getInt(1)),new PropertyKey(rs.getInt(2),rs.getString(3)));
      return rc;

    } // end try
    catch (SQLException e)
    { // translate to a general DatabaseException
      throw generalException(e);

    } // end catch
    finally
    { // shut everything down
      SQLUtils.shutdown(rs);
      SQLUtils.shutdown(stmt);
      SQLUtils.shutdown(conn);

    } // end finally

  } // end listTextParts

} // end class MessageOps_mysql
