Source

Clj-Liquibase / src / main / clj / org / bituf / clj_liquibase.clj

Full commit
  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
(ns org.bituf.clj-liquibase
  "Expose functions from the Liquibase library.
  See also:
    http://www.liquibase.org/manual/home"
  (:import
    (java.io                           File IOException Writer)
    (java.sql                          Connection)
    (java.text                         DateFormat)
    (java.util                         Date List)
    (javax.sql                         DataSource)
    (org.bituf.clj_liquibase           CustomDBDocVisitor)
    (liquibase.changelog               ChangeLogIterator ChangeSet ChangeLogParameters
                                       DatabaseChangeLog)
    (liquibase.change                  Change)
    (liquibase.changelog.filter        AfterTagChangeSetFilter      AlreadyRanChangeSetFilter
                                       ChangeSetFilter              ContextChangeSetFilter
                                       CountChangeSetFilter         DbmsChangeSetFilter
                                       ExecutedAfterChangeSetFilter ShouldRunChangeSetFilter)
    (liquibase.changelog.visitor       DBDocVisitor RollbackVisitor UpdateVisitor)
    (liquibase.database                Database DatabaseFactory)
    (liquibase.database.jvm            JdbcConnection)
    (liquibase.executor                Executor ExecutorService LoggingExecutor)
    (liquibase.exception               LiquibaseException LockException)
    (liquibase.integration.commandline CommandLineUtils)
    (liquibase.lockservice             LockService)
    (liquibase.logging                 LogFactory Logger)
    (liquibase.precondition            Precondition)
    (liquibase.precondition.core       PreconditionContainer)
    (liquibase.sql                     Sql)
    (liquibase.sql.visitor             SqlVisitor)
    (liquibase.sqlgenerator            SqlGeneratorFactory)
    (liquibase.statement               SqlStatement)
    (liquibase.util                    LiquibaseUtil))
  (:require
    [clojure.string         :as sr]
    [org.bituf.clj-dbspec   :as sp]
    [org.bituf.clj-miscutil :as mu]
    [org.bituf.clj-liquibase.internal     :as in]
    [org.bituf.clj-liquibase.change       :as ch]
    [org.bituf.clj-liquibase.precondition :as pc]
    [org.bituf.clj-liquibase.sql-visitor  :as vis]))


(def ^{:doc "Clj-Liquibase version (only major and minor)"}
      version [0 2])


;; ===== Dynamic vars for Integration =====


(def ^{:doc "Logical filepath use by ChangeSet and ChangeLog instances."
       :tag String
       :dynamic true}
      *logical-filepath* nil)


(def ^{:doc "Database (liquibase.database.Database) instance."
       :tag Database
       :dynamic true}
      *db-instance* nil)


(def ^{:doc "Changelog params (liquibase.changelog.ChangeLogParameters) instance."
       :tag ChangeLogParameters
       :dynamic true}
      *changelog-params* nil)


(defn verify-valid-logical-filepath
  "Verify whether the *logical-filepath* var has a valid value. Return true if
  all OK, throw IllegalStateException otherwise."
  []
  (when (not (string? *logical-filepath*))
    (throw (IllegalStateException.
             ^String (format
                       "Expected %s but found %s - not wrapped in 'defchangelog'?"
                       "var *logical-filepath* to be string"
                       (mu/val-dump *logical-filepath*)))))
  true)


;; ===== ChangeSet =====


(defn changeset?
  "Return true if specified argument is a liquibase.changelog.ChangeSet
  instance, false otherwise."
  [x]
  (instance? ChangeSet x))


