• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1/*
2 * Copyright (C) 2022 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 *     http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16import './sql-wasm.js';
17
18import { Counter, Fps, SelectionData } from '../bean/BoxSelection.js';
19import { WakeupBean } from '../bean/WakeupBean.js';
20import { BinderArgBean } from '../bean/BinderArgBean.js';
21import { SPT, SPTChild } from '../bean/StateProcessThread.js';
22import { CpuUsage, Freq } from '../bean/CpuUsage.js';
23
24import {
25  NativeEvent,
26  NativeEventHeap,
27  NativeHookMalloc,
28  NativeHookProcess,
29  NativeHookSampleQueryInfo,
30  NativeHookStatistics,
31} from '../bean/NativeHook.js';
32import {
33  Dma,
34  DmaComparison,
35  GpuMemory,
36  GpuMemoryComparison,
37  LiveProcess,
38  ProcessHistory,
39  SystemCpuSummary,
40  SystemDiskIOSummary,
41  SystemNetworkSummary,
42} from '../bean/AbilityMonitor.js';
43
44import {
45  PerfCall,
46  PerfCallChain,
47  PerfCmdLine,
48  PerfFile,
49  PerfSample,
50  PerfStack,
51  PerfThread,
52} from '../bean/PerfProfile.js';
53import { SearchFuncBean } from '../bean/SearchFuncBean.js';
54import { CounterSummary, SdkSliceSummary } from '../bean/SdkSummary.js';
55import { Smaps } from '../bean/SmapsStruct.js';
56import { CpuFreqRowLimit } from '../component/chart/SpFreqChart.js';
57import { CpuFreqLimitsStruct } from './ui-worker/ProcedureWorkerCpuFreqLimits.js';
58import { CpuStruct } from './ui-worker/ProcedureWorkerCPU.js';
59import { CpuFreqStruct } from './ui-worker/ProcedureWorkerFreq.js';
60import { ThreadStruct } from './ui-worker/ProcedureWorkerThread.js';
61import { FuncStruct } from './ui-worker/ProcedureWorkerFunc.js';
62import { ProcessMemStruct } from './ui-worker/ProcedureWorkerMem.js';
63import { FpsStruct } from './ui-worker/ProcedureWorkerFPS.js';
64import { CpuAbilityMonitorStruct } from './ui-worker/ProcedureWorkerCpuAbility.js';
65import { MemoryAbilityMonitorStruct } from './ui-worker/ProcedureWorkerMemoryAbility.js';
66import { DiskAbilityMonitorStruct } from './ui-worker/ProcedureWorkerDiskIoAbility.js';
67import { NetworkAbilityMonitorStruct } from './ui-worker/ProcedureWorkerNetworkAbility.js';
68import { EnergyAnomalyStruct } from './ui-worker/ProcedureWorkerEnergyAnomaly.js';
69import { EnergyStateStruct } from './ui-worker/ProcedureWorkerEnergyState.js';
70import { CounterStruct } from './ui-worker/ProduceWorkerSdkCounter.js';
71import { SdkSliceStruct } from './ui-worker/ProduceWorkerSdkSlice.js';
72import { SystemDetailsEnergy } from '../bean/EnergyStruct.js';
73import { ClockStruct } from './ui-worker/ProcedureWorkerClock.js';
74import { IrqStruct } from './ui-worker/ProcedureWorkerIrq.js';
75import {
76  HeapEdge,
77  HeapLocation,
78  HeapNode,
79  HeapSample,
80  HeapTraceFunctionInfo,
81} from '../../js-heap/model/DatabaseStruct';
82import { FileInfo } from '../../js-heap/model/UiStruct.js';
83import { AppStartupStruct } from './ui-worker/ProcedureWorkerAppStartup.js';
84import { SoStruct } from './ui-worker/ProcedureWorkerSoInit.js';
85import { HeapTreeDataBean } from './logic-worker/ProcedureLogicWorkerCommon.js';
86import { TaskTabStruct } from '../component/trace/sheet/task/TabPaneTaskFrames.js';
87import { DeviceStruct } from '../bean/FrameComponentBean.js';
88import { FrameSpacingStruct } from './ui-worker/ProcedureWorkerFrameSpacing.js';
89import { FrameDynamicStruct } from './ui-worker/ProcedureWorkerFrameDynamic.js';
90import { FrameAnimationStruct } from './ui-worker/ProcedureWorkerFrameAnimation.js';
91import { SnapshotStruct } from './ui-worker/ProcedureWorkerSnapshot.js';
92import { MemoryConfig } from '../bean/MemoryConfig.js';
93
94class DataWorkerThread extends Worker {
95  taskMap: any = {};
96
97  uuid(): string {
98    // @ts-ignore
99    return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, (c: any) =>
100      (c ^ (crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (c / 4)))).toString(16)
101    );
102  }
103
104  //发送方法名 参数 回调
105  queryFunc(action: string, args: any, handler: Function) {
106    let id = this.uuid();
107    this.taskMap[id] = handler;
108    let msg = {
109      id: id,
110      action: action,
111      args: args,
112    };
113    this.postMessage(msg);
114  }
115}
116
117class DbThread extends Worker {
118  busy: boolean = false;
119  isCancelled: boolean = false;
120  id: number = -1;
121  taskMap: any = {};
122  cacheArray: Array<any> = [];
123
124  uuid(): string {
125    // @ts-ignore
126    return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, (c: any) =>
127      (c ^ (crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (c / 4)))).toString(16)
128    );
129  }
130
131  queryFunc(name: string, sql: string, args: any, handler: Function, action: string | null) {
132    this.busy = true;
133    let id = this.uuid();
134    this.taskMap[id] = handler;
135    let msg = {
136      id: id,
137      name: name,
138      action: action || 'exec',
139      sql: sql,
140      params: args,
141    };
142    this.postMessage(msg);
143  }
144
145  dbOpen = async (
146    parseConfig: string,
147    sdkWasmConfig?: string
148  ): Promise<{
149    status: boolean;
150    msg: string;
151    buffer: ArrayBuffer;
152    sdkConfigMap: any;
153  }> => {
154    return new Promise<any>((resolve, reject) => {
155      let id = this.uuid();
156      this.taskMap[id] = (res: any) => {
157        if (res.init) {
158          resolve({
159            status: res.init,
160            msg: res.msg,
161            sdkConfigMap: res.configSqlMap,
162            buffer: res.buffer,
163          });
164        } else {
165          resolve({ status: res.init, msg: res.msg });
166        }
167      };
168      this.postMessage(
169        {
170          id: id,
171          action: 'open',
172          parseConfig: parseConfig,
173          wasmConfig: sdkWasmConfig,
174          buffer: DbPool.sharedBuffer! /*Optional. An ArrayBuffer representing an SQLite Database file*/,
175        },
176        [DbPool.sharedBuffer!]
177      );
178    });
179  };
180
181  resetWASM() {
182    this.postMessage({
183      id: this.uuid(),
184      action: 'reset',
185    });
186  }
187}
188
189export class DbPool {
190  static sharedBuffer: ArrayBuffer | null = null;
191  maxThreadNumber: number = 0;
192  works: Array<DbThread> = [];
193  progress: Function | undefined | null;
194  num = Math.floor(Math.random() * 10 + 1) + 20;
195  cutDownTimer: any | undefined;
196  dataWorker: DataWorkerThread | undefined | null;
197  currentWasmThread: DbThread | undefined = undefined;
198
199  init = async (type: string, threadBuild: (() => DbThread) | undefined = undefined) => {
200    // wasm | server | sqlite
201    if (this.currentWasmThread) {
202      this.currentWasmThread.resetWASM();
203      this.currentWasmThread = undefined;
204    }
205    await this.close();
206    const { port1, port2 } = new MessageChannel();
207    if (type === 'wasm') {
208      this.maxThreadNumber = 1;
209    } else if (type === 'server') {
210      this.maxThreadNumber = 1;
211    } else if (type === 'sqlite') {
212      this.maxThreadNumber = 1;
213    } else if (type === 'duck') {
214      this.maxThreadNumber = 1;
215    }
216    for (let i = 0; i < this.maxThreadNumber; i++) {
217      let thread: DbThread | undefined;
218      if (threadBuild) {
219        thread = threadBuild();
220      } else {
221        if (type === 'wasm') {
222          thread = new DbThread('trace/database/TraceWorker.js');
223        } else if (type === 'server') {
224          thread = new DbThread('trace/database/SqlLiteWorker.js');
225        } else if (type === 'sqlite') {
226          thread = new DbThread('trace/database/SqlLiteWorker.js');
227        }
228      }
229      if (thread) {
230        this.currentWasmThread = thread;
231        thread!.onmessage = (event: MessageEvent) => {
232          thread!.busy = false;
233          if (Reflect.has(thread!.taskMap, event.data.id)) {
234            if (event.data.results) {
235              let fun = thread!.taskMap[event.data.id];
236              if (fun) {
237                fun(event.data.results);
238              }
239              Reflect.deleteProperty(thread!.taskMap, event.data.id);
240            } else if (Reflect.has(event.data, 'ready')) {
241              this.progress!('database opened', this.num + event.data.index);
242              this.progressTimer(this.num + event.data.index, this.progress!);
243            } else if (Reflect.has(event.data, 'init')) {
244              if (this.cutDownTimer != undefined) {
245                clearInterval(this.cutDownTimer);
246              }
247              let fun = thread!.taskMap[event.data.id];
248              if (!event.data.init && !event.data.status) {
249                if (fun) {
250                  fun(['error', event.data.msg]);
251                }
252              } else {
253                this.progress!('database ready', 40);
254                if (fun) {
255                  fun(event.data);
256                }
257              }
258              Reflect.deleteProperty(thread!.taskMap, event.data.id);
259            } else {
260              let fun = thread!.taskMap[event.data.id];
261              if (fun) {
262                fun([]);
263              }
264              Reflect.deleteProperty(thread!.taskMap, event.data.id);
265            }
266          }
267        };
268        thread!.onmessageerror = (e) => {};
269        thread!.onerror = (e) => {};
270        thread!.id = i;
271        thread!.busy = false;
272        this.works?.push(thread!);
273      }
274    }
275  };
276
277  initServer = async (url: string, progress: Function) => {
278    this.progress = progress;
279    progress('database loaded', 15);
280    DbPool.sharedBuffer = await fetch(url).then((res) => res.arrayBuffer());
281    progress('open database', 20);
282    for (let i = 0; i < this.works.length; i++) {
283      let thread = this.works[i];
284      let { status, msg } = await thread.dbOpen('');
285      if (!status) {
286        DbPool.sharedBuffer = null;
287        return { status, msg };
288      }
289    }
290    return { status: true, msg: 'ok' };
291  };
292  initSqlite = async (buf: ArrayBuffer, parseConfig: string, sdkWasmConfig: string, progress: Function) => {
293    this.progress = progress;
294    progress('database loaded', 15);
295    DbPool.sharedBuffer = buf;
296    progress('parse database', 20);
297    let configMap;
298    for (let i = 0; i < this.works.length; i++) {
299      let thread = this.works[i];
300      let { status, msg, buffer, sdkConfigMap } = await thread.dbOpen(parseConfig, sdkWasmConfig);
301      if (!status) {
302        DbPool.sharedBuffer = null;
303        return { status, msg };
304      } else {
305        configMap = sdkConfigMap;
306        DbPool.sharedBuffer = buffer;
307      }
308    }
309    return { status: true, msg: 'ok', sdkConfigMap: configMap };
310  };
311
312  close = async () => {
313    clearInterval(this.cutDownTimer);
314    for (let i = 0; i < this.works.length; i++) {
315      let thread = this.works[i];
316      thread.terminate();
317    }
318    this.works.length = 0;
319  };
320
321  submit(name: string, sql: string, args: any, handler: Function, action: string | null) {
322    let noBusyThreads = this.works.filter((it) => !it.busy);
323    let thread: DbThread;
324    if (noBusyThreads.length > 0) {
325      //取第一个空闲的线程进行任务
326      thread = noBusyThreads[0];
327      thread.queryFunc(name, sql, args, handler, action);
328    } else {
329      // 随机插入一个线程中
330      thread = this.works[Math.floor(Math.random() * this.works.length)];
331      thread.queryFunc(name, sql, args, handler, action);
332    }
333  }
334
335  //new method replace submit() method
336  submitTask(action: string, args: any, handler: Function) {
337    this.dataWorker?.queryFunc(action, args, handler);
338  }
339
340  progressTimer(num: number, progress: Function) {
341    let currentNum = num;
342    clearInterval(this.cutDownTimer);
343    this.cutDownTimer = setInterval(() => {
344      currentNum += Math.floor(Math.random() * 3);
345      if (currentNum >= 50) {
346        progress('database opened', 40);
347        clearInterval(this.cutDownTimer);
348      } else {
349        progress('database opened', currentNum);
350      }
351    }, Math.floor(Math.random() * 2500 + 1000));
352  }
353}
354
355export const threadPool = new DbPool();
356
357export function query<T extends any>(
358  name: string,
359  sql: string,
360  args: any = null,
361  action: string | null = null
362): Promise<Array<T>> {
363  return new Promise<Array<T>>((resolve, reject) => {
364    threadPool.submit(
365      name,
366      sql,
367      args,
368      (res: any) => {
369        if (res[0] && res[0] === 'error') {
370          window.publish(window.SmartEvent.UI.Error, res[1]);
371          reject(res);
372        } else {
373          resolve(res);
374        }
375      },
376      action
377    );
378  });
379}
380
381export const queryEventCountMap = (): Promise<
382  Array<{
383    eventName: string;
384    count: number;
385  }>
386> => query('queryEventCountMap', `select event_name as eventName,count from stat where stat_type = 'received';`);
387
388export const queryProcess = (): Promise<
389  Array<{
390    pid: number | null;
391    processName: string | null;
392  }>
393> =>
394  query(
395    'queryProcess',
396    `
397    SELECT
398      pid, processName
399    FROM
400      temp_query_process where pid != 0`
401  );
402
403export const queryProcessByTable = (): Promise<
404  Array<{
405    pid: number | null;
406    processName: string | null;
407  }>
408> =>
409  query(
410    'queryProcessByTable',
411    `
412    SELECT
413      pid, name as processName
414    FROM
415      process where pid != 0`
416  );
417
418export const queryProcessAsyncFunc = (_funName?: string): Promise<Array<any>> =>
419  query(
420    'queryProcessAsyncFunc',
421    `
422select tid,
423    P.pid,
424    A.name as threadName,
425    is_main_thread,
426    c.callid as track_id,
427    c.ts-D.start_ts as startTs,
428    c.dur,
429    c.name as funName,
430    c.parent_id,
431    c.id,
432    c.cookie,
433    c.depth,
434    c.argsetid
435from thread A,trace_range D
436left join callstack C on A.id = C.callid
437left join process P on P.id = A.ipid
438where startTs not null and cookie not null ${_funName ? 'funName=$funName' : ''};`,
439    {
440      funName: _funName,
441    }
442  );
443
444export const queryTotalTime = (): Promise<Array<{ total: number; recordStartNS: number; recordEndNS: number }>> =>
445  query(
446    'queryTotalTime',
447    `
448    select
449      start_ts as recordStartNS,end_ts as recordEndNS,end_ts-start_ts as total
450    from
451      trace_range;`
452  );
453
454export const getAsyncEvents = (): Promise<Array<any>> =>
455  query(
456    'getAsyncEvents',
457    `
458    select
459      *,
460      p.pid as pid,
461      c.ts - t.start_ts as "startTime"
462    from
463      callstack c,trace_range t
464    left join
465      process p
466    on
467      c.callid = p.id
468    where
469      cookie is not null;`
470  );
471
472export const getCpuUtilizationRate = (
473  startNS: number,
474  endNS: number
475): Promise<
476  Array<{
477    cpu: number;
478    ro: number;
479    rate: number;
480  }>
481> =>
482  query(
483    'getCpuUtilizationRate',
484    `
485    with cpu as (
486    select
487      cpu,
488      ts,
489      dur,
490      (case when ro < 99 then ro else 99 end) as ro ,
491      (case when ro < 99 then stime+ro*cell else stime + 99 * cell end) as st,
492      (case when ro < 99 then stime + (ro+1)*cell else etime end) as et
493    from (
494        select
495          cpu,
496          ts,
497          A.dur,
498          ((ts+A.dur)-D.start_ts)/((D.end_ts-D.start_ts)/100) as ro,
499          D.start_ts as stime,
500          D.end_ts etime,
501          (D.end_ts-D.start_ts)/100 as cell
502        from
503          sched_slice A
504        left join
505          trace_range D
506        left join
507          thread B on A.itid = B.id
508        where
509          tid != 0
510        and (A.ts)
511          between D.start_ts and D.end_ts))
512    select cpu,ro,
513       sum(case
514               when ts <= st and ts + dur <= et then (ts + dur - st)
515               when ts <= st and ts + dur > et then et-st
516               when ts > st and ts + dur <= et then dur
517               when ts > st and ts + dur > et then et - ts end)/cast(et-st as float) as rate
518    from cpu
519    group by cpu,ro;`,
520    {}
521  );
522
523export const getFps = () =>
524  query<FpsStruct>(
525    'getFps',
526    `
527    select
528      distinct(ts-tb.start_ts) as startNS, fps
529    from
530      hidump c ,trace_range tb
531    where
532      startNS >= 0
533    --order by startNS;
534    `,
535    {}
536  );
537
538export const getFunDataByTid = (tid: number, ipid: number): Promise<Array<FuncStruct>> =>
539  query(
540    'getFunDataByTid',
541    `
542    select
543    c.ts-D.start_ts as startTs,
544    c.dur,
545    c.name as funName,
546    c.argsetid,
547    c.depth,
548    c.id as id,
549    A.itid as itid,
550    A.ipid as ipid
551from thread A,trace_range D
552left join callstack C on A.id = C.callid
553where startTs not null and c.cookie is null and tid = $tid and A.ipid = $ipid`,
554    { $tid: tid, $ipid: ipid }
555  );
556
557export const getMaxDepthByTid = (): Promise<Array<any>> =>
558  query(
559    'getMaxDepthByTid',
560    `
561    select
562tid,
563ipid,
564    MAX(c.depth + 1) as maxDepth
565from thread A
566left join callstack C on A.id = C.callid
567where c.ts not null and c.cookie is null group by tid,ipid`,
568    {}
569  );
570
571export const getStatesProcessThreadDataByRange = (leftNs: number, rightNs: number): Promise<Array<SPT>> =>
572  query<SPT>(
573    'getStatesProcessThreadDataByRange',
574    `
575    select
576      IP.name as process,
577      IP.pid as processId,
578      A.name as thread,
579      B.state as state,
580      A.tid as threadId,
581      B.dur,
582      (B.ts - TR.start_ts + B.dur) as end_ts,
583      (B.ts - TR.start_ts) as start_ts,
584      B.cpu
585    from
586      thread_state as B
587    left join thread as A on B.itid = A.id
588    left join process as IP on A.ipid = IP.id
589    left join trace_range as TR
590    where B.dur > 0
591    and IP.pid not null
592    and (B.ts - TR.start_ts) >= $leftNs
593    and (B.ts - TR.start_ts + B.dur) <= $rightNs
594`,
595    { $leftNs: leftNs, $rightNs: rightNs }
596  );
597
598export const getTabBoxChildData = (
599  leftNs: number,
600  rightNs: number,
601  state: string | undefined,
602  processId: number | undefined,
603  threadId: number | undefined
604): Promise<Array<SPTChild>> =>
605  query<SPTChild>(
606    'getTabBoxChildData',
607    `
608    select
609      IP.name as process,
610      IP.pid as processId,
611      A.name as thread,
612      B.state as state,
613      A.tid as threadId,
614      B.dur as duration,
615      B.ts - TR.start_ts as startNs,
616      B.cpu,
617      C.priority
618    from
619      thread_state AS B
620    left join
621      thread as A
622    on
623      B.itid = A.id
624    left join
625      process AS IP
626    on
627      A.ipid = IP.id
628    left join
629      trace_range AS TR
630    left join
631      sched_slice as C
632    on
633      B.itid = C.itid
634    and
635      C.ts = B.ts
636    where
637      B.dur > 0
638    and
639      IP.pid not null
640    and
641      not ((B.ts - TR.start_ts + B.dur < $leftNS) or (B.ts - TR.start_ts > $rightNS))
642      ${state != undefined && state != '' ? 'and B.state = $state' : ''}
643      ${processId != undefined && processId != -1 ? 'and IP.pid = $processID' : ''}
644      ${threadId != undefined && threadId != -1 ? 'and A.tid = $threadID' : ''}
645    `,
646    {
647      $leftNS: leftNs,
648      $rightNS: rightNs,
649      $state: state,
650      $processID: processId,
651      $threadID: threadId,
652    }
653  );
654
655export const getTabCpuUsage = (cpus: Array<number>, leftNs: number, rightNs: number): Promise<Array<CpuUsage>> =>
656  query<CpuUsage>(
657    'getTabCpuUsage',
658    `
659    select
660      cpu,
661      sum(case
662        when (A.ts - B.start_ts) < $leftNS
663          then (A.ts - B.start_ts + A.dur - $leftNS)
664        when (A.ts - B.start_ts) >= $leftNS
665          and (A.ts - B.start_ts + A.dur) <= $rightNS
666          then A.dur
667        when (A.ts - B.start_ts + A.dur) > $rightNS
668          then ($rightNS - (A.ts - B.start_ts)) end) / cast($rightNS - $leftNS as float) as usage
669    from
670      thread_state A,
671      trace_range B
672    where
673      (A.ts - B.start_ts) > 0 and A.dur > 0
674    and
675      cpu in (${cpus.join(',')})
676    and
677      (A.ts - B.start_ts + A.dur) > $leftNS
678    and
679      (A.ts - B.start_ts) < $rightNS
680    group by
681      cpu`,
682    { $leftNS: leftNs, $rightNS: rightNs }
683  );
684
685export const getTabCpuFreq = (cpus: Array<number>, leftNs: number, rightNs: number): Promise<Array<Freq>> =>
686  query<Freq>(
687    'getTabCpuFreq',
688    `
689    select
690      cpu,
691      value,
692      (ts - tr.start_ts) as startNs
693    from
694      measure m,
695      trace_range tr
696    inner join
697      cpu_measure_filter t
698    on
699      m.filter_id = t.id
700    where
701      (name = 'cpufreq' or name='cpu_frequency')
702    and
703      cpu in (${cpus.join(',')})
704    and
705      startNs > 0
706    and
707      startNs < $rightNS
708    --order by startNs
709    `,
710    { $leftNS: leftNs, $rightNS: rightNs }
711  );
712
713export const getTabFps = (leftNs: number, rightNs: number): Promise<Array<Fps>> =>
714  query<Fps>(
715    'getTabFps',
716    `
717    select
718      distinct(ts-tb.start_ts) as startNS,
719      fps
720    from
721      hidump c,
722      trace_range tb
723    where
724      startNS <= $rightNS
725    and
726      startNS >= 0
727    --order by startNS;
728    `,
729    { $leftNS: leftNs, $rightNS: rightNs }
730  );
731
732export const getTabCounters = (processFilterIds: Array<number>, virtualFilterIds: Array<number>, startTime: number) =>
733  query<Counter>(
734    'getTabCounters',
735    `
736    select
737      t1.filter_id as trackId,
738      t2.name,
739      value,
740      t1.ts - t3.start_ts as startTime
741    from
742      process_measure t1
743    left join
744      process_measure_filter t2
745    on
746      t1.filter_id = t2.id
747    left join
748      trace_range t3
749    where
750      filter_id in (${processFilterIds.join(',')})
751    and
752      startTime <= $startTime
753union
754 select
755      t1.filter_id as trackId,
756      t2.name,
757      value,
758      t1.ts - t3.start_ts as startTime
759    from
760      sys_mem_measure t1
761    left join
762      sys_event_filter t2
763    on
764      t1.filter_id = t2.id
765    left join
766      trace_range t3
767    where
768      filter_id in (${virtualFilterIds.join(',')})
769    and
770      startTime <= $startTime
771    `,
772    { $startTime: startTime }
773  );
774
775export const getTabVirtualCounters = (virtualFilterIds: Array<number>, startTime: number) =>
776  query<Counter>(
777    'getTabVirtualCounters',
778    `
779    select
780      table1.filter_id as trackId,
781      table2.name,
782      value,
783      table1.ts - table3.start_ts as startTime
784    from
785      sys_mem_measure table1
786    left join
787      sys_event_filter table2
788    on
789      table1.filter_id = table2.id
790    left join
791      trace_range table3
792    where
793      filter_id in (${virtualFilterIds.join(',')})
794    and
795      startTime <= $startTime
796    `,
797    { $startTime: startTime }
798  );
799
800export const getTabCpuByProcess = (cpus: Array<number>, leftNS: number, rightNS: number) =>
801  query<any>(
802    'getTabCpuByProcess',
803    `
804    select
805      B.pid as pid,
806      sum(B.dur) as wallDuration,
807      avg(B.dur) as avgDuration,
808      count(B.tid) as occurrences
809    from
810      thread_state AS B
811    left join
812      trace_range AS TR
813    where
814      B.cpu in (${cpus.join(',')})
815    and
816      not ((B.ts - TR.start_ts + B.dur < $leftNS) or (B.ts - TR.start_ts > $rightNS ))
817    group by
818      B.pid
819    order by
820      wallDuration desc;`,
821    { $rightNS: rightNS, $leftNS: leftNS }
822  );
823
824export const getTabCpuByThread = (cpus: Array<number>, leftNS: number, rightNS: number) =>
825  query<any>(
826    'getTabCpuByThread',
827    `
828    select
829      TS.pid as pid,
830      TS.tid as tid,
831      TS.cpu,
832      sum( min(${rightNS},(TS.ts - TR.start_ts + TS.dur)) - max(${leftNS},TS.ts - TR.start_ts)) wallDuration,
833      count(TS.tid) as occurrences
834    from
835      thread_state AS TS
836    left join
837      trace_range AS TR
838    where
839      TS.cpu in (${cpus.join(',')})
840    and
841      not ((TS.ts - TR.start_ts + TS.dur < $leftNS) or (TS.ts - TR.start_ts > $rightNS))
842    group by
843      TS.cpu,
844      TS.pid,
845      TS.tid
846    order by
847      wallDuration desc;`,
848    { $rightNS: rightNS, $leftNS: leftNS }
849  );
850
851export const getTabSlices = (
852  funTids: Array<number>,
853  pids: Array<number>,
854  leftNS: number,
855  rightNS: number
856): Promise<Array<any>> =>
857  query<SelectionData>(
858    'getTabSlices',
859    `
860    select
861      c.name as name,
862      sum(c.dur) as wallDuration,
863      avg(c.dur) as avgDuration,
864      count(c.name) as occurrences
865    from
866      thread T, trace_range TR
867      left join process P on T.ipid = P.id
868    left join
869      callstack C
870    on
871      T.id = C.callid
872    where
873      C.ts not null
874    and
875      c.dur >= 0
876    and
877      T.tid in (${funTids.join(',')})
878    and
879      P.pid in (${pids.join(',')})
880    and
881      c.name != 'binder transaction async'
882    and
883      c.name != 'binder async rcv'
884    and
885      c.cookie is null
886    and
887      not ((C.ts - TR.start_ts + C.dur < $leftNS) or (C.ts - TR.start_ts > $rightNS))
888    group by
889      c.name
890    order by
891      wallDuration desc;`,
892    { $leftNS: leftNS, $rightNS: rightNS }
893  );
894
895export const getTabSlicesAsyncFunc = (
896  asyncNames: Array<string>,
897  asyncPid: Array<number>,
898  leftNS: number,
899  rightNS: number
900): Promise<Array<any>> =>
901  query<SelectionData>(
902    'getTabSlicesAsyncFunc',
903    `
904    select
905      c.name as name,
906      sum(c.dur) as wallDuration,
907      avg(c.dur) as avgDuration,
908      count(c.name) as occurrences
909    from
910      thread A, trace_range D
911    left join
912      callstack C
913    on
914      A.id = C.callid
915    left join process P on P.id = A.ipid
916    where
917      C.ts not null
918    and
919      c.dur >= -1
920    and
921      c.cookie not null
922    and
923      P.pid in (${asyncPid.join(',')})
924    and
925      c.name in (${asyncNames.map((it) => "'" + it + "'").join(',')})
926    and
927      not ((C.ts - D.start_ts + C.dur < $leftNS) or (C.ts - D.start_ts > $rightNS))
928    group by
929      c.name
930    order by
931      wallDuration desc;`,
932    { $leftNS: leftNS, $rightNS: rightNS }
933  );
934
935export const getTabThreadStates = (tIds: Array<number>, leftNS: number, rightNS: number): Promise<Array<any>> =>
936  query<SelectionData>(
937    'getTabThreadStates',
938    `
939    select
940      B.pid,
941      B.tid,
942      B.state,
943      sum(B.dur) as wallDuration,
944      avg(ifnull(B.dur,0)) as avgDuration,
945      count(B.tid) as occurrences
946    from
947      thread_state AS B
948    left join
949      trace_range AS TR
950    where
951      B.tid in (${tIds.join(',')})
952    and
953      not ((B.ts - TR.start_ts + ifnull(B.dur,0) < $leftNS) or (B.ts - TR.start_ts > $rightNS))
954    group by
955      B.pid, B.tid, B.state
956    order by
957      wallDuration desc;`,
958    { $leftNS: leftNS, $rightNS: rightNS }
959  );
960
961export const getTabThreadStatesCpu = (tIds: Array<number>, leftNS: number, rightNS: number): Promise<Array<any>> => {
962  let sql = `
963select
964       B.pid,
965       B.tid,
966       B.cpu,
967       sum( min(${rightNS},(B.ts - TR.start_ts + B.dur)) - max(${leftNS},B.ts - TR.start_ts)) wallDuration
968from thread_state as B
969left join trace_range as TR
970where cpu notnull
971    and B.tid in (${tIds.join(',')})
972    and not ((B.ts - TR.start_ts + ifnull(B.dur,0) < ${leftNS}) or (B.ts - TR.start_ts > ${rightNS}))
973group by B.tid, B.pid, B.cpu;`;
974  return query<SelectionData>('getTabThreadStatesCpu', sql, {
975    $leftNS: leftNS,
976    $rightNS: rightNS,
977  });
978};
979
980export const getTabStartups = (ids: Array<number>, leftNS: number, rightNS: number): Promise<Array<any>> => {
981  let sql = `
982select
983    P.pid,
984    P.name as process,
985    (A.start_time - B.start_ts) as startTs,
986    (case when A.end_time = -1 then 0 else (A.end_time - A.start_time) end) as dur,
987    A.start_name as startName
988from app_startup A,trace_range B
989left join process P on A.ipid = P.ipid
990where P.pid in (${ids.join(',')})
991and not ((startTs + dur < ${leftNS}) or (startTs > ${rightNS}))
992order by start_name;`;
993  return query('getTabStartups', sql, {});
994};
995
996export const getTabStaticInit = (ids: Array<number>, leftNS: number, rightNS: number): Promise<Array<any>> => {
997  let sql = `
998select
999    P.pid,
1000    P.name as process,
1001    (A.start_time - B.start_ts) as startTs,
1002    (case when A.end_time = -1 then 0 else (A.end_time - A.start_time) end) as dur,
1003    A.so_name as soName
1004from static_initalize A,trace_range B
1005left join process P on A.ipid = P.ipid
1006where P.pid in (${ids.join(',')})
1007and not ((startTs + dur < ${leftNS}) or (startTs > ${rightNS}))
1008order by dur desc;`;
1009  return query('getTabStaticInit', sql, {});
1010};
1011
1012export const queryBinderArgsByArgset = (argset: number): Promise<Array<BinderArgBean>> =>
1013  query(
1014    'queryBinderArgsByArgset',
1015    `
1016    select
1017      *
1018    from
1019      args_view
1020    where
1021      argset = $argset;`,
1022    { $argset: argset }
1023  );
1024
1025export const queryCpuData = (cpu: number, startNS: number, endNS: number): Promise<Array<CpuStruct>> =>
1026  query(
1027    'queryCpuData',
1028    `
1029    SELECT
1030    B.pid as processId,
1031    B.cpu,
1032    B.tid,
1033    B.itid as id,
1034    B.dur,
1035    B.ts - TR.start_ts AS startTime,
1036    B.arg_setid as argSetID
1037from thread_state AS B
1038    left join trace_range AS TR
1039where B.itid is not null
1040    and
1041      B.cpu = $cpu
1042    and
1043      startTime between $startNS and $endNS;`,
1044    {
1045      $cpu: cpu,
1046      $startNS: startNS,
1047      $endNS: endNS,
1048    }
1049  );
1050
1051export const queryCpuFreq = (): Promise<Array<{ cpu: number; filterId: number }>> =>
1052  query(
1053    'queryCpuFreq',
1054    `
1055    select
1056      cpu,id as filterId
1057    from
1058      cpu_measure_filter
1059    where
1060      (name='cpufreq' or name='cpu_frequency')
1061    order by cpu;
1062    `
1063  );
1064
1065export const queryCpuFreqData = (cpu: number): Promise<Array<CpuFreqStruct>> =>
1066  query<CpuFreqStruct>(
1067    'queryCpuFreqData',
1068    `
1069    select
1070      cpu,
1071      value,
1072      ifnull(dur,tb.end_ts - c.ts) dur,
1073      ts-tb.start_ts as startNS
1074    from
1075      measure c,
1076      trace_range tb
1077    inner join
1078      cpu_measure_filter t
1079    on
1080      c.filter_id = t.id
1081    where
1082      (name = 'cpufreq' or name='cpu_frequency')
1083    and
1084      cpu= $cpu
1085    --order by ts;
1086    `,
1087    { $cpu: cpu }
1088  );
1089
1090export const queryCpuMax = (): Promise<Array<any>> =>
1091  query(
1092    'queryCpuMax',
1093    `
1094    select
1095      cpu
1096    from
1097      sched_slice
1098    order by
1099      cpu
1100    desc limit 1;`
1101  );
1102
1103export const queryCpuDataCount = () =>
1104  query('queryCpuDataCount', 'select count(1) as count,cpu from thread_state where cpu not null group by cpu');
1105
1106export const queryCpuCount = (): Promise<Array<any>> =>
1107  query(
1108    'queryCpuCount',
1109    `
1110   select max(cpuCount) cpuCount from
1111(select ifnull((max(cpu) + 1),0) cpuCount  from cpu_measure_filter where name in ('cpu_frequency','cpu_idle')
1112 union all
1113 select ifnull((max(callid)+1),0) cpuCount from irq
1114) A;`
1115  );
1116
1117export const queryCpuSchedSlice = (): Promise<Array<any>> =>
1118  query(
1119    'queryCpuSchedSlice',
1120    `
1121   select (ts - start_ts) as ts,
1122       itid,
1123       end_state as endState,
1124       priority
1125   from sched_slice,trace_range;`
1126  );
1127
1128export const queryCpuStateFilter = (): Promise<Array<any>> =>
1129  query(
1130    'queryCpuStateFilter',
1131    `select cpu,id as filterId from cpu_measure_filter where name = 'cpu_idle' order by cpu;`,
1132    {}
1133  );
1134
1135export const queryCpuState = (cpuFilterId: number): Promise<Array<any>> =>
1136  query(
1137    'queryCpuState',
1138    `
1139        select (A.ts - B.start_ts) as startTs,ifnull(dur,B.end_ts - A.ts) dur,
1140            value
1141        from measure A,trace_range B
1142        where filter_id = $filterId;`,
1143    { $filterId: cpuFilterId }
1144  );
1145
1146export const queryCpuMaxFreq = (): Promise<Array<any>> =>
1147  query(
1148    'queryCpuMaxFreq',
1149    `
1150    select
1151      max(value) as maxFreq
1152    from
1153      measure c
1154    inner join
1155      cpu_measure_filter t
1156    on
1157      c.filter_id = t.id
1158    where
1159      (name = 'cpufreq' or name='cpu_frequency');`
1160  );
1161
1162export const queryProcessData = (pid: number, startNS: number, endNS: number): Promise<Array<any>> =>
1163  query(
1164    'queryProcessData',
1165    `
1166    select  ta.cpu,
1167        dur,
1168        ts-${(window as any).recordStartNS} as startTime
1169from thread_state ta
1170where ta.cpu is not null and pid=$pid and startTime between $startNS and $endNS;`,
1171    {
1172      $pid: pid,
1173      $startNS: startNS,
1174      $endNS: endNS,
1175    }
1176  );
1177
1178export const queryProcessMem = (): Promise<Array<any>> =>
1179  query(
1180    'queryProcessMem',
1181    `
1182    select
1183      process_measure_filter.id as trackId,
1184      process_measure_filter.name as trackName,
1185      ipid as upid,
1186      process.pid,
1187      process.name as processName
1188    from
1189      process_measure_filter
1190    join
1191      process using (ipid)
1192    order by trackName;`
1193  );
1194
1195export const queryProcessThreadDataCount = (): Promise<Array<any>> =>
1196  query(
1197    `queryProcessThreadDataCount`,
1198    `select pid,count(id) as count
1199    from thread_state
1200    where ts between ${(window as any).recordStartNS} and ${(window as any).recordEndNS} group by pid;`,
1201    {}
1202  );
1203
1204export const queryProcessFuncDataCount = (): Promise<Array<any>> =>
1205  query(
1206    `queryProcessFuncDataCount`,
1207    `select
1208        P.pid,
1209        count(tid) as count
1210    from callstack C
1211    left join thread A on A.id = C.callid
1212    left join process AS P on P.id = A.ipid
1213    where  C.ts between ${(window as any).recordStartNS} and ${(window as any).recordEndNS}
1214    group by pid;`,
1215    {}
1216  );
1217
1218export const queryProcessMemDataCount = (): Promise<Array<any>> =>
1219  query(
1220    `queryProcessMemDataCount`,
1221    `select
1222      p.pid as pid, count(value) count
1223    from process_measure c
1224    left join process_measure_filter f on f.id = c.filter_id
1225    left join process p on p.ipid = f.ipid
1226where f.id not NULL and value>0
1227 and c.ts between ${(window as any).recordStartNS} and ${(window as any).recordEndNS}
1228group by p.pid`,
1229    {}
1230  );
1231
1232export const queryProcessMemData = (trackId: number): Promise<Array<ProcessMemStruct>> =>
1233  query(
1234    'queryProcessMemData',
1235    `
1236    select
1237      c.type,
1238      ts,
1239      value,
1240      filter_id as track_id,
1241      c.ts-tb.start_ts startTime
1242    from
1243      process_measure c,
1244      trace_range tb
1245    where
1246      filter_id = $id;`,
1247    { $id: trackId }
1248  );
1249
1250export const queryThreads = (): Promise<Array<any>> =>
1251  query('queryThreads', `select id,tid,(ifnull(name,'Thread') || '(' || tid || ')') name from thread where id != 0;`);
1252
1253export const queryDataDICT = (): Promise<Array<any>> => query('queryDataDICT', `select * from data_dict;`);
1254
1255export const queryAppStartupProcessIds = (): Promise<Array<{ pid: number }>> => query('queryAppStartupProcessIds', `
1256  SELECT pid FROM process
1257  WHERE ipid IN (
1258    SELECT ipid FROM app_startup
1259    UNION
1260    SELECT t.ipid FROM app_startup a LEFT JOIN thread t ON a.call_id = t.itid
1261);`);
1262export const queryProcessContentCount = (): Promise<Array<any>> =>
1263  query(`queryProcessContentCount`, `select pid,switch_count,thread_count,slice_count,mem_count from process;`);
1264export const queryProcessThreadsByTable = (): Promise<Array<ThreadStruct>> =>
1265  query(
1266    'queryProcessThreadsByTable',
1267    `
1268        select p.pid as pid,p.ipid as upid,t.tid as tid,p.name as processName,t.name as threadName from thread t left join process  p on t.ipid = p.id where t.tid != 0;
1269    `
1270  );
1271export const queryVirtualMemory = (): Promise<Array<any>> =>
1272  query('queryVirtualMemory', `select id,name from sys_event_filter where type='sys_virtual_memory_filter'`);
1273export const queryVirtualMemoryData = (filterId: number): Promise<Array<any>> =>
1274  query(
1275    'queryVirtualMemoryData',
1276    `select ts-${
1277      (window as any).recordStartNS
1278    } as startTime,value,filter_id as filterID from sys_mem_measure where filter_id=$filter_id`,
1279    { $filter_id: filterId }
1280  );
1281export const queryProcessThreads = (): Promise<Array<ThreadStruct>> =>
1282  query(
1283    'queryProcessThreads',
1284    `
1285    select
1286      the_tracks.ipid as upid,
1287      the_tracks.itid as utid,
1288      total_dur as hasSched,
1289      process.pid as pid,
1290      thread.tid as tid,
1291      process.name as processName,
1292      thread.name as threadName
1293    from (
1294      select ipid,itid from sched_slice group by itid
1295    ) the_tracks
1296    left join (select itid,sum(dur) as total_dur from thread_state where state != 'S' group by itid) using(itid)
1297    left join thread using(itid)
1298    left join process using(ipid)
1299    order by total_dur desc,the_tracks.ipid,the_tracks.itid;`,
1300    {}
1301  );
1302
1303export const queryThreadData = (tid: number, pid: number): Promise<Array<ThreadStruct>> =>
1304  query(
1305    'queryThreadData',
1306    `
1307    select
1308      B.itid as id
1309     , B.tid
1310     , B.cpu
1311     , B.ts - TR.start_ts AS startTime
1312     , B.dur
1313     , B.state
1314     , B.pid
1315     , B.arg_setid as argSetID
1316from thread_state AS B
1317    left join trace_range AS TR
1318where B.tid = $tid and B.pid = $pid;`,
1319    { $tid: tid, $pid: pid }
1320  );
1321
1322export const queryStartupPidArray = (): Promise<Array<{ pid: number }>> =>
1323  query(
1324    'queryStartupPidArray',
1325    `
1326    select distinct pid
1327from app_startup A,trace_range B left join process P on A.ipid = p.ipid
1328where A.start_time between B.start_ts and B.end_ts;`,
1329    {}
1330  );
1331
1332export const queryProcessStartup = (pid: number): Promise<Array<AppStartupStruct>> =>
1333  query(
1334    'queryProcessStartup',
1335    `
1336    select
1337    P.pid,
1338    A.tid,
1339    A.call_id as itid,
1340    (case when A.start_time < B.start_ts then 0 else (A.start_time - B.start_ts) end) as startTs,
1341    (case
1342        when A.start_time < B.start_ts then (A.end_time - B.start_ts)
1343        when A.end_time = -1 then 0
1344        else (A.end_time - A.start_time) end) as dur,
1345    A.start_name as startName
1346from app_startup A,trace_range B
1347left join process P on A.ipid = P.ipid
1348where P.pid = $pid
1349order by start_name;`,
1350    { $pid: pid }
1351  );
1352
1353export const queryProcessSoMaxDepth = (): Promise<Array<{ pid: number; maxDepth: number }>> =>
1354  query(
1355    'queryProcessSoMaxDepth',
1356    `select p.pid,max(depth) maxDepth
1357from static_initalize S,trace_range B left join process p on S.ipid = p.ipid
1358where S.start_time between B.start_ts and B.end_ts
1359group by p.pid;`,
1360    {}
1361  );
1362
1363export const queryProcessSoInitData = (pid: number): Promise<Array<SoStruct>> =>
1364  query(
1365    'queryProcessSoInitData',
1366    `
1367    select
1368    P.pid,
1369    T.tid,
1370    A.call_id as itid,
1371    (A.start_time - B.start_ts) as startTs,
1372    (A.end_time - A.start_time) as dur,
1373    A.so_name as soName,
1374    A.depth
1375from static_initalize A,trace_range B
1376left join process P on A.ipid = P.ipid
1377left join thread T on A.call_id = T.itid
1378where P.pid = $pid;`,
1379    { $pid: pid }
1380  );
1381
1382export const queryThreadAndProcessName = (): Promise<Array<any>> =>
1383  query(
1384    'queryThreadAndProcessName',
1385    `
1386    select tid id,name,'t' type from thread
1387union all
1388select pid id,name,'p' type from process;`,
1389    {}
1390  );
1391
1392export const queryThreadStateArgs = (argset: number): Promise<Array<BinderArgBean>> =>
1393  query('queryThreadStateArgs', ` select args_view.* from args_view where argset = ${argset}`, {});
1394
1395export const queryWakeUpThread_Desc = (): Promise<Array<any>> =>
1396  query(
1397    'queryWakeUpThread_Desc',
1398    `This is the interval from when the task became eligible to run
1399(e.g.because of notifying a wait queue it was a suspended on) to when it started running.`
1400  );
1401
1402export const queryThreadWakeUp = (itid: number, startTime: number, dur: number): Promise<Array<WakeupBean>> =>
1403  query(
1404    'queryThreadWakeUp',
1405    `
1406select TA.tid,min(TA.ts - TR.start_ts) as ts,TA.pid
1407from
1408  (select min(ts) as wakeTs,ref as itid from instant,trace_range
1409       where name = 'sched_wakeup'
1410       and wakeup_from = $itid
1411       and ts > start_ts + $startTime
1412       and ts < start_ts + $startTime + $dur
1413      group by ref
1414       ) TW
1415left join thread_state TA on TW.itid = TA.itid
1416left join trace_range TR
1417where TA.ts > TW.wakeTs
1418group by TA.tid,TA.pid;
1419    `,
1420    { $itid: itid, $startTime: startTime, $dur: dur }
1421  );
1422
1423export const queryRunnableTimeByRunning = (tid: number, startTime: number): Promise<Array<WakeupBean>> => {
1424  let sql = `
1425select ts from thread_state,trace_range where ts + dur -start_ts = ${startTime} and state = 'R' and tid=${tid} limit 1
1426    `;
1427  return query('queryRunnableTimeByRunning', sql, {});
1428};
1429
1430export const queryThreadWakeUpFrom = (itid: number, startTime: number): Promise<Array<WakeupBean>> => {
1431  let sql = `
1432select (A.ts - B.start_ts) as ts,
1433       A.tid,
1434       A.itid,
1435       A.pid,
1436       A.cpu,
1437       A.dur
1438from thread_state A,trace_range B
1439where A.state = 'Running'
1440and A.itid = (select wakeup_from from instant where ts = ${startTime} and ref = ${itid} limit 1)
1441and (A.ts - B.start_ts) < (${startTime} - B.start_ts)
1442order by ts desc limit 1
1443    `;
1444  return query('queryThreadWakeUpFrom', sql, {});
1445};
1446/*-------------------------------------------------------------------------------------*/
1447
1448export const queryHeapGroupByEvent = (type: string): Promise<Array<NativeEventHeap>> => {
1449  let sql1 = `
1450        select
1451            event_type as eventType,
1452            sum(heap_size) as sumHeapSize
1453        from native_hook
1454        where event_type = 'AllocEvent' or event_type = 'MmapEvent'
1455        group by event_type
1456    `;
1457  let sql2 = `
1458        select (case when type = 0 then 'AllocEvent' else 'MmapEvent' end) eventType,
1459            sum(apply_size) sumHeapSize
1460        from native_hook_statistic
1461        group by eventType;
1462    `;
1463  return query('queryHeapGroupByEvent', type === 'native_hook' ? sql1 : sql2, {});
1464};
1465
1466export const queryAllHeapByEvent = (): Promise<Array<NativeEvent>> =>
1467  query(
1468    'queryAllHeapByEvent',
1469    `
1470    select * from (
1471      select h.start_ts - t.start_ts as startTime,
1472       h.heap_size as heapSize,
1473       h.event_type as eventType
1474from native_hook h ,trace_range t
1475where h.start_ts >= t.start_ts and h.start_ts <= t.end_ts
1476and (h.event_type = 'AllocEvent' or h.event_type = 'MmapEvent')
1477union
1478select h.end_ts - t.start_ts as startTime,
1479       h.heap_size as heapSize,
1480       (case when h.event_type = 'AllocEvent' then 'FreeEvent' else 'MunmapEvent' end) as eventType
1481from native_hook h ,trace_range t
1482where h.start_ts >= t.start_ts and h.start_ts <= t.end_ts
1483and (h.event_type = 'AllocEvent' or h.event_type = 'MmapEvent')
1484and h.end_ts not null ) order by startTime;
1485`,
1486    {}
1487  );
1488
1489export const queryHeapAllData = (
1490  startTs: number,
1491  endTs: number,
1492  ipids: Array<number>
1493): Promise<Array<HeapTreeDataBean>> =>
1494  query(
1495    'queryHeapAllData',
1496    `
1497    select
1498      h.start_ts - t.start_ts as startTs,
1499      h.end_ts - t.start_ts as endTs,
1500      h.heap_size as heapSize,
1501      h.event_type as eventType,
1502      h.callchain_id as eventId
1503    from
1504      native_hook h
1505    inner join
1506      trace_range  t
1507    where
1508      event_type = 'AllocEvent'
1509    and
1510      ipid in (${ipids.join(',')})
1511    and
1512      (h.start_ts - t.start_ts between ${startTs} and ${endTs} or h.end_ts - t.start_ts between ${startTs} and ${endTs})`,
1513    { ipids: ipids, $startTs: startTs, $endTs: endTs }
1514  );
1515
1516export const queryNativeHookStatistics = (leftNs: number, rightNs: number): Promise<Array<NativeHookMalloc>> =>
1517  query(
1518    'queryNativeHookStatistics',
1519    `
1520    select
1521      event_type as eventType,
1522      sub_type_id as subTypeId,
1523      max(heap_size) as max,
1524      sum(case when ((A.start_ts - B.start_ts) between ${leftNs} and ${rightNs}) then heap_size else 0 end) as allocByte,
1525      sum(case when ((A.start_ts - B.start_ts) between ${leftNs} and ${rightNs}) then 1 else 0 end) as allocCount,
1526      sum(case when ((A.end_ts - B.start_ts) between ${leftNs} and ${rightNs} ) then heap_size else 0 end) as freeByte,
1527      sum(case when ((A.end_ts - B.start_ts) between ${leftNs} and ${rightNs} ) then 1 else 0 end) as freeCount
1528    from
1529      native_hook A,
1530      trace_range B
1531    where
1532      (A.start_ts - B.start_ts) between ${leftNs} and ${rightNs}
1533     and (event_type = 'AllocEvent' or event_type = 'MmapEvent')
1534    group by event_type;`,
1535    { $leftNs: leftNs, $rightNs: rightNs }
1536  );
1537
1538export const queryNativeHookStatisticsMalloc = (leftNs: number, rightNs: number): Promise<Array<NativeHookMalloc>> =>
1539  query(
1540    'queryNativeHookStatisticsMalloc',
1541    `
1542    select
1543      event_type as eventType,
1544      heap_size as heapSize,
1545      sum(case when ((A.start_ts - B.start_ts) between ${leftNs} and ${rightNs}) then heap_size else 0 end) as allocByte,
1546      sum(case when ((A.start_ts - B.start_ts) between ${leftNs} and ${rightNs}) then 1 else 0 end) as allocCount,
1547      sum(case when ((A.end_ts - B.start_ts) between ${leftNs} and ${rightNs} ) then heap_size else 0 end) as freeByte,
1548      sum(case when ((A.end_ts - B.start_ts) between ${leftNs} and ${rightNs} ) then 1 else 0 end) as freeCount
1549    from
1550      native_hook A,
1551      trace_range B
1552    where
1553      (A.start_ts - B.start_ts) between ${leftNs} and ${rightNs}
1554    and
1555      (event_type = 'AllocEvent' or event_type = 'MmapEvent')
1556    and
1557      sub_type_id is null
1558    group by
1559      event_type,
1560      heap_size
1561    order by heap_size desc
1562    `,
1563    { $leftNs: leftNs, $rightNs: rightNs }
1564  );
1565
1566export const queryNativeHookStatisticsSubType = (leftNs: number, rightNs: number): Promise<Array<NativeHookMalloc>> =>
1567  query(
1568    'queryNativeHookStatisticsSubType',
1569    `
1570    select
1571      event_type as eventType,
1572      sub_type_id as subTypeId,
1573      max(heap_size) as max,
1574      sum(case when ((NH.start_ts - TR.start_ts) between ${leftNs} and ${rightNs}) then heap_size else 0 end) as allocByte,
1575      sum(case when ((NH.start_ts - TR.start_ts) between ${leftNs} and ${rightNs}) then 1 else 0 end) as allocCount,
1576      sum(case when ((NH.end_ts - TR.start_ts) between ${leftNs} and ${rightNs} ) then heap_size else 0 end) as freeByte,
1577      sum(case when ((NH.end_ts - TR.start_ts) between ${leftNs} and ${rightNs} ) then 1 else 0 end) as freeCount
1578    from
1579      native_hook NH,
1580      trace_range TR
1581    where
1582      (NH.start_ts - TR.start_ts) between ${leftNs} and ${rightNs}
1583    and
1584      (event_type = 'MmapEvent')
1585    group by
1586      event_type,sub_type_id;
1587        `,
1588    { $leftNs: leftNs, $rightNs: rightNs }
1589  );
1590
1591export const queryNativeHookSubType = (leftNs: number, rightNs: number): Promise<Array<any>> =>
1592  query(
1593    'queryNativeHookSubType',
1594    `select distinct sub_type_id as subTypeId, DD.data as subType
1595      from
1596        native_hook NH,
1597        trace_range TR
1598      left join data_dict DD on NH.sub_type_id = DD.id
1599      where
1600        NH.sub_type_id not null and
1601        (NH.start_ts - TR.start_ts) between ${leftNs} and ${rightNs}
1602        `,
1603    { $leftNs: leftNs, $rightNs: rightNs }
1604  );
1605
1606export const queryNativeHookStatisticSubType = (leftNs: number, rightNs: number): Promise<Array<any>> =>
1607  query(
1608    'queryNativeHookStatisticSubType',
1609    `SELECT DISTINCT
1610      CASE
1611        WHEN type = 3 AND sub_type_id NOT NULL THEN sub_type_id
1612        ELSE type
1613      END AS subTypeId,
1614      CASE
1615        WHEN type = 2 THEN 'FILE_PAGE_MSG'
1616        WHEN type = 3 AND sub_type_id NOT NULL THEN D.data
1617        WHEN type = 3 THEN 'MEMORY_USING_MSG'
1618        ELSE 'MmapEvent'
1619      END AS subType
1620      FROM
1621        native_hook_statistic NHS
1622        LEFT JOIN data_dict D ON NHS.sub_type_id = D.id,
1623        trace_range TR
1624      WHERE
1625        NHS.type > 1 AND
1626        (NHS.ts - TR.start_ts) between ${leftNs} and ${rightNs}
1627      `,
1628    { $leftNs: leftNs, $rightNs: rightNs }
1629  );
1630
1631export const queryNativeHookStatisticsCount = (): Promise<Array<NativeHookProcess>> =>
1632  query('queryNativeHookStatisticsCount', `select count(1) num from native_hook_statistic`, {});
1633
1634export const queryNativeHookProcess = (table: string): Promise<Array<NativeHookProcess>> => {
1635  let sql = `
1636    select
1637      distinct ${table}.ipid,
1638      pid,
1639      name
1640    from
1641      ${table}
1642    left join
1643      process p
1644    on
1645      ${table}.ipid = p.id
1646    `;
1647  return query('queryNativeHookProcess', sql, {});
1648};
1649
1650export const queryNativeHookSnapshotTypes = (): Promise<Array<NativeHookSampleQueryInfo>> =>
1651  query(
1652    'queryNativeHookSnapshotTypes',
1653    `
1654select
1655      event_type as eventType,
1656      data as subType
1657    from
1658      native_hook left join data_dict on native_hook.sub_type_id = data_dict.id
1659    where
1660      (event_type = 'AllocEvent' or event_type = 'MmapEvent')
1661    group by
1662      event_type,data;`,
1663    {}
1664  );
1665
1666export const queryAllHookData = (rightNs: number): Promise<Array<NativeHookSampleQueryInfo>> =>
1667  query(
1668    'queryAllHookData',
1669    `
1670    select
1671      callchain_id as eventId,
1672      event_type as eventType,
1673      data as subType,
1674      addr,
1675      heap_size as growth,
1676      (n.start_ts - t.start_ts) as startTs,
1677      (n.end_ts - t.start_ts) as endTs
1678    from
1679      native_hook n left join data_dict on n.sub_type_id = data_dict.id,
1680      trace_range t
1681    where
1682      (event_type = 'AllocEvent' or event_type = 'MmapEvent')
1683    and
1684      n.start_ts between t.start_ts and ${rightNs} + t.start_ts`,
1685    { $rightNs: rightNs }
1686  );
1687
1688export const queryNativeHookResponseTypes = (
1689  leftNs: number,
1690  rightNs: number,
1691  types: Array<string>
1692): Promise<Array<any>> =>
1693  query(
1694    'queryNativeHookResponseTypes',
1695    `
1696        select
1697          distinct last_lib_id as lastLibId,
1698          data_dict.data as value
1699        from
1700          native_hook A ,trace_range B
1701          left join data_dict on A.last_lib_id = data_dict.id
1702        where
1703        A.start_ts - B.start_ts
1704        between ${leftNs} and ${rightNs} and A.event_type in (${types.join(',')});
1705    `,
1706    { $leftNs: leftNs, $rightNs: rightNs, $types: types }
1707  );
1708/**
1709 * HiPerf
1710 */
1711export const queryHiPerfEventList = (): Promise<Array<any>> =>
1712  query('queryHiPerfEventList', `select id,report_value from perf_report where report_type='config_name'`, {});
1713export const queryHiPerfEventListData = (eventTypeId: number): Promise<Array<any>> =>
1714  query(
1715    'queryHiPerfEventListData',
1716    `
1717        select s.callchain_id,
1718               (s.timestamp_trace-t.start_ts) startNS
1719        from perf_sample s,trace_range t
1720        where
1721            event_type_id=${eventTypeId}
1722            and s.thread_id != 0
1723            and s.callchain_id != -1;
1724`,
1725    { $eventTypeId: eventTypeId }
1726  );
1727export const queryHiPerfEventData = (eventTypeId: number, cpu: number): Promise<Array<any>> =>
1728  query(
1729    'queryHiPerfEventList',
1730    `
1731    select s.callchain_id,
1732        (s.timestamp_trace-t.start_ts) startNS
1733    from perf_sample s,trace_range t
1734    where
1735        event_type_id=${eventTypeId}
1736        and cpu_id=${cpu}
1737        and s.thread_id != 0
1738        and s.callchain_id != -1;
1739`,
1740    { $eventTypeId: eventTypeId, $cpu: cpu }
1741  );
1742export const queryHiPerfCpuData = (cpu: number): Promise<Array<any>> =>
1743  query(
1744    'queryHiPerfCpuData',
1745    `
1746    select s.callchain_id,
1747        (s.timestamp_trace-t.start_ts) startNS
1748    from perf_sample s,trace_range t
1749    where
1750        cpu_id=${cpu}
1751        and s.thread_id != 0;`,
1752    { $cpu: cpu }
1753  );
1754export const queryHiPerfCpuMergeData = (): Promise<Array<any>> =>
1755  query(
1756    'queryHiPerfCpuData',
1757    `select s.callchain_id,(s.timestamp_trace-t.start_ts) startNS from perf_sample s,trace_range t
1758where s.thread_id != 0;`,
1759    {}
1760  );
1761export const queryHiPerfCpuMergeData2 = (): Promise<Array<any>> =>
1762  query(
1763    'queryHiPerfCpuData2',
1764    `select distinct cpu_id from perf_sample where thread_id != 0 order by cpu_id desc;`,
1765    {}
1766  );
1767
1768export const queryHiPerfProcessData = (pid: number): Promise<Array<any>> =>
1769  query(
1770    'queryHiPerfProcessData',
1771    `
1772SELECT sp.callchain_id,
1773       th.thread_name,
1774       th.thread_id                     tid,
1775       th.process_id                    pid,
1776       sp.timestamp_trace - tr.start_ts startNS
1777from perf_sample sp,
1778     trace_range tr
1779         left join perf_thread th on th.thread_id = sp.thread_id
1780where pid = ${pid} and sp.thread_id != 0 `,
1781    { $pid: pid }
1782  );
1783
1784export const queryHiPerfThreadData = (tid: number): Promise<Array<any>> =>
1785  query(
1786    'queryHiPerfThreadData',
1787    `
1788SELECT sp.callchain_id,
1789       th.thread_name,
1790       th.thread_id                     tid,
1791       th.process_id                    pid,
1792       sp.timestamp_trace - tr.start_ts startNS
1793from perf_sample sp,
1794     trace_range tr
1795         left join perf_thread th on th.thread_id = sp.thread_id
1796where tid = ${tid} and sp.thread_id != 0 ;`,
1797    { $tid: tid }
1798  );
1799
1800export const querySelectTraceStats = (): Promise<
1801  Array<{
1802    event_name: string;
1803    stat_type: string;
1804    count: number;
1805    source: string;
1806    serverity: string;
1807  }>
1808> => query('querySelectTraceStats', 'select event_name,stat_type,count,source,serverity from stat');
1809
1810export const queryCustomizeSelect = (sql: string): Promise<Array<any>> => query('queryCustomizeSelect', sql);
1811
1812export const queryDistributedTerm = (): Promise<
1813  Array<{
1814    threadId: string;
1815    threadName: string;
1816    processId: string;
1817    processName: string;
1818    funName: string;
1819    dur: string;
1820    ts: string;
1821    chainId: string;
1822    spanId: string;
1823    parentSpanId: string;
1824    flag: string;
1825    trace_name: string;
1826  }>
1827> =>
1828  query(
1829    'queryDistributedTerm',
1830    `
1831    select
1832      group_concat(thread.id,',') as threadId,
1833      group_concat(thread.name,',') as threadName,
1834      group_concat(process.id,',') as processId,
1835      group_concat(process.name,',') as processName,
1836      group_concat(callstack.name,',') as funName,
1837      group_concat(callstack.dur,',') as dur,
1838      group_concat(callstack.ts,',') as ts,
1839      cast(callstack.chainId as varchar) as chainId,
1840      callstack.spanId as spanId,
1841      callstack.parentSpanId as parentSpanId,
1842      group_concat(callstack.flag,',') as flag,
1843      (select
1844        value
1845      from
1846        meta
1847      where
1848        name='source_name') as trace_name
1849      from
1850        callstack
1851      inner join thread on callstack.callid = thread.id
1852      inner join process on process.id = thread.ipid
1853      where (callstack.flag='S' or callstack.flag='C')
1854      group by callstack.chainId,callstack.spanId,callstack.parentSpanId`
1855  );
1856
1857export const queryTraceCpu = (): Promise<
1858  Array<{
1859    tid: string;
1860    pid: string;
1861    cpu: string;
1862    dur: string;
1863    min_freq: string;
1864    max_freq: string;
1865    avg_frequency: string;
1866  }>
1867> =>
1868  query(
1869    'queryTraceCpu',
1870    `SELECT
1871        itid AS tid,
1872        ipid AS pid,
1873        group_concat(cpu, ',') AS cpu,
1874        group_concat(dur, ',') AS dur,
1875        group_concat(min_freq, ',') AS min_freq,
1876        group_concat(max_freq, ',') AS max_freq,
1877        group_concat(avg_frequency, ',') AS avg_frequency
1878        FROM
1879        (SELECT
1880            itid,
1881            ipid,
1882            cpu,
1883            CAST (SUM(dur) AS INT) AS dur,
1884            CAST (MIN(freq) AS INT) AS min_freq,
1885            CAST (MAX(freq) AS INT) AS max_freq,
1886            CAST ( (SUM(dur * freq) / SUM(dur) ) AS INT) AS avg_frequency
1887            from
1888            result
1889            group by
1890            itid, cpu
1891        )
1892        GROUP BY
1893        ipid, itid
1894        ORDER BY
1895        ipid
1896    `
1897  );
1898
1899export const queryTraceCpuTop = (): Promise<
1900  Array<{
1901    tid: string;
1902    pid: string;
1903    cpu: string;
1904    duration: string;
1905    min_freq: string;
1906    max_freq: string;
1907    avg_frequency: string;
1908    sumNum: string;
1909  }>
1910> =>
1911  query(
1912    'queryTraceCpuTop',
1913    `SELECT
1914         ipid AS pid,
1915         itid AS tid,
1916        group_concat(cpu, ',') AS cpu,
1917        group_concat(dur, ',') AS dur,
1918        group_concat(avg_frequency, ',') AS avg_frequency,
1919        group_concat(min_freq, ',') AS min_freq,
1920        group_concat(max_freq, ',') AS max_freq,
1921        sum(dur * avg_frequency) AS sumNum
1922        FROM
1923        (SELECT
1924            itid,
1925            ipid,
1926            cpu,
1927            CAST (SUM(dur) AS INT) AS dur,
1928            CAST (MIN(freq) AS INT) AS min_freq,
1929            CAST (MAX(freq) AS INT) AS max_freq,
1930            CAST ( (SUM(dur * freq) / SUM(dur) ) AS INT) AS avg_frequency
1931            from result group by itid, cpu
1932        )
1933        GROUP BY
1934        ipid, itid
1935        ORDER BY
1936        sumNum
1937        DESC
1938        LIMIT 10;
1939    `
1940  );
1941
1942export const queryTraceMemory = (): Promise<
1943  Array<{
1944    maxNum: string;
1945    minNum: string;
1946    avgNum: string;
1947    name: string;
1948    processName: string;
1949  }>
1950> =>
1951  query(
1952    'queryTraceMemory',
1953    `
1954    select
1955        max(value) as maxNum,
1956        min(value) as minNum,
1957        avg(value) as avgNum,
1958        filter.name as name,
1959        p.name as processName
1960        from process_measure
1961        left join process_measure_filter as filter on filter.id= filter_id
1962        left join process as p on p.id = filter.ipid
1963    where
1964    filter_id > 0
1965    and
1966    filter.name = 'mem.rss.anon'
1967    group by
1968    filter_id
1969    order by
1970    avgNum desc`
1971  );
1972
1973export const queryTraceMemoryTop = (): Promise<
1974  Array<{
1975    maxNum: string;
1976    minNum: string;
1977    avgNum: string;
1978    name: string;
1979    processName: string;
1980  }>
1981> =>
1982  query(
1983    'queryTraceMemoryTop',
1984    `
1985    select
1986        max(value) as maxNum,
1987        min(value) as minNum,
1988        avg(value) as avgNum,
1989        f.name as name,
1990        p.name as processName
1991        from process_measure
1992        left join process_measure_filter as f on f.id= filter_id
1993        left join process as p on p.id = f.ipid
1994    where
1995    filter_id > 0
1996    and
1997    f.name = 'mem.rss.anon'
1998    group by
1999    filter_id
2000    order by
2001    avgNum desc limit 10`
2002  );
2003
2004export const queryTraceMemoryUnAgg = (): Promise<
2005  Array<{
2006    processName: string;
2007    name: string;
2008    value: string;
2009    ts: string;
2010  }>
2011> =>
2012  query(
2013    'queryTraceMemoryUnAgg',
2014    `
2015    select
2016        p.name as processName,
2017        group_concat(filter.name) as name,
2018        cast(group_concat(value) as varchar) as value,
2019        cast(group_concat(ts) as varchar) as ts
2020        from process_measure m
2021        left join process_measure_filter as filter on filter.id= m.filter_id
2022        left join process as p on p.id = filter.ipid
2023        where
2024        filter.name = 'mem.rss.anon'
2025        or
2026        filter.name = 'mem.rss.file'
2027        or
2028        filter.name = 'mem.swap'
2029        or
2030        filter.name = 'oom_score_adj'
2031    group by
2032    p.name,filter.ipid
2033    order by
2034    filter.ipid`
2035  );
2036
2037export const queryTraceTaskName = (): Promise<
2038  Array<{
2039    id: string;
2040    pid: string;
2041    process_name: string;
2042    thread_name: string;
2043  }>
2044> =>
2045  query(
2046    'queryTraceTaskName',
2047    `
2048    select
2049        P.id as id,
2050        P.pid as pid,
2051        P.name as process_name,
2052        group_concat(T.name,',') as thread_name
2053    from process as P left join thread as T where P.id = T.ipid
2054    group by pid`
2055  );
2056
2057export const queryTraceMetaData = (): Promise<
2058  Array<{
2059    name: string;
2060    valueText: string;
2061  }>
2062> =>
2063  query(
2064    'queryTraceMetaData',
2065    `
2066    select
2067        cast(name as varchar) as name,
2068        cast(value as varchar) as valueText
2069        from meta
2070        UNION
2071        select 'start_ts',cast(start_ts as varchar) from trace_range
2072        UNION
2073        select 'end_ts',cast(end_ts as varchar) from trace_range`
2074  );
2075
2076export const querySystemCalls = (): Promise<
2077  Array<{
2078    frequency: string;
2079    minDur: string;
2080    maxDur: string;
2081    avgDur: string;
2082    funName: string;
2083  }>
2084> =>
2085  query(
2086    'querySystemCalls',
2087    `
2088    select
2089      count(*) as frequency,
2090      min(dur) as minDur,
2091      max(dur) as maxDur,
2092      avg(dur) as avgDur,
2093      name as funName
2094    from
2095      callstack
2096      group by name
2097      order by
2098    frequency desc limit 100`
2099  );
2100
2101export const querySystemCallsTop = (): Promise<
2102  Array<{
2103    tid: string;
2104    pid: string;
2105    funName: string;
2106    frequency: string;
2107    minDur: string;
2108    maxDur: string;
2109    avgDur: string;
2110  }>
2111> =>
2112  query(
2113    'querySystemCallsTop',
2114    `SELECT
2115        cpu.tid AS tid,
2116        cpu.pid AS pid,
2117        callstack.name AS funName,
2118        count(callstack.name) AS frequency,
2119        min(callstack.dur) AS minDur,
2120        max(callstack.dur) AS maxDur,
2121        round(avg(callstack.dur)) AS avgDur
2122        FROM
2123        callstack
2124        INNER JOIN
2125        (SELECT
2126            itid AS tid,
2127            ipid AS pid,
2128            group_concat(cpu, ',') AS cpu,
2129            group_concat(dur, ',') AS dur,
2130            group_concat(min_freq, ',') AS min_freq,
2131            group_concat(max_freq, ',') AS max_freq,
2132            group_concat(avg_frequency, ',') AS avg_frequency,
2133            sum(dur * avg_frequency) AS sumNum
2134            FROM
2135            (SELECT
2136                itid,
2137                ipid,
2138                cpu,
2139                CAST (SUM(dur) AS INT) AS dur,
2140                CAST (MIN(freq) AS INT) AS min_freq,
2141                CAST (MAX(freq) AS INT) AS max_freq,
2142                CAST ( (SUM(dur * freq) / SUM(dur) ) AS INT) AS avg_frequency
2143                FROM
2144                result
2145                GROUP BY
2146                itid, cpu
2147            )
2148            GROUP BY
2149            ipid, itid
2150            ORDER BY
2151            sumNum
2152            DESC
2153            LIMIT 10
2154        ) AS cpu
2155        ON
2156        callstack.callid = cpu.tid
2157        GROUP BY
2158        callstack.name
2159        ORDER BY
2160        frequency
2161        DESC
2162    LIMIT 10`
2163  );
2164
2165export const getTabLiveProcessData = (leftNs: number, rightNs: number): Promise<Array<LiveProcess>> =>
2166  query<LiveProcess>(
2167    'getTabLiveProcessData',
2168    `SELECT
2169        process.id as processId,
2170        process.name as processName,
2171        process.ppid as responsibleProcess,
2172        process.uud as userName,
2173        process.usag as cpu,
2174        process.threadN as threads,
2175        process.pss as memory,
2176        process.cpu_time as cpuTime,
2177        process.disk_reads as diskReads,
2178        process.disk_writes as diskWrite
2179        FROM
2180        (
2181        SELECT
2182        tt.process_id AS id,
2183        tt.process_name AS name,
2184        tt.parent_process_id AS ppid,
2185        tt.uid as uud,
2186        tt.cpu_usage as usag,
2187        tt.thread_num AS threadN,
2188        mt.maxTT - TR.start_ts as endTs,
2189        tt.pss_info as pss,
2190        tt.cpu_time,
2191        tt.disk_reads,
2192        tt.disk_writes
2193        FROM
2194        live_process tt
2195        LEFT JOIN trace_range AS TR
2196        LEFT JOIN (select re.process_id as idd, max(re.ts) as maxTT, min(re.ts) as minTT
2197        from live_process re GROUP BY re.process_name, re.process_id ) mt
2198        on mt.idd = tt.process_id where endTs >= $rightNS
2199        GROUP BY
2200        tt.process_name,
2201        tt.process_id
2202        ) process ;`,
2203    { $leftNS: leftNs, $rightNS: rightNs }
2204  );
2205
2206export const getTabProcessHistoryData = (
2207  leftNs: number,
2208  rightNs: number,
2209  processId: number | undefined,
2210  threadId: number | undefined
2211): Promise<Array<ProcessHistory>> =>
2212  query<ProcessHistory>(
2213    'getTabProcessHistoryData',
2214    `SELECT
2215        process.id as processId,
2216        process.isD as alive,
2217        process.startTS as firstSeen,
2218        process.endTs as lastSeen,
2219        process.name as processName,
2220        process.ppid as responsibleProcess,
2221        process.uuid as userName,
2222        process.cpu_time as cpuTime,
2223        0 as pss
2224        FROM
2225        (
2226        SELECT
2227        tt.process_id AS id,
2228        tt.process_name AS name,
2229        tt.parent_process_id AS ppid,
2230        tt.uid AS uuid,
2231        tt.cpu_time,
2232        (mt.minTT - TR.start_ts ) AS startTS,
2233        mt.maxTT - TR.start_ts as endTs,
2234        (mt.maxTT - TR.start_ts - $rightNS) > 0 as isD
2235        FROM
2236        live_process tt
2237        LEFT JOIN trace_range AS TR
2238        LEFT JOIN (select re.process_id as idd, max(re.ts) as maxTT, min(re.ts) as minTT
2239        from live_process re GROUP BY re.process_name, re.process_id ) mt
2240        on mt.idd = tt.process_id
2241        GROUP BY
2242        tt.process_name,
2243        tt.process_id
2244        ) process;`,
2245    {
2246      $leftNS: leftNs,
2247      $rightNS: rightNs,
2248      $processID: processId,
2249      $threadID: threadId,
2250    }
2251  );
2252
2253export const getTabCpuAbilityData = (leftNs: number, rightNs: number): Promise<Array<SystemCpuSummary>> =>
2254  query<SystemCpuSummary>(
2255    'getTabCpuAbilityData',
2256    `SELECT
2257        ( n.ts - TR.start_ts ) AS startTime,
2258        n.dur AS duration,
2259        n.total_load AS totalLoad,
2260        n.user_load AS userLoad,
2261        n.system_load AS systemLoad,
2262        n.process_num AS threads
2263        FROM
2264        cpu_usage AS n,
2265        trace_range AS TR
2266        WHERE
2267        ( n.ts - TR.start_ts ) >= ifnull((
2268        SELECT
2269        ( usage.ts - TR.start_ts )
2270        FROM
2271        cpu_usage usage,
2272        trace_range TR
2273        WHERE
2274        ( usage.ts - TR.start_ts ) <= $leftNS
2275        ORDER BY
2276        usage.ts DESC
2277        LIMIT 1
2278        ),0)
2279        AND ( n.ts - TR.start_ts ) <= $rightNS
2280        ORDER BY
2281        startTime ASC;
2282    `,
2283    { $leftNS: leftNs, $rightNS: rightNs }
2284  );
2285
2286export const getTabMemoryAbilityData = (
2287  leftNs: number,
2288  rightNs: number
2289): Promise<
2290  Array<{
2291    startTime: number;
2292    value: string;
2293    name: string;
2294  }>
2295> =>
2296  query(
2297    'getTabMemoryAbilityData',
2298    `SELECT
2299        m.ts AS startTime,
2300        GROUP_CONCAT( IFNULL( m.value, 0 ) ) AS value,
2301        GROUP_CONCAT( f.name ) AS name
2302        FROM
2303        sys_mem_measure AS m
2304        INNER JOIN sys_event_filter AS f ON m.filter_id = f.id
2305        AND (f.name = 'sys.mem.total'
2306         or f.name = 'sys.mem.free'
2307         or f.name = 'sys.mem.buffers'
2308         or f.name = 'sys.mem.cached'
2309         or f.name = 'sys.mem.shmem'
2310         or f.name = 'sys.mem.slab'
2311         or f.name = 'sys.mem.swap.total'
2312         or f.name = 'sys.mem.swap.free'
2313         or f.name = 'sys.mem.mapped'
2314         or f.name = 'sys.mem.vmalloc.used'
2315         or f.name = 'sys.mem.page.tables'
2316         or f.name = 'sys.mem.kernel.stack'
2317         or f.name = 'sys.mem.active'
2318         or f.name = 'sys.mem.inactive'
2319         or f.name = 'sys.mem.unevictable'
2320         or f.name = 'sys.mem.vmalloc.total'
2321         or f.name = 'sys.mem.slab.unreclaimable'
2322         or f.name = 'sys.mem.cma.total'
2323         or f.name = 'sys.mem.cma.free'
2324         or f.name = 'sys.mem.kernel.reclaimable'
2325         or f.name = 'sys.mem.zram'
2326         )
2327        AND m.ts >= ifnull((
2328        SELECT
2329        m.ts AS startTime
2330        FROM
2331        sys_mem_measure AS m
2332        INNER JOIN sys_event_filter AS f ON m.filter_id = f.id
2333        AND m.ts <= $leftNS
2334        AND (f.name = 'sys.mem.total'
2335         or f.name = 'sys.mem.kernel.stack'
2336         or f.name = 'sys.mem.free'
2337         or f.name = 'sys.mem.swap.free'
2338         or f.name = 'sys.mem.cma.free'
2339         or f.name = 'sys.mem.inactive'
2340         or f.name = 'sys.mem.buffers'
2341         or f.name = 'sys.mem.cached'
2342         or f.name = 'sys.mem.shmem'
2343         or f.name = 'sys.mem.slab'
2344         or f.name = 'sys.mem.swap.total'
2345         or f.name = 'sys.mem.vmalloc.used'
2346         or f.name = 'sys.mem.page.tables'
2347         or f.name = 'sys.mem.active'
2348         or f.name = 'sys.mem.unevictable'
2349         or f.name = 'sys.mem.vmalloc.total'
2350         or f.name = 'sys.mem.slab.unreclaimable'
2351         or f.name = 'sys.mem.cma.total'
2352         or f.name = 'sys.mem.mapped'
2353         or f.name = 'sys.mem.kernel.reclaimable'
2354         or f.name = 'sys.mem.zram'
2355         )
2356        ORDER BY
2357        m.ts DESC
2358        LIMIT 1
2359        ),0)
2360        AND m.ts <= $rightNS GROUP BY m.ts;`,
2361    { $leftNS: leftNs, $rightNS: rightNs }
2362  );
2363
2364export const getTabNetworkAbilityData = (leftNs: number, rightNs: number): Promise<Array<SystemNetworkSummary>> =>
2365  query<SystemNetworkSummary>(
2366    'getTabNetworkAbilityData',
2367    `SELECT
2368            ( n.ts - TR.start_ts ) AS startTime,
2369            n.dur AS duration,
2370            n.rx AS dataReceived,
2371            n.tx_speed AS dataReceivedSec,
2372            n.tx AS dataSend,
2373            n.rx_speed AS dataSendSec,
2374            n.packet_in AS packetsIn,
2375            n.packet_in_sec AS packetsInSec,
2376            n.packet_out AS packetsOut,
2377            n.packet_out_sec AS packetsOutSec
2378            FROM
2379            network AS n,
2380            trace_range AS TR
2381            WHERE
2382            ( n.ts - TR.start_ts ) >= ifnull((
2383            SELECT
2384            ( nn.ts - T.start_ts ) AS startTime
2385            FROM
2386            network nn,
2387            trace_range T
2388            WHERE
2389            ( nn.ts - T.start_ts ) <= $leftNS
2390            ORDER BY
2391            nn.ts DESC
2392            LIMIT 1
2393            ),0)
2394            AND ( n.ts - TR.start_ts ) <= $rightNS
2395            ORDER BY
2396            startTime ASC`,
2397    { $leftNS: leftNs, $rightNS: rightNs }
2398  );
2399
2400export const getTabDiskAbilityData = (leftNs: number, rightNs: number): Promise<Array<SystemDiskIOSummary>> =>
2401  query<SystemDiskIOSummary>(
2402    'getTabDiskAbilityData',
2403    `SELECT
2404        ( n.ts - TR.start_ts ) AS startTime,
2405        n.dur AS duration,
2406        n.rd AS dataRead,
2407        n.rd_speed AS dataReadSec,
2408        n.wr AS dataWrite,
2409        n.wr_speed AS dataWriteSec,
2410        n.rd_count AS readsIn,
2411        n.rd_count_speed AS readsInSec,
2412        n.wr_count AS writeOut,
2413        n.wr_count_speed AS writeOutSec
2414        FROM
2415        diskio AS n,
2416        trace_range AS TR
2417        WHERE
2418        ( n.ts - TR.start_ts ) >= ifnull((
2419        SELECT
2420        ( nn.ts - T.start_ts ) AS startTime
2421        FROM
2422        diskio AS nn,
2423        trace_range AS T
2424        WHERE
2425        ( nn.ts - T.start_ts ) <= $leftNS
2426        ORDER BY
2427        nn.ts DESC
2428        LIMIT 1
2429        ),0)
2430        AND ( n.ts - TR.start_ts ) <= $rightNS
2431        ORDER BY
2432        startTime ASC;
2433    `,
2434    { $leftNS: leftNs, $rightNS: rightNs }
2435  );
2436
2437export const queryCpuAbilityData = (): Promise<Array<CpuAbilityMonitorStruct>> =>
2438  query(
2439    'queryCpuAbilityData',
2440    `select
2441        (t.total_load) as value,
2442        (t.ts - TR.start_ts) as startNS
2443        from cpu_usage t, trace_range AS TR;`
2444  );
2445
2446export const queryCpuAbilityUserData = (): Promise<Array<CpuAbilityMonitorStruct>> =>
2447  query(
2448    'queryCpuAbilityUserData',
2449    `select
2450        t.user_load as value,
2451        (t.ts - TR.start_ts) as startNS
2452        from cpu_usage t, trace_range AS TR;`
2453  );
2454
2455export const queryCpuAbilitySystemData = (): Promise<Array<CpuAbilityMonitorStruct>> =>
2456  query(
2457    'queryCpuAbilitySystemData',
2458    `select
2459        t.system_load as value,
2460        (t.ts - TR.start_ts) as startNS
2461        from cpu_usage t, trace_range AS TR;`
2462  );
2463
2464export const queryMemoryUsedAbilityData = (id: string): Promise<Array<MemoryAbilityMonitorStruct>> =>
2465  query(
2466    'queryMemoryUsedAbilityData',
2467    `select
2468        t.value as value,
2469        (t.ts - TR.start_ts) as startNS
2470        from sys_mem_measure t, trace_range AS TR where t.filter_id = $id;`,
2471    { $id: id }
2472  );
2473
2474export const queryCachedFilesAbilityData = (id: string): Promise<Array<MemoryAbilityMonitorStruct>> =>
2475  query(
2476    'queryCachedFilesAbilityData',
2477    `select
2478        t.value as value,
2479        (t.ts - TR.start_ts) as startNS
2480        from sys_mem_measure t, trace_range AS TR where t.filter_id = $id;`,
2481    { $id: id }
2482  );
2483
2484export const queryCompressedAbilityData = (id: string): Promise<Array<MemoryAbilityMonitorStruct>> =>
2485  query(
2486    'queryCompressedAbilityData',
2487    `select
2488        t.value as value,
2489        (t.ts - TR.start_ts) as startNS
2490        from sys_mem_measure t, trace_range AS TR where t.filter_id = $id;`,
2491    { $id: id }
2492  );
2493
2494export const querySwapUsedAbilityData = (id: string): Promise<Array<MemoryAbilityMonitorStruct>> =>
2495  query(
2496    'querySwapUsedAbilityData',
2497    `select
2498        t.value as value,
2499        (t.ts - TR.start_ts) as startNS
2500        from sys_mem_measure t, trace_range AS TR where t.filter_id = $id;`,
2501    { $id: id }
2502  );
2503
2504export const queryBytesReadAbilityData = (): Promise<Array<DiskAbilityMonitorStruct>> =>
2505  query(
2506    'queryBytesReadAbilityData',
2507    `select
2508        t.rd_speed as value,
2509        (t.ts - TR.start_ts) as startNS
2510        from diskio t, trace_range AS TR;`
2511  );
2512
2513export const queryBytesWrittenAbilityData = (): Promise<Array<DiskAbilityMonitorStruct>> =>
2514  query(
2515    'queryBytesWrittenAbilityData',
2516    `select
2517        t.wr_speed as value,
2518        (t.ts - TR.start_ts) as startNS
2519        from diskio t, trace_range AS TR;`
2520  );
2521
2522export const queryReadAbilityData = (): Promise<Array<DiskAbilityMonitorStruct>> =>
2523  query(
2524    'queryReadAbilityData',
2525    `select
2526        t.rd_count_speed as value,
2527        (t.ts - TR.start_ts) as startNS
2528        from diskio t, trace_range AS TR;`
2529  );
2530
2531export const queryWrittenAbilityData = (): Promise<Array<DiskAbilityMonitorStruct>> =>
2532  query(
2533    'queryWrittenAbilityData',
2534    `select
2535        t.wr_count_speed as value,
2536        (t.ts - TR.start_ts) as startNS
2537        from diskio t, trace_range AS TR;`
2538  );
2539
2540export const queryBytesInAbilityData = (): Promise<Array<NetworkAbilityMonitorStruct>> =>
2541  query(
2542    'queryBytesInAbilityData',
2543    `select
2544        t.tx_speed as value,
2545        (t.ts - TR.start_ts) as startNS
2546        from network t, trace_range AS TR;`
2547  );
2548
2549export const queryBytesOutAbilityData = (): Promise<Array<NetworkAbilityMonitorStruct>> =>
2550  query(
2551    'queryBytesOutAbilityData',
2552    `select
2553        t.rx_speed as value,
2554        (t.ts - TR.start_ts) as startNS
2555        from network t, trace_range AS TR;`
2556  );
2557
2558export const queryPacketsInAbilityData = (): Promise<Array<NetworkAbilityMonitorStruct>> =>
2559  query(
2560    'queryPacketsInAbilityData',
2561    `select
2562        t.packet_in_sec as value,
2563        (t.ts - TR.start_ts) as startNS
2564        from network t, trace_range AS TR;`
2565  );
2566
2567export const queryPacketsOutAbilityData = (): Promise<Array<NetworkAbilityMonitorStruct>> =>
2568  query(
2569    'queryPacketsOutAbilityData',
2570    `select
2571        t.packet_out_sec as value,
2572        (t.ts - TR.start_ts) as startNS
2573        from network t, trace_range AS TR;`
2574  );
2575
2576export const queryNetWorkMaxData = (): Promise<Array<any>> =>
2577  query(
2578    'queryNetWorkMaxData',
2579    `select
2580     ifnull(max(tx_speed),0) as maxIn,
2581     ifnull(max(rx_speed),0) as maxOut,
2582     ifnull(max(packet_in_sec),0) as maxPacketIn,
2583     ifnull(max(packet_in_sec),0) as maxPacketOut
2584     from network`
2585  );
2586
2587export const queryMemoryMaxData = (memoryName: string): Promise<Array<any>> =>
2588  query(
2589    'queryMemoryMaxData',
2590    `SELECT ifnull(max(m.value),0) as maxValue,
2591            filter_id
2592            from sys_mem_measure m
2593            WHERE m.filter_id =
2594            (SELECT id FROM sys_event_filter WHERE name = $memoryName)
2595`,
2596    { $memoryName: memoryName }
2597  );
2598
2599export const queryDiskIoMaxData = (): Promise<Array<any>> =>
2600  query(
2601    'queryDiskIoMaxData',
2602    `select
2603    ifnull(max(rd_speed),0) as bytesRead,
2604    ifnull(max(wr_speed),0) as bytesWrite,
2605    ifnull(max(rd_count_speed),0) as readOps,
2606    ifnull(max(wr_count_speed),0)  as writeOps
2607    from diskio`
2608  );
2609
2610export const queryAbilityExits = (): Promise<Array<any>> =>
2611  query(
2612    'queryAbilityExits',
2613    `select
2614      event_name
2615      from stat s
2616      where s.event_name in ('trace_diskio','trace_network', 'trace_cpu_usage','sys_memory')
2617      and s.stat_type ='received' and s.count > 0`
2618  );
2619
2620export const queryStartTime = (): Promise<Array<any>> => query('queryStartTime', `SELECT start_ts FROM trace_range`);
2621
2622export const queryPerfFiles = (): Promise<Array<PerfFile>> =>
2623  query('queryPerfFiles', `select file_id as fileId,symbol,path from perf_files`, {});
2624
2625export const queryPerfProcess = (): Promise<Array<PerfThread>> =>
2626  query(
2627    'queryPerfThread',
2628    `select process_id as pid,thread_name as processName from perf_thread where process_id = thread_id`,
2629    {}
2630  );
2631
2632export const queryPerfThread = (): Promise<Array<PerfThread>> =>
2633  query(
2634    'queryPerfThread',
2635    `select a.thread_id as tid,a.thread_name as threadName,a.process_id as pid,b.thread_name as processName from perf_thread a left join (select * from perf_thread where thread_id = process_id) b on a.process_id = b.thread_id`,
2636    {}
2637  );
2638
2639export const queryPerfSampleListByTimeRange = (
2640  leftNs: number,
2641  rightNs: number,
2642  cpus: Array<number>,
2643  processes: Array<number>,
2644  threads: Array<number>
2645): Promise<Array<PerfSample>> => {
2646  let sql = `
2647select A.callchain_id as sampleId,
2648       A.thread_id as tid,
2649       C.thread_name as threadName,
2650       A.thread_state as state,
2651       C.process_id as pid,
2652       (timestamp_trace - R.start_ts) as time,
2653       cpu_id as core
2654from perf_sample A,trace_range R
2655left join perf_thread C on A.thread_id = C.thread_id
2656where time >= $leftNs and time <= $rightNs and A.thread_id != 0
2657    `;
2658  if (cpus.length != 0 || processes.length != 0 || threads.length != 0) {
2659    let arg1 = cpus.length > 0 ? `or core in (${cpus.join(',')}) ` : '';
2660    let arg2 = processes.length > 0 ? `or pid in (${processes.join(',')}) ` : '';
2661    let arg3 = threads.length > 0 ? `or tid in (${threads.join(',')})` : '';
2662    let arg = `${arg1}${arg2}${arg3}`.substring(3);
2663    sql = `${sql} and (${arg})`;
2664  }
2665  return query('queryPerfSampleListByTimeRange', sql, {
2666    $leftNs: leftNs,
2667    $rightNs: rightNs,
2668  });
2669};
2670
2671export const queryPerfSampleIdsByTimeRange = (
2672  leftNs: number,
2673  rightNs: number,
2674  cpus: Array<number>,
2675  processes: Array<number>,
2676  threads: Array<number>
2677): Promise<Array<PerfSample>> => {
2678  let sql = `
2679select A.callchain_id as sampleId
2680from perf_sample A,trace_range R
2681left join perf_thread C on A.thread_id = C.thread_id
2682where (timestamp_trace - R.start_ts) >= $leftNs and (timestamp_trace - R.start_ts) <= $rightNs and A.thread_id != 0
2683    `;
2684  if (cpus.length != 0 || processes.length != 0 || threads.length != 0) {
2685    let arg1 = cpus.length > 0 ? `or A.cpu_id in (${cpus.join(',')}) ` : '';
2686    let arg2 = processes.length > 0 ? `or C.process_id in (${processes.join(',')}) ` : '';
2687    let arg3 = threads.length > 0 ? `or A.thread_id in (${threads.join(',')})` : '';
2688    let arg = `${arg1}${arg2}${arg3}`.substring(3);
2689    sql = `${sql} and (${arg})`;
2690  }
2691  return query('queryPerfSampleIdsByTimeRange', sql, {
2692    $leftNs: leftNs,
2693    $rightNs: rightNs,
2694  });
2695};
2696
2697export const queryPerfSampleCallChain = (sampleId: number): Promise<Array<PerfStack>> =>
2698  query(
2699    'queryPerfSampleCallChain',
2700    `
2701    select
2702    callchain_id as callChainId,
2703    callchain_id as sampleId,
2704    file_id as fileId,
2705    symbol_id as symbolId,
2706    vaddr_in_file as vaddrInFile,
2707    name as symbol
2708from perf_callchain where callchain_id = $sampleId and symbol_id != -1 and vaddr_in_file != 0;
2709    `,
2710    { $sampleId: sampleId }
2711  );
2712
2713export const queryPerfCmdline = (): Promise<Array<PerfCmdLine>> =>
2714  query(
2715    'queryPerfCmdline',
2716    `
2717    select report_value from perf_report  where report_type = 'cmdline'
2718    `,
2719    {}
2720  );
2721
2722export const queryCPuAbilityMaxData = (): Promise<Array<any>> =>
2723  query(
2724    'queryCPuAbilityMaxData',
2725    `select ifnull(max(total_load),0) as totalLoad,
2726                ifnull(max(user_load),0) as userLoad,
2727                ifnull(max(system_load),0) as systemLoad
2728                from cpu_usage`
2729  );
2730
2731export const querySearchFunc = (search: string): Promise<Array<SearchFuncBean>> =>
2732  query(
2733    'querySearchFunc',
2734    `
2735   select c.cookie,c.id,c.name as funName,c.ts - r.start_ts as startTime,c.dur,c.depth,t.tid,t.name as threadName
2736   ,p.pid ,'func' as type from callstack c left join thread t on c.callid = t.id left join process p on t.ipid = p.id
2737   left join trace_range r
2738   where c.name like '%${search}%' and startTime > 0;
2739    `,
2740    { $search: search }
2741  );
2742
2743export const querySceneSearchFunc = (search: string, processList: Array<string>): Promise<Array<SearchFuncBean>> =>
2744  query(
2745    'querySearchFunc',
2746    `
2747   select c.cookie,c.id,c.name as funName,c.ts - r.start_ts as startTime,c.dur,c.depth,t.tid,t.name as threadName
2748   ,p.pid ,'func' as type from callstack c left join thread t on c.callid = t.id left join process p on t.ipid = p.id
2749   left join trace_range r
2750   where c.name like '%${search}%' and startTime > 0 and p.pid in (${processList.join(',')});
2751    `,
2752    { $search: search }
2753  );
2754
2755export const queryBinderBySliceId = (id: number): Promise<Array<any>> =>
2756  query(
2757    'queryBinderBySliceId',
2758    `select c.ts-D.start_ts as startTime,
2759    c.dur,
2760    t.tid,p.pid,c.depth
2761    from callstack c,trace_range D
2762    left join thread t on c.callid = t.id
2763    left join process p on p.id = t.ipid
2764where cat = 'binder' and c.id = $id;`,
2765    { $id: id }
2766  );
2767
2768export const queryThreadByItid = (itid: number, ts: number): Promise<Array<any>> =>
2769  query(
2770    'queryThreadByItid',
2771    `select tid,pid,c.dur,c.depth,c.name
2772from thread t left join process p on t.ipid = p.ipid
2773left join callstack c on t.itid = c.callid
2774where itid = $itid and c.ts = $ts;`,
2775    { $itid: itid, $ts: ts }
2776  );
2777
2778export const queryBinderByArgsId = (id: number, startTime: number, isNext: boolean): Promise<Array<any>> => {
2779  let sql = `select c.ts - D.start_ts as startTime,
2780    c.dur,
2781    t.tid,p.pid,c.depth
2782    from callstack c,trace_range D
2783    left join thread t on c.callid = t.id
2784    left join process p on p.id = t.ipid
2785where cat = 'binder' and  c.argsetid = $id`;
2786  if (isNext) {
2787    sql += ' and c.ts > $startTime +  D.start_ts';
2788  } else {
2789    sql += ' and c.ts < $startTime +  D.start_ts';
2790  }
2791  return query('queryBinderByArgsId', sql, {
2792    $id: id,
2793    $startTime: startTime,
2794  });
2795};
2796
2797export const getTabPaneFilesystemStatisticsFather = (leftNs: number, rightNs: number): Promise<Array<any>> =>
2798  query(
2799    'getTabPaneFilesystemStatisticsFather',
2800    `
2801    select SUM(dur) as allDuration,
2802    count(f.type) as count,
2803    min(dur) as minDuration,
2804    max(dur) as maxDuration,
2805    round(avg(dur),2) as avgDuration,
2806    p.name,
2807    f.type,
2808    p.pid,
2809    sum(ifnull(size,0)) as size
2810    from file_system_sample as f
2811    left join process as p on f.ipid=p.ipid
2812    where f.start_ts >= $leftNs
2813    and end_ts <= $rightNs
2814    group by f.type;
2815    `,
2816    { $leftNs: leftNs, $rightNs: rightNs }
2817  );
2818
2819export const getTabPaneFilesystemStatisticsChild = (leftNs: number, rightNs: number): Promise<Array<any>> =>
2820  query(
2821    'getTabPaneFilesystemStatisticsChild',
2822    `
2823    select SUM(dur)    as allDuration,
2824        count(f.type) as count,
2825        min(dur)    as minDuration,
2826        max(dur)    as maxDuration,
2827        round(avg(dur),2)    as avgDuration,
2828        p.name,
2829        p.pid,
2830        f.type,
2831        sum(ifnull(size,0))    as size
2832        from file_system_sample as f left join process as p on f.ipid=p.ipid
2833        where f.start_ts >= $leftNs
2834        and end_ts <= $rightNs
2835        group by f.type, f.ipid;
2836`,
2837    { $leftNs: leftNs, $rightNs: rightNs }
2838  );
2839
2840export const getTabPaneFilesystemStatisticsAll = (leftNs: number, rightNs: number): Promise<Array<any>> =>
2841  query(
2842    'getTabPaneFilesystemStatisticsAll',
2843    `
2844    select SUM(dur)    as allDuration,
2845       count(type) as count,
2846       min(dur)    as minDuration,
2847       max(dur)    as maxDuration,
2848       round(avg(dur),2)    as avgDuration,
2849       type
2850    from file_system_sample
2851    where start_ts >= $leftNs
2852    and end_ts <= $rightNs;
2853`,
2854    { $leftNs: leftNs, $rightNs: rightNs }
2855  );
2856
2857export const getTabPaneFilesystemStatistics = (leftNs: number, rightNs: number, types: number[]): Promise<Array<any>> =>
2858  query(
2859    'getTabPaneFilesystemStatistics',
2860    `
2861    select p.pid,
2862       ifnull(p.name,'Process') as name,
2863       f.type,
2864       count(f.ipid) as count,
2865       sum(ifnull(size,0)) as size,
2866       sum(case when f.type = 2 then ifnull(size,0) else 0 end) as logicalReads,
2867       sum(case when f.type = 3 then ifnull(size,0) else 0 end) as logicalWrites,
2868       sum(case when f.type != 2 and f.type != 3 then ifnull(size,0) else 0 end) as otherFile,
2869       sum(dur) as allDuration,
2870       min(dur) as minDuration,
2871       max(dur) as maxDuration,
2872       avg(dur) as avgDuration
2873    from file_system_sample as f left join process as p on f.ipid=p.ipid
2874    where end_ts >= $leftNs
2875    and end_ts <= $rightNs
2876    and f.type in (${types.join(',')})
2877    group by f.type,f.ipid
2878    order by f.type;
2879`,
2880    { $leftNs: leftNs, $rightNs: rightNs }
2881  );
2882
2883export const getTabPaneVirtualMemoryStatisticsData = (leftNs: number, rightNs: number): Promise<Array<any>> =>
2884  query(
2885    'getTabPaneVirtualMemoryStatisticsData',
2886    `
2887    select p.pid,
2888       t.tid,
2889       ifnull(p.name,'Process') as pname,
2890       ifnull(t.name,'Thread') as tname,
2891       f.type,
2892       f.ipid,
2893       f.itid,
2894       count(f.ipid) as count,
2895       sum(dur) as allDuration,
2896       min(dur) as minDuration,
2897       max(dur) as maxDuration,
2898       avg(dur) as avgDuration
2899    from paged_memory_sample as f left join process as p on f.ipid=p.ipid left join thread as t on f.itid=t.itid
2900    where f.end_ts >= $leftNs
2901    and f.end_ts <= $rightNs
2902    group by f.type,f.ipid,f.itid
2903    order by f.type;
2904`,
2905    { $leftNs: leftNs, $rightNs: rightNs }
2906  );
2907
2908export const getTabPaneIOTierStatisticsData = (
2909  leftNs: number,
2910  rightNs: number,
2911  diskIOipids: Array<number>
2912): Promise<Array<any>> => {
2913  let str = '';
2914  if (diskIOipids.length > 0) {
2915    str = ` and i.ipid in (${diskIOipids.join(',')})`;
2916  }
2917  return query(
2918    'getTabPaneIOTierStatisticsData',
2919    `
2920    select p.pid,
2921       ifnull(p.name,'Process') as pname,
2922       i.tier,
2923       i.ipid,
2924       path_id as path,
2925       count(i.ipid) as count,
2926       sum(latency_dur) as allDuration,
2927       min(latency_dur) as minDuration,
2928       max(latency_dur) as maxDuration,
2929       avg(latency_dur) as avgDuration
2930    from bio_latency_sample as i left join process as p on i.ipid=p.ipid
2931    where i.start_ts+latency_dur >= $leftNs
2932    and i.start_ts+latency_dur <= $rightNs
2933    ${str}
2934    group by i.tier,i.ipid,i.path_id
2935    order by i.tier;
2936`,
2937    { $leftNs: leftNs, $rightNs: rightNs }
2938  );
2939};
2940
2941export const getTabPaneCounterSampleData = (
2942  leftNs: number,
2943  rightNs: number,
2944  cpuStateFilterIds: Array<number>
2945): Promise<Array<any>> => {
2946  let str = '';
2947  if (cpuStateFilterIds.length > 0) {
2948    str = ` and filter_id in (${cpuStateFilterIds.join(',')})`;
2949  }
2950  return query(
2951    'getTabPaneCounterSampleData',
2952    `
2953    select value, filter_id as filterId, ts, f.cpu
2954    from measure left join cpu_measure_filter as f on f.id=filter_id
2955    where
2956    ts <= $rightNs${str} order by ts asc;
2957`,
2958    { $leftNs: leftNs, $rightNs: rightNs }
2959  );
2960};
2961
2962export const getTabPaneFrequencySampleData = (
2963  leftNs: number,
2964  rightNs: number,
2965  cpuFreqFilterIds: Array<number>
2966): Promise<Array<any>> => {
2967  let str = '';
2968  if (cpuFreqFilterIds.length > 0) {
2969    str = ` and filter_id in (${cpuFreqFilterIds.join(',')})`;
2970  }
2971  return query(
2972    'getTabPaneFrequencySampleData',
2973    `
2974    select value, filter_id as filterId, ts, f.cpu
2975    from measure left join cpu_measure_filter as f on f.id=filter_id
2976    where
2977    ts <= $rightNs${str} order by ts asc;
2978`,
2979    { $leftNs: leftNs, $rightNs: rightNs }
2980  );
2981};
2982
2983export const hasFileSysData = (): Promise<Array<any>> =>
2984  query(
2985    'hasFileSysData',
2986    `
2987    select
2988        fsCount,
2989        vmCount,
2990        ioCount from
2991        (select count(1) as fsCount from file_system_sample s,trace_range t where (s.start_ts between t.start_ts and t.end_ts) or (s.end_ts between t.start_ts and t.end_ts) )
2992        ,(select count(1) as vmCount from paged_memory_sample s,trace_range t where (s.start_ts between t.start_ts and t.end_ts) or (s.end_ts between t.start_ts and t.end_ts) )
2993        ,(select count(1) as ioCount from bio_latency_sample s,trace_range t where (s.start_ts between t.start_ts and t.end_ts) or (s.end_ts between t.start_ts and t.end_ts) );
2994    `,
2995    {}
2996  );
2997
2998export const getFileSysChartDataByType = (type: number): Promise<Array<any>> =>
2999  query(
3000    'getFileSysChartData',
3001    `
3002    select
3003       (A.start_ts -B.start_ts) as startNS,
3004       (A.end_ts - B.start_ts) as endNS,
3005       dur
3006    from file_system_sample A,trace_range B
3007    where type = $type and startNS > 0;`,
3008    { $type: type },
3009    'exec'
3010  );
3011
3012export const getFileSysVirtualMemoryChartData = (): Promise<Array<any>> =>
3013  query(
3014    'getFileSysVirtualMemoryChartData',
3015    `
3016    select
3017       (A.start_ts -B.start_ts) as startNS,
3018       (A.end_ts - B.start_ts) as endNS,
3019       dur as dur
3020    from paged_memory_sample A,trace_range B
3021    where startNS > 0
3022    order by A.start_ts;`,
3023    {},
3024    'exec'
3025  );
3026
3027export const getDiskIOProcess = (): Promise<Array<any>> =>
3028  query(
3029    'getDiskIOProcess',
3030    `
3031    select name,B.ipid,pid
3032    from (select distinct ipid from bio_latency_sample A,trace_range B where A.start_ts between B.start_ts and B.end_ts) A
3033    left join process B on A.ipid = B.ipid;`,
3034    {}
3035  );
3036
3037export const getDiskIOLatencyChartDataByProcess = (
3038  all: boolean,
3039  ipid: number,
3040  typeArr: Array<number>
3041): Promise<Array<any>> =>
3042  query(
3043    'getDiskIOLatencyChartDataByProcess',
3044    `
3045    select
3046       (A.start_ts -B.start_ts) as startNS,
3047       (A.start_ts - B.start_ts + A.latency_dur) as endNS,
3048       latency_dur as dur
3049    from bio_latency_sample A,trace_range B
3050    where type in (${typeArr.join(',')}) and startNS > 0
3051        ${all ? '' : 'and ipid = ' + ipid}
3052    order by A.start_ts;`,
3053    {},
3054    'exec'
3055  );
3056
3057export const querySdkCount = (sql: string, componentId: number, args?: any): Promise<Array<any>> =>
3058  query('querySdkCount', sql, args, 'exec-sdk-' + componentId);
3059
3060export const querySdkCounterData = (
3061  sql: string,
3062  counter_id: number,
3063  componentId: number
3064): Promise<Array<CounterStruct>> =>
3065  query('querySdkCounterData', sql, { $counter_id: counter_id }, 'exec-sdk-' + componentId);
3066
3067export const getTabSdkCounterData = (
3068  sqlStr: string,
3069  startTime: number,
3070  leftNs: number,
3071  rightNs: number,
3072  counters: Array<string>,
3073  componentId: number
3074): Promise<Array<CounterSummary>> =>
3075  query<CounterSummary>(
3076    'getTabSdkCounterData',
3077    sqlStr,
3078    {
3079      $startTime: startTime,
3080      $leftNs: leftNs,
3081      $rightNs: rightNs,
3082      $counters: counters,
3083    },
3084    'exec-sdk-' + componentId
3085  );
3086
3087export const getTabSdkCounterLeftData = (
3088  sqlStr: string,
3089  leftNs: number,
3090  counters: Array<string>,
3091  componentId: number
3092): Promise<Array<any>> =>
3093  query<any>(
3094    'getTabSdkCounterLeftData',
3095    sqlStr,
3096    {
3097      $leftNs: leftNs,
3098      $counters: counters,
3099    },
3100    'exec-sdk-' + componentId
3101  );
3102
3103export const getTabSdkSliceData = (
3104  sqlStr: string,
3105  startTime: number,
3106  leftNs: number,
3107  rightNs: number,
3108  slices: Array<string>,
3109  componentId: number
3110): Promise<Array<SdkSliceSummary>> =>
3111  query<SdkSliceSummary>(
3112    'getTabSdkSliceData',
3113    sqlStr,
3114    {
3115      $startTime: startTime,
3116      $leftNs: leftNs,
3117      $rightNs: rightNs,
3118      $slices: slices,
3119    },
3120    'exec-sdk-' + componentId
3121  );
3122
3123export const querySdkSliceData = (
3124  sqlStr: string,
3125  column_id: number,
3126  startNS: number,
3127  endNS: number,
3128  componentId: number
3129): Promise<Array<SdkSliceStruct>> =>
3130  query(
3131    'querySdkSliceData',
3132    sqlStr,
3133    { $column_id: column_id, $startNS: startNS, $endNS: endNS },
3134    'exec-sdk-' + componentId
3135  );
3136
3137export const queryCounterMax = (sqlStr: string, counter_id: number, componentId: number): Promise<Array<any>> =>
3138  query('queryCounterMax', sqlStr, { $counter_id: counter_id }, 'exec-sdk-' + componentId);
3139
3140export const queryAnomalyData = (): Promise<Array<EnergyAnomalyStruct>> =>
3141  query(
3142    'queryAnomalyData',
3143    `select
3144      (S.ts - TR.start_ts) as startNS,
3145      D.data as eventName,
3146      D2.data as appKey,
3147      (case when S.type==1 then group_concat(S.string_value,',') else group_concat(S.int_value,',') end) as Value
3148      from trace_range AS TR,hisys_event_measure as S
3149      left join data_dict as D on D.id=S.name_id
3150      left join app_name as APP on APP.id=S.key_id
3151      left join data_dict as D2 on D2.id=APP.app_key
3152      where D.data in ('ANOMALY_SCREEN_OFF_ENERGY','ANOMALY_KERNEL_WAKELOCK','ANOMALY_CPU_HIGH_FREQUENCY','ANOMALY_WAKEUP')
3153     or (D.data in ('ANOMALY_RUNNINGLOCK','ANORMALY_APP_ENERGY','ANOMALY_GNSS_ENERGY','ANOMALY_CPU_ENERGY','ANOMALY_ALARM_WAKEUP') and D2.data in ("APPNAME"))
3154      group by S.serial,D.data`
3155  );
3156
3157export const querySystemLocationData = (): Promise<
3158  Array<{
3159    startNs: string;
3160    eventName: string;
3161    type: string;
3162    state: string;
3163  }>
3164> =>
3165  query(
3166    'querySystemLocationData',
3167    `SELECT
3168        ( S.ts - TR.start_ts ) AS ts,
3169        D.data AS eventName,
3170        D2.data AS appKey,
3171        group_concat( ( CASE WHEN S.type == 1 THEN S.string_value ELSE S.int_value END ), ',' ) AS Value
3172        FROM
3173        trace_range AS TR,
3174        hisys_event_measure AS S
3175        LEFT JOIN data_dict AS D ON D.id = S.name_id
3176        LEFT JOIN app_name AS APP ON APP.id = S.key_id
3177        LEFT JOIN data_dict AS D2 ON D2.id = APP.app_key
3178        WHERE
3179        D.data = 'GNSS_STATE' AND D2.data = 'STATE'
3180        GROUP BY
3181        S.serial,
3182        APP.app_key,
3183        D.data,
3184        D2.data;`
3185  );
3186
3187export const querySystemLockData = (): Promise<
3188  Array<{
3189    startNs: string;
3190    eventName: string;
3191    type: string;
3192    state: string;
3193  }>
3194> =>
3195  query(
3196    'querySystemLockData',
3197    `SELECT
3198        ( S.ts - TR.start_ts ) AS ts,
3199        D.data AS eventName,
3200        D2.data AS appKey,
3201        group_concat(( CASE WHEN S.type == 1 THEN S.string_value ELSE S.int_value END ), ',' ) AS Value
3202        FROM
3203        trace_range AS TR,
3204        hisys_event_measure AS S
3205        LEFT JOIN data_dict AS D ON D.id = S.name_id
3206        LEFT JOIN app_name AS APP ON APP.id = S.key_id
3207        LEFT JOIN data_dict AS D2 ON D2.id = APP.app_key
3208        WHERE
3209        ( D.data = 'POWER_RUNNINGLOCK' AND D2.data in ('TAG','MESSAGE'))
3210        GROUP BY
3211        S.serial;`
3212  );
3213
3214export const querySystemSchedulerData = (): Promise<
3215  Array<{
3216    startNs: string;
3217    eventName: string;
3218    appKey: string;
3219    Value: string;
3220  }>
3221> =>
3222  query(
3223    'querySystemSchedulerData',
3224    `SELECT
3225        ( S.ts - TR.start_ts ) AS startNs,
3226        D.data AS eventName,
3227        group_concat(D2.data, ',') AS appKey,
3228        group_concat( ( CASE WHEN S.type == 1 THEN S.string_value ELSE S.int_value END ), ',' ) AS Value
3229        FROM
3230        trace_range AS TR,
3231        hisys_event_measure AS S
3232        LEFT JOIN data_dict AS D ON D.id = S.name_id
3233        LEFT JOIN app_name AS APP ON APP.id = S.key_id
3234        LEFT JOIN data_dict AS D2 ON D2.id = APP.app_key
3235        WHERE
3236        D.data IN ( 'WORK_REMOVE', 'WORK_STOP', 'WORK_ADD' ) AND D2.data in ('NAME','TYPE','WORKID')
3237        GROUP BY
3238        S.serial;`
3239  );
3240
3241export const querySystemDetailsData = (rightNs: number, eventName: string): Promise<Array<SystemDetailsEnergy>> =>
3242  query(
3243    'querySystemDetailsData',
3244    `SELECT
3245        ( S.ts - TR.start_ts ) AS ts,
3246        D.data AS eventName,
3247        D2.data AS appKey,
3248        group_concat( ( CASE WHEN S.type == 1 THEN S.string_value ELSE S.int_value END ), ',' ) AS appValue
3249    FROM
3250        trace_range AS TR,
3251        hisys_event_measure AS S
3252        LEFT JOIN data_dict AS D ON D.id = S.name_id
3253        LEFT JOIN app_name AS APP ON APP.id = S.key_id
3254        LEFT JOIN data_dict AS D2 ON D2.id = APP.app_key
3255    WHERE
3256        D.data in ($eventName)
3257    AND
3258        D2.data in ('UID', 'TYPE', 'WORKID', 'NAME', 'INTERVAL', 'TAG', 'STATE', 'STACK', 'APPNAME', 'MESSAGE', 'PID', 'LOG_LEVEL')
3259    AND
3260        (S.ts - TR.start_ts) <= $rightNS
3261    GROUP BY
3262        S.serial,
3263        APP.app_key,
3264        D.data,
3265        D2.data;`,
3266    { $rightNS: rightNs, $eventName: eventName }
3267  );
3268
3269export const querySystemWorkData = (rightNs: number): Promise<Array<SystemDetailsEnergy>> =>
3270  query(
3271    'querySystemWorkData',
3272    `SELECT
3273        ( S.ts - TR.start_ts ) AS ts,
3274        D.data AS eventName,
3275        D2.data AS appKey,
3276        group_concat( ( CASE WHEN S.type == 1 THEN S.string_value ELSE S.int_value END ), ',' ) AS appValue
3277        FROM
3278        trace_range AS TR,
3279        hisys_event_measure AS S
3280        LEFT JOIN data_dict AS D
3281        ON D.id = S.name_id
3282        LEFT JOIN app_name AS APP
3283        ON APP.id = S.key_id
3284        LEFT JOIN data_dict AS D2
3285        ON D2.id = APP.app_key
3286        WHERE
3287        D.data in ("WORK_REMOVE", "WORK_STOP", "WORK_ADD", "WORK_START")
3288        and
3289        D2.data in ('UID', 'TYPE', 'WORKID', 'NAME', 'INTERVAL', 'TAG', 'STATE', 'STACK', 'APPNAME', 'MESSAGE', 'PID', 'LOG_LEVEL')
3290        and (S.ts - TR.start_ts) <= $rightNS
3291        GROUP BY
3292        S.serial,
3293        APP.app_key,
3294        D.data,
3295        D2.data;`,
3296    { $rightNS: rightNs }
3297  );
3298
3299export const queryMaxPowerValue = (
3300  appName: string
3301): Promise<
3302  Array<{
3303    maxValue: number;
3304  }>
3305> =>
3306  query(
3307    'queryMaxPowerValue',
3308    `SELECT
3309        max( item ) AS maxValue
3310        FROM
3311        (
3312            SELECT
3313            sum( energy + background_energy + screen_on_energy + screen_off_energy + foreground_energy ) AS item
3314            FROM
3315            energy
3316            WHERE
3317            app_name = $appName
3318            GROUP BY
3319            startNs);`,
3320    { $appName: appName }
3321  );
3322
3323export const queryPowerData = (): Promise<
3324  Array<{
3325    startNS: number;
3326    eventName: string;
3327    appKey: string;
3328    eventValue: string;
3329  }>
3330> =>
3331  query(
3332    'queryPowerData',
3333    `SELECT
3334        ( S.ts - TR.start_ts ) AS startNS,
3335        D.data AS eventName,
3336        D2.data AS appKey,
3337        group_concat( ( CASE WHEN S.type == 1 THEN S.string_value ELSE S.int_value END ), ',' ) AS eventValue
3338        FROM
3339        trace_range AS TR,
3340        hisys_event_measure AS S
3341        LEFT JOIN data_dict AS D
3342        ON D.id = S.name_id
3343        LEFT JOIN app_name AS APP
3344        ON APP.id = S.key_id
3345        LEFT JOIN data_dict AS D2
3346        ON D2.id = APP.app_key
3347        where
3348        D.data in ('POWER_IDE_CPU','POWER_IDE_LOCATION','POWER_IDE_GPU','POWER_IDE_DISPLAY','POWER_IDE_CAMERA','POWER_IDE_BLUETOOTH','POWER_IDE_FLASHLIGHT','POWER_IDE_AUDIO','POWER_IDE_WIFISCAN')
3349        and
3350        D2.data in ('BACKGROUND_ENERGY','FOREGROUND_ENERGY','SCREEN_ON_ENERGY','SCREEN_OFF_ENERGY','ENERGY','APPNAME')
3351        GROUP BY
3352        S.serial,
3353        APP.app_key,
3354        D.data,
3355        D2.data
3356        ORDER BY
3357        eventName;`,
3358    {}
3359  );
3360
3361export const getTabPowerDetailsData = (
3362  leftNs: number,
3363  rightNs: number
3364): Promise<
3365  Array<{
3366    startNS: number;
3367    eventName: string;
3368    appKey: string;
3369    eventValue: string;
3370  }>
3371> =>
3372  query(
3373    'getTabPowerDetailsData',
3374    `SELECT
3375        ( S.ts - TR.start_ts ) AS startNS,
3376        D.data AS eventName,
3377        D2.data AS appKey,
3378        group_concat( ( CASE WHEN S.type == 1 THEN S.string_value ELSE S.int_value END ), ',' ) AS eventValue
3379        FROM
3380        trace_range AS TR,
3381        hisys_event_measure AS S
3382        LEFT JOIN data_dict AS D ON D.id = S.name_id
3383        LEFT JOIN app_name AS APP ON APP.id = S.key_id
3384        LEFT JOIN data_dict AS D2 ON D2.id = APP.app_key
3385        where
3386        D.data in ('POWER_IDE_CPU','POWER_IDE_LOCATION','POWER_IDE_GPU','POWER_IDE_DISPLAY','POWER_IDE_CAMERA','POWER_IDE_BLUETOOTH','POWER_IDE_FLASHLIGHT','POWER_IDE_AUDIO','POWER_IDE_WIFISCAN')
3387        and
3388        D2.data in ('APPNAME')
3389        GROUP BY
3390        S.serial,
3391        APP.app_key,
3392        D.data,
3393        D2.data
3394        UNION
3395        SELECT
3396        ( S.ts - TR.start_ts ) AS startNS,
3397        D1.data AS eventName,
3398        D2.data AS appKey,
3399        group_concat( ( CASE WHEN S.type == 1 THEN S.string_value ELSE S.int_value END ), ',' ) AS eventValue
3400        FROM
3401        trace_range AS TR,
3402        hisys_event_measure AS S
3403        LEFT JOIN data_dict AS D1 ON D1.id = S.name_id
3404        LEFT JOIN app_name AS APP ON APP.id = S.key_id
3405        LEFT JOIN data_dict AS D2 ON D2.id = APP.app_key
3406        where
3407        D1.data in ('POWER_IDE_CPU','POWER_IDE_LOCATION','POWER_IDE_GPU','POWER_IDE_DISPLAY','POWER_IDE_CAMERA','POWER_IDE_BLUETOOTH','POWER_IDE_FLASHLIGHT','POWER_IDE_AUDIO','POWER_IDE_WIFISCAN')
3408        and
3409        D2.data in ('CHARGE','BACKGROUND_TIME','SCREEN_ON_TIME','SCREEN_OFF_TIME','LOAD','USAGE','DURATION','CAMERA_ID',
3410        'FOREGROUND_COUNT','BACKGROUND_COUNT','SCREEN_ON_COUNT','SCREEN_OFF_COUNT','COUNT','UID','FOREGROUND_DURATION',
3411        'FOREGROUND_ENERGY','BACKGROUND_DURATION','BACKGROUND_ENERGY','SCREEN_ON_DURATION','SCREEN_ON_ENERGY',
3412        'SCREEN_OFF_DURATION','SCREEN_OFF_ENERGY','ENERGY')
3413        and
3414        (S.ts - TR.start_ts) >= $leftNS
3415        and (S.ts - TR.start_ts) <= $rightNS
3416        GROUP BY
3417        S.serial,
3418        APP.app_key,
3419        D1.data,
3420        D2.data
3421        ORDER BY
3422        eventName;`,
3423    { $leftNS: leftNs, $rightNS: rightNs }
3424  );
3425
3426export const getTabPowerBatteryData = (
3427  rightNs: number
3428): Promise<
3429  Array<{
3430    ts: number;
3431    eventName: string;
3432    appKey: string;
3433    eventValue: string;
3434  }>
3435> =>
3436  query(
3437    'getTabPowerBatteryData',
3438    `select
3439      MAX(S.ts) as ts,
3440      D.data as eventName,
3441      D2.data as appKey,
3442      group_concat((case when S.type==1 then S.string_value else S.int_value end), ',') as eventValue
3443      from
3444      trace_range AS TR,
3445      hisys_event_measure as S
3446      left join
3447      data_dict as D
3448      on
3449      D.id=S.name_id
3450      left join
3451      app_name as APP
3452      on
3453      APP.id=S.key_id
3454      left join
3455      data_dict as D2
3456      on
3457      D2.id=APP.app_key
3458      where
3459      D.data = 'POWER_IDE_BATTERY'
3460      and D2.data in ('GAS_GAUGE','CHARGE','SCREEN','LEVEL','CURRENT','CAPACITY','UID')
3461      and (S.ts - TR.start_ts) >= 0
3462      and (S.ts - TR.start_ts) <= $rightNS
3463      group by APP.app_key,D.data,D2.data;`,
3464    { $rightNS: rightNs }
3465  );
3466
3467export const queryMaxStateValue = (
3468  eventName: string
3469): Promise<
3470  Array<{
3471    type: string;
3472    maxValue: number;
3473  }>
3474> =>
3475  query(
3476    'queryMaxStateValue',
3477    `select
3478  D.data as type,
3479  max(S.int_value) as maxValue
3480  from trace_range AS TR,hisys_event_measure as S
3481  left join data_dict as D on D.id=S.name_id
3482  left join app_name as APP on APP.id=S.key_id
3483  left join data_dict as D2 on D2.id=APP.app_key
3484  where (case when 'SENSOR_STATE'==$eventName then D.data like '%SENSOR%' else D.data = $eventName end)
3485  and D2.data in ('BRIGHTNESS','STATE','VALUE','LEVEL','VOLUME','OPER_TYPE','VOLUME')
3486  group by APP.app_key,D.data,D2.data;`,
3487    { $eventName: eventName }
3488  );
3489
3490export const queryStateData = (eventName: string): Promise<Array<EnergyStateStruct>> =>
3491  query(
3492    'queryStateData',
3493    `select
3494  (S.ts-TR.start_ts) as startNs,
3495  D.data as type,
3496  D2.data as appKey,
3497  S.int_value as value
3498  from trace_range AS TR,hisys_event_measure as S
3499  left join data_dict as D on D.id=S.name_id
3500  left join app_name as APP on APP.id=S.key_id
3501  left join data_dict as D2 on D2.id=APP.app_key
3502  where (case when 'SENSOR_STATE'==$eventName then D.data like '%SENSOR%' else D.data = $eventName end)
3503  and D2.data in ('BRIGHTNESS','STATE','VALUE','LEVEL','VOLUME','OPER_TYPE','VOLUME')
3504  group by S.serial,APP.app_key,D.data,D2.data;`,
3505    { $eventName: eventName }
3506  );
3507
3508export const querySyseventAppName = (): Promise<
3509  Array<{
3510    string_value: string | null;
3511  }>
3512> =>
3513  query(
3514    'querySyseventAppName',
3515    `
3516    SELECT
3517    DISTINCT hisys_event_measure.string_value from data_dict
3518    left join app_name on app_name.app_key=data_dict.id
3519    left join hisys_event_measure on hisys_event_measure.key_id = app_name.id
3520    where data_dict.data = "APPNAME"`
3521  );
3522
3523export const queryAnomalyDetailedData = (leftNs: number, rightNs: number): Promise<Array<EnergyAnomalyStruct>> =>
3524  query<EnergyAnomalyStruct>(
3525    'queryAnomalyDetailedData',
3526    `select
3527  S.ts,
3528  D.data as eventName,
3529  D2.data as appKey,
3530  group_concat((case when S.type==1 then S.string_value else S.int_value end), ',') as Value
3531  from trace_range AS TR,hisys_event_measure as S
3532  left join data_dict as D on D.id=S.name_id
3533  left join app_name as APP on APP.id=S.key_id
3534  left join data_dict as D2 on D2.id=APP.app_key
3535  where D.data in ('ANOMALY_SCREEN_OFF_ENERGY','ANOMALY_ALARM_WAKEUP','ANOMALY_KERNEL_WAKELOCK',
3536  'ANOMALY_RUNNINGLOCK','ANORMALY_APP_ENERGY','ANOMALY_GNSS_ENERGY','ANOMALY_CPU_HIGH_FREQUENCY','ANOMALY_CPU_ENERGY','ANOMALY_WAKEUP')
3537  and D2.data in ('APPNAME')
3538  and (S.ts - TR.start_ts) >= $leftNS
3539   and (S.ts - TR.start_ts) <= $rightNS
3540  group by S.serial,APP.app_key,D.data,D2.data
3541  union
3542  select
3543  S.ts,
3544  D.data as eventName,
3545  D2.data as appKey,
3546  group_concat((case when S.type == 1 then S.string_value else S.int_value end), ',') as Value
3547  from trace_range AS TR,hisys_event_measure as S
3548  left join data_dict as D on D.id = S.name_id
3549  left join app_name as APP on APP.id = S.key_id
3550  left join data_dict as D2 on D2.id = APP.app_key
3551  where D.data in ('ANOMALY_SCREEN_OFF_ENERGY', 'ANOMALY_ALARM_WAKEUP', 'ANOMALY_KERNEL_WAKELOCK',
3552  'ANOMALY_RUNNINGLOCK', 'ANORMALY_APP_ENERGY', 'ANOMALY_GNSS_ENERGY', 'ANOMALY_CPU_HIGH_FREQUENCY', 'ANOMALY_CPU_ENERGY', 'ANOMALY_WAKEUP')
3553  and D2.data not in ('pid_', 'tid_', 'type_', 'tz_', 'uid_', 'domain_', 'id_', 'level_', 'info_', 'tag_', 'APPNAME')
3554  and (S.ts - TR.start_ts) >= $leftNS
3555  and (S.ts - TR.start_ts) <= $rightNS
3556  group by S.serial, APP.app_key, D.data, D2.data;`,
3557    { $leftNS: leftNs, $rightNS: rightNs }
3558  );
3559
3560export const queryGpuTotalType = (): Promise<Array<{ id: number; data: string }>> =>
3561  query(
3562    'queryGpuTotalType',
3563    `
3564  select distinct module_name_id id,data
3565    from memory_window_gpu A, trace_range TR left join data_dict B on A.module_name_id = B.id
3566    where window_name_id = 0
3567    and A.ts < TR.end_ts;
3568  `
3569  );
3570
3571export const queryGpuDataByTs = (
3572  ts: number,
3573  window: number,
3574  module: number | null
3575): Promise<
3576  Array<{
3577    windowNameId: number;
3578    windowId: number;
3579    moduleId: number;
3580    categoryId: number;
3581    size: number;
3582  }>
3583> => {
3584  let condition =
3585    module === null
3586      ? `and window_name_id = ${window}`
3587      : `and window_name_id = ${window} and module_name_id = ${module}`;
3588  let sql = `select window_name_id as windowNameId,
3589       window_id as windowId,
3590       module_name_id as moduleId,
3591       category_name_id as categoryId,
3592       size
3593       from memory_window_gpu, trace_range
3594       where ts - start_ts = ${ts} ${condition};`;
3595  return query('queryGpuDataByTs', sql);
3596};
3597
3598export const queryGpuTotalData = (moduleId: number | null): Promise<Array<{ startNs: number; value: number }>> => {
3599  let moduleCondition = moduleId === null ? '' : `and module_name_id = ${moduleId}`;
3600  let sql = `
3601  select (ts - start_ts) startNs, sum(size) value
3602    from memory_window_gpu,trace_range
3603    where window_name_id = 0 ${moduleCondition}
3604    and ts< end_ts
3605    group by ts;
3606  `;
3607  return query('queryGpuTotalData', sql);
3608};
3609
3610export const queryGpuGLData = (ipid: number): Promise<Array<{ startNs: number; value: number }>> => {
3611  let sql = `
3612  select (ts - start_ts) startNs,sum(value) value
3613from process_measure, trace_range
3614where filter_id = (
3615    select id
3616    from process_measure_filter
3617    where name = 'mem.gl_pss' and ipid = ${ipid}
3618    )
3619and ts between start_ts and end_ts
3620group by ts;
3621  `;
3622  return query('queryGpuGLData', sql);
3623};
3624
3625export const queryGpuGLDataByRange = (
3626  ipid: number,
3627  leftNs: number,
3628  rightNs: number,
3629  interval: number
3630): Promise<Array<{ startTs: number; size: number }>> => {
3631  let sql = `
3632  select (ts - start_ts) startTs,sum(value) size
3633from process_measure, trace_range
3634where filter_id = (
3635    select id
3636    from process_measure_filter
3637    where name = 'mem.gl_pss' and ipid = ${ipid}
3638    )
3639and not ((startTs + ${interval} < ${leftNs}) or (startTs > ${rightNs}))
3640group by ts;
3641  `;
3642  return query('queryGpuGLDataByRange', sql);
3643};
3644
3645export const queryGpuDataByRange = (
3646  leftNs: number,
3647  rightNs: number,
3648  interval: number
3649): Promise<
3650  Array<{
3651    startTs: number;
3652    windowId: number;
3653    moduleId: number;
3654    categoryId: number;
3655    avgSize: number;
3656    maxSize: number;
3657    minSize: number;
3658  }>
3659> => {
3660  let sql = `select (ts - start_ts) startTs,
3661    window_name_id windowId,
3662    module_name_id moduleId,
3663    category_name_id categoryId,
3664    avg(size) avgSize,
3665    max(size) maxSize,
3666    min(size) minSize
3667  from memory_window_gpu,trace_range
3668  where not ((startTs + ${interval} < ${leftNs}) or (startTs > ${rightNs}))
3669  group by window_name_id,module_name_id,category_name_id
3670  order by avgSize DESC;
3671  `;
3672  return query('queryGpuWindowData', sql);
3673};
3674
3675export const queryGpuWindowData = (
3676  windowId: number,
3677  moduleId: number | null
3678): Promise<Array<{ startNs: number; value: number }>> => {
3679  let moduleCondition = moduleId === null ? '' : `and module_name_id = ${moduleId}`;
3680  let sql = `
3681  select (ts - start_ts) startNs, sum(size) value
3682    from memory_window_gpu,trace_range
3683    where window_name_id = ${windowId} ${moduleCondition}
3684    and ts < end_ts
3685    group by ts;
3686  `;
3687  return query('queryGpuWindowData', sql);
3688};
3689
3690export const queryGpuWindowType = (): Promise<Array<{ id: number; data: string; pid: number }>> =>
3691  query(
3692    'queryGpuWindowType',
3693    `
3694  select distinct A.window_name_id as id,B.data, null as pid
3695from memory_window_gpu A, trace_range tr left join data_dict B on A.window_name_id = B.id
3696where window_name_id != 0
3697and A.ts < tr.end_ts
3698union all
3699select distinct A.module_name_id id, B.data, A.window_name_id pid
3700from memory_window_gpu A, trace_range TR left join data_dict B on A.module_name_id = B.id
3701where window_name_id != 0
3702and A.ts < TR.end_ts
3703  `
3704  );
3705
3706export const querySmapsExits = (): Promise<Array<any>> =>
3707  query(
3708    'querySmapsExits',
3709    `select
3710      event_name
3711      from stat s
3712      where s.event_name = 'trace_smaps'
3713      and s.stat_type ='received' and s.count > 0`
3714  );
3715
3716export const querySmapsData = (columnName: string): Promise<Array<any>> =>
3717  query(
3718    'querySmapsCounterData',
3719    `SELECT (A.timestamp - B.start_ts) as startNs, sum(${columnName}) * 1024 as value, $columnName as name FROM smaps A,trace_range B WHERE A.timestamp < B.end_ts GROUP by A.timestamp;`,
3720    { $columnName: columnName }
3721  );
3722
3723export const querySmapsDataMax = (columnName: string): Promise<Array<any>> =>
3724  query(
3725    'querySmapsDataMax',
3726    `
3727   SELECT (A.timestamp - B.start_ts) as startNS,sum(${columnName}) as max_value FROM smaps A,trace_range B GROUP by A.timestamp order by max_value desc LIMIT 1`
3728  );
3729
3730export const getTabSmapsMaxSize = (leftNs: number, rightNs: number, dur: number): Promise<Array<any>> =>
3731  query<Smaps>(
3732    'getTabSmapsMaxRss',
3733    `
3734SELECT (A.timestamp - B.start_ts) as startNS, sum(virtaul_size) *1024 as max_value FROM smaps A,trace_range B where startNS <= $rightNs and (startNS+$dur)>=$leftNs`,
3735    { $rightNs: rightNs, $leftNs: leftNs, $dur: dur }
3736  );
3737
3738export const getTabSmapsData = (leftNs: number, rightNs: number, dur: number): Promise<Array<Smaps>> =>
3739  query<Smaps>(
3740    'getTabSmapsData',
3741    `
3742    SELECT
3743     (A.timestamp - t.start_ts) AS startNs,
3744     start_addr as startAddr,
3745     end_addr as endAddr,
3746     A.type,
3747     resident_size * 1024 AS rss,
3748     protection_id as pid,
3749     pss * 1024 as pss,virtaul_size * 1024 AS size,reside,A.path_id AS path,
3750     shared_clean * 1024 as sharedClean,shared_dirty * 1024 as sharedDirty,private_clean * 1024 as privateClean,
3751     private_dirty * 1024 as privateDirty,swap * 1024 as swap,swap_pss * 1024 as swapPss
3752     FROM smaps A,
3753     trace_range AS t
3754     WHERE (startNs) <= $rightNs and (startNs+$dur) >=$leftNs`,
3755    { $rightNs: rightNs, $leftNs: leftNs, $dur: dur },
3756    'exec'
3757  );
3758
3759export const getTabVirtualMemoryType = (startTime: number, endTime: number): Promise<Array<string>> =>
3760  query(
3761    'getTabVirtualMemoryType',
3762    `
3763    SELECT type from paged_memory_sample s,trace_range t
3764     WHERE s.end_ts between $startTime + t.start_ts and $endTime + t.start_ts group by type`,
3765    { $startTime: startTime, $endTime: endTime },
3766    'exec'
3767  );
3768
3769export const getTabIoCompletionTimesType = (startTime: number, endTime: number): Promise<Array<string>> =>
3770  query(
3771    'getTabIoCompletionTimesType',
3772    `
3773    SELECT tier from bio_latency_sample s,trace_range t
3774     WHERE s.start_ts + s.latency_dur between $startTime + t.start_ts and $endTime + t.start_ts group by tier`,
3775    { $startTime: startTime, $endTime: endTime },
3776    'exec'
3777  );
3778
3779export const getCpuLimitFreqId = (): Promise<Array<CpuFreqRowLimit>> =>
3780  query(
3781    'getCpuMaxMinFreqId',
3782    `
3783    select cpu,MAX(iif(name = 'cpu_frequency_limits_max',id,0)) as maxFilterId,MAX(iif(name = 'cpu_frequency_limits_min',id,0)) as minFilterId from cpu_measure_filter where name in ('cpu_frequency_limits_max','cpu_frequency_limits_min') group by cpu
3784`,
3785    {}
3786  );
3787
3788export const getCpuLimitFreqMax = (filterIds: string): Promise<Array<any>> => {
3789  return query(
3790    'getCpuLimitFreqMax',
3791    `
3792    select max(value) as maxValue,filter_id as filterId from measure where filter_id in (${filterIds}) group by filter_id
3793`,
3794    {}
3795  );
3796};
3797
3798export const getCpuLimitFreq = (maxId: number, minId: number, cpu: number): Promise<Array<CpuFreqLimitsStruct>> =>
3799  query(
3800    'getCpuLimitFreq',
3801    `
3802    select ts - T.start_ts as startNs,dur,max(value) as max,min(value) as min,$cpu as cpu from measure,trace_range T where filter_id in ($maxId,$minId) group by ts
3803`,
3804    { $maxId: maxId, $minId: minId, $cpu: cpu }
3805  );
3806
3807export const queryHisystemEventExits = (): Promise<Array<any>> =>
3808  query(
3809    'queryHisystemEventExits',
3810    `select
3811      event_name
3812      from stat s
3813      where s.event_name = 'trace_hisys_event'
3814      and s.stat_type ='received' and s.count > 0`
3815  );
3816
3817export const queryEbpfSamplesCount = (startTime: number, endTime: number, ipids: number[]): Promise<Array<any>> =>
3818  query(
3819    'queryEbpfSamplesCount',
3820    `
3821    select
3822fsCount,
3823    vmCount from
3824(select count(1) as fsCount from file_system_sample s,trace_range t where s.end_ts between $startTime + t.start_ts and $endTime + t.start_ts ${
3825      ipids.length > 0 ? `and s.ipid in (${ipids.join(',')})` : ''
3826    })
3827,(select count(1) as vmCount from paged_memory_sample s,trace_range t where s.end_ts between $startTime + t.start_ts and $endTime + t.start_ts ${
3828      ipids.length > 0 ? `and s.ipid in (${ipids.join(',')})` : ''
3829    });
3830`,
3831    { $startTime: startTime, $endTime: endTime }
3832  );
3833
3834export const querySysLockDetailsData = (rightNs: number, eventName: string): Promise<Array<SystemDetailsEnergy>> =>
3835  query(
3836    'querySysLockDetailsData',
3837    `SELECT
3838        ( S.ts - TR.start_ts ) AS ts,
3839        D.data AS eventName,
3840        D2.data AS appKey,
3841        group_concat( ( CASE WHEN S.type == 1 THEN S.string_value ELSE S.int_value END ), ',' ) AS appValue
3842    FROM
3843        trace_range AS TR,
3844        hisys_event_measure AS S
3845        LEFT JOIN data_dict AS D ON D.id = S.name_id
3846        LEFT JOIN app_name AS APP ON APP.id = S.key_id
3847        LEFT JOIN data_dict AS D2 ON D2.id = APP.app_key
3848    WHERE
3849        D.data in ($eventName)
3850    AND
3851        D2.data in ('UID', 'TYPE', 'WORKID', 'NAME', 'INTERVAL', 'TAG', 'STATE', 'STACK', 'APPNAME', 'MESSAGE', 'PID', 'LOG_LEVEL')
3852    AND
3853        (S.ts - TR.start_ts) <= $rightNS
3854    GROUP BY
3855        S.serial, APP.app_key, D.data, D2.data;`,
3856    { $rightNS: rightNs, $eventName: eventName }
3857  );
3858
3859export const queryStateInitValue = (eventName: string, keyName: string): Promise<Array<EnergyStateStruct>> =>
3860  query(
3861    'queryStateInitValue',
3862    `select
3863  0 as startNs,
3864  $eventName as type,
3865  '' as appKey,
3866  (case $keyName
3867  when 'brightness' then device_state.brightness
3868  when 'wifi' then device_state.wifi
3869  when 'bt_state' then device_state.bt_state
3870  when 'location' then device_state.location
3871  else 0 end) as value
3872  from device_state;`,
3873    { $eventName: eventName, $keyName: keyName }
3874  );
3875
3876export const querySysLocationDetailsData = (rightNs: number, eventName: string): Promise<Array<SystemDetailsEnergy>> =>
3877  query(
3878    'querySysLocationDetailsData',
3879    `SELECT
3880        ( S.ts - TR.start_ts ) AS ts,
3881        D.data AS eventName,
3882        D2.data AS appKey,
3883        group_concat( ( CASE WHEN S.type == 1 THEN S.string_value ELSE S.int_value END ), ',' ) AS appValue
3884        FROM
3885        trace_range AS TR,
3886        hisys_event_measure AS S
3887        LEFT JOIN data_dict AS D ON D.id = S.name_id
3888        LEFT JOIN app_name AS APP ON APP.id = S.key_id
3889        LEFT JOIN data_dict AS D2 ON D2.id = APP.app_key
3890        WHERE
3891        D.data in ($eventName)
3892        and
3893        D2.data in ('UID', 'TYPE', 'WORKID', 'NAME', 'INTERVAL', 'TAG', 'STATE', 'STACK', 'APPNAME', 'MESSAGE', 'PID', 'LOG_LEVEL')
3894        and (S.ts - TR.start_ts) <= $rightNS
3895        GROUP BY
3896        S.serial,
3897        APP.app_key,
3898        D.data,
3899        D2.data;`,
3900    { $rightNS: rightNs, $eventName: eventName }
3901  );
3902export const queryNativeMemoryRealTime = (): Promise<Array<any>> =>
3903  query(
3904    'queryNativeMemoryRealTime',
3905    `select cs.ts,cs.clock_name from datasource_clockid dc left join clock_snapshot cs on dc.clock_id = cs.clock_id where data_source_name = 'memory-plugin' or data_source_name = 'nativehook'
3906`,
3907    {}
3908  );
3909
3910export const queryBootTime = (): Promise<Array<any>> =>
3911  query(
3912    'queryBootTime',
3913    `select CS.ts -TR.start_ts as ts ,clock_name from clock_snapshot as CS ,trace_range as TR
3914      where clock_name = 'boottime'`,
3915    {}
3916  );
3917
3918export const queryConfigSysEventAppName = (): Promise<
3919  Array<{
3920    process_name: string;
3921  }>
3922> =>
3923  query(
3924    'queryConfigSysEventAppName',
3925    `
3926    SELECT value from trace_config where trace_source = 'hisys_event' and key = 'process_name'`
3927  );
3928
3929export const queryClockData = (): Promise<
3930  Array<{
3931    name: string;
3932    num: number;
3933    srcname: string;
3934  }>
3935> =>
3936  query(
3937    'queryClockData',
3938    `
3939    select name || ' Frequency' name, COUNT(*) num, name srcname
3940from (select id, name
3941      from clock_event_filter
3942      where type = 'clock_set_rate')
3943group by name
3944union
3945select name || ' State' name, COUNT(*) num, name srcname
3946from (select id, name
3947      from clock_event_filter
3948      where type != 'clock_set_rate')
3949group by name;
3950`
3951  );
3952
3953export const queryClockFrequency = (clockName: string): Promise<Array<ClockStruct>> =>
3954  query(
3955    'queryClockFrequency',
3956    `with freq as (  select measure.filter_id, measure.ts, measure.type, measure.value from clock_event_filter
3957left join measure
3958where clock_event_filter.name = $clockName and clock_event_filter.type = 'clock_set_rate' and clock_event_filter.id = measure.filter_id
3959order by measure.ts)
3960select freq.filter_id as filterId,freq.ts - r.start_ts as startNS,freq.type,freq.value from freq,trace_range r order by startNS`,
3961    { $clockName: clockName }
3962  );
3963
3964export const queryClockState = (clockName: string): Promise<Array<ClockStruct>> =>
3965  query(
3966    'queryClockState',
3967    `with state as (
3968select filter_id, ts, endts, endts-ts as dur, type, value from
3969(select measure.filter_id, measure.ts, lead(ts, 1, null) over( order by measure.ts) endts, measure.type, measure.value from clock_event_filter,trace_range
3970left join measure
3971where clock_event_filter.name = $clockName and clock_event_filter.type != 'clock_set_rate' and clock_event_filter.id = measure.filter_id
3972order by measure.ts))
3973select s.filter_id as filterId,s.ts-r.start_ts as startNS,s.type,s.value,s.dur from state s,trace_range r`,
3974    { $clockName: clockName }
3975  );
3976
3977export const queryScreenState = (): Promise<Array<ClockStruct>> =>
3978  query(
3979    'queryScreenState',
3980    `select m.type, m.ts-r.start_ts as startNS, value, filter_id  as filterId from measure m,trace_range r where filter_id in (select id from process_measure_filter where name = 'ScreenState')  order by startNS;
3981`
3982  );
3983
3984export const queryIrqList = (): Promise<Array<{ name: string; cpu: number }>> =>
3985  query('queryIrqList', `select cat as name,callid as cpu from irq where cat!= 'ipi' group by cat,callid`);
3986
3987export const queryIrqData = (callid: number, cat: string): Promise<Array<IrqStruct>> => {
3988  let sqlSoftIrq = `
3989    select i.ts - t.start_ts as startNS,i.dur,i.name,i.depth,argsetid as argSetId,i.id from irq i,
3990trace_range t where i.callid = ${callid} and i.cat = 'softirq'
3991    `;
3992  let sqlIrq = `
3993    select i.ts - t.start_ts as startNS,i.dur,
3994        case when i.cat = 'ipi' then 'IPI' || i.name else i.name end as name,
3995        i.depth,
3996        argsetid as argSetId,
3997        i.id
3998        from irq i,trace_range t
3999        where i.callid = ${callid} and ((i.cat = 'irq' and i.flag ='1') or i.cat = 'ipi')
4000    `;
4001  return query('queryIrqData', cat === 'irq' ? sqlIrq : sqlSoftIrq, {});
4002};
4003
4004export const queryAllJankProcess = (): Promise<
4005  Array<{
4006    pid: number;
4007  }>
4008> =>
4009  query(
4010    'queryAllJankProcess',
4011    `
4012        SELECT DISTINCT p.pid
4013        FROM frame_slice AS a
4014        LEFT JOIN process AS p ON a.ipid = p.ipid
4015        `
4016  );
4017
4018export const queryAllExpectedData = (): Promise<Array<any>> =>
4019  query(
4020    'queryAllExpectedData',
4021    `
4022        SELECT
4023            a.id,
4024            (a.ts - TR.start_ts) AS ts,
4025            a.vsync as name,
4026            a.type,
4027            a.dur,
4028            p.pid,
4029            p.name as cmdline
4030        FROM frame_slice AS a, trace_range AS TR
4031             LEFT JOIN process AS p ON a.ipid = p.ipid
4032        WHERE a.type = 1
4033          and (a.flag <> 2 or a.flag is null)
4034        ORDER BY a.ipid,ts;`
4035  );
4036
4037export const queryAllActualData = (): Promise<Array<any>> =>
4038  query(
4039    'queryAllActualData',
4040    `
4041        SELECT
4042               a.id,
4043               (a.ts - TR.start_ts) AS ts,
4044               a.vsync AS name,
4045               a.type,
4046               a.dur,
4047               a.src AS src_slice,
4048               a.flag AS jank_tag,
4049               a.dst AS dst_slice,
4050               p.pid,
4051               p.name AS cmdline,
4052               (case when p.name like '%render_service' then 'render_service' else 'app' end) as frame_type
4053        FROM frame_slice AS a, trace_range AS TR
4054                 LEFT JOIN process AS p ON a.ipid = p.ipid
4055        WHERE a.type = 0
4056          AND a.flag <> 2
4057        ORDER BY a.ipid, ts;`
4058  );
4059
4060export const queryActualFrameDate = (): Promise<Array<any>> =>
4061  query(
4062    'queryActualFrameDate',
4063    `SELECT
4064         sf.id,
4065         'frameTime' as frame_type,
4066         fs.ipid,
4067         fs.vsync as name,
4068         fs.dur as app_dur,
4069         (sf.ts + sf.dur - fs.ts) as dur,
4070         (fs.ts - TR.start_ts) AS ts,
4071         fs.type,
4072         (case when (sf.flag == 1 or fs.flag == 1 ) then 1  when (sf.flag == 3 or fs.flag == 3 ) then 3 else 0 end) as jank_tag,
4073         pro.pid,
4074         pro.name as cmdline,
4075         (sf.ts - TR.start_ts) AS rs_ts,
4076         sf.vsync AS rs_vsync,
4077         sf.dur AS rs_dur,
4078         sf.ipid AS rs_ipid,
4079         proc.pid AS rs_pid,
4080         proc.name AS rs_name
4081     FROM frame_slice AS fs
4082              LEFT JOIN process AS pro ON pro.id = fs.ipid
4083              LEFT JOIN frame_slice AS sf ON fs.dst = sf.id
4084              LEFT JOIN process AS proc ON proc.id = sf.ipid
4085              LEFT JOIN trace_range TR
4086     WHERE fs.dst IS NOT NULL
4087       AND fs.type = 0
4088       AND fs.flag <> 2
4089     UNION
4090     SELECT
4091         -1 as id,
4092         'frameTime' as frame_type,
4093         fs.ipid,
4094         fs.vsync  as name,
4095         fs.dur as app_dur,
4096         fs.dur,
4097         (fs.ts - TR.start_ts) AS ts,
4098         fs.type,
4099         fs.flag as jank_tag,
4100         pro.pid,
4101         pro.name as cmdline,
4102         NULL AS rs_ts,
4103         NULL AS rs_vsync,
4104         NULL AS rs_dur,
4105         NULL AS rs_ipid,
4106         NULL AS rs_pid,
4107         NULL AS rs_name
4108     FROM frame_slice AS fs
4109              LEFT JOIN process AS pro ON pro.id = fs.ipid
4110              LEFT JOIN trace_range TR
4111     WHERE fs.dst IS NULL
4112       AND pro.name NOT LIKE '%render_service%'
4113       AND fs.type = 0
4114       AND fs.flag <> 2
4115     ORDER BY ts;`
4116  );
4117
4118export const queryExpectedFrameDate = (): Promise<Array<any>> =>
4119  query(
4120    'queryExpectedFrameDate',
4121    `
4122    SELECT
4123        sf.id,
4124        'frameTime' as frame_type,
4125        fs.ipid,
4126        fs.vsync as name,
4127        fs.dur as app_dur,
4128        (sf.ts + sf.dur - fs.ts) as dur,
4129        (fs.ts - TR.start_ts) AS ts,
4130        fs.type,
4131        fs.flag,
4132        pro.pid,
4133        pro.name as cmdline,
4134        (sf.ts - TR.start_ts) AS rs_ts,
4135        sf.vsync AS rs_vsync,
4136        sf.dur AS rs_dur,
4137        sf.ipid AS rs_ipid,
4138        proc.pid AS rs_pid,
4139        proc.name AS rs_name
4140    FROM frame_slice AS fs
4141    LEFT JOIN process AS pro ON pro.id = fs.ipid
4142    LEFT JOIN frame_slice AS sf ON fs.dst = sf.id
4143    LEFT JOIN process AS proc ON proc.id = sf.ipid
4144    LEFT JOIN trace_range TR
4145    WHERE fs.dst IS NOT NULL
4146        AND fs.type = 1
4147    UNION
4148    SELECT
4149        -1 as id,
4150        'frameTime' as frame_type,
4151        fs.ipid,
4152        fs.vsync  as name,
4153        fs.dur as app_dur,
4154        fs.dur,
4155        (fs.ts - TR.start_ts) AS ts,
4156        fs.type,
4157        fs.flag,
4158        pro.pid,
4159        pro.name as cmdline,
4160        NULL AS rs_ts,
4161        NULL AS rs_vsync,
4162        NULL AS rs_dur,
4163        NULL AS rs_ipid,
4164        NULL AS rs_pid,
4165        NULL AS rs_name
4166    FROM frame_slice AS fs
4167    LEFT JOIN process AS pro ON pro.id = fs.ipid
4168    LEFT JOIN trace_range TR
4169    WHERE fs.dst IS NULL
4170    AND pro.name NOT LIKE '%render_service%'
4171    AND fs.type = 1
4172    ORDER BY ts;`
4173  );
4174
4175export const queryFlowsData = (src_slice: Array<string>): Promise<Array<any>> =>
4176  query(
4177    'queryFlowsData',
4178    `
4179    SELECT fs.vsync AS name,
4180        p.pid,
4181        p.name  AS cmdline,
4182        fs.type
4183    FROM frame_slice AS fs
4184    LEFT JOIN process AS p ON fs.ipid = p.ipid
4185    WHERE fs.type = 0
4186        AND fs.id IN (${src_slice.join(',')});`
4187  );
4188
4189export const queryPrecedingData = (dst_slice: string): Promise<Array<any>> =>
4190  query(
4191    'queryFlowsData',
4192    `
4193        SELECT a.vsync AS name,
4194               p.pid,
4195               p.name  AS cmdline,
4196               a.type
4197        FROM frame_slice AS a
4198                 LEFT JOIN process AS p ON a.ipid = p.ipid
4199        WHERE a.type = 0
4200          AND a.id = $dst_slice;`,
4201    { $dst_slice: dst_slice }
4202  );
4203
4204export const queryFrameTimeData = (): Promise<Array<any>> =>
4205  query(
4206    'queryFrameTimeData',
4207    `
4208        SELECT DISTINCT p.pid
4209        FROM frame_slice AS a
4210            LEFT JOIN process AS p
4211            ON a.ipid = p.ipid;`
4212  );
4213
4214export const queryGpuDur = (id: number): Promise<any> =>
4215  query(
4216    'queryGpuDur',
4217    `
4218        SELECT dur AS gpu_dur
4219        FROM gpu_slice
4220        WHERE frame_row = $id;`,
4221    { $id: id }
4222  );
4223
4224export const queryHeapFile = (): Promise<Array<FileInfo>> =>
4225  query(
4226    'queryHeapFile',
4227    `SELECT f.id,
4228        f.file_name AS name,
4229        f.start_time - t.start_ts AS startTs,
4230        f.end_time - t.start_ts AS endTs,
4231        f.self_size AS size,
4232        c.pid
4233      FROM
4234        js_heap_files f,
4235        trace_range t,
4236        js_config c
4237      WHERE
4238        ( t.end_ts >= f.end_time AND f.file_name != 'Timeline' )
4239        OR f.file_name = 'Timeline'`
4240  );
4241
4242export const queryHeapInfo = (fileId: number): Promise<Array<any>> =>
4243  query(
4244    'queryHeapInfo',
4245    `SELECT file_id as fileId, key, type, int_value as intValue, str_value as strValue
4246      FROM js_heap_info WHERE file_id = ${fileId}`
4247  );
4248
4249export const queryHeapNode = (fileId: number): Promise<Array<HeapNode>> =>
4250  query(
4251    'queryHeapNode',
4252    `SELECT node_index as nodeIndex,type,name as nameIdx,id,self_size as selfSize,edge_count as edgeCount,trace_node_id as traceNodeId,detachedness
4253      FROM js_heap_nodes WHERE file_id = ${fileId}`
4254  );
4255
4256export const queryHeapEdge = (fileId: number): Promise<Array<HeapEdge>> =>
4257  query(
4258    'queryHeapEdge',
4259    `SELECT edge_index as edgeIndex,type,name_or_index as nameOrIndex,to_node as nodeId,from_node_id as fromNodeId,to_node_id as toNodeId
4260      FROM js_heap_edges WHERE file_id = ${fileId}`
4261  );
4262
4263export const queryHeapFunction = (fileId: number): Promise<Array<HeapTraceFunctionInfo>> =>
4264  query(
4265    'queryHeapFunction',
4266    `SELECT function_index as index ,function_id as id ,name,script_name as scriptName,script_id as scriptId,line,column
4267      FROM js_heap_trace_function_info WHERE file_id = ${fileId}`
4268  );
4269
4270export const queryHeapTraceNode = (fileId: number): Promise<Array<any>> =>
4271  query(
4272    'queryHeapTraceNode',
4273    `SELECT F.name,
4274        F.script_name as scriptName,
4275        F.script_id as scriptId,
4276        F.column,
4277        F.line,
4278        N.id,
4279        N.function_info_index as functionInfoIndex,
4280        N.parent_id as parentId,
4281        N.count,
4282        N.size,
4283        IFNULL( S.live_count, 0 ) AS liveCount,
4284        IFNULL( S.live_size, 0 ) AS liveSize
4285    FROM
4286        js_heap_trace_node N
4287        LEFT JOIN (
4288            SELECT
4289                trace_node_id as traceNodeId,
4290                SUM( self_size ) AS liveSize,
4291                count( * ) AS liveCount
4292            FROM
4293                js_heap_nodes
4294            WHERE
4295                file_id = ${fileId}
4296                AND trace_node_id != 0
4297            GROUP BY
4298                trace_node_id
4299        ) S ON N.id = S.trace_node_id
4300    LEFT JOIN js_heap_trace_function_info F ON (F.file_id = N.file_id
4301                AND F.function_index = N.function_info_index)
4302    WHERE
4303        N.file_id = ${fileId}
4304    ORDER BY
4305        N.id`
4306  );
4307
4308export const queryHeapSample = (fileId: number): Promise<Array<HeapSample>> =>
4309  query(
4310    'queryHeapSample',
4311    `SELECT timestamp_us as timestamp , last_assigned_id as lastAssignedId, 0 as size
4312      FROM js_heap_sample WHERE file_id = ${fileId}`
4313  );
4314
4315export const queryHeapLocation = (fileId: number): Promise<Array<HeapLocation>> =>
4316  query(
4317    'queryHeapLocation',
4318    `SELECT object_index as objectIndex,script_id as scriptId ,column
4319      FROM js_heap_location WHERE file_id = ${fileId}`
4320  );
4321
4322export const queryHeapString = (fileId: number): Promise<Array<any>> =>
4323  query(
4324    'queryHeapString',
4325    `SELECT string
4326      FROM js_heap_string WHERE file_id = ${fileId}`
4327  );
4328export const queryTraceRange = (): Promise<Array<any>> =>
4329  query('queryTraceRange', `SELECT t.start_ts as startTs, t.end_ts as endTs FROM trace_range t`);
4330
4331export const queryHiPerfProcessCount = (
4332  leftNs: number,
4333  rightNs: number,
4334  cpus: Array<number>,
4335  threads: Array<number>,
4336  processes: Array<number>
4337): Promise<Array<any>> => {
4338  let str = '';
4339  if (processes.length > 0) {
4340    str = ` and C.process_id in (${processes.join(',')})`;
4341  }
4342  if (threads.length > 0) {
4343    str = ` and A.thread_id in (${threads.join(',')}) `;
4344  }
4345  if (processes.length > 0 && threads.length > 0) {
4346    str = ` and (C.process_id in (${processes.join(',')}) or A.thread_id in (${threads.join(',')}))`;
4347  }
4348  if (cpus.length > 0) {
4349    str = ` and A.cpu_id in (${cpus.join(',')})`;
4350  }
4351  if (cpus.length > 0 && processes.length > 0) {
4352    str = ` and (C.process_id in (${processes.join(',')}) or A.cpu_id in (${cpus.join(',')}))`;
4353  }
4354  return query(
4355    'queryHiPerfProcessCount',
4356    `
4357    select     C.process_id as pid,
4358               (A.timestamp_trace - R.start_ts) as time,
4359               C.thread_name as threadName,
4360               A.thread_id as tid,
4361               A.id,
4362               A.callchain_id
4363        from perf_sample A,trace_range R
4364             left join perf_thread C on A.thread_id = C.thread_id  and  A.thread_id != 0
4365        where time >= $leftNs and time <= $rightNs and A.callchain_id > 0
4366        ${str}
4367    `,
4368    { $leftNs: leftNs, $rightNs: rightNs }
4369  );
4370};
4371
4372export const queryConcurrencyTask = (itid: number, selectStartTime: number, selectEndTime: number) =>
4373  query<TaskTabStruct>(
4374    'queryConcurrencyTask',
4375    `SELECT thread.tid,
4376            thread.ipid,
4377            callstack.name                AS funName,
4378            callstack.ts                  AS startTs,
4379            (case when callstack.dur = -1 then (SELECT end_ts FROM trace_range) else callstack.dur end) as dur,
4380            callstack.id,
4381            task_pool.priority,
4382            task_pool.allocation_task_row AS allocationTaskRow,
4383            task_pool.execute_task_row    AS executeTaskRow,
4384            task_pool.return_task_row     AS returnTaskRow,
4385            task_pool.execute_id          AS executeId
4386     FROM thread
4387            LEFT JOIN callstack ON thread.id = callstack.callid
4388            LEFT JOIN task_pool ON callstack.id = task_pool.execute_task_row
4389     WHERE ipid = (SELECT thread.ipid
4390                   FROM thread
4391                   WHERE thread.itid = $itid)
4392       AND thread.name = 'TaskWorkThread'
4393       AND callstack.name LIKE 'H:Task Perform:%'
4394       AND -- 左包含
4395           (($selectStartTime <= callstack.ts AND $selectEndTime > callstack.ts)
4396        OR -- 右包含
4397       ($selectStartTime < callstack.ts + callstack.dur AND $selectEndTime >= callstack.ts + callstack.dur)
4398        OR -- 包含
4399       ($selectStartTime >= callstack.ts AND $selectEndTime <= callstack.ts +
4400        (case when callstack.dur = -1 then (SELECT end_ts FROM trace_range) else callstack.dur end))
4401        OR -- 被包含
4402       ($selectStartTime <= callstack.ts AND $selectEndTime >= callstack.ts + callstack.dur))
4403     ORDER BY callstack.ts;`,
4404    { $itid: itid, $selectStartTime: selectStartTime, $selectEndTime: selectEndTime }
4405  );
4406
4407export const queryBySelectExecute = (
4408  executeId: string,
4409  itid: number
4410): Promise<
4411  Array<{
4412    tid: number;
4413    allocation_task_row: number;
4414    execute_task_row: number;
4415    return_task_row: number;
4416    priority: number;
4417  }>
4418> => {
4419  let sqlStr = `SELECT thread.tid,
4420                       task_pool.allocation_task_row,
4421                       task_pool.execute_task_row,
4422                       task_pool.return_task_row,
4423                       task_pool.priority
4424                FROM task_pool
4425                       LEFT JOIN callstack ON callstack.id = task_pool.allocation_task_row
4426                       LEFT JOIN thread ON thread.id = callstack.callid
4427                WHERE task_pool.execute_id = $executeId AND task_pool.execute_itid = $itid;
4428    `;
4429  return query('queryBySelectExecute', sqlStr, { $executeId: executeId, $itid: itid });
4430};
4431
4432export const queryBySelectAllocationOrReturn = (
4433  executeId: string,
4434  itid: number
4435): Promise<
4436  Array<{
4437    tid: number;
4438    allocation_task_row: number;
4439    execute_task_row: number;
4440    return_task_row: number;
4441    priority: number;
4442  }>
4443> => {
4444  let sqlStr = `SELECT thread.tid,
4445                       task_pool.allocation_task_row,
4446                       task_pool.execute_task_row,
4447                       task_pool.return_task_row,
4448                       task_pool.priority
4449                FROM task_pool
4450                       LEFT JOIN callstack ON callstack.id = task_pool.execute_task_row
4451                       LEFT JOIN thread ON thread.id = callstack.callid
4452                WHERE task_pool.execute_task_row IS NOT NULL AND task_pool.execute_id = $executeId
4453                AND task_pool.allocation_itid = $itid;
4454    `;
4455  return query('queryBySelectAllocationOrReturn', sqlStr, { $executeId: executeId, $itid: itid });
4456};
4457
4458export const queryTaskListByExecuteTaskIds = (
4459  executeTaskIds: Array<number>,
4460  ipid: number
4461): Promise<Array<TaskTabStruct>> => {
4462  let sqlStr = `
4463    SELECT thread.ipid,
4464           task_pool.allocation_task_row AS allocationTaskRow,
4465           task_pool.execute_task_row    AS executeTaskRow,
4466           task_pool.return_task_row     AS returnTaskRow,
4467           task_pool.execute_id          AS executeId,
4468           task_pool.priority
4469    FROM task_pool
4470           LEFT JOIN callstack ON callstack.id = task_pool.allocation_task_row
4471           LEFT JOIN thread ON thread.id = callstack.callid
4472    WHERE task_pool.execute_id IN (${executeTaskIds.join(',')})
4473      AND thread.ipid = $ipid
4474      AND task_pool.execute_task_row IS NOT NULL;
4475    `;
4476  return query('queryTaskListByExecuteTaskIds', sqlStr, { $executeTaskIds: executeTaskIds, $ipid: ipid });
4477};
4478
4479export const queryTaskPoolCallStack = (): Promise<Array<{ id: number; ts: number; dur: number; name: string }>> => {
4480  let sqlStr = `select * from callstack where name like 'H:Task%';`;
4481  return query('queryTaskPoolCallStack', sqlStr, {});
4482};
4483
4484export const queryTaskPoolTotalNum = (itid: number) =>
4485  query<number>(
4486    'queryTaskPoolTotalNum',
4487    `SELECT thread.tid
4488         FROM thread
4489                LEFT JOIN callstack ON thread.id = callstack.callid
4490         WHERE ipid = (SELECT thread.ipid
4491                       FROM thread
4492                       WHERE thread.itid = $itid)
4493           AND thread.name = 'TaskWorkThread'
4494         GROUP BY thread.tid;`,
4495    { $itid: itid }
4496  );
4497
4498export const queryFrameAnimationData = (): Promise<Array<FrameAnimationStruct>> =>
4499  query(
4500    'queryFrameAnimationData',
4501    `SELECT
4502           a.id AS animationId,
4503           (CASE
4504               WHEN a.input_time not null THEN (a.input_time - R.start_ts)
4505               ELSE (a.start_point- R.start_ts)
4506               END) AS ts,
4507           (a.start_point - R.start_ts) AS dynamicStartTs,
4508           (a.end_point - R.start_ts) AS dynamicEndTs
4509        FROM
4510            animation AS a,
4511            trace_range AS R
4512        ORDER BY
4513            ts;`
4514  );
4515
4516export const queryFrameDynamicData = (): Promise<Array<FrameDynamicStruct>> =>
4517  query(
4518    'queryFrameDynamicData',
4519    `SELECT
4520           d.id,
4521           d.x,
4522           d.y,
4523           d.width,
4524           d.height,
4525           d.alpha,
4526           d.name AS appName,
4527           (d.end_time - R.start_ts) AS ts
4528        FROM
4529            dynamic_frame AS d,
4530            trace_range AS R
4531        ORDER BY
4532            d.end_time;`
4533  );
4534
4535export const queryFrameApp = (): Promise<
4536  Array<{
4537    name: string;
4538  }>
4539> =>
4540  query(
4541    'queryFrameApp',
4542    `SELECT
4543            DISTINCT d.name
4544         FROM
4545             dynamic_frame AS d,
4546             trace_range AS R
4547         WHERE
4548            d.end_time >= R.start_ts
4549            AND
4550            d.end_time <= R.end_ts;`
4551  );
4552
4553export const queryAnimationFrameFps = (
4554  startTime: number,
4555  endTime: number
4556): Promise<
4557  Array<{
4558    fps: number;
4559  }>
4560> =>
4561  query(
4562    'queryAnimationFrameFps',
4563    `SELECT
4564            count(*) as fps
4565        FROM
4566            dynamic_frame AS d,
4567            trace_range AS R
4568        WHERE
4569            d.end_time >= (${startTime} + R.start_ts)
4570        AND
4571            d.end_time <= (${endTime} + R.start_ts)`
4572  );
4573
4574export const queryFrameSpacing = (): Promise<Array<FrameSpacingStruct>> =>
4575  query(
4576    'queryFrameSpacing',
4577    `SELECT
4578         d.id,
4579         d.width AS currentFrameWidth,
4580         d.height AS currentFrameHeight,
4581         d.name AS nameId,
4582         (d.end_time - R.start_ts) AS currentTs,
4583         d.x,
4584         d.y
4585     FROM
4586         dynamic_frame AS d,
4587         trace_range AS R
4588     ORDER BY
4589         d.end_time;`
4590  );
4591
4592export const queryPhysicalData = (): Promise<Array<DeviceStruct>> =>
4593  query(
4594    'queryPhysicalData',
4595    `SELECT physical_width AS physicalWidth,
4596            physical_height AS physicalHeight,
4597            physical_frame_rate AS physicalFrameRate
4598     FROM device_info;`
4599  );
4600
4601export const queryJsCpuProfilerConfig = (): Promise<Array<any>> =>
4602  query('queryJsCpuProfilerConfig', `SELECT pid, type, enable_cpu_Profiler as enableCpuProfiler FROM js_config`);
4603export const queryJsCpuProfilerData = (): Promise<Array<any>> =>
4604  query('queryJsCpuProfilerData', `SELECT 1 WHERE EXISTS(select 1 from js_cpu_profiler_node)`);
4605
4606export const queryJsMemoryData = (): Promise<Array<any>> =>
4607  query('queryJsMemoryData', `SELECT 1 WHERE EXISTS(SELECT 1 FROM js_heap_nodes)`);
4608
4609export const queryAllTaskPoolPid = (): Promise<Array<{ pid: number }>> =>
4610  query(
4611    'queryAllTaskPoolPid',
4612    `SELECT DISTINCT pid from task_pool LEFT JOIN callstack ON callstack.id = task_pool.execute_task_row
4613    LEFT JOIN thread ON thread.id = callstack.callid LEFT JOIN process ON
4614        process.id = thread.ipid WHERE task_pool.execute_task_row IS NOT NULL`
4615  );
4616export const queryVmTrackerShmData = (iPid: number): Promise<Array<any>> =>
4617  query(
4618    'queryVmTrackerShmData',
4619    `SELECT (A.ts - B.start_ts) as startNs,
4620      sum(A.size) as value
4621    FROM
4622      memory_ashmem A,trace_range B
4623    where
4624      A.ipid = ${iPid}
4625      AND A.ts < B.end_ts
4626    and
4627      flag = 0
4628    GROUP by A.ts`,
4629    {}
4630  );
4631
4632export const queryVmTrackerShmSizeData = (
4633  leftNs: number,
4634  rightNs: number,
4635  iPid: number,
4636  dur: number
4637): Promise<Array<any>> =>
4638  query(
4639    'queryVmTrackerShmSizeData',
4640    `SELECT ( A.ts - B.start_ts ) AS startNS,
4641        A.flag,
4642        avg( A.size ) AS avg,
4643        max( A.size ) AS max,
4644        min( A.size ) AS min,
4645        sum( A.size ) AS sum
4646      FROM
4647        memory_ashmem A,
4648        trace_range B
4649      WHERE
4650        startNS <= ${rightNs}  and (startNS+ ${dur}) >=${leftNs}
4651        AND ipid = ${iPid}`,
4652    {}
4653  );
4654
4655export const queryVmTrackerShmSelectionData = (startNs: number, ipid: number): Promise<Array<any>> =>
4656  query(
4657    'queryVmTrackerShmSelectionData',
4658    `SELECT (A.ts - B.start_ts) as startNS,A.ipid,
4659             A.fd,A.size,A.adj,A.ashmem_name_id as name,
4660             A.ashmem_id as id,A.time,A.purged,A.ref_count as count,
4661             A.flag
4662             FROM memory_ashmem A,trace_range B
4663             where startNS = ${startNs} and ipid = ${ipid};`,
4664    {}
4665  );
4666export const getTabSmapsRecordData = (rightNs: number): Promise<Array<Smaps>> =>
4667  query<Smaps>(
4668    'getTabSmapsRecordData',
4669    `
4670      SELECT
4671     (A.timestamp - t.start_ts) AS startNs,
4672     start_addr as startAddr,
4673     end_addr as endAddr,
4674     A.type,
4675     resident_size * 1024 AS rss,
4676     protection_id as pid,
4677     pss * 1024 as pss,virtaul_size * 1024 AS size,reside,A.path_id AS path,
4678     shared_clean * 1024 as sharedClean,shared_dirty * 1024 as sharedDirty,private_clean * 1024 as privateClean,
4679     private_dirty * 1024 as privateDirty,swap * 1024 as swap,swap_pss * 1024 as swapPss
4680     FROM smaps A,
4681     trace_range AS t
4682     WHERE (startNs) = $rightNs`,
4683    { $rightNs: rightNs },
4684    'exec'
4685  );
4686
4687export const getTabSmapsStatisticMaxSize = (rightNs: number): Promise<Array<any>> =>
4688  query<Smaps>(
4689    'getTabSmapsStatisticMaxRss',
4690    `
4691SELECT (A.timestamp - B.start_ts) as startNS, sum(virtaul_size) * 1024 as max_value FROM smaps A,trace_range B where startNS = $rightNs`,
4692    { $rightNs: rightNs }
4693  );
4694export const queryMemoryConfig = (): Promise<Array<MemoryConfig>> =>
4695  query(
4696    'queryMemoryConfiig',
4697    `SELECT ipid as iPid, process.pid AS pid,
4698      process.name AS processName,
4699      (SELECT value FROM trace_config WHERE trace_source = 'memory_config' AND key = 'sample_interval') AS interval
4700    FROM
4701      trace_config
4702      LEFT JOIN process ON value = ipid
4703    WHERE
4704      trace_source = 'memory_config'
4705      AND key = 'ipid'
4706      ;`
4707  );
4708
4709//   Ability Monitor Dma泳道图
4710export const queryDmaAbilityData = (): Promise<Array<SnapshotStruct>> =>
4711  query(
4712    'queryDmaAbilityData',
4713    `SELECT
4714      (A.ts - B.start_ts) as startNs,
4715      sum(A.size) as value,
4716      E.data as expTaskComm,
4717      A.flag as flag
4718    FROM memory_dma A,trace_range B
4719    left join data_dict as E on E.id=A.exp_task_comm_id
4720    WHERE
4721      A.flag = 0
4722      AND A.ts < B.end_ts
4723    GROUP by A.ts;`
4724  );
4725
4726//   Ability Monitor SkiaGpuMemory泳道图
4727export const queryGpuMemoryAbilityData = (): Promise<Array<SnapshotStruct>> =>
4728  query(
4729    'queryGpuMemoryAbilityData',
4730    `SELECT
4731    (A.ts - B.start_ts) as startNs,
4732    sum(A.used_gpu_size) as value
4733    FROM memory_process_gpu A,trace_range B
4734    WHERE A.ts < B.end_ts
4735    GROUP by A.ts;`
4736  );
4737
4738//   VM Tracker Dma泳道图
4739export const queryDmaSampsData = (process: number): Promise<Array<SnapshotStruct>> =>
4740  query(
4741    'queryDmaSampsData',
4742    `SELECT
4743      (A.ts - B.start_ts) as startNs,
4744      sum(A.size) as value,
4745      A.flag as flag,
4746      A.ipid as ipid,
4747      E.data as expTaskComm
4748      FROM memory_dma A,trace_range B
4749      left join data_dict as E on E.id=A.exp_task_comm_id
4750    WHERE
4751      A.flag = 0
4752      AND  $pid = A.ipid
4753      AND A.ts < B.end_ts
4754    GROUP by A.ts;`,
4755    { $pid: process }
4756  );
4757
4758//  VM Tracker Gpu Memory泳道图
4759export const queryGpuMemoryData = (processId: number): Promise<Array<SnapshotStruct>> =>
4760  query(
4761    'queryGpuMemorySampsData',
4762    `SELECT
4763    (A.ts - B.start_ts) as startNs,
4764    sum(A.used_gpu_size) as value,
4765    A.ipid as ipid
4766    FROM memory_process_gpu A,trace_range B
4767    WHERE
4768    $pid = A.ipid
4769    AND A.ts < B.end_ts
4770    GROUP by A.ts;`,
4771    { $pid: processId }
4772  );
4773
4774// Ability Monitor Purgeable泳道图
4775export const queryPurgeableSysData = (isPin?: boolean): Promise<Array<any>> => {
4776  const pinCondition = isPin ? ' AND a.ref_count > 0' : '';
4777  const names = isPin ? " ('sys.mem.pined.purg')" : "('sys.mem.active.purg','sys.mem.inactive.purg')";
4778  return query(
4779    'queryPurgeableSysData',
4780    `SELECT
4781      startNs,
4782      sum( value ) AS value
4783  FROM
4784      (
4785      SELECT
4786          m.ts - tr.start_ts AS startNs,
4787          sum( m.value ) AS value
4788      FROM
4789          sys_mem_measure m,
4790          trace_range tr
4791          LEFT JOIN sys_event_filter f ON f.id = m.filter_id
4792      WHERE
4793          m.ts < tr.end_ts
4794          AND f.name IN ${names}
4795      GROUP BY
4796          m.ts UNION ALL
4797      SELECT
4798          a.ts - tr.start_ts AS startNs,
4799          sum( a.size ) AS value
4800      FROM
4801          memory_ashmem a,
4802          trace_range tr
4803      WHERE
4804          a.ts < tr.end_ts
4805          AND a.flag = 0
4806          ${pinCondition}
4807          GROUP BY
4808              a.ts
4809          )
4810      GROUP BY startNs`
4811  );
4812};
4813
4814// VM Tracker Purgeable泳道图
4815export const queryPurgeableProcessData = (ipid: number, isPin?: boolean): Promise<Array<any>> => {
4816  const pinSql = isPin ? ' AND a.ref_count > 0' : '';
4817  const names = isPin ? " ('mem.purg_pin')" : "('mem.purg_sum')";
4818  return query(
4819    'queryPurgeableProcessData',
4820    `SELECT startNs, sum( value ) AS value
4821    FROM
4822        (SELECT
4823            m.ts - tr.start_ts AS startNs,
4824            sum(m.value) AS value
4825        FROM
4826            process_measure m,
4827            trace_range tr
4828            LEFT JOIN process_measure_filter f ON f.id = m.filter_id
4829        WHERE
4830            m.ts < tr.end_ts
4831            AND f.name = ${names}
4832            AND f.ipid = ${ipid}
4833        GROUP BY m.ts
4834        UNION ALL
4835        SELECT
4836            a.ts - tr.start_ts AS startNs,
4837            sum( a.pss ) AS value
4838        FROM
4839            memory_ashmem a,
4840            trace_range tr
4841        WHERE
4842            a.ts < tr.end_ts
4843            AND a.flag = 0
4844            AND a.ipid = ${ipid}
4845            ${pinSql}
4846            GROUP BY a.ts)
4847        GROUP BY startNs`
4848  );
4849};
4850
4851//Ability Monitor Purgeable 框选 tab页
4852export const querySysPurgeableTab = (
4853  leftNs: number,
4854  rightNs: number,
4855  dur: number,
4856  isPin?: boolean
4857): Promise<Array<any>> => {
4858  let pinsql = isPin ? ' AND ref_count > 0' : '';
4859  const names = isPin ? " ('sys.mem.pined.purg')" : "('sys.mem.active.purg','sys.mem.inactive.purg')";
4860  return query(
4861    'querySysPurgeableTab',
4862    `SELECT name, MAX( size ) AS maxSize,MIN( size ) AS minSize,AVG( size ) AS avgSize
4863    FROM
4864        (SELECT
4865          'ShmPurg' AS name,
4866          ts - tr.start_ts AS startTs,
4867          SUM( size ) AS size
4868        FROM
4869          memory_ashmem,
4870          trace_range tr
4871        WHERE flag = 0
4872        ${pinsql}
4873        GROUP BY ts UNION
4874        SELECT
4875        CASE
4876          WHEN
4877            f.name = 'sys.mem.active.purg' THEN
4878              'ActivePurg'
4879              WHEN f.name = 'sys.mem.inactive.purg' THEN
4880              'InActivePurg' ELSE 'PinedPurg'
4881            END AS name,
4882            m.ts - tr.start_ts AS startTs,
4883            m.value AS size
4884          FROM
4885            sys_mem_measure m,
4886            trace_range tr
4887            LEFT JOIN sys_event_filter f ON f.id = m.filter_id
4888          WHERE
4889            f.name IN ${names}
4890          ),
4891          trace_range tr
4892        WHERE ${leftNs} <= startTs + ${dur} AND ${rightNs} >= startTs
4893        GROUP BY name`
4894  );
4895};
4896
4897//Ability Monitor Purgeable 点选 tab页
4898export const querySysPurgeableSelectionTab = (startNs: number, isPin?: boolean): Promise<Array<any>> => {
4899  const pinSql = isPin ? ' AND ref_count > 0' : '';
4900  const names = isPin ? " ('sys.mem.pined.purg')" : "('sys.mem.active.purg','sys.mem.inactive.purg')";
4901  return query(
4902    'querySysPurgeableSelectionTab',
4903    `SELECT
4904    ( CASE WHEN f.name = 'sys.mem.active.purg' THEN 'ActivePurg' WHEN f.name = 'sys.mem.inactive.purg' THEN 'InActivePurg' ELSE 'PinedPurg' END ) AS name,
4905    m.value AS value
4906    FROM
4907    sys_mem_measure m,
4908    trace_range tr
4909    LEFT JOIN sys_event_filter f ON f.id = m.filter_id
4910    WHERE
4911    f.name IN ${names}
4912    AND m.ts - tr.start_ts = ${startNs}
4913    UNION
4914    SELECT
4915    'ShmPurg' AS name,
4916    SUM( size ) AS value
4917    FROM
4918    memory_ashmem,
4919    trace_range tr
4920    WHERE
4921    memory_ashmem.ts - tr.start_ts = ${startNs}
4922    AND flag=0
4923    ${pinSql}
4924    GROUP BY ts`
4925  );
4926};
4927
4928///////////////////////////////////////////////
4929//VM  Purgeable 框选 tab页
4930export const queryProcessPurgeableTab = (
4931  leftNs: number,
4932  rightNs: number,
4933  dur: number,
4934  ipid: number,
4935  isPin?: boolean
4936): Promise<Array<any>> => {
4937  const pinSql = isPin ? ' AND ref_count > 0' : '';
4938  let filterSql = isPin ? "'mem.purg_pin'" : "'mem.purg_sum'";
4939  return query(
4940    'queryProcessPurgeableTab',
4941    `SELECT name, MAX(size) AS maxSize, MIN(size) AS minSize, AVG(size) AS avgSize
4942    FROM
4943      (SELECT
4944        'ShmPurg' AS name, ts - tr.start_ts AS startTs, SUM( pss ) AS size
4945      FROM
4946        memory_ashmem,
4947        trace_range tr
4948      WHERE
4949        ipid = ${ipid}
4950        AND flag = 0
4951        ${pinSql}
4952      GROUP BY ts
4953      UNION
4954      SELECT
4955      CASE
4956          WHEN f.name = 'mem.purg_pin' THEN
4957          'PinedPurg' ELSE 'TotalPurg'
4958        END AS name,
4959        m.ts - tr.start_ts AS startTs,
4960        sum( m.value ) AS size
4961      FROM
4962        process_measure m,
4963        trace_range tr
4964        LEFT JOIN process_measure_filter f ON f.id = m.filter_id
4965      WHERE f.name = ${filterSql}
4966        AND f.ipid = ${ipid}
4967      GROUP BY m.ts
4968    ) combined_data, trace_range tr
4969    WHERE ${leftNs} <= startTs + ${dur} AND ${rightNs} >= startTs
4970    GROUP BY name`
4971  );
4972};
4973
4974//VM  Purgeable 点选 tab页
4975export const queryProcessPurgeableSelectionTab = (
4976  startNs: number,
4977  ipid: number,
4978  isPin?: boolean
4979): Promise<Array<any>> => {
4980  const condition = isPin ? "'mem.purg_pin'" : "'mem.purg_sum'";
4981  const pinSql = isPin ? ' AND ref_count > 0' : '';
4982  return query(
4983    'queryProcessPurgeableSelectionTab',
4984    `SELECT
4985        ( CASE WHEN f.name = 'mem.purg_pin' THEN 'PinedPurg' ELSE 'TotalPurg' END ) AS name,
4986        SUM( m.value )  AS value
4987    FROM
4988        process_measure m,
4989        trace_range tr
4990        left join process_measure_filter f on f.id = m.filter_id
4991    WHERE
4992        f.name = ${condition}
4993        AND m.ts - tr.start_ts = ${startNs}
4994    AND f.ipid = ${ipid}
4995    GROUP BY m.ts
4996    UNION
4997    SELECT
4998        'ShmPurg' AS name,
4999        SUM( pss ) AS size
5000    FROM
5001        memory_ashmem,
5002        trace_range tr
5003    WHERE
5004        ipid = ${ipid}
5005        AND ts - tr.start_ts = ${startNs}
5006        AND flag = 0
5007        ${pinSql}
5008    GROUP BY ts`
5009  );
5010};
5011
5012export const getTabSmapsStatisticData = (rightNs: number): Promise<Array<Smaps>> =>
5013  query<Smaps>(
5014    'getTabSmapsStatisticData',
5015    `SELECT
5016     (A.timestamp - t.start_ts) AS startNs,
5017     start_addr as startAddr,
5018     end_addr as endAddr,
5019     A.type,
5020     sum(resident_size) * 1024 AS rss,
5021     protection_id as pid,
5022     count(A.path_id) as count,
5023     sum(pss) * 1024 as pss ,sum(virtaul_size) * 1024 AS size,sum(reside) as reside,A.path_id AS path,
5024     sum(shared_clean) * 1024 as sharedClean,sum(shared_dirty) * 1024 as sharedDirty,sum(private_clean) * 1024 as privateClean,sum(private_dirty) * 1024 as privateDirty,
5025     sum(swap) * 1024 as swap,sum(swap_pss) * 1024 as swapPss
5026     FROM smaps A,
5027     trace_range AS t
5028     WHERE (startNs) =$rightNs
5029     group by type,path`,
5030    { $rightNs: rightNs },
5031    'exec'
5032  );
5033
5034export const getTabSmapsStatisticSelectData = (leftNs: number, rightNs: number, dur: number): Promise<Array<Smaps>> =>
5035  query<Smaps>(
5036    'getTabSmapsStatisticData',
5037    `SELECT
5038     (A.timestamp - t.start_ts) AS startNs,
5039     start_addr as startAddr,
5040     end_addr as endAddr,
5041     A.type,
5042     sum(resident_size) * 1024 AS rss,
5043     protection_id as pid,
5044     count(A.path_id) as count,
5045     sum(pss) * 1024 as pss ,sum(virtaul_size) * 1024 AS size,sum(reside) as reside,A.path_id AS path,
5046     sum(shared_clean) * 1024 as sharedClean,sum(shared_dirty) * 1024 as sharedDirty,sum(private_clean) * 1024 as privateClean,sum(private_dirty) * 1024 as privateDirty,
5047     sum(swap) * 1024 as swap,sum(swap_pss) * 1024 as swapPss
5048     FROM smaps A,
5049     trace_range AS t
5050     WHERE (startNs) <=$rightNs and (startNs+$dur)>=$leftNs
5051     group by type,path`,
5052    { $rightNs: rightNs, $leftNs: leftNs, $dur: dur },
5053    'exec'
5054  );
5055
5056//Ability Monitor Dma 框选
5057export const getTabDmaAbilityData = (leftNs: number, rightNs: number, dur: number): Promise<Array<Dma>> =>
5058  query<Dma>(
5059    'getTabDmaAbilityData',
5060    `SELECT (S.ts-TR.start_ts) as startNs,
5061        MAX(S.size) as maxSize,
5062        MIN(S.size) as minSize,
5063        Avg(S.size) as avgSize,
5064        E.pid as processId,
5065        E.name as processName
5066    from trace_range as TR,memory_dma as S
5067    left join process as E on E.ipid=S.ipid
5068    WHERE
5069      $leftNS <= startNs + ${dur} and $rightNS >= startNs
5070      and flag = 0
5071    GROUP by E.pid
5072              `,
5073    { $leftNS: leftNs, $rightNS: rightNs }
5074  );
5075
5076//Ability Monitor SkiaGpuMemory 框选
5077export const getTabGpuMemoryAbilityData = (leftNs: number, rightNs: number, dur: number): Promise<Array<GpuMemory>> =>
5078  query<GpuMemory>(
5079    'getTabGpuMemoryAbilityData',
5080    `SELECT (S.ts-TR.start_ts) as startNs,
5081    gpu_name_id as gpuNameId,
5082    MAX(S.used_gpu_size) as maxSize,
5083    MIN(S.used_gpu_size) as minSize,
5084    Avg(S.used_gpu_size) as avgSize,
5085    E.pid as processId,
5086    E.name as processName
5087    from trace_range as TR,memory_process_gpu as S
5088    left join process as E on E.ipid=S.ipid
5089    WHERE
5090    $leftNS <= startNs + ${dur}
5091    and
5092    $rightNS >= startNs
5093    GROUP by
5094    E.pid ,S.gpu_name_id
5095            `,
5096    { $leftNS: leftNs, $rightNS: rightNs }
5097  );
5098
5099//VM Tracker Dma 框选
5100export const getTabDmaVmTrackerData = (
5101  leftNs: number,
5102  rightNs: number,
5103  processId: number,
5104  dur: number
5105): Promise<Array<Dma>> =>
5106  query<Dma>(
5107    'getTabDmaVmTrackerData',
5108    `SELECT (S.ts-TR.start_ts) as startNs,
5109      MAX(S.size) as maxSize,
5110      MIN(S.size) as minSize,
5111      Avg(S.size) as avgSize
5112    from trace_range as TR,memory_dma as S
5113    left join data_dict as C on C.id=S.exp_task_comm_id
5114    where
5115      $leftNS <= startNs + ${dur} and $rightNS >= startNs
5116      and flag = 0
5117    and
5118        $pid = S.ipid
5119              `,
5120    { $leftNS: leftNs, $rightNS: rightNs, $pid: processId }
5121  );
5122//VM Tracker SkiaGpuMemory 框选
5123export const getTabGpuMemoryData = (
5124  leftNs: number,
5125  rightNs: number,
5126  processId: number,
5127  dur: number
5128): Promise<Array<GpuMemory>> =>
5129  query<GpuMemory>(
5130    'getTabGpuMemoryData',
5131    `SELECT
5132      (S.ts-TR.start_ts) as startNs,
5133      gpu_name_id as gpuNameId,
5134      T.tid as threadId,
5135      T.name as threadName,
5136      MAX(S.used_gpu_size) as maxSize,
5137      MIN(S.used_gpu_size) as minSize,
5138      Avg(S.used_gpu_size) as avgSize
5139      from trace_range as TR,memory_process_gpu as S
5140      left join thread as T on T.itid=S.itid
5141      where
5142       $leftNS <= startNs + ${dur}
5143      and
5144      $rightNS >= startNs
5145      and
5146        $pid = S.ipid
5147      group by gpu_name_id,threadId
5148              `,
5149    { $leftNS: leftNs, $rightNS: rightNs, $pid: processId }
5150  );
5151
5152//Ability Monitor Dma 点选
5153export const getTabDmaAbilityClickData = (startNs: number): Promise<Array<Dma>> =>
5154  query<Dma>(
5155    'getTabDmaAbilityClickData',
5156    `SELECT
5157  (S.ts-TR.start_ts) as startNs,
5158    S.fd as fd,
5159    S.size as size,
5160    S.ino as ino,
5161    S.exp_pid as expPid,
5162    buf_name_id as bufName,
5163    exp_name_id as expName,
5164    exp_task_comm_id as expTaskComm,
5165    E.pid as processId,
5166    E.name as processName,
5167    S.flag as flag
5168    from trace_range as TR,memory_dma as S
5169    left join process as E on E.ipid=S.ipid
5170    WHERE
5171    startNs = ${startNs}
5172              `,
5173    { $startNs: startNs }
5174  );
5175
5176//VM Tracker Dma 点选
5177export const getTabDmaVMTrackerClickData = (startNs: number, processId: number): Promise<Array<Dma>> =>
5178  query<Dma>(
5179    'getTabDmaVMTrackerClickData',
5180    `SELECT
5181    (S.ts-TR.start_ts) as startNs,
5182    S.fd as fd,
5183    S.size as size,
5184    S.ino as ino,
5185    S.exp_pid as expPid,
5186    buf_name_id as bufName,
5187    exp_name_id as expName,
5188    exp_task_comm_id as expTaskComm,
5189    S.flag as flag
5190    from trace_range as TR,memory_dma as S
5191    WHERE
5192    startNs = ${startNs}
5193    AND
5194    $pid = S.ipid
5195              `,
5196    { $startNs: startNs, $pid: processId }
5197  );
5198
5199//Ability Monitor SkiaGpuMemory 点选
5200export const getTabGpuMemoryAbilityClickData = (startNs: number): Promise<Array<GpuMemory>> =>
5201  query<GpuMemory>(
5202    'getTabGpuMemoryAbilityClickData',
5203    `SELECT
5204    (S.ts-TR.start_ts) as startNs,
5205    S.used_gpu_size as size,
5206    E.pid as processId,
5207    E.name as processName,
5208    A.data as gpuName
5209    from trace_range as TR,memory_process_gpu as S
5210    left join process as E on E.ipid=S.ipid
5211    left join data_dict as A on A.id=S.gpu_name_id
5212    WHERE
5213    startNs = ${startNs}
5214              `,
5215    { $startNs: startNs }
5216  );
5217
5218//VM Tracker SkiaGpuMemory 点选
5219export const getTabGpuMemoryVMTrackerClickData = (startNs: number, processId: number): Promise<Array<GpuMemory>> =>
5220  query<GpuMemory>(
5221    'getTabGpuMemoryVMTrackerClickData',
5222    `SELECT
5223    (S.ts-TR.start_ts) as startNs,
5224    S.used_gpu_size as size,
5225    T.tid as threadId,
5226    T.name as threadName,
5227    A.data as gpuName
5228    from trace_range as TR,memory_process_gpu as S
5229    left join thread as T on T.itid=S.itid
5230    left join data_dict as A on A.id=S.gpu_name_id
5231    WHERE
5232    startNs = ${startNs}
5233    AND
5234    $pid = S.ipid
5235              `,
5236    { $startNs: startNs, $pid: processId }
5237  );
5238
5239//Ability Monitor Dma 点选比较
5240export const getTabDmaAbilityComparisonData = (startNs: number): Promise<Array<DmaComparison>> =>
5241  query<DmaComparison>(
5242    'getTabDmaAbilityComparisonData',
5243    `SELECT
5244      (S.ts-TR.start_ts) as startNs,
5245      sum(S.size) as value,
5246      E.pid as processId,
5247      E.name as processName
5248      from trace_range as TR,memory_dma as S
5249      left join process as E on E.ipid=S.ipid
5250      WHERE
5251      startNs = ${startNs}
5252      GROUP by
5253      E.pid
5254                `,
5255    { $startNs: startNs }
5256  );
5257
5258//Ability Monitor Gpu Memory 点选比较
5259export const getTabGpuMemoryComparisonData = (startNs: number): Promise<Array<GpuMemoryComparison>> =>
5260  query<GpuMemoryComparison>(
5261    'getTabGpuMemoryComparisonData',
5262    `SELECT
5263      (S.ts-TR.start_ts) as startNs,
5264      sum(S.used_gpu_size) as value,
5265      E.pid as processId,
5266      S.gpu_name_id as gpuNameId,
5267      E.name as processName
5268      from trace_range as TR,memory_process_gpu as S
5269      left join process as E on E.ipid=S.ipid
5270      WHERE
5271      startNs = ${startNs}
5272      GROUP by
5273      E.pid, S.gpu_name_id
5274                `,
5275    { $startNs: startNs }
5276  );
5277
5278//VM Tracker Dma 点选比较
5279export const getTabDmaVmTrackerComparisonData = (startNs: number, processId: number): Promise<Array<DmaComparison>> =>
5280  query<DmaComparison>(
5281    'getTabDmaVmTrackerComparisonData',
5282    `SELECT
5283    (S.ts-TR.start_ts) as startNs,
5284    sum(S.size) as value
5285    from trace_range as TR,memory_dma as S
5286    WHERE
5287    startNs = ${startNs}
5288    AND
5289    $pid = S.ipid
5290                `,
5291    { $startNs: startNs, $pid: processId }
5292  );
5293
5294//VM Tracker Gpu Memory 点选比较
5295export const getTabGpuMemoryVmTrackerComparisonData = (
5296  startNs: number,
5297  processId: number
5298): Promise<Array<GpuMemoryComparison>> =>
5299  query<GpuMemoryComparison>(
5300    'getTabGpuMemoryVmTrackerComparisonData',
5301    `SELECT
5302    (S.ts-TR.start_ts) as startNs,
5303    sum(S.used_gpu_size) as value,
5304    T.tid as threadId,
5305    T.name as threadName,
5306    S.gpu_name_id as gpuNameId
5307    from trace_range as TR,memory_process_gpu as S
5308    left join thread as T on T.itid=S.itid
5309    WHERE
5310    startNs = ${startNs}
5311    AND
5312    $pid = S.ipid
5313                `,
5314    { $startNs: startNs, $pid: processId }
5315  );
5316