Source

Usually / Usually / Resolve.cs

Full commit
  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
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
using System;
using System.Collections.Generic;
using System.Linq;

namespace Usually
{
    public interface ITransactor
    {
        void Insert(InsertRecord ins);
        void Update(UpdateRecord upd);
        void Delete(DeleteRecord del);
    }
    public abstract class TransactionRecord
    {
        public string TableName = null;
        protected TransactionRecord() : this(null) { }
        protected TransactionRecord(string tableName) { this.TableName = @tableName; }
        public abstract TransactionRecord CloneRecord();
        public abstract void Execute(ITransactor actor);
    }
    public sealed class InsertRecord : TransactionRecord
    {
        public InsertRecord() : base() { }
        public InsertRecord(string tableName) : base(tableName) { }
        public IDictionary<string, object> Values = new Dictionary<string, object>();
        public InsertRecord CloneInsert()
        {
            var r = new InsertRecord();
            r.TableName = this.TableName;
            foreach (var i in this.Values) r.Values[i.Key] = i.Value;
            return r;
        }
        public override TransactionRecord CloneRecord()
        {
            return this.CloneInsert();
        }
        public override void Execute(ITransactor actor)
        {
            actor.Insert(this);
        }
    }
    public sealed class UpdateRecord : TransactionRecord
    {
        public UpdateRecord() : base() { }
        public UpdateRecord(string tableName) : base(tableName) { }
        public bool AtLeastOne = false;
        public bool AtMostOne = false;
        public void TheOne()
        {
            this.AtLeastOne = true;
            this.AtMostOne = true;
        }
        public IDictionary<string, object> Keys = new Dictionary<string, object>();
        public IDictionary<string, object> Values = new Dictionary<string, object>();
        public UpdateRecord CloneUpdate()
        {
            var r = new UpdateRecord();
            r.TableName = this.TableName;
            r.AtLeastOne = this.AtLeastOne;
            r.AtMostOne = this.AtMostOne;
            foreach (var i in this.Keys) r.Keys[i.Key] = i.Value;
            foreach (var i in this.Values) r.Values[i.Key] = i.Value;
            return r;
        }
        public override TransactionRecord CloneRecord()
        {
            return this.CloneUpdate();
        }
        public override void Execute(ITransactor actor)
        {
            actor.Update(this);
        }
    }
    public sealed class DeleteRecord : TransactionRecord
    {
        public DeleteRecord() : base() { }
        public DeleteRecord(string tableName) : base(tableName) { }
        public bool AtLeastOne = false;
        public bool AtMostOne = false;
        public void TheOne()
        {
            this.AtLeastOne = true;
            this.AtMostOne = true;
        }
        public IDictionary<string, object> Keys = new Dictionary<string, object>();
        public UpdateRecord CloneDelete()
        {
            var r = new UpdateRecord();
            r.TableName = this.TableName;
            r.AtLeastOne = this.AtLeastOne;
            r.AtMostOne = this.AtMostOne;
            foreach (var i in this.Keys) r.Keys[i.Key] = i.Value;
            return r;
        }
        public override TransactionRecord CloneRecord()
        {
            return this.CloneDelete();
        }
        public override void Execute(ITransactor actor)
        {
            actor.Delete(this);
        }
    }
    public class TransactionJournal<T>
    {
        public TransactionRecord Record;
        public T Old;
        public T New;
    }
    public interface IKeyBuilder<T>
    {
        void Key(string name, Func<T, object> getKey, Func<object, string> generator = null);
    }
    public interface IMetaBuilder<T> : IKeyBuilder<T>
    {
        void Table(string name);
        void MasterExtaKey(string group);
        void Ref(string name, Func<T, object> getRef);
        void Value(string name, Func<T, object> getValue);
        IKeyBuilder<T> ExtraKey(string group);
    }
    public interface IMetaInfo<T>
    {
        string TableName { get; }
        object[] GetKey(T obj);
        object[] GetKey(IDictionary<string, object> dict);
        object[] GetExtraKey(string group, T obj);
        object[] GetExtraKey(string group, IDictionary<string, object> dict);
        string GeneratorExpr(string name, object value);
        void ForEachKey(T obj, Action<string, object> action);
        void ForEachExtraKey(string group, T obj, Action<string, object> action);
        void ForEachInsertValue(T obj, Action<string, object> action);
        void ForEachValueChange(T o, T n, Action<string, object, object> action);
        string MasterKeyGroup { get; }
        object[] GetMasterRef(T obj);
        void SetActualMasterKey(IDictionary<string, object> dict, object[] actualKey);
    }
    public static class MetaBuilderExtension
    {
        public static void Key<T>(this IKeyBuilder<T> m, string name, Func<T, object> getKey, string sequence, Func<object, bool> isDummy)
        {
            m.Key(name, getKey, (x) => (isDummy(x) ? sequence : null));
        }
        public static void IntegerKey<T>(this IKeyBuilder<T> m, string name, Func<T, int?> getKey, string sequence, Func<int, bool> isDummy)
        {
            m.Key(name, (x) => getKey(x), sequence, (x) => isDummy((int)x));
        }
        public static void IntegerKey<T>(this IKeyBuilder<T> m, string name, Func<T, int?> getKey, string sequence, int dummy = Resolver.DEFAULT_DUMMY_START)
        {
            m.IntegerKey(name, getKey, sequence, (x) => x <= dummy);
        }
        public static void DecimalKey<T>(this IKeyBuilder<T> m, string name, Func<T, decimal?> getKey, string sequence, Func<decimal, bool> isDummy)
        {
            m.Key(name, (x) => getKey(x), sequence, (x) => isDummy((decimal)x));
        }
        public static void DecimalKey<T>(this IKeyBuilder<T> m, string name, Func<T, decimal?> getKey, string sequence, decimal dummy = Resolver.DEFAULT_DUMMY_START)
        {
            m.DecimalKey(name, getKey, sequence, (x) => x <= dummy);
        }
        public static void StringKey<T>(this IKeyBuilder<T> m, string name, Func<T, object> getKey, string sequence, Func<string, bool> isDummy)
        {
            m.Key(name, getKey, sequence, (x) => isDummy(x as string));
        }
        public static void StringKey<T>(this IKeyBuilder<T> m, string name, Func<T, object> getKey, string sequence, string prefix = "new:")
        {
            m.StringKey(name, getKey, sequence, (s) => s.StartsWith(prefix));
        }
    }
    public class MetaInfoBuilder<T> : IMetaBuilder<T>, IMetaInfo<T>
    {
        #region Nested Classes
        private class ColumnsDef
        {
            private IList<string> names = new List<string>();
            private IDictionary<string, Func<T, object>> getters = new Dictionary<string, Func<T, object>>();
            protected void Add(string name, Func<T, object> getter)
            {
                if (this.getters.ContainsKey(name)) throw new Exception("Duplicate name: " + name);
                this.getters.Add(name, getter);
                this.names.Add(name);
            }
            public void ForEach(T obj, Action<string, object> action)
            {
                for (int i = 0; i < this.names.Count; i++)
                    action(this.names[i], this.getters[this.names[i]](obj));
            }
            public void ForEachChange(T o, T n, Action<string, object, object> action)
            {
                for (int i = 0; i < this.names.Count; i++)
                {
                    var ov = this.getters[this.names[i]](o);
                    var nv = this.getters[this.names[i]](n);
                    if (!EqualityComparer<object>.Default.Equals(ov, nv))
                        action(this.names[i], ov, nv);
                }
            }
            public object[] GetFrom(T obj)
            {
                var values = new object[this.names.Count];
                for (int i = 0; i < this.names.Count; i++)
                    values[i] = this.getters[this.names[i]](obj);
                return values;
            }
            public object GetFrom(T obj, string name)
            {
                return this.getters[name](obj);
            }
            public object[] GetFrom(IDictionary<string, object> dict)
            {
                var values = new object[this.names.Count];
                for (int i = 0; i < this.names.Count; i++)
                    values[i] = dict[this.names[i]];
                return values;
            }
        }
        private class KeysDef: ColumnsDef, IKeyBuilder<T>
        {
            private IDictionary<string, Func<object, string>> generators = new Dictionary<string, Func<object, string>>();
            public void Add(string name, Func<T, object> getKey, Func<object, string> generator = null)
            {
                base.Add(name, getKey);
                if (generator != null) this.generators.Add(name, generator);
            }
            void IKeyBuilder<T>.Key(string name, Func<T, object> getKey, Func<object, string> generator)
            {
                this.Add(name, getKey, generator);
            }
            public string GeneratorExpr(string name, object value)
            {
                Func<object, string> g = null;
                if (! this.generators.TryGetValue(name, out g)) return null;
                return g(value);
            }
        }
        private class ValuesDef : ColumnsDef
        {
            public new void Add(string name, Func<T, object> getValue)
            {
                base.Add(name, getValue);
            }
        }
        #endregion

