execute.mako 104 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007
  1. ## Licensed to Cloudera, Inc. under one
  2. ## or more contributor license agreements. See the NOTICE file
  3. ## distributed with this work for additional information
  4. ## regarding copyright ownership. Cloudera, Inc. licenses this file
  5. ## to you under the Apache License, Version 2.0 (the
  6. ## "License"); you may not use this file except in compliance
  7. ## with the License. You may obtain a copy of the License at
  8. ##
  9. ## http://www.apache.org/licenses/LICENSE-2.0
  10. ##
  11. ## Unless required by applicable law or agreed to in writing, software
  12. ## distributed under the License is distributed on an "AS IS" BASIS,
  13. ## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. ## See the License for the specific language governing permissions and
  15. ## limitations under the License.
  16. <%!
  17. from desktop.lib.django_util import extract_field_data
  18. from desktop.views import commonheader, commonfooter, commonshare, _ko
  19. from beeswax import conf as beeswax_conf
  20. from desktop import conf
  21. from desktop.conf import USE_NEW_EDITOR
  22. from django.utils.translation import ugettext as _
  23. from notebook.conf import ENABLE_QUERY_BUILDER
  24. %>
  25. <%namespace name="comps" file="beeswax_components.mako" />
  26. <%namespace name="layout" file="layout.mako" />
  27. ${ commonheader(_('Query'), app_name, user, request) | n,unicode }
  28. ${ layout.menubar(section='query') }
  29. <div id="temporaryPlaceholder"></div>
  30. <div id="beeswax-execute">
  31. <div id="query-editor" class="container-fluid hide section">
  32. <div class="panel-container">
  33. <div class="left-panel" id="navigator">
  34. <ul class="nav nav-tabs" style="margin-bottom: 0">
  35. <li class="active"><a href="#navigatorTab" data-toggle="tab" class="sidetab">${_('Assist')}</a></li>
  36. <li><a href="#settingsTab" data-toggle="tab" class="sidetab">${_('Settings')} <span data-bind="visible:design.settings.values().length + design.fileResources.values().length + design.functions.values().length > 0, text: design.settings.values().length + design.fileResources.values().length + design.functions.values().length" class="badge badge-info">12</span></a></li>
  37. % if app_name == 'impala':
  38. <li><a href="#sessionTab" data-toggle="tab" class="sidetab">${_('Session')}</a></li>
  39. % endif
  40. </ul>
  41. <div class="tab-content" style=" overflow: hidden;">
  42. <div class="tab-pane active" id="navigatorTab">
  43. <div class="card card-small card-tab" style="margin-bottom: 0;">
  44. <div class="card-body" style="margin-top: 0; height: 100%;">
  45. <div class="assist" data-bind="component: {
  46. name: 'assist-panel',
  47. params: {
  48. user: HIVE_AUTOCOMPLETE_USER,
  49. onlySql: true,
  50. sql: {
  51. navigationSettings: {
  52. openItem: false,
  53. showPreview: true,
  54. showStats: true
  55. }
  56. },
  57. visibleAssistPanels: ['sql']
  58. }
  59. }"></div>
  60. </div>
  61. </div>
  62. </div>
  63. <div class="tab-pane" id="settingsTab">
  64. <div class="card card-small card-tab">
  65. <div class="card-body" style="overflow-y: auto; height: 100%;">
  66. <div id="advanced-settings">
  67. <form id="advancedSettingsForm" action="" method="POST" class="form form-horizontal">
  68. ${ csrf_token(request) | n,unicode }
  69. <ul class="nav nav-list" style="border: none; padding: 0;">
  70. <li class="nav-header">${_('settings')}</li>
  71. <li class="white paramContainer">
  72. <!-- ko foreach: design.settings.values -->
  73. <div class="param">
  74. <div class="remove">
  75. <button data-bind="click: $root.removeSetting.bind(this, $index())" type="button" class="btn btn-mini settingsDelete" title="${_('Delete this setting')}">x
  76. </button>
  77. </div>
  78. <div data-bind="css: {'error': $root.getSettingKeyErrors($index()).length > 0}" class="control-group">
  79. <label>${_('Key')}</label>
  80. <input data-bind="value: key" type="text" class="settingsField" autocomplete="off" placeholder="${ 'impala.resultset.cache.size' if app_name == 'impala' else 'mapred.reduce.tasks' }"/>
  81. </div>
  82. <div data-bind="css: {'error': $root.getSettingValueErrors($index()).length > 0}" class="control-group">
  83. <label>${_('Value')}</label>
  84. <input data-bind="value: value" type="text" class="settingValuesField" placeholder="${ '5000' if app_name == 'impala' else '1' }"/>
  85. </div>
  86. </div>
  87. <!-- /ko -->
  88. <div class="control-group">
  89. <a data-bind="click: function() { $root.addSetting('','') }" class="btn btn-mini paramAdd">${_('Add')}</a>
  90. </div>
  91. </li>
  92. <li class="nav-header
  93. % if app_name == 'impala':
  94. hide
  95. % endif
  96. ">
  97. ${_('File Resources')}
  98. </li>
  99. <li class="white paramContainer
  100. % if app_name == 'impala':
  101. hide
  102. % endif
  103. ">
  104. <!-- ko foreach: design.fileResources.values -->
  105. <div class="param">
  106. <div class="remove">
  107. <button data-bind="click: $root.removeFileResource.bind(this, $index())" type="button" class="btn btn-mini" title="${_('Delete this setting')}">&times;</button>
  108. </div>
  109. <div data-bind="css: {'error': $root.getFileResourceTypeErrors($index()).length > 0}" class="control-group">
  110. <label>${_('Type')}</label>
  111. <select data-bind="value: type" class="input-small">
  112. <option value="JAR">${_('jar')}</option>
  113. <option value="ARCHIVE">${_('archive')}</option>
  114. <option value="FILE">${_('file')}</option>
  115. </select>
  116. </div>
  117. <div data-bind="css: {'error': $root.getFileResourcePathErrors($index()).length > 0}" class="control-group">
  118. <label>${_('Path')}</label>
  119. <input data-bind="value: path" type="text" class="filesField fileChooser" placeholder="/user/foo/udf.jar"/>
  120. </div>
  121. </div>
  122. <!-- /ko -->
  123. <div class="control-group">
  124. <a data-bind="click: function() { $root.addFileResource('','') }" class="btn btn-mini paramAdd">${_('Add')}</a>
  125. </div>
  126. </li>
  127. <li title="${ _('User-Defined Functions') }" class="nav-header
  128. % if app_name == 'impala':
  129. hide
  130. % endif
  131. ">
  132. ${_('UDFs')}
  133. </li>
  134. <li class="white paramContainer
  135. % if app_name == 'impala':
  136. hide
  137. % endif
  138. ">
  139. <!-- ko foreach: design.functions.values -->
  140. <div class="param">
  141. <div class="remove">
  142. <button data-bind="click: $root.removeFunction.bind(this, $index())" type="button" class="btn btn-mini settingsDelete" title="${_('Delete this setting')}">&times;</button>
  143. </div>
  144. <div data-bind="css: {'error': $root.getFunctionNameErrors($index()).length > 0}" class="control-group">
  145. <label>${_('Name')}</label>
  146. <input data-bind="value: name" type="text" class="functionsField" autocomplete="off" placeholder="myFunction"/>
  147. </div>
  148. <div data-bind="css: {'error': $root.getFunctionClassNameErrors($index()).length > 0}" class="control-group">
  149. <label>${_('Class name')}</label>
  150. <input data-bind="value: class_name" type="text" class="classNamesField" placeholder="com.acme.example"/>
  151. </div>
  152. </div>
  153. <!-- /ko -->
  154. <div class="control-group">
  155. <a data-bind="click: function() { $root.addFunction('','') }" class="btn btn-mini paramAdd">${_('Add')}</a>
  156. </div>
  157. </li>
  158. <li class="nav-header">${_('Options')}</li>
  159. <li class="white" style="padding-top:0; padding-left:0">
  160. <label class="checkbox" rel="tooltip" data-original-title="${_("If checked (the default), you can include parameters like $parameter_name in your query, and users will be prompted for a value when the query is run.")}">
  161. <input data-bind="checked: design.isParameterized" type="checkbox"/>
  162. ${_("Enable parameterization")}
  163. </label>
  164. </li>
  165. % if app_name == 'impala':
  166. <li class="nav-header">
  167. ${_('Metastore Catalog')}
  168. </li>
  169. <li class="white" style="padding-top:0; padding-left:0">
  170. <div class="control-group">
  171. <span id="refresh-dyk">
  172. <i class="fa fa-refresh"></i>
  173. ${ _('Sync tables tips') }
  174. </span>
  175. <div id="refresh-content" class="hide">
  176. <ul style="text-align: left;">
  177. <li>"invalidate
  178. metadata" ${ _("invalidates the entire catalog metadata. All table metadata will be reloaded on the next access.") }</li>
  179. <li>"invalidate metadata
  180. &lt;table&gt;" ${ _("invalidates the metadata, load on the next access") }</li>
  181. <li>"refresh
  182. &lt;table&gt;" ${ _("refreshes the metadata immediately. It is a faster, incremental refresh.") }</li>
  183. </ul>
  184. </div>
  185. </div>
  186. </li>
  187. % endif
  188. </ul>
  189. </form>
  190. </div>
  191. </div>
  192. </div>
  193. </div>
  194. % if app_name == 'impala':
  195. <div class="tab-pane" id="sessionTab">
  196. <div class="card card-small card-tab">
  197. <div class="card-body">
  198. <!-- ko if: $root.fetchingImpalaSession() -->
  199. <div style="margin: 5px">
  200. <i class="fa fa-spinner fa-spin" style="font-size: 20px; color: #BBB"></i>
  201. </div>
  202. <!-- /ko -->
  203. <!-- ko ifnot: $root.fetchingImpalaSession() -->
  204. <!-- ko if: $root.impalaSessionLink() != '' -->
  205. <ul class="nav nav-list" style="border: none; padding: 0;">
  206. <li class="nav-header">${ _('address')}</li>
  207. </ul>
  208. <div style="margin: 2px">
  209. <a data-bind="attr: {'href': $root.impalaSessionLink()}" target="_blank"><span data-bind="text: $root.impalaSessionLink().replace(/^(https?):\/\//, '')"></span> <i class="fa fa-external-link"></i></a>
  210. </div>
  211. <!-- /ko -->
  212. <!-- ko if: $root.impalaSessionLink() == '' -->
  213. <div style="margin: 5px">
  214. ${ _("There's currently no valid session") }
  215. </div>
  216. <!-- /ko -->
  217. <!-- /ko -->
  218. </div>
  219. </div>
  220. </div>
  221. % endif
  222. </div>
  223. </div>
  224. <div class="resizer" data-bind="splitDraggable : { appName: '${app_name}', onPosition: onPanelPosition, leftPanelVisible: isEditor }"><div class="resize-bar"><i class="fa fa-ellipsis-v"></i></div></div>
  225. <div class="content-panel" id="querySide">
  226. % if USE_NEW_EDITOR.get() and action != 'watch-redirect' and action != 'watch-results':
  227. <div class="alert">
  228. ${ _('This is the old SQL Editor, it is recommended to instead use: ') }
  229. % if app_name == 'impala':
  230. <a href="/hue/editor?type=impala" target="_blank">${_('Impala')}</a>
  231. % else:
  232. <a href="/hue/editor?type=hive" target="_blank">${_('Hive')}</a>
  233. % endif
  234. </div>
  235. % endif
  236. <div class="alert" data-bind="visible: design.isRedacted">
  237. ${ _('This query had some sensitive information removed when saved.') }
  238. </div>
  239. <div id="queryContainer" class="card card-small">
  240. <div class="pull-right" style="margin: 10px">
  241. <i class="fa fa-question-circle" id="help"></i>
  242. <div id="help-content" class="hide">
  243. <ul style="text-align: left;">
  244. <li>${ _('Press CTRL + Space to autocomplete') }</li>
  245. <li>${ _("You can execute queries with multiple SQL statements delimited by a semicolon ';'") }</li>
  246. <li>${ _('You can highlight and run a fragment of a query') }</li>
  247. </ul>
  248. </div>
  249. </div>
  250. <div style="margin-bottom: 30px">
  251. % if can_edit_name:
  252. <h1 class="card-heading simple">
  253. <a class="share-link" rel="tooltip" data-placement="bottom" style="padding-left:10px; padding-right: 10px" data-bind="click: openShareModal,
  254. attr: {'data-original-title': '${ _ko("Share") } '+name},
  255. css: {'baseShared': true, 'isShared': isShared()}">
  256. <i class="fa fa-users"></i>
  257. </a>
  258. <a href="javascript:void(0);"
  259. id="query-name"
  260. data-type="text"
  261. data-name="name"
  262. data-value="${design.name}"
  263. data-original-title="${ _('Query name') }"
  264. data-placement="right">
  265. </a>
  266. <br />
  267. <div style="display: inline-block; margin: 0 10px 0 46px; line-height: 20px; ">
  268. <a href="javascript:void(0);"
  269. id="query-description"
  270. data-type="textarea"
  271. data-name="description"
  272. data-value="${design.desc}"
  273. data-original-title="${ _('Query description') }"
  274. data-placement="bottom"
  275. style="font-size: 14px; line-height: 20px; white-space: normal; " >
  276. </a>
  277. </div>
  278. </h1>
  279. %endif
  280. </div>
  281. <div class="card-body">
  282. <div class="tab-content">
  283. <div id="queryPane">
  284. <div data-bind="css: {'hide': design.errors().length == 0 || design.inlineErrors().length > 0}" class="alert alert-error">
  285. <!-- ko if: $root.getQueryErrors().length > 0 -->
  286. <p><strong>${_('Please provide a query')}</strong></p>
  287. <!-- /ko -->
  288. <!-- ko if: $root.getQueryErrors().length == 0 -->
  289. <p><strong>${_('Your query has the following error(s):')}</strong></p>
  290. <div data-bind="foreach: design.errors">
  291. <p data-bind="text: $data" class="queryErrorMessage"></p>
  292. </div>
  293. <!-- /ko -->
  294. </div>
  295. <div data-bind="css: {'hide': design.watch.errors().length == 0 || design.watch.inlineErrors().length > 0}" class="alert alert-error">
  296. <p><strong>${_('Your query has the following error(s):')}</strong></p>
  297. <div data-bind="foreach: design.watch.errors">
  298. <p data-bind="text: $data" class="queryErrorMessage"></p>
  299. </div>
  300. </div>
  301. <textarea class="hide" tabindex="1" name="query" id="queryField"></textarea>
  302. <div class="actions">
  303. <button data-bind="click: tryExecuteQuery, visible: $root.canExecute, enable: $root.queryEditorBlank" type="button" id="executeQuery" class="btn btn-primary disable-feedback" tabindex="2">${_('Execute')}</button>
  304. <button data-bind="click: tryCancelQuery, visible: $root.design.isRunning()" class="btn btn-danger" data-loading-text="${ _('Canceling...') }" rel="tooltip" data-original-title="${ _('Cancel the query') }">${ _('Cancel') }</button>
  305. <button data-bind="click: tryExecuteNextStatement, visible: !$root.design.isFinished()" type="button" class="btn btn-primary disable-feedback" tabindex="2">${_('Next')}</button>
  306. <button data-bind="click: tryExecuteQuery, visible: !$root.design.isFinished()" type="button" id="executeQuery" class="btn btn-primary disable-feedback" tabindex="2">${_('Restart')}</button>
  307. % if can_edit:
  308. <button data-bind="click: trySaveDesign, css: {'hide': !$root.design.id() || $root.design.id() == -1}" type="button" class="btn hide">${_('Save')}</button>
  309. % endif
  310. <button data-bind="click: saveAsModal" type="button" class="btn">${_('Save as...')}</button>
  311. <button data-bind="click: tryExplainQuery, visible: $root.canExecute" type="button" id="explainQuery" class="btn">${_('Explain')}</button>
  312. <button data-bind="click: formatQuery" type="button" class="btn">${_('Format')}</button>
  313. &nbsp; ${_('or create a')} &nbsp;
  314. <button data-bind="click: createNewQuery" type="button" class="btn">${_('New query')}</button>
  315. <br/><br/>
  316. </div>
  317. </div>
  318. </div>
  319. </div>
  320. </div>
  321. <div id="resizePanel"><a href="javascript:void(0)"><i class="fa fa-ellipsis-h"></i></a></div>
  322. <div class="card card-small scrollable resultsContainer">
  323. <div class="query-right-actions" data-bind="visible: !design.explain()">
  324. <!-- ko if: $root.hasResults() -->
  325. <a id="expandResults" href="javascript:void(0)" title="${_('See results in full screen')}" rel="tooltip"
  326. class="view-query-results hide pull-right"><h4><i class="fa fa-expand"></i></h4></a>
  327. <a id="save-results" data-bind="click: saveResultsModal" href="javascript:void(0)" title="${_('Save the results to HDFS or a new Hive table')}" rel="tooltip"
  328. class="view-query-results hide pull-right"><h4><i class="fa fa-save"></i></h4>
  329. </a>
  330. ## Tricks for not triggering the closing of the query on download
  331. <a id="download-csv" data-bind="attr: {'href': '/${ app_name }/download/' + $root.design.history.id() + '/csv'}, event: { mouseover: function(){ window.onbeforeunload = null; }, mouseout: function() { window.onbeforeunload = $(window).data('beforeunload'); } }" href="javascript:void(0)" title="${_('Download the results in CSV format')}" rel="tooltip"
  332. class="view-query-results download hide pull-right"><h4><i class="hfo hfo-file-csv"></i></h4>
  333. </a>
  334. <a id="download-excel" data-bind="attr: {'href': '/${ app_name }/download/' + $root.design.history.id() + '/xls'}, event: { mouseover: function(){ window.onbeforeunload = null; }, mouseout: function() { window.onbeforeunload = $(window).data('beforeunload'); } }" href="javascript:void(0)" title="${_('Download the results in XLS format')}" rel="tooltip"
  335. class="view-query-results download hide pull-right"><h4><i class="hfo hfo-file-xls"></i></h4></a>
  336. <!-- /ko -->
  337. <a href="#clearHistoryModal" title="${_('Clear the query history')}" rel="tooltip" class="clear-queries pull-right" data-toggle="modal"><h4><i class="fa fa-calendar-times-o"></i></h4></a>
  338. </div>
  339. <div class="card-body">
  340. <ul class="nav nav-tabs">
  341. <li class="active recentLi"><a href="#recentTab" data-toggle="tab">${_('Recent queries')}</a></li>
  342. <li><a href="#query" data-toggle="tab">${_('Query')}</a></li>
  343. %if ENABLE_QUERY_BUILDER.get():
  344. <li><a href="#queryBuilderTab" data-toggle="tab">${_('Query builder')}</a></li>
  345. %endif
  346. <!-- ko if: !design.explain() -->
  347. <li><a href="#log" data-toggle="tab">${_('Log')}</a></li>
  348. <!-- /ko -->
  349. <!-- ko if: !design.explain() -->
  350. <li><a href="#columns" data-toggle="tab">${_('Columns')}</a></li>
  351. <li><a href="#results" data-toggle="tab">${_('Results')}</a></li>
  352. <li><a href="#chart" data-toggle="tab">${_('Chart')}</a></li>
  353. <!-- /ko -->
  354. <!-- ko if: design.explain() && !design.isRunning() -->
  355. <li><a href="#explanation" data-toggle="tab">${_('Explanation')}</a></li>
  356. <!-- /ko -->
  357. </ul>
  358. <div class="tab-content">
  359. <div class="active tab-pane" id="recentTab">
  360. <div id="recentLoader">
  361. <i class="fa fa-spinner fa-spin" style="font-size: 20px; color: #DDD"></i>
  362. </div>
  363. <table id="recentQueries" class="table table-condensed datatables" cellpadding="0" cellspacing="0" data-tablescroller-enforce-height="true">
  364. <thead>
  365. <tr>
  366. <th>${_('Time')}</th>
  367. <th>${_('Query')}</th>
  368. <th>${_('Result')}</th>
  369. <th>&nbsp;</th>
  370. </tr>
  371. </thead>
  372. <tbody>
  373. </tbody>
  374. </table>
  375. </div>
  376. <div class="tab-pane" id="query">
  377. <pre data-bind="visible: viewModel.design.statement() == ''">${_('There is currently no query to visualize.')}</pre>
  378. <pre data-bind="visible: viewModel.design.statement() != '', text: viewModel.design.statement()"></pre>
  379. </div>
  380. %if ENABLE_QUERY_BUILDER.get():
  381. <div class="tab-pane" id="queryBuilderTab">
  382. <div id="queryBuilderAlert" style="display: none" class="alert">${ _('There are currently no rules defined. To get started, right click on any table column in the SQL Assist panel.') }</div>
  383. <table id="queryBuilder" class="table table-condensed">
  384. <thead>
  385. <tr>
  386. <th width="10%">${ _('Table') }</th>
  387. <th>${ _('Column') }</th>
  388. <th width="10%">${ _('Operation') }</th>
  389. <th width="5%">&nbsp;</th>
  390. <th width="1%">&nbsp;</th>
  391. </tr>
  392. </thead>
  393. </table>
  394. <div class="button-panel">
  395. <button class="btn btn-primary disable-feedback" onclick="generateQuery()">${_('Build query')}</button>
  396. </div>
  397. </div>
  398. %endif
  399. <!-- ko if: design.explain() -->
  400. <div class="tab-pane" id="explanation">
  401. <pre data-bind="text: $root.design.results.explanation()"></pre>
  402. </div>
  403. <!-- /ko -->
  404. <!-- ko if: !design.explain() -->
  405. <div class="tab-pane" id="log">
  406. <div style="position:relative">
  407. <ul data-bind="foreach: $root.design.watch.jobUrls" class="unstyled jobs-overlay">
  408. <li><a data-bind="text: $.trim($data.name), attr: { href: $data.url }" target="_blank"></a></li>
  409. </ul>
  410. <pre data-bind="visible: $root.design.watch.logs().length == 0">${_('There are currently no logs to visualize.')} <img src="${ static('desktop/art/spinner.gif') }" alt="${ _('Spinner') }" data-bind="visible: $root.design.isRunning()"/></pre>
  411. <pre data-bind="visible: $root.design.watch.logs().length > 0, text: $root.design.watch.logs().join('\n')"></pre>
  412. </div>
  413. </div>
  414. <div class="tab-pane" id="columns">
  415. <pre data-bind="visible: $root.design.results.columns().length == 0">${_('There are currently no columns to visualize.')}</pre>
  416. <div data-bind="visible: $root.design.results.columns().length > 10">
  417. <input id="columnFilter" class="input-xlarge" type="text" placeholder="${_('Filter for column name or type...')}" />
  418. </div>
  419. <table class="table table-condensed" cellpadding="0" cellspacing="0">
  420. <tbody data-bind="foreach: $root.design.results.columns">
  421. <tr class="columnRow" data-bind="visible: $index() > 0">
  422. <td rel="columntooltip" data-placement="left" data-bind="attr: {title: '${ _ko("Scroll to the column") }">
  423. <a href="javascript:void(0)" data-row-selector="true" class="column-selector" data-bind="text: $data.name"></a>
  424. </td>
  425. <td class="columnType" data-bind="text: $.trim($data.type)"></td>
  426. </tr>
  427. </tbody>
  428. </table>
  429. </div>
  430. <div class="tab-pane" id="results">
  431. <div data-bind="css: {'hide': design.results.errors().length == 0}" class="alert alert-error">
  432. <p><strong>${_('Fetching results ran into the following error(s):')}</strong></p>
  433. <div data-bind="foreach: design.results.errors">
  434. <p data-bind="text: $data" class="queryErrorMessage"></p>
  435. </div>
  436. </div>
  437. <div data-bind="css: {'hide': !$root.hasResults()}">
  438. <table id="resultTable" class="table table-condensed" cellpadding="0" cellspacing="0" data-tablescroller-enforce-height="true">
  439. <thead>
  440. <tr data-bind="foreach: $root.design.results.columns">
  441. <th data-bind="html: ($index() == 0 ? '&nbsp;' : $data.name), css: { 'sort-numeric': isNumericColumn($data.type), 'sort-date': isDateTimeColumn($data.type), 'sort-string': isStringColumn($data.type), 'datatables-counter-col': $index() == 0}"></th>
  442. </tr>
  443. </thead>
  444. </table>
  445. % if app_name == 'impala':
  446. <a class="pointer" data-bind="visible: $root.scrollNotWorking() && $root.hasMoreResults(), click: manualFetch" style="padding: 10px">${ _('Show more results...') }</a>
  447. % endif
  448. </div>
  449. <div data-bind="css: {'hide': !$root.design.results.empty() || $root.design.results.expired()}" id="resultEmpty">
  450. <pre>${_('The operation has no results.')}</pre>
  451. </div>
  452. <div data-bind="css: {'hide': !$root.design.results.expired()}" id="resultExpired">
  453. <pre>${_('The results have expired, rerun the query if needed.')}</pre>
  454. </div>
  455. </div>
  456. <div class="tab-pane" id="chart">
  457. <pre data-bind="visible: $root.design.results.empty() || $root.design.results.expired()">${_('There is currently no data to build a chart on.')}</pre>
  458. <div class="alert hide">
  459. <strong>${_('Warning:')}</strong> ${_('the results on the chart have been limited to 1000 rows.')}
  460. </div>
  461. <div data-bind="visible: ! $root.design.results.empty() && ! $root.design.results.expired()" style="text-align: center">
  462. <form class="form-inline">
  463. ${_('Chart type')}&nbsp;
  464. <div class="btn-group" data-toggle="buttons-radio">
  465. <a rel="tooltip" data-placement="top" title="${_('Bars')}" id="blueprintBars" href="javascript:void(0)" class="btn"><i class="hcha hcha-bar-chart"></i></a>
  466. <a rel="tooltip" data-placement="top" title="${_('Lines')}" id="blueprintLines" href="javascript:void(0)" class="btn"><i class="hcha hcha-line-chart"></i></a>
  467. <a rel="tooltip" data-placement="top" title="${_('Pie')}" id="blueprintPie" href="javascript:void(0)" class="btn"><i class="hcha hcha-pie-chart"></i></a>
  468. <a rel="tooltip" data-placement="top" title="${_('Map')}" id="blueprintMap" href="javascript:void(0)" class="btn"><i class="hcha hcha-map-chart"></i></a>
  469. </div>&nbsp;&nbsp;
  470. <span id="blueprintAxis" class="hide">
  471. <label>${_('X-Axis')}
  472. <select id="blueprintX" class="blueprintSelect"></select>
  473. </label>&nbsp;&nbsp;
  474. <label>${_('Y-Axis')}
  475. <select id="blueprintY" class="blueprintSelect"></select>
  476. </label>&nbsp;
  477. <div class="btn-group" data-toggle="buttons-radio">
  478. <a rel="tooltip" data-placement="top" title="${_('No sorting')}" id="blueprintNoSort" href="javascript:void(0)" class="btn active"><i class="fa fa-align-left fa-rotate-270"></i></a>
  479. <a rel="tooltip" data-placement="top" title="${_('Sort ascending')}" id="blueprintSortAsc" href="javascript:void(0)" class="btn"><i class="fa fa-sort-amount-asc fa-rotate-270"></i></a>
  480. <a rel="tooltip" data-placement="top" title="${_('Sort descending')}" id="blueprintSortDesc" href="javascript:void(0)" class="btn"><i class="fa fa-sort-amount-desc fa-rotate-270"></i></a>
  481. </div>&nbsp;&nbsp;
  482. </span>
  483. <span id="blueprintLatLng" class="hide">
  484. <label>${_('Latitude')}
  485. <select id="blueprintLat" class="blueprintSelect"></select>
  486. </label>&nbsp;&nbsp;
  487. <label>${_('Longitude')}
  488. <select id="blueprintLng" class="blueprintSelect"></select>
  489. </label>&nbsp;&nbsp;
  490. <label>${_('Label')}
  491. <select id="blueprintDesc" class="blueprintSelect"></select>
  492. </label>
  493. </span>
  494. </form>
  495. </div>
  496. <div data-bind="visible: ! $root.design.results.empty() && ! $root.design.results.expired()" id="blueprint" class="empty center">${_("Please select a chart type.")}</div>
  497. <div style="margin: 10px" data-bind="visible: ! $root.design.results.empty() && ! $root.design.results.expired()">
  498. <div id="pieChart" data-bind="pieChart: {data: {counts: $root.chartData}, fqs: ko.observableArray([]),
  499. transformer: pieChartDataTransformer,
  500. maxWidth: 350 }, visible: $root.chartType() == 'pie'"></div>
  501. <div id="barChart" data-bind="barChart: {datum: {counts: $root.chartData}, fqs: ko.observableArray([]), hideSelection: true,
  502. transformer: barChartDataTransformer}, visible: $root.chartType() == 'bars'"></div>
  503. <div id="lineChart" data-bind="lineChart: {datum: {counts: $root.chartData},
  504. transformer: lineChartDataTransformer,
  505. showControls: false }, visible: $root.chartType() == 'lines'"></div>
  506. <div id="leafletMapChart" data-bind="leafletMapChart: {datum: {counts: $root.chartData},
  507. transformer: leafletMapChartDataTransformer,
  508. showControls: false }, visible: $root.chartType() == 'map'"></div>
  509. </div>
  510. </div>
  511. <!-- /ko -->
  512. </div>
  513. </div>
  514. </div>
  515. </div>
  516. </div>
  517. </div>
  518. <div id="execute-parameter-selection" class="container-fluid hide section">
  519. <div class="row-fluid">
  520. <div class="card card-small">
  521. <h1 class="card-heading simple">${_('Please specify parameters for this query')}</h1>
  522. <div class="card-body">
  523. <p>
  524. <form method="POST" action="" class="form-horizontal">
  525. ${ csrf_token(request) | n,unicode }
  526. <fieldset>
  527. <!-- ko foreach: $root.design.parameters -->
  528. <div class="control-group">
  529. <label data-bind="text: name" class="control-label"></label>
  530. <div class="controls">
  531. <input data-bind="value: value, valueUpdate:'afterkeydown'" type="text"/>
  532. </div>
  533. </div>
  534. <!-- /ko -->
  535. <div class="form-actions" style="padding-left: 10px">
  536. <a class="btn" href="javascript:history.go(-1);">${_('Cancel')}</a>
  537. <button data-bind="enable: $root.hasParametersFilled, click: tryExecuteParameterizedQuery" type="button" class="btn btn-primary">${_('Execute query')}</button>
  538. </div>
  539. </fieldset>
  540. </form>
  541. </p>
  542. </div>
  543. </div>
  544. </div>
  545. </div>
  546. <div id="explain-parameter-selection" class="container-fluid hide section">
  547. <div class="row-fluid">
  548. <div class="card card-small">
  549. <h1 class="card-heading simple">${_('Please specify parameters for this query')}</h1>
  550. <div class="card-body">
  551. <p>
  552. <form method="POST" action="" class="form-horizontal">
  553. ${ csrf_token(request) | n,unicode }
  554. <fieldset>
  555. <!-- ko foreach: $root.design.parameters -->
  556. <div class="control-group">
  557. <label data-bind="text: name" class="control-label"></label>
  558. <div class="controls">
  559. <input data-bind="value: value, valueUpdate:'afterkeydown'" type="text"/>
  560. </div>
  561. </div>
  562. <!-- /ko -->
  563. <div class="form-actions" style="padding-left: 10px">
  564. <a class="btn" href="javascript:history.go(-1);">${_('Cancel')}</a>
  565. <button data-bind="enable: $root.hasParametersFilled, click: tryExplainParameterizedQuery" type="button" class="btn btn-primary">${_('Explain query')}</button>
  566. </div>
  567. </fieldset>
  568. </form>
  569. </p>
  570. </div>
  571. </div>
  572. </div>
  573. </div>
  574. <div id="chooseFolder" class="modal hide fade">
  575. <div class="modal-header">
  576. <button type="button" class="close" data-dismiss="modal" aria-label="${ _('Close') }"><span aria-hidden="true">&times;</span></button>
  577. <h2 class="modal-title">${ _('Select a directory') }</h2>
  578. </div>
  579. <div class="modal-body">
  580. <div id="folderchooser">
  581. </div>
  582. </div>
  583. <div class="modal-footer">
  584. </div>
  585. </div>
  586. <div id="choosePath" class="modal hide fade">
  587. <div class="modal-header">
  588. <button type="button" class="close" data-dismiss="modal" aria-label="${ _('Close') }"><span aria-hidden="true">&times;</span></button>
  589. <h2 class="modal-title">${ _('Select a file or directory') }</h2>
  590. </div>
  591. <div class="modal-body">
  592. <div id="pathchooser">
  593. </div>
  594. </div>
  595. <div class="modal-footer">
  596. </div>
  597. </div>
  598. <div id="saveAs" class="modal hide fade">
  599. <div class="modal-header">
  600. <button type="button" class="close" data-dismiss="modal" aria-label="${ _('Close') }"><span aria-hidden="true">&times;</span></button>
  601. <h2 class="modal-title">${ _('Choose a name') }</h2>
  602. </div>
  603. <form class="form-horizontal">
  604. <div class="control-group" id="saveas-query-name">
  605. <label class="control-label">${_('Name')}</label>
  606. <div class="controls">
  607. <input data-bind="value: $root.design.name, html" type="text" class="input-xlarge">
  608. <span class="help-inline"></span>
  609. </div>
  610. </div>
  611. <div class="control-group" id="saveas-query-description">
  612. <label class="control-label">${_('Description')}</label>
  613. <div class="controls">
  614. <input data-bind="value: $root.design.description, html" type="text" class="input-xlarge">
  615. <span class="help-inline"></span>
  616. </div>
  617. </div>
  618. </form>
  619. <div class="modal-footer">
  620. <button class="btn" data-dismiss="modal">${_('Cancel')}</button>
  621. <button data-bind="click: trySaveAsDesign" class="btn btn-primary">${_('Save')}</button>
  622. </div>
  623. </div>
  624. <div id="saveResultsModal" class="modal hide fade">
  625. <div class="loader">
  626. <div class="overlay"></div>
  627. <i class="fa fa-spinner fa-spin"></i>
  628. </div>
  629. <div class="modal-header">
  630. <button type="button" class="close" data-dismiss="modal" aria-label="${ _('Close') }"><span aria-hidden="true">&times;</span></button>
  631. <h2 class="modal-title">${ _('Save Query Results') }</h2>
  632. </div>
  633. <div class="modal-body" style="padding: 4px">
  634. <!-- ko if: $root.design.results.save.saveTargetError() -->
  635. <h4 data-bind="text: $root.design.results.save.saveTargetError()"></h4>
  636. <!-- /ko -->
  637. <!-- ko if: $root.design.results.save.targetTableError() -->
  638. <h4 data-bind="text: $root.design.results.save.targetTableError()"></h4>
  639. <!-- /ko -->
  640. <!-- ko if: $root.design.results.save.targetDirectoryError() -->
  641. <h4 data-bind="text: $root.design.results.save.targetDirectoryError()"></h4>
  642. <!-- /ko -->
  643. <form id="saveResultsForm" method="POST" class="form form-inline">
  644. ${ csrf_token(request) | n,unicode }
  645. <fieldset>
  646. <div data-bind="css: {'error': $root.design.results.save.targetFileError()}" class="control-group">
  647. <div class="controls">
  648. <label class="radio">
  649. <input data-bind="checked: $root.design.results.save.type" type="radio" name="save-results-type" value="hdfs-file">
  650. &nbsp;${ _('In an HDFS file') }
  651. </label>
  652. <span data-bind="visible: $root.design.results.save.type() == 'hdfs-file'">
  653. <input data-bind="value: $root.design.results.save.path" type="text" name="target_file" placeholder="${_('Path to CSV file')}" class="pathChooser">
  654. </span>
  655. <label class="radio" data-bind="visible: $root.design.results.save.type() == 'hdfs-file'">
  656. <input data-bind="checked: $root.design.results.save.overwrite" type="checkbox" name="overwrite">
  657. ${ _('Overwrite') }
  658. </label>
  659. </div>
  660. </div>
  661. <div data-bind="css: {'error': $root.design.results.save.targetTableError()}" class="control-group">
  662. <div class="controls">
  663. <label class="radio">
  664. <input data-bind="checked: $root.design.results.save.type" type="radio" name="save-results-type" value="hive-table">
  665. &nbsp;${ _('In a new table') }
  666. </label>
  667. <span data-bind="visible: $root.design.results.save.type() == 'hive-table'">
  668. <input data-bind="value: $root.design.results.save.path" type="text" name="target_table" class="span4" placeholder="${_('Table name or <database name>.<table name>')}">
  669. </span>
  670. </div>
  671. </div>
  672. <div data-bind="css: {'error': $root.design.results.save.targetDirectoryError()}" class="control-group hide advanced">
  673. <div class="controls">
  674. <label class="radio">
  675. <input data-bind="checked: $root.design.results.save.type" type="radio" name="save-results-type" value="hdfs-directory">
  676. &nbsp;${ _('Big Query in HDFS') }
  677. </label>
  678. <span data-bind="visible: $root.design.results.save.type() == 'hdfs-directory'">
  679. <input data-bind="value: $root.design.results.save.path" type="text" name="target_dir" placeholder="${_('Path to directory')}" class="folderChooser">
  680. <i class="fa fa-question-circle" id="hdfs-directory-help"></i>
  681. </span>
  682. </div>
  683. </div>
  684. </fieldset>
  685. </form>
  686. <div id="hdfs-directory-help-content" class="hide">
  687. <p>${ _("Use this option if you have a large result. It will rerun the entire query and save the results to the chosen HDFS directory.") }</p>
  688. </div>
  689. </div>
  690. <div class="modal-footer">
  691. % if app_name != 'impala':
  692. <a id="save-results-advanced" href="javascript:void(0)" class="pull-left">${ _('Show advanced fields') }</a>
  693. % endif
  694. <a id="save-results-simple" href="javascript:void(0)" class="pull-left hide">${ _('Hide advanced fields') }</a>
  695. <button class="btn" data-dismiss="modal">${_('Cancel')}</button>
  696. <button data-bind="click: trySaveResults" class="btn btn-primary disable-feedback">${_('Save')}</button>
  697. </div>
  698. </div>
  699. </div>
  700. <div id="clearHistoryModal" class="modal hide fade">
  701. <div class="modal-header">
  702. <button type="button" class="close" data-dismiss="modal" aria-label="${ _('Close') }"><span aria-hidden="true">&times;</span></button>
  703. <h2 class="modal-title">${ _('Confirm History Clear') }</h2>
  704. </div>
  705. <div class="modal-body">
  706. <p>${_('Are you sure you want to clear the query history?')}</p>
  707. </div>
  708. <div class="modal-footer">
  709. <a class="btn" data-dismiss="modal">${_('No')}</a>
  710. <a class="btn btn-danger disable-feedback" onclick="viewModel.clearQueryHistory()">${_('Yes')}</a>
  711. </div>
  712. </div>
  713. %if ENABLE_QUERY_BUILDER.get():
  714. <div id="invalidQueryBuilder" class="modal hide fade">
  715. <div class="modal-header">
  716. <button type="button" class="close" data-dismiss="modal" aria-label="${ _('Close') }"><span aria-hidden="true">&times;</span></button>
  717. <h2 class="modal-title">${ _('Invalid Query') }</h2>
  718. </div>
  719. <div class="modal-body">
  720. <p>${_('Query requires a select or an aggregate.')}</p>
  721. </div>
  722. <div class="modal-footer">
  723. <a class="btn" data-dismiss="modal">${_('Close')}</a>
  724. </div>
  725. </div>
  726. %endif
  727. ${ commonshare() | n,unicode }
  728. <script>
  729. var SqlAutocompleter2 = {};
  730. </script>
  731. <script src="${ static('desktop/js/hue.routie.js') }" type="text/javascript" charset="utf-8"></script>
  732. <script src="${ static('beeswax/js/beeswax.vm.js') }"></script>
  733. <script src="${ static('desktop/js/share.vm.js') }"></script>
  734. %if ENABLE_QUERY_BUILDER.get():
  735. <!-- For query builder -->
  736. <link rel="stylesheet" href="${ static('desktop/ext/css/jquery.contextMenu.min.css') }">
  737. <script src="${ static('desktop/ext/js/jquery/plugins/jquery.contextMenu.min.js') }"></script>
  738. <script src="${ static('desktop/js/queryBuilder.js') }"></script>
  739. <script>
  740. // query-builder-menu is the class to use
  741. // Callback will run after each rule add, just focus to the queryBuilder tab
  742. QueryBuilder.bindMenu('.query-builder-menu', function () {
  743. $("a[href='#queryBuilderTab']").click();
  744. });
  745. function generateQuery() {
  746. var result = QueryBuilder.buildHiveQuery();
  747. if (result.status == "fail") {
  748. $("#invalidQueryBuilder").modal("show");
  749. } else {
  750. codeMirror.setValue(result.query);
  751. codeMirror.focus();
  752. }
  753. }
  754. window.setInterval(function(){
  755. if ($('#queryBuilder tbody').length > 0 && $('#queryBuilder tbody').find('tr').length > 0){
  756. $('.button-panel').show();
  757. $('#queryBuilder').show();
  758. $('#queryBuilderAlert').hide();
  759. }
  760. else {
  761. $('.button-panel').hide();
  762. $('#queryBuilder').hide();
  763. $('#queryBuilderAlert').show();
  764. }
  765. }, 500);
  766. </script>
  767. <!-- End query builder imports -->
  768. %endif
  769. <script src="${ static('desktop/ext/js/codemirror-3.11.js') }"></script>
  770. <link rel="stylesheet" href="${ static('desktop/ext/css/codemirror.css') }">
  771. <script src="${ static('desktop/js/codemirror-hql.js') }"></script>
  772. % if app_name == 'impala':
  773. <script src="${ static('desktop/js/codemirror-isql-hint.js') }"></script>
  774. % else:
  775. <script src="${ static('desktop/js/codemirror-hql-hint.js') }"></script>
  776. % endif
  777. <script src="${ static('desktop/js/codemirror-show-hint.js') }"></script>
  778. <link href="${ static('desktop/ext/css/bootstrap-editable.css') }" rel="stylesheet">
  779. <script src="${ static('beeswax/js/stats.utils.js') }"></script>
  780. <style type="text/css">
  781. h1 {
  782. margin-bottom: 5px;
  783. }
  784. .panel-container {
  785. width: 100%;
  786. position: relative;
  787. }
  788. .left-panel {
  789. position: fixed !important;
  790. z-index: 1030;
  791. outline: none !important;
  792. }
  793. .mega-popover .popover-content {
  794. min-height: 190px !important;
  795. }
  796. .mega-popover .content {
  797. height: auto !important;
  798. max-height: 280px;
  799. }
  800. .resizer {
  801. position: fixed !important;
  802. margin-left: 15px;
  803. width: 20px;
  804. text-align: center;
  805. z-index: 1000;
  806. }
  807. .resize-bar {
  808. top: 50%;
  809. position: relative;
  810. cursor: ew-resize;
  811. }
  812. .content-panel {
  813. position: absolute;
  814. outline: none !important;
  815. }
  816. #chooseFile, #chooseFolder, #choosePath {
  817. z-index: 1100;
  818. }
  819. #filechooser, #folderchooser, #pathchooser {
  820. min-height: 100px;
  821. overflow-y: auto;
  822. }
  823. .control-group {
  824. margin-bottom: 3px !important;
  825. }
  826. .control-group label {
  827. float: left;
  828. padding-top: 5px;
  829. text-align: left;
  830. width: 40px;
  831. }
  832. .control-group label.radio {
  833. float: none;
  834. width: auto;
  835. }
  836. .sidebar-nav {
  837. margin-bottom: 90px !important;
  838. }
  839. .paramContainer {
  840. padding-top: 3px!important;
  841. padding-left: 0px!important;
  842. padding-right: 0px!important;
  843. }
  844. .param {
  845. margin-bottom: 5px;
  846. padding:4px;
  847. padding-left:8px;
  848. border-bottom: 1px solid #F6F6F6;
  849. }
  850. .param:nth-child(even) {
  851. background-color: #F0F0F0;
  852. }
  853. .table-actions {
  854. position: absolute;
  855. right: 0;
  856. padding-left: 3px;
  857. background-color: #FFF;
  858. }
  859. .preview-data {
  860. margin-right: 5px;
  861. }
  862. .remove {
  863. float: right;
  864. }
  865. .CodeMirror {
  866. border: 1px solid #eee;
  867. margin-bottom: 20px;
  868. }
  869. .editorError {
  870. color: #B94A48;
  871. background-color: #F2DEDE;
  872. padding: 4px;
  873. font-size: 11px;
  874. }
  875. .editable-empty, .editable-empty:hover {
  876. color: #666;
  877. font-style: normal;
  878. }
  879. .tooltip.left {
  880. margin-left: -13px;
  881. }
  882. .fullscreen {
  883. position: fixed;
  884. top: -16px;
  885. left: 0;
  886. width: 100%;
  887. background-color: #FFFFFF;
  888. z-index: 2000;
  889. }
  890. body.fullscreen {
  891. overflow: hidden;
  892. }
  893. .map {
  894. height: 200px;
  895. }
  896. #resultTable td, #resultTable th {
  897. white-space: nowrap;
  898. border-right: 1px solid #e5e5e5;
  899. }
  900. .tab-content {
  901. min-height: 100px;
  902. }
  903. .columnType {
  904. text-align: right!important;
  905. color: #999;
  906. }
  907. #queryContainer {
  908. margin-bottom: 0;
  909. }
  910. #resizePanel a {
  911. position: absolute;
  912. cursor: ns-resize;
  913. color: #666;
  914. margin-left: auto;
  915. margin-right: auto;
  916. }
  917. .resultsContainer {
  918. margin-top: 20px;
  919. }
  920. #recentQueries {
  921. width: 100%;
  922. }
  923. #recentQueries code {
  924. cursor: pointer;
  925. white-space: normal;
  926. }
  927. #recentQueries tr td:first-child {
  928. white-space: nowrap;
  929. }
  930. .table-container {
  931. margin-right:10px;
  932. }
  933. #navigator .card-body {
  934. margin-top: 1px !important;
  935. padding: 7px !important;
  936. }
  937. #navigator .nav-header {
  938. padding-left: 0;
  939. }
  940. #navigator .control-group {
  941. padding-left: 0;
  942. }
  943. #navigator .nav-list > li.white, #navigator .nav-list .nav-header {
  944. margin: 0;
  945. }
  946. #saveResultsModal .overlay {
  947. background: black; opacity: 0.5;
  948. position: absolute;
  949. top: 0px;
  950. right:0px;
  951. left: 0px;
  952. bottom: 0px;
  953. z-index: 100;
  954. }
  955. #saveResultsModal .loader {
  956. text-align: center;
  957. position: absolute;
  958. top: 0px;
  959. right:0px;
  960. left: 0px;
  961. bottom: 0px;
  962. }
  963. #saveResultsModal i.fa-spinner, #saveResultsModal img.spinner {
  964. margin-top: -30px;
  965. margin-left: -30px;
  966. position: absolute;
  967. top: 50%;
  968. left: 50%;
  969. z-index: 101;
  970. }
  971. #saveResultsModal i.fa-spinner {
  972. font-size: 60px;
  973. color: #DDD;
  974. }
  975. .tooltip {
  976. z-index: 10001;
  977. }
  978. .filesField, .functionsField, .classNamesField, .settingsField, .settingValuesField {
  979. width: 60%;
  980. }
  981. .fileChooser, .folderChooser {
  982. border-radius: 3px 0 0 3px !important;
  983. border-right: 0 !important;
  984. }
  985. .pull-right.hover-actions, .pull-right.blue {
  986. margin-top: -4px;
  987. }
  988. .query-right-actions {
  989. margin-right: 10px;
  990. }
  991. .query-right-actions h4 {
  992. padding: 0 10px;
  993. }
  994. </style>
  995. <link rel="stylesheet" href="${ static('desktop/ext/css/hue-filetypes.css') }">
  996. <script src="${ static('desktop/ext/js/jquery/plugins/jquery-fieldselection.js') }" type="text/javascript"></script>
  997. <script type="text/javascript">
  998. // avoid blinking of the panels
  999. var leftPanelWidth = $.totalStorage("${app_name}_left_panel_width") != null ? $.totalStorage("${app_name}_left_panel_width") : 250;
  1000. $(".left-panel").css("width", leftPanelWidth + "px");
  1001. $(".content-panel").css("left", leftPanelWidth + 20 + "px");
  1002. var codeMirror, dataTable, renderRecent, syncWithHive;
  1003. var HIVE_AUTOCOMPLETE_BASE_URL = "${ autocomplete_base_url | n,unicode }";
  1004. var HIVE_AUTOCOMPLETE_FAILS_QUIETLY_ON = [500]; // error codes from beeswax/views.py - autocomplete
  1005. var HIVE_AUTOCOMPLETE_USER = "${ user }";
  1006. var HIVE_AUTOCOMPLETE_APP = "${app_name}";
  1007. var STATS_PROBLEMS = "${ _('There was a problem loading the stats.') }";
  1008. var snippetType = HIVE_AUTOCOMPLETE_APP == "impala" ? "impala" : "hive";
  1009. var editorViewModelOptions = {
  1010. snippetViewSettings: {},
  1011. languages: [],
  1012. user: HIVE_AUTOCOMPLETE_USER
  1013. };
  1014. editorViewModelOptions.snippetViewSettings[snippetType] = {
  1015. sqlDialect: true
  1016. };
  1017. editorViewModelOptions.languages.push({
  1018. type: snippetType,
  1019. name: HIVE_AUTOCOMPLETE_APP == "impala" ? "Impala" : "Hive"
  1020. });
  1021. var apiHelper = window.apiHelper;
  1022. var editorViewModel = {
  1023. sqlSourceTypes: [{
  1024. type: snippetType,
  1025. name: HIVE_AUTOCOMPLETE_APP == "impala" ? "Impala" : "Hive"
  1026. }]
  1027. };
  1028. var snippet = {
  1029. type: ko.observable(snippetType),
  1030. isSqlDialect: ko.observable(true),
  1031. database: ko.observable()
  1032. };
  1033. var autocompleter = new AceAutocompleteWrapper({
  1034. snippet: snippet,
  1035. user: HIVE_AUTOCOMPLETE_USER,
  1036. oldEditor: true,
  1037. optEnabled: false,
  1038. timeout: AUTOCOMPLETE_TIMEOUT
  1039. });
  1040. var totalStorageUserPrefix = apiHelper.getTotalStorageUserPrefix(snippetType);
  1041. var truncateOutput = function (obj) {
  1042. //default to 20 characters (column output displays first 21 chars so we need to consider the length of both column name and type
  1043. var chars = obj.chars || 20,
  1044. name = obj.name || '',
  1045. type = obj.type || '',
  1046. output = name.length + type.length,
  1047. suffix = '',
  1048. trim;
  1049. if (output > chars) {
  1050. trim = Math.abs((output + 4) - chars); // 4 accounts for ellipsis, spaces, parenthesis
  1051. type = type.slice(0, Math.abs(type.length - trim));
  1052. suffix = '&hellip;';
  1053. }
  1054. return hueUtils.escapeOutput(type) + suffix;
  1055. };
  1056. var reinitTimeout = -1;
  1057. function onPanelPosition() {
  1058. placeResizePanelHandle();
  1059. window.clearTimeout(reinitTimeout);
  1060. reinitTimeout = window.setTimeout(function () {
  1061. reinitializeTableExtenders();
  1062. }, 50);
  1063. }
  1064. function placeResizePanelHandle() {
  1065. // dynamically positioning the resize panel handle since IE doesn't play well with styles.
  1066. $("#resizePanel a").css("left", $("#resizePanel").position().left + $("#resizePanel").width()/2 - 8);
  1067. }
  1068. function reinitializeTableExtenders() {
  1069. if (viewModel.design.results.columns().length > 0 && viewModel.design.results.columns().length < 500) {
  1070. $("#resultTable").jHueTableExtender({
  1071. fixedHeader: true,
  1072. fixedFirstColumn: true,
  1073. includeNavigator: false,
  1074. clonedContainerPosition: "absolute"
  1075. });
  1076. }
  1077. $("#recentQueries").jHueTableExtender({
  1078. fixedHeader: true,
  1079. includeNavigator: false,
  1080. clonedContainerPosition: "absolute"
  1081. });
  1082. }
  1083. var CURRENT_CODEMIRROR_SIZE = 100;
  1084. var INITIAL_CODEMIRROR_SIZE = CURRENT_CODEMIRROR_SIZE;
  1085. var CODEMIRROR_MANUALLY_RESIZED = false;
  1086. var INITIAL_HORIZONTAL_RESIZE_POSITION = -1;
  1087. // Navigator, recent queries
  1088. $(document).ready(function () {
  1089. $(document).on('click', '.assist-table .fa-list', function(){ $('.modal-backdrop').before($('#assistQuickLook')) });
  1090. $("#resizePanel a").draggable({
  1091. axis: "y",
  1092. start: function (e, ui) {
  1093. CODEMIRROR_MANUALLY_RESIZED = true;
  1094. draggableHelper($(this), e, ui);
  1095. },
  1096. drag: function (e, ui) {
  1097. draggableHelper($(this), e, ui);
  1098. $(".jHueTableExtenderClonedContainer").hide();
  1099. $(".jHueTableExtenderClonedContainerColumn").hide();
  1100. $(".jHueTableExtenderClonedContainerCell").hide();
  1101. },
  1102. stop: function (e, ui) {
  1103. draggableHelper($(this), e, ui);
  1104. $(".jHueTableExtenderClonedContainer").show();
  1105. $(".jHueTableExtenderClonedContainerColumn").show();
  1106. $(".jHueTableExtenderClonedContainerCell").show();
  1107. reinitializeTableExtenders();
  1108. }
  1109. });
  1110. function checkForInitialSplitterPosition() {
  1111. INITIAL_HORIZONTAL_RESIZE_POSITION = $("#resizePanel a").position().top;
  1112. if (INITIAL_HORIZONTAL_RESIZE_POSITION <= 0) {
  1113. window.setTimeout(checkForInitialSplitterPosition, 200);
  1114. }
  1115. }
  1116. checkForInitialSplitterPosition();
  1117. function resizeCodeMirror(el) {
  1118. CURRENT_CODEMIRROR_SIZE = INITIAL_CODEMIRROR_SIZE + (el.position().top - INITIAL_HORIZONTAL_RESIZE_POSITION);
  1119. if (CURRENT_CODEMIRROR_SIZE < 100) {
  1120. CURRENT_CODEMIRROR_SIZE = 100;
  1121. }
  1122. codeMirror.setSize("99%", CURRENT_CODEMIRROR_SIZE);
  1123. }
  1124. function draggableHelper(el, e, ui) {
  1125. resizeCodeMirror(el);
  1126. var minHandlePosition = $('.card-heading.simple').is(':visible') ? $('.card-heading.simple').outerHeight() + 205 : 205;
  1127. if (ui.position.top < minHandlePosition) {
  1128. ui.position.top = minHandlePosition;
  1129. }
  1130. }
  1131. var recentQueries = $("#recentQueries").dataTable({
  1132. "bPaginate": false,
  1133. "bLengthChange": false,
  1134. "bInfo": false,
  1135. "bFilter": false,
  1136. "aoColumns": [
  1137. { "sWidth" : "100px", "sSortDataType":"dom-sort-value", "sType":"numeric" },
  1138. null,
  1139. { "sWidth" : "80px", "bSortable": false },
  1140. { "bSortable": false, "sWidth" : "4px" }
  1141. ],
  1142. "aaSorting": [
  1143. [0, 'desc']
  1144. ],
  1145. "oLanguage": {
  1146. "sEmptyTable": "${_('No data available')}",
  1147. "sInfo": "${_('Showing _START_ to _END_ of _TOTAL_ entries')}",
  1148. "sInfoEmpty": "${_('Showing 0 to 0 of 0 entries')}",
  1149. "sInfoFiltered": "${_('(filtered from _MAX_ total entries)')}",
  1150. "sZeroRecords": "${_('No matching records')}",
  1151. "oPaginate": {
  1152. "sFirst": "${_('First')}",
  1153. "sLast": "${_('Last')}",
  1154. "sNext": "${_('Next')}",
  1155. "sPrevious": "${_('Previous')}"
  1156. }
  1157. }
  1158. });
  1159. renderRecent = function() {
  1160. $("#recentLoader").show();
  1161. $("#recentQueries").hide();
  1162. recentQueries.fnClearTable();
  1163. $.getJSON("${ url(app_name + ':list_query_history') }?format=json&recent=true", function(data) {
  1164. if (data && data.queries) {
  1165. var _rows = [];
  1166. $(data.queries).each(function(cnt, item){
  1167. _rows.push([
  1168. '<span data-sort-value="' + item.timeInMs + '">' + moment(item.timeInMs*1000).format("L LTS") + '</span>',
  1169. '<code style="cursor:pointer">' + item.query + '</code>',
  1170. (item.resultsUrl != "" ? '<a href="' + item.resultsUrl + '" data-row-selector-exclude="true">${_('See results...')}</a>': ''),
  1171. (item.designUrl != "" ? '<a href="' + item.designUrl + '" data-row-selector="true">&nbsp;</a>': '')
  1172. ]);
  1173. });
  1174. recentQueries.fnAddData(_rows);
  1175. if (_rows.length > 0){
  1176. $(".clear-queries").show();
  1177. }
  1178. else {
  1179. $(".clear-queries").hide();
  1180. }
  1181. }
  1182. $("a[data-row-selector='true']").jHueRowSelector();
  1183. $("#recentLoader").hide();
  1184. $("#recentQueries").show().css("width", "100%");
  1185. reinitializeTableExtenders();
  1186. });
  1187. };
  1188. renderRecent();
  1189. $("#navigatorSearch").jHueDelayedInput(function(){
  1190. $("#navigatorTables li").removeClass("hide");
  1191. $("#navigatorTables li").each(function () {
  1192. if ($(this).text().toLowerCase().indexOf($("#navigatorSearch").val().toLowerCase()) == -1) {
  1193. $(this).addClass("hide");
  1194. }
  1195. });
  1196. });
  1197. $("#columnFilter").jHueDelayedInput(function(){
  1198. $(".columnRow").removeClass("hide");
  1199. $(".columnRow").each(function () {
  1200. if ($(this).text().toLowerCase().indexOf($("#columnFilter").val().toLowerCase()) == -1) {
  1201. $(this).addClass("hide");
  1202. }
  1203. });
  1204. });
  1205. var lastWindowHeight = -1;
  1206. var resizeNavigator = function () {
  1207. var newHeight = $(window).height();
  1208. if (lastWindowHeight !== newHeight) {
  1209. $(".resizer").css("height", (newHeight - 90) + "px");
  1210. $("#navigator .card").css("height", (newHeight - 130) + "px").css("overflow-y", "hidden");
  1211. lastWindowHeight = newHeight;
  1212. }
  1213. };
  1214. resizeNavigator();
  1215. $(window).on("scroll", resizeNavigator);
  1216. $(window).on("resize", resizeNavigator);
  1217. window.setInterval(resizeNavigator, 500);
  1218. $(document).on("click", "#expandResults", function(){
  1219. $("#resultTablejHueTableExtenderClonedContainer").remove();
  1220. $("#resultTablejHueTableExtenderClonedContainerColumn").remove();
  1221. $("#resultTablejHueTableExtenderClonedContainerCell").remove();
  1222. if ($(this).find("i").hasClass("fa-expand")){
  1223. $(this).find("i").removeClass("fa-expand").addClass("fa-compress");
  1224. $(this).parents('.resultsContainer').addClass("fullscreen");
  1225. $('body').addClass("fullscreen");
  1226. }
  1227. else {
  1228. $(this).find("i").addClass("fa-expand").removeClass("fa-compress");
  1229. $(this).parents('.resultsContainer').removeClass("fullscreen");
  1230. $('body').removeClass("fullscreen");
  1231. }
  1232. window.setTimeout(reinitializeTable, 200);
  1233. });
  1234. $(document).on("click", ".column-selector", function () {
  1235. var _t = $("#resultTable");
  1236. var _text = $.trim($(this).text().split("(")[0]);
  1237. var _col = _t.find("th").filter(function() {
  1238. return $.trim($(this).text()) == _text;
  1239. });
  1240. _t.find(".columnSelected").removeClass("columnSelected");
  1241. _t.find("tr td:nth-child(" + (_col.index() + 1) + ")").addClass("columnSelected");
  1242. $("a[href='#results']").click();
  1243. });
  1244. $(document).on("clear.history", function() {
  1245. renderRecent();
  1246. $("#clearHistoryModal").modal("hide");
  1247. });
  1248. $(document).on("shown", "a[data-toggle='tab']:not(.sidetab)", function (e) {
  1249. if ($(e.target).attr("href") == "#log" || $(e.target).attr("href") == "#query" ) {
  1250. logsAtEnd = true;
  1251. window.setTimeout(resizeLogs, 100);
  1252. }
  1253. if ($(e.target).attr("href") == "#results" && $(e.relatedTarget).attr("href") == "#columns") {
  1254. if ($("#resultTable .columnSelected").length > 0) {
  1255. var _t = $("#resultTable");
  1256. var _col = _t.find("th:nth-child(" + ($("#resultTable .columnSelected").index() + 1) + ")");
  1257. _t.parent().animate({
  1258. scrollLeft: _col.position().left + _t.parent().scrollLeft() - _t.parent().offset().left - 30
  1259. }, 300);
  1260. }
  1261. }
  1262. if ($(e.target).attr("href") == "#results" || $(e.target).attr("href") == "#recentTab") {
  1263. reinitializeTableExtenders();
  1264. }
  1265. if ($(e.target).attr("href") != "#results" && $(e.target).attr("href") != "#columns"){
  1266. $($(e.target).attr("href")).css('height', 'auto');
  1267. if ($(e.target).attr("href") == "#chart") {
  1268. hueAnalytics.log('beeswax', 'results/chart');
  1269. predictGraph();
  1270. }
  1271. } else {
  1272. reinitializeTable();
  1273. }
  1274. return e;
  1275. });
  1276. });
  1277. // Codemirror query field
  1278. function getHighlightedQuery() {
  1279. var selection = codeMirror.getSelection();
  1280. if (selection != "") {
  1281. return selection;
  1282. }
  1283. return null;
  1284. }
  1285. function reinitializeTable(max) {
  1286. var _max = max || 10;
  1287. var _heightCorrection = $('body').hasClass('fullscreen') ? 85 : 150;
  1288. function fn(){
  1289. var container = $($("a[data-toggle='tab']:not(.sidetab)").parent(".active").find("a").attr("href"));
  1290. if ($("#results .dataTables_wrapper").height() > 0) {
  1291. $("#results .dataTables_wrapper").jHueTableScroller({
  1292. minHeight: $(window).height() - _heightCorrection,
  1293. heightAfterCorrection: 0
  1294. });
  1295. $("#recentTab .dataTables_wrapper").jHueTableScroller({
  1296. minHeight: $(window).height() - _heightCorrection,
  1297. heightAfterCorrection: 0
  1298. });
  1299. reinitializeTableExtenders();
  1300. container.height($(window).height() - _heightCorrection);
  1301. $("#results .dataTables_wrapper").jHueScrollUp();
  1302. } else if ($('#resultEmpty').height() > 0) {
  1303. container.height($('#resultEmpty').height());
  1304. } else if ($('#resultExpired').height() > 0) {
  1305. container.height($('#resultExpired').height());
  1306. }
  1307. if ($("#results .dataTables_wrapper").data('original-height') == 0 && --_max != 0) {
  1308. $("#results .dataTables_wrapper").data('original-height', $("#results .dataTables_wrapper").height());
  1309. window.setTimeout(fn, 100);
  1310. }
  1311. if ($("#recentTab .dataTables_wrapper").data('original-height') == 0 && --_max != 0) {
  1312. $("#recentTab .dataTables_wrapper").data('original-height', $("#recentTab .dataTables_wrapper").height());
  1313. window.setTimeout(fn, 100);
  1314. }
  1315. }
  1316. window.setTimeout(fn, 100);
  1317. }
  1318. $(document).ready(function () {
  1319. $.jHueScrollUp();
  1320. var queryPlaceholder = $("<span>").html($("<span>").html("${_('Example: SELECT * FROM tablename, or press CTRL + space')}").text()).text();
  1321. $("#executeQuery").tooltip({
  1322. title: '${_("Press \"tab\", then \"enter\".")}'
  1323. });
  1324. initQueryField();
  1325. function initQueryField() {
  1326. if ($("#queryField").val() == "") {
  1327. $("#queryField").val(queryPlaceholder);
  1328. }
  1329. }
  1330. var queryEditor = $("#queryField")[0];
  1331. % if app_name == 'impala':
  1332. var AUTOCOMPLETE_SET = CodeMirror.impalaSQLHint;
  1333. % else:
  1334. var AUTOCOMPLETE_SET = CodeMirror.hiveQLHint;
  1335. % endif
  1336. CodeMirror.onAutocomplete = function (data, from, to) {
  1337. if (data.indexOf("(") > -1){
  1338. codeMirror.setCursor({line: from.line, ch: from.ch + data.length - 1});
  1339. codeMirror.execCommand("autocomplete");
  1340. }
  1341. if (CodeMirror.tableFieldMagic) {
  1342. codeMirror.replaceRange(" ", from, from);
  1343. codeMirror.setCursor(from);
  1344. codeMirror.execCommand("autocomplete");
  1345. }
  1346. };
  1347. $(document).on("error.autocomplete", function(){
  1348. $(".CodeMirror-spinner").remove();
  1349. });
  1350. function splitStatements(hql) {
  1351. var statements = [];
  1352. var current = "";
  1353. var betweenQuotes = null;
  1354. for (var i = 0, len = hql.length; i < len; i++) {
  1355. var c = hql[i];
  1356. current += c;
  1357. if ($.inArray(c, ['"', "'"]) > -1) {
  1358. if (betweenQuotes == c) {
  1359. betweenQuotes = null;
  1360. }
  1361. else if (betweenQuotes == null) {
  1362. betweenQuotes = c;
  1363. }
  1364. }
  1365. else if (c == ";") {
  1366. if (betweenQuotes == null) {
  1367. statements.push(current);
  1368. current = "";
  1369. }
  1370. }
  1371. }
  1372. if (current != "" && current != ";") {
  1373. statements.push(current);
  1374. }
  1375. return statements;
  1376. }
  1377. function getStatementAtCursor() {
  1378. var _pos = codeMirror.indexFromPos(codeMirror.getCursor());
  1379. var _statements = splitStatements(codeMirror.getValue());
  1380. var _cumulativePos = 0;
  1381. var _statementAtCursor = "";
  1382. var _relativePos = 0;
  1383. for (var i = 0; i < _statements.length; i++) {
  1384. if (_cumulativePos + _statements[i].length >= _pos && _statementAtCursor == "") {
  1385. _statementAtCursor = _statements[i].split("\n").join(" ");
  1386. _relativePos = _pos - _cumulativePos;
  1387. }
  1388. _cumulativePos += _statements[i].length;
  1389. }
  1390. return {
  1391. statement: _statementAtCursor,
  1392. relativeIndex: _relativePos
  1393. };
  1394. }
  1395. CodeMirror.commands.autocomplete = function (cm) {
  1396. $(document.body).on("contextmenu", function (e) {
  1397. e.preventDefault(); // prevents native menu on FF for Mac from being shown
  1398. });
  1399. var pos = cm.cursorCoords();
  1400. if ($(".CodeMirror-spinner").length == 0) {
  1401. $("<i class='fa fa-spinner fa-spin CodeMirror-spinner'></i>").appendTo($("body"));
  1402. }
  1403. $(".CodeMirror-spinner").css("top", pos.top + "px").css("left", (pos.left - 4) + "px").show();
  1404. var _statementAtCursor = getStatementAtCursor();
  1405. var _before = codeMirror.getValue().substr(0, codeMirror.indexFromPos(codeMirror.getCursor()));
  1406. var _after = _statementAtCursor.statement.substr(_statementAtCursor.relativeIndex).replace(/;+$/, "");
  1407. autocompleter.autocomplete(_before, _after, function(suggestions) {
  1408. var isFromDot = _before.match(/.*\.[^ ]*$/) != null;
  1409. var isTable = false;
  1410. var tableFieldMagic = false;
  1411. var hasFromPrefix = false;
  1412. var values = suggestions.map(function(suggestion) {
  1413. if (suggestion.meta === "table") {
  1414. isTable = true; // They're all tables.
  1415. var match = suggestion.value.match(/(\? )?from ([^ ]+)$/i);
  1416. if (match != null) {
  1417. if (typeof match[1] != "undefined") {
  1418. tableFieldMagic = true;
  1419. return match[2];
  1420. } else {
  1421. hasFromPrefix = true;
  1422. }
  1423. }
  1424. return suggestion.value;
  1425. } else {
  1426. return isFromDot ? "." + suggestion.value : suggestion.value;
  1427. }
  1428. }).join(" ");
  1429. if (values.length > 0 && !hasFromPrefix) {
  1430. CodeMirror.fromDot = isFromDot;
  1431. CodeMirror.possibleSoloField = true;
  1432. CodeMirror.tableFieldMagic = tableFieldMagic;
  1433. CodeMirror.possibleTable = isTable && !tableFieldMagic;
  1434. CodeMirror.catalogTables = isTable ? values : "";
  1435. CodeMirror.catalogFields = isTable ? "" : values;
  1436. } else {
  1437. CodeMirror.fromDot = false;
  1438. CodeMirror.possibleSoloField = false;
  1439. CodeMirror.tableFieldMagic = false;
  1440. CodeMirror.possibleTable = false;
  1441. CodeMirror.catalogTables = "";
  1442. CodeMirror.catalogFields = "";
  1443. }
  1444. CodeMirror.showHint(cm, AUTOCOMPLETE_SET);
  1445. });
  1446. };
  1447. codeMirror = CodeMirror(function (elt) {
  1448. queryEditor.parentNode.replaceChild(elt, queryEditor);
  1449. }, {
  1450. value: queryEditor.value,
  1451. readOnly: false,
  1452. lineNumbers: true,
  1453. viewportMargin: Infinity,
  1454. % if app_name == 'impala':
  1455. mode: "text/x-impalaql",
  1456. % else:
  1457. mode: "text/x-hiveql",
  1458. % endif
  1459. extraKeys: {
  1460. "Ctrl-Space": function () {
  1461. codeMirror.execCommand("autocomplete");
  1462. },
  1463. Tab: function (cm) {
  1464. $("#executeQuery").focus();
  1465. }
  1466. },
  1467. onKeyEvent: function (e, s) {
  1468. if (s.type == "keydown" && s.keyCode == 73 && (s.altKey || s.ctrlKey || s.metaKey)) {
  1469. formatQuery();
  1470. }
  1471. if (s.type == "keyup") {
  1472. if (s.keyCode == 190) {
  1473. var _statement = getStatementAtCursor().statement;
  1474. if (_statement.toUpperCase().indexOf("FROM") > -1) {
  1475. window.setTimeout(function () {
  1476. codeMirror.execCommand("autocomplete");
  1477. }, 100); // timeout for IE8
  1478. }
  1479. }
  1480. }
  1481. }
  1482. });
  1483. huePubSub.subscribe('assist.dblClickDbItem', function(assistDbEntry) {
  1484. var text = assistDbEntry.editorText();
  1485. if (codeMirror.getValue() == queryPlaceholder) {
  1486. codeMirror.setValue("");
  1487. if (assistDbEntry.definition.isTable) {
  1488. text = "SELECT * FROM " + assistDbEntry.editorText() + " LIMIT 100";
  1489. }
  1490. else if (assistDbEntry.definition.isColumn) {
  1491. text = "SELECT " + assistDbEntry.editorText().split(",")[0] + " FROM " + assistDbEntry.parent.editorText() + " LIMIT 100";
  1492. }
  1493. }
  1494. codeMirror.replaceSelection(text);
  1495. codeMirror.setSelection(codeMirror.getCursor());
  1496. codeMirror.focus();
  1497. });
  1498. $(".CodeMirror").droppable({
  1499. accept: ".draggableText",
  1500. drop: function (e, ui) {
  1501. var position = codeMirror.coordsChar({"left": e.clientX, "top": e.clientY});
  1502. var text = ui.helper.text();
  1503. codeMirror.setCursor(position);
  1504. var value = codeMirror.getValue();
  1505. var index = codeMirror.indexFromPos(codeMirror.getCursor());
  1506. if (index > 0 && value.charAt(index - 1) !== ' ' && value.charAt(index - 1) !== '.') {
  1507. text = " " + text;
  1508. }
  1509. if ((index + 1) < value.length - 1 && value.charAt(index + 1) !== ' ' && text.charAt(text.length - 1) !== ' ') {
  1510. text += " ";
  1511. }
  1512. codeMirror.replaceSelection(text);
  1513. codeMirror.setSelection(codeMirror.getCursor());
  1514. codeMirror.focus();
  1515. }
  1516. });
  1517. codeMirror.on("focus", function () {
  1518. if (codeMirror.getValue() == queryPlaceholder) {
  1519. codeMirror.setValue("");
  1520. }
  1521. viewModel.queryEditorBlank(true);
  1522. clearErrorWidgets();
  1523. $("#validationResults").empty();
  1524. });
  1525. % if not (design and design.id) and not ( query_history and query_history.id ):
  1526. if ($.totalStorage(totalStorageUserPrefix + "${app_name}_temp_query") != null && $.totalStorage(totalStorageUserPrefix + "${app_name}_temp_query") != "") {
  1527. viewModel.queryEditorBlank(true);
  1528. codeMirror.setValue($.totalStorage(totalStorageUserPrefix + "${app_name}_temp_query"));
  1529. }
  1530. % endif
  1531. codeMirror.on("blur", function () {
  1532. $(document.body).off("contextmenu");
  1533. });
  1534. codeMirror.on("change", function () {
  1535. window.setTimeout(function () {
  1536. if (!CODEMIRROR_MANUALLY_RESIZED && $('.CodeMirror').height() < 270 && codeMirror.lineCount() > 7) {
  1537. CURRENT_CODEMIRROR_SIZE = 270;
  1538. if ($('.card-heading.simple').is(':visible')) {
  1539. INITIAL_CODEMIRROR_SIZE = 270;
  1540. INITIAL_HORIZONTAL_RESIZE_POSITION = $('.card-heading.simple').outerHeight() + 374;
  1541. }
  1542. codeMirror.setSize("99%", CURRENT_CODEMIRROR_SIZE);
  1543. reinitializeTableExtenders();
  1544. }
  1545. }, 200);
  1546. });
  1547. $("#download-excel").click(function () {
  1548. if (viewModel.design.results.columns().length > 255) {
  1549. $.jHueNotify.warn("${ _('Results exceeds maximum number of columns permitted by Excel, will truncate results to 255 columns.') }")
  1550. }
  1551. });
  1552. });
  1553. var editables = function() {
  1554. // Edit query name and description.
  1555. $("#query-name").editable({
  1556. validate: function (value) {
  1557. if ($.trim(value) == '') {
  1558. return "${ _('This field is required.') }";
  1559. }
  1560. },
  1561. success: function (response, newValue) {
  1562. viewModel.design.name(newValue);
  1563. },
  1564. emptytext: "${ _('Query name') }"
  1565. });
  1566. $("#query-description").editable({
  1567. success: function (response, newValue) {
  1568. viewModel.design.description(newValue);
  1569. },
  1570. emptytext: "${ _('Empty description') }"
  1571. });
  1572. $(".fileChooser:not(:has(~ button))").after(hueUtils.getFileBrowseButton($(".fileChooser:not(:has(~ button))")));
  1573. };
  1574. $(document).one('fetched.design', editables);
  1575. $(document).one('fetched.query', editables);
  1576. function isNumericColumn(type) {
  1577. return $.inArray(type, ['TINYINT_TYPE', 'SMALLINT_TYPE', 'INT_TYPE', 'BIGINT_TYPE', 'FLOAT_TYPE', 'DOUBLE_TYPE', 'DECIMAL_TYPE', 'TIMESTAMP_TYPE', 'DATE_TYPE', 'DATETIME_TYPE']) > -1;
  1578. }
  1579. function isDateTimeColumn(type) {
  1580. return $.inArray(type, ['TIMESTAMP_TYPE', 'DATE_TYPE', 'DATETIME_TYPE']) > -1;
  1581. }
  1582. function isStringColumn(type) {
  1583. return !isNumericColumn(type) && !isDateTimeColumn(type);
  1584. }
  1585. var map;
  1586. var graphHasBeenPredicted = false;
  1587. function getMapBounds(lats, lngs) {
  1588. lats = lats.sort();
  1589. lngs = lngs.sort();
  1590. return [
  1591. [lats[lats.length - 1], lngs[lngs.length - 1]], // north-east
  1592. [lats[0], lngs[0]] // south-west
  1593. ]
  1594. }
  1595. function generateGraph(graphType) {
  1596. $("#chart").height(Math.max($(window).height() - $("#blueprint").offset().top + 30, 500));
  1597. $("#chart .alert").addClass("hide");
  1598. if (graphType != "") {
  1599. $("#blueprint").attr("class", "").attr("style", "").empty();
  1600. if (graphType == window.HUE_CHARTS.TYPES.MAP) {
  1601. if ($("#blueprintLat").val() != "-1" && $("#blueprintLng").val() != "-1") {
  1602. var _latCol = $("#blueprintLat").val() * 1;
  1603. var _lngCol = $("#blueprintLng").val() * 1;
  1604. var _descCol = $("#blueprintDesc").val() * 1;
  1605. var _lats = [];
  1606. var _lngs = [];
  1607. $("#resultTable>tbody>tr>td:nth-child(" + _latCol + ")").each(function (cnt) {
  1608. _lats.push($.trim($(this).text()) * 1);
  1609. });
  1610. $("#resultTable>tbody>tr>td:nth-child(" + _lngCol + ")").each(function (cnt) {
  1611. _lngs.push($.trim($(this).text()) * 1);
  1612. });
  1613. var _koData = [];
  1614. try {
  1615. $("#resultTable>tbody>tr>td:nth-child(" + _latCol + ")").each(function (cnt) {
  1616. if (cnt < 1000) {
  1617. if (_descCol != "-1") {
  1618. _koData.push({ lat: $.trim($(this).text()) * 1, lng: $.trim($("#resultTable>tbody>tr:nth-child(" + (cnt + 1) + ")>td:nth-child(" + _lngCol + ")").text()) * 1, label: $.trim($("#resultTable>tbody>tr:nth-child(" + (cnt + 1) + ")>td:nth-child(" + _descCol + ")").text())});
  1619. }
  1620. else {
  1621. _koData.push({ lat: $.trim($(this).text()) * 1, lng: $.trim($("#resultTable>tbody>tr:nth-child(" + (cnt + 1) + ")>td:nth-child(" + _lngCol + ")").text()) * 1});
  1622. }
  1623. }
  1624. });
  1625. viewModel.chartData(_koData);
  1626. }
  1627. catch (err) {
  1628. if (typeof console != "undefined") {
  1629. console.error(err);
  1630. }
  1631. }
  1632. if ($("#resultTable>tbody>tr>td:nth-child(" + _latCol + ")").length > 1000){
  1633. $("#chart .alert").removeClass("hide");
  1634. }
  1635. }
  1636. else {
  1637. $("#blueprint").addClass("empty").css("text-align", "center").text("${_("Please select the latitude and longitude columns.")}");
  1638. }
  1639. }
  1640. else {
  1641. if ($("#blueprintX").val() != "-1" && $("#blueprintY").val() != "-1") {
  1642. var _x = $("#blueprintX").val() * 1;
  1643. var _y = $("#blueprintY").val() * 1;
  1644. var _koData = [];
  1645. $("#resultTable>tbody>tr>td:nth-child(" + _x + ")").each(function (cnt) {
  1646. if (cnt < 1000) {
  1647. _koData.push({ value: $.trim($(this).text()), count: $.trim($("#resultTable>tbody>tr:nth-child(" + (cnt + 1) + ")>td:nth-child(" + _y + ")").text()) * 1});
  1648. }
  1649. });
  1650. viewModel.chartData(_koData);
  1651. if ($("#resultTable>tbody>tr>td:nth-child(" + _x + ")").length > 1000){
  1652. $("#chart .alert").removeClass("hide");
  1653. }
  1654. }
  1655. else {
  1656. $("#blueprint").addClass("empty").css("text-align", "center").text("${_("Please select the columns you would like to see in this chart.")}");
  1657. }
  1658. }
  1659. }
  1660. }
  1661. function getGraphType() {
  1662. var _type = "";
  1663. if ($("#blueprintBars").hasClass("active")) {
  1664. _type = window.HUE_CHARTS.TYPES.BARCHART;
  1665. }
  1666. if ($("#blueprintLines").hasClass("active")) {
  1667. _type = window.HUE_CHARTS.TYPES.LINECHART;
  1668. }
  1669. if ($("#blueprintMap").hasClass("active")) {
  1670. _type = window.HUE_CHARTS.TYPES.MAP;
  1671. }
  1672. if ($("#blueprintPie").hasClass("active")) {
  1673. _type = window.HUE_CHARTS.TYPES.PIECHART;
  1674. }
  1675. viewModel.chartType(_type);
  1676. return _type;
  1677. }
  1678. function predictGraph() {
  1679. if (!graphHasBeenPredicted) {
  1680. graphHasBeenPredicted = true;
  1681. var _firstAllString, _firstAllNumeric;
  1682. var _cols = viewModel.design.results.columns();
  1683. $(_cols).each(function (cnt, col) {
  1684. if (cnt > 0){
  1685. if (_firstAllString == null && !isNumericColumn(col.type)) {
  1686. _firstAllString = cnt + 1;
  1687. }
  1688. if (_firstAllNumeric == null && isNumericColumn(col.type)) {
  1689. _firstAllNumeric = cnt + 1;
  1690. }
  1691. }
  1692. });
  1693. if (_firstAllString != null && _firstAllNumeric != null) {
  1694. $("#blueprintBars").addClass("active");
  1695. $("#blueprintLines").removeClass("active");
  1696. $("#blueprintPie").removeClass("active");
  1697. $("#blueprintMap").removeClass("active");
  1698. $("#blueprintAxis").removeClass("hide");
  1699. $("#blueprintLatLng").addClass("hide");
  1700. $("#blueprintX").val(_firstAllString);
  1701. $("#blueprintY").val(_firstAllNumeric);
  1702. }
  1703. }
  1704. generateGraph(getGraphType());
  1705. }
  1706. // Logs
  1707. var logsAtEnd = true;
  1708. $(document).ready(function () {
  1709. var labels = {
  1710. MRJOB: "${_('MR Job')}",
  1711. MRJOBS: "${_('MR Jobs')}"
  1712. };
  1713. $('.assist').css('top', '36px');
  1714. $(window).resize(function () {
  1715. resizeLogs();
  1716. });
  1717. $("a[href='#log']").on("shown", function () {
  1718. resizeLogs();
  1719. });
  1720. $("a[href='#query']").on("shown", function () {
  1721. resizeLogs();
  1722. });
  1723. % if app_name == 'impala':
  1724. $("a[href='#sessionTab']").on("shown", function () {
  1725. // get the impala session info
  1726. viewModel.fetchImpalaSession();
  1727. });
  1728. % endif
  1729. $(".blueprintSelect").on("change", function () {
  1730. generateGraph(getGraphType())
  1731. });
  1732. $("#blueprintBars").on("click", function () {
  1733. $("#blueprintAxis").removeClass("hide");
  1734. $("#blueprintLatLng").addClass("hide");
  1735. viewModel.chartType(window.HUE_CHARTS.TYPES.BARCHART);
  1736. generateGraph(window.HUE_CHARTS.TYPES.BARCHART)
  1737. });
  1738. $("#blueprintLines").on("click", function () {
  1739. $("#blueprintAxis").removeClass("hide");
  1740. $("#blueprintLatLng").addClass("hide");
  1741. viewModel.chartType(window.HUE_CHARTS.TYPES.LINECHART);
  1742. generateGraph(window.HUE_CHARTS.TYPES.LINECHART)
  1743. });
  1744. $("#blueprintPie").on("click", function () {
  1745. $("#blueprintAxis").removeClass("hide");
  1746. $("#blueprintLatLng").addClass("hide");
  1747. viewModel.chartType(window.HUE_CHARTS.TYPES.PIECHART);
  1748. generateGraph(window.HUE_CHARTS.TYPES.PIECHART)
  1749. });
  1750. $("#blueprintMap").on("click", function () {
  1751. $("#blueprintAxis").addClass("hide");
  1752. $("#blueprintLatLng").removeClass("hide");
  1753. viewModel.chartType(window.HUE_CHARTS.TYPES.MAP);
  1754. generateGraph(window.HUE_CHARTS.TYPES.MAP)
  1755. });
  1756. $("#blueprintNoSort").on("click", function () {
  1757. viewModel.chartSorting("none");
  1758. redrawChart();
  1759. });
  1760. $("#blueprintSortAsc").on("click", function () {
  1761. viewModel.chartSorting("asc");
  1762. redrawChart();
  1763. });
  1764. $("#blueprintSortDesc").on("click", function () {
  1765. viewModel.chartSorting("desc");
  1766. redrawChart();
  1767. });
  1768. function redrawChart() {
  1769. generateGraph(viewModel.chartType());
  1770. }
  1771. $("#log pre:eq(1)").scroll(function () {
  1772. if ($(this).scrollTop() + $(this).height() + 20 >= $(this)[0].scrollHeight) {
  1773. logsAtEnd = true;
  1774. }
  1775. else {
  1776. logsAtEnd = false;
  1777. }
  1778. });
  1779. viewModel.design.watch.logs.subscribe(function(val){
  1780. var _logsEl = $("#log pre:eq(1)");
  1781. if (logsAtEnd && _logsEl[0]) {
  1782. _logsEl.scrollTop(_logsEl[0].scrollHeight - _logsEl.height());
  1783. }
  1784. window.setTimeout(resizeLogs, 10);
  1785. });
  1786. viewModel.design.results.columns.subscribe(function(val){
  1787. $("*[rel=columntooltip]").tooltip({
  1788. delay: {show: 500}
  1789. });
  1790. $("a[data-row-selector='true']").jHueRowSelector();
  1791. });
  1792. });
  1793. function resizeLogs() {
  1794. // Use fixed subtraction since logs aren't always visible.
  1795. if ($("#log pre:eq(1)").length > 0) {
  1796. var _height = Math.max($(window).height() - $("#log pre:eq(1)").offset().top, 250);
  1797. $("#log").height(_height - 10);
  1798. $("#log pre:eq(1)").css("overflow", "auto").height(_height - 50);
  1799. }
  1800. if ($("#query pre:eq(1)").length > 0) {
  1801. var _height = Math.max($(window).height() - $("#query pre:eq(1)").offset().top, 250);
  1802. $("#query").height(_height - 10);
  1803. $("#query pre:eq(1)").css("overflow", "auto").height(_height - 50);
  1804. }
  1805. }
  1806. // Result Datatable
  1807. function cleanResultsTable() {
  1808. if (dataTable) {
  1809. viewModel.design.results.rows([]);
  1810. dataTable.fnClearTable();
  1811. dataTable.fnDestroy();
  1812. viewModel.design.results.columns.valueHasMutated();
  1813. viewModel.design.results.rows.valueHasMutated();
  1814. dataTable = null;
  1815. }
  1816. }
  1817. function addRowNumberToResults(data, startIndex) {
  1818. var _tmpdata = [];
  1819. $(data).each(function(cnt, item){
  1820. item.unshift(cnt + startIndex + 1);
  1821. _tmpdata.push(item);
  1822. });
  1823. return _tmpdata;
  1824. }
  1825. var _scrollTimeout = -1;
  1826. function datatableScroll() {
  1827. viewModel.scrollNotWorking(false);
  1828. // Automatic results grower
  1829. var dataTableEl = $("#results .dataTables_wrapper");
  1830. var _lastScrollPosition = dataTableEl.data("scrollPosition") != null ? dataTableEl.data("scrollPosition") : 0;
  1831. window.clearTimeout(_scrollTimeout);
  1832. _scrollTimeout = window.setTimeout(function(){
  1833. dataTableEl.data("scrollPosition", dataTableEl.scrollTop());
  1834. if (_lastScrollPosition != dataTableEl.scrollTop() && dataTableEl.scrollTop() + dataTableEl.outerHeight() + 20 > dataTableEl[0].scrollHeight && dataTable && viewModel.hasMoreResults()) {
  1835. dataTableEl.animate({opacity: '0.55'}, 200);
  1836. viewModel.fetchResults();
  1837. }
  1838. }, 100);
  1839. }
  1840. var firstFnDrawcallback = false;
  1841. var manualFetchResultCounter = 0;
  1842. function addResults(viewModel, dataTable, startRow, nextRow) {
  1843. if (startRow == 0) {
  1844. firstFnDrawcallback = true;
  1845. }
  1846. dataTable.fnAddData(addRowNumberToResults(viewModel.design.results.rows.slice(startRow, nextRow), startRow));
  1847. % if app_name == 'impala':
  1848. manualFetchResultCounter += (nextRow - startRow);
  1849. if (manualFetchResultCounter < 100 && viewModel.scrollNotWorking() && viewModel.hasMoreResults()){
  1850. manualFetch();
  1851. }
  1852. else {
  1853. manualFetchResultCounter = 0;
  1854. }
  1855. %endif
  1856. }
  1857. function resultsTable(e, data) {
  1858. $("#results .dataTables_wrapper").animate({opacity: '1'}, 50);
  1859. $.totalStorage(totalStorageUserPrefix + "${app_name}_temp_query", null);
  1860. if (viewModel.design.results.columns().length > 0) {
  1861. if (!dataTable) {
  1862. if (viewModel.design.results.columns().length < 500) {
  1863. dataTable = $("#resultTable").dataTable({
  1864. "bPaginate": false,
  1865. "bLengthChange": false,
  1866. "bInfo": false,
  1867. "bDestroy": true,
  1868. "bAutoWidth": false,
  1869. "oLanguage": {
  1870. "sEmptyTable": "${_('No data available')}",
  1871. "sZeroRecords": "${_('No matching records')}"
  1872. },
  1873. "fnDrawCallback": function (oSettings) {
  1874. reinitializeTableExtenders();
  1875. if (firstFnDrawcallback) {
  1876. firstFnDrawcallback = false;
  1877. window.setTimeout(reinitializeTable, 100);
  1878. }
  1879. },
  1880. "aoColumnDefs": [
  1881. {
  1882. "sType": "numeric",
  1883. "aTargets": [ "sort-numeric" ]
  1884. },
  1885. {
  1886. "sType": "string",
  1887. "aTargets": [ "sort-string" ]
  1888. },
  1889. {
  1890. "sType": "date",
  1891. "aTargets": [ "sort-date" ]
  1892. }
  1893. ]
  1894. });
  1895. $(".dataTables_filter").hide();
  1896. }
  1897. else {
  1898. dataTable = $("#resultTable").hueDataTable({
  1899. "oLanguage": {
  1900. "sEmptyTable": "${_('No data available')}",
  1901. "sZeroRecords": "${_('No matching records')}"
  1902. },
  1903. "fnDrawCallback": function (oSettings) {
  1904. reinitializeTableExtenders();
  1905. if (firstFnDrawcallback) {
  1906. firstFnDrawcallback = false;
  1907. window.setTimeout(reinitializeTable, 100);
  1908. }
  1909. }
  1910. });
  1911. }
  1912. reinitializeTable();
  1913. var _options = '<option value="-1">${ _("Please select a column")}</option>';
  1914. $(viewModel.design.results.columns()).each(function(cnt, item){
  1915. if (cnt > 0){
  1916. _options += '<option value="'+(cnt + 1)+'">'+ item.name +'</option>';
  1917. }
  1918. });
  1919. $(".blueprintSelect").html(_options);
  1920. // Automatic results grower
  1921. var dataTableEl = $("#results .dataTables_wrapper");
  1922. dataTableEl.on("scroll", datatableScroll);
  1923. }
  1924. addResults(viewModel, dataTable, data.start_row, data.next_row);
  1925. }
  1926. }
  1927. function manualFetch() {
  1928. $("#results .dataTables_wrapper").css("opacity", "0.55");
  1929. viewModel.fetchResults();
  1930. }
  1931. $(document).on('execute.query', cleanResultsTable);
  1932. $(document).on('explain.query', cleanResultsTable);
  1933. $(document).on('fetched.results', resultsTable);
  1934. var selectedLine = -1;
  1935. var errorWidgets = [];
  1936. function clearErrorWidgets() {
  1937. $(".jHueTableExtenderClonedContainer").hide();
  1938. $(".jHueTableExtenderClonedContainerColumn").hide();
  1939. $(".jHueTableExtenderClonedContainerCell").hide();
  1940. $.each(errorWidgets, function(index, errorWidget) {
  1941. errorWidget.clear();
  1942. });
  1943. errorWidgets = [];
  1944. }
  1945. $(document).on('execute.query', clearErrorWidgets);
  1946. $(document).on('explain.query', clearErrorWidgets);
  1947. $(document).on('error.query', function () {
  1948. $.each(errorWidgets, function(index, el) {
  1949. $(el).remove();
  1950. errorWidgets = [];
  1951. });
  1952. // Move error to codeMirror if we know the line number
  1953. $.each($(".queryErrorMessage"), function(index, el) {
  1954. var err = $(el).text();
  1955. var firstPos = err.toLowerCase().indexOf("line");
  1956. if (firstPos > -1) {
  1957. selectedLine = $.trim(err.substring(err.indexOf(" ", firstPos), err.indexOf(":", firstPos))) * 1;
  1958. if (codeMirror.getSelection()) {
  1959. selectedLine += codeMirror.getCursor(true).line;
  1960. }
  1961. errorWidgets.push(
  1962. codeMirror.addLineWidget(
  1963. selectedLine > 0 ? selectedLine - 1 : selectedLine,
  1964. $("<div>").addClass("editorError").text(err)[0], {
  1965. coverGutter: true,
  1966. noHScroll: true
  1967. }
  1968. )
  1969. );
  1970. codeMirror.scrollTo(null, codeMirror.charCoords({
  1971. line: selectedLine > 0 ? selectedLine - 1 : selectedLine,
  1972. ch: 0
  1973. }, "local").top - codeMirror.getScrollerElement().offsetHeight / 2 - 5);
  1974. $(el).hide();
  1975. }
  1976. });
  1977. reinitializeTableExtenders();
  1978. });
  1979. // Save
  1980. function trySaveDesign() {
  1981. var query = codeMirror.getValue();
  1982. viewModel.design.query.value(query);
  1983. if (viewModel.design.id() && viewModel.design.id() != -1) {
  1984. viewModel.saveDesign();
  1985. hueAnalytics.log('beeswax', 'design/save');
  1986. }
  1987. }
  1988. function saveAsModal() {
  1989. var query = getHighlightedQuery() || codeMirror.getValue();
  1990. viewModel.design.query.value(query);
  1991. $('#saveAs').modal('show');
  1992. }
  1993. function trySaveAsDesign() {
  1994. if (viewModel.design.query.value() && viewModel.design.name()) {
  1995. viewModel.design.id(-1);
  1996. viewModel.saveDesign();
  1997. $('#saveAs').find('.help-inline').text('');
  1998. $('#saveAs').find('.control-group').removeClass('error');
  1999. hueAnalytics.log('beeswax', 'design/save-as');
  2000. } else if (viewModel.design.name()) {
  2001. $.jHueNotify.error("${_('No query provided to save.')}");
  2002. $('#saveAs').modal('hide');
  2003. } else {
  2004. $('#saveas-query-name').addClass('error');
  2005. }
  2006. }
  2007. function saveResultsModal() {
  2008. $("#saveResultsModal .loader").hide();
  2009. $('#saveResultsModal').modal('show');
  2010. }
  2011. function trySaveResults() {
  2012. var deferred = viewModel.saveResults();
  2013. if (deferred) {
  2014. $("#saveResultsModal button.btn-primary").button('loading');
  2015. $("#saveResultsModal .loader").show();
  2016. deferred.done(function() {
  2017. $("#saveResultsModal button.btn-primary").button('reset');
  2018. $("#saveResultsModal .loader").hide();
  2019. });
  2020. }
  2021. hueAnalytics.log('beeswax', 'results/save');
  2022. }
  2023. $(document).on('saved.results', function() {
  2024. $('#saveResultsModal').modal('hide');
  2025. });
  2026. // Querying and click events.
  2027. function tryExecuteQuery() {
  2028. viewModel.scrollNotWorking(true);
  2029. $("#results .dataTables_wrapper").off("scroll", datatableScroll);
  2030. $(".jHueTableExtenderClonedContainer").hide();
  2031. $(".jHueTableExtenderClonedContainerColumn").hide();
  2032. $(".jHueTableExtenderClonedContainerCell").hide();
  2033. $(".tooltip").remove();
  2034. var query = getHighlightedQuery() || codeMirror.getValue();
  2035. viewModel.design.query.value(query);
  2036. if ($("#results .dataTables_wrapper").length > 0) { // forces results to be up
  2037. $("#results .dataTables_wrapper").scrollTop(0);
  2038. }
  2039. if ($("#recentQueries .dataTables_wrapper").length > 0) { // forces results to be up
  2040. $("#recentQueries .dataTables_wrapper").scrollTop(0);
  2041. }
  2042. renderRecent();
  2043. clickHard('.resultsContainer .nav-tabs a[href="#log"]');
  2044. graphHasBeenPredicted = false;
  2045. if (viewModel.design.isParameterized()) {
  2046. viewModel.fetchParameters();
  2047. } else {
  2048. viewModel.executeQuery();
  2049. }
  2050. hueAnalytics.log('beeswax', 'query/execute');
  2051. }
  2052. function tryExecuteNextStatement() {
  2053. viewModel.scrollNotWorking(true);
  2054. var query = getHighlightedQuery() || codeMirror.getValue();
  2055. // If we highlight a part of query, we update the query and restart the query history
  2056. // In the other case we update the query but continue at the same statement we were
  2057. if (viewModel.design.query.value() != query) {
  2058. viewModel.design.query.value(query);
  2059. if (getHighlightedQuery()) {
  2060. viewModel.executeQuery();
  2061. } else {
  2062. viewModel.executeNextStatement();
  2063. }
  2064. } else {
  2065. viewModel.executeNextStatement();
  2066. }
  2067. hueAnalytics.log('beeswax', 'query/execute_next');
  2068. }
  2069. function tryExecuteParameterizedQuery() {
  2070. viewModel.scrollNotWorking(true);
  2071. $(".tooltip").remove();
  2072. viewModel.executeQuery();
  2073. routie('query');
  2074. }
  2075. function tryExplainQuery() {
  2076. $(".tooltip").remove();
  2077. var query = getHighlightedQuery() || codeMirror.getValue();
  2078. viewModel.design.query.value(query);
  2079. viewModel.explainQuery();
  2080. hueAnalytics.log('beeswax', 'query/explain');
  2081. }
  2082. function formatQuery() {
  2083. $.post("/notebook/api/format", {
  2084. statements: codeMirror.getSelection() != '' ? codeMirror.getSelection() : codeMirror.getValue()
  2085. }, function (data) {
  2086. if (data.status == 0) {
  2087. if (codeMirror.getSelection() != '') {
  2088. codeMirror.replaceSelection(data.formatted_statements);
  2089. }
  2090. else {
  2091. codeMirror.setValue(data.formatted_statements);
  2092. }
  2093. viewModel.design.query.value(codeMirror.getValue());
  2094. } else {
  2095. $.jHueNotify.error(data);
  2096. }
  2097. });
  2098. }
  2099. function tryExplainParameterizedQuery() {
  2100. $(".tooltip").remove();
  2101. viewModel.explainQuery();
  2102. routie('query');
  2103. }
  2104. function tryCancelQuery() {
  2105. $(".tooltip").remove();
  2106. viewModel.cancelQuery();
  2107. }
  2108. function createNewQuery() {
  2109. $.totalStorage(totalStorageUserPrefix + "${app_name}_temp_query", null);
  2110. location.href="${ url(app_name + ':execute_query') }";
  2111. }
  2112. // Server error handling.
  2113. $(document).on('server.error', function (e, data) {
  2114. $(document).trigger('error', "${_('Server error occurred: ')}" + data.message ? data.message : data.error);
  2115. });
  2116. $(document).on('server.unmanageable_error', function (e, responseText) {
  2117. var message = responseText;
  2118. if (! message) {
  2119. message = '${ _("Hue server is probably down.") }';
  2120. }
  2121. $(document).trigger('error', "${_('Unmanageable server error occurred: ')}" + message);
  2122. });
  2123. // Other
  2124. $(document).on('saved.design', function (e, id) {
  2125. $('#saveAs').modal('hide');
  2126. $(document).trigger('info', "${_('Query saved.')}");
  2127. huePubSub.publish('open.link', "/${ app_name }/execute/design/" + id);
  2128. });
  2129. $(document).on('error_save.design', function (e, message) {
  2130. var _message = "${_('Could not save design')}";
  2131. if (typeof message == "object"){
  2132. $('#saveAs').find('.help-inline').text('');
  2133. $('#saveAs').find('.control-group').removeClass('error');
  2134. if (message.saveform){
  2135. if ($('#saveAs').is(":visible")){
  2136. if (message.saveform.name){
  2137. $('#saveas-query-name').addClass('error');
  2138. $('#saveas-query-name').find('.help-inline').text(message.saveform.name.join(' '));
  2139. }
  2140. if (message.saveform.description) {
  2141. $('#saveas-query-description').addClass('error');
  2142. $('#saveas-query-name').find('.help-inline').text(message.saveform.description.join(' '));
  2143. }
  2144. }
  2145. else {
  2146. if (message.saveform.name) {
  2147. _message += " - ${_('Name')}: " + message.saveform.name.join(' ');
  2148. }
  2149. if (message.saveform.description) {
  2150. _message += " - ${_('Description')}: " + message.saveform.description.join(' ');
  2151. }
  2152. $(document).trigger('error', _message);
  2153. }
  2154. }
  2155. }
  2156. else {
  2157. if (message) {
  2158. _message += ": " + message;
  2159. }
  2160. $(document).trigger('error', _message);
  2161. }
  2162. });
  2163. $(document).on('error_save.results', function (e, message) {
  2164. var _message = "${_('Could not save results')}";
  2165. if (message) {
  2166. _message += ": " + message;
  2167. }
  2168. $(document).trigger('error', _message);
  2169. });
  2170. $(document).on('error_cancel.query', function (e, message) {
  2171. $(document).trigger("error", "${ _('Problem: ') }" + message);
  2172. });
  2173. $(document).on('cancelled.query', function (e) {
  2174. $(document).trigger("info", "${ _('Query canceled!') }")
  2175. });
  2176. function updateSidebarTooltips(selector) {
  2177. $(selector).each(function(){
  2178. $(this).tooltip({
  2179. placement: "right",
  2180. title: $(this).val()
  2181. }).attr('data-original-title', hueUtils.escapeOutput($(this).val())).tooltip('fixTitle');
  2182. });
  2183. }
  2184. $(document).ready(function () {
  2185. $("*[rel=tooltip]").tooltip({
  2186. placement: 'bottom'
  2187. });
  2188. // hack for select default rendered fields
  2189. $("select").addClass("input-medium");
  2190. // Type ahead for settings.
  2191. $.getJSON("${ url(app_name + ':configuration') }", function (data) {
  2192. $(".settingsField").typeahead({
  2193. source: $.map(data.configuration, function (value, key) {
  2194. return value.key;
  2195. })
  2196. });
  2197. });
  2198. $("#help").popover({
  2199. 'title': "${_('Did you know?')}",
  2200. 'content': $("#help-content").html(),
  2201. 'trigger': 'hover',
  2202. 'placement': 'left',
  2203. 'html': true
  2204. });
  2205. $("#hdfs-directory-help").popover({
  2206. 'title': "${_('Did you know?')}",
  2207. 'content': $("#hdfs-directory-help-content").html(),
  2208. 'trigger': 'hover',
  2209. 'placement': 'right',
  2210. 'html': true
  2211. });
  2212. $(document).on('click', '#save-results-simple', function() {
  2213. $('#save-results-advanced').removeClass('hide');
  2214. $('#save-results-simple').addClass('hide');
  2215. $('#saveResultsForm .advanced').addClass('hide');
  2216. });
  2217. $(document).on('click', '#save-results-advanced', function() {
  2218. $('#save-results-advanced').addClass('hide');
  2219. $('#save-results-simple').removeClass('hide');
  2220. $('#saveResultsForm .advanced').removeClass('hide');
  2221. });
  2222. $(document).on("change", ".settingsField", function(){
  2223. updateSidebarTooltips(".settingsField");
  2224. });
  2225. $(document).on("change", ".settingValuesField", function(){
  2226. updateSidebarTooltips(".settingValuesField");
  2227. });
  2228. $(document).on("change", ".filesField", function(){
  2229. updateSidebarTooltips(".filesField");
  2230. });
  2231. $(document).on("change", ".functionsField", function(){
  2232. updateSidebarTooltips(".functionsField");
  2233. });
  2234. $(document).on("change", ".classNamesField", function(){
  2235. updateSidebarTooltips(".classNamesField");
  2236. });
  2237. // loads default
  2238. updateSidebarTooltips(".settingsField");
  2239. updateSidebarTooltips(".settingValuesField");
  2240. updateSidebarTooltips(".filesField");
  2241. updateSidebarTooltips(".functionsField");
  2242. updateSidebarTooltips(".classNamesField");
  2243. });
  2244. % if app_name == 'impala':
  2245. $(document).ready(function () {
  2246. $("#downloadQuery").click(function () {
  2247. $("<input>").attr("type", "hidden").attr("name", "button-submit").attr("value", "Execute").appendTo($("#advancedSettingsForm"));
  2248. $("<input>").attr("type", "hidden").attr("name", "download").attr("value", "true").appendTo($("#advancedSettingsForm"));
  2249. tryExecuteQuery();
  2250. });
  2251. $("#refresh-dyk").popover({
  2252. 'title': "${_('Missing some tables? In order to update the list of tables/metadata seen by Impala, execute one of these queries:')}",
  2253. 'content': $("#refresh-content").html(),
  2254. 'trigger': 'hover',
  2255. 'html': true
  2256. });
  2257. $("#refresh-tip").popover({
  2258. 'title': "${_('Missing some tables? In order to update the list of tables/metadata seen by Impala, execute one of these queries:')}",
  2259. 'content': $("#refresh-content").html(),
  2260. 'trigger': 'hover',
  2261. 'html': true
  2262. });
  2263. });
  2264. % endif
  2265. <%
  2266. if app_name == 'impala':
  2267. from impala import conf as impala_conf
  2268. %>
  2269. % if ( app_name == 'beeswax' and beeswax_conf.CLOSE_QUERIES.get() ) or ( app_name == 'impala' and impala_conf.CLOSE_QUERIES.get() ):
  2270. $(document).ready(function () {
  2271. $(document).on('explain.query', function() {
  2272. viewModel.closeQuery();
  2273. });
  2274. $(document).on('execute.query', function() {
  2275. viewModel.closeQuery();
  2276. });
  2277. });
  2278. // Close the query when leaving the page, backup for later when disabling the close before downloading results.
  2279. window.onbeforeunload = function(e) {
  2280. viewModel.closeQuery();
  2281. };
  2282. % endif
  2283. $(window).data('beforeunload', window.onbeforeunload);
  2284. $(".folderChooser:not(:has(~ button))").after(getFolderBrowseButton($(".folderChooser:not(:has(~ button))"), true));
  2285. $(".pathChooser:not(:has(~ button))").after(getPathBrowseButton($(".pathChooser:not(:has(~ button))"), true));
  2286. // Routie
  2287. $(document).ready(function () {
  2288. function queryPageComponents() {
  2289. $('#advanced-settings').show();
  2290. $('#navigator').show();
  2291. $('#queryContainer').show();
  2292. $('#resizePanel').show();
  2293. $('a[href="#query"]').parent().show();
  2294. $('.hue-title-bar').show();
  2295. $('.resultsContainer').css('marginTop', '20px');
  2296. }
  2297. function watchPageComponents() {
  2298. $('#advanced-settings').hide();
  2299. viewModel.isEditor(false);
  2300. $('#navigator').hide();
  2301. $('#queryContainer').hide();
  2302. $('#resizePanel').hide();
  2303. $('a[href="#query"]').parent().hide();
  2304. $('a[href="#recentTab"]').parent().hide();
  2305. $('a[href="#queryBuilderTab"]').parent().hide();
  2306. $('.hue-title-bar').hide();
  2307. $('.resultsContainer').css('marginTop', '-50px');
  2308. }
  2309. function queryPage() {
  2310. queryPageComponents();
  2311. $('.resultsContainer .watch-query').hide();
  2312. $('.resultsContainer .view-query-results').hide();
  2313. }
  2314. function queryLogPage() {
  2315. queryPageComponents();
  2316. $('.resultsContainer .watch-query').show();
  2317. $('.resultsContainer .view-query-results').hide();
  2318. }
  2319. function queryResultsPage() {
  2320. queryPageComponents();
  2321. $('.resultsContainer .watch-query').hide();
  2322. $('.resultsContainer .view-query-results').show();
  2323. $(".view-query-results[rel=tooltip]").tooltip({
  2324. placement: 'bottom'
  2325. });
  2326. }
  2327. function parametersPage() {
  2328. queryPageComponents();
  2329. $('.resultsContainer .watch-query').hide();
  2330. $('.resultsContainer .view-query-results').hide();
  2331. }
  2332. function watchLogsPage() {
  2333. watchPageComponents();
  2334. $('.resultsContainer .watch-query').show();
  2335. $('.resultsContainer .view-query-results').hide();
  2336. }
  2337. function watchResultsPage() {
  2338. watchPageComponents();
  2339. $('.resultsContainer .watch-query').hide();
  2340. $('.resultsContainer .view-query-results').show();
  2341. }
  2342. routie({
  2343. 'query': function () {
  2344. showSection('query-editor');
  2345. queryPage();
  2346. codeMirror.setSize("99%", CURRENT_CODEMIRROR_SIZE);
  2347. placeResizePanelHandle();
  2348. },
  2349. 'query/execute/params': function () {
  2350. if (viewModel.design.parameters().length == 0) {
  2351. routie('query');
  2352. }
  2353. showSection('execute-parameter-selection');
  2354. parametersPage();
  2355. },
  2356. 'query/explain/params': function () {
  2357. if (viewModel.design.parameters().length == 0) {
  2358. routie('query');
  2359. }
  2360. showSection('explain-parameter-selection');
  2361. parametersPage();
  2362. },
  2363. 'query/logs': function () {
  2364. if (viewModel.design.watch.logs().length == 0 && viewModel.design.watch.errors().length == 0) {
  2365. routie('query');
  2366. }
  2367. showSection('query-editor');
  2368. queryLogPage();
  2369. clickHard('.resultsContainer .nav-tabs a[href="#log"]');
  2370. },
  2371. 'query/results': function () {
  2372. showSection('query-editor');
  2373. queryResultsPage();
  2374. clickHard('.resultsContainer .nav-tabs a[href="#results"]');
  2375. renderRecent();
  2376. placeResizePanelHandle();
  2377. hueAnalytics.log('beeswax', 'query/results');
  2378. },
  2379. 'query/explanation': function () {
  2380. if (! viewModel.design.results.explanation()) {
  2381. routie('query');
  2382. }
  2383. showSection('query-editor');
  2384. queryResultsPage();
  2385. clickHard('.resultsContainer .nav-tabs a[href="#explanation"]');
  2386. },
  2387. 'watch/logs': function() {
  2388. showSection('query-editor');
  2389. watchLogsPage();
  2390. clickHard('.resultsContainer .nav-tabs a[href="#log"]');
  2391. hueAnalytics.log('beeswax', 'watch/logs');
  2392. },
  2393. 'watch/results': function() {
  2394. showSection('query-editor');
  2395. watchResultsPage();
  2396. clickHard('.resultsContainer .nav-tabs a[href="#results"]');
  2397. hueAnalytics.log('beeswax', 'watch/results');
  2398. },
  2399. '*': function () {
  2400. routie('query');
  2401. }
  2402. });
  2403. });
  2404. // Event setup
  2405. function queryEvents() {
  2406. $(document).on('fetched.parameters', function () {
  2407. if (viewModel.design.parameters().length > 0) {
  2408. routie('query/execute/params');
  2409. } else {
  2410. viewModel.executeQuery();
  2411. }
  2412. });
  2413. $(document).on('explained.query', function () {
  2414. routie('query/explanation');
  2415. });
  2416. $(document).on('watched.query', function (e, data) {
  2417. if (data.status != 2) {
  2418. if (data.status && data.status && data.status != 0) {
  2419. viewModel.design.watch.errors.push(data.error || data.message);
  2420. }
  2421. }
  2422. routie('query/logs');
  2423. });
  2424. $(document).on('error_watch.query', function () {
  2425. routie('query/logs');
  2426. });
  2427. $(document).on('fetched.results', function () {
  2428. routie('query/results');
  2429. });
  2430. $(document).on('execute.query', function() {
  2431. routie('query');
  2432. });
  2433. $(document).ready(function() {
  2434. routie('query');
  2435. });
  2436. }
  2437. function watchEvents() {
  2438. $(document).ready(function() {
  2439. routie('watch/logs');
  2440. });
  2441. $(document).on('error_watch.query', function () {
  2442. routie('watch/logs');
  2443. });
  2444. $(document).on('fetched.results', function () {
  2445. routie('watch/results');
  2446. });
  2447. }
  2448. function cacheQueryTextEvents() {
  2449. var _waitForCodemirrorInit = -1;
  2450. _waitForCodemirrorInit = window.setInterval(function () {
  2451. if (typeof codeMirror != "undefined") {
  2452. codeMirror.on("change", function () {
  2453. $(".query").val(codeMirror.getValue());
  2454. $.totalStorage(totalStorageUserPrefix + "${app_name}_temp_query", codeMirror.getValue());
  2455. });
  2456. window.clearInterval(_waitForCodemirrorInit);
  2457. }
  2458. }, 100);
  2459. }
  2460. function loadDesign(design_id) {
  2461. viewModel.design.id(design_id);
  2462. viewModel.fetchDesign();
  2463. setupCodeMirrorSubscription();
  2464. }
  2465. function loadQueryHistory(query_history_id) {
  2466. viewModel.design.history.id(query_history_id);
  2467. viewModel.fetchQueryHistory();
  2468. setupCodeMirrorSubscription();
  2469. }
  2470. function setupCodeMirrorSubscription() {
  2471. var codeMirrorSubscription = viewModel.design.query.value.subscribe(function (value) {
  2472. viewModel.queryEditorBlank(true);
  2473. var _waitForCodemirrorInit = -1;
  2474. _waitForCodemirrorInit = window.setInterval(function () {
  2475. if (typeof codeMirror != "undefined") {
  2476. codeMirror.setValue(value);
  2477. codeMirrorSubscription.dispose();
  2478. window.clearInterval(_waitForCodemirrorInit);
  2479. }
  2480. }, 100);
  2481. });
  2482. }
  2483. // Knockout
  2484. viewModel = new BeeswaxViewModel("${app_name}", apiHelper);
  2485. ko.applyBindings(viewModel, $("#beeswax-execute")[0]);
  2486. var handleAssistSelection = function (databaseDef) {
  2487. if (databaseDef.sourceType === snippetType && snippet.database() !== databaseDef.name) {
  2488. snippet.database(databaseDef.name);
  2489. }
  2490. };
  2491. huePubSub.subscribe("assist.database.set", handleAssistSelection);
  2492. huePubSub.subscribe("assist.database.selected", handleAssistSelection);
  2493. if (! snippet.database()) {
  2494. huePubSub.publish("assist.get.database", snippetType);
  2495. }
  2496. shareViewModel = initSharing("#documentShareModal");
  2497. shareViewModel.setDocId(${doc_id});
  2498. $('.left-panel').on('mousewheel', function(e){
  2499. e.preventDefault();
  2500. e.stopPropagation();
  2501. return false;
  2502. });
  2503. % if not beeswax_conf.USE_GET_LOG_API.get() and app_name != 'impala':
  2504. viewModel.shouldAppendLogs = true;
  2505. % endif
  2506. % if query_history:
  2507. loadQueryHistory(${query_history.id});
  2508. % elif design.id:
  2509. loadDesign(${design.id});
  2510. % else:
  2511. $(document).ready(cacheQueryTextEvents);
  2512. % endif
  2513. viewModel.design.fileResources.values.subscribe(function() {
  2514. // File chooser button for file resources.
  2515. $(".fileChooser:not(:has(~ button))").after(hueUtils.getFileBrowseButton($(".fileChooser:not(:has(~ button))")));
  2516. });
  2517. % if action == 'watch-results':
  2518. $(document).ready(watchEvents);
  2519. $(document).one('fetched.query', function(e) {
  2520. viewModel.watchQueryLoop();
  2521. cacheQueryTextEvents();
  2522. });
  2523. % elif action == 'watch-redirect':
  2524. $(document).ready(watchEvents);
  2525. $(document).one('fetched.query', function(e) {
  2526. viewModel.watchQueryLoop();
  2527. cacheQueryTextEvents();
  2528. });
  2529. $(document).on('stop_watch.query', function(e) {
  2530. var successUrl = "${request.GET['on_success_url']}";
  2531. if (viewModel.design.watch.errors().length != 0) {
  2532. window.setTimeout(function(){
  2533. huePubSub.publish('open.link', successUrl + (successUrl.indexOf("?") > -1 ? "&" : "?") + "error=" + encodeURIComponent(viewModel.design.watch.errors().join("\n")));
  2534. }, 200);
  2535. }
  2536. else if (viewModel.design.results.errors().length == 0) {
  2537. window.setTimeout(function(){
  2538. huePubSub.publish('open.link', successUrl + (successUrl.indexOf("?") > -1 ? "&" : "?") + "refresh=true");
  2539. }, 1000);
  2540. }
  2541. });
  2542. % elif action == 'editor-results':
  2543. $(document).ready(queryEvents);
  2544. $(document).one('fetched.query', function(e) {
  2545. viewModel.watchQueryLoop();
  2546. cacheQueryTextEvents();
  2547. });
  2548. % elif action == 'editor-expired-results':
  2549. $(document).ready(queryEvents);
  2550. $(document).one('fetched.query', function(e) {
  2551. viewModel.design.results.expired(true);
  2552. $(document).trigger('fetched.results', [ [] ]);
  2553. cacheQueryTextEvents();
  2554. });
  2555. % else:
  2556. $(document).ready(queryEvents);
  2557. % endif
  2558. // chart related stuff
  2559. function pieChartDataTransformer(data) {
  2560. var _data = [];
  2561. $(data.counts()).each(function (cnt, item) {
  2562. _data.push({
  2563. label: item.value,
  2564. value: item.count,
  2565. obj: item
  2566. });
  2567. });
  2568. if (viewModel.chartSorting() == "asc"){
  2569. _data.sort(function(a, b){
  2570. return a.value - b.value
  2571. });
  2572. }
  2573. if (viewModel.chartSorting() == "desc"){
  2574. _data.sort(function(a, b){
  2575. return b.value - a.value
  2576. });
  2577. }
  2578. return _data;
  2579. }
  2580. function leafletMapChartDataTransformer(data) {
  2581. if (data != null && data.counts != null) return data.counts();
  2582. }
  2583. function barChartDataTransformer(rawDatum) {
  2584. var _datum = [];
  2585. var _data = [];
  2586. $(rawDatum.counts()).each(function (cnt, item) {
  2587. if (typeof item.from != "undefined") {
  2588. _data.push({
  2589. series: 0,
  2590. x: item.from,
  2591. x_end: item.to,
  2592. y: item.value,
  2593. obj: item
  2594. });
  2595. }
  2596. else {
  2597. _data.push({
  2598. series: 0,
  2599. x: item.value,
  2600. y: item.count,
  2601. obj: item
  2602. });
  2603. }
  2604. });
  2605. if (viewModel.chartSorting() == "asc"){
  2606. _data.sort(function(a, b){
  2607. return a.y - b.y
  2608. });
  2609. }
  2610. if (viewModel.chartSorting() == "desc"){
  2611. _data.sort(function(a, b){
  2612. return b.y - a.y
  2613. });
  2614. }
  2615. _datum.push({
  2616. key: $("#blueprintY option:selected").text(),
  2617. values: _data
  2618. });
  2619. return _datum;
  2620. }
  2621. function lineChartDataTransformer(rawDatum) {
  2622. var _datum = [];
  2623. var _data = [];
  2624. $(rawDatum.counts()).each(function (cnt, item) {
  2625. if (typeof item.from != "undefined") {
  2626. _data.push({
  2627. series: 0,
  2628. x: item.from,
  2629. x_end: item.to,
  2630. y: item.value,
  2631. obj: item
  2632. });
  2633. }
  2634. else {
  2635. _data.push({
  2636. series: 0,
  2637. x: item.value,
  2638. y: item.count,
  2639. obj: item
  2640. });
  2641. }
  2642. });
  2643. if (viewModel.chartSorting() == "asc"){
  2644. _data.sort(function(a, b){
  2645. return a.y - b.y
  2646. });
  2647. }
  2648. if (viewModel.chartSorting() == "desc"){
  2649. _data.sort(function(a, b){
  2650. return b.y - a.y
  2651. });
  2652. }
  2653. _datum.push({
  2654. key: $("#blueprintY option:selected").text(),
  2655. values: _data
  2656. });
  2657. return _datum;
  2658. }
  2659. </script>
  2660. ${ commonfooter(request, messages) | n,unicode }