title: Where should a *sqlx.DB object be save for a cobra application?
body: <p>I have a cobra project which accesses database using <code>sqlx</code> package, and the command has sub-commands. The cobra related code is in the <code>cmd</code> folder/subpackage and the DB related code is in the <code>db</code> folder/subpackage.</p>
  
  <p>I would like to have package db to have a factory function</p>
  
  <pre><code>func NewDB() *sqlx.DB
  </code></pre>
  
  <p>which is called somewhere from the <code>cmd</code> package. But I am not sure where to call it and how to make it available to all sub-commands.</p>
  
  <p>One idea is to have a global variable in the <code>cmd</code> package, and initialize it either in <code>root.go</code>'s <code>init()</code> or <code>rootCmd</code>'s <code>PersistentPreRun</code>. Is it bad to use global variable in this case?</p>
  
  <p>If I don't use global variable, 
  one possibility is to have the sub-commands call <code>db.NewDB()</code>. Somehow it doesn't feel very nice this way either.</p>
  
  <p>I find it nicer to call <code>db.NewDB()</code> once in <code>cmd</code> package, probably in <code>root.go</code>. But where should I save the DB handle such that sub-commands can use it? </p>