summaryrefslogtreecommitdiffstats
path: root/akregator/src/mk4storage/metakit/src/store.cpp
blob: f43bc0e395728becec5cc7eb3f7435864feace39 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
// store.cpp --
// $Id$
// This is part of Metakit, the homepage is http://www.equi4.com/metakit/

/** @file
 * Storage management and several other loose ends
 */

#include "header.h"
#include "handler.h"  // 19990906
#include "store.h"
#include "field.h"
#include "persist.h"
#include "format.h"   // 19990906

#include "mk4io.h"    // 19991104

#if !q4_INLINE
#include "store.inl"
#endif
  
/////////////////////////////////////////////////////////////////////////////

c4_Dependencies::c4_Dependencies ()
{
  _refs.SetSize(0, 3);  // a little optimization
}

c4_Dependencies::~c4_Dependencies ()
{
}

void c4_Dependencies::Add(c4_Sequence* seq_)
{
  for (int i = 0; i < _refs.GetSize(); ++i)
    d4_assert(_refs.GetAt(i) != seq_);

  _refs.Add(seq_);
}

bool c4_Dependencies::Remove(c4_Sequence* seq_)
{
  int n = _refs.GetSize() - 1;
  d4_assert(n >= 0);

  for (int i = 0; i <= n; ++i)
    if (_refs.GetAt(i) == seq_) {
      _refs.SetAt(i, _refs.GetAt(n));     
      _refs.SetSize(n);
      return n > 0;
    }

  d4_assert(0); // dependency not found
  return true;
}

/////////////////////////////////////////////////////////////////////////////

c4_Notifier::~c4_Notifier ()
{
  if (_type > kNone && _origin->GetDependencies()) {
    c4_PtrArray& refs = _origin->GetDependencies()->_refs;

    for (int i = 0; i < refs.GetSize(); ++i) {
      c4_Sequence* seq = (c4_Sequence*) refs.GetAt(i);
      d4_assert(seq != 0);

      seq->PostChange(*this);

      if (_chain && _chain->_origin == seq) {
        c4_Notifier* next = _chain->_next;
        _chain->_next = 0;

        delete _chain;
        
        _chain = next;
      }
    }
  }

  d4_assert(!_chain);
  d4_assert(!_next);
}

void c4_Notifier::StartSetAt(int index_, c4_Cursor& cursor_)
{
  _type = kSetAt;
  _index = index_;
  _cursor = &cursor_;
  
  Notify();
}

void c4_Notifier::StartInsertAt(int i_, c4_Cursor& cursor_, int n_)
{
  _type = kInsertAt;
  _index = i_;
  _cursor = &cursor_;
  _count = n_;
  
  Notify();
}

void c4_Notifier::StartRemoveAt(int index_, int count_)
{
  _type = kRemoveAt;
  _index = index_;
  _count = count_;
  
  Notify();
}

void c4_Notifier::StartMove(int from_, int to_)
{
  _type = kMove;
  _index = from_;
  _count = to_;
  
  Notify();
}

void c4_Notifier::StartSet(int i_, int propId_, const c4_Bytes& buf_)
{
  _type = kSet;
  _index = i_;
  _propId = propId_;
  _bytes = &buf_;
  
  Notify();
}

void c4_Notifier::Notify()
{
  d4_assert(_origin->GetDependencies() != 0);
  c4_PtrArray& refs = _origin->GetDependencies()->_refs;

  int n = refs.GetSize();
  d4_assert(n > 0);
  
  c4_Notifier** rover = &_chain;

  for (int i = 0; i < n; ++i) {
    c4_Sequence* seq = (c4_Sequence*) refs.GetAt(i);
    d4_assert(seq != 0);

    c4_Notifier* ptr = seq->PreChange(*this);
    if (ptr) {
      d4_assert(ptr->_origin == seq);

      d4_assert(!*rover);
      *rover = ptr;
      rover = &ptr->_next;
    }
  }
}

/////////////////////////////////////////////////////////////////////////////

