title: How can I more easily use Jooq transactions in Kotlin
body: <p>I have Jooq code written in Kotlin using transactions, and sometimes I want a method to work stand-alone as a top-level action that will have its own transactions, and other times want it to work composited with other methods within the same transaction.  For example, I have two lower level functions <code>actionAbc</code> and <code>actionXyz</code> that I want to compose into different higher level data methods and inherit their transaction if present, otherwise have their own.</p>
  <p>I know in Spring or other frameworks there are annotations that can be added that validate &quot;transaction required&quot; or &quot;create transaction if none&quot; type functionality.  But how do I do the same with Jooq + Kotlin without using those libraries?</p>
  <p>The closest I came up with is to pass the transaction in as an optional parameter and default it to a new transaction if missing.  But if someone forgets to pass in the transaction, then has the subtle failure of using a new top-level and unrelated transaction, I don't want that.</p>
  
  <pre class="lang-kotlin prettyprint-override"><code>fun tx(ctx: DSLContext = rootContext, codeBlock: DSLContext.() -&gt; Unit): Unit {
          ctx.transaction { cfg -&gt;
              DSL.using(cfg).codeBlock()
          }
      }
  }
  
  // and used as:
  
  fun actionAbc(parm1: String, parm2: Int, ctx: DSLContext = rootContext) {
     tx(ctx) { ... }
  }
  
  fun actionXyz(parm: Date, ctx: DSLContext = rootContext) {
     tx(ctx) { ... }
  }
  
  // composed:
  
  fun higherLevelAction(parm1: String, parm2: Date) {
    tx {
      actionAbc(parm1, 45, this) // if you forget `this` you are doing the wrong thing
      actionXyz(parm2, this)
  
      tx(this) {
         // nested transaction, also dangerous if forgetting `this` parameter
      }
    }
  }
  </code></pre>
  <p>How do I do this more naturally, and less dangerously?</p>
  <p><strong>Note:</strong> <em>this question is intentionally written and answered by the author (<a href="https://blog.stackoverflow.com/2011/07/its-ok-to-ask-and-answer-your-own-questions/">Self-Answered Questions</a>), so that the answers to commonly asked Kotlin topics are present in SO.</em></p>