Module: XMigra::MSSQLSpecifics

Defined in:
lib/xmigra/db_support/mssql.rb

Defined Under Namespace

Classes: StatisticsObject

Constant Summary collapse

SYSTEM_NAME =
'Microsoft SQL Server'
IDENTIFIER_SUBPATTERN =
'[a-z_@#][a-z0-9@$#_]*|"[^\[\]"]+"|\[[^\[\]]+\]'
DBNAME_PATTERN =
/^
  (?:(#{IDENTIFIER_SUBPATTERN})\.)?
  (#{IDENTIFIER_SUBPATTERN})
$/ix
STATISTICS_FILE =
'statistics-objects.yaml'
ID_COLLATION =
'Latin1_General_CS_AS'

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.init_schema(schema_config) ⇒ Object



1221
1222
1223
1224
1225
1226
1227
1228
# File 'lib/xmigra/db_support/mssql.rb', line 1221

def init_schema(schema_config)
  Console.output_section "Microsoft SQL Server Specifics" do
    if Console.yes_no("Use more verbose syntax compatible with SQL Server 2005", :no)
      schema_config.dbinfo["MSSQL 2005 compatible"] = true
      puts "Configured for SQL Server 2005 compatibility mode."
    end
  end
end

.object_type_codes(type) ⇒ Object



1209
1210
1211
1212
1213
1214
1215
# File 'lib/xmigra/db_support/mssql.rb', line 1209

def object_type_codes(type)
  case type
  when StoredProcedure then %w{P PC}
  when View then ['V']
  when Function then %w{AF FN FS FT IF TF}
  end
end

.string_literal(s) ⇒ Object



1217
1218
1219
# File 'lib/xmigra/db_support/mssql.rb', line 1217

def string_literal(s)
  "N'#{s.gsub("'","''")}'"
end

.strip_identifier_quoting(s) ⇒ Object



1200
1201
1202
1203
1204
1205
1206
1207
# File 'lib/xmigra/db_support/mssql.rb', line 1200

def strip_identifier_quoting(s)
  case
  when s.empty? then return s
  when s[0,1] == "[" && s[-1,1] == "]" then return s[1..-2]
  when s[0,1] == '"' && s[-1,1] == '"' then return s[1..-2]
  else return s
  end
end

Instance Method Details

#alter_table_columns_sql_statements(col_pairs) ⇒ Object



1192
1193
1194
1195
1196
1197
# File 'lib/xmigra/db_support/mssql.rb', line 1192

def alter_table_columns_sql_statements(col_pairs)
  col_pairs.map do |_, col|
    nullability = (col.nullable? ? "" : "NOT ") + "NULL"
    "ALTER TABLE #{name} ALTER COLUMN #{col.name} #{col.type} #{nullability};"
  end
end

#amend_script_parts(parts) ⇒ Object



123
124
125
126
127
128
129
130
131
132
133
# File 'lib/xmigra/db_support/mssql.rb', line 123

def amend_script_parts(parts)
  parts.insert_after(
    :create_and_fill_indexes_table_sql,
    :create_and_fill_statistics_table_sql
  )
  parts.insert_after(
    :remove_undesired_indexes_sql,
    :remove_undesired_statistics_sql
  )
  parts.insert_after(:create_new_indexes_sql, :create_new_statistics_sql)
end

#batch_separatorObject



1016
1017
1018
# File 'lib/xmigra/db_support/mssql.rb', line 1016

def batch_separator
  "GO\n"
end

#branch_id_literalObject



1066
1067
1068
# File 'lib/xmigra/db_support/mssql.rb', line 1066

def branch_id_literal
  @mssql_branch_id_literal ||= MSSQLSpecifics.string_literal(XMigra.secure_digest(branch_identifier))
end

#branch_upgrade_sqlObject



1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
# File 'lib/xmigra/db_support/mssql.rb', line 1081

def branch_upgrade_sql
  return unless respond_to? :branch_identifier
  
  parts = ["IF \#{upgrading_to_new_branch_test_sql}\nBEGIN\n  PRINT N'Migrating from previous schema branch:';\n  \n  DECLARE @sqlcmd NVARCHAR(MAX);\n  \n  DECLARE CmdCursor CURSOR LOCAL FOR\n  SELECT bu.[UpgradeSql]\n  FROM [xmigra].[branch_upgrade] bu\n  WHERE bu.[Next] = \#{branch_id_literal}\n  ORDER BY bu.[ApplicationOrder] ASC;\n  \n  OPEN CmdCursor;\n  \n  FETCH NEXT FROM CmdCursor INTO @sqlcmd;\n  \n  WHILE @@FETCH_STATUS = 0 BEGIN\nEXECUTE sp_executesql @sqlcmd;\n\nFETCH NEXT FROM CmdCursor INTO @sqlcmd;\n  END;\n  \n  CLOSE CmdCursor;\n  DEALLOCATE CmdCursor;\n  \n  DECLARE @applied NVARCHAR(80);\n  DECLARE @old_branch NVARCHAR(80);\n  \n  SELECT TOP(1) @applied = [CompletesMigration], @old_branch = [Current]\n  FROM [xmigra].[branch_upgrade]\n  WHERE [Next] = \#{branch_id_literal};\n  \n  -- Delete the \"applied\" record for the migration if there was one, so that\n  -- a new record with this ID can be inserted.\n  DELETE FROM [xmigra].[applied] WHERE [MigrationID] = @applied;\n  \n  -- Create a \"version bridge\" record in the \"applied\" table for the branch upgrade\n  INSERT INTO [xmigra].[applied] ([MigrationID], [VersionBridgeMark], [Description])\n  VALUES (@applied, 1, N'Branch upgrade from branch ' + @old_branch);\nEND;\n\nDELETE FROM [xmigra].[branch_upgrade];\n\n  END_OF_SQL\n  \n  if branch_upgrade.applicable? migrations\n    batch_template = <<-\"END_OF_SQL\"\nINSERT INTO [xmigra].[branch_upgrade]\n([Current], [Next], [CompletesMigration], [UpgradeSql])\nVALUES (\n  \#{branch_id_literal},\n  \#{MSSQLSpecifics.string_literal(branch_upgrade.target_branch)},\n  \#{MSSQLSpecifics.string_literal(branch_upgrade.migration_completed_id)},\n  %s\n);\n    END_OF_SQL\n    \n    each_batch(branch_upgrade.sql) do |batch|\n      # Insert the batch into the [xmigra].[branch_upgrade] table\n      parts << (batch_template % MSSQLSpecifics.string_literal(batch))\n    end\n  else\n    # Insert a placeholder that only declares the current branch of the schema\n    parts << <<-\"END_OF_SQL\"\nINSERT INTO [xmigra].[branch_upgrade] ([Current]) VALUES (\#{branch_id_literal});\n    END_OF_SQL\n  end\n  \n  return parts.join(\"\\n\")\nend\n"]

#check_chain_continuity_sqlObject



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
# File 'lib/xmigra/db_support/mssql.rb', line 475

def check_chain_continuity_sql
  "IF NOT \#{upgrading_to_new_branch_test_sql}\nBEGIN\n  PRINT N'Checking migration chain continuity:';\n  -- Get the [xmigra].[migrations] ApplicationOrder of the most recent version bridge migration\n  DECLARE @BridgePoint INT;\n  SET @BridgePoint = (\nSELECT COALESCE(MAX(m.[ApplicationOrder]), 0)\nFROM [xmigra].[applied] a\nINNER JOIN [xmigra].[migrations] m\n  ON a.[MigrationID] = m.[MigrationID]\nWHERE a.[VersionBridgeMark] <> 0\n  );\n  \n  -- Test for previously applied migrations that break the continuity of the\n  -- migration chain in this script:\n  IF EXISTS (\nSELECT *\nFROM [xmigra].[applied] a\nINNER JOIN [xmigra].[migrations] m\n  ON a.[MigrationID] = m.[MigrationID]\nINNER JOIN [xmigra].[migrations] p\n  ON m.[ApplicationOrder] - 1 = p.[ApplicationOrder]\nWHERE p.[ApplicationOrder] > @BridgePoint\nAND p.[MigrationID] NOT IN (\n  SELECT a2.[MigrationID] FROM [xmigra].[applied] a2\n)\n  )\n  BEGIN\nRAISERROR(\n  N'Previously applied migrations interrupt the continuity of the migration chain',\n  11,\n  1\n);\n  END;\nEND;\n  END_OF_SQL\nend\n"

#check_execution_environment_sqlObject



135
136
137
138
139
140
141
142
143
# File 'lib/xmigra/db_support/mssql.rb', line 135

def check_execution_environment_sql
  "PRINT N'Checking execution environment:';\nIF DB_NAME() IN ('master', 'tempdb', 'model', 'msdb')\nBEGIN\n  RAISERROR(N'Please select an appropriate target database for the update script.', 11, 1);\nEND;\n  END_OF_SQL\nend\n"

#check_existence_sql(for_existence, error_message) ⇒ Object



1020
1021
1022
1023
1024
1025
1026
1027
1028
# File 'lib/xmigra/db_support/mssql.rb', line 1020

def check_existence_sql(for_existence, error_message)
  error_message = sprintf(error_message, quoted_name)
  
  return "\nIF \#{\"NOT\" if for_existence} \#{existence_test_sql}\nRAISERROR(N'\#{error_message}', 11, 1);\n  END_OF_SQL\nend\n"

#check_preceding_migrations_sqlObject



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
# File 'lib/xmigra/db_support/mssql.rb', line 433

def check_preceding_migrations_sql
  parts = []
  
  parts << ("IF EXISTS (\n  SELECT TOP(1) * FROM [xmigra].[branch_upgrade]\n) AND NOT EXISTS (\n  SELECT TOP(1) * FROM [xmigra].[branch_upgrade]\n  WHERE \#{branch_id_literal} IN ([Current], [Next])\n)\nRAISERROR (N'Existing database is from a different (and non-upgradable) branch.', 11, 1);\n\n  END_OF_SQL\n  \n  parts << (<<-\"END_OF_SQL\")\nIF NOT \#{upgrading_to_new_branch_test_sql}\nBEGIN\n  PRINT N'Checking preceding migrations:';\n  -- Get the ApplicationOrder of the most recent version bridge migration\n  DECLARE @VersionBridge INT;\n  SET @VersionBridge = (\nSELECT COALESCE(MAX([ApplicationOrder]), 0)\nFROM [xmigra].[applied]\nWHERE [VersionBridgeMark] <> 0\n  );\n  \n  -- Check for existence of applied migrations after the latest version\n  -- bridge that are not in [xmigra].[migrations]\n  IF EXISTS (\nSELECT * FROM [xmigra].[applied] a\nWHERE a.[ApplicationOrder] > @VersionBridge\nAND a.[MigrationID] NOT IN (\n  SELECT m.[MigrationID] FROM [xmigra].[migrations] m\n)\n  )\n  RAISERROR (N'Unknown in-branch migrations have been applied.', 11, 1);\nEND;\n  END_OF_SQL\n  \n  return parts.join('')\nend\n") if production 

#create_and_fill_indexes_table_sqlObject



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
# File 'lib/xmigra/db_support/mssql.rb', line 372

def create_and_fill_indexes_table_sql
  intro = "PRINT N'Creating and filling index manipulation table:';\nIF EXISTS (\n  SELECT * FROM sys.objects\n  WHERE object_id = OBJECT_ID(N'[xmigra].[updated_indexes]')\n  AND type IN (N'U')\n)\nBEGIN\n  DROP TABLE [xmigra].[updated_indexes];\nEND;\nGO\n\nCREATE TABLE [xmigra].[updated_indexes] (\n  [IndexID]                  NVARCHAR(80) NOT NULL PRIMARY KEY\n);\nGO\n\n  END_OF_SQL\n  \n  insertion = <<-\"END_OF_SQL\"\nINSERT INTO [xmigra].[updated_indexes] ([IndexID]) VALUES\n  END_OF_SQL\n  \n  strlit = MSSQLSpecifics.method :string_literal\n  return intro + (insertion + indexes.collect do |index|\n    \"(\#{strlit[index.id]})\"\n  end.join(\",\\n\") + \";\\n\" unless indexes.empty?).to_s\nend\n"

#create_and_fill_migration_table_sqlObject



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
# File 'lib/xmigra/db_support/mssql.rb', line 325

def create_and_fill_migration_table_sql
  intro = "IF EXISTS (\n  SELECT * FROM sys.objects\n  WHERE object_id = OBJECT_ID(N'[xmigra].[migrations]')\n  AND type IN (N'U')\n)\nBEGIN\n  DROP TABLE [xmigra].[migrations];\nEND;\nGO\n\nCREATE TABLE [xmigra].[migrations] (\n  [MigrationID]            nvarchar(80) COLLATE \#{ID_COLLATION} NOT NULL,\n  [ApplicationOrder]       int NOT NULL,\n  [Description]            ntext NOT NULL,\n  [Install]                bit NOT NULL DEFAULT(0)\n);\nGO\n\n  END_OF_SQL\n  \n  mig_insert = <<-\"END_OF_SQL\"\nINSERT INTO [xmigra].[migrations] (\n  [MigrationID],\n  [ApplicationOrder],\n  [Description]\n) VALUES\n  END_OF_SQL\n  \n  if (@db_info || {}).fetch('MSSQL 2005 compatible', false).eql?(true)\n    parts = [intro]\n    (0...migrations.length).each do |i|\n      m = migrations[i]\n      description_literal = MSSQLSpecifics.string_literal(m.description.strip)\n      parts << mig_insert + \"(N'\#{m.id}', \#{i + 1}, \#{description_literal});\\n\"\n    end\n    return parts.join('')\n  else\n    return intro + mig_insert + (0...migrations.length).collect do |i|\n      m = migrations[i]\n      description_literal = MSSQLSpecifics.string_literal(m.description.strip)\n      \"(N'\#{m.id}', \#{i + 1}, \#{description_literal})\"\n    end.join(\",\\n\") + \";\\n\"\n  end\nend\n"

#create_and_fill_statistics_table_sqlObject



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
# File 'lib/xmigra/db_support/mssql.rb', line 402

def create_and_fill_statistics_table_sql
  intro = "PRINT N'Creating and filling statistics object manipulation table:';\nIF EXISTS (\n  SELECT * FROM sys.objects\n  WHERE object_id = OBJECT_ID(N'[xmigra].[updated_statistics]')\n  AND type in (N'U')\n)\nBEGIN\n  DROP TABLE [xmigra].[updated_statistics];\nEND;\nGO\n\nCREATE TABLE [xmigra].[updated_statistics] (\n  [Name] nvarchar(100) NOT NULL PRIMARY KEY,\n  [Columns] nvarchar(256) NOT NULL\n);\nGO\n\n  END_OF_SQL\n  \n  insertion = <<-\"END_OF_SQL\"\nINSERT INTO [xmigra].[updated_statistics] ([Name], [Columns]) VALUES\n  END_OF_SQL\n  \n  strlit = MSSQLSpecifics.method :string_literal\n  return intro + (insertion + stats_objs.collect do |stats_obj|\n    \"(\#{strlit[stats_obj.name]}, \#{strlit[stats_obj.columns]})\"\n  end.join(\",\\n\") + \";\\n\" unless stats_objs.empty?).to_s\nend\n"

#create_new_indexes_sqlObject



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
# File 'lib/xmigra/db_support/mssql.rb', line 749

def create_new_indexes_sql
  indexes.collect do |index|
    index_id_literal = MSSQLSpecifics.string_literal(index.id)
    index_name_literal = MSSQLSpecifics.string_literal(index.name)
    "PRINT N'Index ' + \#{index_id_literal} + ':';\nIF EXISTS(\n  SELECT * FROM [xmigra].[updated_indexes] ui\n  WHERE ui.[IndexID] = \#{index_id_literal}\n  AND ui.[IndexID] NOT IN (\nSELECT i.[IndexID] FROM [xmigra].[indexes] i\n  )\n)\nBEGIN\n  IF EXISTS (\nSELECT * FROM sys.indexes\nWHERE [name] = \#{index_name_literal}\n  )\n  BEGIN\nRAISERROR(N'An index already exists named %s', 11, 1, \#{index_name_literal});\n  END;\n  \n  PRINT N'    Creating...';\n  \#{index.definition_sql};\n  \n  IF (SELECT COUNT(*) FROM sys.indexes WHERE [name] = \#{index_name_literal}) <> 1\n  BEGIN\nRAISERROR(N'Index %s was not created by its definition.', 11, 1,\n  \#{index_name_literal});\n  END;\n\n  INSERT INTO [xmigra].[indexes] ([IndexID], [name])\n  VALUES (\#{index_id_literal}, \#{index_name_literal});\nEND\nELSE\nBEGIN\n  PRINT N'    Already exists.';\nEND;\n    END_OF_SQL\n  end.join(ddl_block_separator)\nend\n"

#create_new_statistics_sqlObject



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
# File 'lib/xmigra/db_support/mssql.rb', line 791

def create_new_statistics_sql
  stats_objs.collect do |stats_obj|
    stats_name = MSSQLSpecifics.string_literal(stats_obj.name)
    strlit = lambda {|s| MSSQLSpecifics.string_literal(s)}
    
    stats_obj.creation_sql
    "PRINT N'Statistics object \#{stats_obj.name}:';\nIF EXISTS (\n  SELECT * FROM [xmigra].[updated_statistics] us\n  WHERE us.[Name] = \#{stats_name}\n  AND us.[Columns] NOT IN (\nSELECT s.[Columns]\nFROM [xmigra].[statistics] s\nWHERE s.[Name] = us.[Name]\n  )\n)\nBEGIN\n  IF EXISTS (\nSELECT * FROM sys.stats\nWHERE [name] = \#{stats_name}\n  )\n  BEGIN\nRAISERROR(N'A statistics object named %s already exists.', 11, 1, \#{stats_name})\n  END;\n  \n  PRINT N'    Creating...';\n  \#{stats_obj.creation_sql}\n  \n  INSERT INTO [xmigra].[statistics] ([Name], [Columns])\n  VALUES (\#{stats_name}, \#{strlit[stats_obj.columns]})\nEND\nELSE\nBEGIN\n  PRINT N'    Already exists.';\nEND;\n    END_OF_SQL\n  end.join(ddl_block_separator)\nend\n"

#creation_noticeObject



1030
1031
1032
# File 'lib/xmigra/db_support/mssql.rb', line 1030

def creation_notice
  return "PRINT " + MSSQLSpecifics.string_literal("Creating #{printable_type} #{quoted_name}:") + ";"
end

#ddl_block_separatorObject



41
# File 'lib/xmigra/db_support/mssql.rb', line 41

def ddl_block_separator; "\nGO\n"; end

#each_batch(sql) ⇒ Object



999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
# File 'lib/xmigra/db_support/mssql.rb', line 999

def each_batch(sql)
  current_batch_lines = []
  sql.each_line do |line|
    if line.strip.upcase == 'GO'
      batch = current_batch_lines.join('')
      yield batch unless batch.strip.empty?
      current_batch_lines.clear
    else
      current_batch_lines << line
    end
  end
  unless current_batch_lines.empty?
    batch = current_batch_lines.join('')
    yield batch unless batch.strip.empty?
  end
end

#ensure_permissions_table_sqlObject



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
# File 'lib/xmigra/db_support/mssql.rb', line 840

def ensure_permissions_table_sql
  strlit = MSSQLSpecifics.method(:string_literal)
  "-- ------------ SET UP XMIGRA PERMISSION TRACKING OBJECTS ------------ --\n\nPRINT N'Setting up XMigra permission tracking:';\nIF NOT EXISTS (\n  SELECT * FROM sys.schemas\n  WHERE name = N'xmigra'\n)\nBEGIN\n  EXEC sp_executesql N'\nCREATE SCHEMA [xmigra] AUTHORIZATION [dbo];\n  ';\nEND;\nGO\n\nIF NOT EXISTS(\n  SELECT * FROM sys.objects\n  WHERE object_id = OBJECT_ID(N'[xmigra].[revokable_permissions]')\n  AND type IN (N'U')\n)\nBEGIN\n  CREATE TABLE [xmigra].[revokable_permissions] (\n[permissions] nvarchar(200) NOT NULL,\n[object] nvarchar(260) NOT NULL,\n[principal_id] int NOT NULL\n  ) ON [PRIMARY];\nEND;\nGO\n\nIF EXISTS(\n  SELECT * FROM sys.objects\n  WHERE object_id = OBJECT_ID(N'[xmigra].[ip_prepare_revoke]')\n  AND type IN (N'P', N'PC')\n)\nBEGIN\n  DROP PROCEDURE [xmigra].[ip_prepare_revoke];\nEND;\nGO\n\nCREATE PROCEDURE [xmigra].[ip_prepare_revoke]\n(\n  @permissions nvarchar(200),\n  @object nvarchar(260),\n  @principal sysname\n)\nAS\nBEGIN\n  INSERT INTO [xmigra].[revokable_permissions] ([permissions], [object], [principal_id])\n  VALUES (@permissions, @object, DATABASE_PRINCIPAL_ID(@principal));\nEND;\n  END_OF_SQL\nend\n"

#ensure_version_tables_sqlObject



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
# File 'lib/xmigra/db_support/mssql.rb', line 145

def ensure_version_tables_sql
  "PRINT N'Ensuring version tables:';\nIF NOT EXISTS (\n  SELECT * FROM sys.schemas\n  WHERE name = N'xmigra'\n)\nBEGIN\n  EXEC sp_executesql N'\nCREATE SCHEMA [xmigra] AUTHORIZATION [dbo];\n  ';\nEND;\nGO\n\nIF NOT EXISTS (\n  SELECT * FROM sys.objects\n  WHERE object_id = OBJECT_ID(N'[xmigra].[applied]')\n  AND type IN (N'U')\n)\nBEGIN\n  CREATE TABLE [xmigra].[applied] (\n[MigrationID]            nvarchar(80) COLLATE \#{ID_COLLATION} NOT NULL,\n[ApplicationOrder]       int IDENTITY(1,1) NOT NULL,\n[VersionBridgeMark]      bit NOT NULL,\n[Description]            nvarchar(max) NOT NULL,\n\nCONSTRAINT [PK_version] PRIMARY KEY CLUSTERED (\n  [MigrationID] ASC\n) WITH (\n  PAD_INDEX = OFF,\n  STATISTICS_NORECOMPUTE  = OFF,\n  IGNORE_DUP_KEY = OFF,\n  ALLOW_ROW_LOCKS = ON,\n  ALLOW_PAGE_LOCKS = ON\n) ON [PRIMARY]\n  ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY];\nEND;\nGO\n\nIF NOT EXISTS (\n  SELECT * FROM sys.columns\n  WHERE object_id = OBJECT_ID(N'[xmigra].[applied]')\n  AND name = N'MigrationID'\n  AND collation_name = N'\#{ID_COLLATION}'\n)\nBEGIN\n  ALTER TABLE xmigra.applied DROP CONSTRAINT PK_version;\n  ALTER TABLE xmigra.applied ALTER COLUMN [MigrationID] nvarchar(80) COLLATE Latin1_General_CS_AS NOT NULL;\n  ALTER TABLE xmigra.applied ADD CONSTRAINT PK_version PRIMARY KEY ([MigrationID] ASC) WITH (\nPAD_INDEX = OFF,\nSTATISTICS_NORECOMPUTE  = OFF,\nIGNORE_DUP_KEY = OFF,\nALLOW_ROW_LOCKS = ON,\nALLOW_PAGE_LOCKS = ON\n  ) ON [PRIMARY];\nEND;\n\nIF NOT EXISTS (\n  SELECT * FROM sys.objects\n  WHERE object_id = OBJECT_ID(N'[xmigra].[previous_states]')\n  AND type IN (N'U')\n)\nBEGIN\n  CREATE TABLE [xmigra].[previous_states] (\n[Changed]                   datetime NOT NULL,\n[MigrationApplicationOrder] int NOT NULL,\n[FromMigrationID]           nvarchar(80) COLLATE \#{ID_COLLATION},\n[ToRangeStartMigrationID]   nvarchar(80) COLLATE \#{ID_COLLATION} NOT NULL,\n[ToRangeEndMigrationID]     nvarchar(80) COLLATE \#{ID_COLLATION} NOT NULL,\n\nCONSTRAINT [PK_previous_states] PRIMARY KEY CLUSTERED (\n  [Changed] ASC,\n  [MigrationApplicationOrder] ASC\n)\n  );\nEND;\nGO\n\nIF NOT EXISTS (\n  SELECT * FROM sys.objects\n  WHERE object_id = OBJECT_ID(N'[xmigra].[DF_version_VersionBridgeMark]')\n  AND type IN (N'D')\n)\nBEGIN\n  ALTER TABLE [xmigra].[applied] ADD CONSTRAINT [DF_version_VersionBridgeMark]\nDEFAULT (0) FOR [VersionBridgeMark];\nEND;\nGO\n\nIF NOT EXISTS (\n  SELECT * FROM sys.objects\n  WHERE object_id = OBJECT_ID(N'[xmigra].[access_objects]')\n  AND type IN (N'U')\n)\nBEGIN\n  CREATE TABLE [xmigra].[access_objects] (\n[type] nvarchar(40) NOT NULL,\n[name] nvarchar(256) NOT NULL,\n[order] int identity(1,1) NOT NULL,\n\nCONSTRAINT [PK_access_objects] PRIMARY KEY CLUSTERED (\n  [name] ASC\n) WITH (\n  PAD_INDEX = OFF,\n  STATISTICS_NORECOMPUTE  = OFF,\n  IGNORE_DUP_KEY = OFF,\n  ALLOW_ROW_LOCKS = ON,\n  ALLOW_PAGE_LOCKS = ON\n) ON [PRIMARY]\n  ) ON [PRIMARY];\nEND;\nGO\n\nIF NOT EXISTS (\n  SELECT * FROM sys.objects\n  WHERE object_id = OBJECT_ID(N'[xmigra].[indexes]')\n  AND type in (N'U')\n)\nBEGIN\n  CREATE TABLE [xmigra].[indexes] (\n[IndexID] nvarchar(80) NOT NULL PRIMARY KEY,\n[name] nvarchar(256) NOT NULL\n  ) ON [PRIMARY];\nEND;\n\nIF NOT EXISTS (\n  SELECT * FROM sys.objects\n  WHERE object_id = OBJECT_ID(N'[xmigra].[statistics]')\n  AND type in (N'U')\n)\nBEGIN\n  CREATE TABLE [xmigra].[statistics] (\n[Name] nvarchar(100) NOT NULL PRIMARY KEY,\n[Columns] nvarchar(256) NOT NULL\n  ) ON [PRIMARY];\nEND;\n\nIF NOT EXISTS (\n  SELECT * FROM sys.objects\n  WHERE object_id = OBJECT_ID(N'[xmigra].[branch_upgrade]')\n  AND type in (N'U')\n)\nBEGIN\n  CREATE TABLE [xmigra].[branch_upgrade] (\n[ApplicationOrder] int identity(1,1) NOT NULL,\n[Current] nvarchar(80) COLLATE \#{ID_COLLATION} NOT NULL PRIMARY KEY,\n[Next] nvarchar(80) COLLATE \#{ID_COLLATION} NULL,\n[UpgradeSql] nvarchar(max) NULL,\n[CompletesMigration] nvarchar(80) COLLATE \#{ID_COLLATION} NULL\n  ) ON [PRIMARY];\nEND;\nGO\nALTER TABLE [xmigra].[branch_upgrade] ALTER COLUMN [CompletesMigration] nvarchar(80) COLLATE \#{ID_COLLATION} NULL;\n\nIF EXISTS (\n  SELECT * FROM sys.objects\n  WHERE object_id = OBJECT_ID(N'[xmigra].[last_applied_migrations]')\n  AND type IN (N'V')\n)\nBEGIN\n  DROP VIEW [xmigra].[last_applied_migrations];\nEND;\nGO\n\nCREATE VIEW [xmigra].[last_applied_migrations] AS\nSELECT\n  ROW_NUMBER() OVER (ORDER BY a.[ApplicationOrder] DESC) AS [RevertOrder],\n  a.[Description]\nFROM\n  [xmigra].[applied] a\nWHERE\n  a.[ApplicationOrder] > COALESCE((\nSELECT TOP (1) ps.[MigrationApplicationOrder]\nFROM [xmigra].[previous_states] ps\nJOIN [xmigra].[applied] a2 ON ps.[ToRangeStartMigrationID] = a2.[MigrationID]\nORDER BY ps.[Changed] DESC\n  ), 0);\n  END_OF_SQL\nend\n"

#existence_test_sqlObject



1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
# File 'lib/xmigra/db_support/mssql.rb', line 1054

def existence_test_sql
  object_type_list = object_type_codes.collect {|t| "N'#{t}'"}.join(', ')
  
  return "EXISTS (\n  SELECT * FROM sys.objects\n  WHERE object_id = OBJECT_ID(N'\#{quoted_name}')\n  AND type IN (\#{object_type_list})\n)\n  END_OF_SQL\nend\n"

#filename_metavariableObject



42
# File 'lib/xmigra/db_support/mssql.rb', line 42

def filename_metavariable; "[{filename}]"; end

#function_definition_template_sqlObject



1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
# File 'lib/xmigra/db_support/mssql.rb', line 1180

def function_definition_template_sql
  "CREATE FUNCTION [{filename}] (\n  <<<parameters>>>\n) RETURNS <<<return-type>>>\nAS BEGIN\n  <<<statements>>>\n  RETURN <<<return-value-expression>>>;\nEND\n"
end

#grant_permissions_sql(permissions, object, principal) ⇒ Object



945
946
947
948
949
950
951
952
953
954
# File 'lib/xmigra/db_support/mssql.rb', line 945

def grant_permissions_sql(permissions, object, principal)
  strlit = MSSQLSpecifics.method(:string_literal)
  permissions_string = permissions.to_a.join(', ')
  
  "PRINT N'Granting \#{permissions_string} on \#{object} to \#{principal}:';\nGRANT \#{permissions_string} ON \#{object} TO \#{principal};\nEXEC [xmigra].[ip_prepare_revoke] \#{strlit[permissions_string]}, \#{strlit[object]}, \#{strlit[principal]};\n  END_OF_SQL\nend\n"

#granting_permissions_comment_sqlObject



937
938
939
940
941
942
943
# File 'lib/xmigra/db_support/mssql.rb', line 937

def granting_permissions_comment_sql
  "  \n-- ---------------------- GRANTING PERMISSIONS ----------------------- --\n\n  END_OF_SQL\nend\n"

#in_ddl_transaction(options = {}) ⇒ Object



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
# File 'lib/xmigra/db_support/mssql.rb', line 60

def in_ddl_transaction(options={})
  parts = []
  parts << "SET ANSI_NULLS ON\nGO\n\nSET QUOTED_IDENTIFIER ON\nGO\n\nSET ANSI_PADDING ON\nGO\n\nSET NOCOUNT ON\nGO\n-------------------- ERROR REFERENCE LINE --------------------\nDECLARE @BATCH_START_OFFSET INTEGER; SET @BATCH_START_OFFSET = 0;\nBEGIN TRY\n  BEGIN TRAN;\n  END_OF_SQL\n  \n  offset_lines = 5\n  each_batch(yield) do |batch|\n    batch_literal = MSSQLSpecifics.string_literal(\"\\n\" + batch)\n    parts << \"SET @BATCH_START_OFFSET = \#{offset_lines}; EXEC sp_executesql @statement = \#{batch_literal}; SET @BATCH_START_OFFSET = 0;\"\n    offset_lines += parts[-1].count(\"\\n\") + 1\n  end\n  \n  if options[:dry_run]\n    parts << \"  PRINT N'Dry-run successful.  Rolling back changes.'; ROLLBACK TRAN;\"\n  else\n    parts << \"  COMMIT TRAN;\"\n  end\n  parts << <<-\"END_OF_SQL\"\nEND TRY\nBEGIN CATCH\n  ROLLBACK TRAN;\n  \n  DECLARE @ErrorMessage NVARCHAR(4000);\n  DECLARE @ErrorSeverity INT;\n  DECLARE @ErrorState INT;\n  \n  PRINT N'Update failed: ' + ERROR_MESSAGE();\n  PRINT N'    State: ' + CAST(ERROR_STATE() AS NVARCHAR);\n  PRINT N'    Line: ' + CAST(@BATCH_START_OFFSET + ERROR_LINE() - 1 AS NVARCHAR) + N' after ERROR REFERENCE LINE'\n\n  SELECT \n  @ErrorMessage = N'Update failed: ' + ERROR_MESSAGE(),\n  @ErrorSeverity = ERROR_SEVERITY(),\n  @ErrorState = ERROR_STATE();\n\n  -- Use RAISERROR inside the CATCH block to return error\n  -- information about the original error that caused\n  -- execution to jump to the CATCH block.\n  RAISERROR (@ErrorMessage, -- Message text.\n         @ErrorSeverity, -- Severity.\n         @ErrorState -- State.\n         );\nEND CATCH;\n  END_OF_SQL\n  \n  return parts.join(\"\\n\")\nend\n"

#index_template_sqlObject



1156
1157
1158
1159
1160
1161
# File 'lib/xmigra/db_support/mssql.rb', line 1156

def index_template_sql
  "CREATE INDEX [{filename}]\nON <<<table>>> (<<<columns>>>);\n"
end

#insert_access_creation_record_sqlObject



956
957
958
959
960
961
962
963
# File 'lib/xmigra/db_support/mssql.rb', line 956

def insert_access_creation_record_sql
  name_literal = MSSQLSpecifics.string_literal(quoted_name)
  
  "INSERT INTO [xmigra].[access_objects] ([type], [name])\nVALUES (N'\#{self.class::OBJECT_TYPE}', \#{name_literal});\n  END_OF_SQL\nend\n"

#migration_application_sqlObject

Call on an extended Migration object to get the SQL to execute.



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
# File 'lib/xmigra/db_support/mssql.rb', line 966

def migration_application_sql
  id_literal = MSSQLSpecifics.string_literal(id)
  template = "IF EXISTS (\n  SELECT * FROM [xmigra].[migrations]\n  WHERE [MigrationID] = \#{id_literal}\n  AND [Install] <> 0\n)\nBEGIN\n  PRINT \#{MSSQLSpecifics.string_literal('Applying \"' + File.basename(file_path) + '\":')};\n  \n%s\n\n  INSERT INTO [xmigra].[applied] ([MigrationID], [Description])\n  VALUES (\#{id_literal}, \#{MSSQLSpecifics.string_literal(description)});\nEND;\n  END_OF_SQL\n  \n  parts = []\n  \n  each_batch(sql) do |batch|\n    parts << batch\n  end\n  \n  return (template % parts.collect do |batch|\n    \"EXEC sp_executesql @statement = \" + MSSQLSpecifics.string_literal(batch) + \";\"\n  end.join(\"\\n\"))\nend\n"

#name_partsObject



1034
1035
1036
1037
1038
1039
1040
1041
1042
# File 'lib/xmigra/db_support/mssql.rb', line 1034

def name_parts
  if m = DBNAME_PATTERN.match(name)
    [m[1], m[2]].compact.collect do |p|
      MSSQLSpecifics.strip_identifier_quoting(p)
    end
  else
    raise XMigra::Error, "Invalid database object name"
  end
end

#object_type_codesObject



1050
1051
1052
# File 'lib/xmigra/db_support/mssql.rb', line 1050

def object_type_codes
  MSSQLSpecifics.object_type_codes(self)
end

#procedure_definition_template_sqlObject



1170
1171
1172
1173
1174
1175
1176
1177
1178
# File 'lib/xmigra/db_support/mssql.rb', line 1170

def procedure_definition_template_sql
  "CREATE PROCEDURE [{filename}]\n  <<<parameters>>>\nAS BEGIN\n  <<<statements>>>\nEND\n"
end

#production_config_check_sqlObject



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
# File 'lib/xmigra/db_support/mssql.rb', line 585

def production_config_check_sql
  unless production
    id_literal = MSSQLSpecifics.string_literal(@migrations[0].id)
    "PRINT N'Checking for production status:';\nIF EXISTS (\n  SELECT * FROM [xmigra].[migrations]\n  WHERE [MigrationID] = \#{id_literal}\n  AND [Install] <> 0\n)\nBEGIN\n  CREATE TABLE [xmigra].[development] (\n[info] nvarchar(200) NOT NULL PRIMARY KEY\n  );\nEND;\nGO\n\nIF NOT EXISTS (\n  SELECT * FROM [sys].[objects]\n  WHERE object_id = OBJECT_ID(N'[xmigra].[development]')\n  AND type = N'U'\n)\nRAISERROR(N'Development script cannot be applied to a production database.', 11, 1);\n    END_OF_SQL\n  end\nend\n"

#quoted_nameObject



1044
1045
1046
1047
1048
# File 'lib/xmigra/db_support/mssql.rb', line 1044

def quoted_name
  name_parts.collect do |p|
    "[]".insert(1, p)
  end.join('.')
end

#remove_access_artifacts_sqlObject



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
# File 'lib/xmigra/db_support/mssql.rb', line 612

def remove_access_artifacts_sql
  # Iterate the [xmigra].[access_objects] table and drop all access
  # objects previously created by xmigra
  return "PRINT N'Removing data access artifacts:';\nDECLARE @sqlcmd NVARCHAR(1000); -- Built SQL command\nDECLARE @obj_name NVARCHAR(256); -- Name of object to drop\nDECLARE @obj_type NVARCHAR(40); -- Type of object to drop\n\nDECLARE AccObjs_cursor CURSOR LOCAL FOR\nSELECT [name], [type]\nFROM [xmigra].[access_objects]\nORDER BY [order] DESC;\n\nOPEN AccObjs_cursor;\n\nFETCH NEXT FROM AccObjs_cursor INTO @obj_name, @obj_type;\n\nWHILE @@FETCH_STATUS = 0 BEGIN\n  SET @sqlcmd = N'DROP ' + @obj_type + N' ' + @obj_name + N';';\n  EXEC sp_executesql @sqlcmd;\n  \n  FETCH NEXT FROM AccObjs_cursor INTO @obj_name, @obj_type;\nEND;\n\nCLOSE AccObjs_cursor;\nDEALLOCATE AccObjs_cursor;\n\nDELETE FROM [xmigra].[access_objects];\n\n"
end

#remove_undesired_indexes_sqlObject



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
# File 'lib/xmigra/db_support/mssql.rb', line 645

def remove_undesired_indexes_sql
  "PRINT N'Removing undesired indexes:';\n-- Iterate over indexes in [xmigra].[indexes] that don't have an entry in\n-- [xmigra].[updated_indexes].\nDECLARE @sqlcmd NVARCHAR(1000); -- Built SQL command\nDECLARE @index_name NVARCHAR(256); -- Name of index to drop\nDECLARE @table_name SYSNAME; -- Name of table owning index\nDECLARE @match_count INT; -- Number of matching index names\n\nDECLARE Index_cursor CURSOR LOCAL FOR\nSELECT \n  xi.[name], \n  MAX(QUOTENAME(OBJECT_SCHEMA_NAME(si.object_id)) + N'.' + QUOTENAME(OBJECT_NAME(si.object_id))), \n  COUNT(*)\nFROM [xmigra].[indexes] xi\nINNER JOIN sys.indexes si ON si.[name] = xi.[name]\nWHERE xi.[IndexID] NOT IN (\n  SELECT [IndexID]\n  FROM [xmigra].[updated_indexes]\n)\nGROUP BY xi.[name];\n\nOPEN Index_cursor;\n\nFETCH NEXT FROM Index_cursor INTO @index_name, @table_name, @match_count;\n\nWHILE @@FETCH_STATUS = 0 BEGIN\n  IF @match_count > 1\n  BEGIN\nRAISERROR(N'Multiple indexes are named %s', 11, 1, @index_name);\n  END;\n  \n  SET @sqlcmd = N'DROP INDEX ' + @index_name + N' ON ' + @table_name + N';';\n  EXEC sp_executesql @sqlcmd;\n  PRINT N'    Removed ' + @index_name + N'.';\n  \n  FETCH NEXT FROM Index_cursor INTO @index_name, @table_name, @match_count;\nEND;\n\nCLOSE Index_cursor;\nDEALLOCATE Index_cursor;\n\nDELETE FROM [xmigra].[indexes]\nWHERE [IndexID] NOT IN (\n  SELECT ui.[IndexID]\n  FROM [xmigra].[updated_indexes] ui\n);\n  END_OF_SQL\nend\n"

#remove_undesired_statistics_sqlObject



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
# File 'lib/xmigra/db_support/mssql.rb', line 696

def remove_undesired_statistics_sql
  "PRINT N'Removing undesired statistics objects:';\n-- Iterate over statistics in [xmigra].[statistics] that don't have an entry in\n-- [xmigra].[updated_statistics].\nDECLARE @sqlcmd NVARCHAR(1000); -- Built SQL command\nDECLARE @statsobj_name NVARCHAR(256); -- Name of statistics object to drop\nDECLARE @table_name SYSNAME; -- Name of table owning the statistics object\nDECLARE @match_count INT; -- Number of matching statistics object names\n\nDECLARE Stats_cursor CURSOR LOCAL FOR\nSELECT \n  QUOTENAME(xs.[Name]), \n  MAX(QUOTENAME(OBJECT_SCHEMA_NAME(ss.object_id)) + N'.' + QUOTENAME(OBJECT_NAME(ss.object_id))), \n  COUNT(ss.object_id)\nFROM [xmigra].[statistics] xs\nINNER JOIN sys.stats ss ON ss.[name] = xs.[Name]\nWHERE xs.[Columns] NOT IN (\n  SELECT us.[Columns]\n  FROM [xmigra].[updated_statistics] us\n  WHERE us.[Name] = xs.[Name]\n)\nGROUP BY xs.[Name];\n\nOPEN Stats_cursor;\n\nFETCH NEXT FROM Stats_cursor INTO @statsobj_name, @table_name, @match_count;\n\nWHILE @@FETCH_STATUS = 0 BEGIN\n  IF @match_count > 1\n  BEGIN\nRAISERROR(N'Multiple indexes are named %s', 11, 1, @statsobj_name);\n  END;\n  \n  SET @sqlcmd = N'DROP STATISTICS ' + @table_name + N'.' + @statsobj_name + N';';\n  EXEC sp_executesql @sqlcmd;\n  PRINT N'    Removed statistics object ' + @statsobj_name + N'.'\n  \n  FETCH NEXT FROM Stats_cursor INTO @statsobj_name, @table_name, @match_count;\nEND;\n\nCLOSE Stats_cursor;\nDEALLOCATE Stats_cursor;\n\nDELETE FROM [xmigra].[statistics]\nWHERE [Columns] NOT IN (\n  SELECT us.[Columns]\n  FROM [xmigra].[updated_statistics] us\n  WHERE us.[Name] = [Name]\n);\n  END_OF_SQL\nend\n"

#reversion_tracking_sqlObject



995
996
997
# File 'lib/xmigra/db_support/mssql.rb', line 995

def reversion_tracking_sql
  "DELETE FROM [xmigra].[applied] WHERE [MigrationID] = '#{id}';\n"
end

#revoke_previous_permissions_sqlObject



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
# File 'lib/xmigra/db_support/mssql.rb', line 895

def revoke_previous_permissions_sql
  "\n-- ------------- REVOKING PREVIOUSLY GRANTED PERMISSIONS ------------- --\n\nPRINT N'Revoking previously granted permissions:';\n-- Iterate over permissions listed in [xmigra].[revokable_permissions]\nDECLARE @sqlcmd NVARCHAR(1000); -- Built SQL command\nDECLARE @permissions NVARCHAR(200); \nDECLARE @object NVARCHAR(260); \nDECLARE @principal NVARCHAR(150);\n\nDECLARE Permission_cursor CURSOR LOCAL FOR\nSELECT\n  xp.[permissions],\n  xp.[object],\n  QUOTENAME(sdp.name)\nFROM [xmigra].[revokable_permissions] xp\nINNER JOIN sys.database_principals sdp ON xp.principal_id = sdp.principal_id;\n\nOPEN Permission_cursor;\n\nFETCH NEXT FROM Permission_cursor INTO @permissions, @object, @principal;\n\nWHILE @@FETCH_STATUS = 0 BEGIN\n  SET @sqlcmd = N'REVOKE ' + @permissions + N' ON ' + @object + ' FROM ' + @principal + N';';\n  BEGIN TRY\nEXEC sp_executesql @sqlcmd;\n  END TRY\n  BEGIN CATCH\n  END CATCH\n  \n  FETCH NEXT FROM Permission_cursor INTO @permissions, @object, @principal;\nEND;\n\nCLOSE Permission_cursor;\nDEALLOCATE Permission_cursor;\n\nDELETE FROM [xmigra].[revokable_permissions];\n  END_OF_SQL\nend\n"

#select_for_install_sqlObject



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
# File 'lib/xmigra/db_support/mssql.rb', line 515

def select_for_install_sql
  "PRINT N'Selecting migrations to apply:';\nDECLARE @BridgePoint INT;\nIF \#{upgrading_to_new_branch_test_sql}\nBEGIN\n  -- Get the [xmigra].[migrations] ApplicationOrder of the record corresponding to the branch transition\n  SET @BridgePoint = (\nSELECT MAX(m.[ApplicationOrder])\nFROM [xmigra].[migrations] m\nINNER JOIN [xmigra].[branch_upgrade] bu\n  ON m.[MigrationID] = bu.[CompletesMigration]\n  );\n  \n  UPDATE [xmigra].[migrations]\n  SET [Install] = 1\n  WHERE [ApplicationOrder] > @BridgePoint;\nEND\nELSE BEGIN\n  -- Get the [xmigra].[migrations] ApplicationOrder of the most recent version bridge migration\n  SET @BridgePoint = (\nSELECT COALESCE(MAX(m.[ApplicationOrder]), 0)\nFROM [xmigra].[applied] a\nINNER JOIN [xmigra].[migrations] m\n  ON a.[MigrationID] = m.[MigrationID]\nWHERE a.[VersionBridgeMark] <> 0\n  );\n  \n  UPDATE [xmigra].[migrations]\n  SET [Install] = 1\n  WHERE [MigrationID] NOT IN (\nSELECT a.[MigrationID] FROM [xmigra].[applied] a\n  )\n  AND [ApplicationOrder] > @BridgePoint;\nEND;\n\nINSERT INTO [xmigra].[previous_states] (\n  [Changed],\n  [MigrationApplicationOrder],\n  [FromMigrationID],\n  [ToRangeStartMigrationID],\n  [ToRangeEndMigrationID]\n)\nSELECT TOP (1)\n  CURRENT_TIMESTAMP,\n  -- Application order of last installed migration --\n  COALESCE(\n( \n  SELECT TOP(1) [ApplicationOrder] FROM [xmigra].[applied]\n  ORDER BY [ApplicationOrder] DESC\n),\n0\n  ),\n  ( -- Last installed migration --\nSELECT TOP (1) [MigrationID]\nFROM [xmigra].[applied]\nORDER BY [ApplicationOrder] DESC\n  ),\n  m.[MigrationID],\n  ( -- Last migration to install --\nSELECT TOP(1) [MigrationID] FROM [xmigra].[migrations]\nWHERE [Install] <> 0\nORDER BY [ApplicationOrder] DESC\n  )\nFROM [xmigra].[migrations] m\nWHERE m.[Install] <> 0\nORDER BY m.[ApplicationOrder] ASC;\n  END_OF_SQL\nend\n"

#stats_objsObject



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/xmigra/db_support/mssql.rb', line 44

def stats_objs
  return @stats_objs if @stats_objs
  
  begin
    stats_data = YAML::load_file(path.join(MSSQLSpecifics::STATISTICS_FILE))
  rescue Errno::ENOENT
    return @stats_objs = [].freeze
  end
  
  @stats_objs = stats_data.collect {|item| StatisticsObject.new(*item)}
  @stats_objs.each {|o| o.freeze}
  @stats_objs.freeze
  
  return @stats_objs
end

#upgrade_cleanup_sqlObject



831
832
833
834
835
836
837
838
# File 'lib/xmigra/db_support/mssql.rb', line 831

def upgrade_cleanup_sql
  "PRINT N'Cleaning up from the upgrade:';\nDROP TABLE [xmigra].[migrations];\nDROP TABLE [xmigra].[updated_indexes];\nDROP TABLE [xmigra].[updated_statistics];\n  END_OF_SQL\nend\n"

#upgrading_to_new_branch_test_sqlObject



1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
# File 'lib/xmigra/db_support/mssql.rb', line 1070

def upgrading_to_new_branch_test_sql
  return "(0 = 1)" unless respond_to? :branch_identifier
  
  ("(EXISTS (\n  SELECT TOP(1) * FROM [xmigra].[branch_upgrade]\n  WHERE [Next] = \#{branch_id_literal}\n))\n  END_OF_SQL\nend\n").chomp

#view_definition_template_sqlObject



1163
1164
1165
1166
1167
1168
# File 'lib/xmigra/db_support/mssql.rb', line 1163

def view_definition_template_sql
  "CREATE VIEW [{filename}]\nAS SELECT <<<query>>>;\n"
end