|
From: <sv...@de...> - 2005-07-08 14:39:33
|
Author: marcelo
Date: 2005-07-08 10:39:29 -0400 (Fri, 08 Jul 2005)
New Revision: 1452
Modified:
humano2/trunk/core/db/pgsql/pgsqlCrud.cs
Log:
* Applying Marijns patch for pgsqlCrud which refactors ReadData() and Re=
adStructure().
Modified: humano2/trunk/core/db/pgsql/pgsqlCrud.cs
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D
--- humano2/trunk/core/db/pgsql/pgsqlCrud.cs 2005-07-08 14:29:43 UTC (rev=
1451)
+++ humano2/trunk/core/db/pgsql/pgsqlCrud.cs 2005-07-08 14:39:29 UTC (rev=
1452)
@@ -63,256 +63,20 @@
///<summary>Devuelve la estructura completa de una entidad.</summary>
///<param name=3D"idEntity">El ID del objecto cual se quiere leer su e=
structura.</param>
///<param name=3D"withDeletes">Si es True tambien muestre los valores=
borrados. Si es false no.</param>
+ /// <returns>Devuelve la estructura de una entidad.</returns>
///<remarks>El read estructural es independiente si se le sumimistra e=
l id
/// de una clase o de una instancia de esta</remarks>
override public DataSet ReadStructure(int idEntity, bool withDeletes)
{
- if( !IsActive( idEntity ) )
- {
- throw new NoExistException( "The id_entity " + idEntity + " doesn't =
exist for read." );
- }
- =09
- conn.BeginTransaction();
- =09
- //Estructuras y variables usadas en la funcion
- DataSet ds =3D new DataSet( ); //El DataSet a retornar
- NpgsqlCommand dbCmd =3D null; //
- NpgsqlDataAdapter da =3D new NpgsqlDataAdapter( ); //Esttructuras par=
a la conexion con la BD
- dbCmd =3D new NpgsqlCommand( ); //
- string query =3D null;
- =09
- // Cast-down a tipo mas potente.
- NpgsqlConnection pgConn =3D ( (NpgsqlConnection) conn.getConnObj() );
- //Inicializo el command
- dbCmd.Connection =3D pgConn;
- =09
- //Buscar todos los attributos del tipo y sus padres.
- //Para ello hay que considerar los casos en la idEntity pertenece a u=
na clase o una instancia
- =09
- //Lista de id's de herencia de la clase.
- ArrayList idList =3D new ArrayList( );
- string idListStr =3D "";
- int[] Inh =3D getInheritanceIfIsInstance( idEntity );
- idList.AddRange( Inh );
- =09
- //Verifico cual es el id de la clase base.
- //int idParent;
- if( Inh.Length =3D=3D 0 )
- {
- //idParent =3D idEntity;
- idList.AddRange( getInheritanceOfType( idEntity ) );
- }
- else
- {
- //idParent =3D Inh[0];
- }
- =09
- =09
- //Lo transformo a string en formato para poder usarlo en los select's
- foreach( Object id in idList )
- {
- idListStr +=3D "," + id.ToString( );
- }
- idListStr =3D idListStr.Remove( 0, 1 );
- =09
- //Ingreso las tablas base
- //Devuelve la informacion basica sobre el idEntity.
- query =3D String.Format( "select * from entity where id_entity =3D ({=
0})", idEntity );
- dbCmd.CommandText =3D query;
- da.SelectCommand =3D dbCmd;
- da.Fill( ds, "entity" );
- =09
- //Devuelve la informacion sobre los clases cual esta en la tabla "cla=
ss".
- query =3D String.Format( "select * from class where id_entity in ({0}=
)", idListStr );
- dbCmd.CommandText =3D query;
- da.Fill( ds, "class" );
- =09
- //Ahora obtengo la tabla arttribute con una fila para cada uno de mis=
attributos
- //Pero recordar que es necesario buscar la herencia de cada uno de lo=
s attributos
- //en el for de mas abajo.
- if(withDeletes)
- {
- query =3D String.Format(@"select a.*,c.""sysName"" as ""refClassSysN=
ame"" ,d.""xslt"" as ""refXslt"" " +
- @"from attribute a
- INNER JOIN entity e ON a.id_entity =3D e.id_entity
- INNER JOIN class c ON e.class =3D c.id_entity
- LEFT JOIN ""displayAttribute"" d ON d.id_entity =3D a.""dis=
play""" +
- @"where a.""classId"" in ({0})",
- idListStr);
- } else {
- query =3D String.Format(@"select a.*,c.""sysName"" as ""refClassSysN=
ame"" ,d.""xslt"" as ""refXslt"" " +
- @"from attribute a
- INNER JOIN entity e ON a.id_entity =3D e.id_entity
- INNER JOIN class c ON e.class =3D c.id_entity and e.""d=
elDate"" is null
- LEFT JOIN ""displayAttribute"" d ON d.id_entity =3D a.""dis=
play""" +
- @"where a.""classId"" in ({0})
- order by a.""order"", a.""attName""",
- idListStr);
- =09
- }
- =09
- //Realizo la query y el llenado del DataSet
- dbCmd.CommandText =3D query;
- da.Fill( ds, "attribute" );
- =09
- //Son bastante autoexplicativas estas variables.
- int index;
- string attIds =3D null, attClassName;
- ArrayList attInheritance;
- DataRowCollection drc =3D ds.Tables["attribute"].Copy( ).Rows;
- =09
- //Una array con todos los atributos y sFillus herencias
- ArrayList attList =3D new ArrayList( );
- =09
- // Camina por todos los tablas atributo buscando su herencia
- while( drc.Count > 0 )
- {
- //La info sobre a el atributo
- attClassName =3D (String)drc[0]["refClassSysName"];
- attInheritance =3D getInheritanceByName( attClassName, "attribute" )=
;
- =09
- //Agrego la herencia a la lista a buscar
- for( index =3D drc.Count - 1; index >=3D 0; index-- )
- {
- if( (String)drc[index]["refClassSysName"] =3D=3D attClassName )
- {
- string[] att =3D new string[2];
- att[0] =3D Convert.ToString( drc[index]["id_entity"] );
- att[1] =3D attClassName;
- //Lo grego a la lista
- attList.Add( att );
- =09
- //Agrego su herencia
- foreach( object table in attInheritance )
- {
- string[] inh =3D new string[2];
- inh[0] =3D att[0];
- inh[1] =3D (String)table;
- attList.Add( inh );
- }
- drc.RemoveAt( index );
- }
- }
- }
- =09
- =09
- //Creo el select para la consulta
- string[] attTable;
- while( attList.Count > 0 )
- {
- //La info sobre a el atributo
- attTable =3D (string[])attList[0];
- attIds =3D attTable[0];
- attClassName =3D attTable[1];
- attList.RemoveAt( 0 );
- =09
- for( index =3D attList.Count - 1; index >=3D 0; index-- )
- {
- attTable =3D (string[])attList[index];
- if( attTable[1] =3D=3D attClassName )
- {
- attIds +=3D "," + attTable[0];
- attList.RemoveAt( index );
- }
- }
- =09
- query =3D String.Format( @"select * from ""{0}"" where id_entity in =
({1})", attClassName, attIds );
- dbCmd.CommandText =3D query;
- da.Fill( ds, attClassName );
- }
- =09
- //Ahora recuperamos las option para los choice y para los atributos c=
hoice de cada atributo
- {
- ArrayList optionGroups =3D new ArrayList( );
- =09
- if( ds.Tables.Contains( "choice" ) )
- {
- DataTable choice =3D ds.Tables["choice"];
- =09
- //Para los attributos choice de la tabla
- for( int i=3D0;i < choice.Rows.Count;i++ )
- {
- if( !optionGroups.Contains( (Int32)choice.Rows[i]["groupType"] ) )
- {
- optionGroups.Add( (Int32)choice.Rows[i]["groupType"] );
- }
- }
- }
- =09
- //-_-
- //Para los attributos choice de los attributos de la tabla pedida
- =09
- //Obtenemos las tablas que se descuelgan de la tabla pedida
- string sysNameTables =3D "";
- for( int i=3D0;i < ds.Tables.Count;i++ )
- {
- if( sysNameTables =3D=3D "" )
- {
- sysNameTables =3D "'" + ds.Tables[i].TableName + "'";
- }
- else
- {
- sysNameTables +=3D ",'" + ds.Tables[i].TableName + "'";
- }
- }
- =09
- //La query para optener los option
- query =3D @"select ch.""groupType""
- from ""attribute"" as a,
- ""class"" as c,
- ""choice"" as ch
- where c.""sysName"" in (" + sysNameTables + @") and
- a.""classId"" =3D c.id_entity and
- ch.id_entity =3D a.id_entity
- group by ch.""groupType""";
- =09
- =09
- string groups =3D "";
- //Creamos la query
- foreach( int group in optionGroups )
- {
- if( groups =3D=3D "" )
- {
- groups =3D group.ToString( );
- }
- else
- {
- groups +=3D "," + group.ToString( );
- }
- }
- =09
- if( groups =3D=3D "" )
- {
- groups =3D "null";
- }
- =09
- query =3D String.Format( @"select * from ""option"" where ""group"" =
in ({0}) or ""group"" in ({1})", groups, query );
- dbCmd.CommandText =3D query;
- da.Fill( ds, "option" );
- }
- =09
- DataColumn[] dc;
- foreach( DataTable dt in ds.Tables )
- {
- dc =3D new DataColumn[1];
- dc[0] =3D dt.Columns["id_entity"];
- dt.PrimaryKey =3D dc;
- }
- =09
- conn.Commit();
- =09
- return ds;
- =09
+ return ReadStructure(idEntity, withDeletes, "");
}
=20
- /// <summary>
- /// FIXME Modular funcion generica
- /// </summary>
- /// <param name=3D"idEntity"></param>
- /// <param name=3D"withDeletes"></param>
- /// <param name=3D"idAttributes"></param>
- /// <returns></returns>
- override public DataSet ReadStructure(int idEntity, bool withDeletes,s=
tring idAttributes)
+ ///<summary>Devuelve la estructura de cierta attributos de una entidad=
.</summary>
+ /// <param name=3D"idEntity">El ID del objecto cual se quiere leer su =
estructura.</param>
+ /// <param name=3D"withDeletes">Si es True tambien muestre los valore=
s borrados. Si es false no.</param>
+ /// <param name=3D"idAttributes">Los attributos para devolver. Por def=
ecto devuelve todos los attributos.</param>
+ /// <returns>Devuelve la estructura de una entidad.</returns>
+ override public DataSet ReadStructure(int idEntity, bool withDeletes, =
string idAttributes)
{
if( !IsActive( idEntity ) )
{
@@ -478,7 +242,7 @@
}
=09
//Ahora recuperamos las option para los choice y para los atributos c=
hoice de cada atributo
- {
+ {
ArrayList optionGroups =3D new ArrayList( );
=09
if( ds.Tables.Contains( "choice" ) )
@@ -545,7 +309,7 @@
query =3D String.Format( @"select * from ""option"" where ""group"" i=
n ({0}) or ""group"" in ({1})", groups, query );
dbCmd.CommandText =3D query;
da.Fill( ds, "option" );
- }
+ }
=09
DataColumn[] dc;
foreach( DataTable dt in ds.Tables )
@@ -559,221 +323,36 @@
=09
return ds;
}
- =09
+ =20
/// <summary>
- /// Method ReadData
+ /// Obtener los datos de una entidad.
/// </summary>
- /// <param name=3D"idEntity">An int</param>
- /// <returns>A DataSet</returns>
+ /// <param name=3D"idEntity">Id id_entity de la entidad</param>
+ /// <returns>Devuele un data structure con los datos de la entidad.</r=
eturns>
override public DataSet ReadData(int idEntity)
{
- //Verifico si existe el tipo, sino retorno una exeption
- if( !IsActive( idEntity ) )
- {
- throw new NoExistException( "The id_entity " + idEntity + " doesn't =
exist for read." );
- }
- =09
- //Containers de Datos
- DataSet ds =3D new DataSet( "DataRead" );
- DataTable dt;
- DataRow dr;
- =09
- // Buscar todos los attributos del tipo.
- string query =3D String.Format( @"select a.""id_entity"" as ""id"",
- a.""sysAttName"" as ""attName"",
- a.""isVirtual"" as ""isVirtual"",
- ca.""sysName"" as ""typeName"",
- cp.""sysName"" as ""className"",
- cd.""parentId"" as ""inheritance""
- from attribute a,class cp,class ca,entity e,class cd
- where a.""classId"" in ({0}) and
- a.""classId"" =3D cp.""id_entity"" and
- a.""id_entity"" =3D e.""id_entity"" and
- e.""class"" =3D ca.""id_entity"" and
- cd.""id_entity"" =3D ca.""parentId""",
- inheritanceToString( idEntity ) );
- =09
- //Realizo la consulta
- DataTable dtAtt =3D conn.doSelect( query ); // NpgsqlDataReader drA=
tt =3D ( (NpgsqlDataReader) conn.doSelect( query ) );
- //Reader para almacenar los valores de cada at tributo obtenido
- DataSet dsData; //NpgsqlDataReader drData;
- =09
- //ToDel: dbLog.WriteToLog(query,"Init Query");
- =09
- //Cada fila del read corresponde a un atributo del cual debo recupera=
r su valor.
- StringCollection attType =3D new StringCollection( );
- ArrayList attId =3D new ArrayList( );
- query =3D "";
- foreach(DataRow drAtt in dtAtt.Rows) // while( drAtt.Read( ) )
- {
- //Para verificar si un atribito hereda de pertinence
- bool isParentPertinence =3D false;
- //Si el atributo tiene herencia, verifico si hereda de un pertinence
- if( drAtt[5] !=3D DBNull.Value && (Int32)drAtt["inheritance"] !=3D (=
Int32)MetaModelConsts.EntitiesAttribute ) //( !drAtt.IsDBNull( 5 ) && (In=
t32)drAtt["inheritance"] !=3D (Int32)MetaModelConsts.EntitiesAttribute )
- {
- ArrayList idParentList =3D new ArrayList( getInheritance( (Int32)dr=
Att["id"] ) );
- if( idParentList.Contains( (Int32)MetaModelConsts.EntitiesPertinenc=
e ) )
- {
- isParentPertinence =3D true;
- }
- }
- =09
- //ToDel: dbLog.WriteToLog(drAtt.ToString(),"Init Query");
- //verifico si el attributo es virtual, si no lo es lo agrego a la co=
nsulta
- if( (String)drAtt["typeName"] =3D=3D "pertinence" || isParentPertine=
nce )
- {
- DataTable dtMetaData; // NpgsqlDataReader drMetaData;
- //Busco la relacion y donde se encuentra.
- string metaQuery =3D (
- @" select co.""sysName"" as ""classOwnerName"",
- co.""id_entity"" as ""classOwnerId"",
- a.""sysAttName"" as ""ownerName"",
- a.""id_entity"" as ""ownerId"",
- p.""ratio"" as ""ratio"",
- ct.""sysName"" as ""classDestinyName"",
- ct.""id_entity"" as ""classDestinyId""
- from attribute a,class co,class ct,pertinence p
- where co.id_entity =3D a.""classId"" and
- a.id_entity =3D p.owner and
- p.""to"" =3D ct.id_entity and
- p.id_entity =3D " + drAtt["id"].ToString( ) );
- =09
- //ToDel: dbLog.c(metaQuery,"pertenence");
- dtMetaData =3D conn.doSelect( metaQuery ); //(NpgsqlDataReader)con=
n.doSelect( metaQuery );
- // drMetaData.Read( );
- //Recuperamos las tablas con sus respectivos link
- string ownerName =3D dtMetaData.Rows[0]["ownerName"].ToString( );
- string ownerId =3D dtMetaData.Rows[0]["ownerId"].ToString( );
- string className =3D dtMetaData.Rows[0]["classOwnerName"].ToStrin=
g( );
- string classId =3D dtMetaData.Rows[0]["classOwnerId"].ToString(=
);
- string classDName =3D dtMetaData.Rows[0]["classDestinyName"].ToStr=
ing( );
- string classDId =3D dtMetaData.Rows[0]["classDestinyId"].ToStrin=
g( );
- =09
- //dtMetaData.Dispose( );
- =09
- =09
- //Obtengo los datos segun el tipo de ralacion.
- #region n:m
- //Caso n:m
- //dbLog.WriteToLog("|"+(String)drMetaData["ratio"]+"|","ratio");
- =09
- if( (String)dtMetaData.Rows[0]["ratio"] =3D=3D "n:m" )
- {
- //Obtengo las tablas a las cuales se hace referencia
- metaQuery =3D mnInfoQuery( classId, ownerId );
- =09
- //dbLog.WriteToLog(metaQuery,"n:m");
- dtMetaData =3D conn.doSelect(metaQuery); //drMetaData =3D (Npgsql=
DataReader)conn.doSelect( metaQuery );
- =09
- foreach(DataRow drMetaData in dtMetaData.Rows) //while( drMetaDat=
a.Read( ) )
- {
- // Recupero el valor para el atributo
- query +=3D ( @" ; select cd.id_entity , cd.""" + drMetaData["disp=
layColumn"] + @"""" +
- @" from """ + drMetaData["classDestinyName"] +
- @"""cd, """ + className + @""" p" +
- @" where p.""" + ownerName + @""" =3D " + idEntity + @" and
- p.""" + drMetaData["attName"] + @""" =3D cd.id_entity" + "\n" );
- attType.Add( (String)drAtt["typeName"] );
- attId.Add( drAtt["id"] );
- }
- }
- #endregion
- #region n:1
- else // Caso n:1
- {
- //Obtengo la informacion sobre la tabla a desplegar
- string DisplayColumn =3D (String)conn.doScalar(
- @"select ""sysAttName""
- from attribute
- where ""isPrimary"" =3D true and
- ""classId"" =3D " + classDId );
- =09
- // Recupero el valor para el atributo
- query +=3D ( @" ; select ""to"".id_entity,""to"".""" + DisplayColu=
mn + @"""" +
- @" from """ + className + @""" as owner,
- """ + classDName + @""" as ""to"" " +
- @" where owner.""" + ownerName + @""" =3D ""to"".id_entity and
- owner.id_entity =3D " + idEntity + "\n" );
- attType.Add( (String)drAtt["typeName"] );
- attId.Add( drAtt["id"] );
- =09
- }
- #endregion
- }
- else if( (Boolean)drAtt["isVirtual"] )
- {/* Solo para capturar los virtuals*/}
- else
- {
- // Recupero el valor para el atributo
- query +=3D ( @" ; select """ + drAtt["attName"] + @"""" +
- @" from """ + drAtt["className"] + @"""" +
- @" where ""id_entity"" =3D " + idEntity + "\n" );
- attType.Add( (String)drAtt["typeName"] );
- attId.Add( drAtt["id"] );
- }
- }
- =09
- //ToDel: dbLog.WriteToLog(query,"Big query");
- =09
- //realizo la consulta
- dsData =3D conn.doSelect( query,new DataSet() );
- =09
- foreach(DataTable dTable in dsData.Tables)
- {
- foreach(DataRow drData in dTable.Rows) // while( drData.Read( ) )
- {
- //Recupero el valor a menos que sea nulo
- if(drData[0] !=3D DBNull.Value) // ( !drData.IsDBNull( 0 ) )
- {
- =09
- //Si no existe la tabla para el tipo la creo
- if( !ds.Tables.Contains( attType[0] ) )
- {
- dt =3D new DataTable( attType[0] );
- dt.Columns.Add( "id_entity", typeof(int) );
- dt.Columns.Add( "data", drData[0].GetType( ) );
- if( attType[0] =3D=3D "pertinence" )
- {
- dt.Columns.Add( "refData", drData[1].GetType( ) );
- }
- ds.Tables.Add( dt );
- }
- =09
- dr =3D ds.Tables[attType[0]].NewRow( );
- dr[0] =3D attId[0];
- dr[1] =3D drData[0];
- if( attType[0] =3D=3D "pertinence" )
- {
- dr[2] =3D drData[1];
- }
- ds.Tables[attType[0]].Rows.Add( dr );
- }
- }
- attId.RemoveAt( 0 );
- attType.RemoveAt( 0 );
- }//while(drData.NextResult( ));
- =09
- return ds;
+ return ReadData(idEntity, false, "");
}
=09
/// <summary>
- /// Method ReadData
+ /// Obtener los datos de una entidad.=20
/// </summary>
- /// <param name=3D"idEntity">An int</param>
- /// <param name=3D"withDeletes">A bool</param>
- /// <returns>A DataSet</returns>
+ /// <param name=3D"idEntity">Id id_entity de la entidad</param>
+ /// <param name=3D"withDeletes">si es TRUE devuelve los datos, incluso=
cuando estan marcado como borrados</param>
+ /// <returns>Devuele un data structure con los datos de la entidad.</r=
eturns>
override public DataSet ReadData(int idEntity, bool withDeletes)
{
- throw new DriverException( "Not Implemented" );
+ return ReadData(idEntity, withDeletes, "");
}
=20
/// <summary>
- /// Method ReadData
+ /// Obtener los datos de algunas attributos de una entidad.=20
/// </summary>
- /// <param name=3D"idEntity">An int</param>
- /// <param name=3D"withDeletes">A bool</param>
- /// <returns>A DataSet</returns>
- override public DataSet ReadData(int idEntity, bool withDeletes,string=
idsAtt)
+ /// <param name=3D"idEntity">Id id_entity de la entidad</param>
+ /// <param name=3D"withDeletes">si es TRUE devuelve los datos, incluso=
cuando estan marcado como borrados</param>
+ /// <param name=3D"attributeIds">Los Id de los attributos cuale=
s son devueltas. Por defecto devuelven todas los attributos.</param>
+ /// <returns>Devuele un data structure con los datos de la entidad.</r=
eturns>
+ override public DataSet ReadData(int idEntity, bool withDeletes, strin=
g attributeIds)
{
//Verifico si existe el tipo, sino retorno una exeption
if( !IsActive( idEntity ) )
@@ -785,27 +364,33 @@
DataSet ds =3D new DataSet( "DataRead" );
DataTable dt;
DataRow dr;
- string queryInAtt=3D"";
- if (idsAtt !=3D"")
+
+ string deleteString =3D "and e.\"delDate\" is null";
+ if ( withDeletes =3D=3D true )=20
{
- queryInAtt=3D "and a.id_entity in("+idsAtt+")";
- }
- =09
+ deleteString =3D "";
+ } =09
=20
+ string queryInAtt =3D "";
+ if (attributeIds !=3D "")
+ {
+ queryInAtt =3D "and a.id_entity in("+ attributeIds +")";
+ }
+ =09
// Buscar todos los attributos del tipo.
string query =3D String.Format( @"select a.""id_entity"" as ""id"",
- a.""sysAttName"" as ""attName"",
- a.""isVirtual"" as ""isVirtual"",
- ca.""sysName"" as ""typeName"",
- cp.""sysName"" as ""className"",
- cd.""parentId"" as ""inheritance""
- from attribute a,class cp,class ca,entity e,class cd
- where a.""classId"" in ({0}) and
- a.""classId"" =3D cp.""id_entity"" and
- a.""id_entity"" =3D e.""id_entity"" and
- e.""class"" =3D ca.""id_entity"" and
- cd.""id_entity"" =3D ca.""parentId""" + queryInAtt ,
- inheritanceToString( idEntity ) );
+ a.""sysAttName"" as ""attName"",
+ a.""isVirtual"" as ""isVirtual"",
+ ca.""sysName"" as ""typeName"",
+ cp.""sysName"" as ""className"",
+ cd.""parentId"" as ""inheritance""
+ from attribute a, class cp, class ca, entity e, class cd
+ where a.""classId"" in ({0}) and
+ a.""classId"" =3D cp.""id_entity"" and
+ a.""id_entity"" =3D e.""id_entity"" and
+ e.""class"" =3D ca.""id_entity"" and
+ cd.""id_entity"" =3D ca.""parentId"" {1} {2}",
+ inheritanceToString( idEntity ), deleteString, queryInAtt );
=09
//Realizo la consulta
DataTable dtAtt =3D conn.doSelect( query );
@@ -832,7 +417,6 @@
}
}
=09
- //ToDel: dbLog.WriteToLog(drAtt.ToString(),"Init Query");
//verifico si el attributo es virtual, si no lo es lo agrego a la co=
nsulta
if( (String)drAtt["typeName"] =3D=3D "pertinence" || isParentPertine=
nce )
{
|