alexlloyd / BigQuery: Switch to Standard SQL

// ==UserScript==
// @name         BigQuery: Switch to Standard SQL
// @version      0.1
// @description  Ensure the Standard SQL dialect is always selected unless there's nonempty SQL text
// @author       alexlloyd
// @match        https://bigquery.cloud.google.com/*
// @license      MIT
// @grant        none

// ==/UserScript==

// Docs: http://tampermonkey.net/documentation.php
(function () {
  'use strict';

  var reg = new RegExp('^SELECT  FROM \\[(.*):(.*)\\] LIMIT 1000$')

  var enableStandardSql = () => {
    var checkedCheckbox = document.querySelector('#use-legacy-sql .jfk-checkbox-checked');
    var codeMirrorContainer = document.querySelector('.CodeMirror');
    if (checkedCheckbox) {
      console.log('bq-enable-standard-sql: #use-legacy-sql is checked and .CodeMirror is empty, clicking to uncheck');
      checkedCheckbox.click();
    }
    if (codeMirrorContainer) {
      setTimeout(function() {
          var sql = codeMirrorContainer.CodeMirror.getValue();
          var match = sql.match(reg)
          if (match !== null) {
            var [full, project, table] = match;
            var text_box = codeMirrorContainer.CodeMirror
            text_box.setValue('SELECT  FROM `' + project + '.' + table + '` LIMIT 1000');
            console.log('bq-enable-standard-sql: #.CodeMirror contains Legacy SQL, changing to Standard');

            // TODO: move caret to between SELECT and FROM. Alternatively, work out how to trigger the tableCtrl.queryTable function to overwrite the textbox

            // if(text_box.createTextRange) {
            //     var range = text_box.createTextRange();
            //     range.move('character', 7);
            //     range.select();
            // }
            // else {
            //     if(text_box.selectionStart) {
            //         text_box.focus();
            //         text_box.setSelectionRange(7, 7);
            //     }
            //     else
            //         text_box.focus();
            // }
        }
      }, 100);
    }
  };

  var pollPeriodMs = 500;
  console.log('bq-enable-standard-sql: Starting, pollPeriodMs=' + pollPeriodMs);
  setInterval(enableStandardSql, pollPeriodMs);

})();