Consolidated ASP Classic MVC framework from best components
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

437 lignes
18KB

  1. <%
  2. '=======================================================================================================================
  3. ' MIGRATION SYSTEM
  4. '=======================================================================================================================
  5. ' Provides database migration capabilities for version-controlled schema changes.
  6. '
  7. ' Features:
  8. ' - Sequential migration versioning (timestamp-based)
  9. ' - Up/Down migration support
  10. ' - Migration tracking in schema_migrations table
  11. ' - Transaction support for atomic migrations
  12. ' - Migration status checking
  13. '
  14. ' Usage:
  15. ' Set migrator = Migrator()
  16. ' migrator.ApplyMigration "20260109120000_create_users_table.asp"
  17. ' migrator.RollbackMigration "20260109120000_create_users_table.asp"
  18. ' pending = migrator.GetPendingMigrations()
  19. ' applied = migrator.GetAppliedMigrations()
  20. '
  21. Class Migrator_Class
  22. Private m_db
  23. Private m_migrations_path
  24. Private m_schema_table
  25. '-------------------------------------------------------------------------------------------------------------------
  26. Private Sub Class_Initialize()
  27. Set m_db = DAL()
  28. m_schema_table = "schema_migrations"
  29. m_migrations_path = Server.MapPath("../db/migrations/")
  30. End Sub
  31. ' Override the migrations folder (needed when run from the CLI, where relative MapPath is not meaningful)
  32. Public Property Let MigrationsPath(v)
  33. m_migrations_path = v
  34. End Property
  35. '-------------------------------------------------------------------------------------------------------------------
  36. ' Ensure the schema_migrations table exists
  37. '-------------------------------------------------------------------------------------------------------------------
  38. Public Sub EnsureSchemaMigrationsTable()
  39. On Error Resume Next
  40. ' Try to query the table - if it doesn't exist, create it
  41. Dim rs
  42. Set rs = m_db.Query("SELECT version FROM " & m_schema_table & " WHERE 1=0", empty)
  43. If Err.Number <> 0 Then
  44. ' Table doesn't exist, create it
  45. Err.Clear
  46. On Error GoTo 0
  47. Dim createSQL
  48. createSQL = "CREATE TABLE " & m_schema_table & " (" & _
  49. "version VARCHAR(14) PRIMARY KEY, " & _
  50. "applied_at DATETIME NOT NULL)"
  51. m_db.Execute createSQL, empty
  52. Else
  53. If Not rs Is Nothing Then
  54. rs.Close
  55. Set rs = Nothing
  56. End If
  57. End If
  58. On Error GoTo 0
  59. End Sub
  60. '-------------------------------------------------------------------------------------------------------------------
  61. ' Get all applied migration versions
  62. '-------------------------------------------------------------------------------------------------------------------
  63. Public Function GetAppliedMigrations()
  64. EnsureSchemaMigrationsTable
  65. Dim rs, versions, version
  66. Set versions = Server.CreateObject("Scripting.Dictionary")
  67. Set rs = m_db.Query("SELECT version FROM " & m_schema_table & " ORDER BY version", empty)
  68. Do While Not rs.EOF
  69. version = Trim(rs("version"))
  70. versions.Add version, True
  71. rs.MoveNext
  72. Loop
  73. rs.Close
  74. Set rs = Nothing
  75. Set GetAppliedMigrations = versions
  76. End Function
  77. '-------------------------------------------------------------------------------------------------------------------
  78. ' Get all available migration files
  79. '-------------------------------------------------------------------------------------------------------------------
  80. Public Function GetAvailableMigrations()
  81. Dim fso, folder, files, file
  82. Set fso = Server.CreateObject("Scripting.FileSystemObject")
  83. If Not fso.FolderExists(m_migrations_path) Then
  84. Set GetAvailableMigrations = Server.CreateObject("Scripting.Dictionary")
  85. Exit Function
  86. End If
  87. Set folder = fso.GetFolder(m_migrations_path)
  88. Set files = folder.Files
  89. Dim migrations
  90. Set migrations = Server.CreateObject("Scripting.Dictionary")
  91. For Each file In files
  92. If LCase(fso.GetExtensionName(file.Name)) = "asp" Then
  93. Dim version
  94. version = GetVersionFromFilename(file.Name)
  95. If version <> "" Then
  96. migrations.Add version, file.Name
  97. End If
  98. End If
  99. Next
  100. Set GetAvailableMigrations = migrations
  101. End Function
  102. '-------------------------------------------------------------------------------------------------------------------
  103. ' Get pending migrations (available but not applied)
  104. '-------------------------------------------------------------------------------------------------------------------
  105. Public Function GetPendingMigrations()
  106. Dim applied, available, pending, version
  107. Set applied = GetAppliedMigrations()
  108. Set available = GetAvailableMigrations()
  109. Set pending = Server.CreateObject("Scripting.Dictionary")
  110. For Each version In available.Keys
  111. If Not applied.Exists(version) Then
  112. pending.Add version, available(version)
  113. End If
  114. Next
  115. Set GetPendingMigrations = pending
  116. End Function
  117. '-------------------------------------------------------------------------------------------------------------------
  118. ' Extract version from migration filename
  119. ' Expected format: YYYYMMDDHHMMSS_description.asp
  120. '-------------------------------------------------------------------------------------------------------------------
  121. Private Function GetVersionFromFilename(filename)
  122. Dim parts
  123. parts = Split(filename, "_")
  124. If UBound(parts) >= 0 Then
  125. Dim version
  126. version = parts(0)
  127. ' Validate it's a 14-digit timestamp
  128. If Len(version) = 14 And IsNumeric(version) Then
  129. GetVersionFromFilename = version
  130. Exit Function
  131. End If
  132. End If
  133. GetVersionFromFilename = ""
  134. End Function
  135. '-------------------------------------------------------------------------------------------------------------------
  136. ' Apply a migration (run the Up method)
  137. '-------------------------------------------------------------------------------------------------------------------
  138. Public Sub ApplyMigration(filename)
  139. Dim version, msg
  140. version = GetVersionFromFilename(filename)
  141. If version = "" Then
  142. Err.Raise vbObjectError + 1, "Migrator", "Invalid migration filename format: " & filename
  143. End If
  144. If GetAppliedMigrations().Exists(version) Then
  145. Response.Write "Migration " & version & " already applied. Skipping." & vbCrLf
  146. Exit Sub
  147. End If
  148. Response.Write "Applying migration: " & filename & "..." & vbCrLf
  149. m_db.BeginTransaction
  150. msg = RunMigrationFile(filename, "Up")
  151. If msg = "" Then
  152. msg = TrySql("INSERT INTO " & m_schema_table & " (version, applied_at) VALUES (?, ?)", Array(version, NowIso()))
  153. If msg <> "" Then msg = "Failed to record migration: " & msg
  154. End If
  155. If msg <> "" Then
  156. m_db.RollbackTransaction
  157. Err.Raise vbObjectError + 2, "Migrator", "Migration " & version & " FAILED and was rolled back: " & msg
  158. End If
  159. m_db.CommitTransaction
  160. Response.Write "Migration " & version & " applied successfully." & vbCrLf
  161. End Sub
  162. '-------------------------------------------------------------------------------------------------------------------
  163. ' Rollback a migration (run the Down method)
  164. '-------------------------------------------------------------------------------------------------------------------
  165. Public Sub RollbackMigration(filename)
  166. Dim version, msg
  167. version = GetVersionFromFilename(filename)
  168. If version = "" Then
  169. Err.Raise vbObjectError + 1, "Migrator", "Invalid migration filename format: " & filename
  170. End If
  171. If Not GetAppliedMigrations().Exists(version) Then
  172. Response.Write "Migration " & version & " is not applied. Skipping." & vbCrLf
  173. Exit Sub
  174. End If
  175. Response.Write "Rolling back migration: " & filename & "..." & vbCrLf
  176. m_db.BeginTransaction
  177. msg = RunMigrationFile(filename, "Down")
  178. If msg = "" Then
  179. msg = TrySql("DELETE FROM " & m_schema_table & " WHERE version = ?", version)
  180. If msg <> "" Then msg = "Failed to remove migration record: " & msg
  181. End If
  182. If msg <> "" Then
  183. m_db.RollbackTransaction
  184. Err.Raise vbObjectError + 4, "Migrator", "Rollback of " & version & " FAILED: " & msg
  185. End If
  186. m_db.CommitTransaction
  187. Response.Write "Migration " & version & " rolled back successfully." & vbCrLf
  188. End Sub
  189. '-------------------------------------------------------------------------------------------------------------------
  190. ' Execute a migration file's Up or Down method
  191. '-------------------------------------------------------------------------------------------------------------------
  192. Private Function NowIso()
  193. Dim n : n = Now()
  194. NowIso = Year(n) & "-" & Right("0" & Month(n), 2) & "-" & Right("0" & Day(n), 2) & " " & _
  195. Right("0" & Hour(n), 2) & ":" & Right("0" & Minute(n), 2) & ":" & Right("0" & Second(n), 2)
  196. End Function
  197. Private Function TrySql(sql, params)
  198. ' Runs one statement; returns "" on success or a readable error message (never swallows the error)
  199. On Error Resume Next
  200. m_db.Execute sql, params
  201. If Err.Number <> 0 Then
  202. TrySql = "[" & Err.Number & "] " & Err.Description
  203. Err.Clear
  204. Else
  205. TrySql = ""
  206. End If
  207. End Function
  208. ' Loads and runs a migration file's Up/Down. Returns "" on success or a readable error message.
  209. Private Function RunMigrationFile(filename, direction)
  210. On Error Resume Next
  211. Dim migrationPath, fso, ts, code, migration, step
  212. migrationPath = m_migrations_path & "/" & filename
  213. migrationPath = Replace(migrationPath, "//", "/")
  214. step = "locate file " & migrationPath
  215. Set fso = Server.CreateObject("Scripting.FileSystemObject")
  216. If Not fso.FileExists(migrationPath) Then
  217. RunMigrationFile = "Migration file not found: " & migrationPath
  218. Exit Function
  219. End If
  220. step = "read file"
  221. Set ts = fso.OpenTextFile(migrationPath, 1)
  222. code = ts.ReadAll
  223. ts.Close
  224. If Err.Number <> 0 Then RunMigrationFile = "[" & Err.Number & "] " & Err.Description & " (while trying to " & step & ")" : Err.Clear : Exit Function
  225. step = "compile file"
  226. code = Replace(Replace(code, "<%", ""), "%>", "")
  227. ExecuteGlobal code
  228. If Err.Number <> 0 Then RunMigrationFile = "[" & Err.Number & "] " & Err.Description & " (while trying to " & step & ")" : Err.Clear : Exit Function
  229. Set migration = New MigrationContext_Class
  230. Set migration.DB = m_db
  231. step = "run Migration_" & direction
  232. Execute "Call Migration_" & direction & "(migration)"
  233. If Err.Number <> 0 Then RunMigrationFile = "[" & Err.Number & "] " & Err.Description & " (while trying to " & step & ")" : Err.Clear : Exit Function
  234. RunMigrationFile = ""
  235. End Function
  236. '-------------------------------------------------------------------------------------------------------------------
  237. ' Apply all pending migrations
  238. '-------------------------------------------------------------------------------------------------------------------
  239. Public Sub ApplyAllPending()
  240. Dim pending, version, versions()
  241. Set pending = GetPendingMigrations()
  242. If pending.Count = 0 Then
  243. Response.Write "No pending migrations." & vbCrLf
  244. Exit Sub
  245. End If
  246. ' Sort versions
  247. ReDim versions(pending.Count - 1)
  248. Dim i : i = 0
  249. For Each version In pending.Keys
  250. versions(i) = version
  251. i = i + 1
  252. Next
  253. ' Simple bubble sort for versions
  254. Dim j, temp
  255. For i = 0 To UBound(versions) - 1
  256. For j = i + 1 To UBound(versions)
  257. If CDbl(versions(i)) > CDbl(versions(j)) Then
  258. temp = versions(i)
  259. versions(i) = versions(j)
  260. versions(j) = temp
  261. End If
  262. Next
  263. Next
  264. ' Apply in order
  265. For i = 0 To UBound(versions)
  266. ApplyMigration pending(versions(i))
  267. Next
  268. End Sub
  269. '-------------------------------------------------------------------------------------------------------------------
  270. ' Rollback the last applied migration
  271. '-------------------------------------------------------------------------------------------------------------------
  272. Public Sub RollbackLast()
  273. Dim applied, version, lastVersion
  274. Set applied = GetAppliedMigrations()
  275. If applied.Count = 0 Then
  276. Response.Write "No migrations to rollback." & vbCrLf
  277. Exit Sub
  278. End If
  279. ' Find the last version
  280. lastVersion = ""
  281. For Each version In applied.Keys
  282. ' VBScript does not short-circuit Or, so CDbl("") must be avoided explicitly
  283. If lastVersion = "" Then
  284. lastVersion = version
  285. ElseIf CDbl(version) > CDbl(lastVersion) Then
  286. lastVersion = version
  287. End If
  288. Next
  289. ' Find the filename
  290. Dim available
  291. Set available = GetAvailableMigrations()
  292. If available.Exists(lastVersion) Then
  293. RollbackMigration available(lastVersion)
  294. Else
  295. Err.Raise vbObjectError + 7, "Migrator", "Migration file not found for version: " & lastVersion
  296. End If
  297. End Sub
  298. End Class
  299. '=======================================================================================================================
  300. ' MIGRATION CONTEXT
  301. '=======================================================================================================================
  302. ' Provides helper methods for use within migration files
  303. '
  304. Class MigrationContext_Class
  305. Public DB ' Reference to DAL
  306. '-------------------------------------------------------------------------------------------------------------------
  307. ' Execute raw SQL
  308. '-------------------------------------------------------------------------------------------------------------------
  309. Public Sub ExecuteSQL(sql)
  310. On Error Resume Next
  311. DB.Execute sql, empty
  312. If Err.Number <> 0 Then
  313. Dim n, d : n = Err.Number : d = Err.Description
  314. On Error GoTo 0
  315. Err.Raise n, "MigrationContext", d
  316. End If
  317. End Sub
  318. '-------------------------------------------------------------------------------------------------------------------
  319. ' Create a table
  320. '-------------------------------------------------------------------------------------------------------------------
  321. Public Sub CreateTable(tableName, columns)
  322. Dim sql
  323. sql = "CREATE TABLE " & tableName & " (" & columns & ")"
  324. ExecuteSQL sql
  325. End Sub
  326. '-------------------------------------------------------------------------------------------------------------------
  327. ' Drop a table
  328. '-------------------------------------------------------------------------------------------------------------------
  329. Public Sub DropTable(tableName)
  330. ExecuteSQL "DROP TABLE " & tableName
  331. End Sub
  332. '-------------------------------------------------------------------------------------------------------------------
  333. ' Add a column to a table
  334. '-------------------------------------------------------------------------------------------------------------------
  335. Public Sub AddColumn(tableName, columnName, columnType)
  336. ExecuteSQL "ALTER TABLE " & tableName & " ADD COLUMN " & columnName & " " & columnType
  337. End Sub
  338. '-------------------------------------------------------------------------------------------------------------------
  339. ' Drop a column from a table
  340. '-------------------------------------------------------------------------------------------------------------------
  341. Public Sub DropColumn(tableName, columnName)
  342. ExecuteSQL "ALTER TABLE " & tableName & " DROP COLUMN " & columnName
  343. End Sub
  344. '-------------------------------------------------------------------------------------------------------------------
  345. ' Create an index
  346. '-------------------------------------------------------------------------------------------------------------------
  347. Public Sub CreateIndex(indexName, tableName, columns)
  348. ExecuteSQL "CREATE INDEX " & indexName & " ON " & tableName & " (" & columns & ")"
  349. End Sub
  350. '-------------------------------------------------------------------------------------------------------------------
  351. ' Drop an index
  352. '-------------------------------------------------------------------------------------------------------------------
  353. Public Sub DropIndex(indexName, tableName)
  354. ExecuteSQL "DROP INDEX " & indexName ' SQLite syntax (Access/SQL Server need "ON table")
  355. End Sub
  356. End Class
  357. '=======================================================================================================================
  358. ' SINGLETON
  359. '=======================================================================================================================
  360. Dim Migrator__Singleton : Set Migrator__Singleton = Nothing
  361. Function Migrator()
  362. If Migrator__Singleton Is Nothing Then
  363. Set Migrator__Singleton = New Migrator_Class
  364. End If
  365. Set Migrator = Migrator__Singleton
  366. End Function
  367. %>

Powered by TurnKey Linux.