/** @class c4_Storage
 *
 *  Manager for persistent storage of view structures.
 *
 *  The storage class uses a view, with additional functionality to be able 
 *  to store and reload the data it tqcontains (including nested subviews).
 *
 *  By default, data is loaded on demand, i.e. whenever data which has
 *  not yet been referenced is used for the first time.  Loading is limited
 *  to the lifetime of this storage object, since the storage object carries
 *  the file descriptor with it that is needed to access the data file.
 *
 *  To save changes, call the Commit member.  This is the only time
 *  that data is written to file - when using a read-only file simply avoid
 *  calling Commit.
 *
 *  The LoadFromStream and SaveToStream members can be used to
 *  serialize the contents of this storage row using only sequential I/O
 *  (no seeking, only read or write calls).
 *
 *  The data storage mechanism implementation provides fail-safe operation:
 *  if anything prevents Commit from completing its task, the last
 *  succesfully committed version of the saved data will be recovered on
 *  the next open. This also includes changes made to the table structure. 
 *
 *  The following code creates a view with 1 row and stores it on file:
 * @code
 *    c4_StringProp pName ("Name");
 *    c4_IntProp pAge ("Age");
 *
 *    c4_Storage storage ("myfile.dat", true);
 *    c4_View myView = storage.GetAs("Musicians[Name:S,Age:I]");
 *
 *    myView.Add(pName ["John Williams"] + pAge [43]);
 *
 *    storage.Commit();
 * @endcode
 */

c4_Storage::c4_Storage ()
{
    // changed to r/o, now that commits don't crash on it anymore
  Initialize(*d4_new c4_Strategy, true, 0);
}

c4_Storage::c4_Storage (c4_Strategy& strategy_, bool owned_, int mode_)
{
  Initialize(strategy_, owned_, mode_);
  Persist()->LoadAll();
}

c4_Storage::c4_Storage (const char* fname_, int mode_)
{
  c4_FileStrategy* strat = d4_new c4_FileStrategy;
  strat->DataOpen(fname_, mode_);

  Initialize(*strat, true, mode_);
  if (strat->IsValid())
    Persist()->LoadAll();
}

c4_Storage::c4_Storage (const c4_View& root_)
{
  if (root_.Persist() != 0) // only restore if view was indeed persistent
    *(c4_View*) this = root_;
  else // if this was not possible, start with a fresh empty storage
    Initialize(*d4_new c4_Strategy, true, 0);
}

c4_Storage::~c4_Storage ()
{
  // cannot unmap here, because there may still be an autocommit pending
  //((c4_HandlerSeq*) _seq)->UnmapAll();
}

void c4_Storage::Initialize(c4_Strategy& strategy_, bool owned_, int mode_)
{
  c4_Persist* pers = d4_new c4_Persist (strategy_, owned_, mode_);
  c4_HandlerSeq* seq = d4_new c4_HandlerSeq (pers);
  seq->DefineRoot();
  *(c4_View*) this = seq;
  pers->SetRoot(seq);
}

  /// Get or set a named view in this storage object
c4_ViewRef c4_Storage::View(const char* name_)
{
  /*
    The easy solution would seem to be:

      c4_ViewProp prop (name_);
      return prop (Contents());

    But this does not work, because the return value would point to
    an object allocated on the stack.

    Instead, make sure the view *has* such a property, and use the
    one inside the c4_Handler for it (since this will stay around).
  */

//  int n = _root->PropIndex(c4_ViewProp (name_));

  c4_ViewProp prop (name_);
  int n = AddProperty(prop);
  d4_assert(n >= 0);

    // the following is an expression of the form "property (rowref)"
  return NthProperty(n) (GetAt(0));
}

  /// Get a named view, redefining it to match the given structure