        #region Private Fields
        private string tableName;
        private KeysDef keys = new KeysDef();
        private IDictionary<string, KeysDef> extraKeys = new Dictionary<string, KeysDef>();
        private ValuesDef values = new ValuesDef();
        private IList<string> refList = new List<string>();
        private string group = null;
        #endregion

        #region Implement IMetaBuilder<T>
        void IMetaBuilder<T>.Table(string name) { this.tableName = name; }
        void IKeyBuilder<T>.Key(string name, Func<T, object> getKey, Func<object, string> generator)
        {
            this.keys.Add(name, getKey, generator);
        }
        IKeyBuilder<T> IMetaBuilder<T>.ExtraKey(string group)
        {
            KeysDef r = null;
            if (this.extraKeys.TryGetValue(group, out r)) return r;
            r = new KeysDef();
            this.extraKeys.Add(group, r);
            return r;
        }
        void IMetaBuilder<T>.Ref(string name, Func<T, object> getRef)
        {
            this.values.Add(name, getRef);
            this.refList.Add(name);
        }
        void IMetaBuilder<T>.Value(string name, Func<T, object> getValue)
        {
            this.values.Add(name, getValue);
        }
        void IMetaBuilder<T>.MasterExtaKey(string group)
        {
            this.group = @group;
        }
        #endregion