(defn ^ChangeSet make-changeset
  "Return a ChangeSet instance.
  Arguments:
    id      (String)     Author-assigned ID, which can be sequential
    author  (String)     Author name (must be kept same across changesets)
    changes (collection) List of Change objects
  Optional arguments:
    :dbms                          ; String/Keyword/vector-of-multiple
    :run-always         :always    ; Boolean
    :run-on-change      :on-change ; Boolean
    :context            :ctx       ; String
    :run-in-transaction :in-txn    ; Boolean (true by default)
    :fail-on-error      :fail-err  ; Boolean
    ;; sub tags
    :comment                        ; String
    :pre-conditions     :pre-cond   ; list of Precondition objects, or PreconditionContainer object
    :valid-checksum     :valid-csum ; String
    :visitors                       ; list of SqlVisitor objects
  See also:
    http://www.liquibase.org/manual/changeset"
  [^String id ^String author ^List changes
   & {:keys [logical-filepath   filepath
             dbms
             run-always         always
             run-on-change      on-change
             context            ctx
             run-in-transaction in-txn
             fail-on-error      fail-err
             comment
             pre-conditions     pre-cond
             rollback-changes   rollback
             valid-checksum     valid-csum
             visitors
             ] :as opt}] {:post [(instance? ChangeSet %)]
                          :pre  [(mu/verify-opt #{:logical-filepath   :filepath
                                                  :dbms
                                                  :run-always         :always
                                                  :run-on-change      :on-change
                                                  :context            :ctx
                                                  :run-in-transaction :in-txn
                                                  :fail-on-error      :fail-err
                                                  :comment
                                                  :pre-conditions     :pre-cond
                                                  :rollback-changes   :rollback
                                                  :valid-checksum     :valid-csum
                                                  :visitors} opt)
                                 (mu/verify-arg (string?       id))
                                 (mu/verify-arg (string?       author))
                                 (mu/verify-arg (coll?         changes))
                                 (mu/verify-arg (mu/not-empty? changes))
                                 (mu/verify-arg (every? vis/visitor? visitors))]}
  (when-not (or logical-filepath filepath)
    (verify-valid-logical-filepath))
  (let [s-filepath (or logical-filepath filepath *logical-filepath*)
        s-dbms     (in/as-dbident-names dbms)
        b-always   (or run-always       always    false)
        b-change   (or run-on-change    on-change false)
        s-contxt   (or context          ctx)
        b-in-txn   (let [x (or run-in-transaction in-txn)]
                     (if (nil? x) true (or x false)))
        b-fail-err (or fail-on-error    fail-err  false)
        ;; sub tags
        s-comment  comment
        v-pre-cond (or pre-conditions     pre-cond)
        v-rollback (or rollback-changes   rollback)
        s-val-csum (or valid-checksum     valid-csum)
        _ (do
            (mu/verify-arg (string?       id))
            (mu/verify-arg (string?       author))
            (mu/verify-arg (string?       s-filepath))
            (mu/verify-arg (mu/not-empty? changes))
            (doseq [each changes]
              (mu/verify-arg (instance? Change each)))
            (mu/verify-arg (mu/boolean? b-always))
            (mu/verify-arg (mu/boolean? b-change))
            (mu/verify-arg (or (nil? s-contxt) (string? s-contxt)))
            (mu/verify-arg (string?     s-dbms))
            (mu/verify-arg (mu/boolean? b-in-txn))
            (mu/verify-arg (or (nil? v-pre-cond)
                             (instance? PreconditionContainer v-pre-cond)
                             (and (coll? v-pre-cond)
                               (every? #(instance? Precondition %) v-pre-cond)))))
        ;; String id, String author, boolean alwaysRun, boolean runOnChange,
        ;; String filePath, String contextList, String dbmsList, boolean runInTransaction
        c-set (ChangeSet.
                ^String id ^String author   ^Boolean b-always ^Boolean b-change
                ^String (mu/java-filepath s-filepath)
                ^String s-contxt ^String  s-dbms   ^Boolean b-in-txn)]
    (doseq [each changes]
      (.addChange c-set each))
    (if b-fail-err (.setFailOnError   c-set b-fail-err))
    (if s-comment  (.setComments      c-set s-comment))
    (if v-pre-cond (.setPreconditions c-set (if (coll? v-pre-cond)
                                              (pc/pre-cond v-pre-cond)
                                              v-pre-cond)))
    (if v-rollback (doseq [each (mu/as-vector v-rollback)]
                     (if (string? each) (.addRollBackSQL c-set ^String each)
                       (.addRollbackChange c-set ^Change each))))
    (if s-val-csum (doseq [each (mu/as-vector s-val-csum)]
                     (.addValidCheckSum c-set each)))
    (doseq [each visitors]
      (.addSqlVisitor c-set ^SqlVisitor each))
    c-set))


(defn create-table-changeset-internal
  "Common internal implementation for `create-table-changeset` and
  `create-table-withid-changeset`."
  [f ct-vkeys ^String id ^String author table-name ^List columns
   & {:keys [dummy] :as opt}]
  (let [map2vec  (partial reduce into [])
        ct-vargs (map2vec (select-keys opt ct-vkeys))
        ;; mc = make-changeset
        mc-visit (vis/make-visitors
                   :include (map (partial vis/for-dbms! :mysql)
                                 (vis/make-visitors :append "engine=InnoDB")))
        mc-vargs (map2vec (apply dissoc (merge {:visitors mc-visit} opt)
                                 ct-vkeys))]
    (apply make-changeset id author
           [(apply f table-name columns ct-vargs)]
           mc-vargs)))


(defn create-table-changeset
  "Convenience function to build a changeset for `create-table` change with
  sensible defaults, e.g. create a table on MySQL with InnoDB storage engine.
  Optional arguments are a union of those in `make-changeset` and
  `change/create-table`.
  See also:
    make-changeset
    change/create-table"
  [^String id ^String author table-name ^List columns & args]
  (apply create-table-changeset-internal
         ch/create-table
         [:schema-name :schema :table-space :tspace :remarks]
         id author table-name columns args))


(defn create-table-withid-changeset
  "Convenience function to build a changeset for `create-table-withid` with
  sensible defaults, e.g. create a table on MySQL with InnoDB storage engine.
  Optional arguments are a union of those in `make-changeset` and
  `change/create-table-withid`.
  See also:
    make-changeset
    change/create-table-withid"
  [^String id ^String author table-name ^List columns & args]
  (apply create-table-changeset-internal
         ch/create-table-withid
         [:schema-name :schema :table-space :tspace :remarks :idcol]
         id author table-name columns args))


;; ===== DatabaseChangeLog helpers =====


(defn ^Database make-db-instance
  "Return a Database instance for current connection."
  [^Connection conn]
  ;; DatabaseFactory.getInstance().findCorrectDatabaseImplementation(new JdbcConnection(conn))
  (.findCorrectDatabaseImplementation (DatabaseFactory/getInstance)
    (JdbcConnection. conn)))


(defn ^ChangeLogParameters make-changelog-params
  "Return a ChangeLogParameters instance."
  [^Database db-instance
   & {:keys [contexts ; list of string
             ]}]
  (let [clp (ChangeLogParameters. db-instance)]
    (doseq [each (mu/as-vector contexts)]
      (.addContext clp (mu/as-string each)))
    clp))


;; ===== Integration =====


(defn wrap-lb-init
  "Initialize global settings and wrap f with that context."
  [f] {:post [(fn? %)]
       :pre  [(fn? f)]}
  (fn [& args]
    (if (mu/not-nil? *db-instance*) (apply f args)
      (let [g (sp/wrap-connection
                #(binding [*db-instance* (make-db-instance
                                           (:connection sp/*dbspec*))
                           *changelog-params* (make-changelog-params
                                                *db-instance*)]
                   (apply f args)))]
        (g)))))


(defmacro with-lb
  "Execute of code in the context of initialized Liquibase settings."
  [& body]
  `(let [g# (wrap-lb-init (fn [] ~@body))]
     (g#)))


;; ===== DatabaseChangeLog =====


(defn changelog?
  "Return true if specified argument is a liquibase.changelog.DatabaseChangeLog
  instance, false otherwise."
  [x]
  (instance? DatabaseChangeLog x))


(defn ^DatabaseChangeLog make-changelog
  "Return a DatabaseChangeLog instance.
  Arguments:
    change-sets  (collection/list) List of ChangeSet instances, or
                                   List of arg-lists (for 'make-changeset' fn)
  Optional args:
    :pre-conditions :pre-cond  ; PreconditionContainer object, or list of Precondition objects
  See also:
    http://www.liquibase.org/manual/databasechangelog
    make-changelog-params"
  [^String filepath ^List change-sets
   & {:keys [pre-conditions     pre-cond   ; vector
             ] :as opt}] {:post [(instance? DatabaseChangeLog %)]
                          :pre  [(mu/verify-opt #{:pre-conditions   :pre-cond} opt)
                                 (mu/verify-arg (string?       filepath))
                                 (mu/verify-arg (coll?         change-sets))
                                 (mu/verify-arg (mu/not-empty? change-sets))]}
  (let [dbcl       (DatabaseChangeLog.)
        v-pre-cond (or pre-conditions pre-cond)
        _          (mu/verify-arg
                     (or (nil? v-pre-cond)
                       (instance? PreconditionContainer v-pre-cond)
                       (and (coll? v-pre-cond)
                         (every? #(instance? Precondition %) v-pre-cond))))]
    (doto dbcl
      (.setLogicalFilePath (mu/java-filepath filepath))
      (.setChangeLogParameters ^ChangeLogParameters *changelog-params*))
    (doseq [each change-sets]
      (binding [*logical-filepath* (mu/java-filepath filepath)]
        (cond
          (changeset? each)    (.addChangeSet dbcl ^ChangeSet each)
          (and (coll? each)
            (not (map? each))) (.addChangeSet dbcl
                                 ^ChangeSet (apply make-changeset each))
          :else
          (mu/illegal-argval "change-sets#element"
            "ChangeSet object or arg-lists for 'make-changeset' fn"
            each))))
    (if v-pre-cond
      (.setPreconditions dbcl
        ^PreconditionContainer (if (coll? v-pre-cond) (pc/pre-cond v-pre-cond)
                                 v-pre-cond)))
    dbcl))


(defmacro defchangelog
  "Define a function that when executed with no arguments, returns a database
  changelog (DatabaseChangeLog instance). Do so in the context where
  *logical-filepath* is bound to *file* i.e. name of the current file.
  See also:
    make-changelog"
  [var-name change-sets & var-args]
  `(def ~var-name
     (partial make-changelog (or (and *logical-filepath* (mu/java-filepath
                                                           *logical-filepath*))
                               (mu/pick-filename *file*))
       ~change-sets ~@var-args)))


;; ===== Actions helpers =====


(def ^{:doc "Liquibase logger"
       :tag Logger}
      log (LogFactory/getLogger))

(defn check-database-changelog-table
  "Check database changelog table.
  See also:
    liquibase.Liquibase/checkDatabaseChangeLogTable"
  [^Database db ^Boolean update-existing-null-checksums
   ^DatabaseChangeLog db-changelog contexts]
  (when (and update-existing-null-checksums (nil? db-changelog))
    (throw
      (LiquibaseException.
        "'db-changelog' parameter is required if updating existing checksums")))
  (.checkDatabaseChangeLogTable db
    update-existing-null-checksums db-changelog (into-array String contexts))
  (when (not (.hasChangeLogLock (LockService/getInstance db)))
    (.checkDatabaseChangeLogLockTable db)))


(defn ^ChangeLogIterator make-changelog-iterator
  "Return a ChangeLogIterator instance.
  See also:
    liquibase.Liquibase/getStandardChangelogIterator"
  ([^DatabaseChangeLog changelog ^List changeset-filters]
    (ChangeLogIterator. changelog
      (into-array ChangeSetFilter changeset-filters)))
  ([^List ran-changesets ^DatabaseChangeLog changelog ^List changeset-filters]
    (ChangeLogIterator. ran-changesets changelog
      (into-array ChangeSetFilter
        changeset-filters))))


(defn ^Executor get-db-executor
  []
  (let [ex (ExecutorService/getInstance)]
    (.getExecutor ex *db-instance*)))


(defn output-header
  [^String message]
  (let [ex (get-db-executor)]
    (doto ex
      (.comment "*********************************************************************")
      (.comment message)
      (.comment "*********************************************************************")
      (.comment (format "Change Log: %s" *file*)) ; TODO get the logical filename
      (.comment (format "Ran at: %s" (.format (DateFormat/getDateTimeInstance
                                                DateFormat/SHORT DateFormat/SHORT)
                                       (Date.))))
      (.comment (format "Against: %s@%s"
                  (-> *db-instance* .getConnection .getConnectionUserName)
                  (-> *db-instance* .getConnection .getURL)))
      (.comment (format "Liquibase version: %s"
                  (LiquibaseUtil/getBuildVersion)))
      (.comment "*********************************************************************"))))


(defmacro with-writer
  [^Writer output & body]
  `(let [old-template# (get-db-executor)
         log-executor# (LoggingExecutor.
                         (get-db-executor) ~output *db-instance*)]
     (.setExecutor (ExecutorService/getInstance) *db-instance* log-executor#)
     ~@body
     (try
       (.flush ~output)
       (catch IOException e#
         (throw (LiquibaseException. e#))))
     (.setExecutor (ExecutorService/getInstance) *db-instance* old-template#)))


(defmacro do-locked
  "Acquire lock and execute body of code in that context. Make sure the lock is
  released (or log an error if it can't be) before exit."
  [& body]
  `(let [ls# (LockService/getInstance *db-instance*)]
     (.waitForLock ls#)
     (try ~@body
       (finally
         (try (.releaseLock ls#)
           (catch LockException e#
             (.severe log "Could not release lock" e#)))))))


;; ===== Actions =====


(defn ^List change-sql
  "Return a list of SQL statements (string) that would be required to execute
  the given Change object instantly for current database without versioning."
  [^Change change] {:post [(mu/verify-cond (vector? %))
                           (mu/verify-cond (every? string? %))]
                    :pre  [(mu/verify-arg  (instance? Change change))
                           (mu/verify-cond (instance? Database *db-instance*))]}
  (let [sgf (SqlGeneratorFactory/getInstance)
        sql (map (fn [^SqlStatement stmt]
                   (map (fn [^Sql sql]
                          ^String (.toSql sql))
                     (.generateSql sgf stmt *db-instance*)))
              (.generateStatements change *db-instance*))]
    (into [] (flatten sql))))


(defmacro with-writable
  "Set spec with :read-only as false and execute body of code in that context."
  [& body]
  `(sp/with-dbspec (sp/assoc-readonly sp/*dbspec* false)
     ~@body))


(defn update
  "Run the Liquibase Update command.
  See also:
    liquibase.Liquibase/update
    make-db-instance
    http://www.liquibase.org/manual/update"
  ([changelog-fn]
    (update changelog-fn []))
  ([changelog-fn ^List contexts] {:pre [(mu/verify-arg (fn? changelog-fn))
                                        (mu/verify-arg (coll? contexts))]}
    (sp/verify-writable)
    (do-locked
      (.setContexts *changelog-params* contexts)
      (let [changelog ^DatabaseChangeLog (changelog-fn)]
        (check-database-changelog-table *db-instance* true changelog contexts)
        (.validate changelog *db-instance* (into-array String contexts))
        (let [changelog-it (make-changelog-iterator changelog
                             [(ShouldRunChangeSetFilter. *db-instance*)
                              (ContextChangeSetFilter.
                                (into-array String
                                  [(mu/comma-sep-str contexts)]))
                              (DbmsChangeSetFilter. *db-instance*)
                              ])]
          (.run changelog-it (UpdateVisitor. *db-instance*) *db-instance*)))))
  ([changelog-fn ^List contexts ^Writer output]
    {:pre [(mu/verify-arg (instance? Writer output))]}
    (.setContexts *changelog-params* contexts)
    (with-writer output
      (output-header "Update Database Script")
      (with-writable
        (update changelog-fn contexts)))))


(defn update-by-count
  "Run Liquibase Update command restricting number of changes to howmany-changesets.
  See also:
    liquibase.Liquibase/update
    make-db-instance
    http://www.liquibase.org/manual/update"
  ([changelog-fn ^Integer howmany-changesets]
    (update-by-count changelog-fn howmany-changesets []))
  ([changelog-fn ^Integer howmany-changesets ^List contexts]
    {:pre [(mu/verify-arg (fn? changelog-fn))
           (mu/verify-arg (mu/posnum? howmany-changesets))
           (mu/verify-arg (coll? contexts))]}
    (sp/verify-writable)
    (.setContexts *changelog-params* contexts)
    (do-locked
      (let [changelog ^DatabaseChangeLog (changelog-fn)]
        (check-database-changelog-table *db-instance* true changelog contexts)
        (.validate changelog *db-instance* (into-array String contexts))
        (let [changelog-it (make-changelog-iterator changelog
                             [(ShouldRunChangeSetFilter. *db-instance*)
                              (ContextChangeSetFilter.
                                (into-array String
                                  [(mu/comma-sep-str contexts)]))
                              (DbmsChangeSetFilter. *db-instance*)
                              (CountChangeSetFilter. howmany-changesets)
                              ])]
          (.run changelog-it (UpdateVisitor. *db-instance*) *db-instance*)))))
  ([changelog-fn ^Integer howmany-changesets ^List contexts ^Writer output]
    (.setContexts *changelog-params* contexts)
    (with-writer output
      (output-header (str "Update " howmany-changesets " Change-sets Database Script"))
      (with-writable
        (update-by-count changelog-fn howmany-changesets contexts)))))


(defn tag
  "Tag the database schema with specified tag (coerced as string)."
  [the-tag] {:pre [(mu/verify-arg (or (string? the-tag) (keyword? the-tag)))]}
  (sp/verify-writable)
  (do-locked
    (check-database-changelog-table *db-instance* false nil nil)
    (.tag *db-instance* (mu/as-string the-tag))))


(defn rollback-to-tag
  "Rollback schema to specified tag.
  See also:
    liquibase.Liquibase/rollback
    http://www.liquibase.org/manual/rollback"
  ([changelog-fn ^String tag]
    (rollback-to-tag changelog-fn tag []))
  ([changelog-fn ^String tag ^List contexts]
    {:pre [(mu/verify-arg (fn? changelog-fn))
           (mu/verify-arg (coll? contexts))]}
    (sp/verify-writable)
    (do-locked
      (.setContexts *changelog-params* contexts)
      (let [changelog ^DatabaseChangeLog (changelog-fn)]
        (check-database-changelog-table *db-instance* false changelog contexts)
        (.validate changelog *db-instance* (into-array String contexts))
        (let [ran-changesets (.getRanChangeSetList *db-instance*)
              changelog-it (make-changelog-iterator ran-changesets changelog
                             [(AfterTagChangeSetFilter. tag ran-changesets)
                              (AlreadyRanChangeSetFilter. ran-changesets)
                              (ContextChangeSetFilter.
                                (into-array String
                                  [(mu/comma-sep-str contexts)]))
                              (DbmsChangeSetFilter. *db-instance*)
                              ])]
          (.run changelog-it (RollbackVisitor. *db-instance*) *db-instance*)))))
  ([changelog-fn ^String tag ^List contexts ^Writer output]
    {:pre [(mu/verify-arg (instance? Writer output))]}
    (.setContexts *changelog-params* contexts)
    (with-writer output
      (output-header (str "Rollback to '" tag "' Script"))
      (with-writable
        (rollback-to-tag changelog-fn tag contexts)))))


(defn rollback-to-date
  "Rollback schema to specified date.
  See also:
    liquibase.Liquibase/rollback
    http://www.liquibase.org/manual/rollback"
  ([changelog-fn ^Date date]
    (rollback-to-date changelog-fn date []))
  ([changelog-fn ^Date date ^List contexts]
    {:pre [(mu/verify-arg (fn? changelog-fn))
           (mu/verify-arg (mu/date? date))
           (mu/verify-arg (coll? contexts))]}
    (sp/verify-writable)
    (do-locked
      (.setContexts *changelog-params* contexts)
      (let [changelog ^DatabaseChangeLog (changelog-fn)]
        (check-database-changelog-table *db-instance* false changelog contexts)
        (.validate changelog *db-instance* (into-array String contexts))
        (let [ran-changesets (.getRanChangeSetList *db-instance*)
              changelog-it (make-changelog-iterator ran-changesets changelog
                             [(ExecutedAfterChangeSetFilter. date ran-changesets)
                              (AlreadyRanChangeSetFilter. ran-changesets)
                              (ContextChangeSetFilter.
                                (into-array String
                                  [(mu/comma-sep-str contexts)]))
                              (DbmsChangeSetFilter. *db-instance*)
                              ])]
          (.run changelog-it (RollbackVisitor. *db-instance*) *db-instance*)))))
  ([changelog-fn ^Date date contexts ^Writer output]
    {:pre [(mu/verify-arg (instance? Writer output))]}
    (.setContexts *changelog-params* contexts)
    (with-writer output
      (output-header (str "Rollback to " date " Script"))
      (with-writable
        (rollback-to-date changelog-fn date contexts)))))


(defn rollback-by-count
  "Rollback schema by specified count of changes.
  See also:
    liquibase.Liquibase/rollback
    http://www.liquibase.org/manual/rollback"
  ([changelog-fn ^Integer howmany-changesets]
    (rollback-by-count changelog-fn ^Integer howmany-changesets []))
  ([changelog-fn ^Integer howmany-changesets ^List contexts]
    {:pre [(mu/verify-arg (fn? changelog-fn))
           (mu/verify-arg (mu/posnum? howmany-changesets))
           (mu/verify-arg (coll? contexts))]}
    (sp/verify-writable)
    (.setContexts *changelog-params* contexts)
    (do-locked
      (let [changelog ^DatabaseChangeLog (changelog-fn)]
        (check-database-changelog-table *db-instance* false changelog contexts)
        (.validate changelog *db-instance* (into-array String contexts))
        (let [ran-changesets (.getRanChangeSetList *db-instance*)
              changelog-it (make-changelog-iterator ran-changesets changelog
                             [(AlreadyRanChangeSetFilter. ran-changesets)
                              (ContextChangeSetFilter.
                                (into-array String
                                  [(mu/comma-sep-str contexts)]))
                              (DbmsChangeSetFilter. *db-instance*)
                              (CountChangeSetFilter. howmany-changesets)
                              ])]
          (.run changelog-it (RollbackVisitor. *db-instance*) *db-instance*)))))
  ([changelog-fn ^Integer howmany-changesets ^List contexts ^Writer output]
    {:pre [(mu/verify-arg (instance? Writer output))]}
    (.setContexts *changelog-params* contexts)
    (with-writer output
      (output-header (str "Rollback to " howmany-changesets " Change-sets Script"))
      (with-writable
        (rollback-by-count changelog-fn howmany-changesets contexts)))))


(defn generate-doc
  "Generate documentation for changelog.
  See also:
    http://www.liquibase.org/manual/dbdoc
    http://www.liquibase.org/dbdoc/index.html"
  ([changelog-fn ^String output-dir ^List contexts]
    {:pre [(mu/verify-arg (fn? changelog-fn))
           (mu/verify-arg (string? output-dir))
           (mu/verify-arg (coll? contexts))
           (mu/verify-cond (mu/not-nil? *db-instance*))]}
    (.setContexts *changelog-params* contexts)
    (do-locked
      (let [changelog ^DatabaseChangeLog (changelog-fn)]
        (check-database-changelog-table *db-instance* false changelog nil)
        (.validate changelog *db-instance* (into-array String contexts))
        (let [changelog-it (make-changelog-iterator changelog
                             [(DbmsChangeSetFilter. *db-instance*)])
              dbdoc-visitor (DBDocVisitor. *db-instance*)]
          (.run changelog-it dbdoc-visitor *db-instance*)
          (.writeHTML (CustomDBDocVisitor. *db-instance*)
            (File. output-dir) nil)))))
  ([changelog-fn ^String output-dir]
    (generate-doc changelog-fn output-dir [])))


(defn diff
  "Report a description of the differences between two databases to standard out.
  See also:
    http://www.liquibase.org/manual/diff"
  [^Database ref-db-instance]
  (CommandLineUtils/doDiff ref-db-instance *db-instance*))