-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfdata_pg.cs
1885 lines (1607 loc) · 66.3 KB
/
fdata_pg.cs
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
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System.Web ;
using System.Data.SqlClient ;
using System.IO ;
using System.Threading ;
using System;
using System.Net ;
using System.Collections ;
using System.Collections.Generic ;
using Npgsql ;
using Microsoft.Win32;
using System.Diagnostics;
using System.Text.RegularExpressions;
using System.Xml.Linq;
using System.Linq;
using System.Text;
// DON'T MESS WITH THIS.
class LJTrafficCop
{
private static void FireWhenReady()
{
try
{
Semaphore s = Semaphore.OpenExisting("COPS");
Thread.Sleep(1000);
s.Release();
}
catch (Exception e)
{
Console.WriteLine(e.ToString()); // eat it.
}
}
public static void WaitMyTurn()
{
Semaphore s = new Semaphore(1, 1, "COPS");
s.WaitOne();
Thread newThread = new Thread(LJTrafficCop.FireWhenReady);
newThread.Start();
}
}
public class MyNpgsqlCommand
{
NpgsqlCommand m_npgsqlCmd = null ;
public MyNpgsqlCommand ( string strCmd, NpgsqlConnection userDBConnection )
{
if( strCmd[ strCmd.Length -1 ] != ';')
strCmd += ";" ;
int iDate = strCmd.ToUpper().IndexOf("GETDATE()") ;
if (iDate != -1)
{
strCmd = strCmd.Replace("GETDATE()", "now()") ;
// Console.WriteLine("Watch us crash.") ;
}
m_npgsqlCmd = new NpgsqlCommand( strCmd, userDBConnection ) ;
}
public NpgsqlDataReader ExecuteReader()
{
return m_npgsqlCmd.ExecuteReader() ;
}
public int ExecuteNonQuery()
{
return m_npgsqlCmd.ExecuteNonQuery() ;
}
public int CommandTimeout
{
get { return m_npgsqlCmd.CommandTimeout ; }
set { m_npgsqlCmd.CommandTimeout = value ; }
}
} ;
public class MMDB
{
private static NpgsqlConnection m_DBConnection = null;
public static NpgsqlConnection DBConnection
{
get
{
return m_DBConnection;
}
}
public static void MakeSureDBIsOpen()
{
if (m_DBConnection == null)
{
// m_DBConnection = new NpgsqlConnection( "Database=mindmap;Server=localhost;Port=5432;User Id=postgres;Password=postgres;") ; // pgsql
m_DBConnection = new NpgsqlConnection(Registry.GetValue("HKEY_CURRENT_USER\\Software\\MindMap", "PostgreInitString", null).ToString());
m_DBConnection.Open();
}
}
public static void ExecuteNonQuery(string sql, bool showIt = true )
{
MakeSureDBIsOpen();
if( showIt)
Console.WriteLine(sql);
NpgsqlCommand cmd = new NpgsqlCommand(sql, DBConnection);
cmd.ExecuteNonQuery();
}
public static Int64? MaybeNullInt64(NpgsqlDataReader reader, int iPosition)
{
if (reader.IsDBNull(iPosition))
return null;
return reader.GetInt64(iPosition);
}
public static Int32? MaybeNullInt32(NpgsqlDataReader reader, int iPosition)
{
if (reader.IsDBNull(iPosition))
return null;
return reader.GetInt32(iPosition);
}
public static Int16? MaybeNullInt16(NpgsqlDataReader reader, int iPosition)
{
if (reader.IsDBNull(iPosition))
return null;
return reader.GetInt16(iPosition);
}
public static bool QueryFindsRow(string sql)
{
System.Diagnostics.Debug.Assert(sql.ToUpper().Contains("LIMIT 1")); // should force optimize
NpgsqlCommand cmd = new NpgsqlCommand(sql, DBConnection);
NpgsqlDataReader myReader = cmd.ExecuteReader();
myReader.Read();
bool ret = myReader.HasRows;
myReader.Close();
return ret;
}
}
public class Extras
{
public static DateTime TwoK = new DateTime(2000, 1, 1);
public static void CheckForRenameOrOffline(Int32 checkTarget)
{
// is this already an offline?
NpgsqlDataReader myReader = new MyNpgsqlCommand(string.Format("select offline_last_detected_on from nameidmap where id={0}", checkTarget), MMDB.DBConnection).ExecuteReader();
myReader.Read();
Int16? offlineDetectedOn = MMDB.MaybeNullInt16(myReader, 0);
myReader.Close();
if (offlineDetectedOn != null)
{
if (offlineDetectedOn >= DateTime.Now.Subtract(TwoK).Days - 120)
return; // i don't believe an additioan lcheck is needed
}
// hey this better not be an existing offline or maybe it's an update check?
string uri = string.Format("http://www.livejournal.com/users/{0}/data/foaf", IDMap.IDToName(checkTarget));
Console.WriteLine("Loadin: " + uri);
XDocument document = null;
try
{
LJTrafficCop.WaitMyTurn(); // And we've learned the foaf must wait twice.
LJTrafficCop.WaitMyTurn(); // And we've learned the foaf must wait twice.
document = XDocument.Load(uri);
}
catch (System.Xml.XmlException )
{
return;
}
catch (WebException we)
{
if ((we.ToString().Contains("404") || we.ToString().Contains("410")) || we.ToString().Contains("403"))
{
Console.WriteLine(IDMap.IDToName(checkTarget) + " offline.");
new NpgsqlCommand(
string.Format("update nameidmap set offline_last_detected_on={0}, postsperyear=0, iaddperyear=0 where name='{1}';",
DateTime.Now.Subtract(TwoK).Days,
IDMap.IDToName(checkTarget)),
MMDB.DBConnection).ExecuteNonQuery();
}
else
Console.WriteLine("JERK: " + we.ToString());
return;
}
XElement personElement = document.Element("{http://www.w3.org/1999/02/22-rdf-syntax-ns#}RDF").Element("{http://xmlns.com/foaf/0.1/}Person");
if (personElement != null)
{
string nick = personElement.Element("{http://xmlns.com/foaf/0.1/}nick").Value;
string name = IDMap.IDToName(checkTarget);
if (nick != name)
{
Console.WriteLine(name + " >> " + nick);
new NpgsqlCommand(
string.Format("update nameidmap set made_by_rename_detected_on={0}, offline_last_detected_on=null where name='{1}';", DateTime.Now.Subtract(TwoK).Days, nick),
MMDB.DBConnection).ExecuteNonQuery();
new NpgsqlCommand(
string.Format("update nameidmap set offline_last_detected_on={0}, postsperyear=0, iaddperyear=0 where name='{1}';", DateTime.Now.Subtract(TwoK).Days, name),
MMDB.DBConnection).ExecuteNonQuery();
}
}
}
public static List<string> DinkyPeople
{
get
{
MMDB.MakeSureDBIsOpen();
string strCmd = string.Format("SELECT name from ljuserextras where dinky=true");
MyNpgsqlCommand cmd = new MyNpgsqlCommand(strCmd, MMDB.DBConnection);
NpgsqlDataReader myReader = null;
try
{
myReader = cmd.ExecuteReader();
List<string> lsDinkyPeople = new List<string>() ;
while (myReader.Read())
lsDinkyPeople.Add(myReader.GetString(0).Trim());
return lsDinkyPeople;
}
finally
{
myReader.Close();
}
}
}
}
public class IDMap
{
// private static SortedList<string, Int32> m_nameIdMap = new SortedList<string, Int32>();
// private static SortedList<Int32, string> m_idNameMap = new SortedList<Int32, string>();
// private static long m_cleanPopulateAt = 0;
// i am ok with IDMap controlling the memcached instance,
protected static BeIT.MemCached.MemcachedClient cache = null;
private static bool m_fMemcacheDInitialized = false;
private static void InitializeMCD()
{
m_fMemcacheDInitialized = true;
Console.Out.WriteLine("Setting up Memcached Client.");
// BeIT.MemCached.MemcachedClient.Setup("NameIdMaps", new string[] { "127.0.0.1:11211" });
BeIT.MemCached.MemcachedClient.Setup("NameIdMaps", new string[] { "127.0.0.1:11211" });
//Get the instance we just set up so we can use it. You can either store this reference yourself in
//some field, or fetch it every time you need it, it doesn't really matter.
cache = BeIT.MemCached.MemcachedClient.GetInstance("NameIdMaps");
//It is also possible to set up clients in the standard config file. Check the section "beitmemcached"
//in the App.config file in this project and you will see that a client called "MyConfigFileCache" is defined.
// MemcachedClient configFileCache = MemcachedClient.GetInstance("MyConfigFileCache");
//Change client settings to values other than the default like this:
cache.SendReceiveTimeout = 5000;
cache.MinPoolSize = 1;
cache.MaxPoolSize = 5;
}
public static bool Set(string key, object value)
{
if (false == m_fMemcacheDInitialized)
InitializeMCD();
return cache.Set(key, value);
}
public static object Gets(string key, out ulong unique)
{
if (false == m_fMemcacheDInitialized)
InitializeMCD();
return cache.Gets(key, out unique);
}
internal static int NameToID(string name)
{
Debug.Assert(false == name.Contains("-"));// use underscore
Debug.Assert(name == name.ToLower());
Debug.Assert(name.Contains(" ") == false);
if (false == m_fMemcacheDInitialized)
InitializeMCD();
// we want an id from a name.
// the key will be # plus the ID, vs @ plus a name.
TRY_AGAIN_JOE:
ulong unique;
Int32? id = Gets("@" + name.ToUpper(), out unique) as Int32?;
if (id != null)
return (int)id;
else
{ // id is null so unfound in cache.
// if i can't find him in my db, then he needs to get created.
string strGetEm = string.Format("SELECT id from nameidmap where name='{0}'; ", name);
MyNpgsqlCommand cmdGetEm = new MyNpgsqlCommand(strGetEm, MMDB.DBConnection);
NpgsqlDataReader myReader = cmdGetEm.ExecuteReader();
myReader.Read();
if (myReader.HasRows)
{
Set("@" + name.ToUpper(), myReader.GetInt32(0));
// don't need Set("#" + myReader.GetInt32(0).ToString(), name.ToUpper());
myReader.Close();
goto TRY_AGAIN_JOE;
}
else
{
myReader.Close();
// if the id doesn't exist, we need to create it.
MMDB.ExecuteNonQuery(string.Format("INSERT INTO nameidmap (name) Values('{0}') ", name));
goto TRY_AGAIN_JOE; // return NameToID(name); // me so sloppy lazy strange
}
}
}
// if (id == null)
// if the id is not known from the name, then the cache is probably brand new
// so use the existing code to pre-populate it for screamin good throughputs
// so long as we have the first stab and wait for these to populate,
// assuring one party does so.
/*
Console.Write("Populating whole name-id cache via database...");
string strCmdPrePop = string.Format("SELECT name, id from nameidmap order by name asc");
MyNpgsqlCommand cmdPrePop = new MyNpgsqlCommand(strCmdPrePop, MMDB.DBConnection);
cmdPrePop.CommandTimeout = 180; // hmmm slow db?
NpgsqlDataReader myReaderPrePop = cmdPrePop.ExecuteReader();
while (myReaderPrePop.Read())
{
Set(myReaderPrePop.GetString(0).Trim().ToUpper(), myReaderPrePop.GetInt32(1));
}
myReaderPrePop.Close();
Console.WriteLine(" Done.");
}
m.ReleaseMutex();
goto TRY_AGAIN_JOE;
}
*/
/*
try
{
if (m_nameIdMap.Count == 0)
{
// ok we just started up. do we pre-populate?
// if (0 != int.Parse(Registry.GetValue("HKEY_CURRENT_USER\\Software\\MindMap", "DelayCachePrePop", null).ToString()))
{
// we are in debug mode. determine the size of the big list...
m_cleanPopulateAt = 200; // fixed at 400 GET_NAMEIDMAP_RECORD_COUNT() / 100; // at 1%
}
}
// if we are not in debug, then we will prepopulate right off the top ( 0 == 0 )
if (m_cleanPopulateAt != -1)
{
if (m_nameIdMap.Count >= m_cleanPopulateAt)
// if (m_nameIdMap.Count == 0)
{
Console.Write("Populating whole name-id cache via database...");
string strCmdPrePop = string.Format("SELECT name, id from nameidmap order by name asc");
MyNpgsqlCommand cmdPrePop = new MyNpgsqlCommand(strCmdPrePop, MMDB.DBConnection);
cmdPrePop.CommandTimeout = 180; // hmmm slow db?
NpgsqlDataReader myReaderPrePop = cmdPrePop.ExecuteReader();
m_nameIdMap.Clear(); // we dump it, in case we've been delay-cache functionin'.
while (myReaderPrePop.Read())
{
m_nameIdMap[myReaderPrePop.GetString(0)] = myReaderPrePop.GetInt32(1);
}
myReaderPrePop.Close();
m_cleanPopulateAt = -1; // never do this again for this run
Console.WriteLine(" Done.");
}
}
return m_nameIdMap[name];
}
catch (KeyNotFoundException)
{
// query as usual
}
// if the name exists, we return it.
// if we must create it, the database enforces uniqueness
// so isn't there some kind of "ask" for such data?
string strCmd = string.Format("SELECT id from nameidmap where name='{0}'", name);
MyNpgsqlCommand cmd = new MyNpgsqlCommand(strCmd, MMDB.DBConnection);
cmd.CommandTimeout = 240;
NpgsqlDataReader myReader = null;
try
{
myReader = cmd.ExecuteReader();
if (myReader.Read())
{
m_nameIdMap[name] = myReader.GetInt32(0);
return myReader.GetInt32(0);
}
}
finally
{
myReader.Close();
}
// if the id doesn't exist, we need to create it.
strCmd = string.Format("INSERT INTO nameidmap (name) Values('{0}') ", name);
cmd = new MyNpgsqlCommand(strCmd, MMDB.DBConnection);
cmd.ExecuteNonQuery();
return NameToID(name); // me so sloppy lazy strange
}
*/
internal static string IDToName(int id)
{
if (false == m_fMemcacheDInitialized)
InitializeMCD();
TRY_AGAIN_BOB:
ulong unique;
string name = Gets("#" + id.ToString(), out unique) as string;
if (name != null)
{
return name.ToLower() ;
}
else
{ // name is null so unfound in cache.
// if i can't find him in my db, then how doe he exist?
string strGetEm = string.Format("SELECT name from nameidmap where id={0} ", id);
MyNpgsqlCommand cmdGetEm = new MyNpgsqlCommand(strGetEm, MMDB.DBConnection);
NpgsqlDataReader myReader = cmdGetEm.ExecuteReader();
myReader.Read();
Debug.Assert(myReader.HasRows);
Set("@" + myReader.GetString(0).Trim().ToUpper(), id);
Set("#" + id.ToString(), myReader.GetString(0).Trim().ToUpper());
myReader.Close();
goto TRY_AGAIN_BOB;
}
}
/*
try
{
if (m_idNameMap.Count == 0)
{
string strCmdPrePop = string.Format("SELECT name, id from nameidmap order by id asc");
MyNpgsqlCommand cmdPrePop = new MyNpgsqlCommand(strCmdPrePop, MMDB.DBConnection);
cmdPrePop.CommandTimeout = 120;
Console.Write("Pre-populating id-name cache...");
NpgsqlDataReader myReaderPrePop = cmdPrePop.ExecuteReader();
while (myReaderPrePop.Read())
{
m_idNameMap[myReaderPrePop.GetInt32(1)] = myReaderPrePop.GetString(0);
}
myReaderPrePop.Close();
Console.WriteLine(" Done.");
}
return m_idNameMap[id];
}
catch (KeyNotFoundException)
{
// query as usual
}
// if the item does not exist, explode, cuz it should.
string strCmd = string.Format("SELECT name from nameidmap where id='{0}'", id);
MyNpgsqlCommand cmd = new MyNpgsqlCommand(strCmd, MMDB.DBConnection);
NpgsqlDataReader myReader = null;
try
{
myReader = cmd.ExecuteReader();
myReader.Read();
m_idNameMap[id] = myReader.GetString(0);
return myReader.GetString(0);
}
finally
{
myReader.Close();
}
* */
}
/*
public static void FLUSH_NAMEIDMAP_TABLE( )
{
MMDB.MakeSureDBIsOpen();
MyNpgsqlCommand cmd = new MyNpgsqlCommand("DELETE FROM nameidmap", MMDB.DBConnection);
cmd.ExecuteNonQuery();
}
* */
/* slow
public static long GET_NAMEIDMAP_RECORD_COUNT()
{
MMDB.MakeSureDBIsOpen();
MyNpgsqlCommand cmd = new MyNpgsqlCommand("SELECT count(*) from nameidmap", MMDB.DBConnection);
NpgsqlDataReader myReader = null;
try
{
myReader = cmd.ExecuteReader();
myReader.Read();
return myReader.GetInt64(0);
}
finally
{
myReader.Close();
}
}
* */
public class Incident
{
public Incident(int theDay, string theSubj, string theObj, bool whetherAddOrDrop)
{
day = theDay;
subj = theSubj;
obj = theObj;
addOrDrop = whetherAddOrDrop;
}
public int day;
public string subj;
public string obj;
public bool addOrDrop;
public bool mutual = false; // false by default
} ;
public class FEvents : MMDB
{
/*
public static void FLUSH_FEVENTS_TABLE()
{
MyNpgsqlCommand cmd = new MyNpgsqlCommand("DELETE FROM fevents", MMDB.DBConnection);
cmd.ExecuteNonQuery();
}
*/
/*
public static long GET_RECORD_COUNT()
{
MyNpgsqlCommand cmd = new MyNpgsqlCommand("SELECT count(*) from fevents", DBConnection);
NpgsqlDataReader myReader = null;
try
{
myReader = cmd.ExecuteReader();
myReader.Read();
return myReader.GetInt64(0);
}
finally
{
myReader.Close();
}
}
* */
public static bool EverReading(string actor, string target)
{
// in fevents table, did actor ever add *or just remove???* target?
// in this implementation, just one-way question, that simple.
// we only run if highestdayprocessed for actor is today
// select highestdayprocessed from nameidmap where name='actor';
Debug.Assert( GetHighestDayProcessed(actor) > -1);
// or just that it's ever been done ha ha lazy
// select from fevents where name=actor and target=target
// look up his number? can i do that
// can't be sloppy// can i get someone's #?
int iactor = IDMap.NameToID(actor);
int itarget = IDMap.NameToID(target);
string strCmd = string.Format("SELECT count(*) FROM fevents where fevents.subj={0} and fevents.obj={1}",
iactor, itarget);
MyNpgsqlCommand cmd = new MyNpgsqlCommand(strCmd, DBConnection);
NpgsqlDataReader myReader = null;
try
{
myReader = cmd.ExecuteReader();
while (myReader.Read())
{
if (myReader.GetInt64(0) > 0)
return true ;
}
}
finally
{
myReader.Close();
}
return false ;
}
public static List<string> EveryAssociateEver(string name)
{
MakeSureDBIsOpen();
List<string> everyone = new List<string>() ;
/* this is the old, slow style:
string strCmd = string.Format("select DISTINCT nameidmap.name from nameidmap, fevents WHERE " +
"(nameidmap.id = fevents.obj OR nameidmap.id = fevents.subj) AND (fevents.obj = {0} or fevents.subj = {0});", IDMap.NameToID(name));
* */
string strCmd = string.Format("(select nameidmap.name from nameidmap, fevents WHERE (fevents.subj = {0}) AND " +
"(nameidmap.id = fevents.obj)) union (select nameidmap.name from nameidmap, fevents_by_obj " +
"WHERE (fevents_by_obj.obj = {0}) AND (nameidmap.id = fevents_by_obj.subj))", IDMap.NameToID(name));
MyNpgsqlCommand cmd = new MyNpgsqlCommand(strCmd, DBConnection);
cmd.CommandTimeout = 190;
NpgsqlDataReader myReader = null;
try
{
myReader = cmd.ExecuteReader();
while (myReader.Read())
{
everyone.Add(myReader.GetString(0));
}
return everyone;
}
finally
{
myReader.Close();
}
}
static void SortByDayThenSeed(List<Incident> il, string seed)
{
il.Sort(
delegate(Incident left, Incident right)
{
if (left == null)
if (right == null)
{
return 0;
}
else
{
return -1;
}
else
{
if (right == null)
return 1;
}
// same-days show seed deeds first
if (left.day == right.day)
{
if (left.subj == seed && right.subj == seed)
return 0;
if (left.subj == seed)
return -1;
if (right.subj == seed)
return 1;
}
/*
if (left.obj == seed)
return -1;
if (right.obj == seed)
return 1;
return 0; // same spot
}
* */
return left.day.CompareTo(right.day);
});
}
// give me names, and i give you every event involving one of those names IN BOTH FIELDS.
public static List<Incident> GetEvents(List<string> names, string seed, List<Incident> liRadarClues)
{
Debug.Assert(names.Count > 0);
// if it's just one name, use the old function.
if (names.Count == 1)
return GetEvents(names[0]);
// ok, i'll create a temporary table that contains the id's for all these names
// and it needs a random table name that starts with 'temp' like 'temp123'
// but what if it already exists? then we should crash i guess. whatever.
// mutex time!
Mutex m = new Mutex(false, "ONE_TEMP_TABLE_USER");
m.WaitOne();
string strCmd = "CREATE TABLE id_set_TEMPORARY ( id integer NOT NULL, CONSTRAINT id_key UNIQUE (id) ) WITHOUT OIDS";
MyNpgsqlCommand cmd = new MyNpgsqlCommand(strCmd, MMDB.DBConnection);
cmd.ExecuteNonQuery();
strCmd = "ALTER TABLE id_set_TEMPORARY OWNER TO postgres";
cmd = new MyNpgsqlCommand(strCmd, MMDB.DBConnection);
cmd.ExecuteNonQuery();
// now stuff it full.
foreach (string name in names)
{
strCmd = string.Format("INSERT INTO id_set_TEMPORARY(id) Values({0})", IDMap.NameToID(name));
cmd = new MyNpgsqlCommand(strCmd, MMDB.DBConnection);
cmd.ExecuteNonQuery();
}
Try_Again_Joker2:
List<Incident> il = new List<Incident>();
// old style strCmd = "select distinct fevents.day, fevents.subj, fevents.obj, fevents.add_or_drop from id_set, fevents where (fevents.subj=id_set.id or fevents.obj=id_set.id) order by day asc";
strCmd = "(select fevents.day, fevents.subj, fevents.obj, fevents.add_or_drop from id_set_TEMPORARY, fevents " +
"where (fevents.subj=id_set_TEMPORARY.id )) UNION " +
"(select fevents_by_obj.day, fevents_by_obj.subj, fevents_by_obj.obj, fevents_by_obj.add_or_drop from id_set_TEMPORARY, fevents_by_obj " +
"where (fevents_by_obj.obj=id_set_TEMPORARY.id )) order by day asc";
cmd = new MyNpgsqlCommand(strCmd, DBConnection);
cmd.CommandTimeout = 720 * 4; // it's big baby
NpgsqlDataReader myReader = null;
try
{
try
{
myReader = cmd.ExecuteReader();
}
catch (Npgsql.NpgsqlException ne)
{
Console.WriteLine("Npgsql.NpgsqlException in GetEvents[] on : " + strCmd);
Console.WriteLine(ne.ToString());
Console.WriteLine("Gonna try again...");
goto Try_Again_Joker2; // FAILS CUZ IT DOES THE FREAKIN FINALLY FIRST AND THAT NUKES THE TABLE I THINK.
}
// int iScrapsForRadar = 0;
while (myReader.Read())
{
// IF BOTH FIELDS AREN'T IN THE LIST OF NAMES, WE DON'T ADD.
string actor = IDMap.IDToName(myReader.GetInt32(1));
string target = IDMap.IDToName(myReader.GetInt32(2));
if (names.Contains(actor))
{
Incident i = new Incident(myReader.GetInt16(0),
actor,
target,
myReader.GetBoolean(3));
if (names.Contains(target))
{
il.Add(i);
}
else
{
// if actor is not seed,
// and event occured within last 180 days,
// we store this incident for possible use in new radar.
// appraising cost first.
// (adds only)
if( liRadarClues != null)
// if (myReader.GetBoolean(3) == true) // we want + and -'s
if (actor != seed)
if (myReader.GetInt16(0) > DateTime.Now.AddDays(-180).Subtract(Extras.TwoK).Days)
liRadarClues.Add(i);
}
}
}
SortByDayThenSeed(il, seed);
// well i have a radar clue... let's investigate its potential:
// see who people i read added... to know that i need to pass this back.
// ok, test...
return il;
}
finally
{
myReader.Close();
strCmd = "DROP TABLE id_set_TEMPORARY ";
cmd = new MyNpgsqlCommand(strCmd, DBConnection);
cmd = new MyNpgsqlCommand(strCmd, MMDB.DBConnection);
cmd.ExecuteNonQuery();
m.ReleaseMutex();
}
}
// the old school
public static List<Incident> GetEvents( string name )
{
Try_Again_Joker:
List<Incident> il = new List<Incident>();
// old style string strCmd = string.Format("SELECT day, subj, obj, add_or_drop FROM fevents where subj={0} or obj={0} order by day", IDMap.NameToID(name));
string strCmd = string.Format("(SELECT day, subj, obj, add_or_drop FROM fevents " +
"where subj={0}) UNION " +
"(SELECT day, subj, obj, add_or_drop FROM fevents_by_obj where obj={0})", IDMap.NameToID(name));
MyNpgsqlCommand cmd = new MyNpgsqlCommand(strCmd, DBConnection);
cmd.CommandTimeout = 70; // if it suppresses a crash, i'll take it.
NpgsqlDataReader myReader = null;
try
{
try
{
myReader = cmd.ExecuteReader();
}
catch (Npgsql.NpgsqlException ne)
{
Console.WriteLine("Npgsql.NpgsqlException in GetEvents on " + name + "\r\n " + ne.ToString() + "\r\nTrying again...") ;
goto Try_Again_Joker;
}
while (myReader.Read())
{
il.Add(new Incident(myReader.GetInt16(0),
IDMap.IDToName( myReader.GetInt32(1)),
IDMap.IDToName( myReader.GetInt32(2)),
myReader.GetBoolean(3)));
}
SortByDayThenSeed(il, name);
/* I REFUSE TO DO THIS HERE. TOO RISKY.
// CAN'T USE FOR-EACH WHEN IT CHAGES THE CONTENTS
for (int iPos = 0; iPos < il.Count; iPos++)
{
Incident i = il[iPos];
// Incident iConverse = new Incident(i.day, i.obj, i.subj, i.addOrDrop);
for (int iPosOfDupe = iPos + 1; iPosOfDupe < il.Count; iPosOfDupe++)
{
if ((il[iPosOfDupe].day == i.day) &&
(il[iPosOfDupe].subj == i.obj) &&
(il[iPosOfDupe].obj == i.subj) &&
(il[iPosOfDupe].addOrDrop == i.addOrDrop))
{
il.RemoveAt(iPosOfDupe);
i.mutual = true;
break;
}
}
}
* */
return il;
}
finally
{
myReader.Close();
}
}
public static void RemoveEvents(List<Incident> il)
{
foreach (Incident i in il)
{
string strCmd = string.Format("DELETE FROM fevents where day={0} and subj={1} and obj={2} and add_or_drop={3}",
i.day, IDMap.NameToID(i.subj), IDMap.NameToID(i.obj), i.addOrDrop) ;
MyNpgsqlCommand cmd = new MyNpgsqlCommand(strCmd, DBConnection);
cmd.ExecuteNonQuery();
strCmd = strCmd.Replace("FROM fevents", "FROM fevents_by_obj");
cmd = new MyNpgsqlCommand(strCmd, DBConnection);
cmd.ExecuteNonQuery();
}
}
public static void SetHighestDayProcessed(string name, int i)
{
string strCmd = string.Format("update nameidmap set highestdayprocessed='{0}' where name='{1}'",
i, name);
MyNpgsqlCommand cmd = new MyNpgsqlCommand(strCmd, DBConnection);
cmd.ExecuteNonQuery();
}
public static int GetHighestDayProcessed(string name)
{
// calling nametoid creates this name if it doesn't already exist
string strCmd = string.Format("select highestdayprocessed from nameidmap where id='{0}'", IDMap.NameToID(name));
MyNpgsqlCommand cmd = new MyNpgsqlCommand(strCmd, DBConnection);
NpgsqlDataReader myReader = null;
try
{
myReader = cmd.ExecuteReader();
myReader.Read();
return myReader.GetInt16(0);
}
finally
{
myReader.Close();
}
}
public static void Add(int day, string subj, string obj, bool addedOrDropped)
{
// Debug.Assert(subj != obj); // i can add or drop myself. totally legit i guess.
// except you know what? it might play havoc with my otherwise-pure data model
if (subj == obj)
return;
Debug.Assert(subj == subj.ToLower());
Debug.Assert(obj == obj.ToLower());
Debug.Assert(subj.Contains(" ") == false);
Debug.Assert(obj.Contains(" ") == false);
MakeSureDBIsOpen();
int iSubj = IDMap.NameToID(subj);
int iObj = IDMap.NameToID(obj);
string strCmd = string.Format("INSERT INTO fevents (day, subj, obj, add_or_drop) Values('{0}', '{1}', '{2}', '{3}')",
day, iSubj, iObj, addedOrDropped);
MyNpgsqlCommand cmd = new MyNpgsqlCommand(strCmd, DBConnection);
try
{
cmd.ExecuteNonQuery();
}
catch (Npgsql.NpgsqlException e )
{
// my code migh detect a duplicate row from two angles. i ignore this occurance.
Debug.Assert( e.Code == "23505") ;
}
// now do the object-ordered copy
strCmd = string.Format("INSERT INTO fevents_by_obj (day, subj, obj, add_or_drop) Values('{0}', '{1}', '{2}', '{3}')",
day, iSubj, iObj, addedOrDropped);
cmd = new MyNpgsqlCommand(strCmd, DBConnection);
try
{
cmd.ExecuteNonQuery();
}
catch (Npgsql.NpgsqlException e)
{
// my code migh detect a duplicate row from two angles. i ignore this occurance.
Debug.Assert(e.Code == "23505");
}
// work in progress somewhere here
// strCmd = string.Format("update FEvents set select Day,fdata from FData where Name='{0}' ORDER BY DAY DESC", seed) ;
}
}
public class FData : MMDB
{
public static string GetCity(string seed) // also not FData but who cares? This unencodes!
{
// note: i don't fetch a city if i don't already have one. i just return the default empty string.
MakeSureDBIsOpen();
string strCmdPrePop = string.Format("SELECT city from nameidmap where name='{0}'", seed);
MyNpgsqlCommand cmdPrePop = new MyNpgsqlCommand(strCmdPrePop, MMDB.DBConnection);
NpgsqlDataReader myReaderPrePop = cmdPrePop.ExecuteReader();
try
{
if (myReaderPrePop.Read())
{
return myReaderPrePop.GetString(0);
}
}
finally
{
myReaderPrePop.Close();
}
return "";
}