        #region Implement IMetaInfo<T>
        string IMetaInfo<T>.TableName { get { return this.tableName; } }
        object[] IMetaInfo<T>.GetKey(T obj)
        {
            return this.keys.GetFrom(obj);
        }
        object[] IMetaInfo<T>.GetKey(IDictionary<string, object> dict)
        {
            return this.keys.GetFrom(dict);
        }
        object[] IMetaInfo<T>.GetExtraKey(string group, T obj)
        {
            return this.extraKeys[group].GetFrom(obj);
        }
        object[] IMetaInfo<T>.GetExtraKey(string group, IDictionary<string, object> dict)
        {
            return this.extraKeys[group].GetFrom(dict);
        }
        string IMetaInfo<T>.GeneratorExpr(string name, object value)
        {
            var r = this.keys.GeneratorExpr(name, value);
            if (r != null) return r;
            foreach (var x in this.extraKeys)
            {
                r = x.Value.GeneratorExpr(name, value);
                if (r != null) return r;
            }
            return null;
        }
        void IMetaInfo<T>.ForEachKey(T obj, Action<string, object> action)
        {
            this.keys.ForEach(obj, action);
        }
        void IMetaInfo<T>.ForEachExtraKey(string group, T obj, Action<string, object> action)
        {
            this.extraKeys[group].ForEach(obj, action);
        }
        void IMetaInfo<T>.ForEachInsertValue(T obj, Action<string, object> action)
        {
            this.keys.ForEach(obj, action);
            foreach (var keys in this.extraKeys.Values) keys.ForEach(obj, action);
            this.values.ForEach(obj, action);
        }
        void IMetaInfo<T>.ForEachValueChange(T o, T n, Action<string, object, object> action)
        {
            this.values.ForEachChange(o, n, action);
        }
        string IMetaInfo<T>.MasterKeyGroup { get { return this.group; } }
        object[] IMetaInfo<T>.GetMasterRef(T obj)
        {
            if (this.refList.Count <= 0) return null;
            var r = new object[this.refList.Count];
            for (int i = 0; i < this.refList.Count; i++)
            {
                r[i] = this.values.GetFrom(obj, this.refList[i]);
            }
            return r;
        }
        void IMetaInfo<T>.SetActualMasterKey(IDictionary<string, object> dict, object[] actualKey)
        {
            if (this.refList.Count <= 0) return;
            for (int i = 0; i < actualKey.Length; i++)
                dict[this.refList[i]] = actualKey[i];
        }
        #endregion
    }
    public delegate void Meta<T>(IMetaBuilder<T> m);
    class Reconciler<T>
    {
        private IMetaInfo<T> info = null;
        private IEnumerable<T> olds = null;
        private IEnumerable<T> news = null;
        private IDictionary<object[], T> oldLookup = null;
        private IDictionary<object[], T> newLookup = null;
        public Reconciler(IMetaInfo<T> info, IEnumerable<T> olds, IEnumerable<T> news)
        {
            this.info = @info;
            this.olds = @olds;
            this.news = @news;
            this.oldLookup = CreateLookup(this.info, @olds);
            this.newLookup = CreateLookup(this.info, @news);
        }
        private static IDictionary<object[], T> CreateLookup(IMetaInfo<T> info, IEnumerable<T> list)
        {
            var r = new Dictionary<object[], T>(JonSkeet.ArrayEqualityComparer<object>.Default);
            foreach (var o in list) r.Add(info.GetKey(o), o);
            if (r.Count != list.Count()) throw new Exception("Duplicate keys");
            return r;
        }
        private TransactionJournal<T> CreateJournal(T o, T n)
        {
            if (o == null && n == null) throw new Exception("To create TransactionJournal, Old and New object cannot be both null");
            if (o == null && n != null)
            {
                var r = new InsertRecord(this.info.TableName);
                this.info.ForEachInsertValue(n, (k, v) => r.Values[k] = v);
                if (!r.Values.Any()) throw new Exception("Not enough meta information to create TransactionJournal");
                return new TransactionJournal<T> { Record = r, Old = o, New = n };
            }
            if (o != null && n != null)
            {
                var r = new UpdateRecord(this.info.TableName);
                r.AtMostOne = true;
                this.info.ForEachKey(n, r.Keys.Add);
                this.info.ForEachValueChange(o, n, (k, ov, nv) => r.Values[k] = nv);
                if (r.Values.Any())
                {
                    if (!r.Keys.Any()) throw new Exception("Not enough meta information to create TransactionJournal");
                    return new TransactionJournal<T> { Record = r, Old = o, New = n };
                }
                else
                {
                    return new TransactionJournal<T> { Record = null, Old = o, New = n };
                }
            }
            if (o != null && n == null)
            {
                var r = new DeleteRecord(this.info.TableName);
                r.AtMostOne = true;
                this.info.ForEachKey(o, r.Keys.Add);
                if (!r.Keys.Any()) throw new Exception("Not enough meta information to create TransactionJournal"); 
                return new TransactionJournal<T> { Record = r, Old = o, New = n };
            }
            throw new Exception("Should not reah here");
        }
        public IEnumerable<TransactionJournal<T>> ReconcileInsert()
        {
            return from j in this.ReconcileNonDelete()
                   where j.Record is InsertRecord
                   select j;
        }
        public IEnumerable<TransactionJournal<T>> ReconcileNonInsert()
        {
            foreach (var o in this.olds)
            {
                var key = this.info.GetKey(o);
                T n;
                if (! this.newLookup.TryGetValue(key, out n)) n = default(T);
                yield return this.CreateJournal(o, n);
            }
        }
        public IEnumerable<TransactionJournal<T>> ReconcileDelete()
        {
            return from j in this.ReconcileNonInsert()
                   where j.Record is DeleteRecord
                   select j;
        }
        public IEnumerable<TransactionJournal<T>> ReconcileNonDelete()
        {
            foreach (var n in this.news)
            {
                var key = this.info.GetKey(n);
                T o;
                if (!this.oldLookup.TryGetValue(key, out o)) o = default(T);
                yield return this.CreateJournal(o, n);
            }
        }
    }
    public class Resolver
    {
        public const int DEFAULT_DUMMY_START = -1;
        private IList<IResolverItem> items = new List<IResolverItem>();
        private Func<string, object> generator = null;
        public Resolver(Func<string, object> generator = null)
        {
            this.generator = @generator;
        }
        public ResolverItem<T> Add<T>(Meta<T> meta, IEnumerable<T> olds, IEnumerable<T> news) 
        {
            var r = new ResolverItem<T>(this, meta, olds, news);
            this.items.Add(r);
            return r;
        }
        public object Generate(string expr)
        {
            return (this.generator == null) ? null : this.generator(expr);
        }
        public IEnumerable<TransactionRecord> Resolve()
        {
            return this.items.SelectMany((i) => i.ResolveForRoot());
        }
        public static IEnumerable<TransactionRecord> Resolve<T>(Meta<T> meta, IEnumerable<T> olds, IEnumerable<T> news) 
        {
            var r = new Resolver();
            r.Add(meta, olds, news);
            return r.Resolve();
        }
    }
    public interface IResolverItem
    {
        string Group { get; }
        IEnumerable<TransactionRecord> ResolveForRoot();
        IEnumerable<TransactionRecord> ResolveForMasterInsert(object[] refKey, object[] actualKey);
        IEnumerable<TransactionRecord> ResolveForMasterStatic(object[] refKey);
        IEnumerable<TransactionRecord> ResolveForMasterDelete(object[] refKey);
    }
    public class ResolverItem<T> : IResolverItem 
    {
        private Resolver host = null;
        private IList<IResolverItem> items = new List<IResolverItem>();
        private IMetaInfo<T> info = null;
        private string group = null;
        private IEnumerable<T> olds = null;
        private IEnumerable<T> news = null;
        private IDictionary<object[], IList<TransactionJournal<T>>> _journals = null;
        protected IDictionary<object[], IList<TransactionJournal<T>>> CreateJournals()
        {
            var r = new Dictionary<object[], IList<TransactionJournal<T>>>(JonSkeet.ArrayEqualityComparer<object>.Default);
            var reconciler = new Reconciler<T>(this.info, this.olds, this.news);
            foreach (var j in reconciler.ReconcileNonDelete())
            {
                var k = this.info.GetMasterRef(j.New);
                IList<TransactionJournal<T>> list = null;
                if (! r.TryGetValue(k, out list)) 
                {
                    list = new List<TransactionJournal<T>>();
                    r.Add(k, list);
                }
                list.Add(j);
            }
            foreach (var j in reconciler.ReconcileDelete())
            {
                var k = this.info.GetMasterRef(j.Old);
                IList<TransactionJournal<T>> list = null;
                if (! r.TryGetValue(k, out list)) 
                {
                    list = new List<TransactionJournal<T>>();
                    r.Add(k, list);
                }
                list.Add(j);
            }
            return r;
        }
        protected IEnumerable<TransactionJournal<T>> GetJournals(object[] masterKey)
        {
            if (this._journals == null) this._journals = this.CreateJournals();
            IList<TransactionJournal<T>> r = null;
            if (!this._journals.TryGetValue(masterKey, out r)) return Enumerable.Empty<TransactionJournal<T>>();
            return r;
        }
        string IResolverItem.Group { get { return this.group; } }
        public ResolverItem(Resolver host, Meta<T> meta, IEnumerable<T> olds, IEnumerable<T> news)
        {
            this.host = @host;
            var m = new MetaInfoBuilder<T>();
            meta(m);
            this.info = m;
            this.olds = @olds;
            this.news = @news;
        }
        public ResolverItem<D> Add<D>(Meta<D> meta, IEnumerable<D> olds, IEnumerable<D> news)
        {
            var i = new ResolverItem<D>(this.host, meta, olds, news);
            this.items.Add(i);
            return i;
        }
        private void GenerateKey(InsertRecord ins)
        {
            foreach (var i in ins.Values.ToArray())
            {
                var expr = this.info.GeneratorExpr(i.Key, i.Value);
                if (expr != null)
                {
                    var g = this.host.Generate(expr);
                    if (g != null) ins.Values[i.Key] = g;
                }
            }
        }
        private object[] GetKeyForDetail(IResolverItem i, T obj)
        {
            return String.IsNullOrEmpty(i.Group)
                 ? this.info.GetKey(obj)
                 : this.info.GetExtraKey(i.Group, obj);
        }
        private object[] GetKeyForDetail(IResolverItem i, IDictionary<string, object> dict)
        {
            return String.IsNullOrEmpty(i.Group)
                 ? this.info.GetKey(dict)
                 : this.info.GetExtraKey(i.Group, dict);
        }
        protected void SetActualMasterKey(TransactionRecord t, object[] actualKey)
        {
            IDictionary<string, object> dict = null;
            if (t is InsertRecord) dict = (t as InsertRecord).Values;
            if (t is UpdateRecord) dict = (t as InsertRecord).Values;
            if (dict == null) throw new Exception("Unexpect type: " + t.GetType().Name);
            this.info.SetActualMasterKey(dict, actualKey);
        }
        IEnumerable<TransactionRecord> IResolverItem.ResolveForMasterInsert(object[] refKey, object[] actualKey)
        {
            foreach (var j in this.GetJournals(refKey))
            {
                var records = (j.Record is InsertRecord)
                            ? this.ResolveForInsert(j)
                            : this.ResolveForStatic(j);
                foreach (var t in records)
                {
                    if (t == j.Record) this.SetActualMasterKey(t, actualKey);
                    yield return t;
                }
            }
        }
        IEnumerable<TransactionRecord> IResolverItem.ResolveForMasterStatic(object[] refKey)
        {
            foreach (var j in this.GetJournals(refKey))
            {
                var records = Enumerable.Empty<TransactionRecord>();
                if (j.Record is InsertRecord) 
                    records = this.ResolveForInsert(j);
                else if ((j.Record == null) || (j.Record is UpdateRecord)) 
                    records = this.ResolveForStatic(j);
                else if (j.Record is DeleteRecord) records = 
                    records = this.ResolveForDelete(j);
                foreach (var t in records) yield return t;
            }
        }
        IEnumerable<TransactionRecord> IResolverItem.ResolveForMasterDelete(object[] refKey)
        {
            foreach (var j in this.GetJournals(refKey))
            {
                var records = Enumerable.Empty<TransactionRecord>();
                if (j.Record is DeleteRecord) records = this.ResolveForDelete(j);
                else if ((j.Record == null) || (j.Record is UpdateRecord))
                {
                    var del = new DeleteRecord(this.info.TableName);
                    this.info.ForEachKey(j.Old, del.Keys.Add);
                    var jdel = new TransactionJournal<T> { Record = del, Old = j.Old, New = default(T) };
                    records = this.ResolveForDelete(jdel);
                }
                foreach (var t in records) yield return t;
            }
        }
        protected IEnumerable<TransactionRecord> ResolveForInsert(TransactionJournal<T> j)
        {
            var ins = (InsertRecord)j.Record;
            this.GenerateKey(ins);
            yield return ins;
            foreach (var i in this.items)
            {
                var refKey = this.GetKeyForDetail(i, j.New);
                var actualKey = this.GetKeyForDetail(i, ins.Values);
                foreach (var t in i.ResolveForMasterInsert(refKey, actualKey))
                    yield return t;
            }
        }
        protected IEnumerable<TransactionRecord> ResolveForStatic(TransactionJournal<T> j)
        {
            if (j.Record != null) yield return j.Record;
            foreach (var i in this.items)
            {
                var refKey = this.GetKeyForDetail(i, j.New);
                foreach (var t in i.ResolveForMasterStatic(refKey))
                    yield return t;
            }
        }
        protected IEnumerable<TransactionRecord> ResolveForDelete(TransactionJournal<T> j)
        {
            foreach (var i in this.items)
            {
                var refKey = this.GetKeyForDetail(i, j.Old);
                foreach (var t in i.ResolveForMasterDelete(refKey))
                    yield return t;
            }
            yield return j.Record;
        }
        IEnumerable<TransactionRecord> IResolverItem.ResolveForRoot()
        {
            var r = new Reconciler<T>(this.info, this.olds, this.news);
            foreach (var j in r.ReconcileNonDelete())
            {
                if (j.Record is InsertRecord)
                    foreach (var t in this.ResolveForInsert(j))
                        yield return t;
                else
                    foreach (var t in this.ResolveForStatic(j))
                        yield return t;
            }
            foreach (var j in r.ReconcileDelete())
            {
                foreach (var t in this.ResolveForDelete(j))
                    yield return t;
            }
        }
    }
    public class Settler<T>
    {
        private class GenericItemList
        {
            private IMetaInfo<T> info = null;
            private List<object[]> items = new List<object[]>();
            private Dictionary<string, int> indexByName = null;
            private int[] indexByNumber = null;
            private void BuildValueNames(T obj)
            {
                if (this.indexByName == null)
                {
                    var byName = new Dictionary<string, int>();
                    var byNumber = new List<int>();
                    this.info.ForEachInsertValue(obj, (k, v) =>
                    {
                        var i = byName.ContainsKey(k) ? byName[k] : byName.Count;
                        byNumber.Add(i);
                        byName[k] = i;
                    });
                    this.indexByName = byName;
                    this.indexByNumber = byNumber.ToArray();
                }
            }
            public GenericItemList(IMetaInfo<T> info)
            {
                this.info = info;
            }
            private static bool FAST = true;
            public object[] Add(T obj)
            {
                this.BuildValueNames(obj);
                var item = new object[this.indexByName.Count];
                int i = 0;
                if (FAST)
                {
                    this.info.ForEachInsertValue(obj, (k, v) => item[this.indexByNumber[i++]] = v);
                }
                else
                {
                    this.info.ForEachInsertValue(obj, (k, v) => item[this.indexByName[k]] = v);
                }
                this.items.Add(item);
                return item;
            }
            public void Clear()
            {
                this.items.Clear();
            }
            public int Count { get { return this.items.Count; } }
            public void ForEach(Action<object[]> action)
            {
                this.items.ForEach(action);
            }
        }
        public class SettlerItem
        {
            public SettlerItem Add(string name, Meta<T> meta)
            {
                return null;
            }
        }
        public SettlerItem Add(string name, Meta<T> meta)
        {
            return null;
        }
        public void Load(Func<string, IEnumerable<T>> data)
        {
        }
        public IEnumerable<TransactionRecord> Resolve()
        {
            return null;
        }
    }
}