Exemple #1
0
def explain_query(request):
    response = {'status': -1, 'message': ''}

    if request.method != 'POST':
        response['message'] = _('A POST request is required.')

    app_name = get_app_name(request)
    query_type = beeswax_models.SavedQuery.TYPES_MAPPING[app_name]

    try:
        form = get_query_form(request)

        if form.is_valid():
            query = SQLdesign(form, query_type=query_type)
            query_server = dbms.get_query_server_config(
                request.POST.get('server'))
            db = dbms.get(request.user, query_server)

            try:
                db.use(form.cleaned_data['database'])
                datatable = db.explain(query)
                results = db.client.create_result(datatable)

                response['status'] = 0
                response['results'] = results_to_dict(results)
            except Exception, e:
                response['status'] = -1
                response['message'] = str(e)

        else:
Exemple #2
0
def fetch_results(request, id, first_row=0):
    """
  Returns the results of the QueryHistory with the given id.

  The query results MUST be ready.

  If ``first_row`` is 0, restarts (if necessary) the query read.  Otherwise, just
  spits out a warning if first_row doesn't match the servers conception.
  Multiple readers will produce a confusing interaction here, and that's known.
  """
    first_row = long(first_row)
    results = type('Result', (object, ), {
        'rows': 0,
        'columns': [],
        'has_more': False,
        'start_row': 0,
    })
    fetch_error = False
    error_message = ''

    query_history = authorized_get_query_history(request, id, must_exist=True)
    query_server = query_history.get_query_server_config()
    design = SQLdesign.loads(query_history.design.data)
    db = dbms.get(request.user, query_server)

    try:
        database = design.query.get('database', 'default')
        db.use(database)
        datatable = db.execute_and_wait(design)
        results = db.client.create_result(datatable)
        status = 0
    except Exception, e:
        fetch_error = True
        error_message = str(e)
        status = -1
Exemple #3
0
def fetch_results(request, id, first_row=0):
  """
  Returns the results of the QueryHistory with the given id.

  The query results MUST be ready.

  If ``first_row`` is 0, restarts (if necessary) the query read.  Otherwise, just
  spits out a warning if first_row doesn't match the servers conception.
  Multiple readers will produce a confusing interaction here, and that's known.
  """
  first_row = long(first_row)
  results = type('Result', (object,), {
                'rows': 0,
                'columns': [],
                'has_more': False,
                'start_row': 0,
            })
  fetch_error = False
  error_message = ''

  query_history = authorized_get_query_history(request, id, must_exist=True)
  query_server = query_history.get_query_server_config()
  design = SQLdesign.loads(query_history.design.data)
  db = dbms.get(request.user, query_server)

  try:
    database = design.query.get('database', 'default')
    db.use(database)
    datatable = db.execute_and_wait(design)
    results = db.client.create_result(datatable)
    status = 0
  except Exception, e:
    fetch_error = True
    error_message = str(e)
    status = -1
Exemple #4
0
    def test_convert_rdbms_query(self):
        sql = 'SELECT * FROM auth_user'
        data = {
            'query': {
                'query': sql,
                'server': 'sqlite',
                'type': 'rdbms',
                'database': 'desktop/desktop.db'
            },
            'VERSION': '0.0.1'
        }
        data_json = json.dumps(data)
        design = SQLdesign.loads(data_json)
        query = SavedQuery.objects.create(
            type=SavedQuery.TYPES_MAPPING['rdbms'],
            owner=self.user,
            data=design.dumps(),
            name='SQLite query',
            desc='Test SQLite query')
        doc = Document.objects.link(query,
                                    owner=query.owner,
                                    extra=query.type,
                                    name=query.name,
                                    description=query.desc)

        # Setting doc.last_modified to older date
        Document.objects.filter(
            id=doc.id).update(last_modified=datetime.strptime(
                '2000-01-01T00:00:00Z', '%Y-%m-%dT%H:%M:%SZ'))
        doc = Document.objects.get(id=doc.id)

        try:
            # Test that corresponding doc2 is created after convert
            assert_false(
                Document2.objects.filter(owner=self.user,
                                         type='query-sqlite').exists())

            converter = DocumentConverter(self.user)
            converter.convert()

            doc2 = Document2.objects.get(owner=self.user, type='query-sqlite')

            # Verify Document2 attributes
            assert_equal(doc.name, doc2.data_dict['name'])
            assert_equal(doc.description, doc2.data_dict['description'])
            assert_equal(doc.last_modified.strftime('%Y-%m-%dT%H:%M:%S'),
                         doc2.last_modified.strftime('%Y-%m-%dT%H:%M:%S'))

            # Verify session type
            assert_equal('sqlite', doc2.data_dict['sessions'][0]['type'])

            # Verify snippet values
            assert_equal('ready', doc2.data_dict['snippets'][0]['status'])
            assert_equal(sql, doc2.data_dict['snippets'][0]['statement'])
            assert_equal(sql, doc2.data_dict['snippets'][0]['statement_raw'])
        finally:
            query.delete()
Exemple #5
0
def design_to_dict(design):
    sql_design = SQLdesign.loads(design.data)
    return {
        'id': design.id,
        'query': sql_design.sql_query,
        'name': design.name,
        'desc': design.desc,
        'server': sql_design.server,
        'database': sql_design.database
    }