c4_View c4_Storage::GetAs(const char* description_)
{
  d4_assert(description_ != 0);

    // Dec 2001: now that GetAs is being used so much more frequently, 
    // add a quick check to see whether restructuring is needed at all
  const char* q = strchr(description_, '[');
  if (q != 0) {
    c4_String vname (description_, q - description_);
    const char* d = Description(vname);
    if (d != 0) {
      c4_String desc (d);
      if (("[" + desc + "]").CompareNoCase(q) == 0)
	return View(vname);
    }
  }

  c4_Field* field = d4_new c4_Field (description_);
  d4_assert(field != 0);

  d4_assert(!*description_);

  c4_String name = field->Name();
  d4_assert(!name.IsEmpty());

  c4_Field& curr = Persist()->Root().Definition();

  c4_String newField = "," + field->Description();
  bool keep = newField.Find('[') >= 0;

  c4_String newDef;

    // go through all subfields
  for (int i = 0; i < curr.NumSubFields(); ++i) {
    c4_Field& of = curr.SubField(i);   
    if (of.Name().CompareNoCase(name) == 0) {
      if (field->IsRepeating())
        newDef += newField;
      // else new is not a repeating entry, so drop this entire field
      
      newField.Empty(); // don't append it later on
      continue;
    }

    newDef += "," + of.Description(); // keep original field
  }

  if (keep)       // added 19990824 ignore if deletion
    newDef += newField; // appends new definition if not found earlier

  delete field;

  const char* p = newDef;
  SetStructure(*p ? ++p : p); // skip the leading comma

  if (!keep)        // 19990916: avoid adding an empty view again
    return c4_View ();

  return View(name);
}

  /// Define the complete view structure of the storage
void c4_Storage::SetStructure(const char* description_)
{
  d4_assert(description_ != 0);

  if (description_ != Description()) {
    c4_String s = "[" + c4_String (description_) + "]";
    description_ = s;

    c4_Field* field = d4_new c4_Field (description_);
    d4_assert(!*description_);

    d4_assert(field != 0);
    Persist()->Root().Restructure(*field, false);
  }
}

  /// Return the strategy object associated with this storage
c4_Strategy& c4_Storage::Strategy() const
{
  return Persist()->Strategy();
}

  /// Return a description of the view structure (default is all)
const char* c4_Storage::Description(const char* name_)
{
  if (name_ == 0 || *name_ == 0)
    return c4_View::Description();

  c4_View v = View(name_);
  return v.Description();
}

  /// Define the storage to use for differential commits
bool c4_Storage::SetAside(c4_Storage& aside_)
{
  c4_Persist* pers = Persist();
  bool f = pers->SetAside(aside_);
  // adjust our copy when the root view has been tqreplaced
  *(c4_View*) this = &pers->Root();
  return f;
}

  /// Return storage used for differential commits, or null
c4_Storage* c4_Storage::GetAside() const
{
  return Persist()->GetAside();
}

  /// Flush pending changes to file right now
bool c4_Storage::Commit(bool full_)
{
  return Strategy().IsValid() && Persist()->Commit(full_);
}

/** (Re)initialize for on-demand loading
 *
 *  Calling Rollback will cancel all uncommitted changes.
 */
bool c4_Storage::Rollback(bool full_)
{
  c4_Persist* pers = Persist();
  bool f = Strategy().IsValid() && pers->Rollback(full_);
  // adjust our copy when the root view has been tqreplaced
  *(c4_View*) this = &pers->Root();
  return f;
}

  /// Set storage up to always call Commit in the destructor
bool c4_Storage::AutoCommit(bool flag_)
{
  return Persist()->AutoCommit(flag_);
}

  /// Load contents from the specified input stream
bool c4_Storage::LoadFrom(c4_Stream& stream_)
{
  c4_HandlerSeq* newRoot = c4_Persist::Load(&stream_);
  if (newRoot == 0)
    return false;

    // fix commit-after-load bug, by using a full view copy
  // this is inefficient, but avoids mapping/strategy problems
  c4_View temp (newRoot);

  SetSize(0);
  SetStructure(temp.Description());
  InsertAt(0, temp);

  return true;
}

  /// Save contents to the specified output stream
void c4_Storage::SaveTo(c4_Stream& stream_)
{
  c4_Persist::Save(&stream_, Persist()->Root());
}

/////////////////////////////////////////////////////////////////////////////

c4_DerivedSeq::c4_DerivedSeq (c4_Sequence& seq_)
  : _seq (seq_)
{
  _seq.Attach(this);
}

