<commit_before>﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web.Mvc;
using StackExchange.DataExplorer.Helpers;
using StackExchange.DataExplorer.Models;

namespace StackExchange.DataExplorer.Controllers
{
    public class QueryController : StackOverflowController
    {
        [HttpPost]
        [Route(@"query/save/{parentId?:\d+}")]
        public ActionResult Create(string sql, int? parentId, int? siteId, bool? textResults, bool? executionPlan, bool? crossSite, bool? excludeMetas)
        {
            if (CurrentUser.IsAnonymous && !CaptchaController.CaptchaPassed(GetRemoteIP()))
            {
                return Json(new { captcha = true });
            }

            Revision parent = null;

            if (parentId.HasValue)
            {
                parent = Current.DB.Query<Revision>(
                    "SELECT * FROM Revisions WHERE ID = @id",
                    new
                    {
                        id = parentId.Value
                    }
                ).FirstOrDefault();

                if (parent == null)
                {
                    throw new ApplicationException("Invalid revision ID");
                }
            }

            var parsedQuery = new ParsedQuery(sql, Request.Params);
            var query = Current.DB.Query<Query>(
                "SELECT * FROM Queries WHERE QueryHash = @hash",
                new
                {
                    hash = parsedQuery.Hash
                }
            ).FirstOrDefault();

            int? saveID = null, queryID = null;

            // We only create revisions if something actually changed.
            // We'll log it as an execution anyway if applicable, so the user will
            // still get a link in their profile, just not their own revision.
            if (!(parent != null && query != null && query.ID == parent.ID))
            {
                if (query == null)
                {
                    queryID = (int)Current.DB.Query<decimal>(@"
                        INSERT INTO Queries(
                            QueryHash, QueryBody
                        ) VALUES(
                            @hash, @body
                        )

                        SELECT SCOPE_IDENTITY()",
                        new
                        {
                            hash = parsedQuery.Hash,
                            body = parsedQuery.RawSql
                        }
                    ).First();
                }
                else
                {
                    queryID = query.ID;
                }

                saveID = (int)Current.DB.Query<decimal>(@"
                    INSERT INTO Revisions(
                        QueryID, RootID, OwnerID, OwnerIP, CreationDate
                    ) VALUES(
                        @query, @root, @owner, @ip, @creation
                    )

                    SELECT SCOPE_IDENTITY()",
                    new
                    {
                        query = queryID,
                        root = parent != null ? (int?)parent.ID : null,
                        owner = CurrentUser.IsAnonymous ? null : (int?)CurrentUser.Id,
                        ip = GetRemoteIP(),
                        creation = DateTime.UtcNow
                    }
                ).First();
            }

            ActionResult response = null;

            

            return response;
        }


        [Route(@"{sitename}/mcsv/{queryId:\d+}/{slug?}", RoutePriority.Low)]
        public ActionResult ShowmCsv(string sitename, int queryId)
        {
            Query query = FindQuery(queryId);

            if (query == null)
            {
                return PageNotFound();
            }
            
            var json = QueryRunner.GetMultiSiteResults(new ParsedQuery(query.BodyWithoutComments, Request.Params), CurrentUser, false).ToJson();

            return new CsvResult(json);
        }

        [Route(@"{sitename}/nmcsv/{queryId:\d+}/{slug?}", RoutePriority.Low)]
        public ActionResult ShownmCsv(string sitename, int queryId)
        {
            Query query = FindQuery(queryId);

            if (query == null)
            {
                return PageNotFound();<commit_msg>Parameter tidying and addition of new Execute method to handle query runs that aren't done from the editor<commit_after>﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web.Mvc;
using StackExchange.DataExplorer.Helpers;
using StackExchange.DataExplorer.Models;

namespace StackExchange.DataExplorer.Controllers
{
    public class QueryController : StackOverflowController
    {
        [HttpPost]
        [Route(@"query/save/{parentID?:\d+}")]
        public ActionResult Create(string sql, int? parentID, int? siteID, bool? textResults, bool? executionPlan, bool? crossSite, bool? excludeMetas)
        {
            if (CurrentUser.IsAnonymous && !CaptchaController.CaptchaPassed(GetRemoteIP()))
            {
                return Json(new { captcha = true });
            }

            Revision parent = null;

            if (parentID.HasValue)
            {
                parent = Current.DB.Query<Revision>(
                    "SELECT * FROM Revisions WHERE ID = @id",
                    new
                    {
                        id = parentID.Value
                    }
                ).FirstOrDefault();

                if (parent == null)
                {
                    throw new ApplicationException("Invalid revision ID");
                }
            }

            var parsedQuery = new ParsedQuery(sql, Request.Params);
            var query = Current.DB.Query<Query>(
                "SELECT * FROM Queries WHERE QueryHash = @hash",
                new
                {
                    hash = parsedQuery.Hash
                }
            ).FirstOrDefault();

            int? saveID = null, queryID = null;
            DateTime saveTime;

            // We only create revisions if something actually changed.
            // We'll log it as an execution anyway if applicable, so the user will
            // still get a link in their profile, just not their own revision.
            if (!(parent != null && query != null && query.ID == parent.ID))
            {
                if (query == null)
                {
                    queryID = (int)Current.DB.Query<decimal>(@"
                        INSERT INTO Queries(
                            QueryHash, QueryBody
                        ) VALUES(
                            @hash, @body
                        )

                        SELECT SCOPE_IDENTITY()",
                        new
                        {
                            hash = parsedQuery.Hash,
                            body = parsedQuery.RawSql
                        }
                    ).First();
                }
                else
                {
                    queryID = query.ID;
                }

                saveID = (int)Current.DB.Query<decimal>(@"
                    INSERT INTO Revisions(
                        QueryID, RootID, OwnerID, OwnerIP, CreationDate
                    ) VALUES(
                        @query, @root, @owner, @ip, @creation
                    )

                    SELECT SCOPE_IDENTITY()",
                    new
                    {
                        query = queryID,
                        root = parent != null ? (int?)parent.ID : null,
                        owner = CurrentUser.IsAnonymous ? null : (int?)CurrentUser.Id,
                        ip = GetRemoteIP(),
                        creation = saveTime = DateTime.UtcNow
                    }
                ).First();
            }

            ActionResult response = null;

            

            return response;
        }

        [HttpPost]
        [Route(@"query/run/{siteID:\d+}/{revisionID:\d+}")]
        public ActionResult Execute(int revisionID, int siteID, bool? textResults, bool? executionPlan, bool? crossSite, bool? excludeMetas)
        {
            ActionResult response = null;



            return response;
        }


        [Route(@"{sitename}/mcsv/{queryId:\d+}/{slug?}", RoutePriority.Low)]
        public ActionResult ShowmCsv(string sitename, int queryId)
        {
            Query query = FindQuery(queryId);

            if (query == null)
            {
                return PageNotFound();
            }
            
            var json = QueryRunner.GetMultiSiteResults(new ParsedQuery(query.BodyWithoutComments, Request.Params), CurrentUser, false).ToJson();

            return new CsvResult(json);
        }

        [Route(@"{sitename}/nmcsv/{queryId:\d+}/{slug?}", RoutePriority.Low)]
        public ActionResult ShownmCsv(string sitename, int queryId)
        {
            Query query = FindQuery(queryId);

            if (query == null)
            {
                return PageNotFound();
{'fraction_non_alphanumeric': 0.09093937375083277, 'fraction_numerical': 0.0, 'mean_word_length': 1.1995115995115995, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 11, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3107423', 'n_tokens_mistral': 2244, 'n_tokens_neox': 2034, 'n_words': 518}