Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.CEDMA.DB/Database.cs @ 392

Last change on this file since 392 was 392, checked in by gkronber, 16 years ago

worked on unification of agents and runs (ticket #188)

File size: 17.7 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2008 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
4 *
5 * This file is part of HeuristicLab.
6 *
7 * HeuristicLab is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * HeuristicLab is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
19 */
20#endregion
21
22using System;
23using System.Collections.Generic;
24using System.Linq;
25using System.Text;
26using System.Data.Linq;
27using HeuristicLab.CEDMA.DB.Interfaces;
28using System.ServiceModel;
29using System.Data;
30using System.Data.SQLite;
31using System.Data.Common;
32using System.Threading;
33
34namespace HeuristicLab.CEDMA.DB {
35  [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Multiple, UseSynchronizationContext = false)]
36  public class Database : IDatabase {
37    private string connectionString;
38    private ReaderWriterLockSlim rwLock;
39    public Database(string connectionString) {
40      this.connectionString = connectionString;
41      rwLock = new ReaderWriterLockSlim();
42    }
43
44    #region create empty database
45    public void CreateNew() {
46      rwLock.EnterWriteLock();
47      try {
48        using(DbConnection cnn = new SQLiteConnection(connectionString)) {
49          cnn.Open();
50          using(DbTransaction t = cnn.BeginTransaction()) {
51            using(DbCommand cmd = cnn.CreateCommand()) {
52              cmd.CommandText = "CREATE TABLE Project (ID integer primary key autoincrement, Name text, Description text, CreationTime DateTime)";
53              cmd.Transaction = t;
54              cmd.ExecuteNonQuery();
55            }
56            using(DbCommand cmd = cnn.CreateCommand()) {
57              cmd.CommandText = "CREATE TABLE Agent (ID integer primary key autoincrement, ProjectId integer, ParentAgentId integer, Name text, Status text default "+ProcessStatus.Unknown+", ControllerAgent integer, CreationTime DateTime, RawData Blob)";
58              cmd.Transaction = t;
59              cmd.ExecuteNonQuery();
60            }
61            using(DbCommand cmd = cnn.CreateCommand()) {
62              cmd.CommandText = "CREATE TABLE Result (ID integer primary key autoincrement, AgentId integer, ParentResultId integer, Summary text, Description text, CreationTime DateTime, RawData Blob)";
63              cmd.Transaction = t;
64              cmd.ExecuteNonQuery();
65            }
66            t.Commit();
67          }
68        }
69      } finally {
70        rwLock.ExitWriteLock();
71      }
72    }
73    #endregion
74
75    #region insert agent/run/result/sub-result
76    public long InsertAgent(long? parentAgentId, string name, bool controllerAgent, byte[] rawData) {
77      rwLock.EnterWriteLock();
78      try {
79        using(DbConnection cnn = new SQLiteConnection(connectionString)) {
80          cnn.Open();
81          long id;
82          using(DbTransaction t = cnn.BeginTransaction()) {
83            using(DbCommand c = cnn.CreateCommand()) {
84              c.Transaction = t;
85              c.CommandText = "Insert into Agent (Name, ParentAgentId, ControllerAgent, CreationTime, RawData) values (@Name, @ParentAgentId, @ControllerAgent, @CreationTime, @RawData); select last_insert_rowid()";
86              DbParameter nameParam = c.CreateParameter();
87              nameParam.ParameterName = "@Name";
88              nameParam.Value = name;
89              c.Parameters.Add(nameParam);
90              DbParameter parentParam = c.CreateParameter();
91              parentParam.ParameterName = "@ParentAgentId";
92              parentParam.Value = parentAgentId;
93              c.Parameters.Add(parentParam);
94              DbParameter controllerParam = c.CreateParameter();
95              controllerParam.ParameterName = "@ControllerAgent";
96              controllerParam.Value = controllerAgent;
97              c.Parameters.Add(controllerParam);
98              DbParameter creationTimeParam = c.CreateParameter();
99              creationTimeParam.ParameterName = "@CreationTime";
100              creationTimeParam.Value = DateTime.Now;
101              c.Parameters.Add(creationTimeParam);
102              DbParameter dataParam = c.CreateParameter();
103              dataParam.ParameterName = "@RawData";
104              dataParam.Value = rawData;
105              c.Parameters.Add(dataParam);
106              id = (long)c.ExecuteScalar();
107            }
108            t.Commit();
109            return id;
110          }
111        }
112      } finally {
113        rwLock.ExitWriteLock();
114      }
115    }
116
117    public long InsertResult(long agentId, string summary, string description, byte[] rawData) {
118      rwLock.EnterWriteLock();
119      try {
120        using(SQLiteConnection cnn = new SQLiteConnection(connectionString)) {
121          cnn.Open();
122          long id;
123          using(DbTransaction t = cnn.BeginTransaction()) {
124            using(DbCommand c = cnn.CreateCommand()) {
125              c.Transaction = t;
126              c.CommandText = "Insert into Result (AgentId, CreationTime, Summary, Description, RawData) values (@AgentId, @CreationTime, @Summary, @Description, @RawData); select last_insert_rowid()";
127              DbParameter agentIdParam = c.CreateParameter();
128              agentIdParam.ParameterName = "@AgentId";
129              agentIdParam.Value = agentId;
130              c.Parameters.Add(agentIdParam);
131              DbParameter creationParam = c.CreateParameter();
132              creationParam.ParameterName = "@CreationTime";
133              DateTime now = DateTime.Now;
134              creationParam.Value = now;
135              c.Parameters.Add(creationParam);
136              DbParameter summaryParam = c.CreateParameter();
137              summaryParam.ParameterName = "@Summary";
138              summaryParam.Value = summary;
139              c.Parameters.Add(summaryParam);
140              DbParameter descParam = c.CreateParameter();
141              descParam.ParameterName = "@Description";
142              descParam.Value = description;
143              c.Parameters.Add(descParam);
144              DbParameter rawDataParam = c.CreateParameter();
145              rawDataParam.ParameterName = "@RawData";
146              rawDataParam.Value = rawData;
147              c.Parameters.Add(rawDataParam);
148              id = (long)c.ExecuteScalar();
149            }
150            t.Commit();
151            return id;
152          }
153        }
154      } finally {
155        rwLock.ExitWriteLock();
156      }
157    }
158
159    public long InsertSubResult(long resultId, string summary, string description, byte[] rawData) {
160      rwLock.EnterWriteLock();
161      try {
162        using(SQLiteConnection cnn = new SQLiteConnection(connectionString)) {
163          cnn.Open();
164          long id;
165          using(DbTransaction t = cnn.BeginTransaction()) {
166            using(DbCommand c = cnn.CreateCommand()) {
167              c.Transaction = t;
168              c.CommandText = "Insert into Result (ParentResultId, CreationTime, Summary, Description, RawData) values (@ParentResultId, @CreationTime, @Summary, @Description, @RawData); select last_insert_rowid()";
169              DbParameter resultIdParam = c.CreateParameter();
170              resultIdParam.ParameterName = "@ParentResultId";
171              resultIdParam.Value = resultId;
172              c.Parameters.Add(resultIdParam);
173              DbParameter creationParam = c.CreateParameter();
174              creationParam.ParameterName = "@CreationTime";
175              DateTime now = DateTime.Now;
176              creationParam.Value = now;
177              c.Parameters.Add(creationParam);
178              DbParameter summaryParam = c.CreateParameter();
179              summaryParam.ParameterName = "@Summary";
180              summaryParam.Value = summary;
181              c.Parameters.Add(summaryParam);
182              DbParameter descParam = c.CreateParameter();
183              descParam.ParameterName = "@Description";
184              descParam.Value = description;
185              c.Parameters.Add(descParam);
186              DbParameter rawDataParam = c.CreateParameter();
187              rawDataParam.ParameterName = "@RawData";
188              rawDataParam.Value = rawData;
189              c.Parameters.Add(rawDataParam);
190              id = (long)c.ExecuteScalar();
191            }
192            t.Commit();
193            return id;
194          }
195        }
196      } finally {
197        rwLock.ExitWriteLock();
198      }
199    }
200    #endregion
201
202    #region update agent/run
203    public void UpdateAgent(long id, string name) {
204      rwLock.EnterWriteLock();
205      try {
206        using(SQLiteConnection cnn = new SQLiteConnection(connectionString)) {
207          cnn.Open();
208          using(SQLiteTransaction t = cnn.BeginTransaction()) {
209            using(SQLiteCommand c = cnn.CreateCommand()) {
210              c.Transaction = t;
211              c.CommandText = "Update Agent set Name=@Name where id=@Id";
212              DbParameter nameParam = c.CreateParameter();
213              DbParameter idParam = c.CreateParameter();
214              nameParam.ParameterName = "@Name";
215              nameParam.Value = name;
216              idParam.ParameterName = "@Id";
217              idParam.Value = id;
218              c.Parameters.Add(nameParam);
219              c.Parameters.Add(idParam);
220              c.ExecuteNonQuery();
221            }
222            t.Commit();
223          }
224        }
225      } finally {
226        rwLock.ExitWriteLock();
227      }
228    }
229
230    public void UpdateAgent(long id, ProcessStatus status) {
231      rwLock.EnterWriteLock();
232      try {
233        using(SQLiteConnection cnn = new SQLiteConnection(connectionString)) {
234          cnn.Open();
235          using(SQLiteTransaction t = cnn.BeginTransaction()) {
236            using(SQLiteCommand c = cnn.CreateCommand()) {
237              c.Transaction = t;
238              c.CommandText = "Update Agent set Status=@Status where id=@Id";
239              DbParameter statusParam = c.CreateParameter();
240              DbParameter idParam = c.CreateParameter();
241              statusParam.ParameterName = "@Status";
242              statusParam.Value = status.ToString();
243              idParam.ParameterName = "@Id";
244              idParam.Value = id;
245              c.Parameters.Add(statusParam);
246              c.Parameters.Add(idParam);
247              c.ExecuteNonQuery();
248            }
249            t.Commit();
250          }
251        }
252      } finally {
253        rwLock.ExitWriteLock();
254      }
255    }
256
257    public void UpdateAgent(long id, byte[] rawData) {
258      rwLock.EnterWriteLock();
259      try {
260        using(SQLiteConnection cnn = new SQLiteConnection(connectionString)) {
261          cnn.Open();
262          using(SQLiteTransaction t = cnn.BeginTransaction()) {
263            using(SQLiteCommand c = cnn.CreateCommand()) {
264              c.Transaction = t;
265              c.CommandText = "Update Agent set RawData=@RawData where id=@Id";
266              DbParameter rawDataParam = c.CreateParameter();
267              DbParameter idParam = c.CreateParameter();
268              rawDataParam.ParameterName = "@RawData";
269              rawDataParam.Value = rawData;
270              idParam.ParameterName = "@Id";
271              idParam.Value = id;
272              c.Parameters.Add(rawDataParam);
273              c.Parameters.Add(idParam);
274              c.ExecuteNonQuery();
275            }
276            t.Commit();
277          }
278        }
279      } finally {
280        rwLock.ExitWriteLock();
281      }
282    }
283
284    #endregion
285
286    #region get agent/run/result/sub-result
287
288    public ICollection<AgentEntry> GetAgents(ProcessStatus status) {
289      rwLock.EnterReadLock();
290      List<AgentEntry> agents = new List<AgentEntry>();
291      try {
292        using(SQLiteConnection cnn = new SQLiteConnection(connectionString)) {
293          cnn.Open();
294          SQLiteCommand c = cnn.CreateCommand();
295          c.CommandText = "Select id, name, ControllerAgent, rawdata from Agent where Status=@Status";
296          DbParameter statusParameter = c.CreateParameter();
297          statusParameter.ParameterName = "@Status";
298          statusParameter.Value = status.ToString();
299          c.Parameters.Add(statusParameter);
300
301          SQLiteDataReader r = c.ExecuteReader();
302          while(r.Read()) {
303            AgentEntry agent = new AgentEntry();
304            agent.ParentAgentId = null;
305            agent.Status = status;
306            agent.Id = r.GetInt32(0);
307            agent.Name = r.IsDBNull(1)?"":r.GetString(1);
308            agent.ControllerAgent = r.GetBoolean(2);
309            agent.RawData = (byte[])r.GetValue(3);
310            agents.Add(agent);
311          }
312        }
313      } finally {
314        rwLock.ExitReadLock();
315      }
316      return agents;
317    }
318
319    public ICollection<AgentEntry> GetAgents() {
320      rwLock.EnterReadLock();
321      List<AgentEntry> agents = new List<AgentEntry>();
322      try {
323        using(DbConnection cnn = new SQLiteConnection(connectionString)) {
324          cnn.Open();
325          using(DbCommand c = cnn.CreateCommand()) {
326            c.CommandText = "Select id, ParentAgentId, name, status, ControllerAgent, rawdata from Agent";
327            using(DbDataReader r = c.ExecuteReader()) {
328              while(r.Read()) {
329                AgentEntry agent = new AgentEntry();
330                agent.Id = r.GetInt32(0);
331                agent.ParentAgentId = r.IsDBNull(1) ? null : new Nullable<long>(r.GetInt32(1));
332                agent.Name = r.GetString(2);
333                agent.Status = (ProcessStatus)Enum.Parse(typeof(ProcessStatus), r.GetString(3));
334                agent.ControllerAgent = r.GetBoolean(4);
335                agent.RawData = (byte[])r.GetValue(5);
336                agents.Add(agent);
337              }
338            }
339          }
340        }
341      } finally {
342        rwLock.ExitReadLock();
343      }
344      return agents;
345    }
346
347    public ICollection<AgentEntry> GetSubAgents(long parentAgentId) {
348      rwLock.EnterReadLock();
349      List<AgentEntry> agents = new List<AgentEntry>();
350      try {
351        using(DbConnection cnn = new SQLiteConnection(connectionString)) {
352          cnn.Open();
353          using(DbCommand c = cnn.CreateCommand()) {
354            c.CommandText = "Select id, name, status, controllerAgent, rawdata from Agent where ParentAgentId=@ParentAgentId";
355            using(DbDataReader r = c.ExecuteReader()) {
356              while(r.Read()) {
357                AgentEntry agent = new AgentEntry();
358                agent.ParentAgentId = parentAgentId;
359                agent.Id = r.GetInt32(0);
360                agent.Name = r.GetString(1);
361                agent.Status = (ProcessStatus)Enum.Parse(typeof(ProcessStatus), r.GetString(2));
362                agent.ControllerAgent = r.GetBoolean(3);
363                agent.RawData = (byte[])r.GetValue(4);
364                agents.Add(agent);
365              }
366            }
367          }
368        }
369      } finally {
370        rwLock.ExitReadLock();
371      }
372      return agents;
373    }
374
375    public ICollection<ResultEntry> GetResults(long agentId) {
376      List<ResultEntry> results = new List<ResultEntry>();
377      rwLock.EnterReadLock();
378      try {
379        using(DbConnection cnn = new SQLiteConnection(connectionString)) {
380          cnn.Open();
381          using(DbCommand c = cnn.CreateCommand()) {
382            c.CommandText = "Select Id, CreationTime, Summary, Description, Rawdata from Result where AgentId=@AgentId";
383            DbParameter agentParam = c.CreateParameter();
384            agentParam.ParameterName = "@AgentId";
385            agentParam.Value = agentId;
386            c.Parameters.Add(agentParam);
387            using(DbDataReader r = c.ExecuteReader()) {
388              while(r.Read()) {
389                ResultEntry result = new ResultEntry();
390                result.AgentId = agentId;
391                result.Id = r.GetInt32(0);
392                result.CreationTime = r.GetDateTime(1);
393                result.Summary = r.GetString(2);
394                result.Description = r.GetString(3);
395                result.RawData = (byte[])r.GetValue(4);
396                results.Add(result);
397              }
398            }
399          }
400        }
401      } finally {
402        rwLock.ExitReadLock();
403      }
404      return results;
405    }
406
407    public ICollection<ResultEntry> GetSubResults(long resultId) {
408      List<ResultEntry> results = new List<ResultEntry>();
409      rwLock.EnterReadLock();
410      try {
411        using(DbConnection cnn = new SQLiteConnection(connectionString)) {
412          cnn.Open();
413          using(DbCommand c = cnn.CreateCommand()) {
414            c.CommandText = "Select Id, CreationTime, Summary, Description, Rawdata from Result where ParentResultId=@ParentResultId";
415            DbParameter parentParam = c.CreateParameter();
416            parentParam.ParameterName = "@ParentResultId";
417            parentParam.Value = resultId;
418            c.Parameters.Add(parentParam);
419            using(DbDataReader r = c.ExecuteReader()) {
420              while(r.Read()) {
421                ResultEntry result = new ResultEntry();
422                result.ParentResultId = resultId;
423                result.Id = r.GetInt32(0);
424                result.CreationTime = r.GetDateTime(1);
425                result.Summary = r.GetString(2);
426                result.Description = r.GetString(3);
427                result.RawData = (byte[])r.GetValue(4);
428                results.Add(result);
429              }
430            }
431          }
432        }
433      } finally {
434        rwLock.ExitReadLock();
435      }
436      return results;
437    }
438    #endregion
439  }
440}
Note: See TracBrowser for help on using the repository browser.