-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathfrmMain.cs
More file actions
1309 lines (1013 loc) · 50.3 KB
/
frmMain.cs
File metadata and controls
1309 lines (1013 loc) · 50.3 KB
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;
using System.Collections;
using System.Data;
using System.Data.Common;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using System.Reflection;
using System.IO;
using System.Diagnostics;
using System.Data.SqlClient;
namespace zenComparer
{
public partial class frmMain : Form
{
public static string masterConnectionString;
public static string slaveConnectionString;
public static string commandLineArguments;
public static string commandLineTool;
public DataTable masterTables { get; set; }
public DataTable masterIndexes { get; set; }
public DataTable masterObjects { get; set; }
#region Initialize
int excludedNumber;
public frmMain()
{
InitializeComponent();
//Form
this.Text = string.Format("{0} {1} | {2}", AssemblyProduct, AssemblyVersion, AssemblyDescription);
// toolCompare.Click += new EventHandler(btncompare_Click);
//Porownanie schema
btnStartCompare.Click += new EventHandler(btncompare_Click); //porownanie schema
btnShowDiff.Click += new EventHandler(btnShowDiff_Click);
butSwitch.Click += new EventHandler(butSwitch_Click);
txtMaster.KeyUp += new KeyEventHandler(ConnectionStringToTextbox);
txtSlave.KeyUp += new KeyEventHandler(ConnectionStringToTextbox);
//KAzde nacisniecie powoduje odswiezenie connectionstringa
mserver.KeyUp += new KeyEventHandler(TextboxToConnectionString);
mdatabase.KeyUp += new KeyEventHandler(TextboxToConnectionString);
mlogin.KeyUp += new KeyEventHandler(TextboxToConnectionString);
mpassword.KeyUp += new KeyEventHandler(TextboxToConnectionString);
mSSI.CheckedChanged += new EventHandler(CheckedChanged);
sserver.KeyUp += new KeyEventHandler(TextboxToConnectionString);
sdatabase.KeyUp += new KeyEventHandler(TextboxToConnectionString);
slogin.KeyUp += new KeyEventHandler(TextboxToConnectionString);
spassword.KeyUp += new KeyEventHandler(TextboxToConnectionString);
sssi.CheckedChanged += new EventHandler(CheckedChanged);
//Ekran About
toolAbout.Click += new EventHandler(toolAbout_Click);
commandLineArguments = txtarguments.Text;
commandLineTool = txtExternalTool.Text;
}
void btnShowDiff_Click(object sender, EventArgs e)
{
try
{
foreach (DataGridViewRow dgvr in dgResult.Rows)
{
if ((dgvr.Selected && (string)dgvr.Cells["scriptModel"].Value != "" && (string)dgvr.Cells["scriptTarget"].Value != ""))
{
Process myProc;
// Generate File
Directory.CreateDirectory(Application.StartupPath + "\\log\\");
string filenameModel = string.Format(Application.StartupPath +"\\log\\{3}_{0}_{1}_{2}_M.sql", mdatabase.Text, (string)dgvr.Cells["object"].Value, DateTime.Now.ToString("yyyymmddhhmmss"), mserver.Text);
FileStream f = new FileStream(filenameModel, FileMode.Create);
StreamWriter s = new StreamWriter(f);
s.WriteLine((string)dgvr.Cells["scriptModel"].Value);
s.Close();
f.Close();
string filenameTarget = string.Format(Application.StartupPath +"\\log\\{3}_{0}_{1}_{2}_T.sql", sdatabase.Text, (string)dgvr.Cells["object"].Value, DateTime.Now.ToString("yyyymmddhhmmss"), mserver.Text);
f = new FileStream(filenameTarget, FileMode.Create);
s = new StreamWriter(f);
s.WriteLine((string)dgvr.Cells["scriptTarget"].Value);
s.Close();
f.Close();
string commandline = txtarguments.Text.Replace("%Model", filenameModel);
commandline = commandline.Replace("%Target", filenameTarget);
myProc = Process.Start(txtExternalTool.Text, commandline);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
#endregion
/// <summary>
/// Porownnanie
/// </summary>
void btncompare_Click(object sender, EventArgs e)
{
// try
// {
Cursor.Current = Cursors.WaitCursor;
excludedNumber = 0;
dgResult.Rows.Clear();
toolLog.Clear();
result.Clear();
logger("COMPARE START");
compareTables();
Refresh();
compareObjects();
compareIndex();
gridToScript(true);
logger(string.Format("COMPARE FINISHED found {0} problems. Excluded item {1}", dgResult.Rows.Count.ToString(), excludedNumber));
Cursor.Current = Cursors.Default;
//}
//catch (Exception ex)
//{
// Cursor.Current = Cursors.Default;
// MessageBox.Show(this, ex.Message.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
//}
}
void compareObjects()
{
logger("Get schema for objects from MODEL ");
DataTable master = new DataTable();
if (masterObjects != null)
{
master = masterObjects;
}
else
{
master = Extensions.GetDataTable(variables.sqlObjects, txtMaster.Text);
}
logger("Get schema for objects from TARGET");
DataTable slave = new DataTable();
slave = Extensions.GetDataTable(variables.sqlObjects, txtSlave.Text);
logger("START COMPARING objects SCHEMA");
compare(master, slave, out excludedNumber);
if (masterObjects == null)
{
master.Dispose();
slave.Dispose();
}
}
/// <summary>
/// Dodanie pozycji do gridview
/// </summary>
void dgResultInsertRow(string _source, string _type, string _object, string _details, string _action, string _scriptModel, string _scriptTarget)
{
DataGridViewRow dgrow = new DataGridViewRow();
DataGridViewCell dgCell;
dgCell = new DataGridViewTextBoxCell();
dgCell.Value = _source;
dgrow.Cells.Add(dgCell);
dgCell = new DataGridViewTextBoxCell();
dgCell.Value = _type;
dgrow.Cells.Add(dgCell);
dgCell = new DataGridViewTextBoxCell();
dgCell.Value = _object;
dgrow.Cells.Add(dgCell);
dgCell = new DataGridViewTextBoxCell();
dgCell.Value = _details;
dgrow.Cells.Add(dgCell);
dgCell = new DataGridViewTextBoxCell();
dgCell.Value = _action;
dgrow.Cells.Add(dgCell);
dgCell = new DataGridViewTextBoxCell();
dgCell.Value = _scriptModel.Trim();
dgrow.Cells.Add(dgCell);
dgCell = new DataGridViewTextBoxCell();
dgCell.Value = _scriptTarget.Trim();
dgrow.Cells.Add(dgCell);
dgResult.Rows.Add(dgrow);
//dgResult.Refresh();
}
void CheckedChanged(object sender, EventArgs e)
{
TextboxToConnectionString(null, null);
}
void butSwitch_Click(object sender, EventArgs e)
{
string temp = txtMaster.Text;
string temp1 = txtSlave.Text;
txtMaster.Text = temp1;
txtSlave.Text = temp;
Refresh();
ConnectionStringToTextbox(null, null);
}
void ConnectionStringToTextboxMethod()
{
try
{
DbConnectionStringBuilder builder = new DbConnectionStringBuilder();
DbConnectionStringBuilder builder1 = new DbConnectionStringBuilder();
builder.ConnectionString = txtMaster.Text.Replace(Environment.NewLine, " ");
builder1.ConnectionString = txtSlave.Text.Replace(Environment.NewLine, " ");
mserver.Text = connectionStringValue(builder, "Data source");
mdatabase.Text = connectionStringValue(builder, "Initial Catalog", "database");
mlogin.Text = connectionStringValue(builder, "User ID", "UID");
mpassword.Text = connectionStringValue(builder, "Password");
mSSI.Checked = connectionStringValue(builder, "Integrated Security").ToLower() == "sspi" ? true : false;
sserver.Text = connectionStringValue(builder1, "Data source");
sdatabase.Text = connectionStringValue(builder1, "Initial Catalog", "database");
slogin.Text = connectionStringValue(builder1, "User ID", "UID");
spassword.Text = connectionStringValue(builder1, "Password");
sssi.Checked = connectionStringValue(builder1, "Integrated Security").ToLower() == "sspi" ? true : false;
masterConnectionString = builder.ConnectionString;
slaveConnectionString = builder1.ConnectionString;
}
catch (Exception ex)
{
toolLog.Text = ex.Message.ToString();
}
}
/// <summary>
/// Tlumaczenie connectionstring
/// </summary>
void ConnectionStringToTextbox(object sender, KeyEventArgs e)
{
ConnectionStringToTextboxMethod();
}
void TextboxToConnectionStringMethod()
{
DbConnectionStringBuilder builder = new DbConnectionStringBuilder();
try
{
builder.Add("Data Source", mserver.Text);
builder.Add("Initial Catalog", mdatabase.Text);
if (mSSI.Checked)
builder.Add("Integrated Security", "SSPI");
else
{
builder.Add("User ID", mlogin.Text);
builder.Add("Password", mpassword.Text);
}
txtMaster.Text = builder.ConnectionString;
}
catch (Exception)
{
toolLog.Text = "Invalid Model connection String";
}
try
{
builder.Clear();
builder.Add("Data Source", sserver.Text);
builder.Add("Initial Catalog", sdatabase.Text);
if (sssi.Checked)
builder.Add("Integrated Security", "SSPI");
else
{
builder.Add("User ID", slogin.Text);
builder.Add("Password", spassword.Text);
}
txtSlave.Text = builder.ConnectionString;
}
catch (Exception)
{
toolLog.Text = "Invalid Target connection String";
}
toolLog.Text = "";
}
void TextboxToConnectionString(object sender, KeyEventArgs e)
{
TextboxToConnectionStringMethod();
}
string connectionStringValue(DbConnectionStringBuilder builder, string input, string input1)
{
object test = "";
if (!builder.TryGetValue(input, out test))
if (!builder.TryGetValue(input1, out test))
return "";
return test.ToString();
}
string connectionStringValue(DbConnectionStringBuilder builder, string input)
{
object test = "";
if (!builder.TryGetValue(input, out test))
return "";
return test.ToString();
}
void logger(string text)
{
toolLog.Text = text;
if (ActiveForm != null)
ActiveForm.Refresh();
}
void compareIndex()
{
logger("Get schema for index from MODEL ");
DataTable master = new DataTable();
if (masterIndexes != null)
{
master = masterIndexes;
}
else
{
master = Extensions.GetDataTable(variables.sqlIndex, txtMaster.Text);
}
logger("Get schema for index from TARGET");
DataTable slave = new DataTable();
slave = Extensions.GetDataTable(variables.sqlIndex, txtSlave.Text);
logger("START COMPARING index SCHEMA");
compare(master, slave, out excludedNumber);
if (masterIndexes == null)
{
master.Dispose();
slave.Dispose();
}
}
/// <summary>
/// Porownywanie tables
/// </summary>
void compareTables()
{
//Pobranie danych z master
logger("Get schema for tables from MODEL");
DataTable master = new DataTable();
DataTable slave = new DataTable();
if (masterTables != null)
{
master = masterTables;
}
else
{
master = Extensions.GetDataTable(variables.sqlTables, txtMaster.Text);
}
logger("Get schema for tables from TARGET");
//Pobranie danych z slav
slave = Extensions.GetDataTable(variables.sqlTables, txtSlave.Text);
logger("START COMPARING tables SCHEMA");
compare(master, slave, out excludedNumber);
if (masterTables == null)
{
master.Dispose();
slave.Dispose();
}
}
/// <summary>
/// Procedura porownujaca Datatabel musi posiadac key i text
/// </summary>
/// <param name="master"></param>
/// <param name="slave"></param>
public void compare(DataTable master, DataTable slave, out int excludedCounter)
{
excludedCounter = excludedNumber;
//pobranie slave
Hashtable ht = zenComparer.Extensions._convertDataTableToHashTable(slave, "Key", "text");
foreach (DataRow r in master.Rows)
{
string option = r["type"].ToString().Trim().ToUpper(); //typ
string action = "";
string a = "", b = "", temp = "";
bool excluded = false;
string script = "";
string ModelScript = "";
string TargetScript = "";
//Sprawdzenie czy wogole porownywac
char[] delim = { ',' };
string[] excludeditem = txtexclude.Text.ToLower().Split(delim);
string details = "";
string key = Extensions._getSeparatedString(r["key"].ToString().ToLower(), 0);
// key = key.Replace("dbo.", "");
key = key.Replace("[", "");
key = key.Replace("]", ""); //nazwa obiektu
foreach (string s in excludeditem)
{
if (s.Trim().StartsWith("*") && s.Trim().EndsWith("*"))
{
if (key.Trim().Contains(s.Trim().ToLower().Replace("*", "")))
{
excluded = true;
break;
}
}
else if (s.Trim().EndsWith("*"))
{
if (key.Trim().StartsWith(s.Trim().ToLower().Replace("*", "")))
{
excluded = true;
break;
}
}
else if (s.Trim().StartsWith("*"))
{
if (key.Trim().EndsWith(s.Trim().ToLower().Replace("*", "")))
{
excluded = true;
break;
}
}
else
if (key == s.Trim().ToLower())
{
excluded = true;
break;
}
}
if (excluded)
{
excludedCounter += 1;
continue;
}
//sprawdzenie czy slave zawiera taki klucz jelsi tak trzeba porownac
if (ht.ContainsKey(r["key"].ToString().ToLower()))
{
a = ht[r["key"].ToString().ToLower()].ToString().Trim(); //pobranie ze slave
b = r["text"].ToString().Trim(); //pobranie z master
ModelScript = unification(a).Trim();//zenComparer.Extensions._cleanstring(unification(a));
TargetScript = unification(b).Trim();//zenComparer.Extensions._cleanstring(unification(b));
//Wazne cleanstring porownuje bez whitespace
//unification zapewnia ze tpominiete zostana texty create ktore czesto maja male duze litery
if (string.CompareOrdinal(zenComparer.Extensions._cleanstring(ModelScript), zenComparer.Extensions._cleanstring(TargetScript)) != 0)
{
action = "Missmatched";
}
//Porównujemy bez komentarzy i
if (action == "Missmatched")
{
string text = zenComparer.Extensions._cleanstringWithoutComments(ModelScript);
if (string.CompareOrdinal(zenComparer.Extensions._cleanstringWithoutComments(ModelScript), zenComparer.Extensions._cleanstringWithoutComments(TargetScript)) == 0)
{
action = "Missmatched.Comments";
}
}
}
else //Obiekt missing
{
b = r["text"].ToString(); //pobranie z master
action = "Missing";
}
details = Extensions._getSeparatedString(b, 1);
if (action == "Missing" || action == "Missmatched" || action =="Missmatched.Comments")
switch (option)
{
//case "U":
// if (action == "Missing") //Brak tabeli
// {
// }
// break;
case "CO": //user tables sa bardziej skomplikowane
/// 0 -table name
/// 1- column_name
/// 2- isnull(cast(data_type as varchar), '')
/// 3- isnull(cast(character_maximum_length as varchar), '')
/// 4- isnull(column_default, '')
/// 5- numeric precision
/// 6- numeric_scale
/// 7- is nullable
/// 8- default constraint name
/// 9- isidentity 1
if (action == "Missing") //brakuje kolumny
{
script = string.Format("alter table [{5}].[{0}] add [{1}] {2} {3} {4}",
Extensions._getSeparatedString(b, 0), //table name
Extensions._getSeparatedString(b, 1), //column name
datatype(b), //get varchar(max) decimal(18,2)
identity(b), //identity
notnull(b), //not null
Extensions._getSeparatedString(b, 9) //schema
);
dgResultInsertRow("Target",
string.Format("{0}.{1}.{2}", SymbolToObject(option), "Column", action),
key,
details,
"Generated script " + temp,
script, "");
}
else if (action == "Missmatched" || action =="Missmatched.Comments") //data_type, character maximum length,numeric precision, numeric scale
{
// 0 1
//a "tbldoc|docagreement|datetime|||0|0|YES|" string
//b "tbldoc|docagreement|smalldatetime|||0|0|YES|" string
string x, x1;
//porownanie typow datetime,smalldtatime
x = datatype(a); //slave
x1 = datatype(b); //master
if (string.CompareOrdinal(x, x1) != 0)
{
if (!string.IsNullOrEmpty(Extensions._getSeparatedString(a, 8)))
{
script = string.Format(@"
exec sp_unbindefault @objname = '[{4}].[{0}].[{1}]' --try to unbind default throw error if no default
GO
ALTER TABLE [{4}].[{0}] DROP CONSTRAINT [{5}] -- drop default constraint which prevents update of datatype, Default constraint will be created in second schema comparision hit, Ugly but works :)
GO
",
Extensions._getSeparatedString(b, 0), //table name
Extensions._getSeparatedString(b, 1), //column name
datatype(b),
notnull(b), //not null
Extensions._getSeparatedString(b, 9), //schema
Extensions._getSeparatedString(a, 8) //default constarint name jelsi jest jakis
);
}
script += string.Format(@"
-- DROP INDEX[{4}].[{0}].[index name] --IF index exists you must drop first, zencomparer will recreate from source index
alter table [{4}].[{0}] ALTER COLUMN [{1}] {2} {3} ",
Extensions._getSeparatedString(b, 0), //table name
Extensions._getSeparatedString(b, 1), //column name
datatype(b),
notnull(b), //not null
Extensions._getSeparatedString(b, 9) //schema
);
dgResultInsertRow("Target",
string.Format("{0}.{1}.{2}", SymbolToObject(option), action, "data type"),
key,
details,
String.Format("Generated script > change {0}> from:{1} to:{2} ", temp, datatype(a), datatype(b)),
script, "");
}
//porownanie default
x = Extensions._getSeparatedString(a, 4);
x1 = Extensions._getSeparatedString(b, 4);
script = "";
if (string.CompareOrdinal(x, x1) != 0)
{
if (!string.IsNullOrEmpty(Extensions._getSeparatedString(a, 8)))
{
script = string.Format(@"
exec sp_unbindefault @objname = '[{4}].[{0}].[{1}]' --try to unbind default throw error if no default
GO
ALTER TABLE [{4}].[{0}] DROP CONSTRAINT [{5}] -- drop default constraint which prevents update of datatype, Default constraint will be created in second schema comparision hit, Ugly but works :)
GO
",
Extensions._getSeparatedString(b, 0), //table name
Extensions._getSeparatedString(b, 1), //column name
datatype(b),
notnull(b), //not null
Extensions._getSeparatedString(b, 9), //schema
Extensions._getSeparatedString(a, 8) //default constarint name jelsi jest jakis
);
}
script += string.Format("alter table [{4}].[{0}] add CONSTRAINT [{1}] DEFAULT {2} FOR {3} --bind",
Extensions._getSeparatedString(b, 0), //table name
Extensions._getSeparatedString(b, 8), //default constraint name
Extensions._getSeparatedString(b, 4), //isnull(column_default, '')
Extensions._getSeparatedString(b, 1), //1- column_name
Extensions._getSeparatedString(b, 9) //schema
);
dgResultInsertRow("Target",
string.Format("{0}.{1}.{2}", SymbolToObject(option), action, "column_default"),
key,
details,
String.Format("Generated script > change {0}> from:{1} to:{2} ", temp, Extensions._getSeparatedString(a, 4), Extensions._getSeparatedString(b, 4)),
script, "");
}
//porownanie not null
x = Extensions._getSeparatedString(a, 7);
x1 = Extensions._getSeparatedString(b, 7);
if (string.CompareOrdinal(x, x1) != 0)
{
script = string.Format(@"
-- DROP INDEX [{4}].[{0}].[index name] --IF index exists you must drop first, zencomparer will recreate from source index
-- SELECT * from [{4}].[{0}] where [{1}] is null -- Helper query
-- update [{4}].[{0}] set [{1}] = Defaultvalue where is null -- Helper query
ALTER TABLE [{4}].[{0}] ALTER COLUMN [{1}] {2} {3}",
Extensions._getSeparatedString(b, 0), //table name
Extensions._getSeparatedString(b, 1), //column name
datatype(b),
// identity(b), //identity
notnull(b), //not null
Extensions._getSeparatedString(b, 9) //schema
);
dgResultInsertRow("Target",
string.Format("{0}.{1}.{2}", SymbolToObject(option), action, "not null"),
key,
details,
"Generated Script",
script, "");
}
//porownanie identity
x = Extensions._getSeparatedString(a, 9);
x1 = Extensions._getSeparatedString(b, 9);
if (string.CompareOrdinal(x, x1) != 0)
{
dgResultInsertRow("Target",
string.Format("{0}.{1}.{2}", SymbolToObject(option), action, "identity"),
key,
SymbolToObject(option),
details,
"no Action > change manual ", "");
//nie da sie dodac identity do istniejacej
}
//drop all index
// add all index
}
break;
case "FN": // Scalar function
case "TF": // Table-valued Function
case "IF": //FN ,IF,P,TR,V
case "P": //FN ,IF,P,TR,V
case "TR": //FN ,IF,P,TR,V
case "V": //FN ,IF,P,TR,V
if (action == "Missmatched" || action =="Missmatched.Comments")
{
script = replaceAlter(r["text"].ToString());
ModelScript = replaceAlter(ModelScript);
}
else
{
script = r["text"].ToString();
}
dgResultInsertRow("Target",
string.Format("{0}.{1}", SymbolToObject(option), action),
key,
details,
"Generated Script",
script,
ModelScript);
break;
case "PK":
// PK|pk_tblpriceitem|PRIMARY_KEY_CONSTRAINT|tblPriceItem|pricedetailID
/// 0- type
/// 1- name
/// 2- type description
/// 3- table name
/// 4- column name
if (action == "Missing") //brakuje kolumny
{
//FIX alter table [dbo].[] ADD CONSTRAINT PK PRIMARY KEY () on funcitons
if (!string.IsNullOrEmpty(Extensions._getSeparatedString(b, 3)))
{
script = string.Format("alter table [{3}].[{0}] ADD CONSTRAINT {1} PRIMARY KEY ({2}) ",
Extensions._getSeparatedString(b, 3), //table name
Extensions._getSeparatedString(b, 0), //name
Extensions._getSeparatedString(b, 4), //column name
Extensions._getSeparatedString(b, 5) //schema
);
dgResultInsertRow("Target",
string.Format("{0}.{1}", SymbolToObject(option), action),
key,
details,
"Generated Script Primary key ",
script, "");
}
}
break;
case "IX":
if (action == "Missmatched")
{
script = r["text"].ToString();
}
else //new
{
script = r["text"].ToString();
//script = script.Replace(", DROP_EXISTING = ON", "");
}
dgResultInsertRow("Target",
string.Format("{0}.{1}.{2}", SymbolToObject(option), r["key"].ToString(), action),
key,
details,
"Generated Script",
script,
ModelScript);
break;
default:
dgResultInsertRow("Target",
string.Format("{0}.{1}", SymbolToObject(option), action),
key,
details,
"no Action > change manual ",
"", "");
break;
}
//if (!excluded && !string.IsNullOrEmpty(script))
// result.AppendText(script + variables.scriptSeparator );
}
ht.Clear();
dgResult.Refresh();
}
string SymbolToObject(string symbol)
{
if (symbol == "FN") return "SQL_SCALAR_FUNCTION";
else if (symbol == "TF") return "Table-valued Function";
else if (symbol == "F") return "FOREIGN_KEY_CONSTRAINT";
else if (symbol == "U") return "USER_TABLE";
else if (symbol == "CO") return "USER_TABLE";
else if (symbol == "IF") return "User Function";
else if (symbol == "P") return "SQL_STORED_PROCEDURE";
else if (symbol == "TR") return "SQL_TRIGGER";
else if (symbol == "D") return "DEFAULT_CONSTRAINT";
else if (symbol == "V") return "VIEW";
else if (symbol == "IT") return "INTERNAL_TABLE";
else if (symbol == "PK") return "PRIMARY_KEY_CONSTRAINT";
else if (symbol == "S") return "SYSTEM_TABLE";
else if (symbol == "SQ") return "SERVICE_QUEUE";
else if (symbol == "UQ") return "UNIQUE_CONSTRAINT";
return symbol;
}
string showDiff(string a, string b, int charBeforeAfter)
{
string retval = "";
retval += string.Format("a-length:{0} b-length:{1}\n", a.Length, b.Length);
if (a.Length == 0 || b.Length == 0)
return retval;
CharEnumerator charEnum = a.GetEnumerator();
int counter = 0;
int astart;
int afinish;
int bfinish;
while (charEnum.MoveNext())
{
if (a[counter] != b[counter])
{
//start
if (counter - charBeforeAfter > -1)
astart = counter - charBeforeAfter;
else
astart = 0;
//end a
if (counter + (charBeforeAfter * 2) < a.Length + 1)
afinish = charBeforeAfter * 2;
else
afinish = a.Length - counter;
//end b
if (counter + (charBeforeAfter * 2) < b.Length + 1)
bfinish = charBeforeAfter * 2;
else
bfinish = b.Length - counter;
retval += string.Format("a-text:[{0}]\nb-text:[{1}]",
a.Substring(astart, afinish),
b.Substring(astart, bfinish));
return retval;
}
counter++;
}
return retval;
}
string identity(string item)
{
if (Extensions._getSeparatedString(item, 9) == "1")
return "IDENTITY(1,1)";
else
return "";
}
string notnull(string item)
{
if (Extensions._getSeparatedString(item, 7) == "YES")
return "NULL";
else
return "NOT NULL";
}
/// <summary>
/// Zadaniem jesst zwrocenie np varchar(max) decimal(18,2)
/// tblatribut|adddate|smalldatetime||(getutcdate())|0|0|YES|DF_tblAtribut_adddate|0
/// Parametry getSeparatedString
/// 0 -table name
/// 1- column_name
/// 2- isnull(cast(data_type as varchar), '')
/// 3- isnull(cast(character_maximum_length as varchar), '')
/// 4- isnull(column_default, '')
/// 5- numeric precision
/// 6- numeric_scale
/// 7- null not null
/// 8- default constraint name
/// 9- isidentity 1
/// </summary>
/// <param name="item"></param>
/// <returns>decimal(18,2) ,varchar(max)</returns>
string datatype(string item)
{
//System.Diagnostics.Debug.Write("datatype:" +
// "[0] " + Extensions._getSeparatedString(item, 0) +
// "[1] " + Extensions._getSeparatedString(item, 1) +
// "[2] " + Extensions._getSeparatedString(item, 2) +
// "[3] " + Extensions._getSeparatedString(item, 3) +
// "[4] " + Extensions._getSeparatedString(item, 4) +
// "[5] " + Extensions._getSeparatedString(item, 5) +
// "[6] " + Extensions._getSeparatedString(item, 6) +
// "[7] " + Extensions._getSeparatedString(item, 7)
// );
string retval = "";
switch (Extensions._getSeparatedString(item, 2).ToLower())
{
case "numeric":
case "decimal":
retval = String.Format("({0},{1})", Extensions._getSeparatedString(item, 5), Extensions._getSeparatedString(item, 6));
break;
case "sql_variant":
retval = "";// String.Format("({0},{1})", Extensions._getSeparatedString(item, 5), Extensions._getSeparatedString(item, 6));
break;
default:
retval = string.IsNullOrEmpty(Extensions._getSeparatedString(item, 3))
? "" :
string.Concat("(", Extensions._getSeparatedString(item, 3).Replace("-1", "Max"), ")"); //maximum length
break;
}
retval = String.Concat(Extensions._getSeparatedString(item, 2),//data_type
retval//, //data_type
//Extensions._getSeparatedString(item, 7).ToLower() == "yes" ? " NULL" : " NOT NULL"
);//not null
return correctCreateStatement(retval); //poprawka typowych bledow
}