             query = query.union(db.table(opts.tables[i]))
         query.changes(includeInitial:false).run (err, feed) =>
             feed.each(opts.cb)
+
+    # Wait until the table is ready for queries.
+    # NOTE:
+    wait_until_ready_for_writes: (opts) =>
+        opts = defaults opts,
+            table     : required     # string -- name of a table
+            timeout_s : 30
+            cache     : true         # if true, cache success for 10s; this is more efficient, but means SMC will stop responding properly during a failure for a few seconds.
+            cb        : required     # cb(undefined, obj) on success and cb('timeout') on failure due to timeout
+        last = (@_wait_until_ready_for_writes_last ?= {})
+        if opts.cache and (last[opts.table]? and new Date() - last[opts.table] < 10000)
+            opts.cb()
+            return
+        d = (@_wait_until_ready_for_writes ?= {})
+        if not d[opts.table]?
+            d[opts.table] = [opts.cb]
+        else
+            d[opts.table].push(opts.cb)
+            return
+        @table(opts.table).wait(waitFor: "ready_for_writes", timeout:30).run (err) =>
+            if not err and opts.cache
+                last[opts.table] = new Date()
+            for cb in d[opts.table]
+                cb(err)
+            delete d[opts.table]
 
     # Wait until the query results in at least one result obj, and
     # calls cb(undefined, obj).

            warning  : 30          # display warning and stop using connection if run takes this many seconds or more
            error    : 10*60       # kill any query that takes this long (and corresponding connection)
            concurrent_warn  : 500  # if number of concurrent outstanding db queries exceeds this number, put a concurrent_warn message in the log.
            concurrent_error : 600  # if nonzero, and this many queries at once, any query instantly fails!
            mod_warn : 2           # display MOD_WARN warning in log if any query modifies at least this many docs
            cache_expiry  : 15000  # expire cached queries after this many milliseconds (default: 15s)
            cache_size    : 250    # cache this many queries; use @...query.run({cache:true}, cb) to cache result for a few seconds

                        opts.options.push(x)

        result = undefined
        table_name = SCHEMA[opts.table].virtual ? opts.table
        db_query = @table(table_name)
        opts.this = @

        # The killfeed below is only used when changes is true in case of tricky queries that depend
