Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.DataAccess.ADOHelper/3.2/DataAdapterBase.cs @ 2285

Last change on this file since 2285 was 2084, checked in by svonolfe, 15 years ago

Further improved handling of job objects (#372)

File size: 7.6 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.Data;
24using System.Collections.Generic;
25using System.Text;
26using System.Linq;
27using System.Threading;
28using HeuristicLab.DataAccess.Interfaces;
29
30namespace HeuristicLab.DataAccess.ADOHelper {
31  public abstract class DataAdapterBase<AdapterT, ObjT, RowT>
32    where AdapterT : new()
33    where RowT : System.Data.DataRow
34    where ObjT : IPersistableObject, new() {
35
36    private ISession session;
37
38    private ITableAdapterWrapper<AdapterT, ObjT, RowT> dataAdapter;
39
40    protected DataAdapterBase(
41      ITableAdapterWrapper<AdapterT, ObjT, RowT> dataAdapter) {
42      this.dataAdapter = dataAdapter;
43    }
44
45    protected AdapterT Adapter {
46      get {
47        return dataAdapter.TransactionalAdapter;
48      }
49    }
50
51    protected ITableAdapterWrapper<AdapterT, ObjT, RowT> DataAdapterWrapper {
52      get {
53        return dataAdapter;
54      }
55    }
56
57    public ISession Session {
58      get {
59        return this.session;
60      }
61
62      set {
63        if (!(value is Session))
64          throw new Exception("Can only bind to ADO session");
65
66        this.session = value;
67        this.dataAdapter.Session = value as Session;
68      }
69    }
70
71    public object InnerAdapter {
72      get {
73        return this.Adapter;
74      }
75    }
76
77    #region Abstract methods
78    protected abstract RowT ConvertObj(ObjT obj, RowT row);
79
80    protected abstract ObjT ConvertRow(RowT row, ObjT obj);
81    #endregion
82
83    protected delegate IEnumerable<RowT> Selector();
84    protected delegate object TransactionalAction();
85
86    protected ObjT Convert(RowT row, ObjT obj) {
87      try {
88        obj = ConvertRow(row, obj);
89        return obj;
90      }
91      catch (DeletedRowInaccessibleException) {
92        return default(ObjT);
93      }
94      catch (RowNotInTableException) {
95        return default(ObjT);
96      }
97    }
98
99    protected RowT FindSingleRow(Selector selector) {
100      RowT row = default(RowT);
101
102      IEnumerable<RowT> found =
103        selector();
104
105      if (found.Count<RowT>() == 1)
106        row = found.First<RowT>();
107
108      return row;
109    }
110
111    protected ObjT FindSingle(Selector selector) {
112      return
113        (ObjT)doInTransaction(
114         delegate() {
115          RowT row = FindSingleRow(selector);
116
117          ObjT result;
118          if (row != null) {
119            ObjT obj = new ObjT();
120            obj = Convert(row, obj);
121
122            result = obj;
123          } else {
124            result = default(ObjT);
125          }
126
127          return result;
128        });
129    }
130
131    private ICollection<ObjT> FindMultiple(Selector selector,
132      int from, int size) {
133      return (ICollection<ObjT>)doInTransaction(
134        delegate() {
135          IEnumerable<RowT> found =
136            selector();
137
138          if (from > 0 && size > 0)
139            found = found.Skip<RowT>(from).Take<RowT>(size);
140
141          IList<ObjT> result =
142            new List<ObjT>();
143
144          foreach (RowT row in found) {
145            ObjT obj = new ObjT();
146            obj = Convert(row, obj);
147            if (obj != null)
148              result.Add(obj);
149          }
150
151          return result;
152        });   
153    }
154
155    protected ICollection<ObjT> FindMultiple(Selector selector) {
156      return FindMultiple(
157        selector, 0, -1);
158    }
159
160    protected virtual RowT GetRowById(Guid id) {
161      return FindSingleRow(
162        delegate() {
163          return dataAdapter.FindById(id);
164        });
165    }
166
167    protected object doInTransaction(TransactionalAction action) {
168      ITransaction trans =
169        session.GetCurrentTransaction();
170      bool transactionExists = trans != null;
171      if (!transactionExists) {
172        trans = session.BeginTransaction();
173      }
174
175      try {
176        object result = action();
177
178        if (!transactionExists && trans != null) {
179            trans.Commit();
180        }
181
182        return result;
183      }
184      catch (Exception e) {
185        if (!transactionExists && trans != null) {
186          trans.Rollback();
187        }
188
189        throw e;
190      }
191    }
192
193    protected virtual void doUpdate(ObjT obj) {
194      if (obj != null) {
195        RowT row = null;
196
197        if (obj.Id != Guid.Empty) {
198          row = GetRowById(obj.Id);
199        } else {
200          obj.Id = Guid.NewGuid();
201        }
202
203        if (row == null) {
204          row = dataAdapter.InsertNewRow(obj);
205        }
206
207        ConvertObj(obj, row);
208        dataAdapter.UpdateRow(row);
209      }
210    }
211
212    public void Update(ObjT obj) {
213      try {
214        doInTransaction(
215          delegate() {
216            doUpdate(obj);
217            return true;
218          });       
219      }
220      catch (DBConcurrencyException ex) {
221        DataRow row = ex.Row;
222
223        RowT current = GetRowById(obj.Id);
224        if (current != null) {
225          //find out changes
226          for (int i = 0; i < row.ItemArray.Length; i++) {           
227            if (!row[i, DataRowVersion.Current].Equals(
228                 row[i, DataRowVersion.Original])) {
229              current[i] = row[i];
230            }
231          }
232
233          ConvertRow(current, obj);
234          //try updating again
235          Update(obj);
236        }
237        //otherwise: row was deleted in the meantime - nothing to do
238      }
239    }
240
241    public virtual ObjT GetById(Guid id) {
242      return FindSingle(delegate() {
243        return dataAdapter.FindById(id);
244      });
245    }
246
247    public virtual ICollection<ObjT> GetAll() {
248      return new List<ObjT>(
249        FindMultiple(
250          new Selector(dataAdapter.FindAll)));
251    }
252
253    public virtual ICollection<ObjT> GetAll(int from, int size) {
254      //note - this base implementation is inefficient,
255      //consider overriding the implementation
256      //in derived adapters (based on a query (SQL LIMIT))
257      return new List<ObjT>(
258        FindMultiple(
259          new Selector(dataAdapter.FindAll),
260          from, size));
261    }
262
263    protected virtual bool doDelete(ObjT obj) {
264      bool success = false;
265
266      if (obj != null) {
267        RowT row =
268          GetRowById(obj.Id);
269
270        if (row != null) {
271          row.Delete();
272          dataAdapter.UpdateRow(row);
273
274          success = true;
275        }
276      }
277
278      return success;
279    }
280
281    public bool Delete(ObjT obj) {
282      try {
283        return (bool)doInTransaction(
284          delegate() {
285            return doDelete(obj);
286          });
287      }
288      catch (DBConcurrencyException) {
289        RowT current = GetRowById(obj.Id);
290        if (current != null) {
291          ConvertRow(current, obj);
292          //try deleting again
293          return Delete(obj);
294        } else {
295          //row has already been deleted
296          return false;
297        }
298      }
299    }
300  }
301}
302
Note: See TracBrowser for help on using the repository browser.