import rethinkdb as r

from . import coerce, geo, operators, terms
from .coerce import COERSIONS
from .operators import BOOLEAN, EXPRESSIONS, MODIFIERS
from .terms import TERMS
from .exceptions import ReqonError, InvalidTypeError, InvalidFilterError


def query(query):
    try:
        reql = r.db(query['$db']).table(query['$table'])
    except KeyError:
        try:
            reql = r.table(query['$table'])
        except KeyError:
            raise ReqonError('The query descriptor requires a $table key.')
    return build_terms(query['$query'], reql)


def build_terms(reql, query):
    for sequence in query:
        term = sequence[0]
        try:
            reql = TERMS[term](reql, *sequence[1:])
        except ReqonError:
            raise
        except r.ReqlError:
            message = 'Invalid values for {0} with args {1}'
            raise ReqonError(message.format(term, sequence[1:]))
        except Exception:
            message = 'Unknown exception, {0}: {1}'
            raise ReqonError(message.format(term, sequence[1:]))

    return reql

import rethinkdb as r

from . import coerce, geo, operators, terms
from .coerce import COERSIONS
from .operators import BOOLEAN, EXPRESSIONS, MODIFIERS
from .terms import TERMS
from .exceptions import ReqonError, InvalidTypeError, InvalidFilterError


def query(query):
    try:
        reql = r.db(query['$db']).table(query['$table'])
    except KeyError:
        try:
            reql = r.table(query['$table'])
        except KeyError:
            raise ReqonError('The query descriptor requires a $table key.')
    return build_terms(query['$query'], reql)


def build_terms(query, reql):
    for sequence in query:
        term = sequence[0]
        try:
            reql = TERMS[term](reql, *sequence[1:])
        except ReqonError:
            raise
        except r.ReqlError:
            message = 'Invalid values for {0} with args {1}'
            raise ReqonError(message.format(term, sequence[1:]))
        except Exception:
            message = 'Unknown exception, {0}: {1}'
            raise ReqonError(message.format(term, sequence[1:]))

    return reql

--- 
+++ 
@@ -18,7 +18,7 @@
     return build_terms(query['$query'], reql)
 
 
-def build_terms(query, reql):
+def build_terms(reql, query):
     for sequence in query:
         term = sequence[0]
         try:
Fix arguments order of reqon.deprecated.build_terms().
