/
StdAdoDelegate.cs
2846 lines (2519 loc) · 118 KB
/
StdAdoDelegate.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
#region License
/*
* All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
*/
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Data;
using System.Globalization;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using Common.Logging;
using Quartz.Impl.Matchers;
using Quartz.Impl.Triggers;
using Quartz.Spi;
using Quartz.Util;
namespace Quartz.Impl.AdoJobStore
{
/// <summary>
/// This is meant to be an abstract base class for most, if not all, <see cref="IDriverDelegate" />
/// implementations. Subclasses should override only those methods that need
/// special handling for the DBMS driver in question.
/// </summary>
/// <author><a href="mailto:jeff@binaryfeed.org">Jeffrey Wescott</a></author>
/// <author>James House</author>
/// <author>Marko Lahma (.NET)</author>
public class StdAdoDelegate : StdAdoConstants, IDriverDelegate, ICommandAccessor
{
private ILog logger;
private string tablePrefix = DefaultTablePrefix;
private string instanceId;
private string schedName;
private bool useProperties;
private IDbProvider dbProvider;
private ITypeLoadHelper typeLoadHelper;
private AdoUtil adoUtil;
private readonly IList<ITriggerPersistenceDelegate> triggerPersistenceDelegates = new List<ITriggerPersistenceDelegate>();
private string schedNameLiteral;
private IObjectSerializer objectSerializer;
/// <summary>
/// Initializes the driver delegate.
/// </summary>
public virtual void Initialize(DelegateInitializationArgs args)
{
logger = args.Logger;
tablePrefix = args.TablePrefix;
schedName = args.InstanceName;
instanceId = args.InstanceId;
dbProvider = args.DbProvider;
typeLoadHelper = args.TypeLoadHelper;
useProperties = args.UseProperties;
adoUtil = new AdoUtil(args.DbProvider);
objectSerializer = args.ObjectSerializer;
AddDefaultTriggerPersistenceDelegates();
if (!String.IsNullOrEmpty(args.InitString))
{
string[] settings = args.InitString.Split('\\', '|');
foreach (string setting in settings)
{
string[] parts = setting.Split('=');
string name = parts[0];
if (parts.Length == 1 || parts[1] == null || parts[1].Equals(""))
{
continue;
}
if (name.Equals("triggerPersistenceDelegateClasses"))
{
string[] trigDelegates = parts[1].Split(',');
foreach (string triggerTypeName in trigDelegates)
{
try
{
Type trigDelClass = typeLoadHelper.LoadType(triggerTypeName);
AddTriggerPersistenceDelegate((ITriggerPersistenceDelegate) Activator.CreateInstance(trigDelClass));
}
catch (Exception e)
{
throw new NoSuchDelegateException("Error instantiating TriggerPersistenceDelegate of type: " + triggerTypeName, e);
}
}
}
else
{
throw new NoSuchDelegateException("Unknown setting: '" + name + "'");
}
}
}
}
protected virtual void AddDefaultTriggerPersistenceDelegates() {
AddTriggerPersistenceDelegate(new SimpleTriggerPersistenceDelegate());
AddTriggerPersistenceDelegate(new CronTriggerPersistenceDelegate());
AddTriggerPersistenceDelegate(new CalendarIntervalTriggerPersistenceDelegate());
AddTriggerPersistenceDelegate(new DailyTimeIntervalTriggerPersistenceDelegate());
}
protected virtual bool CanUseProperties
{
get { return useProperties; }
}
public virtual void AddTriggerPersistenceDelegate(ITriggerPersistenceDelegate del)
{
logger.Debug("Adding TriggerPersistenceDelegate of type: " + del.GetType());
del.Initialize(tablePrefix, schedName, this);
triggerPersistenceDelegates.Add(del);
}
public virtual ITriggerPersistenceDelegate FindTriggerPersistenceDelegate(IOperableTrigger trigger)
{
foreach (ITriggerPersistenceDelegate del in triggerPersistenceDelegates)
{
if (del.CanHandleTriggerType(trigger))
{
return del;
}
}
return null;
}
public virtual ITriggerPersistenceDelegate FindTriggerPersistenceDelegate(string discriminator)
{
foreach (ITriggerPersistenceDelegate del in triggerPersistenceDelegates)
{
if (del.GetHandledTriggerTypeDiscriminator().Equals(discriminator))
{
return del;
}
}
return null;
}
//---------------------------------------------------------------------------
// startup / recovery
//---------------------------------------------------------------------------
/// <summary>
/// Insert the job detail record.
/// </summary>
/// <param name="conn">the DB Connection</param>
/// <param name="newState">the new state for the triggers</param>
/// <param name="oldState1">the first old state to update</param>
/// <param name="oldState2">the second old state to update</param>
/// <returns>number of rows updated</returns>
public virtual int UpdateTriggerStatesFromOtherStates(ConnectionAndTransactionHolder conn, string newState,
string oldState1,
string oldState2)
{
using (IDbCommand cmd = PrepareCommand(conn, ReplaceTablePrefix(SqlUpdateTriggerStatesFromOtherStates)))
{
AddCommandParameter(cmd, "newState", newState);
AddCommandParameter(cmd, "oldState1", oldState1);
AddCommandParameter(cmd, "oldState2", oldState2);
return cmd.ExecuteNonQuery();
}
}
/// <summary>
/// Get the names of all of the triggers that have misfired.
/// </summary>
/// <param name="conn">the DB Connection</param>
/// <param name="ts">The ts.</param>
/// <returns>an array of <see cref="TriggerKey" /> objects</returns>
public virtual IList<TriggerKey> SelectMisfiredTriggers(ConnectionAndTransactionHolder conn, long ts)
{
using (IDbCommand cmd = PrepareCommand(conn, ReplaceTablePrefix(SqlSelectMisfiredTriggers)))
{
AddCommandParameter(cmd, "timestamp", ts);
using (IDataReader rs = cmd.ExecuteReader())
{
List<TriggerKey> list = new List<TriggerKey>();
while (rs.Read())
{
string triggerName = rs.GetString(ColumnTriggerName);
string groupName = rs.GetString(ColumnTriggerGroup);
list.Add(new TriggerKey(triggerName, groupName));
}
return list;
}
}
}
/// <summary>
/// Select all of the triggers in a given state.
/// </summary>
/// <param name="conn">The DB Connection</param>
/// <param name="state">The state the triggers must be in</param>
/// <returns> an array of trigger <see cref="TriggerKey" />s </returns>
public virtual IList<TriggerKey> SelectTriggersInState(ConnectionAndTransactionHolder conn, string state)
{
using (IDbCommand cmd = PrepareCommand(conn, ReplaceTablePrefix(SqlSelectTriggersInState)))
{
AddCommandParameter(cmd, "state", state);
using (IDataReader rs = cmd.ExecuteReader())
{
List<TriggerKey> list = new List<TriggerKey>();
while (rs.Read())
{
list.Add(new TriggerKey(rs.GetString(0), rs.GetString(1)));
}
return list;
}
}
}
/// <summary>
/// Get the names of all of the triggers in the given state that have
/// misfired - according to the given timestamp.
/// </summary>
/// <param name="conn">The DB Connection</param>
/// <param name="state">The state.</param>
/// <param name="ts">The time stamp.</param>
/// <returns>An array of <see cref="TriggerKey" /> objects</returns>
public virtual IList<TriggerKey> HasMisfiredTriggersInState(ConnectionAndTransactionHolder conn, string state, long ts)
{
using (IDbCommand cmd = PrepareCommand(conn, ReplaceTablePrefix(SqlSelectMisfiredTriggersInState)))
{
AddCommandParameter(cmd, "timestamp", ts);
AddCommandParameter(cmd, "state", state);
using (IDataReader rs = cmd.ExecuteReader())
{
List<TriggerKey> list = new List<TriggerKey>();
while (rs.Read())
{
string triggerName = rs.GetString(ColumnTriggerName);
string groupName = rs.GetString(ColumnTriggerGroup);
list.Add(new TriggerKey(triggerName, groupName));
}
return list;
}
}
}
/// <summary>
/// Get the names of all of the triggers in the given state that have
/// misfired - according to the given timestamp. No more than count will
/// be returned.
/// </summary>
/// <param name="conn">The conn.</param>
/// <param name="state1">The state1.</param>
/// <param name="ts">The ts.</param>
/// <param name="count">The most misfired triggers to return, negative for all</param>
/// <param name="resultList">
/// Output parameter. A List of <see cref="TriggerKey" /> objects. Must not be null
/// </param>
/// <returns>Whether there are more misfired triggers left to find beyond the given count.</returns>
public virtual bool HasMisfiredTriggersInState(ConnectionAndTransactionHolder conn, string state1, DateTimeOffset ts, int count, IList<TriggerKey> resultList)
{
using (IDbCommand cmd = PrepareCommand(conn, ReplaceTablePrefix(SqlSelectHasMisfiredTriggersInState)))
{
AddCommandParameter(cmd, "nextFireTime", Convert.ToDecimal(ts.Ticks));
AddCommandParameter(cmd, "state1", state1);
using (IDataReader rs = cmd.ExecuteReader())
{
bool hasReachedLimit = false;
while (rs.Read() && (hasReachedLimit == false))
{
if (resultList.Count == count)
{
hasReachedLimit = true;
}
else
{
string triggerName = rs.GetString(ColumnTriggerName);
string groupName = rs.GetString(ColumnTriggerGroup);
resultList.Add(new TriggerKey(triggerName, groupName));
}
}
return hasReachedLimit;
}
}
}
/// <summary>
/// Get the number of triggers in the given state that have
/// misfired - according to the given timestamp.
/// </summary>
/// <param name="conn"></param>
/// <param name="state1"></param>
/// <param name="ts"></param>
/// <returns></returns>
public int CountMisfiredTriggersInState(ConnectionAndTransactionHolder conn, string state1, DateTimeOffset ts)
{
using (IDbCommand cmd = PrepareCommand(conn, ReplaceTablePrefix(SqlCountMisfiredTriggersInStates)))
{
AddCommandParameter(cmd, "nextFireTime", Convert.ToDecimal(ts.Ticks));
AddCommandParameter(cmd, "state1", state1);
using (IDataReader rs = cmd.ExecuteReader())
{
if (rs.Read())
{
return Convert.ToInt32(rs.GetValue(0), CultureInfo.InvariantCulture);
}
}
throw new Exception("No misfired trigger count returned.");
}
}
/// <summary>
/// Get the names of all of the triggers in the given group and state that
/// have misfired.
/// </summary>
/// <param name="conn">The DB Connection</param>
/// <param name="groupName">Name of the group.</param>
/// <param name="state">The state.</param>
/// <param name="ts">The timestamp.</param>
/// <returns>an array of <see cref="TriggerKey" /> objects</returns>
public virtual IList<TriggerKey> SelectMisfiredTriggersInGroupInState(ConnectionAndTransactionHolder conn, string groupName, string state, long ts)
{
using (IDbCommand cmd = PrepareCommand(conn, ReplaceTablePrefix(SqlSelectMisfiredTriggersInGroupInState))
)
{
AddCommandParameter(cmd, "timestamp", Convert.ToDecimal(ts));
AddCommandParameter(cmd, "triggerGroup", groupName);
AddCommandParameter(cmd, "state", state);
using (IDataReader rs = cmd.ExecuteReader())
{
List<TriggerKey> list = new List<TriggerKey>();
while (rs.Read())
{
string triggerName = rs.GetString(ColumnTriggerName);
list.Add(new TriggerKey(triggerName, groupName));
}
return list;
}
}
}
/// <summary>
/// Select all of the triggers for jobs that are requesting recovery. The
/// returned trigger objects will have unique "recoverXXX" trigger names and
/// will be in the <see cref="SchedulerConstants.DefaultRecoveryGroup" />
/// trigger group.
/// </summary>
/// <remarks>
/// In order to preserve the ordering of the triggers, the fire time will be
/// set from the <i>ColumnFiredTime</i> column in the <i>TableFiredTriggers</i>
/// table. The caller is responsible for calling <see cref="IOperableTrigger.ComputeFirstFireTimeUtc" />
/// on each returned trigger. It is also up to the caller to insert the
/// returned triggers to ensure that they are fired.
/// </remarks>
/// <param name="conn">The DB Connection</param>
/// <returns> an array of <see cref="ITrigger" /> objects</returns>
public virtual IList<IOperableTrigger> SelectTriggersForRecoveringJobs(ConnectionAndTransactionHolder conn)
{
List<IOperableTrigger> list = new List<IOperableTrigger>();
using (IDbCommand cmd = PrepareCommand(conn, ReplaceTablePrefix(SqlSelectInstancesRecoverableFiredTriggers)))
{
AddCommandParameter(cmd, "instanceName", instanceId);
AddCommandParameter(cmd, "requestsRecovery", GetDbBooleanValue(true));
using (IDataReader rs = cmd.ExecuteReader())
{
long dumId = SystemTime.UtcNow().Ticks;
while (rs.Read())
{
string jobName = rs.GetString(ColumnJobName);
string jobGroup = rs.GetString(ColumnJobGroup);
// string trigName = rs.GetString(ColumnTriggerName);
// string trigGroup = rs.GetString(ColumnTriggerGroup);
long firedTimeInTicks = Convert.ToInt64(rs[ColumnFiredTime], CultureInfo.InvariantCulture);
int priority = Convert.ToInt32(rs[ColumnPriority], CultureInfo.InvariantCulture);
DateTimeOffset firedTime = new DateTimeOffset(firedTimeInTicks, TimeSpan.Zero);
SimpleTriggerImpl rcvryTrig = new SimpleTriggerImpl("recover_" + instanceId + "_" + Convert.ToString(dumId++, CultureInfo.InvariantCulture),
SchedulerConstants.DefaultRecoveryGroup, firedTime);
rcvryTrig.JobName = jobName;
rcvryTrig.JobGroup = jobGroup;
rcvryTrig.Priority = priority;
rcvryTrig.MisfireInstruction = MisfireInstruction.SimpleTrigger.FireNow;
list.Add(rcvryTrig);
}
}
}
// read JobDataMaps with different reader..
foreach (SimpleTriggerImpl trigger in list)
{
JobDataMap jd = SelectTriggerJobDataMap(conn, trigger.Key);
jd.Put(SchedulerConstants.FailedJobOriginalTriggerName, trigger.Name);
jd.Put(SchedulerConstants.FailedJobOriginalTriggerGroup, trigger.Group);
jd.Put(SchedulerConstants.FailedJobOriginalTriggerFiretimeInMillisecoonds, Convert.ToString(trigger.StartTimeUtc, CultureInfo.InvariantCulture));
trigger.JobDataMap = jd;
}
return list.ToArray();
}
/// <summary>
/// Delete all fired triggers.
/// </summary>
/// <param name="conn">The DB Connection.</param>
/// <returns>The number of rows deleted.</returns>
public virtual int DeleteFiredTriggers(ConnectionAndTransactionHolder conn)
{
using (IDbCommand cmd = PrepareCommand(conn, ReplaceTablePrefix(SqlDeleteFiredTriggers)))
{
return cmd.ExecuteNonQuery();
}
}
/// <summary>
/// Delete all fired triggers of the given instance.
/// </summary>
/// <param name="conn">The DB Connection</param>
/// <param name="instanceName">The instance id.</param>
/// <returns>The number of rows deleted</returns>
public virtual int DeleteFiredTriggers(ConnectionAndTransactionHolder conn, string instanceName)
{
using (IDbCommand cmd = PrepareCommand(conn, ReplaceTablePrefix(SqlDeleteInstancesFiredTriggers)))
{
AddCommandParameter(cmd, "instanceName", instanceName);
return cmd.ExecuteNonQuery();
}
}
/// <summary>
/// Clear (delete!) all scheduling data - all <see cref="IJob"/>s, <see cref="ITrigger" />s
/// <see cref="ICalendar" />s.
/// </summary>
/// <remarks>
/// </remarks>
public void ClearData(ConnectionAndTransactionHolder conn)
{
IDbCommand ps = null;
ps = PrepareCommand(conn, ReplaceTablePrefix(SqlDeleteAllSimpleTriggers));
ps.ExecuteNonQuery();
ps = PrepareCommand(conn, ReplaceTablePrefix(SqlDeleteAllSimpropTriggers));
ps.ExecuteNonQuery();
ps = PrepareCommand(conn, ReplaceTablePrefix(SqlDeleteAllCronTriggers));
ps.ExecuteNonQuery();
ps = PrepareCommand(conn, ReplaceTablePrefix(SqlDeleteAllBlobTriggers));
ps.ExecuteNonQuery();
ps = PrepareCommand(conn, ReplaceTablePrefix(SqlDeleteAllTriggers));
ps.ExecuteNonQuery();
ps = PrepareCommand(conn, ReplaceTablePrefix(SqlDeleteAllJobDetails));
ps.ExecuteNonQuery();
ps = PrepareCommand(conn, ReplaceTablePrefix(SqlDeleteAllCalendars));
ps.ExecuteNonQuery();
ps = PrepareCommand(conn, ReplaceTablePrefix(SqlDeleteAllPausedTriggerGrps));
ps.ExecuteNonQuery();
}
//---------------------------------------------------------------------------
// jobs
//---------------------------------------------------------------------------
/// <summary>
/// Insert the job detail record.
/// </summary>
/// <param name="conn">The DB Connection.</param>
/// <param name="job">The job to insert.</param>
/// <returns>Number of rows inserted.</returns>
public virtual int InsertJobDetail(ConnectionAndTransactionHolder conn, IJobDetail job)
{
byte[] baos = SerializeJobData(job.JobDataMap);
int insertResult;
using (IDbCommand cmd = PrepareCommand(conn, ReplaceTablePrefix(SqlInsertJobDetail)))
{
AddCommandParameter(cmd, "jobName", job.Key.Name);
AddCommandParameter(cmd, "jobGroup", job.Key.Group);
AddCommandParameter(cmd, "jobDescription", job.Description);
AddCommandParameter(cmd, "jobType", GetStorableJobTypeName(job.JobType));
AddCommandParameter(cmd, "jobDurable", GetDbBooleanValue(job.Durable));
AddCommandParameter(cmd, "jobVolatile", GetDbBooleanValue(job.ConcurrentExectionDisallowed));
AddCommandParameter(cmd, "jobStateful", GetDbBooleanValue(job.PersistJobDataAfterExecution));
AddCommandParameter(cmd, "jobRequestsRecovery", GetDbBooleanValue(job.RequestsRecovery));
AddCommandParameter(cmd, "jobDataMap", baos, dbProvider.Metadata.DbBinaryType);
insertResult = cmd.ExecuteNonQuery();
}
return insertResult;
}
/// <summary>
/// Gets the db presentation for boolean value. Subclasses can overwrite this behaviour.
/// </summary>
/// <param name="booleanValue">Value to map to database.</param>
/// <returns></returns>
public virtual object GetDbBooleanValue(bool booleanValue)
{
// works nicely for databases we have currently supported
return booleanValue;
}
/// <summary>
/// Gets the boolean value from db presentation. Subclasses can overwrite this behaviour.
/// </summary>
/// <param name="columnValue">Value to map from database.</param>
/// <returns></returns>
public virtual bool GetBooleanFromDbValue(object columnValue)
{
if (columnValue != null)
{
return (bool) columnValue;
}
throw new ArgumentException("Value must be non-null.");
}
protected virtual string GetStorableJobTypeName(Type jobType)
{
int idx = jobType.AssemblyQualifiedName.IndexOf(',');
// find next
idx = jobType.AssemblyQualifiedName.IndexOf(',', idx + 1);
string retValue = jobType.AssemblyQualifiedName.Substring(0, idx);
return retValue;
}
/// <summary>
/// Update the job detail record.
/// </summary>
/// <param name="conn">The DB Connection.</param>
/// <param name="job">The job to update.</param>
/// <returns>Number of rows updated.</returns>
public virtual int UpdateJobDetail(ConnectionAndTransactionHolder conn, IJobDetail job)
{
byte[] baos = SerializeJobData(job.JobDataMap);
using (IDbCommand cmd = PrepareCommand(conn, ReplaceTablePrefix(SqlUpdateJobDetail)))
{
AddCommandParameter(cmd, "jobDescription", job.Description);
AddCommandParameter(cmd, "jobType", GetStorableJobTypeName(job.JobType));
AddCommandParameter(cmd, "jobDurable", GetDbBooleanValue(job.Durable));
AddCommandParameter(cmd, "jobVolatile", GetDbBooleanValue(job.ConcurrentExectionDisallowed));
AddCommandParameter(cmd, "jobStateful", GetDbBooleanValue(job.PersistJobDataAfterExecution));
AddCommandParameter(cmd, "jobRequestsRecovery", GetDbBooleanValue(job.RequestsRecovery));
AddCommandParameter(cmd, "jobDataMap", baos, dbProvider.Metadata.DbBinaryType);
AddCommandParameter(cmd, "jobName", job.Key.Name);
AddCommandParameter(cmd, "jobGroup", job.Key.Group);
int insertResult = cmd.ExecuteNonQuery();
return insertResult;
}
}
/// <summary>
/// Get the names of all of the triggers associated with the given job.
/// </summary>
/// <param name="conn">The DB Connection.</param>
/// <param name="jobKey">The key identifying the job.</param>
/// <returns>An array of <see cref="TriggerKey" /> objects</returns>
public virtual IList<TriggerKey> SelectTriggerNamesForJob(ConnectionAndTransactionHolder conn, JobKey jobKey)
{
using (IDbCommand cmd = PrepareCommand(conn, ReplaceTablePrefix(SqlSelectTriggersForJob)))
{
AddCommandParameter(cmd, "jobName", jobKey.Name);
AddCommandParameter(cmd, "jobGroup", jobKey.Group);
using (IDataReader rs = cmd.ExecuteReader())
{
List<TriggerKey> list = new List<TriggerKey>(10);
while (rs.Read())
{
string trigName = rs.GetString(ColumnTriggerName);
string trigGroup = rs.GetString(ColumnTriggerGroup);
list.Add(new TriggerKey(trigName, trigGroup));
}
return list;
}
}
}
/// <summary>
/// Delete the job detail record for the given job.
/// </summary>
/// <param name="conn">the DB Connection</param>
/// <param name="jobKey">The key identifying the job.</param>
/// <returns>the number of rows deleted</returns>
public virtual int DeleteJobDetail(ConnectionAndTransactionHolder conn, JobKey jobKey)
{
using (IDbCommand cmd = PrepareCommand(conn, ReplaceTablePrefix(SqlDeleteJobDetail)))
{
if (logger.IsDebugEnabled)
{
logger.Debug("Deleting job: " + jobKey);
}
AddCommandParameter(cmd, "jobName", jobKey.Name);
AddCommandParameter(cmd, "jobGroup", jobKey.Group);
return cmd.ExecuteNonQuery();
}
}
/// <summary>
/// Check whether or not the given job is stateful.
/// </summary>
/// <param name="conn">the DB Connection</param>
/// <param name="jobKey">The key identifying the job.</param>
/// <returns>
/// true if the job exists and is stateful, false otherwise
/// </returns>
public virtual bool IsJobStateful(ConnectionAndTransactionHolder conn, JobKey jobKey)
{
using (IDbCommand cmd = PrepareCommand(conn, ReplaceTablePrefix(SqlSelectJobNonConcurrent)))
{
AddCommandParameter(cmd, "jobName", jobKey.Name);
AddCommandParameter(cmd, "jobGroup", jobKey.Group);
object o = cmd.ExecuteScalar();
if (o != null)
{
return (bool) o;
}
return false;
}
}
/// <summary>
/// Check whether or not the given job exists.
/// </summary>
/// <param name="conn">the DB Connection</param>
/// <param name="jobKey">The key identifying the job.</param>
/// <returns>true if the job exists, false otherwise</returns>
public virtual bool JobExists(ConnectionAndTransactionHolder conn, JobKey jobKey)
{
using (IDbCommand cmd = PrepareCommand(conn, ReplaceTablePrefix(SqlSelectJobExistence)))
{
AddCommandParameter(cmd, "jobName", jobKey.Name);
AddCommandParameter(cmd, "jobGroup", jobKey.Group);
using (IDataReader dr = cmd.ExecuteReader())
{
if (dr.Read())
{
return true;
}
return false;
}
}
}
/// <summary>
/// Update the job data map for the given job.
/// </summary>
/// <param name="conn">The conn.</param>
/// <param name="job">the job to update</param>
/// <returns>the number of rows updated</returns>
public virtual int UpdateJobData(ConnectionAndTransactionHolder conn, IJobDetail job)
{
byte[] baos = SerializeJobData(job.JobDataMap);
using (IDbCommand cmd = PrepareCommand(conn, ReplaceTablePrefix(SqlUpdateJobData)))
{
AddCommandParameter(cmd, "jobDataMap", baos, dbProvider.Metadata.DbBinaryType);
AddCommandParameter(cmd, "jobName", job.Key.Name);
AddCommandParameter(cmd, "jobGroup", job.Key.Group);
return cmd.ExecuteNonQuery();
}
}
/// <summary>
/// Select the JobDetail object for a given job name / group name.
/// </summary>
/// <param name="conn">The DB Connection.</param>
/// <param name="jobKey">The key identifying the job.</param>
/// <param name="loadHelper">The load helper.</param>
/// <returns>The populated JobDetail object.</returns>
public virtual IJobDetail SelectJobDetail(ConnectionAndTransactionHolder conn, JobKey jobKey, ITypeLoadHelper loadHelper)
{
using (IDbCommand cmd = PrepareCommand(conn, ReplaceTablePrefix(SqlSelectJobDetail)))
{
AddCommandParameter(cmd, "jobName", jobKey.Name);
AddCommandParameter(cmd, "jobGroup", jobKey.Group);
using (IDataReader rs = cmd.ExecuteReader())
{
JobDetailImpl job = null;
if (rs.Read())
{
job = new JobDetailImpl();
job.Name = rs.GetString(ColumnJobName);
job.Group = rs.GetString(ColumnJobGroup);
job.Description = rs.GetString(ColumnDescription);
job.JobType = loadHelper.LoadType(rs.GetString(ColumnJobClass));
job.Durable = GetBooleanFromDbValue(rs[ColumnIsDurable]);
job.RequestsRecovery = GetBooleanFromDbValue(rs[ColumnRequestsRecovery]);
IDictionary map;
if (CanUseProperties)
{
map = GetMapFromProperties(rs, 6);
}
else
{
map = GetObjectFromBlob<IDictionary>(rs, 6);
}
if (null != map)
{
job.JobDataMap = new JobDataMap(map);
}
}
return job;
}
}
}
/// <summary> build Map from java.util.Properties encoding.</summary>
private IDictionary GetMapFromProperties(IDataReader rs, int idx)
{
IDictionary map;
NameValueCollection properties = GetJobDataFromBlob<NameValueCollection>(rs, idx);
if (properties == null)
{
return null;
}
map = ConvertFromProperty(properties);
return map;
}
/// <summary>
/// Select the total number of jobs stored.
/// </summary>
/// <param name="conn">The DB Connection.</param>
/// <returns>The total number of jobs stored.</returns>
public virtual int SelectNumJobs(ConnectionAndTransactionHolder conn)
{
using (IDbCommand cmd = PrepareCommand(conn, ReplaceTablePrefix(SqlSelectNumJobs)))
{
return (int)cmd.ExecuteScalar();
}
}
/// <summary>
/// Select all of the job group names that are stored.
/// </summary>
/// <param name="conn">The DB Connection.</param>
/// <returns>An array of <see cref="String" /> group names.</returns>
public virtual IList<string> SelectJobGroups(ConnectionAndTransactionHolder conn)
{
using (IDbCommand cmd = PrepareCommand(conn, ReplaceTablePrefix(SqlSelectJobGroups)))
{
using (IDataReader rs = cmd.ExecuteReader())
{
List<string> list = new List<string>();
while (rs.Read())
{
list.Add(rs.GetString(0));
}
return list.ToArray();
}
}
}
/// <summary>
/// Select all of the jobs contained in a given group.
/// </summary>
/// <param name="conn">The DB Connection.</param>
/// <param name="matcher"></param>
/// <returns>An array of <see cref="String" /> job names.</returns>
public virtual Collection.ISet<JobKey> SelectJobsInGroup(ConnectionAndTransactionHolder conn, GroupMatcher<JobKey> matcher)
{
using (IDbCommand cmd = PrepareCommand(conn, ReplaceTablePrefix(SqlSelectJobsInGroup)))
{
AddCommandParameter(cmd, "jobGroup", ToSqlLikeClause(matcher));
using (IDataReader rs = cmd.ExecuteReader())
{
Collection.HashSet<JobKey> list = new Collection.HashSet<JobKey>();
while (rs.Read())
{
list.Add(new JobKey(rs.GetString(0), rs.GetString(1)));
}
return list;
}
}
}
protected static string ToSqlLikeClause<T>(GroupMatcher<T> matcher) where T : Key<T>
{
string groupName;
if (StringOperator.Equality.Equals(matcher.CompareWithOperator))
{
groupName = matcher.CompareToValue;
}
else if (StringOperator.Contains.Equals(matcher.CompareWithOperator))
{
groupName = "%" + matcher.CompareToValue + "%";
}
else if (StringOperator.EndsWith.Equals(matcher.CompareWithOperator))
{
groupName = "%" + matcher.CompareToValue;
}
else if (StringOperator.StartsWith.Equals(matcher.CompareWithOperator))
{
groupName = matcher.CompareToValue + "%";
}
else
{
throw new ArgumentOutOfRangeException("Don't know how to translate " + matcher.CompareWithOperator + " into SQL");
}
return groupName;
}
//---------------------------------------------------------------------------
// triggers
//---------------------------------------------------------------------------
/// <summary>
/// Insert the base trigger data.
/// </summary>
/// <param name="conn">the DB Connection</param>
/// <param name="trigger">the trigger to insert</param>
/// <param name="state">the state that the trigger should be stored in</param>
/// <param name="jobDetail">The job detail.</param>
/// <returns>the number of rows inserted</returns>
public virtual int InsertTrigger(ConnectionAndTransactionHolder conn, IOperableTrigger trigger, string state, IJobDetail jobDetail)
{
byte[] baos = null;
if (trigger.JobDataMap.Count > 0)
{
baos = SerializeJobData(trigger.JobDataMap);
}
using (IDbCommand cmd = PrepareCommand(conn, ReplaceTablePrefix(SqlInsertTrigger)))
{
AddCommandParameter(cmd, "triggerName", trigger.Key.Name);
AddCommandParameter(cmd, "triggerGroup", trigger.Key.Group);
AddCommandParameter(cmd, "triggerJobName", trigger.JobKey.Name);
AddCommandParameter(cmd, "triggerJobGroup", trigger.JobKey.Group);
AddCommandParameter(cmd, "triggerDescription", trigger.Description);
if (trigger.GetNextFireTimeUtc().HasValue)
{
AddCommandParameter(cmd, "triggerNextFireTime",
Convert.ToDecimal(trigger.GetNextFireTimeUtc().Value.Ticks));
}
else
{
AddCommandParameter(cmd, "triggerNextFireTime", null);
}
if (trigger.GetPreviousFireTimeUtc().HasValue)
{
AddCommandParameter(cmd, "triggerPreviousFireTime", Convert.ToDecimal(trigger.GetPreviousFireTimeUtc().Value.Ticks));
}
else
{
AddCommandParameter(cmd, "triggerPreviousFireTime", null);
}
AddCommandParameter(cmd, "triggerState", state);
string paramName = "triggerType";
ITriggerPersistenceDelegate tDel = FindTriggerPersistenceDelegate(trigger);
string type = TriggerTypeBlob;
if (tDel != null)
{
type = tDel.GetHandledTriggerTypeDiscriminator();
}
AddCommandParameter(cmd, paramName, type);
AddCommandParameter(cmd, "triggerStartTime", Convert.ToDecimal(trigger.StartTimeUtc.Ticks));
if (trigger.EndTimeUtc.HasValue)
{
AddCommandParameter(cmd, "triggerEndTime", Convert.ToDecimal(trigger.EndTimeUtc.Value.Ticks));
}
else
{
AddCommandParameter(cmd, "triggerEndTime", null);
}
AddCommandParameter(cmd, "triggerCalendarName", trigger.CalendarName);
AddCommandParameter(cmd, "triggerMisfireInstruction", trigger.MisfireInstruction);
paramName = "triggerJobJobDataMap";
if (baos != null)
{
AddCommandParameter(cmd, paramName, baos, dbProvider.Metadata.DbBinaryType);
}
else
{
AddCommandParameter(cmd, paramName, null, dbProvider.Metadata.DbBinaryType);
}
AddCommandParameter(cmd, "triggerPriority", trigger.Priority);
int insertResult = cmd.ExecuteNonQuery();
if (tDel == null)
{
InsertBlobTrigger(conn, trigger);
}
else
{
tDel.InsertExtendedTriggerProperties(conn, trigger, state, jobDetail);
}
return insertResult;
}
}
/// <summary>
/// Insert the blob trigger data.
/// </summary>
/// <param name="conn">The DB Connection.</param>
/// <param name="trigger">The trigger to insert.</param>
/// <returns>The number of rows inserted.</returns>
public virtual int InsertBlobTrigger(ConnectionAndTransactionHolder conn, IOperableTrigger trigger)
{
using (IDbCommand cmd = PrepareCommand(conn, ReplaceTablePrefix(SqlInsertBlobTrigger)))
{
// update the blob
byte[] buf = SerializeObject(trigger);
AddCommandParameter(cmd, "triggerName", trigger.Key.Name);
AddCommandParameter(cmd, "triggerGroup", trigger.Key.Group);
AddCommandParameter(cmd, "blob", buf, dbProvider.Metadata.DbBinaryType);
return cmd.ExecuteNonQuery();
}
}
/// <summary>
/// Update the base trigger data.
/// </summary>
/// <param name="conn">The DB Connection.</param>
/// <param name="trigger">The trigger to insert.</param>
/// <param name="state">The state that the trigger should be stored in.</param>
/// <param name="jobDetail">The job detail.</param>
/// <returns>The number of rows updated.</returns>
public virtual int UpdateTrigger(ConnectionAndTransactionHolder conn, IOperableTrigger trigger, string state, IJobDetail jobDetail)
{
// save some clock cycles by unnecessarily writing job data blob ...
bool updateJobData = trigger.JobDataMap.Dirty;
byte[] baos = null;
if (updateJobData && trigger.JobDataMap.Count > 0)
{
baos = SerializeJobData(trigger.JobDataMap);
}
IDbCommand cmd;
int insertResult;
if (updateJobData)
{
cmd = PrepareCommand(conn, ReplaceTablePrefix(SqlUpdateTrigger));
}
else
{
cmd = PrepareCommand(conn, ReplaceTablePrefix(SqlUpdateTriggerSkipData));
}