from __future__ import absolute_import, unicode_literals
from celery import shared_task
from django.utils import timezone
from apps.bi.models import Dataset, DatasetRecord
from apps.bi.services import exec_dataset
import json
from apps.utils.tools import MyJSONEncoder
    
@shared_task()
def exec_dataset_and_store(code: str, query: str = ''):
    dt = Dataset.objects.get(code=code)
    dtr = DatasetRecord()
    dtr.timex = timezone.now()
    dtr.dataset = dt
    squery = {}
    if query:
        squery = json.loads(query)
    dtr.full_sql, dtr.result = exec_dataset(dt, squery)
    dtr.result = json.loads(json.dumps(dtr.result, cls=MyJSONEncoder))
    dtr.save()