c4_DerivedSeq::~c4_DerivedSeq ()
{
  _seq.Detach(this);
}
  
int c4_DerivedSeq::RemapIndex(int index_, const c4_Sequence* seq_) const
{
  return seq_ == this ? index_ : _seq.RemapIndex(index_, seq_);
}
  
int c4_DerivedSeq::NumRows() const
{
  return _seq.NumRows();
}

int c4_DerivedSeq::NumHandlers() const
{
  return _seq.NumHandlers();
}

c4_Handler& c4_DerivedSeq::NthHandler(int colNum_) const
{
  return _seq.NthHandler(colNum_);
}

const c4_Sequence* c4_DerivedSeq::HandlerContext(int colNum_) const
{
  return  _seq.HandlerContext(colNum_);
}

int c4_DerivedSeq::AddHandler(c4_Handler* handler_)
{
  return _seq.AddHandler(handler_);
}

c4_Handler* c4_DerivedSeq::CreateHandler(const c4_Property& prop_)
{
  return _seq.CreateHandler(prop_);
}

void c4_DerivedSeq::SetNumRows(int size_)
{
  _seq.SetNumRows(size_);
}

c4_Notifier* c4_DerivedSeq::PreChange(c4_Notifier& nf_)
{
  if (!GetDependencies())
    return 0;

  c4_Notifier* chg = d4_new c4_Notifier (this);

  switch (nf_._type)
  {
    case c4_Notifier::kSetAt:
      chg->StartSetAt(nf_._index, *nf_._cursor);
      break;

    case c4_Notifier::kSet:
      chg->StartSet(nf_._index, nf_._propId, *nf_._bytes);
      break;

    case c4_Notifier::kInsertAt:
      chg->StartInsertAt(nf_._index, *nf_._cursor, nf_._count);
      break;

    case c4_Notifier::kRemoveAt:
      chg->StartRemoveAt(nf_._index, nf_._count);
      break;

    case c4_Notifier::kMove:
      chg->StartMove(nf_._index, nf_._count);
      break;
  }

  return chg;
}

/////////////////////////////////////////////////////////////////////////////

c4_StreamStrategy::c4_StreamStrategy (t4_i32 buflen_)
  : _stream (0), _buffer (d4_new t4_byte [buflen_]), _buflen (buflen_), _position (0)
{
  _mapStart = _buffer;
  _dataSize = buflen_;
}

c4_StreamStrategy::c4_StreamStrategy (c4_Stream* stream_)
  : _stream (stream_), _buffer (0), _buflen (0), _position (0)
{
}

c4_StreamStrategy::~c4_StreamStrategy ()
{
  _mapStart = 0;
  _dataSize = 0;
  
  if (_buffer != 0)
    delete [] _buffer;
}

bool c4_StreamStrategy::IsValid() const
{
  return true;
}

int  c4_StreamStrategy::DataRead(t4_i32 pos_, void* buffer_, int length_)
{
  if (_buffer != 0) {
    d4_assert(pos_ <= _buflen);
    _position = pos_ + _baseOffset;

    if (length_ > _buflen - _position)
      length_ = _buflen - _position;
    if (length_ > 0)
      memcpy(buffer_, _buffer + _position, length_);
  } else {
    d4_assert(_position == pos_ + _baseOffset);
    length_ = _stream != 0 ? _stream->Read(buffer_, length_) : 0;
  }

  _position += length_;
  return length_;
}

void c4_StreamStrategy::DataWrite(t4_i32 pos_, const void* buffer_, int length_)
{
  if (_buffer != 0) {
    d4_assert(pos_ <= _buflen);
    _position = pos_ + _baseOffset;

    int n = length_;
    if (n > _buflen - _position)
      n = _buflen - _position;
    if (n > 0)
      memcpy(_buffer + _position, buffer_, n);
  } else {
    d4_assert(_position == pos_ + _baseOffset);
    if (_stream != 0 && !_stream->Write(buffer_, length_))
      ++_failure;
  }

  _position += length_;
}

t4_i32 c4_StreamStrategy::FileSize()
{
  return _position;
}

/////////////////////////////////////////////////////////////////////////////