/
Serializer.cs
1272 lines (1039 loc) · 41 KB
/
Serializer.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
// ___________________________________________________
//
// © Hi-Integrity Systems 2012. All rights reserved.
// www.hisystems.com.au - Toby Wicks
// ___________________________________________________
//
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
namespace DatabaseObjects.SQL.Serializers
{
/// <summary>
/// Serializes an DatabaseObjects.SQL.* object into an SQL string ready for execution.
/// This class manages generic SQL serialisation that applies to all database systems.
/// Methods can be overridden if a database system serializes differently.
/// </summary>
internal abstract class Serializer
{
/// <summary>
/// Joins all of the strings and ensures that there are spaces between each item if the item not blank.
/// </summary>
protected class TokenSerializer
{
private string separator;
private List<string> tokens = new List<string>();
public TokenSerializer()
: this(separator: " ")
{
}
public TokenSerializer(string separator)
{
if (String.IsNullOrEmpty(separator))
throw new ArgumentNullException();
this.separator = separator;
}
public void Add(string token)
{
tokens.Add(token);
}
/// <summary>
/// Joins all of the strings and ensures that there are spaces between each item if the item not blank.
/// </summary>
public override string ToString()
{
return String.Join(this.separator, tokens.Where(token => !String.IsNullOrEmpty(token)).ToArray());
}
}
/// <summary>
/// Indicates the serialization type to utilise.
/// </summary>
public abstract Database.ConnectionType Type { get; }
/// <summary>
/// Should place tags around a field name or table name to ensure it doesn't
/// conflict with a reserved word or if it contains spaces it is not misinterpreted
/// </summary>
public abstract string SerializeIdentifier(string strIdentifierName);
/// <summary>
/// Should return the SELECT statement that when executed returns a row.
/// If a row is returned then the table exists.
/// </summary>
public abstract string SerializeTableExists(SQLTableExists tableExists);
/// <summary>
/// Should return the SELECT statement for determining whether a view exists.
/// If a row is returned then the view exists.
/// </summary>
public abstract string SerializeViewExists(SQLViewExists viewExists);
public string SerializeInsert(SQLInsert insert)
{
if (String.IsNullOrEmpty(insert.TableName))
throw new Exceptions.DatabaseObjectsException("TableName property has not been set.");
else if (insert.Fields.Count == 0)
throw new Exceptions.DatabaseObjectsException("Field values have not been set.");
string fieldNames = String.Join(", ", insert.Fields.Select(field => SerializeIdentifier(field.Name)).ToArray());
string fieldValues = String.Join(", ", insert.Fields.Select(field => SerializeValue(field.Value)).ToArray());
var tokens = new TokenSerializer();
tokens.Add("INSERT INTO");
tokens.Add(SerializeIdentifier(insert.TableName));
tokens.Add("(" + fieldNames + ")");
tokens.Add("VALUES");
tokens.Add("(" + fieldValues + ")");
return tokens.ToString();
}
public virtual string SerializeUpdate(SQLUpdate update)
{
if (String.IsNullOrEmpty(update.TableName))
throw new Exceptions.DatabaseObjectsException("TableName property has not been set.");
else if (update.Fields.Count == 0)
throw new Exceptions.DatabaseObjectsException("Field values have not been set.");
else if (update.Fields.Any(field => String.IsNullOrEmpty(field.Name)))
throw new Exceptions.DatabaseObjectsException("Field Name has not been set.");
var fieldNameAndValues = String.Join(", ", update.Fields.Select(field => SerializeIdentifier(field.Name) + " = " + SerializeValue(field.Value)).ToArray());
var tokens = new TokenSerializer();
tokens.Add("UPDATE");
tokens.Add(SerializeIdentifier(update.TableName));
tokens.Add("SET");
tokens.Add(fieldNameAndValues);
if (update.Where != null && !update.Where.IsEmpty)
{
tokens.Add("WHERE");
tokens.Add(SerializeConditions(update.Where));
}
return tokens.ToString();
}
public string SerializeInsertFromSelect(SQLInsertFromSelect insertFromSelect)
{
if (String.IsNullOrEmpty(insertFromSelect.TableName))
throw new Exceptions.DatabaseObjectsException("TableName property has not been set.");
var tokens = new TokenSerializer();
tokens.Add("INSERT INTO");
tokens.Add(SerializeIdentifier(insertFromSelect.TableName));
if (insertFromSelect.Fields.Count > 0)
{
var fields = String.Join(", ", insertFromSelect.Fields.Cast<string>().Select(fieldName => SerializeIdentifier(fieldName)).ToArray());
tokens.Add("(" + fields + ")");
}
tokens.Add(SerializeSelect(insertFromSelect.Source));
return tokens.ToString();
}
public virtual string SerializeDelete(SQLDelete delete)
{
if (String.IsNullOrEmpty(delete.TableName))
throw new Exceptions.DatabaseObjectsException("TableName property has not been set.");
var tokens = new TokenSerializer();
tokens.Add("DELETE FROM");
tokens.Add(SerializeIdentifier(delete.TableName));
if (delete.Where != null && !delete.Where.IsEmpty)
{
tokens.Add("WHERE");
tokens.Add(SerializeConditions(delete.Where));
}
return tokens.ToString();
}
public virtual string SerializeSelect(SQLSelect select)
{
if (select.Tables.Count == 0)
throw new Exceptions.DatabaseObjectsException("The table has not been set.");
var tokens = new TokenSerializer();
tokens.Add("SELECT");
tokens.Add(SerializeBeforeSelectFields(select));
tokens.Add(SerializeSelectFields(select.Fields));
tokens.Add("FROM");
tokens.Add(SerializeSelectTables(select.Tables));
tokens.Add(SerializeAfterSelectTables(select));
if (select.Where != null && !select.Where.IsEmpty)
{
tokens.Add("WHERE");
tokens.Add(SerializeConditions(select.Where));
}
if (select.GroupBy != null && !select.GroupBy.IsEmpty)
{
tokens.Add("GROUP BY");
tokens.Add(SerializeSelectGroupByFields(select.GroupBy));
}
if (select.OrderBy != null && !select.OrderBy.IsEmpty)
{
tokens.Add("ORDER BY");
tokens.Add(SerializeSelectOrderByFields(select.OrderBy));
}
if (select.Having != null && !select.Having.IsEmpty)
{
tokens.Add("HAVING");
tokens.Add(SerializeSelectHavingConditions(select.Having));
}
return tokens.ToString();
}
public virtual string SerializeDropView(SQLDropView dropView)
{
return "DROP VIEW " + SerializeIdentifier(dropView.ViewName);
}
public virtual string SerializeCreateView(SQLCreateView createView)
{
if (string.IsNullOrEmpty(createView.Name))
throw new Exceptions.DatabaseObjectsException("View name has not been set");
else if (createView.Select == null)
throw new Exceptions.DatabaseObjectsException("Select statement has not been set");
return "CREATE VIEW " + SerializeIdentifier(createView.Name) + " AS " + SerializeSelect(createView.Select);
}
public virtual string SerializeSetTransactionIsolationLevel(SQLSetTransactionIsolationLevel level)
{
return "SET TRANSACTION ISOLATION LEVEL " + SerializeIsolationLevel(level.Value);
}
public virtual string SerializeIsolationLevel(System.Data.IsolationLevel isolationLevel)
{
switch (isolationLevel)
{
case IsolationLevel.ReadCommitted:
return "READ COMMITTED";
case IsolationLevel.ReadUncommitted:
return "READ UNCOMMITTED";
case IsolationLevel.RepeatableRead:
return "REPEATABLE READ";
case IsolationLevel.Serializable:
return "SERIALIZABLE";
default:
throw new NotSupportedException("Snapshots isolation level is not supported for " + isolationLevel.ToString());
}
}
public virtual string SerializeRollbackTransaction(SQLRollbackTransaction rollbackTransaction)
{
return "ROLLBACK TRANSACTION";
}
public virtual string SerializeCommitTransaction(SQLCommitTransaction commitTransaction)
{
return "COMMIT TRANSACTION";
}
public virtual string SerializeBeingTransaction(SQLBeginTransaction beginTransaction)
{
return "BEGIN TRANSACTION";
}
public virtual string SerializeSelectHavingConditions(SQLSelectHavingConditions havingConditions)
{
int index = 0;
string strSQL = string.Empty;
foreach (var condition in havingConditions)
{
if (index > 0)
strSQL += " " + SerializeLogicalOperator(havingConditions.LogicalOperators[index - 1]) + " ";
if (condition is SQLSelectHavingCondition)
strSQL += ((SQLSelectHavingCondition)condition).SQL(this);
else if (condition is SQLSelectHavingConditions)
strSQL += "(" + SerializeSelectHavingConditions((SQLSelectHavingConditions)condition) + ")";
else
throw new NotImplementedException(condition.GetType().FullName);
index++;
}
return strSQL;
}
public virtual string SerializeSelectOrderByFields(SQLSelectOrderByFields orderByFields)
{
return String.Join(", ", orderByFields.Select(field => SerializeSelectOrderByField(field)).ToArray());
}
public virtual string SerializeSelectOrderByField(SQLSelectOrderByField orderByField)
{
if (String.IsNullOrEmpty(orderByField.Name))
throw new Exceptions.DatabaseObjectsException("Order By field has not been set.");
string strSQL = string.Empty;
if (orderByField.AggregateFunction > 0)
strSQL = SerializeAggregateFunction(orderByField.AggregateFunction) + "(";
strSQL += SerializeFieldNameAndTablePrefix(orderByField.Table, orderByField.Name);
if (orderByField.AggregateFunction > 0)
strSQL += ")";
switch (orderByField.Order)
{
case OrderBy.Ascending:
break;
case OrderBy.Descending:
strSQL += " DESC";
break;
}
return strSQL;
}
public virtual string SerializeSelectGroupByFields(SQLSelectGroupByFields groupByFields)
{
return String.Join(", ", groupByFields.Select(field => field.Expression.SQL(this)).ToArray());
}
public string SerializeConditions(SQLConditions conditions)
{
int index = 0;
string strSQL = string.Empty;
foreach (var condition in conditions)
{
if (index > 0)
strSQL += " " + SerializeLogicalOperator(conditions.LogicalOperators[index - 1]) + " ";
if (condition is SQLCondition)
strSQL += SerializeCondition((SQLCondition)condition);
else if (condition is SQLConditions)
strSQL += "(" + SerializeConditions((SQLConditions)condition) + ")";
else if (condition is SQLConditionInSelect)
strSQL += SerializeConditionInSelect((SQLConditionInSelect)condition);
else if (condition is SQLConditionSelect)
strSQL += SerializeConditionSelect((SQLConditionSelect)condition);
else if (condition is SQLConditionFieldCompare)
strSQL += SerializeConditionFieldCompare((SQLConditionFieldCompare)condition);
else if (condition is SQLConditionExpression)
strSQL += ((SQLConditionExpression)condition).SQL(this);
else
throw new NotImplementedException(condition.GetType().FullName);
index++;
}
return strSQL;
}
public virtual string SerializeConditionFieldCompare(SQLConditionFieldCompare fieldCompare)
{
if (String.IsNullOrEmpty(fieldCompare.FieldName1))
throw new ArgumentException("FieldName1 not set.");
else if (String.IsNullOrEmpty(fieldCompare.FieldName2))
throw new ArgumentException("FieldName2 not set.");
return SerializeFieldNameAndTablePrefix(fieldCompare.Table1, fieldCompare.FieldName1) + " " + SerializeComparisonOperator(fieldCompare.Compare) + " " + SerializeFieldNameAndTablePrefix(fieldCompare.Table2, fieldCompare.FieldName2);
}
public string SerializeArithmeticOperator(SQL.ArithmeticOperator @operator)
{
switch (@operator)
{
case ArithmeticOperator.Add:
return "+";
case ArithmeticOperator.Subtract:
return "-";
case ArithmeticOperator.Multiply:
return "*";
case ArithmeticOperator.Divide:
return "/";
case ArithmeticOperator.Modulus:
return "%";
default:
throw new NotSupportedException(@operator.ToString());
}
}
public virtual string SerializeArithmeticExpression(SQLArithmeticExpression arithmeticExpression)
{
if (arithmeticExpression.LeftExpression == null)
throw new ArgumentNullException(arithmeticExpression.GetType().Name + ".LeftExpression");
else if (arithmeticExpression.RightExpression == null)
throw new ArgumentNullException(arithmeticExpression.GetType().Name + ".RightExpression");
return "(" + arithmeticExpression.LeftExpression.SQL(this) + " " + SerializeArithmeticOperator(arithmeticExpression.Operator) + " " + arithmeticExpression.RightExpression.SQL(this) + ")";
}
public virtual string SerializeLogicalExpression(SQLLogicalExpression logicalExpression)
{
if (logicalExpression.LeftExpression == null)
throw new ArgumentNullException(logicalExpression.GetType().Name + ".LeftExpression");
else if (logicalExpression.RightExpression == null)
throw new ArgumentNullException(logicalExpression.GetType().Name + ".RightExpression");
return "(" + logicalExpression.LeftExpression.SQL(this) + " " + SerializeLogicalOperator(logicalExpression.Operator) + " " + logicalExpression.RightExpression.SQL(this) + ")";
}
public virtual string SerializeAggregateExpression(SQLAggregateExpression aggregateExpression)
{
return SerializeAggregateFunction(aggregateExpression.Aggregate) + SerializeFunctionExpressionArguments(aggregateExpression);
}
public virtual string SerializeConditionSelect(SQLConditionSelect conditionSelect)
{
if (conditionSelect.Select == null)
throw new Exceptions.DatabaseObjectsException("Select is not set.");
return "(" + SerializeSelect(conditionSelect.Select) + ") " + SerializeCondition(conditionSelect.Compare, conditionSelect.Value);
}
public virtual string SerializeConditionInSelect(SQLConditionInSelect conditionInSelect)
{
if (String.IsNullOrEmpty(conditionInSelect.FieldName))
throw new Exceptions.DatabaseObjectsException("FieldName not set.");
else if (conditionInSelect.Select == null)
throw new Exceptions.DatabaseObjectsException("SelectSet not set.");
string strIn;
if (conditionInSelect.NotInSelect)
strIn = "NOT IN";
else
strIn = "IN";
return SerializeFieldNameAndTablePrefix(conditionInSelect.Table, conditionInSelect.FieldName) + " " + strIn + " (" + SerializeSelect(conditionInSelect.Select) + ")";
}
/// <summary>
/// Serializes all of the tables from the SELECT statment.
/// </summary>
public virtual string SerializeSelectTables(SQLSelectTables selectTables)
{
var strSQL = String.Join(", ",
selectTables
.Where(table => selectTables.Joins == null || !selectTables.Joins.Exists(table))
.Select(table => SerializeSelectTableBase(table))
.ToArray());
if (selectTables.Joins != null)
{
string strJoinsSQL = SerializeSelectTableJoins(selectTables.Joins);
if (strJoinsSQL != string.Empty && strSQL != string.Empty)
strSQL += " ";
strSQL += strJoinsSQL;
}
return strSQL;
}
public virtual string SerializeAfterSelectTables(SQLSelect select)
{
return String.Empty;
}
public virtual string SerializeSelectTableFromSelect(SQLSelectTableFromSelect tableFromSelect)
{
return "(" + SerializeSelect(tableFromSelect.Select) + ")";
}
public virtual string SerializeSelectHavingCondition(SQLSelectHavingCondition havingCondition)
{
return havingCondition.LeftExpression.SQL(this) + " " + SerializeComparisonOperator(havingCondition.Compare) + " " + havingCondition.RightExpression.SQL(this);
}
public virtual string SerializeTableFieldComputed(SQLTableFieldComputed tableFieldComputed, SQLTableFields.AlterModeType alterMode)
{
if (alterMode == SQLTableFields.AlterModeType.Drop)
throw new InvalidOperationException("Computed columns cannot be used for dropping fields");
return tableFieldComputed.NameAsExpression.SQL(this) + " AS (" + tableFieldComputed.Computation.SQL(this) + ")";
}
public virtual string SerializeCreateTable(SQLCreateTable createTable)
{
if (String.IsNullOrEmpty(createTable.Name))
throw new Exceptions.DatabaseObjectsException("TableName has not been set.");
var tokens = new TokenSerializer();
tokens.Add("CREATE TABLE");
tokens.Add(SerializeIdentifier(createTable.Name));
tokens.Add("(" + SerializeTableFields(createTable.Fields, includeColumnModifier: false) + ")");
return tokens.ToString();
}
public virtual string SerializeDropTable(SQLDropTable dropTable)
{
if (String.IsNullOrEmpty(dropTable.Name))
throw new Exceptions.DatabaseObjectsException("TableName has not been set.");
return "DROP TABLE " + SerializeIdentifier(dropTable.Name);
}
public virtual string SerializeDropIndex(SQLDropIndex dropIndex)
{
if (String.IsNullOrEmpty(dropIndex.Name))
throw new Exceptions.DatabaseObjectsException("IndexName has not been set.");
else if (String.IsNullOrEmpty(dropIndex.TableName))
throw new Exceptions.DatabaseObjectsException("TableName has not been set.");
return "DROP INDEX " + SerializeIdentifier(dropIndex.Name) + " ON " + SerializeIdentifier(dropIndex.TableName);
}
public virtual string SerializeCreateIndex(SQLCreateIndex createIndex)
{
//Although the index name is optional with SQL Server it is not optional with MySQL or Pervasive
if (String.IsNullOrEmpty(createIndex.Name))
throw new Exceptions.DatabaseObjectsException("IndexName has not been set.");
else if (String.IsNullOrEmpty(createIndex.TableName))
throw new Exceptions.DatabaseObjectsException("TableName has not been set.");
var tokens = new TokenSerializer();
tokens.Add("CREATE");
tokens.Add(SerializeCreateIndexModifier(createIndex));
tokens.Add("INDEX");
tokens.Add(SerializeIdentifier(createIndex.Name));
tokens.Add("ON");
tokens.Add(SerializeIdentifier(createIndex.TableName));
tokens.Add("(" + SerializeIndexFields(createIndex.Fields) + ")");
return tokens.ToString();
}
public virtual string SerializeCreateIndexModifier(SQLCreateIndex createIndex)
{
if (createIndex.IsUnique)
return "UNIQUE";
else
return String.Empty;
}
public virtual string SerializeIndexFields(SQLIndexFields fields)
{
var tokens = new TokenSerializer(", ");
foreach (SQLIndexField objField in fields)
tokens.Add(SerializeIndexField(objField));
return tokens.ToString();
}
public virtual string SerializeIndexField(SQLIndexField indexField)
{
var tokens = new TokenSerializer();
tokens.Add(SerializeIdentifier(indexField.Name));
tokens.Add(SerializeOrderBy(indexField.Order));
return tokens.ToString();
}
public virtual string SerializeOrderBy(OrderBy orderBy)
{
switch (orderBy)
{
case OrderBy.None:
case OrderBy.Ascending:
return String.Empty;
case OrderBy.Descending:
return "DESC";
default:
throw new NotImplementedException();
}
}
public virtual string SerializeAlterTable(SQLAlterTable alterTable)
{
if (String.IsNullOrEmpty(alterTable.Name))
throw new Exceptions.DatabaseObjectsException("TableName has not been set.");
return "ALTER TABLE " + SerializeIdentifier(alterTable.Name) + " " + SerializeTableFields(alterTable.Fields, includeColumnModifier: true);
}
/// <summary>
/// </summary>
/// <param name="includeColumnModifier">
/// Indicates whether the ADD, MODIFY or DROP modifiers are required for each column.
/// When utilised from SQLCreateTable this will always be false. However, for SQLAlterTable this will be true.</param>
/// <returns></returns>
public virtual string SerializeTableFields(SQLTableFields tableFields, bool includeColumnModifier)
{
var tokens = new TokenSerializer();
//Include mode when altering a table, otherwise when creating a table the mode is not required.
if (includeColumnModifier)
tokens.Add(SerializeAlterTableFieldsModifier(tableFields.AlterMode));
var fieldsTokens = new TokenSerializer(", ");
foreach (SQLTableFieldBase field in tableFields)
{
var fieldToken = new TokenSerializer();
if (includeColumnModifier)
fieldToken.Add(SerializeAlterTableFieldModifier(tableFields.AlterMode));
fieldToken.Add(field.SQL(this, tableFields.AlterMode));
fieldsTokens.Add(fieldToken.ToString());
}
tokens.Add(fieldsTokens.ToString());
return tokens.ToString();
}
/// <summary>
/// The field modifier that is used before all of the fields modifications are listed.
/// Typically used by SQL Server to indicate the type of operation to be performed on ALL fields.
/// </summary>
/// <param name="tableFields"></param>
/// <returns></returns>
public virtual string SerializeAlterTableFieldsModifier(SQLTableFields.AlterModeType alterMode)
{
return SerializeColumnAlterMode(alterMode);
}
/// <summary>
/// The field modifier that is used before each field that is being modified.
/// Typically used by MySQL the type of operation to be performed on each field.
/// </summary>
/// <param name="tableFields"></param>
/// <returns></returns>
public virtual string SerializeAlterTableFieldModifier(SQLTableFields.AlterModeType alterMode)
{
return String.Empty;
}
public virtual string SerializeColumnAlterMode(SQLTableFields.AlterModeType alterMode)
{
switch (alterMode)
{
case SQLTableFields.AlterModeType.Add:
return "ADD";
case SQLTableFields.AlterModeType.Modify:
return "ALTER COLUMN";
case SQLTableFields.AlterModeType.Drop:
return "DROP COLUMN";
default:
throw new NotImplementedException();
}
}
public virtual string SerializeSelectTableJoins(SQLSelectTableJoins tableJoins)
{
if (tableJoins.Count > 0)
//recurse through the joins from right to left
return SerializeSelectTableJoin(tableJoins[tableJoins.Count - 1]);
else
return string.Empty;
}
public virtual string SerializeTableFieldAsName(SQLTableField field)
{
return field.NameAsExpression.SQL(this);
}
public virtual string SerializeTableField(SQLTableField field, SQLTableFields.AlterModeType alterMode)
{
var tokens = new TokenSerializer();
if (alterMode == SQLTableFields.AlterModeType.Drop)
tokens.Add(SerializeTableFieldAsName(field));
else
{
tokens.Add(SerializeTableFieldAsName(field));
tokens.Add(SerializeTableFieldDataType(field));
tokens.Add(SerializeTableFieldDefaultOption(field));
tokens.Add(SerializeTableFieldNullableOption(field));
tokens.Add(SerializeTableFieldKeyTypeOption(field));
}
return tokens.ToString();
}
public virtual string SerializeTableFieldDataType(SQLTableField field)
{
return SerializeDataType(field.DataType, field.Size, field.Precision, field.ScaleLength);
}
public virtual string SerializeTableFieldDefaultOption(SQLTableField field)
{
if (field.Default != null)
return "DEFAULT " + SerializeValue(field.Default);
else
return String.Empty;
}
public virtual string SerializeTableFieldNullableOption(SQLTableField field)
{
if (field.AcceptsNull)
return "NULL";
else
return "NOT NULL";
}
public virtual string SerializeTableFieldKeyTypeOption(SQLTableField field)
{
if (field.KeyType == KeyType.Primary)
return "PRIMARY KEY";
else if (field.KeyType == KeyType.Unique)
return "UNIQUE";
else
return String.Empty;
}
public virtual string SerializeSelectTable(SQLSelectTable table)
{
if (String.IsNullOrEmpty(table.Name))
throw new Exceptions.DatabaseObjectsException("Table has not been set.");
string strSQL = string.Empty;
if (!String.IsNullOrEmpty(table.DatabaseName))
strSQL += SerializeIdentifier(table.DatabaseName) + ".";
if (!String.IsNullOrEmpty(table.SchemaName))
strSQL += SerializeIdentifier(table.SchemaName) + ".";
return strSQL + SerializeIdentifier(table.Name);
}
public virtual string SerializeSelectTableJoin(SQLSelectTableJoin table)
{
string strSQL = SerializeSelectTableBase(table.LeftTable) + " " + SerializeTableJoinType(table.TheType) + " " + SerializeSelectTableBase(table.RightTable);
var conditions = table.Where;
if (conditions != null && !conditions.IsEmpty)
strSQL += " ON " + SerializeSelectTableJoinConditions(conditions);
//Surround the join with parentheses - MS Access won't accept it otherwise
return "(" + strSQL + ")";
}
public virtual string SerializeSelectTableJoinConditions(SQLSelectTableJoinConditions joinConditions)
{
string strSQL = string.Empty;
int intIndex = 0;
foreach (object objCondition in joinConditions)
{
if (intIndex > 0)
strSQL += " " + SerializeLogicalOperator(joinConditions.LogicalOperators[intIndex - 1]) + " ";
if (objCondition is SQLSelectTableJoinConditions)
strSQL += "(" + SerializeSelectTableJoinConditions((SQLSelectTableJoinConditions)objCondition) + ")";
else if (objCondition is SQLSelectTableJoinCondition)
strSQL += SerializeSelectTableJoinCondition((SQLSelectTableJoinCondition)objCondition);
else
throw new NotImplementedException(objCondition.GetType().FullName);
intIndex++;
}
return strSQL;
}
public virtual string SerializeSelectTableJoinCondition(SQLSelectTableJoinCondition joinCondition)
{
//Account for the situation where EqualTo to NULL is appropriately translated to 'IS NULL'
if (joinCondition.RightExpression is SQLValueExpression)
return joinCondition.LeftExpression.SQL(this) + " " + SerializeCondition(joinCondition.Compare, ((SQLValueExpression)joinCondition.RightExpression).Value);
else
return joinCondition.LeftExpression.SQL(this) + " " + SerializeComparisonOperator(joinCondition.Compare) + " " + joinCondition.RightExpression.SQL(this);
}
public virtual string SerializeCaseExpressionCase(SQLCaseExpression.Case expressionCase)
{
return "WHEN " + expressionCase.WhenCondition.SQL(this) + " THEN " + expressionCase.Result.SQL(this);
}
public virtual string SerializeCaseExpression(SQLCaseExpression expression)
{
if (expression.Cases.Count() == 0)
throw new InvalidOperationException("There are no cases for the CASE statement");
var tokens = new TokenSerializer();
tokens.Add("CASE");
if (expression.InputExpression != null)
tokens.Add(expression.InputExpression.SQL(this));
var cases = string.Join(" ", expression.Cases.Select(objCase => SerializeCaseExpressionCase(objCase)).ToArray());
tokens.Add(cases);
if (expression.ElseResult != null)
{
tokens.Add("ELSE");
tokens.Add(expression.ElseResult.SQL(this));
}
tokens.Add("END");
return tokens.ToString();
}
public virtual string SerializeCastExpression(SQLCastExpression expression)
{
return "CAST(" + SerializeIdentifier(expression.FieldName) + " AS " + SerializeDataType(expression.ToDataType, expression.Size, expression.Precision, expression.ScaleLength) + ")";
}
public virtual string SerializeDataType(SQL.DataType dataType, int intSize, int intPrecision, int intScale)
{
throw new NotImplementedException("Data type " + dataType.ToString() + " is not implemented for " + this.GetType().Name);
}
public virtual string SerializeBitwiseExpression(SQLBitwiseExpression expression)
{
if (expression.LeftExpression == null)
throw new ArgumentNullException(expression.GetType().Name + ".LeftExpression");
else if (expression.RightExpression == null)
throw new ArgumentNullException(expression.GetType().Name + ".RightExpression");
return "(" + expression.LeftExpression.SQL(this) + " " + SerializeBitwiseOperator(expression.Operator) + " " + expression.RightExpression.SQL(this) + ")";
}
public virtual string SerializeFieldAggregateExpression(SQLFieldAggregateExpression expression)
{
if (expression.AggregateFunction == AggregateFunction.None)
throw new InvalidOperationException("AggregateFunction unspecified for " + this.GetType().Name);
string strFieldName = string.Empty;
if (expression.AggregateFunction == AggregateFunction.Count)
strFieldName = "*";
else
strFieldName = SerializeFieldExpression(expression);
return SerializeAggregateFunction(expression.AggregateFunction) + "(" + strFieldName + ")";
}
/// <summary>
/// Includes parentheses around arguments if required.
/// </summary>
/// <returns></returns>
public virtual string SerializeFunctionExpressionArguments(SQLFunctionExpression functionExpression)
{
string strArguments = string.Empty;
if (functionExpression.Arguments != null)
strArguments = String.Join(", ", functionExpression.Arguments.Select(argument => argument.SQL(this)).ToArray());
if ((functionExpression.IncludeParenthesesWhenArgumentsEmpty && !functionExpression.HasArguments) || functionExpression.HasArguments)
strArguments = "(" + strArguments + ")";
return strArguments;
}
/// <summary>
/// Should return a SELECT statement that can be used to obtain the value from a auto increment / identity field
/// after an INSERT statement.
/// </summary>
public virtual string SerializeAutoIncrementValue(SQLAutoIncrementValue autoIncrementValue)
{
return "SELECT @@IDENTITY AS " + SerializeIdentifier(autoIncrementValue.ReturnFieldName);
}
public virtual string SerializeSelectExpression(SQLSelectExpression selectExpression)
{
return "SELECT " + selectExpression.Expression.SQL(this);
}
public virtual string SerializeSelectField(SQLSelectField field)
{
string strSQL = field.Expression.SQL(this);
if (!String.IsNullOrEmpty(field.Alias))
strSQL += " AS " + SerializeIdentifier(field.Alias);
return strSQL;
}
public virtual string SerializeStringContactExpression(SQLStringConcatExpression expression)
{
if (expression.LeftExpression == null)
throw new ArgumentNullException(expression.GetType().Name + ".LeftExpression");
else if (expression.RightExpression == null)
throw new ArgumentNullException(expression.GetType().Name + ".RightExpression");
return expression.LeftExpression.SQL(this) + " + " + expression.RightExpression.SQL(this);
}
public virtual string SerializeLengthFunctionExpression(SQLLengthFunctionExpression expression)
{
throw new NotImplementedException();
}
public virtual string SerializeLeftFunctionExpression(SQLLeftFunctionExpression expression)
{
return "LEFT" + SerializeFunctionExpressionArguments(expression);
}
public virtual string SerializeRightFunctionExpression(SQLRightFunctionExpression expression)
{
return "RIGHT" + SerializeFunctionExpressionArguments(expression);
}
public virtual string SerializeGetDateFunctionExpression(SQLGetDateFunctionExpression expression)
{
throw new NotImplementedException();
}
public virtual string SerializeFieldExpression(SQLFieldExpression fieldExpression)
{
if (String.IsNullOrEmpty(fieldExpression.Name))
throw new Exceptions.DatabaseObjectsException("Field Name has not been set.");
return SerializeFieldNameAndTablePrefix(fieldExpression.Table, fieldExpression.Name);
}
public virtual string SerializeBitwiseOperator(SQL.BitwiseOperator eOperator)
{
if (eOperator == BitwiseOperator.And)
return "&";
else if (eOperator == BitwiseOperator.Or)
return "|";
else
throw new NotSupportedException(eOperator.ToString());
}
public virtual string SerializeUnion(SQLUnion union)
{
if (union.SelectStatements.Count() < 2)
throw new Exceptions.DatabaseObjectsException("The select statements have not been set");
var tokens = new TokenSerializer();
int index = 0;
foreach (var statement in union.SelectStatements)
{
if (index > 0)
tokens.Add(SerializeUnionType(union.UnionTypes[index - 1]));
tokens.Add("(" + SerializeSelect(statement) + ")");
index++;
}
if (union.OrderBy != null && !union.OrderBy.IsEmpty)
{
tokens.Add("ORDER BY");
tokens.Add(SerializeSelectOrderByFields(union.OrderBy));
}
return tokens.ToString();
}
public virtual string SerializeUnionType(SQLUnion.Type type)
{
switch (type)
{
case SQLUnion.Type.Distinct:
return "UNION";
case SQLUnion.Type.All:
return "UNION ALL";
default:
throw new NotImplementedException(type.ToString());
}
}
public string SerializeConditionExpression(SQLConditionExpression expression)
{
if (expression.LeftExpression == null)
throw new InvalidOperationException("Left expression is not set");
else if (expression.RightExpression == null)
throw new InvalidOperationException("Right expression is not set");
string strSQL = expression.LeftExpression.SQL(this) + " ";
if (expression.RightExpression is SQLValueExpression)
strSQL += SerializeCondition(expression.Compare, ((SQLValueExpression)expression.RightExpression).Value);
else
strSQL += SerializeComparisonOperator(expression.Compare) + " " + expression.RightExpression.SQL(this);
return strSQL;
}
private static void EnsureCompareValuePairValid(SQL.ComparisonOperator eCompare, object objValue)
{
if (!(objValue is string) && (eCompare == ComparisonOperator.Like || eCompare == ComparisonOperator.NotLike))
throw new Exceptions.DatabaseObjectsException("The LIKE operator cannot be used in conjunction with a non-string data type");
else if (objValue is bool && !(eCompare == ComparisonOperator.EqualTo || eCompare == ComparisonOperator.NotEqualTo))
throw new Exceptions.DatabaseObjectsException("A boolean value can only be used in conjunction with the " + ComparisonOperator.EqualTo.ToString() + " or " + ComparisonOperator.NotEqualTo.ToString() + " operators");
}
public virtual string SerializeCondition(SQLCondition condition)
{
return SerializeFieldNameAndTablePrefix(condition.Table, condition.FieldName) + " " + SerializeCondition(condition.Compare, condition.Value);
}
protected string SerializeCondition(ComparisonOperator eCompare, object objValue)
{
EnsureCompareValuePairValid(eCompare, objValue);