// Persist library : Persistence layer
// Copyright (C) 2003 Vincent Daron
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
using System;
using System.Data;
using System.Collections.Specialized;
using Persist;
using Persist.Maps;
using Persist.Sql;
using Persist.IdGenerators;
namespace Persist.OleDb{
/**
* ID generator for the MySql database.
*
* @author:
*/
public class OleDbHighLowIdGenerator : AbstractHighLowIdGenerator
{
private string theTableName;
private string theColumnName;
public OleDbHighLowIdGenerator()
{
}
public override void Init(NameValueCollection nameValueCollection)
{
base.Init(nameValueCollection);
theTableName = nameValueCollection["TableName"];
theColumnName = nameValueCollection["ColumnName"];
}
protected override ulong GetNextHighValue(ClassMap classMap)
{
ulong highValue = 1;
IDbConnection conn = null;
IDbCommand command = null;
try
{
conn = classMap.RelationalDatabase.GetConnection();
command = conn.CreateCommand();
command.CommandText = "LOCK TABLES "+theTableName+" WRITE";
command.ExecuteNonQuery();
command.CommandText = "SELECT "+theColumnName+" FROM "+theTableName;
IDataReader dataReader = command.ExecuteReader();
if (dataReader.Read())
{
highValue = (ulong)dataReader[theColumnName];
highValue++;
command.CommandText ="UPDATE "+theTableName+" SET "+theColumnName+"="+highValue;
command.ExecuteNonQuery();
}
else
{
command.CommandText ="INSERT INTO "+theTableName+"+("+ theColumnName +") VALUES ("+highValue+")";
command.ExecuteNonQuery();
}
dataReader.Dispose();
command.CommandText ="UNLOCK TABLES";
command.ExecuteNonQuery();
classMap.RelationalDatabase.FreeConnection(conn);
}
catch (Exception e)
{
if(command != null)
{
try
{
command.CommandText = "UNLOCK TABLES";
command.ExecuteNonQuery();
}
catch
{
}
}
throw e;
}
highValue <<= 16;
highValue &= 0xffffffffffff0000L;
return highValue;
}
}
}
|