• 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 */
15import { FpsStruct } from '../ui-worker/ProcedureWorkerFPS';
16import { Counter, Fps } from '../../bean/BoxSelection';
17import { NativeEvent, NativeEventHeap } from '../../bean/NativeHook';
18import { HeapTreeDataBean } from '../logic-worker/ProcedureLogicWorkerCommon';
19import { EnergyAnomalyStruct } from '../ui-worker/ProcedureWorkerEnergyAnomaly';
20import { SystemDetailsEnergy } from '../../bean/EnergyStruct';
21import { EnergyStateStruct } from '../ui-worker/ProcedureWorkerEnergyState';
22import { FileInfo } from '../../../js-heap/model/UiStruct';
23import { HeapEdge, HeapLocation, HeapNode, HeapSample } from '../../../js-heap/model/DatabaseStruct';
24import { TaskTabStruct } from '../../component/trace/sheet/task/TabPaneTaskFrames';
25import type { FrameAnimationStruct } from '../ui-worker/ProcedureWorkerFrameAnimation';
26import type { FrameDynamicStruct } from '../ui-worker/ProcedureWorkerFrameDynamic';
27import type { FrameSpacingStruct } from '../ui-worker/ProcedureWorkerFrameSpacing';
28import type { DeviceStruct } from '../../bean/FrameComponentBean';
29import { LogStruct } from '../ui-worker/ProcedureWorkerLog';
30import { query } from '../SqlLite';
31import { Utils } from '../../component/trace/base/Utils';
32import { FuncStruct } from '../ui-worker/ProcedureWorkerFunc';
33
34export const queryEventCountMap = (
35  traceId?: string
36): Promise<
37  Array<{
38    eventName: string;
39    count: number;
40  }>
41> =>
42  query(
43    'queryEventCountMap',
44    `select
45  event_name as eventName,
46  count
47  from stat where stat_type = 'received';`,
48    {},
49    { traceId: traceId }
50  );
51
52export const queryTotalTime = (
53  traceId?: string
54): Promise<Array<{ total: number; recordStartNS: number; recordEndNS: number }>> =>
55  query(
56    'queryTotalTime',
57    `select start_ts as recordStartNS,end_ts as recordEndNS,end_ts-start_ts as total
58    from
59      trace_range;`,
60    {},
61    { traceId: traceId }
62  );
63export const getFps = (): Promise<FpsStruct[]> =>
64  query<FpsStruct>(
65    'getFps',
66    `
67    select
68      distinct(ts-tb.start_ts) as startNS, fps
69    from
70      hidump c ,trace_range tb
71    where
72      startNS >= 0
73    --order by startNS;
74    `,
75    {}
76  );
77
78export const getTabFps = (leftNs: number, rightNs: number): Promise<Array<Fps>> =>
79  query<Fps>(
80    'getTabFps',
81    `
82    select
83      distinct(ts-tb.start_ts) as startNS,
84      fps
85    from
86      hidump c,
87      trace_range tb
88    where
89      startNS <= $rightNS
90    and
91      startNS >= 0
92    --order by startNS;
93    `,
94    { $leftNS: leftNs, $rightNS: rightNs }
95  );
96
97export const getTabVirtualCounters = (virtualFilterIds: Array<number>, startTime: number): Promise<Counter[]> =>
98  query<Counter>(
99    'getTabVirtualCounters',
100    `
101    select
102      table1.filter_id as trackId,
103      table2.name,
104      value,
105      table1.ts - table3.start_ts as startTime
106    from
107      sys_mem_measure table1
108    left join
109      sys_event_filter table2
110    on
111      table1.filter_id = table2.id
112    left join
113      trace_range table3
114    where
115      filter_id in (${virtualFilterIds.join(',')})
116    and
117      startTime <= $startTime
118    `,
119    { $startTime: startTime }
120  );
121
122export const queryAllSoInitNames = (): //@ts-ignore
123  Promise<Array<unknown>> => {
124  return query(
125    'queryAllSoInitNames',
126    `
127        select id,so_name as name from static_initalize;`
128  );
129};
130
131export const queryAllSrcSlices = (): //@ts-ignore
132  Promise<Array<unknown>> => {
133  return query(
134    'queryAllSrcSlices',
135    `
136        select src,id from frame_slice;`
137  );
138};
139
140export const queryHeapSizeByIpid = (ipid: number): //@ts-ignore
141  Promise<Array<NativeEventHeap>> => {
142  return query(
143    'queryHeapSizeByIpid',
144    `SELECT
145      event_type AS eventType,
146      sum(heap_size) AS sumHeapSize
147    FROM
148      native_hook h left join process p on p.ipid = h.ipid
149    WHERE
150      event_type = 'AllocEvent' and
151      p.ipid = ${ipid}
152    UNION ALL
153    SELECT
154      event_type AS eventType,
155      sum(heap_size) AS sumHeapSize
156    FROM
157      native_hook h left join process p on p.ipid = h.ipid
158    WHERE
159      event_type = 'MmapEvent' and
160      p.ipid = ${ipid}`
161  );
162};
163/*-------------------------------------------------------------------------------------*/
164export const queryHeapGroupByEvent = (type: string): Promise<Array<NativeEventHeap>> => {
165  let sql1 = `
166    SELECT
167      event_type AS eventType,
168      sum(heap_size) AS sumHeapSize
169    FROM
170      native_hook
171    WHERE
172      event_type = 'AllocEvent'
173    UNION ALL
174    SELECT
175      event_type AS eventType,
176      sum(heap_size) AS sumHeapSize
177    FROM
178      native_hook
179    WHERE
180      event_type = 'MmapEvent'
181    `;
182  let sql2 = `
183        select (case when type = 0 then 'AllocEvent' else 'MmapEvent' end) eventType,
184            sum(apply_size) sumHeapSize
185        from native_hook_statistic
186        group by eventType;
187    `;
188  return query('queryHeapGroupByEvent', type === 'native_hook' ? sql1 : sql2, {});
189};
190
191export const queryAllHeapByEvent = (): Promise<Array<NativeEvent>> =>
192  query(
193    'queryAllHeapByEvent',
194    `
195    select * from (
196      select h.start_ts - t.start_ts as startTime,
197       h.heap_size as heapSize,
198       h.event_type as eventType
199from native_hook h ,trace_range t
200where h.start_ts >= t.start_ts and h.start_ts <= t.end_ts
201and (h.event_type = 'AllocEvent' or h.event_type = 'MmapEvent')
202union
203select h.end_ts - t.start_ts as startTime,
204       h.heap_size as heapSize,
205       (case when h.event_type = 'AllocEvent' then 'FreeEvent' else 'MunmapEvent' end) as eventType
206from native_hook h ,trace_range t
207where h.start_ts >= t.start_ts and h.start_ts <= t.end_ts
208and (h.event_type = 'AllocEvent' or h.event_type = 'MmapEvent')
209and h.end_ts not null ) order by startTime;
210`,
211    {}
212  );
213
214export const queryHeapAllData = (
215  startTs: number,
216  endTs: number,
217  ipids: Array<number>
218): Promise<Array<HeapTreeDataBean>> =>
219  query(
220    'queryHeapAllData',
221    `
222    select
223      h.start_ts - t.start_ts as startTs,
224      h.end_ts - t.start_ts as endTs,
225      h.heap_size as heapSize,
226      h.event_type as eventType,
227      h.callchain_id as eventId
228    from
229      native_hook h
230    inner join
231      trace_range  t
232    where
233      event_type = 'AllocEvent'
234    and
235      ipid in (${ipids.join(',')})
236    and
237      (h.start_ts - t.start_ts between ${startTs} and ${endTs}
238      or h.end_ts - t.start_ts between ${startTs} and ${endTs})`,
239    { ipids: ipids, $startTs: startTs, $endTs: endTs }
240  );
241
242export const querySelectTraceStats = (): Promise<
243  Array<{
244    event_name: string;
245    stat_type: string;
246    count: number;
247    source: string;
248    serverity: string;
249  }>
250> => query('querySelectTraceStats', 'select event_name,stat_type,count,source,serverity from stat');
251
252export const queryCustomizeSelect = (
253  sql: string
254): //@ts-ignore
255  Promise<Array<unknown>> => query('queryCustomizeSelect', sql);
256
257export const queryDistributedTerm = (): Promise<
258  Array<{
259    threadId: string;
260    threadName: string;
261    processId: string;
262    processName: string;
263    funName: string;
264    dur: string;
265    ts: string;
266    chainId: string;
267    spanId: string;
268    parentSpanId: string;
269    flag: string;
270    trace_name: string;
271  }>
272> =>
273  query(
274    'queryDistributedTerm',
275    `
276    select
277      group_concat(thread.id,',') as threadId,
278      group_concat(thread.name,',') as threadName,
279      group_concat(process.id,',') as processId,
280      group_concat(process.name,',') as processName,
281      group_concat(callstack.name,',') as funName,
282      group_concat(callstack.dur,',') as dur,
283      group_concat(callstack.ts,',') as ts,
284      cast(callstack.chainId as varchar) as chainId,
285      callstack.spanId as spanId,
286      callstack.parentSpanId as parentSpanId,
287      group_concat(callstack.flag,',') as flag,
288      (select
289        value
290      from
291        meta
292      where
293        name='source_name') as trace_name
294      from
295        callstack
296      inner join thread on callstack.callid = thread.id
297      inner join process on process.id = thread.ipid
298      where (callstack.flag='S' or callstack.flag='C')
299      group by callstack.chainId,callstack.spanId,callstack.parentSpanId`
300  );
301export const queryTraceTaskName = (): Promise<
302  Array<{
303    id: string;
304    pid: string;
305    process_name: string;
306    thread_name: string;
307  }>
308> =>
309  query(
310    'queryTraceTaskName',
311    `
312    select
313        P.id as id,
314        P.pid as pid,
315        P.name as process_name,
316        group_concat(T.name,',') as thread_name
317    from process as P left join thread as T where P.id = T.ipid
318    group by pid`
319  );
320
321export const queryTraceMetaData = (): Promise<
322  Array<{
323    name: string;
324    valueText: string;
325  }>
326> =>
327  query(
328    'queryTraceMetaData',
329    `
330    select
331        cast(name as varchar) as name,
332        cast(value as varchar) as valueText
333        from meta
334        UNION
335        select 'start_ts',cast(start_ts as varchar) from trace_range
336        UNION
337        select 'end_ts',cast(end_ts as varchar) from trace_range`
338  );
339
340export const querySystemCalls = (): Promise<
341  Array<{
342    frequency: string;
343    minDur: number;
344    maxDur: number;
345    avgDur: number;
346    funName: string;
347  }>
348> =>
349  query(
350    'querySystemCalls',
351    `
352    select
353      count(*) as frequency,
354      min(dur) as minDur,
355      max(dur) as maxDur,
356      avg(dur) as avgDur,
357      name as funName
358    from
359      callstack
360      group by name
361      order by
362    frequency desc limit 100`
363  );
364
365export const queryNetWorkMaxData = (): //@ts-ignore
366  Promise<Array<unknown>> =>
367  query(
368    'queryNetWorkMaxData',
369    `select
370     ifnull(max(tx_speed),0) as maxIn,
371     ifnull(max(rx_speed),0) as maxOut,
372     ifnull(max(packet_in_sec),0) as maxPacketIn,
373     ifnull(max(packet_in_sec),0) as maxPacketOut
374     from network`
375  );
376
377export const queryDiskIoMaxData = (): //@ts-ignore
378  Promise<Array<unknown>> =>
379  query(
380    'queryDiskIoMaxData',
381    `select
382    ifnull(max(rd_speed),0) as bytesRead,
383    ifnull(max(wr_speed),0) as bytesWrite,
384    ifnull(max(rd_count_speed),0) as readOps,
385    ifnull(max(wr_count_speed),0)  as writeOps
386    from diskio`
387  );
388//@ts-ignore
389export const queryStartTime = (): Promise<Array<unknown>> =>
390  query('queryStartTime', 'SELECT start_ts FROM trace_range');
391//@ts-ignore
392export const queryRangeTime = (): Promise<Array<unknown>> =>
393  query('queryRangeTime', `SELECT start_ts, end_ts FROM trace_range`);
394
395export const queryBinderBySliceId = (
396  id: number
397): //@ts-ignore
398  Promise<Array<unknown>> =>
399  query(
400    'queryBinderBySliceId',
401    `SELECT
402    c.ts - D.start_ts AS startTs,
403    c.dur,
404    t.tid,
405    p.pid,
406    c.depth,
407    c.argsetid,
408    c.name AS funName,
409    c.cookie,
410    c.trace_level,
411    c.trace_tag,
412    c.custom_category as category,
413    c.custom_args
414  FROM
415    callstack c,
416    trace_range D
417    LEFT JOIN thread t ON c.callid = t.id
418    LEFT JOIN process p ON p.id = t.ipid
419  WHERE
420    cat = 'binder' and c.id = $id;`,
421    { $id: id },
422    { traceId: Utils.currentSelectTrace }
423  );
424
425export const queryThreadByItid = (
426  itid: number,
427  ts: number
428): //@ts-ignore
429  Promise<Array<unknown>> =>
430  query(
431    'queryThreadByItid',
432    `SELECT
433      tid,
434      pid,
435      c.dur,
436      c.depth,
437      c.name
438    FROM
439      thread t
440      LEFT JOIN process p ON t.ipid = p.ipid
441      LEFT JOIN callstack c ON t.itid = c.callid
442    WHERE itid = $itid and c.ts = $ts;`,
443    { $itid: itid, $ts: ts }
444  );
445export const queryBinderByArgsId = (
446  id: number,
447  startTime: number,
448  isNext: boolean
449): //@ts-ignore
450  Promise<Array<unknown>> => {
451  let sql = `select c.ts - D.start_ts as startTs,
452    c.dur,
453    t.tid,
454    p.pid,
455    c.depth,
456    c.argsetid,
457    c.name as funName,
458    c.cookie,
459    c.trace_level,
460    c.trace_tag,
461    c.custom_category as category,
462    c.custom_args
463    from callstack c,trace_range D
464    left join thread t on c.callid = t.id
465    left join process p on p.id = t.ipid
466where cat = 'binder' and  c.argsetid = $id`;
467  if (isNext) {
468    sql += ' and c.ts > $startTime +  D.start_ts';
469  } else {
470    sql += ' and c.ts < $startTime +  D.start_ts';
471  }
472  return query('queryBinderByArgsId', sql, { $id: id, $startTime: startTime },
473    { traceId: Utils.currentSelectTrace }
474  );
475};
476
477export const getTabPaneFilesystemStatisticsFather = (
478  leftNs: number,
479  rightNs: number
480): //@ts-ignore
481  Promise<Array<unknown>> =>
482  query(
483    'getTabPaneFilesystemStatisticsFather',
484    `
485    select SUM(dur) as allDuration,
486    count(f.type) as count,
487    min(dur) as minDuration,
488    max(dur) as maxDuration,
489    round(avg(dur),2) as avgDuration,
490    p.name,
491    f.type,
492    p.pid,
493    sum(ifnull(size,0)) as size
494    from file_system_sample as f
495    left join process as p on f.ipid=p.ipid
496    where f.start_ts >= $leftNs
497    and end_ts <= $rightNs
498    group by f.type;
499    `,
500    { $leftNs: leftNs, $rightNs: rightNs }
501  );
502
503export const getTabPaneFilesystemStatisticsChild = (
504  leftNs: number,
505  rightNs: number
506): //@ts-ignore
507  Promise<Array<unknown>> =>
508  query(
509    'getTabPaneFilesystemStatisticsChild',
510    `
511    select SUM(dur)    as allDuration,
512        count(f.type) as count,
513        min(dur)    as minDuration,
514        max(dur)    as maxDuration,
515        round(avg(dur),2)    as avgDuration,
516        p.name,
517        p.pid,
518        f.type,
519        sum(ifnull(size,0))    as size
520        from file_system_sample as f left join process as p on f.ipid=p.ipid
521        where f.start_ts >= $leftNs
522        and end_ts <= $rightNs
523        group by f.type, f.ipid;
524`,
525    { $leftNs: leftNs, $rightNs: rightNs }
526  );
527
528export const getTabPaneFilesystemStatisticsAll = (
529  leftNs: number,
530  rightNs: number
531): //@ts-ignore
532  Promise<Array<unknown>> =>
533  query(
534    'getTabPaneFilesystemStatisticsAll',
535    `
536    select SUM(dur)    as allDuration,
537       count(type) as count,
538       min(dur)    as minDuration,
539       max(dur)    as maxDuration,
540       round(avg(dur),2)    as avgDuration,
541       type
542    from file_system_sample
543    where start_ts <= $rightNs
544    and end_ts >= $leftNs;
545`,
546    { $leftNs: leftNs, $rightNs: rightNs }
547  );
548
549export const getTabPaneFilesystemStatistics = (
550  leftNs: number,
551  rightNs: number,
552  types: number[]
553): //@ts-ignore
554  Promise<Array<unknown>> =>
555  query(
556    'getTabPaneFilesystemStatistics',
557    `
558    select p.pid,
559       ifnull(p.name,'Process') as name,
560       f.type,
561       count(f.ipid) as count,
562       sum(ifnull(size,0)) as size,
563       sum(case when f.type = 2 then ifnull(size,0) else 0 end) as logicalReads,
564       sum(case when f.type = 3 then ifnull(size,0) else 0 end) as logicalWrites,
565       sum(case when f.type != 2 and f.type != 3 then ifnull(size,0) else 0 end) as otherFile,
566       sum(dur) as allDuration,
567       min(dur) as minDuration,
568       max(dur) as maxDuration,
569       avg(dur) as avgDuration
570    from file_system_sample as f left join process as p on f.ipid=p.ipid
571    where f.end_ts >= $leftNs
572    and f.start_ts <= $rightNs
573    and f.type in (${types.join(',')})
574    group by f.type,f.ipid
575    order by f.type;
576`,
577    { $leftNs: leftNs, $rightNs: rightNs }
578  );
579
580export const getTabPaneIOTierStatisticsData = (
581  leftNs: number,
582  rightNs: number,
583  diskIOipids: Array<number>
584): //@ts-ignore
585  Promise<Array<unknown>> => {
586  let str = '';
587  if (diskIOipids.length > 0) {
588    str = ` and i.ipid in (${diskIOipids.join(',')})`;
589  }
590  return query(
591    'getTabPaneIOTierStatisticsData',
592    `
593    select p.pid,
594       ifnull(p.name,'Process') as pname,
595       i.tier,
596       i.ipid,
597       path_id as path,
598       count(i.ipid) as count,
599       sum(latency_dur) as allDuration,
600       min(latency_dur) as minDuration,
601       max(latency_dur) as maxDuration,
602       avg(latency_dur) as avgDuration
603    from bio_latency_sample as i left join process as p on i.ipid=p.ipid
604    where i.end_ts+latency_dur >= $leftNs
605    and i.start_ts+latency_dur <= $rightNs
606    ${str}
607    group by i.tier,i.ipid,i.path_id
608    order by i.tier;
609`,
610    { $leftNs: leftNs, $rightNs: rightNs }
611  );
612};
613
614export const getTabPaneFrequencySampleData = (
615  leftNs: number,
616  rightNs: number,
617  cpuFreqFilterIds: Array<number>
618): //@ts-ignore
619  Promise<Array<unknown>> => {
620  let str = '';
621  if (cpuFreqFilterIds.length > 0) {
622    str = ` and filter_id in (${cpuFreqFilterIds.join(',')})`;
623  }
624  return query(
625    'getTabPaneFrequencySampleData',
626    `
627    select value, filter_id as filterId, ts, f.cpu
628    from measure left join cpu_measure_filter as f on f.id=filter_id
629    where
630    ts <= $rightNs${str} order by ts asc;
631`,
632    { $leftNs: leftNs, $rightNs: rightNs }, { traceId: Utils.currentSelectTrace }
633  );
634};
635
636export const getFileSysChartDataByType = (
637  type: number
638): //@ts-ignore
639  Promise<Array<unknown>> =>
640  query(
641    'getFileSysChartData',
642    `
643    select
644       (A.start_ts -B.start_ts) as startNS,
645       (A.end_ts - B.start_ts) as endNS,
646       dur
647    from file_system_sample A,trace_range B
648    where type = $type and startNS > 0;`,
649    { $type: type }
650  );
651
652export const getDiskIOProcess = (): //@ts-ignore
653  Promise<Array<unknown>> =>
654  query(
655    'getDiskIOProcess',
656    `
657    select name,B.ipid,pid
658    from (select distinct ipid from bio_latency_sample A,trace_range B
659    where A.start_ts between B.start_ts and B.end_ts) A
660    left join process B on A.ipid = B.ipid;`,
661    {}
662  );
663
664export const getDiskIOLatencyChartDataByProcess = (
665  all: boolean,
666  ipid: number,
667  typeArr: Array<number>
668): //@ts-ignore
669  Promise<Array<unknown>> =>
670  query(
671    'getDiskIOLatencyChartDataByProcess',
672    `
673    select
674       (A.start_ts -B.start_ts) as startNS,
675       (A.start_ts - B.start_ts + A.latency_dur) as endNS,
676       latency_dur as dur
677    from bio_latency_sample A,trace_range B
678    where type in (${typeArr.join(',')}) and startNS > 0
679        ${all ? '' : 'and ipid = ' + ipid}
680    order by A.start_ts;`,
681    {}
682  );
683
684export const queryAnomalyData = (): Promise<Array<EnergyAnomalyStruct>> =>
685  query(
686    'queryAnomalyData',
687    `select
688       S.id,
689      (S.ts - TR.start_ts) as startNS,
690      D.data as eventName,
691      D2.data as appKey,
692      (case when S.type==1 then group_concat(S.string_value,',') else group_concat(S.int_value,',')
693      end) as Value
694      from trace_range AS TR,hisys_event_measure as S
695      left join data_dict as D on D.id=S.name_id
696      left join app_name as APP on APP.id=S.key_id
697      left join data_dict as D2 on D2.id=APP.app_key
698      where D.data in ('ANOMALY_SCREEN_OFF_ENERGY','ANOMALY_KERNEL_WAKELOCK',
699      'ANOMALY_CPU_HIGH_FREQUENCY','ANOMALY_WAKEUP')
700     or (D.data in ('ANOMALY_RUNNINGLOCK','ANORMALY_APP_ENERGY','ANOMALY_GNSS_ENERGY',
701     'ANOMALY_CPU_ENERGY','ANOMALY_ALARM_WAKEUP') and D2.data in ("APPNAME"))
702      group by S.serial,D.data`
703  );
704
705export const querySystemLocationData = (): Promise<
706  Array<{
707    ts: string;
708    eventName: string;
709    appKey: string;
710    Value: string;
711  }>
712> =>
713  query(
714    'querySystemLocationData',
715    `SELECT
716        ( S.ts - TR.start_ts ) AS ts,
717        D.data AS eventName,
718        D2.data AS appKey,
719        group_concat( ( CASE WHEN S.type == 1 THEN S.string_value ELSE S.int_value END ), ',' ) AS Value
720        FROM
721        trace_range AS TR,
722        hisys_event_measure AS S
723        LEFT JOIN data_dict AS D ON D.id = S.name_id
724        LEFT JOIN app_name AS APP ON APP.id = S.key_id
725        LEFT JOIN data_dict AS D2 ON D2.id = APP.app_key
726        WHERE
727        D.data = 'GNSS_STATE' AND D2.data = 'STATE'
728        GROUP BY
729        S.serial,
730        APP.app_key,
731        D.data,
732        D2.data;`
733  );
734
735export const querySystemLockData = (): Promise<
736  Array<{
737    ts: string;
738    eventName: string;
739    appKey: string;
740    Value: string;
741  }>
742> =>
743  query(
744    'querySystemLockData',
745    `SELECT
746        ( S.ts - TR.start_ts ) AS ts,
747        D.data AS eventName,
748        D2.data AS appKey,
749        group_concat(( CASE WHEN S.type == 1 THEN S.string_value ELSE S.int_value END ), ',' ) AS Value
750        FROM
751        trace_range AS TR,
752        hisys_event_measure AS S
753        LEFT JOIN data_dict AS D ON D.id = S.name_id
754        LEFT JOIN app_name AS APP ON APP.id = S.key_id
755        LEFT JOIN data_dict AS D2 ON D2.id = APP.app_key
756        WHERE
757        ( D.data = 'POWER_RUNNINGLOCK' AND D2.data in ('TAG','MESSAGE'))
758        GROUP BY
759        S.serial;`
760  );
761
762export const querySystemAllData = (): Promise<
763  Array<{
764    id: number;
765    eventName: string;
766    eventValue: string;
767  }>
768> =>
769  query(
770    'querySystemAllData',
771    `SELECT
772      S.id,
773      D.data AS eventName,
774      contents AS eventValue
775     FROM
776      trace_range AS TR,
777      hisys_all_event AS S
778          LEFT JOIN data_dict AS D ON S.event_name_id = D.id
779          LEFT JOIN data_dict AS D2 ON S.domain_id = D2.id
780     WHERE
781       eventName IN ( 'POWER_RUNNINGLOCK', 'GNSS_STATE', 'WORK_REMOVE', 'WORK_STOP', 'WORK_ADD' );`
782  );
783
784export const querySystemSchedulerData = (): Promise<
785  Array<{
786    startNs: string;
787    eventName: string;
788    appKey: string;
789    Value: string;
790  }>
791> =>
792  query(
793    'querySystemSchedulerData',
794    `SELECT
795      ( S.ts - TR.start_ts ) AS startNs,
796      D.data AS eventName,
797      group_concat(D2.data, ',') AS appKey,
798      group_concat( ( CASE WHEN S.type == 1 THEN S.string_value ELSE S.int_value END ), ',' ) AS Value
799      FROM
800      trace_range AS TR,
801      hisys_event_measure AS S
802      LEFT JOIN data_dict AS D ON D.id = S.name_id
803      LEFT JOIN app_name AS APP ON APP.id = S.key_id
804      LEFT JOIN data_dict AS D2 ON D2.id = APP.app_key
805      WHERE
806      D.data IN ( 'WORK_REMOVE', 'WORK_STOP', 'WORK_ADD' ) AND D2.data in ('NAME','TYPE','WORKID')
807      GROUP BY
808      S.serial;`
809  );
810
811export const querySystemDetailsData = (rightNs: number, eventName: string): Promise<Array<SystemDetailsEnergy>> =>
812  query(
813    'querySystemDetailsData',
814    `SELECT
815        ( S.ts - TR.start_ts ) AS ts,
816        D.data AS eventName,
817        D2.data AS appKey,
818        group_concat( ( CASE WHEN S.type == 1 THEN S.string_value ELSE S.int_value END ), ',' ) AS appValue
819    FROM
820        trace_range AS TR,
821        hisys_event_measure AS S
822        LEFT JOIN data_dict AS D ON D.id = S.name_id
823        LEFT JOIN app_name AS APP ON APP.id = S.key_id
824        LEFT JOIN data_dict AS D2 ON D2.id = APP.app_key
825    WHERE
826        D.data in ($eventName)
827    AND
828        D2.data in ('UID', 'TYPE', 'WORKID', 'NAME', 'INTERVAL', 'TAG', 'STATE', 'STACK', 'APPNAME',
829        'MESSAGE', 'PID', 'LOG_LEVEL')
830    AND
831        (S.ts - TR.start_ts) <= $rightNS
832    GROUP BY
833        S.serial,
834        APP.app_key,
835        D.data,
836        D2.data;`,
837    { $rightNS: rightNs, $eventName: eventName }
838  );
839
840export const querySystemWorkData = (rightNs: number): Promise<Array<SystemDetailsEnergy>> =>
841  query(
842    'querySystemWorkData',
843    `SELECT
844    ( S.ts - TR.start_ts ) AS ts,
845    D.data AS eventName,
846    D2.data AS appKey,
847    group_concat( ( CASE WHEN S.type == 1 THEN S.string_value ELSE S.int_value END ), ',' ) AS appValue
848    FROM
849    trace_range AS TR,
850    hisys_event_measure AS S
851    LEFT JOIN data_dict AS D
852    ON D.id = S.name_id
853    LEFT JOIN app_name AS APP
854    ON APP.id = S.key_id
855    LEFT JOIN data_dict AS D2
856    ON D2.id = APP.app_key
857    WHERE
858    D.data in ("WORK_REMOVE", "WORK_STOP", "WORK_ADD", "WORK_START")
859    and
860    D2.data in ('UID', 'TYPE', 'WORKID', 'NAME', 'INTERVAL', 'TAG', 'STATE', 'STACK', 'APPNAME',
861    'MESSAGE', 'PID', 'LOG_LEVEL')
862    and (S.ts - TR.start_ts) <= $rightNS
863    GROUP BY
864    S.serial,
865    APP.app_key,
866    D.data,
867    D2.data;`,
868    { $rightNS: rightNs }
869  );
870
871export const queryMaxPowerValue = (
872  appName: string
873): Promise<
874  Array<{
875    maxValue: number;
876  }>
877> =>
878  query(
879    'queryMaxPowerValue',
880    `SELECT
881    max( item ) AS maxValue
882    FROM
883    (
884    SELECT
885    sum( energy + background_energy + screen_on_energy + screen_off_energy + foreground_energy ) AS item
886    FROM
887    energy
888    WHERE
889    app_name = $appName
890    GROUP BY
891    startNs);`,
892    { $appName: appName }
893  );
894
895export const queryMaxStateValue = (
896  eventName: string
897): Promise<
898  Array<{
899    type: string;
900    maxValue: number;
901  }>
902> =>
903  query(
904    'queryMaxStateValue',
905    `select
906  D.data as type,
907  max(S.int_value) as maxValue
908  from trace_range AS TR,hisys_event_measure as S
909  left join data_dict as D on D.id=S.name_id
910  left join app_name as APP on APP.id=S.key_id
911  left join data_dict as D2 on D2.id=APP.app_key
912  where (case when 'SENSOR_STATE'==$eventName then D.data like '%SENSOR%' else D.data = $eventName end)
913  and D2.data in ('BRIGHTNESS','STATE','VALUE','LEVEL','VOLUME','OPER_TYPE','VOLUME')
914  group by APP.app_key,D.data,D2.data;`,
915    { $eventName: eventName }
916  );
917
918export const queryStateData = (eventName: string): Promise<Array<EnergyStateStruct>> =>
919  query(
920    'queryStateData',
921    `select
922  (S.ts-TR.start_ts) as startNs,
923  D.data as type,
924  D2.data as appKey,
925  S.int_value as value
926  from trace_range AS TR,hisys_event_measure as S
927  left join data_dict as D on D.id=S.name_id
928  left join app_name as APP on APP.id=S.key_id
929  left join data_dict as D2 on D2.id=APP.app_key
930  where (case when 'SENSOR_STATE'==$eventName then D.data like '%SENSOR%' else D.data = $eventName end)
931  and D2.data in ('BRIGHTNESS','STATE','VALUE','LEVEL','VOLUME','OPER_TYPE','VOLUME')
932  group by S.serial,APP.app_key,D.data,D2.data;`,
933    { $eventName: eventName }
934  );
935
936export const queryEnergyAppName = (): Promise<
937  Array<{
938    string_value: string | null;
939  }>
940> =>
941  query(
942    'queryEnergyAppName',
943    `
944    SELECT
945    DISTINCT hisys_event_measure.string_value from data_dict
946    left join app_name on app_name.app_key=data_dict.id
947    left join hisys_event_measure on hisys_event_measure.key_id = app_name.id
948    where data_dict.data = "APPNAME"`
949  );
950
951export const getTabIoCompletionTimesType = (startTime: number, endTime: number): Promise<Array<string>> =>
952  query(
953    'getTabIoCompletionTimesType',
954    `
955    SELECT tier from bio_latency_sample s,trace_range t
956     WHERE s.start_ts + s.latency_dur >= $startTime + t.start_ts
957     and s.start_ts <= $endTime + t.start_ts group by tier`,
958    { $startTime: startTime, $endTime: endTime }
959  );
960
961export const queryEnergyEventExits = (): //@ts-ignore
962  Promise<Array<unknown>> =>
963  query(
964    'queryEnergyEventExits',
965    `select
966      event_name
967      from stat s
968      where s.event_name = 'trace_hisys_event'
969      and s.stat_type ='received' and s.count > 0`
970  );
971
972export const querySysLockDetailsData = (rightNs: number, eventName: string): Promise<Array<SystemDetailsEnergy>> =>
973  query(
974    'querySysLockDetailsData',
975    `SELECT
976      ( S.ts - TR.start_ts ) AS ts,
977      D.data AS eventName,
978      D2.data AS appKey,
979      group_concat( ( CASE WHEN S.type == 1 THEN S.string_value ELSE S.int_value END ), ',' ) AS appValue
980    FROM
981      trace_range AS TR,
982      hisys_event_measure AS S
983      LEFT JOIN data_dict AS D ON D.id = S.name_id
984      LEFT JOIN app_name AS APP ON APP.id = S.key_id
985      LEFT JOIN data_dict AS D2 ON D2.id = APP.app_key
986    WHERE
987        D.data in ($eventName)
988    AND
989        D2.data in ('UID', 'TYPE', 'WORKID', 'NAME', 'INTERVAL', 'TAG', 'STATE', 'STACK', 'APPNAME',
990        'MESSAGE', 'PID', 'LOG_LEVEL')
991    AND
992        (S.ts - TR.start_ts) <= $rightNS
993    GROUP BY
994        S.serial, APP.app_key, D.data, D2.data;`,
995    { $rightNS: rightNs, $eventName: eventName }
996  );
997
998export const queryStateInitValue = (eventName: string, keyName: string): Promise<Array<EnergyStateStruct>> =>
999  query(
1000    'queryStateInitValue',
1001    `select
1002  0 as startNs,
1003  $eventName as type,
1004  '' as appKey,
1005  (case $keyName
1006  when 'brightness' then device_state.brightness
1007  when 'wifi' then device_state.wifi
1008  when 'bt_state' then device_state.bt_state
1009  when 'location' then device_state.location
1010  else 0 end) as value
1011  from device_state;`,
1012    { $eventName: eventName, $keyName: keyName }
1013  );
1014
1015export const querySysLocationDetailsData = (rightNs: number, eventName: string): Promise<Array<SystemDetailsEnergy>> =>
1016  query(
1017    'querySysLocationDetailsData',
1018    `SELECT
1019        ( S.ts - TR.start_ts ) AS ts,
1020        D.data AS eventName,
1021        D2.data AS appKey,
1022        group_concat( ( CASE WHEN S.type == 1 THEN S.string_value ELSE S.int_value END ), ',' ) AS appValue
1023        FROM
1024        trace_range AS TR,
1025        hisys_event_measure AS S
1026        LEFT JOIN data_dict AS D ON D.id = S.name_id
1027        LEFT JOIN app_name AS APP ON APP.id = S.key_id
1028        LEFT JOIN data_dict AS D2 ON D2.id = APP.app_key
1029        WHERE
1030        D.data in ($eventName)
1031        and
1032        D2.data in ('UID', 'TYPE', 'WORKID', 'NAME', 'INTERVAL', 'TAG', 'STATE', 'STACK',
1033        'APPNAME', 'MESSAGE', 'PID', 'LOG_LEVEL')
1034        and (S.ts - TR.start_ts) <= $rightNS
1035        GROUP BY
1036        S.serial,
1037        APP.app_key,
1038        D.data,
1039        D2.data;`,
1040    { $rightNS: rightNs, $eventName: eventName }
1041  );
1042export const queryConfigEnergyAppName = (): Promise<
1043  Array<{
1044    process_name: string;
1045  }>
1046> =>
1047  query(
1048    'queryConfigEnergyAppName',
1049    `
1050    SELECT value from trace_config where trace_source = 'hisys_event' and key = 'process_name'`
1051  );
1052
1053export const queryAllExpectedData = (): //@ts-ignore
1054  Promise<Array<unknown>> =>
1055  query(
1056    'queryAllExpectedData',
1057    `
1058        SELECT
1059            a.id,
1060            (a.ts - TR.start_ts) AS ts,
1061            a.vsync as name,
1062            a.type,
1063            a.dur,
1064            p.pid,
1065            p.name as cmdline
1066        FROM frame_slice AS a, trace_range AS TR
1067             LEFT JOIN process AS p ON a.ipid = p.ipid
1068        WHERE a.type = 1
1069          and (a.flag <> 2 or a.flag is null)
1070        ORDER BY a.ipid,ts;`
1071  );
1072
1073export const queryFlowsData = (
1074  src_slice: Array<string>
1075): //@ts-ignore
1076  Promise<Array<unknown>> =>
1077  query(
1078    'queryFlowsData',
1079    `SELECT CASE WHEN p.pid != t.tid THEN fs.vsync || '-' || T.tid ELSE fs.vsync END AS name,
1080        p.pid,
1081        p.name  AS cmdline,
1082        fs.type
1083    FROM frame_slice AS fs
1084    LEFT JOIN process AS p ON fs.ipid = p.ipid
1085    LEFT JOIN thread as t ON fs.itid = t.id
1086    WHERE fs.type = 0
1087        AND fs.id IN (${src_slice.join(',')});`
1088  );
1089
1090export const queryPrecedingData = (
1091  dst_slice: string
1092): //@ts-ignore
1093  Promise<Array<unknown>> =>
1094  query(
1095    'queryFlowsData',
1096    `
1097        SELECT a.vsync AS name,
1098               p.pid,
1099               p.name  AS cmdline,
1100               a.type
1101        FROM frame_slice AS a
1102                 LEFT JOIN process AS p ON a.ipid = p.ipid
1103        WHERE a.type = 0
1104          AND a.id = $dst_slice;`,
1105    { $dst_slice: dst_slice }
1106  );
1107
1108export const queryFrameTimeData = (): //@ts-ignore
1109  Promise<Array<unknown>> =>
1110  query(
1111    'queryFrameTimeData',
1112    `
1113        SELECT DISTINCT p.pid
1114        FROM frame_slice AS a
1115            LEFT JOIN process AS p
1116            ON a.ipid = p.ipid
1117        WHERE vsync IS NOT NULL;`
1118  );
1119
1120export const queryAllSnapshotNames = (): Promise<Array<FileInfo>> =>
1121  query(
1122    'queryAllSnapshotNames',
1123    `SELECT f.id,
1124        f.file_name AS name
1125      FROM
1126        js_heap_files f,
1127        trace_range t
1128      WHERE
1129        ( t.end_ts >= f.end_time AND f.file_name != 'Timeline' )
1130        OR f.file_name = 'Timeline'`
1131  );
1132export const queryHeapFile = (): Promise<Array<FileInfo>> =>
1133  query(
1134    'queryHeapFile',
1135    `SELECT f.id,
1136        f.file_name AS name,
1137        f.start_time - t.start_ts AS startTs,
1138        f.end_time - t.start_ts AS endTs,
1139        f.self_size AS size,
1140        c.pid
1141      FROM
1142        js_heap_files f,
1143        trace_range t,
1144        js_config c
1145      WHERE
1146        ( t.end_ts >= f.end_time AND f.file_name != 'Timeline' )
1147        OR f.file_name = 'Timeline'`
1148  );
1149
1150export const queryHeapInfo = (
1151  fileId: number
1152): //@ts-ignore
1153  Promise<Array<unknown>> =>
1154  query(
1155    'queryHeapInfo',
1156    `SELECT file_id as fileId, key, type, int_value as intValue, str_value as strValue
1157      FROM js_heap_info WHERE file_id = ${fileId}`
1158  );
1159
1160export const queryHeapNode = (fileId: number): Promise<Array<HeapNode>> =>
1161  query(
1162    'queryHeapNode',
1163    `SELECT
1164    node_index as nodeIndex,
1165    type,
1166    name as nameIdx,
1167    id,
1168    self_size as selfSize,
1169    edge_count as edgeCount,
1170    trace_node_id as traceNodeId,
1171    detachedness
1172    FROM js_heap_nodes WHERE file_id = ${fileId}`
1173  );
1174
1175export const queryHeapEdge = (fileId: number): Promise<Array<HeapEdge>> =>
1176  query(
1177    'queryHeapEdge',
1178    `SELECT
1179      edge_index as edgeIndex,
1180      type,
1181      name_or_index as nameOrIndex,
1182      to_node as nodeId,
1183      from_node_id as fromNodeId,
1184      to_node_id as toNodeId
1185    FROM js_heap_edges WHERE file_id = ${fileId}`
1186  );
1187export const queryHeapSample = (fileId: number): Promise<Array<HeapSample>> =>
1188  query(
1189    'queryHeapSample',
1190    `SELECT timestamp_us as timestamp , last_assigned_id as lastAssignedId, 0 as size
1191      FROM js_heap_sample WHERE file_id = ${fileId}`
1192  );
1193
1194export const queryHeapLocation = (fileId: number): Promise<Array<HeapLocation>> =>
1195  query(
1196    'queryHeapLocation',
1197    `SELECT object_index as objectIndex,script_id as scriptId ,column
1198      FROM js_heap_location WHERE file_id = ${fileId}`
1199  );
1200
1201export const queryHeapString = (
1202  fileId: number
1203): //@ts-ignore
1204  Promise<Array<unknown>> =>
1205  query(
1206    'queryHeapString',
1207    `SELECT string
1208      FROM js_heap_string WHERE file_id = ${fileId}`
1209  );
1210export const queryTraceRange = (): Promise<Array<unknown>> =>
1211  query(
1212    'queryTraceRange',
1213    `SELECT
1214    t.start_ts as startTs,
1215    t.end_ts as endTs
1216    FROM trace_range t`
1217  );
1218
1219export const queryBySelectAllocationOrReturn = (
1220  executeId: string,
1221  itid: number
1222): Promise<
1223  Array<{
1224    tid: number;
1225    allocation_task_row: number;
1226    execute_task_row: number;
1227    return_task_row: number;
1228    priority: number;
1229  }>
1230> => {
1231  let sqlStr = `SELECT thread.tid,
1232                       task_pool.allocation_task_row,
1233                       task_pool.execute_task_row,
1234                       task_pool.return_task_row,
1235                       task_pool.priority
1236                FROM task_pool
1237                       LEFT JOIN callstack ON callstack.id = task_pool.execute_task_row
1238                       LEFT JOIN thread ON thread.id = callstack.callid
1239                WHERE task_pool.execute_task_row IS NOT NULL AND task_pool.task_id = $executeId
1240                AND task_pool.allocation_itid = $itid;
1241    `;
1242  return query('queryBySelectAllocationOrReturn', sqlStr, { $executeId: executeId, $itid: itid });
1243};
1244
1245export const queryTaskListByExecuteTaskIds = (
1246  executeTaskIds: Array<number>,
1247  ipid: number
1248): Promise<Array<TaskTabStruct>> => {
1249  let sqlStr = `
1250    SELECT thread.ipid,
1251           task_pool.allocation_task_row AS allocationTaskRow,
1252           task_pool.execute_task_row    AS executeTaskRow,
1253           task_pool.return_task_row     AS returnTaskRow,
1254           task_pool.task_id          AS executeId,
1255           task_pool.priority
1256    FROM task_pool
1257           LEFT JOIN callstack ON callstack.id = task_pool.allocation_task_row
1258           LEFT JOIN thread ON thread.id = callstack.callid
1259    WHERE task_pool.task_id IN (${executeTaskIds.join(',')})
1260      AND thread.ipid = $ipid
1261      AND task_pool.execute_task_row IS NOT NULL;
1262    `;
1263  return query('queryTaskListByExecuteTaskIds', sqlStr, { $executeTaskIds: executeTaskIds, $ipid: ipid });
1264};
1265
1266export const queryTaskPoolCallStack = (): Promise<Array<{ id: number; ts: number; dur: number; name: string }>> => {
1267  let sqlStr = `
1268  select
1269    *
1270  from callstack where name like 'H:Task%';`;
1271  return query('queryTaskPoolCallStack', sqlStr, {});
1272};
1273
1274export const queryTaskPoolTotalNum = (itid: number): Promise<number[]> =>
1275  query<number>(
1276    'queryTaskPoolTotalNum',
1277    `SELECT thread.tid
1278         FROM thread
1279                LEFT JOIN callstack ON thread.id = callstack.callid
1280         WHERE ipid in (SELECT thread.ipid
1281                       FROM thread
1282                       WHERE thread.itid = $itid)
1283           AND thread.name LIKE '%TaskWork%'
1284         GROUP BY thread.tid;`,
1285    { $itid: itid }
1286  );
1287
1288export const queryFrameAnimationData = (): Promise<Array<FrameAnimationStruct>> =>
1289  query(
1290    'queryFrameAnimationData',
1291    `SELECT a.id AS animationId,
1292           'Response delay' as status,
1293           (CASE WHEN a.input_time NOT NULL
1294               THEN ( a.input_time - R.start_ts )
1295               ELSE ( a.start_point - R.start_ts ) END
1296           ) AS startTs,
1297           (a.start_point - R.start_ts) AS endTs,
1298           0 AS frameInfo,
1299           a.name AS name
1300         FROM
1301             animation AS a,
1302             trace_range AS R
1303         UNION
1304         SELECT a.id AS animationId,
1305           'Completion delay' as status,
1306           (CASE WHEN a.input_time NOT NULL
1307               THEN ( a.input_time - R.start_ts )
1308               ELSE ( a.start_point - R.start_ts ) END
1309           ) AS startTs,
1310           (a.end_point - R.start_ts) AS endTs,
1311           a.frame_info AS frameInfo,
1312           a.name AS name
1313         FROM
1314             animation AS a,
1315             trace_range AS R
1316         ORDER BY
1317            endTs;`
1318  );
1319
1320export const queryAnimationTimeRangeData = (): Promise<Array<FrameAnimationStruct>> =>
1321  query(
1322    'queryAnimationTimeRangeData',
1323    `SELECT 'Response delay' as status,
1324           (CASE WHEN a.input_time NOT NULL
1325               THEN ( a.input_time - R.start_ts )
1326               ELSE ( a.start_point - R.start_ts ) END
1327           ) AS startTs,
1328            (a.start_point - R.start_ts) AS endTs
1329         FROM
1330             animation AS a,
1331             trace_range AS R
1332         UNION
1333         SELECT 'Completion delay' as status,
1334           (CASE WHEN a.input_time NOT NULL
1335               THEN ( a.input_time - R.start_ts )
1336               ELSE ( a.start_point - R.start_ts ) END
1337           ) AS startTs,
1338           (a.end_point - R.start_ts) AS endTs
1339         FROM
1340             animation AS a,
1341             trace_range AS R
1342         ORDER BY
1343            endTs;`
1344  );
1345export const querySourceTypen = (): Promise<Array<unknown>> =>
1346  query(
1347    'querySourceTypen',
1348    `SELECT
1349      value
1350    FROM
1351      meta
1352    where
1353      name = 'source_type'
1354    `
1355  );
1356
1357export const queryFrameDynamicData = (): Promise<FrameDynamicStruct[]> =>
1358  query(
1359    'queryFrameDynamicData',
1360    `SELECT d.id,
1361           d.x,
1362           d.y,
1363           d.width,
1364           d.height,
1365           d.alpha,
1366           d.name AS appName,
1367           (d.end_time - R.start_ts) AS ts
1368        FROM
1369            dynamic_frame AS d,
1370            trace_range AS R
1371        ORDER BY
1372            d.end_time;`
1373  );
1374
1375export const queryDynamicIdAndNameData = (): Promise<Array<{ id: number; appName: string }>> =>
1376  query('queryDynamicIdAndNameData', 'SELECT id, name AS appName FROM dynamic_frame;');
1377
1378export const queryAnimationIdAndNameData = (): Promise<
1379  Array<{
1380    id: number;
1381    name: string;
1382    info: string;
1383  }>
1384> => query('queryAnimationIdAndNameData', 'SELECT id, name, frame_info as info FROM animation;');
1385
1386export const queryFrameApp = (): Promise<
1387  Array<{
1388    name: string;
1389  }>
1390> =>
1391  query(
1392    'queryFrameApp',
1393    `SELECT
1394            DISTINCT d.name
1395         FROM
1396             dynamic_frame AS d,
1397             trace_range AS R
1398         WHERE
1399            d.end_time >= R.start_ts
1400            AND
1401            d.end_time <= R.end_ts;`
1402  );
1403
1404export const queryFrameSpacing = (): Promise<Array<FrameSpacingStruct>> =>
1405  query(
1406    'queryFrameSpacing',
1407    `SELECT d.id,
1408         d.width AS currentFrameWidth,
1409         d.height AS currentFrameHeight,
1410         d.name AS nameId,
1411         (d.end_time - R.start_ts) AS currentTs,
1412         d.x,
1413         d.y
1414     FROM
1415         dynamic_frame AS d,
1416         trace_range AS R
1417     ORDER BY
1418         d.end_time;`
1419  );
1420
1421export const queryPhysicalData = (): Promise<Array<DeviceStruct>> =>
1422  query(
1423    'queryPhysicalData',
1424    `SELECT physical_width AS physicalWidth,
1425            physical_height AS physicalHeight,
1426            physical_frame_rate AS physicalFrameRate
1427     FROM device_info;`
1428  );
1429export const getSystemLogsData = (): Promise<
1430  Array<{
1431    id: number;
1432    ts: number;
1433    processName: string;
1434    tid: number;
1435    level: string;
1436    tag: string;
1437    message: string;
1438    des: number;
1439  }>
1440> =>
1441  query(
1442    'getSystemLogsData',
1443    `SELECT ROW_NUMBER() OVER (ORDER BY l.ts) AS processName,
1444            l.seq AS id,
1445            (l.ts - TR.start_ts) AS ts,
1446            l.pid AS indexs,
1447            l.tid,
1448            l.level,
1449            l.tag,
1450            l.context AS message,
1451            l.origints AS des
1452         FROM trace_range AS TR,
1453              log AS l
1454         ORDER BY ts`
1455  );
1456
1457export const queryLogData = (): Promise<Array<LogStruct>> =>
1458  query(
1459    'queryLogData',
1460    `SELECT
1461    l.ts - tr.start_ts as startNs
1462    FROM log AS l, trace_range tr WHERE startNs > 0 LIMIT 1;`
1463  );
1464
1465export const queryMetric = (metricName: string): Promise<Array<string>> =>
1466  query('queryMetric', metricName, '', { action: 'exec-metric' });
1467
1468export const queryExistFtrace = (): Promise<Array<number>> =>
1469  query(
1470    'queryExistFtrace',
1471    `select 1 from thread_state
1472         UNION
1473         select 1 from args;`
1474  );
1475
1476export const queryTraceType = (): Promise<
1477  Array<{
1478    value: string;
1479  }>
1480> =>
1481  query(
1482    'queryTraceType',
1483    `SELECT m.value
1484            FROM
1485                meta AS m
1486            WHERE
1487                m.name = 'source_type';`
1488  );
1489
1490export const queryLogAllData = (oneDayTime: number, leftNs: number, rightNs: number): Promise<Array<LogStruct>> =>
1491  query(
1492    'queryLogAllData',
1493    `SELECT l.seq AS id,
1494         CASE
1495             WHEN l.ts < ${oneDayTime} THEN 0
1496             ELSE (l.ts - TR.start_ts)
1497             END AS startTs,
1498         CASE l.level
1499             WHEN 'D' THEN 'Debug'
1500             WHEN 'I' THEN 'Info'
1501             WHEN 'W' THEN 'Warn'
1502             WHEN 'E' THEN 'Error'
1503             WHEN 'F' THEN 'Fatal'
1504             END AS level,
1505         l.tag AS tag,
1506         l.context AS context,
1507         (strftime( '%m-%d %H:%M:%S', l.origints / 1000000000, 'unixepoch', 'localtime' ) ||
1508         '.' || printf('%03d', (l.origints / 1000000) % 1000)) AS originTime,
1509         COALESCE(p.name, 'Process ' || l.pid) AS processName
1510     FROM
1511         log AS l
1512             LEFT JOIN trace_range AS TR ON l.ts >= TR.start_ts
1513             LEFT JOIN process AS p ON p.pid = l.pid
1514     WHERE
1515         startTs >= ${Math.floor(leftNs)}
1516       AND startTs <= ${Math.floor(rightNs)}
1517     ORDER BY
1518         l.ts;`,
1519    { $oneDayTime: oneDayTime }
1520  );
1521
1522export const queryFpsSourceList = (
1523  inputTime: number,
1524  endTime: number,
1525  name: string
1526): Promise<
1527  Array<{
1528    name: string;
1529    ts: number;
1530    dur: number;
1531    pid: number;
1532    tid: number;
1533    depth: number;
1534  }>
1535> =>
1536  query(
1537    'queryFpsSourceList',
1538    `SELECT t.tid,
1539        c.dur,
1540        c.depth,
1541        c.ts,
1542        c.name
1543      FROM
1544        callstack c
1545      INNER JOIN thread t ON c.callid = t.itid
1546      WHERE
1547        c.name LIKE '%${name}%'
1548        AND
1549        c.ts BETWEEN ${inputTime} and ${endTime}
1550        AND
1551        t.name = 'render_service';`
1552  );
1553
1554export const queryStateFreqList = (
1555  startTime: number,
1556  endTime: number,
1557  cpu: number
1558): //@ts-ignore
1559  Promise<Array<unknown>> => {
1560  let sql = `select c.value,
1561    c.ts,
1562    c.dur,
1563    c.ts - r.start_ts AS startTime,
1564    c.ts - r.start_ts + c.dur AS endTime
1565   from
1566     measure c, trace_range r
1567   inner join
1568     cpu_measure_filter t
1569   on
1570     c.filter_id = t.id
1571   where
1572     (name = 'cpufreq' or name='cpu_frequency')
1573     and
1574     t.cpu = $cpu
1575     and
1576     (((startTime < $startTime) and  (endtime > $endTime))
1577      or ((startTime < $startTime) and ($startTime < endtime and endtime < $endTime))
1578      or ((startTime > $startTime) and ( $startTime < endtime and endtime < $endTime))
1579      or ((startTime > $startTime and startTime < $endTime) and (endtime > $endTime)))`;
1580  return query('queryBinderByArgsId', sql, {
1581    $endTime: endTime,
1582    $startTime: startTime,
1583    $cpu: cpu,
1584  });
1585};
1586export const queryPerfOutputData = (): Promise<Array<unknown>> =>
1587  query(
1588    'queryPerfOutputData',
1589    `SELECT
1590    name,
1591    ts
1592    FROM callstack where name like '%PERFORMANCE_DATA%'`
1593  );
1594
1595export const queryPerfToolsDur = (): Promise<Array<unknown>> =>
1596  query(
1597    'queryPerfToolsDur',
1598    `SELECT
1599    name,
1600    ts,
1601    dur
1602    FROM callstack where name = 'H:GRAB'`
1603  );
1604
1605export const queryCallstackDetail = (): Promise<Array<FuncStruct>> =>
1606    query(
1607        'queryCallstackDetail',
1608        `SELECT
1609    id,
1610    trace_level,
1611    trace_tag,
1612    custom_category as category,
1613    custom_args
1614    FROM callstack, trace_range AS TR
1615    where (trace_level is not null or
1616           trace_tag is not null or
1617           custom_args is not null or
1618           custom_category is not null)
1619      and ts - TR.start_ts >= 0
1620      and TR.end_ts - ts >=0;`
1621    );
1622