code: def format(sql, args=None):
      
      resolved_vars = {}
      code = []
      SqlStatement._find_recursive_dependencies(sql, args, code=code,
                                                resolved_vars=resolved_vars)
  
      # Rebuild the SQL string, substituting just '$' for escaped $ occurrences,
      # variable references substituted with their values, or literal text copied
      # over as-is.
      parts = []
      for (escape, placeholder, _, literal) in SqlStatement._get_tokens(sql):
        if escape:
          parts.append('$')
        elif placeholder:
          variable = placeholder[1:]
          try:
            value = resolved_vars[variable]
          except KeyError as e:
            raise Exception('Invalid sql. Unable to substitute $%s.' % e.args[0])
  
          if isinstance(value, types.ModuleType):
            value = _utils.get_default_query_from_module(value)
  
          if isinstance(value, SqlStatement):
            sql = value.format(value._sql, resolved_vars)
            value = '(%s)' % sql
          elif '_repr_sql_' in dir(value):
            # pylint: disable=protected-access
            value = value._repr_sql_()
          elif isinstance(value, basestring):
            value = SqlStatement._escape_string(value)
          elif isinstance(value, list) or isinstance(value, tuple):
            if isinstance(value, tuple):
              value = list(value)
            expansion = '('
            for v in value:
              if len(expansion) > 1:
                expansion += ', '
              if isinstance(v, basestring):
                expansion += SqlStatement._escape_string(v)
              else:
                expansion += str(v)
            expansion += ')'
            value = expansion
          else:
            value = str(value)
          parts.append(value)
        elif literal:
          parts.append(literal)
  
      expanded = ''.join(parts)
      return expanded
docs: Resolve variable references in a query within an environment.
  
      This computes and resolves the transitive dependencies in the query and raises an
      exception if that fails due to either undefined or circular references.
  
      Args:
        sql: query to format.
        args: a dictionary of values to use in variable expansion.
  
      Returns:
        The resolved SQL text with variables expanded.
  
      Raises:
        Exception on failure.