Exemple #6
0
def design_to_dict(design):
  sql_design = SQLdesign.loads(design.data)
  return {
    'id': design.id,
    'query': sql_design.sql_query,
    'name': design.name,
    'desc': design.desc,
    'server': sql_design.server,
    'database': sql_design.database
  }
Exemple #7
0
Fichier : api.py Projet : Kewtt/hue
def design_to_dict(design):
    sql_design = SQLdesign.loads(design.data)
    return {
        "id": design.id,
        "query": sql_design.sql_query,
        "name": design.name,
        "desc": design.desc,
        "server": sql_design.server,
        "database": sql_design.database,
    }
Exemple #8
0
  def test_convert_rdbms_query(self):
    sql = 'SELECT * FROM auth_user'
    data = {
        'query': {
            'query': sql,
            'server': 'sqlite',
            'type': 'rdbms',
            'database': 'desktop/desktop.db'
        },
        'VERSION': '0.0.1'
    }
    data_json = json.dumps(data)
    design = SQLdesign.loads(data_json)
    query = SavedQuery.objects.create(
        type=SavedQuery.TYPES_MAPPING['rdbms'],
        owner=self.user,
        data=design.dumps(),
        name='SQLite query',
        desc='Test SQLite query'
    )
    doc = Document.objects.link(query, owner=query.owner, extra=query.type, name=query.name, description=query.desc)

    # Setting doc.last_modified to older date
    Document.objects.filter(id=doc.id).update(last_modified=datetime.strptime('2000-01-01T00:00:00Z', '%Y-%m-%dT%H:%M:%SZ'))
    doc = Document.objects.get(id=doc.id)

    try:
      # Test that corresponding doc2 is created after convert
      assert_false(Document2.objects.filter(owner=self.user, type='query-sqlite').exists())

      converter = DocumentConverter(self.user)
      converter.convert()

      doc2 = Document2.objects.get(owner=self.user, type='query-sqlite')

      # Verify Document2 attributes
      assert_equal(doc.name, doc2.data_dict['name'])
      assert_equal(doc.description, doc2.data_dict['description'])
      assert_equal(doc.last_modified.strftime('%Y-%m-%dT%H:%M:%S'), doc2.last_modified.strftime('%Y-%m-%dT%H:%M:%S'))

      # Verify session type
      assert_equal('sqlite', doc2.data_dict['sessions'][0]['type'])

      # Verify snippet values
      assert_equal('ready', doc2.data_dict['snippets'][0]['status'])
      assert_equal(sql, doc2.data_dict['snippets'][0]['statement'])
      assert_equal(sql, doc2.data_dict['snippets'][0]['statement_raw'])
    finally:
      query.delete()
Exemple #9
0
def execute_query(request, design_id=None):
    response = {'status': -1, 'message': ''}

    if request.method != 'POST':
        response['message'] = _('A POST request is required.')

    app_name = get_app_name(request)
    query_type = beeswax_models.SavedQuery.TYPES_MAPPING[app_name]
    design = safe_get_design(request, query_type, design_id)

    try:
        form = get_query_form(request, design_id)

        if form.is_valid():
            design = save_design(request, SaveForm(), form, query_type, design)

            query = SQLdesign(form, query_type=query_type)
            query_server = dbms.get_query_server_config(
                request.POST.get('server'))
            db = dbms.get(request.user, query_server)
            query_history = db.execute_query(query, design)
            query_history.last_state = beeswax_models.QueryHistory.STATE.expired.value
            query_history.save()

            try:
                db.use(form.cleaned_data['database'])
                datatable = db.execute_and_wait(query)
                results = db.client.create_result(datatable)

                response['status'] = 0
                response['results'] = results_to_dict(results)
                response['design'] = design.id
            except Exception as e:
                response['status'] = -1
                response['message'] = str(e)

        else:
            response['message'] = _('There was an error with your query.')
            response['errors'] = form.errors
    except RuntimeError as e:
        response['message'] = str(e)

    return JsonResponse(response, encoder=ResultEncoder)
Exemple #10
0
    def test_convert_rdbms_query(self):
        sql = "SELECT * FROM auth_user"
        data = {
            "query": {"query": sql, "server": "sqlite", "type": "rdbms", "database": "desktop/desktop.db"},
            "VERSION": "0.0.1",
        }
        data_json = json.dumps(data)
        design = SQLdesign.loads(data_json)
        query = SavedQuery.objects.create(
            type=SavedQuery.TYPES_MAPPING["rdbms"],
            owner=self.user,
            data=design.dumps(),
            name="SQLite query",
            desc="Test SQLite query",
        )
        doc = Document.objects.link(query, owner=query.owner, extra=query.type, name=query.name, description=query.desc)

        try:
            # Test that corresponding doc2 is created after convert
            assert_false(Document2.objects.filter(owner=self.user, type="query-sqlite").exists())

            converter = DocumentConverter(self.user)
            converter.convert()

            doc2 = Document2.objects.get(owner=self.user, type="query-sqlite")

            # Verify Document2 attributes
            assert_equal(doc.name, doc2.data_dict["name"])
            assert_equal(doc.description, doc2.data_dict["description"])

            # Verify session type
            assert_equal("sqlite", doc2.data_dict["sessions"][0]["type"])

            # Verify snippet values
            assert_equal("ready", doc2.data_dict["snippets"][0]["status"])
            assert_equal(sql, doc2.data_dict["snippets"][0]["statement"])
            assert_equal(sql, doc2.data_dict["snippets"][0]["statement_raw"])
        finally:
            query.delete()