프로젝트

일반

사용자정보

통계
| 개정판:

hytos / HYTOS / HYTOS / AppDocData.py @ b2ff26e4

이력 | 보기 | 이력해설 | 다운로드 (77.9 KB)

1
# coding: utf-8
2
""" This is document data(SDI) class """
3

    
4
import sys
5
import os
6
import sqlite3
7
import datetime
8
from enum import Enum
9
from typing import List
10
try:
11
    from PyQt5.QtCore import *
12
    from PyQt5.QtGui import *
13
    from PyQt5 import QtWidgets
14
except ImportError:
15
    from PyQt4.QtCore import *
16
    from PyQt4.QtGui import *
17

    
18
from App import App
19
from SingletonInstance import SingletonInstane
20
import symbol
21
from NominalPipeSize import NominalPipeSize
22

    
23

    
24
class Config:
25
    def __init__(self, section, key, value):
26
        self.section = section
27
        self.key = key
28
        self.value = value
29

    
30

    
31
'''
32
    @brief      MessageType
33
    @author     humkyung 
34
    @date       2018.07.31
35
'''
36

    
37

    
38
class MessageType(Enum):
39
    Normal = 1
40
    Error = 2
41
    Information = 3
42

    
43
class Inst_Item:
44
    def __init__(self, itemNo, type, dataSource):
45
        self.itemNo = itemNo
46
        self.type = type
47
        self.dataSource = dataSource
48
        self.attributes = []
49

    
50
    def printf(self):
51
        print(f"""itemNo = {self.itemNo}, type ={self.type}, dataSource = {self.dataSource}""")
52
        for attr in self.attributes:
53
            print(f"""{attr.table}.{attr.column} : {attr.value} """)
54
        print(f"""***********************************************************************""")
55

    
56
    def json(self):
57
        values = [con.json() for con in self.attributes]
58
        dics = {
59
                 'itemNo': self.itemNo,
60
                 'type': self.type,
61
                 'dataSource': self.dataSource,
62
                 'values': values
63
               }
64
        return dics
65

    
66
class Inst_Attribute:
67
    def __init__(self, table, column, value):
68
        self.table = table
69
        self.column = column
70
        if value is None:
71
            value = ''
72
        self.value = value
73

    
74
    def json(self):
75
        return {'table': self.table, 'column': self.column, 'value': self.value}
76

    
77
class PAPUploadInformation:
78
    def __init__(self,param_project_uid = '',
79
                      param_projectno = '',
80
                      param_calculationcase = ''):
81
        self.Project_UID = param_project_uid
82
        self.ProjectNo = param_projectno
83
        self.CalculationCase = param_calculationcase
84

    
85
    def to_sql(self) -> str:
86
        return f"""insert or replace into PAPUploadInformation( 
87
                    Project_UID, 
88
                    ProjectNo, 
89
                    CalculationCase)
90
                    values(
91
                    '{self.Project_UID}',
92
                    '{self.ProjectNo}',
93
                    '{self.CalculationCase}'
94
                    )"""
95

    
96
class PAPUploadInformationItem:
97
    def __init__(self, param_project_uid = '',
98
                       param_projectno = '',
99
                       param_components_uid = '',
100
                       param_components_type = '',
101
                       param_components_itemno = '',
102
                       param_components_datacase = ''):
103
        self.Project_UID = param_project_uid
104
        self.ProjectNo = param_projectno
105
        self.Components_UID = param_components_uid
106
        self.Components_Type = param_components_type
107
        self.Components_ItemNo = param_components_itemno
108
        self.Components_DataCase = param_components_datacase
109

    
110
    def to_sql(self) -> str:
111
        return f"""insert or replace into PAPUploadInformationItem( 
112
                     Project_UID,
113
                     ProjectNo,
114
                     Components_UID, 
115
                     Components_Type, 
116
                     Components_ItemNo, 
117
                     Components_DataCase)
118
        values(
119
                '{self.Project_UID}',
120
                '{self.ProjectNo}',
121
                '{self.Components_UID}',
122
                '{self.Components_Type}',
123
                '{self.Components_ItemNo}',
124
                '{self.Components_DataCase}')"""
125

    
126
class AppDocData(SingletonInstane):
127

    
128
    def __init__(self):
129

    
130
        self._imgFilePath = None
131
        self.imgName = None
132

    
133
        self.outputs = []  # store calculation outputs
134
        self.equipments = []
135
        self.lineNos = []
136
        self.lines = []
137
        self.texts = []
138
        self.symbols = []
139
        self.unknowns = []
140
        self.tracerLineNos = []
141
        self.lineIndicators = []
142
        self._colors = None
143
        self._lineNoProperties = None
144
        self._lineTypes = None
145
        self._lineTypeConfigs = None
146
        self._activeDrawing = None
147
        self._titleBlockProperties = None
148
        self.needReOpening = None
149
        self.configTable = None
150
        #self.API_HOST = "https://papwebapi.azurewebsites.net"
151
        #self.API_HOST = "http://localhost:53443"
152
        #self.API_HOST = "http://localhost:8080"
153
        self.API_HOST = "http://66.11.11.147:3001"
154

    
155

    
156
    def clearItemList(self, trim):
157
        '''
158
            @brief      clear item list
159
            @author     euisung
160
            @date       2018.11.28
161
        '''
162
        self.equipments.clear()
163
        self.symbols.clear()
164
        self.lineNos.clear()
165
        self.texts.clear()
166
        self.lines.clear()
167
        self.unknowns.clear()
168
        self.lineIndicators.clear()
169
        if trim:
170
            self.tracerLineNos.clear()
171

    
172
    '''
173
        @brief      clear
174
        @author     humkyung
175
        @date       2018.09.06
176
    '''
177

    
178
    def clear(self):
179
        self._imgFilePath = None
180
        self.imgName = None
181

    
182
        self.equipments.clear()
183
        self.lineNos.clear()
184
        self.lines.clear()
185
        self.texts.clear()
186
        self.symbols.clear()
187
        self.unknowns.clear()
188
        self.tracerLineNos.clear()
189
        self.lineIndicators.clear()
190
        self._colors = None
191
        self._lineNoProperties = None
192
        self._lineTypeConfigs = None
193
        self._activeDrawing = None
194
        self._titleBlockProperties = None
195

    
196
    '''
197
        @brief      Get DB file path in ProgramData
198
        @author     Jeongwoo
199
        @date       2018.06.27
200
        @history    2018.06.29  Jeongwoo    Change method to get template db path
201
    '''
202

    
203
    def getTemplateDbPath(self):
204
        path = App.COMMON_APP_DATA_FOLDER
205
        templateDbPath = os.path.join(path, 'Template.db')
206
        return templateDbPath
207

    
208
    def getTemplateSymbolCategoryList(self):
209
        symbolCategoryList = []
210

    
211
        conn = sqlite3.connect(self.getTemplateDbPath())
212
        with conn:
213
            cursor = conn.cursor()
214
            sql = 'SELECT distinct category FROM SymbolType ORDER BY Category'
215
            try:
216
                cursor.execute(sql)
217
                rows = cursor.fetchall()
218
                for row in rows:
219
                    symbolCategoryList.append((row[0]))
220
            except Exception as ex:
221
                from App import App
222
                message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
223
                                                               sys.exc_info()[-1].tb_lineno)
224
                App.mainWnd().addMessage.emit(MessageType.Error, message)
225

    
226
        return symbolCategoryList
227

    
228
    def getTemplateSymbolTypeList(self, category):
229
        symbolCategoryList = []
230

    
231
        conn = sqlite3.connect(self.getTemplateDbPath())
232
        with conn:
233
            cursor = conn.cursor()
234
            sql = 'SELECT UID, Type FROM SymbolType Where Category = ? ORDER BY Type'
235

    
236
            try:
237
                param = (category,)
238
                cursor.execute(sql, param)
239
                rows = cursor.fetchall()
240
                for row in rows:
241
                    symbolCategoryList.append((row[0], row[1]))
242
            except Exception as ex:
243
                from App import App
244
                message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
245
                                                               sys.exc_info()[-1].tb_lineno)
246
                App.mainWnd().addMessage.emit(MessageType.Error, message)
247

    
248
        return symbolCategoryList
249

    
250
    def updateTemplateSymbol(self, uid, originalPoint, connectionPoint):
251
        isUpdated = False
252

    
253
        try:
254
            conn = sqlite3.connect(self.getTemplateDbPath())
255
            conn.execute('PRAGMA foreign_keys = ON')
256
            # Get a cursor object
257
            cursor = conn.cursor()
258

    
259
            sql = """Update Symbols
260
                        set OriginalPoint = ?
261
                          , ConnectionPoint = ?
262
                      where UID = ?"""
263

    
264
            param = (originalPoint, connectionPoint, uid)
265
            cursor.execute(sql, param)
266
            conn.commit()
267
            isUpdated = True
268
        # Catch the exception
269
        except Exception as ex:
270
            from App import App
271
            # Roll back any change if something goes wrong
272
            conn.rollback()
273

    
274
            message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
275
                                                           sys.exc_info()[-1].tb_lineno)
276
            App.mainWnd().addMessage.emit(MessageType.Error, message)
277
        finally:
278
            # Close the db connection
279
            conn.close()
280
            return isUpdated
281

    
282
    def getTemplateSymbol(self, UID):
283
        symbolList = []
284

    
285
        conn = sqlite3.connect(self.getTemplateDbPath())
286
        with conn:
287
            cursor = conn.cursor()
288
            sql = 'SELECT UID, Name, OriginalPoint, ConnectionPoint FROM Symbols Where UID = ? ORDER BY Name'
289

    
290
            try:
291
                param = (UID,)
292
                cursor.execute(sql, param)
293
                rows = cursor.fetchall()
294
                for row in rows:
295
                    symbolList.append((row[0], row[1], row[2], row[3]))
296
            except Exception as ex:
297
                from App import App
298
                message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
299
                                                               sys.exc_info()[-1].tb_lineno)
300
                App.mainWnd().addMessage.emit(MessageType.Error, message)
301

    
302
        return symbolList
303

    
304
    def getTemplateSymbolNameList(self, typeUID):
305
        symbolCategoryList = []
306

    
307
        conn = sqlite3.connect(self.getTemplateDbPath())
308
        with conn:
309
            cursor = conn.cursor()
310
            sql = 'SELECT UID, Name FROM Symbols Where SymbolType_UID = ? ORDER BY Name'
311

    
312
            try:
313
                param = (typeUID,)
314
                cursor.execute(sql, param)
315
                rows = cursor.fetchall()
316
                for row in rows:
317
                    symbolCategoryList.append((row[0], row[1]))
318
            except Exception as ex:
319
                from App import App
320
                message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
321
                                                               sys.exc_info()[-1].tb_lineno)
322
                App.mainWnd().addMessage.emit(MessageType.Error, message)
323

    
324
        return symbolCategoryList
325

    
326
    def getAppDbPath(self):
327
        """
328
        @brief      Get application DB file path in ProgramData
329
        @author     humkyung
330
        @date       2018.10.01
331
        """
332

    
333
        path = App.LOCAL_APP_DATA_FOLDER
334
        app_database = os.path.join(path, 'App.db')
335
        return app_database
336

    
337
    '''
338
        @brief  build application database
339
        @author humkyung
340
        @date   2018.04.20
341
    '''
342

    
343
    def buildAppDatabase(self):
344
        from App import App
345

    
346
        try:
347
            path = App.LOCAL_APP_DATA_FOLDER
348
            appDatabaseFilePath = os.path.join(path, 'App.db')
349

    
350
            # Creates or opens a file called mydb with a SQLite3 DB
351
            with sqlite3.connect(appDatabaseFilePath) as conn:
352
                conn.execute('PRAGMA foreign_keys = ON')
353
                # Get a cursor object
354
                cursor = conn.cursor()
355

    
356
                sqlFiles = ['App.sql']
357
                for sqlFile in sqlFiles:
358
                    filePath = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'Scripts', sqlFile)
359
                    try:
360
                        file = QFile(filePath)
361
                        file.open(QFile.ReadOnly)
362
                        sql = file.readAll()
363
                        sql = str(sql, encoding='utf8')
364
                        cursor.executescript(sql)
365
                    finally:
366
                        file.close()
367
                conn.commit()
368
        # Catch the exception
369
        except Exception as ex:
370
            from App import App
371
            # Roll back any change if something goes wrong
372
            conn.rollback()
373

    
374
            message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
375
                                                           sys.exc_info()[-1].tb_lineno)
376
            App.mainWnd().addMessage.emit(MessageType.Error, message)
377

    
378
    def build_drawing_database(self, drawing) -> bool:
379
        """build database for given drawing"""
380
        try:
381
            from App import App
382
            from packaging import version
383
            import re
384

    
385
            sqlFiles = ['update_database.sql']
386
            string_main_version = QCoreApplication.applicationVersion()
387
            app_version = version.parse(string_main_version)
388
            with sqlite3.connect(drawing) as conn:
389
                conn.execute('PRAGMA foreign_keys = ON')
390
                # Get a cursor object
391
                cursor = conn.cursor()
392

    
393
                filelist = os.listdir(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'Scripts'))
394
                file_list = list()
395
                docver_list = list()
396

    
397
                file_list = re.findall('DocVer_(\d+[.]\d+[.]\d+[.]\d+)[.]sql', "".join(filelist))
398

    
399
                for ver in file_list:
400
                    docver_list.append(version.parse(ver))
401
                docver_list.sort()
402

    
403
                configs = self.getConfigs('Version', 'Doc_Ver')
404
                doc_version = version.parse('0.0.0.0')
405
                if configs:
406
                    doc_version = version.parse(configs[0].value)
407

    
408
                if app_version > doc_version:
409
                    for i in docver_list:
410
                        if app_version >= i > doc_version:
411
                            sqlFiles.append(f'DocVer_{i}.sql')
412
                    cursor.execute(
413
                        f"insert or replace into Configuration values ('Version', 'Doc_Ver', '{string_main_version}');")
414
                elif app_version < doc_version:
415
                    return False
416
                else:
417
                    pass
418

    
419
                for sqlFile in sqlFiles:
420
                    filePath = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'Scripts', sqlFile)
421
                    try:
422
                        file = QFile(filePath)
423
                        file.open(QFile.ReadOnly)
424
                        sql = file.readAll()
425
                        sql = str(sql, encoding='utf8')
426
                        cursor.executescript(sql)
427
                    finally:
428
                        file.close()
429

    
430
                conn.commit()
431

    
432
            return True
433
        # Catch the exception
434
        except Exception as ex:
435
            from App import App
436
            # Roll back any change if something goes wrong
437
            conn.rollback()
438

    
439
            message = f'error occurred({repr(ex)}) in {sys.exc_info()[-1].tb_frame.f_code.co_filename}:' \
440
                      f'{sys.exc_info()[-1].tb_lineno}'
441
            App.mainWnd().addMessage.emit(MessageType.Error, message)
442

    
443
    '''
444
        @brief  load app style
445
        @author humkyung
446
        @date   2018.04.20
447
    '''
448

    
449
    def loadAppStyle(self):
450
        style = 'Fusion'
451
        self.buildAppDatabase()
452

    
453
        return style
454

    
455
    @property
456
    def border_file_path(self):
457
        """ return border file path """
458

    
459
        path = App.COMMON_APP_DATA_FOLDER
460
        return os.path.join(path, 'Border.png')
461

    
462
    @property
463
    def symbol_file_path(self):
464
        """ return svg symbol file path """
465

    
466
        path = App.COMMON_APP_DATA_FOLDER
467
        return os.path.join(path, 'svg')
468

    
469
    def update_symbol_shape(self, drawing, symbol, svg_file):
470
        """update symbol shape"""
471

    
472
        conn = sqlite3.connect(drawing)
473
        conn.execute('PRAGMA foreign_keys = ON')
474
        with conn:
475
            try:
476
                conn.row_factory = sqlite3.Row
477
                # Get a cursor object
478
                cursor = conn.cursor()
479

    
480
                sql = f"update Symbols set Shape = ? where UID='{symbol}'"
481

    
482
                blob_data = None
483
                with open(svg_file, 'rb') as file:
484
                    blob_data = file.read()
485

    
486
                # Convert data into tuple format
487
                params = (blob_data,)
488
                cursor.execute(sql, params)
489
                conn.commit()
490

    
491
            # Catch the exception
492
            except Exception as ex:
493
                from App import App
494
                # Roll back any change if something goes wrong
495
                conn.rollback()
496

    
497
                message = 'error occurred({}) in {}:{}'.format(repr(ex), sys.exc_info()[-1].tb_frame.f_code.co_filename,
498
                                                               sys.exc_info()[-1].tb_lineno)
499
                App.mainWnd().addMessage.emit(MessageType.Error, message)
500

    
501
    def read_symbol_shape(self, drawing, symbol):
502
        """read symbol shape"""
503

    
504
        res = None
505

    
506
        with sqlite3.connect(drawing) as conn:
507
            conn.execute('PRAGMA foreign_keys = ON')
508
            try:
509
                conn.row_factory = sqlite3.Row
510
                # Get a cursor object
511
                cursor = conn.cursor()
512

    
513
                sql = f"select Shape from Symbols where UID='{symbol}'"
514
                cursor.execute(sql)
515
                records = cursor.fetchall()
516
                for record in records:
517
                    res = record[0]
518
                    break
519

    
520
            # Catch the exception
521
            except Exception as ex:
522
                from App import App
523
                # Roll back any change if something goes wrong
524
                conn.rollback()
525

    
526
                message = 'error occurred({}) in {}:{}'.format(repr(ex), sys.exc_info()[-1].tb_frame.f_code.co_filename,
527
                                                               sys.exc_info()[-1].tb_lineno)
528
                App.mainWnd().addMessage.emit(MessageType.Error, message)
529

    
530
        return res
531

    
532
    def getRoughness(self, phase_type):
533
        res = []
534

    
535
        with sqlite3.connect(self.activeDrawing.path) as conn:
536
            conn.execute('PRAGMA foreign_keys = ON')
537
            try:
538
                conn.row_factory = sqlite3.Row
539
                # Get a cursor object
540
                cursor = conn.cursor()
541

    
542
                sql = "select UID, Material, Meter, Inch, Feet, Milimeter from Roughness where phase_type = ?"
543
                param = (phase_type,)
544
                cursor.execute(sql, param)
545
                rows = cursor.fetchall()
546
                for row in rows:
547
                    res.append((row[0], row[1], row[2], row[3], row[4], row[5]))
548
            # Catch the exception
549
            except Exception as ex:
550
                from App import App
551

    
552
                message = f"error occurred({repr(ex)}) in {sys.exc_info()[-1].tb_frame.f_code.co_filename}:" \
553
                          f"{sys.exc_info()[-1].tb_lineno}"
554
                App.mainWnd().addMessage.emit(MessageType.Error, message)
555

    
556
        return res
557

    
558
    def get_selected_nd(self, row_id, unit):
559
        res = None
560

    
561
        try:
562
            conn = sqlite3.connect(self.activeDrawing.path)
563
            conn.execute('PRAGMA foreign_keys = ON')
564
            # Get a cursor object
565
            cursor = conn.cursor()
566

    
567
            if unit == 'in':
568
                sql = 'select Inch from NominalDiameter where rowid <= ?'
569
            elif unit == 'mm':
570
                sql = 'select Milimeter from NominalDiameter where rowid <= ?'
571

    
572
            param = (row_id,)
573
            cursor.execute(sql, param)
574
            rows = cursor.fetchall()
575
            for row in rows:
576
                res = row[0]
577
        except Exception as ex:
578
            from App import App
579
            # Roll back any change if something goes wrong
580
            conn.rollback()
581

    
582
            message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
583
                                                           sys.exc_info()[-1].tb_lineno)
584
            App.mainWnd().addMessage.emit(MessageType.Error, message)
585
        finally:
586
            # Close the db connection
587
            conn.close()
588

    
589
        return res
590

    
591
    def get_row_id(self, size, unit):
592
        res = None
593

    
594
        try:
595
            conn = sqlite3.connect(self.activeDrawing.path)
596
            conn.execute('PRAGMA foreign_keys = ON')
597
            # Get a cursor object
598
            cursor = conn.cursor()
599

    
600
            if unit == 'in':
601
                sql = 'select count(*) from NominalDiameter where Inch <= ?'
602
            elif unit == 'mm':
603
                sql = 'select count(*) from NominalDiameter where Milimeter <= ?'
604

    
605
            param = (size,)
606
            cursor.execute(sql, param)
607
            rows = cursor.fetchall()
608
            for row in rows:
609
                res = row[0]
610
        except Exception as ex:
611
            from App import App
612
            # Roll back any change if something goes wrong
613
            conn.rollback()
614

    
615
            message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
616
                                                           sys.exc_info()[-1].tb_lineno)
617
            App.mainWnd().addMessage.emit(MessageType.Error, message)
618
        finally:
619
            # Close the db connection
620
            conn.close()
621

    
622
        return res
623

    
624
    def getInsideDiameter(self, nominaldiameter_uid, schedule_uid):
625
        res = []
626
        try:
627
            conn = sqlite3.connect(self.activeDrawing.path)
628
            conn.execute('PRAGMA foreign_keys = ON')
629
            # Get a cursor object
630
            cursor = conn.cursor()
631

    
632
            sql = """select UID
633
                          , Milimeter
634
                          , Inch 
635
                       from InsideDiameter
636
                      where NominalDiameter_UID = ?
637
                        and Schedule_UID = ?"""
638

    
639
            param = (nominaldiameter_uid, schedule_uid)
640
            cursor.execute(sql, param)
641
            rows = cursor.fetchall()
642
            for row in rows:
643
                res.append((row[0], row[1], row[2]))
644
        # Catch the exception
645
        except Exception as ex:
646
            from App import App
647
            # Roll back any change if something goes wrong
648
            conn.rollback()
649

    
650
            message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
651
                                                           sys.exc_info()[-1].tb_lineno)
652
            App.mainWnd().addMessage.emit(MessageType.Error, message)
653
        finally:
654
            # Close the db connection
655
            conn.close()
656

    
657
        return res
658

    
659
    def getSchedule(self):
660
        res = []
661

    
662
        conn = sqlite3.connect(self.activeDrawing.path)
663
        conn.execute('PRAGMA foreign_keys = ON')
664
        with conn:
665
            try:
666
                # Get a cursor object
667
                cursor = conn.cursor()
668

    
669
                sql = "select UID, No from Schedule"
670
                cursor.execute(sql)
671
                rows = cursor.fetchall()
672
                for row in rows:
673
                    res.append((row[0], row[1]))
674
            # Catch the exception
675
            except Exception as ex:
676
                from App import App
677
                # Roll back any change if something goes wrong
678
                conn.rollback()
679

    
680
                message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
681
                                                               sys.exc_info()[-1].tb_lineno)
682
                App.mainWnd().addMessage.emit(MessageType.Error, message)
683
        return res
684

    
685
    def get_nominal_diameter_info(self, nominal_diameter, unit):
686
        res = []
687

    
688
        # Creates or opens a file called mydb with a SQLite3 DB
689
        conn = sqlite3.connect(self.activeDrawing.path)
690
        conn.execute('PRAGMA foreign_keys = ON')
691
        with conn:
692
            try:
693
                # Get a cursor object
694
                cursor = conn.cursor()
695

    
696
                if unit == 'mm':
697
                    sql = "select UID, Milimeter, Inch, Friction_Factor from NominalDiameter where Milimeter = ?"
698
                else:
699
                    sql = "select UID, Milimeter, Inch, Friction_Factor from NominalDiameter where Inch = ?"
700

    
701
                param = (nominal_diameter,)
702
                cursor.execute(sql, param)
703
                rows = cursor.fetchall()
704
                for row in rows:
705
                    res.append((row[0], row[1], row[2], row[3]))
706
            # Catch the exception
707
            except Exception as ex:
708
                from App import App
709

    
710
                # Roll back any change if something goes wrong
711
                conn.rollback()
712

    
713
                message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
714
                                                               sys.exc_info()[-1].tb_lineno)
715
                App.mainWnd().addMessage.emit(MessageType.Error, message)
716
        return res
717

    
718
    def getNominalDiameterByUid(self, uid):
719
        res = []
720

    
721
        # Creates or opens a file called mydb with a SQLite3 DB
722
        conn = sqlite3.connect(self.activeDrawing.path)
723
        conn.execute('PRAGMA foreign_keys = ON')
724
        with conn:
725
            try:
726
                # Get a cursor object
727
                cursor = conn.cursor()
728

    
729
                sql = "select UID, Milimeter, Inch, Friction_Factor from NominalDiameter where uid = ?"
730
                param = (uid,)
731
                cursor.execute(sql, param)
732
                rows = cursor.fetchall()
733
                for row in rows:
734
                    res.append((row[0], row[1], row[2], row[3]))
735
            # Catch the exception
736
            except Exception as ex:
737
                from App import App
738

    
739
                # Roll back any change if something goes wrong
740
                conn.rollback()
741

    
742
                message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
743
                                                               sys.exc_info()[-1].tb_lineno)
744
                App.mainWnd().addMessage.emit(MessageType.Error, message)
745
        return res
746

    
747
    def getNominalDiameter(self):
748
        res = []
749

    
750
        # Creates or opens a file called mydb with a SQLite3 DB
751
        conn = sqlite3.connect(self.activeDrawing.path)
752
        conn.execute('PRAGMA foreign_keys = ON')
753
        with conn:
754
            try:
755
                # Get a cursor object
756
                cursor = conn.cursor()
757

    
758
                sql = "select UID, Milimeter, Inch from NominalDiameter"
759
                cursor.execute(sql)
760
                rows = cursor.fetchall()
761
                for row in rows:
762
                    res.append((row[0], row[1], row[2]))
763
            # Catch the exception
764
            except Exception as ex:
765
                from App import App
766

    
767
                # Roll back any change if something goes wrong
768
                conn.rollback()
769

    
770
                message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
771
                                                               sys.exc_info()[-1].tb_lineno)
772
                App.mainWnd().addMessage.emit(MessageType.Error, message)
773
        return res
774

    
775
    def getAppDrawing(self, uid):
776
        res = []
777

    
778
        try:
779
            # Creates or opens a file called mydb with a SQLite3 DB
780
            dbPath = self.getAppDbPath()
781
            conn = sqlite3.connect(dbPath)
782
            conn.execute('PRAGMA foreign_keys = ON')
783
            # Get a cursor object
784
            cursor = conn.cursor()
785

    
786
            sql = "select * from Drawings where uid=?"
787
            param = (uid,)
788

    
789
            cursor.execute(sql, param)
790
            rows = cursor.fetchall()
791
            for row in rows:
792
                res.append([row[0], row[1], row[2]])
793
        # Catch the exception
794
        except Exception as ex:
795
            from App import App
796
            # Roll back any change if something goes wrong
797
            conn.rollback()
798

    
799
            message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
800
                                                           sys.exc_info()[-1].tb_lineno)
801
            App.mainWnd().addMessage.emit(MessageType.Error, message)
802
        finally:
803
            # Close the db connection
804
            conn.close()
805

    
806
        return res
807

    
808
    def getAppConfigs(self, section, key=None):
809
        """
810
            @brief  get application configurations
811
            @author humkyung
812
            @date   2018.11.01
813
        """
814

    
815
        res = []
816

    
817
        try:
818
            # Creates or opens a file called mydb with a SQLite3 DB
819
            dbPath = self.getAppDbPath()
820
            with sqlite3.connect(dbPath) as conn:
821
                conn.execute('PRAGMA foreign_keys = ON')
822
                # Get a cursor object
823
                cursor = conn.cursor()
824

    
825
                if key is not None:
826
                    sql = "select * from configuration where section=? and key=?"
827
                    param = (section, key)
828
                else:
829
                    sql = "select * from configuration where section=?"
830
                    param = (section,)
831

    
832
                cursor.execute(sql, param)
833
                rows = cursor.fetchall()
834
                for row in rows:
835
                    res.append(Config(row[0], row[1], row[2]))
836
        # Catch the exception
837
        except Exception as ex:
838
            from App import App
839
            # Roll back any change if something goes wrong
840
            conn.rollback()
841

    
842
            message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
843
                                                           sys.exc_info()[-1].tb_lineno)
844
            App.mainWnd().addMessage.emit(MessageType.Error, message)
845
        finally:
846
            # Close the db connection
847
            conn.close()
848

    
849
        return res
850

    
851
    def getConfigs(self, section, key=None):
852
        """
853
            @brief  get application configurations
854
            @author humkyung
855
            @date   2018.11.01
856
        """
857

    
858
        res = []
859

    
860
        try:
861
            # Creates or opens a file called mydb with a SQLite3 DB
862
            conn = sqlite3.connect(self.activeDrawing.path)
863
            conn.execute('PRAGMA foreign_keys = ON')
864
            # Get a cursor object
865
            cursor = conn.cursor()
866

    
867
            if key is not None:
868
                sql = "select Section, Key, Value from configuration where section=? and key=?"
869
                param = (section, key)
870
            else:
871
                sql = "select Section, Key, Value from configuration where section=?"
872
                param = (section,)
873

    
874
            cursor.execute(sql, param)
875
            rows = cursor.fetchall()
876
            for row in rows:
877
                res.append(Config(row[0], row[1], row[2]))
878
        # Catch the exception
879
        except Exception as ex:
880
            from App import App
881

    
882
            # Roll back any change if something goes wrong
883
            conn.rollback()
884

    
885
            message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
886
                                                           sys.exc_info()[-1].tb_lineno)
887
            App.mainWnd().addMessage.emit(MessageType.Error, message)
888
        finally:
889
            # Close the db connection
890
            conn.close()
891

    
892
        return res
893

    
894
    def saveAppConfigs(self, configs):
895
        """
896
        @brief      save application configurations
897
        @author     humkyung
898
        @date       2018.10.01
899
        """
900

    
901
        try:
902
            # Creates or opens a file called mydb with a SQLite3 DB
903
            dbPath = self.getAppDbPath()
904
            with sqlite3.connect(dbPath) as conn:
905
                conn.execute('PRAGMA foreign_keys = ON')
906
                # Get a cursor object
907
                cursor = conn.cursor()
908

    
909
                for config in configs:
910
                    value = config.value
911
                    if type(value) is str and "'" in value:
912
                        value = value.replace("'", "''")
913

    
914
                    sql = "insert or replace into configuration values(?,?,?)"
915
                    param = (config.section, config.key, value)
916

    
917
                    cursor.execute(sql, param)
918
                conn.commit()
919
        # Catch the exception
920
        except Exception as ex:
921
            from App import App
922
            # Roll back any change if something goes wrong
923
            conn.rollback()
924

    
925
            message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
926
                                                           sys.exc_info()[-1].tb_lineno)
927
            App.mainWnd().addMessage.emit(MessageType.Error, message)
928

    
929
    def update_roughness(self, roughness):
930
        try:
931
            # Creates or opens a file called mydb with a SQLite3 DB
932
            conn = sqlite3.connect(self.activeDrawing.path)
933
            conn.execute('PRAGMA foreign_keys = ON')
934
            # Get a cursor object
935
            cursor = conn.cursor()
936

    
937
            for r in roughness:
938
                uid = r[0]
939
                material = r[1]
940
                meter = r[2]
941
                inch = r[3]
942
                feet = r[4]
943
                millimeter = r[5]
944

    
945
                sql = """Update Roughness
946
                            Set Material = ?
947
                              , Meter = ?
948
                              , Inch = ?
949
                              , Feet = ?
950
                              , Milimeter = ? 
951
                          Where UID = ?"""
952
                param = (material, meter, inch, feet, millimeter, uid)
953

    
954
                cursor.execute(sql, param)
955
            conn.commit()
956
        except Exception as ex:
957
            from App import App
958
            # Roll back any change if something goes wrong
959
            conn.rollback()
960

    
961
            message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
962
                                                           sys.exc_info()[-1].tb_lineno)
963
            App.mainWnd().addMessage.emit(MessageType.Error, message)
964
        finally:
965
            # Close the db connection
966
            conn.close()
967

    
968
    def apply_path_data(self, scripts):
969
        with sqlite3.connect(self.activeDrawing.path) as conn:
970
            try:
971
                conn.execute('PRAGMA foreign_keys = ON')
972
                # Get a cursor object
973
                cursor = conn.cursor()
974
                cursor.executescript(scripts)
975
                conn.commit()
976
            except Exception as ex:
977
                from App import App
978
                # Roll back any change if something goes wrong
979
                conn.rollback()
980

    
981
                message = f"error occurred({repr(ex)}) in {sys.exc_info()[-1].tb_frame.f_code.co_filename}:" \
982
                          f"{sys.exc_info()[-1].tb_lineno}"
983
                App.mainWnd().addMessage.emit(MessageType.Error, message)
984

    
985
    def saveConfigs(self, configs):
986
        """
987
        @brief      save application configurations
988
        @author     humkyung
989
        @date       2018.10.01
990
        """
991

    
992
        try:
993
            # Creates or opens a file called mydb with a SQLite3 DB
994
            conn = sqlite3.connect(self.activeDrawing.path)
995
            conn.execute('PRAGMA foreign_keys = ON')
996
            # Get a cursor object
997
            cursor = conn.cursor()
998

    
999
            for config in configs:
1000
                value = config.value
1001
                if type(value) is str and "'" in value:
1002
                    value = value.replace("'", "''")
1003

    
1004
                sql = "insert or replace into configuration values(?,?,?)"
1005
                param = (config.section, config.key, value)
1006

    
1007
                cursor.execute(sql, param)
1008
            conn.commit()
1009
        # Catch the exception
1010
        except Exception as ex:
1011
            from App import App
1012
            # Roll back any change if something goes wrong
1013
            conn.rollback()
1014

    
1015
            message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
1016
                                                           sys.exc_info()[-1].tb_lineno)
1017
            App.mainWnd().addMessage.emit(MessageType.Error, message)
1018
        finally:
1019
            # Close the db connection
1020
            conn.close()
1021

    
1022
    def initializeDataByDrawingUID(self, uid):
1023
        try:
1024
            # Creates or opens a file called mydb with a SQLite3 DB
1025
            conn = sqlite3.connect(self.activeDrawing.path)
1026
            conn.execute('PRAGMA foreign_keys = ON')
1027
            # Get a cursor object
1028
            cursor = conn.cursor()
1029

    
1030
            sql = "delete from Components"
1031
            cursor.execute(sql)
1032

    
1033
            conn.commit()
1034
        # Catch the exception
1035
        except Exception as ex:
1036
            from App import App
1037
            # Roll back any change if something goes wrong
1038
            conn.rollback()
1039
            message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
1040
                                                           sys.exc_info()[-1].tb_lineno)
1041
            App.mainWnd().addMessage.emit(MessageType.Error, message)
1042
        finally:
1043
            # Close the db connection
1044
            conn.close()
1045

    
1046
    def deleteDrawingByName(self, drawingName):
1047
        """ delete given drawing """
1048
        conn = sqlite3.connect(self.getAppDbPath())
1049
        conn.execute('PRAGMA foreign_keys = ON')
1050
        with conn:
1051
            try:
1052
                # Get a cursor object
1053
                cursor = conn.cursor()
1054

    
1055
                sql = 'delete from Drawings where Name=?'
1056
                param = (drawingName,)
1057
                cursor.execute(sql, param)
1058

    
1059
                conn.commit()
1060
            # Catch the exception
1061
            except Exception as ex:
1062
                from App import App
1063
                # Roll back any change if something goes wrong
1064
                conn.rollback()
1065

    
1066
                message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
1067
                                                               sys.exc_info()[-1].tb_lineno)
1068
                App.mainWnd().addMessage.emit(MessageType.Error, message)
1069

    
1070
    def deleteAppConfigs(self, section, key=None):
1071
        """
1072
        @brief  delete application configurations
1073
        @author humkyung
1074
        @date   2018.11.01
1075
        """
1076

    
1077
        try:
1078
            # Creates or opens a file called mydb with a SQLite3 DB
1079
            dbPath = self.getAppDbPath()
1080
            conn = sqlite3.connect(dbPath)
1081
            conn.execute('PRAGMA foreign_keys = ON')
1082
            # Get a cursor object
1083
            cursor = conn.cursor()
1084

    
1085
            if key is not None:
1086
                sql = "delete from configuration where section='{}' and key='{}'".format(section, key)
1087
            else:
1088
                sql = "delete from configuration where section='{}'".format(section)
1089
            cursor.execute(sql)
1090

    
1091
            conn.commit()
1092
        # Catch the exception
1093
        except Exception as ex:
1094
            from App import App
1095

    
1096
            # Roll back any change if something goes wrong
1097
            conn.rollback()
1098

    
1099
            message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
1100
                                                           sys.exc_info()[-1].tb_lineno)
1101
            App.mainWnd().addMessage.emit(MessageType.Error, message)
1102
        finally:
1103
            # Close the db connection
1104
            conn.close()
1105

    
1106
    '''
1107
        @brief  get symbol name
1108
        @history    18.04.24    Jeongwoo    Add isExceptDetect Field
1109
    '''
1110

    
1111
    def getSymbolByQuery(self, fieldName, param):
1112
        ret = None
1113

    
1114
        conn = sqlite3.connect(self.activeDrawing.path)
1115
        conn.execute('PRAGMA foreign_keys = ON')
1116
        with conn:
1117
            cursor = conn.cursor()
1118

    
1119
            sql = """select s.UID
1120
                            , s.Name
1121
                            , t.Category
1122
                            , t.Type
1123
                            , s.OriginalPoint
1124
                            , s.ConnectionPoint
1125
                        from Symbols s
1126
                        inner join SymbolType t
1127
                            on s.SymbolType_UID = t.UID 
1128
                        where """ + "s." + fieldName + '=?'
1129

    
1130
            try:
1131
                cursor.execute(sql, (param,))
1132
                rows = cursor.fetchall()
1133
                if rows is not None and len(rows) > 0:
1134
                    symbolTuple = rows[0]
1135
                    ret = symbol.SymbolBase(symbolTuple[0], symbolTuple[1], symbolTuple[2], symbolTuple[3],
1136
                                            symbolTuple[4], symbolTuple[5])
1137
            except Exception as ex:
1138
                from App import App
1139

    
1140
                message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
1141
                                                               sys.exc_info()[-1].tb_lineno)
1142
                App.mainWnd().addMessage.emit(MessageType.Error, message)
1143

    
1144
        return ret
1145

    
1146
    def getSymbolListByUID(self, uid):
1147
        """ get symbol list by given uid """
1148
        ret = []
1149

    
1150
        conn = sqlite3.connect(self.activeDrawing.path)
1151
        conn.execute('PRAGMA foreign_keys = ON')
1152
        with conn:
1153
            cursor = conn.cursor()
1154

    
1155
            sql = """select s.UID
1156
                            , s.Name
1157
                            , t.Category
1158
                            , t.Type
1159
                            , s.OriginalPoint
1160
                            , s.ConnectionPoint
1161
                        from Symbols s
1162
                        inner join SymbolType t
1163
                            on s.SymbolType_UID = t.uid 
1164
                        where s.SymbolType_UID = ?"""
1165

    
1166
            try:
1167
                cursor.execute(sql, (uid,))
1168
                rows = cursor.fetchall()
1169
                if rows is not None and len(rows) > 0:
1170
                    for row in rows:
1171
                        sym = symbol.SymbolBase(row[0], row[1], row[2], row[3], row[4], row[5])
1172

    
1173
                        ret.append(sym)
1174
            except Exception as ex:
1175
                from App import App
1176

    
1177
                message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
1178
                                                               sys.exc_info()[-1].tb_lineno)
1179
                App.mainWnd().addMessage.emit(MessageType.Error, message)
1180

    
1181
        return ret
1182

    
1183
    def get_mixed_pressure_variation(self, uid):
1184
        res = []
1185

    
1186
        # Creates or opens a file called mydb with a SQLite3 DB
1187
        db_path = os.path.join(self.activeDrawing.path)
1188
        with sqlite3.connect(db_path) as conn:
1189
            try:
1190
                conn.execute('PRAGMA foreign_keys = ON')
1191
                conn.row_factory = sqlite3.Row
1192
                # Get a cursor object
1193
                cursor = conn.cursor()
1194

    
1195
                sql = """select Element
1196
                              , Inside_Pipe_Size
1197
                              , Length
1198
                              , Angle
1199
                              , K
1200
                              , Pressure
1201
                              , Void
1202
                              , Quality
1203
                              , Density
1204
                              , Homo_Den
1205
                              , V_Den                          
1206
                              , Mean_Vel
1207
                              , Homo_Vel
1208
                              , Max_Vel
1209
                              , Ero_Vel
1210
                              , Pattern_X
1211
                              , Pattern_Y
1212
                              , Regime
1213
                              , Friction
1214
                              , Gravity
1215
                              , Momentum
1216
                              , Total
1217
                           from PressureVariation
1218
                          where Components_UID = ?
1219
                          order by rowid"""
1220

    
1221
                param = (uid,)
1222
                cursor.execute(sql, param)
1223
                rows = cursor.fetchall()
1224
                for row in rows:
1225
                    res.append((row[0], row[1], row[2], row[3], row[4], row[5], row[6], row[7], row[8], row[9], row[10],
1226
                                row[11], row[12], row[13], row[14], row[15], row[16], row[17], row[18], row[19],
1227
                                row[20],
1228
                                row[21]))
1229
            # Catch the exception
1230
            except Exception as ex:
1231
                from App import App
1232

    
1233
                # Roll back any change if something goes wrong
1234
                conn.rollback()
1235

    
1236
                message = f"error occurred({repr(ex)}) in {sys.exc_info()[-1].tb_frame.f_code.co_filename}:" \
1237
                          f"{sys.exc_info()[-1].tb_lineno}"
1238
                App.mainWnd().addMessage.emit(MessageType.Error, message)
1239

    
1240
        return res
1241

    
1242
    def get_geometry_input(self, uid):
1243
        res = []
1244

    
1245
        # Creates or opens a file called mydb with a SQLite3 DB
1246
        db_path = os.path.join(self.activeDrawing.path)
1247
        with sqlite3.connect(db_path) as conn:
1248
            try:
1249
                conn.execute('PRAGMA foreign_keys = ON')
1250
                conn.row_factory = sqlite3.Row
1251
                # Get a cursor object
1252
                cursor = conn.cursor()
1253

    
1254
                sql = """select Element
1255
                              , Nominal_Pipe_Size
1256
                              , Schedule_No
1257
                              , Inside_Pipe_Size
1258
                              , Roughness
1259
                              , Length
1260
                              , Angle
1261
                              , RPD
1262
                              , D1_D2
1263
                              , K
1264
                           from Geometry_Input
1265
                          where Components_UID = ?
1266
                          order by rowid"""
1267

    
1268
                param = (uid,)
1269
                cursor.execute(sql, param)
1270
                rows = cursor.fetchall()
1271
                for row in rows:
1272
                    res.append((row[0], row[1], row[2], row[3], row[4], row[5], row[6], row[7], row[8], row[9]))
1273
            # Catch the exception
1274
            except Exception as ex:
1275
                from App import App
1276

    
1277
                # Roll back any change if something goes wrong
1278
                conn.rollback()
1279

    
1280
                message = f"error occurred({repr(ex)}) in {sys.exc_info()[-1].tb_frame.f_code.co_filename}:" \
1281
                          f"{sys.exc_info()[-1].tb_lineno}"
1282
                App.mainWnd().addMessage.emit(MessageType.Error, message)
1283

    
1284
        return res
1285

    
1286
    def get_fittings_input(self, uid):
1287
        res = []
1288
        try:
1289
            # Creates or opens a file called mydb with a SQLite3 DB
1290
            dbPath = os.path.join(self.activeDrawing.path)
1291
            conn = sqlite3.connect(dbPath)
1292
            conn.execute('PRAGMA foreign_keys = ON')
1293
            conn.row_factory = sqlite3.Row
1294
            # Get a cursor object
1295
            cursor = conn.cursor()
1296

    
1297
            sql = """select Fittings_UID
1298
                          , Method
1299
                          , Sub_Size
1300
                          , Angle
1301
                          , Count
1302
                       from Fittings_Input
1303
                      where Components_UID = ?
1304
                      order by rowid"""
1305

    
1306
            param = (uid,)
1307
            cursor.execute(sql, param)
1308
            rows = cursor.fetchall()
1309
            for row in rows:
1310
                res.append((row[0], row[1], row[2], row[3], row[4]))
1311
        # Catch the exception
1312
        except Exception as ex:
1313
            from App import App
1314

    
1315
            # Roll back any change if something goes wrong
1316
            conn.rollback()
1317

    
1318
            message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
1319
                                                           sys.exc_info()[-1].tb_lineno)
1320
            App.mainWnd().addMessage.emit(MessageType.Error, message)
1321

    
1322
        finally:
1323
            # Close the db connection
1324
            conn.close()
1325

    
1326
        return res
1327

    
1328
    def get_fittings_by_uid(self, uid):
1329
        res = None
1330
        try:
1331
            # Creates or opens a file called mydb with a SQLite3 DB
1332
            dbPath = os.path.join(self.activeDrawing.path)
1333
            conn = sqlite3.connect(dbPath)
1334
            conn.execute('PRAGMA foreign_keys = ON')
1335
            conn.row_factory = sqlite3.Row
1336
            # Get a cursor object
1337
            cursor = conn.cursor()
1338

    
1339
            sql = """select UID
1340
                          , Method
1341
                          , Category
1342
                          , Type
1343
                          , Name
1344
                          , K 
1345
                          , Image
1346
                       from Fittings 
1347
                      where UID = ?
1348
                      order by rowid"""
1349

    
1350
            param = (uid,)
1351
            cursor.execute(sql, param)
1352
            rows = cursor.fetchall()
1353
            if rows:
1354
                res = rows[0]
1355
        # Catch the exception
1356
        except Exception as ex:
1357
            from App import App
1358

    
1359
            # Roll back any change if something goes wrong
1360
            conn.rollback()
1361

    
1362
            message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
1363
                                                           sys.exc_info()[-1].tb_lineno)
1364
            App.mainWnd().addMessage.emit(MessageType.Error, message)
1365

    
1366
        finally:
1367
            # Close the db connection
1368
            conn.close()
1369

    
1370
        return res
1371

    
1372
    def get_fittings_by_method(self, method):
1373
        res = []
1374
        try:
1375
            # Creates or opens a file called mydb with a SQLite3 DB
1376
            dbPath = os.path.join(self.activeDrawing.path)
1377
            conn = sqlite3.connect(dbPath)
1378
            conn.execute('PRAGMA foreign_keys = ON')
1379
            conn.row_factory = sqlite3.Row
1380
            # Get a cursor object
1381
            cursor = conn.cursor()
1382

    
1383
            sql = """select UID
1384
                          , Method
1385
                          , Category
1386
                          , Type
1387
                          , Name
1388
                          , K 
1389
                          , Image
1390
                       from Fittings 
1391
                      where Method = ?
1392
                      order by rowid"""
1393

    
1394
            param = (method,)
1395
            cursor.execute(sql, param)
1396
            rows = cursor.fetchall()
1397
            for row in rows:
1398
                res.append((row[0], row[1], row[2], row[3], row[4], row[5], row[6]))
1399
        # Catch the exception
1400
        except Exception as ex:
1401
            from App import App
1402

    
1403
            # Roll back any change if something goes wrong
1404
            conn.rollback()
1405

    
1406
            message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
1407
                                                           sys.exc_info()[-1].tb_lineno)
1408
            App.mainWnd().addMessage.emit(MessageType.Error, message)
1409

    
1410
        finally:
1411
            # Close the db connection
1412
            conn.close()
1413

    
1414
        return res
1415

    
1416
    def saveToDatabase(self, items, show_progress=None):
1417
        """ save given items to database """
1418

    
1419
        queries = []
1420
        for item in items:
1421
            queries.append(item.toSql())
1422

    
1423
        """store sql query string for output"""
1424
        for output in self.outputs:
1425
            queries.append(output.to_sql())
1426
        """up to here"""
1427

    
1428
        with sqlite3.connect(self.activeDrawing.path, isolation_level=None) as conn:
1429
            conn.execute('PRAGMA foreign_keys = ON')
1430
            try:
1431
                # Get a cursor object
1432
                cursor = conn.cursor()
1433
                cursor.execute('begin')
1434

    
1435
                # delete Components
1436
                sql = 'delete from Components'
1437
                cursor.execute(sql)
1438

    
1439
                progress = 0
1440
                length = len(queries)
1441
                for sql in queries:
1442
                    if type(sql) is list:
1443
                        for item in sql:
1444
                            if item is not None and 2 == len(item):
1445
                                cursor.execute(item[0], item[1])
1446
                    else:
1447
                        if sql is not None and 2 == len(sql):
1448
                            cursor.execute(sql[0], sql[1])
1449

    
1450
                    if show_progress:
1451
                        show_progress(int((progress / length) * 100))
1452
                    progress += 1
1453

    
1454
                cursor.execute('commit')
1455
            # Catch the exception
1456
            except Exception as ex:
1457
                from App import App
1458
                # Roll back any change if something goes wrong
1459
                conn.rollback()
1460

    
1461
                message = f"error occurred({repr(ex)}) in {sys.exc_info()[-1].tb_frame.f_code.co_filename}:" \
1462
                          f"{sys.exc_info()[-1].tb_lineno}"
1463
                App.mainWnd().addMessage.emit(MessageType.Error, message)
1464
            finally:
1465
                if show_progress:
1466
                    show_progress(100)
1467

    
1468
    def get_drawings(self):
1469
        """get drawings"""
1470
        from Drawing import Drawing
1471

    
1472
        res = []
1473
        # Creates or opens a file called mydb with a SQLite3 DB
1474
        dbPath = self.getAppDbPath()
1475
        with sqlite3.connect(dbPath) as conn:
1476
            conn.execute('PRAGMA foreign_keys = ON')
1477
            try:
1478
                conn.row_factory = sqlite3.Row
1479
                # Get a cursor object
1480
                cursor = conn.cursor()
1481

    
1482
                sql = 'select UID,[NAME],[DATETIME],' \
1483
                      'IFNULL(B.[X], 0) as X, IFNULL(B.[Y], 0) as Y,' \
1484
                      'IFNULL(B.[Width], 0) as Width, IFNULL(B.[Height], 0) as Height from ' \
1485
                      'Drawings A left join Views B on A.UID=B.Drawings_UID'
1486
                cursor.execute(sql)
1487
                rows = cursor.fetchall()
1488
                for row in rows:
1489
                    if os.path.exists(row[1]):
1490
                        rect = QRectF(float(row['X']), float(row['Y']), float(row['Width']), float(row['Height']))
1491
                        res.append(Drawing(row[0], row[1], row[2], rect))
1492
            # Catch the exception
1493
            except Exception as ex:
1494
                # Roll back any change if something goes wrong
1495
                conn.rollback()
1496
                from App import App
1497

    
1498
                message = f"error occurred({repr(ex)}) in {sys.exc_info()[-1].tb_frame.f_code.co_filename}:" \
1499
                          f"{sys.exc_info()[-1].tb_lineno}"
1500
                App.mainWnd().addMessage.emit(MessageType.Error, message)
1501

    
1502
        return res
1503

    
1504
    '''
1505
        @brief      update drawings
1506
        @author     yeonjin
1507
        @date       2019.08.07
1508
    '''
1509

    
1510
    def update_drawing(self, drawing):
1511
        import uuid
1512

    
1513
        # Creates or opens a file called mydb with a SQLite3 DB
1514
        dbPath = self.getAppDbPath()
1515
        with sqlite3.connect(dbPath) as conn:
1516
            conn.execute('PRAGMA foreign_keys = ON')
1517
            try:
1518
                # Get a cursor object
1519
                cursor = conn.cursor()
1520

    
1521
                sql = """update Drawings
1522
                            set Name=?,DateTime=? where UID = ?"""
1523
                param = (drawing.org_path, drawing.date_time, drawing.UID)
1524
                cursor.execute(sql, param)
1525

    
1526
                conn.commit()
1527
            # Catch the exception
1528
            except Exception as ex:
1529
                # Roll back any change if something goes wrong
1530
                conn.rollback()
1531
                from App import App
1532

    
1533
                message = f"error occurred({repr(ex)}) in {sys.exc_info()[-1].tb_frame.f_code.co_filename}:" \
1534
                          f"{sys.exc_info()[-1].tb_lineno}"
1535
                App.mainWnd().addMessage.emit(MessageType.Error, message)
1536

    
1537
        self.update_view_region(drawing)
1538

    
1539
    '''
1540
        @brief      save drawings
1541
        @author     humkyung
1542
        @date       2018.11.03
1543
    '''
1544

    
1545
    def save_drawing(self, drawing):
1546
        import uuid
1547
        from shutil import copyfile
1548

    
1549
        with sqlite3.connect(self.getAppDbPath()) as conn:
1550
            conn.execute('PRAGMA foreign_keys = ON')
1551
            try:
1552
                # Get a cursor object
1553
                cursor = conn.cursor()
1554

    
1555
                sql = 'insert or replace into Drawings(UID, [NAME], [DATETIME]) values(?, ?, ?)'
1556
                param = (drawing.UID, drawing.org_path, drawing.date_time)
1557
                cursor.execute(sql, param)
1558

    
1559
                conn.commit()
1560

    
1561
                if not os.path.exists(drawing.path):
1562
                    copyfile(self.getTemplateDbPath(), drawing.path)
1563
            # Catch the exception
1564
            except Exception as ex:
1565
                # Roll back any change if something goes wrong
1566
                conn.rollback()
1567
                from App import App
1568

    
1569
                message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
1570
                                                               sys.exc_info()[-1].tb_lineno)
1571
                App.mainWnd().addMessage.emit(MessageType.Error, message)
1572

    
1573
        self.update_view_region(drawing)
1574

    
1575
    def update_view_region(self, drawing):
1576
        """update view region"""
1577
        with sqlite3.connect(self.getAppDbPath()) as conn:
1578
            try:
1579
                # Get a cursor object
1580
                cursor = conn.cursor()
1581

    
1582
                # check if there is view region
1583
                sql = f"select count(*) from Views where Drawings_UID=?"
1584
                params = [drawing.UID]
1585
                cursor.execute(sql, params)
1586
                rows = cursor.fetchall()
1587
                if rows[0][0]:
1588
                    sql = f"update Views set X=?,Y=?,Width=?,Height=? where Drawings_UID=?"
1589
                    params = (drawing.view_rect.x(), drawing.view_rect.y(),
1590
                              drawing.view_rect.width(), drawing.view_rect.height(), drawing.UID)
1591
                else:
1592
                    sql = f"insert into Views(Drawings_UID,X,Y,Width,Height) values(?,?,?,?,?)"
1593
                    params = (drawing.UID, drawing.view_rect.x(), drawing.view_rect.y(),
1594
                              drawing.view_rect.width(), drawing.view_rect.height())
1595

    
1596
                cursor.execute(sql, params)
1597
                conn.commit()
1598
            # Catch the exception
1599
            except Exception as ex:
1600
                from App import App
1601
                message = f"error occurred({repr(ex)}\\n{sql}) in {sys.exc_info()[-1].tb_frame.f_code.co_filename}:" \
1602
                          f"{sys.exc_info()[-1].tb_lineno}"
1603
                App.mainWnd().addMessage.emit(MessageType.Error, message)
1604

    
1605
    '''
1606
        @brief      Return Symbol Category Items
1607
        @author     yeonjin
1608
        @date       19.07.11
1609
    '''
1610

    
1611
    def getSymbolCategoryList(self):
1612
        SymbolCategoryList = []
1613

    
1614
        with sqlite3.connect(self.activeDrawing.path) as conn:
1615
            conn.execute('PRAGMA foreign_keys = ON')
1616
            cursor = conn.cursor()
1617
            sql = 'SELECT DISTINCT CATEGORY FROM SymbolType ORDER BY type ASC'
1618
            try:
1619
                cursor.execute(sql)
1620
                rows = cursor.fetchall()
1621
                for row in rows:
1622
                    if row[0] not in ['Stream Line', 'Callout']:
1623
                        SymbolCategoryList.append((row[0]))  # category
1624
            except Exception as ex:
1625
                from App import App
1626

    
1627
                message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
1628
                                                               sys.exc_info()[-1].tb_lineno)
1629
                App.mainWnd().addMessage.emit(MessageType.Error, message)
1630

    
1631
        return SymbolCategoryList
1632

    
1633
    def getComponentByComponentUID(self, uid):
1634

    
1635
        with sqlite3.connect(self.activeDrawing.path) as conn:
1636
            conn.execute('PRAGMA foreign_keys = ON')
1637
            try:
1638
                conn.row_factory = sqlite3.Row
1639
                cursor = conn.cursor()
1640

    
1641
                sql = """select c.UID as Comp_UID
1642
                                , c.Name
1643
                                , c.[Index] as Comp_Index
1644
                                , c.Symbols_UID
1645
                                , t.Category
1646
                                , t.type
1647
                                , s.Name as Symbol_Name
1648
                                , s.OriginalPoint
1649
                                , c.X as Comp_X
1650
                                , c.Y as Comp_Y
1651
                                , c.Rotation
1652
                                , c.ScaleX
1653
                                , c.ScaleY
1654
                                , c.Transform
1655
                                , p.UID as Point_UID
1656
                                , p.[Index]
1657
                                , p.X
1658
                                , p.Y
1659
                                , p.ConnectedItem_UID
1660
                            from points p
1661
                            left join components c
1662
                                on p.components_uid = c.uid
1663
                            left join symbols s
1664
                                on c.Symbols_UID = s.UID    
1665
                            left join SymbolType t
1666
                                on s.symboltype_uid = t.uid
1667
                            where c.uid = ?
1668
                            order by p.[Index]"""
1669
                param = (uid,)
1670
                cursor.execute(sql, param)
1671
                return cursor.fetchall()
1672
            except Exception as ex:
1673
                from App import App
1674

    
1675
                message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
1676
                                                               sys.exc_info()[-1].tb_lineno)
1677
                App.mainWnd().addMessage.emit(MessageType.Error, message)
1678

    
1679
        return None
1680

    
1681
    def get_nozzle_data(self, uid):
1682
        """ get nozzle data of given uid """
1683
        from EngineeringConnectorItem import NozzleData
1684

    
1685
        res = None
1686
        with sqlite3.connect(self.activeDrawing.path) as conn:
1687
            conn.execute('PRAGMA foreign_keys = ON')
1688
            conn.row_factory = sqlite3.Row
1689
            cursor = conn.cursor()
1690
            sql = 'select Pressure, Pressure_Drop, Elevation, Over_Design_CV, CV_Type, ' \
1691
                  'B.Name, B.X, B.Y from Nozzles A ' \
1692
                  'left join Components B on A.Points_UID=B.UID where Points_UID=?'
1693
            param = (uid,)
1694
            cursor.execute(sql, param)
1695
            rows = cursor.fetchall()
1696
            if rows:
1697
                res = NozzleData()
1698
                res.parse(rows[0])
1699

    
1700
        return res
1701

    
1702
    '''
1703
        @brief      Return Components By DrawingUID
1704
        @author     yeonjin
1705
        @date       19.07.29
1706
    '''
1707

    
1708
    def getComponentListByDrawingUID(self):
1709
        ComponentList = []
1710

    
1711
        with sqlite3.connect(self.activeDrawing.path) as conn:
1712
            conn.execute('PRAGMA foreign_keys = ON')
1713
            try:
1714
                conn.row_factory = sqlite3.Row
1715
                cursor = conn.cursor()
1716
                sql = 'select UID from Components order by x desc'
1717
                cursor.execute(sql)
1718
                rows = cursor.fetchall()
1719
                for row in rows:
1720
                    ComponentList.append((row[0]))  # Components_UID
1721
            except Exception as ex:
1722
                from App import App
1723

    
1724
                message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
1725
                                                               sys.exc_info()[-1].tb_lineno)
1726
                App.mainWnd().addMessage.emit(MessageType.Error, message)
1727

    
1728
        return ComponentList
1729

    
1730
    '''
1731
        @brief      Return Symbol Type Items By Category
1732
        @author     yeonjin
1733
        @date       19.07.11
1734
    '''
1735

    
1736
    def getSymbolTypeListByCategory(self, category):
1737
        symbolTypeList = []
1738

    
1739
        conn = sqlite3.connect(self.activeDrawing.path)
1740
        conn.execute('PRAGMA foreign_keys = ON')
1741
        with conn:
1742
            cursor = conn.cursor()
1743
            sql = 'SELECT UID, Category, Type FROM SymbolType WHERE Category = "' + category + '"'
1744
            try:
1745
                cursor.execute(sql)
1746
                rows = cursor.fetchall()
1747
                for row in rows:
1748
                    symbolTypeList.append((row[0], row[1], row[2]))  # UID, Category, Type
1749
            except Exception as ex:
1750
                from App import App
1751

    
1752
                message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
1753
                                                               sys.exc_info()[-1].tb_lineno)
1754
                App.mainWnd().addMessage.emit(MessageType.Error, message)
1755

    
1756
        return symbolTypeList
1757

    
1758
    def get_sheet_history(self):
1759
        """get sheet history from database"""
1760

    
1761
        with sqlite3.connect(self.activeDrawing.path) as conn:
1762
            conn.row_factory = sqlite3.Row
1763
            conn.execute('PRAGMA foreign_keys = ON')
1764
            cursor = conn.cursor()
1765
            sql = 'Select UID, Activity, Date, User, IP From SheetHistory Order by Date Desc'
1766
            try:
1767
                cursor.execute(sql)
1768
                rows = cursor.fetchall()
1769
                return rows
1770
            except Exception as ex:
1771
                from App import App
1772

    
1773
                message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
1774
                                                               sys.exc_info()[-1].tb_lineno)
1775
                App.mainWnd().addMessage.emit(MessageType.Error, message)
1776

    
1777
        return None
1778

    
1779
    def save_sheet_history(self, activity):
1780
        """save sheet history data to database"""
1781
        from datetime import datetime
1782

    
1783
        configs = self.getAppConfigs('app', 'SingleID')
1784
        user_name = configs[0].value
1785
        configs = self.getAppConfigs('app', 'IP')
1786
        IP = configs[0].value
1787

    
1788
        with sqlite3.connect(self.activeDrawing.path) as conn:
1789
            try:
1790
                conn.row_factory = sqlite3.Row
1791
                conn.execute('PRAGMA foreign_keys = ON')
1792
                cursor = conn.cursor()
1793
                sql = 'insert into SheetHistory(Activity, Date, User, IP) values(?,?,?,?)'
1794
                param = (activity, datetime.now().strftime("%Y-%m-%d %H:%M:%S"), user_name, IP)
1795
                cursor.execute(sql, param)
1796
                conn.commit()
1797
            except Exception as ex:
1798
                from App import App
1799

    
1800
                message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
1801
                                                               sys.exc_info()[-1].tb_lineno)
1802
                App.mainWnd().addMessage.emit(MessageType.Error, message)
1803

    
1804
    def getUnits(self):
1805
        unitsList = []
1806

    
1807
        try:
1808
            conn = sqlite3.connect(self.activeDrawing.path)
1809
            conn.execute('PRAGMA foreign_keys = ON')
1810
            cursor = conn.cursor()
1811
            sql = 'Select UID, Key, Value From Units'
1812
            try:
1813
                cursor.execute(sql)
1814
                rows = cursor.fetchall()
1815
                for row in rows:
1816
                    unitsList.append((row[0], row[1], row[2]))  # UID, Key, Value
1817
            except Exception as ex:
1818
                from App import App
1819

    
1820
                message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
1821
                                                               sys.exc_info()[-1].tb_lineno)
1822
                App.mainWnd().addMessage.emit(MessageType.Error, message)
1823
        finally:
1824
            conn.close()
1825

    
1826
        return unitsList
1827

    
1828
    def getHMBDisplayNameAndUnitsExpression(self) -> QStandardItemModel:
1829
        res = QStandardItemModel(0, 2)
1830

    
1831
        if self.activeDrawing:
1832
            with sqlite3.connect(self.activeDrawing.path) as conn:
1833
                conn.execute('PRAGMA foreign_keys = ON')
1834
                cursor = conn.cursor()
1835
                sql = """SELECT dn.DISPLAY_NAME
1836
                                , hu.Units_Expression
1837
                            FROM DisplayNames dn
1838
                            left join HMBUnits hu
1839
                                on dn.COLUMN_NAME = Hu.Column_Name
1840
                            where dn.Table_Name = 'HMB'
1841
                            order by dn.[Order]"""
1842
                try:
1843
                    cursor.execute(sql)
1844
                    rows = cursor.fetchall()
1845
                    for row in rows:
1846
                        items = [QStandardItem(row[0]), QStandardItem(row[1])]
1847
                        items[0].setTextAlignment(Qt.AlignLeft | Qt.AlignVCenter)
1848
                        items[0].setBackground(QColor(51, 153, 102))
1849
                        items[0].setEditable(False)
1850
                        items[1].setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
1851
                        items[1].setBackground(QColor(204, 255, 204))
1852
                        items[1].setEditable(False)
1853

    
1854
                        res.appendRow(items)
1855
                        # res.append((row[0], row[1]))
1856
                except Exception as ex:
1857
                    from App import App
1858

    
1859
                    message = f'error occurred({ex}) in {sys.exc_info()[-1].tb_frame.f_code.co_filename}:' \
1860
                              f'{sys.exc_info()[-1].tb_lineno}'
1861
                    App.mainWnd().addMessage.emit(MessageType.Error, message)
1862

    
1863
        return res
1864

    
1865
    '''
1866
        @brief      Get Symbol Category by Symbol Type
1867
        @author     Jeongwoo
1868
        @date       2018.05.09
1869
    '''
1870

    
1871
    def getSymbolCategoryByType(self, type):
1872
        category = None
1873

    
1874
        conn = sqlite3.connect(self.activeDrawing.path)
1875
        conn.execute('PRAGMA foreign_keys = ON')
1876
        with conn:
1877
            try:
1878
                cursor = conn.cursor()
1879
                sql = 'SELECT Category FROM SymbolType WHERE type = "' + type + '"'
1880
                cursor.execute(sql)
1881
                rows = cursor.fetchall()
1882
                if rows is not None and len(rows) > 0:
1883
                    category = rows[0][0]
1884
            except Exception as ex:
1885
                from App import App
1886

    
1887
                message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
1888
                                                               sys.exc_info()[-1].tb_lineno)
1889
                App.mainWnd().addMessage.emit(MessageType.Error, message)
1890

    
1891
        return category
1892

    
1893
    def add_column(self, column_name, column_type, table_name):
1894
        try:
1895
            # Creates or opens a file called mydb with a SQLite3 DB
1896
            conn = sqlite3.connect(self.activeDrawing.path)
1897
            conn.execute('PRAGMA foreign_keys = ON')
1898
            # Get a cursor object
1899
            cursor = conn.cursor()
1900

    
1901
            sql = "Alter Table " + table_name + " Add Column '" + column_name + "' " + column_type
1902
            cursor.execute(sql)
1903

    
1904
            conn.commit()
1905
        # Catch the exception
1906
        except Exception as ex:
1907
            from App import App
1908
            # Roll back any change if something goes wrong
1909
            conn.rollback()
1910

    
1911
            message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
1912
                                                           sys.exc_info()[-1].tb_lineno)
1913
            App.mainWnd().addMessage.emit(MessageType.Error, message)
1914
        finally:
1915
            # Close the db connection
1916
            conn.close()
1917

    
1918
    def get_column_names(self, table_name):
1919
        res = []
1920

    
1921
        # Creates or opens a file called mydb with a SQLite3 DB
1922
        conn = sqlite3.connect(self.activeDrawing.path)
1923
        with conn:
1924
            try:
1925
                # Get a cursor object
1926
                cursor = conn.cursor()
1927

    
1928
                sql = "PRAGMA Table_Info ('" + table_name + "')"
1929
                cursor.execute(sql)
1930
                rows = cursor.fetchall()
1931
                for row in rows:
1932
                    res.append(row[1])
1933
            # Catch the exception
1934
            except Exception as ex:
1935
                from App import App
1936

    
1937
                # Roll back any change if something goes wrong
1938
                conn.rollback()
1939

    
1940
                message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
1941
                                                               sys.exc_info()[-1].tb_lineno)
1942
                App.mainWnd().addMessage.emit(MessageType.Error, message)
1943
        return res
1944

    
1945
    def is_table(self, table_name):
1946
        """ This method seems to be working now"""
1947
        result = False
1948
        # Creates or opens a file called mydb with a SQLite3 DB
1949
        conn = sqlite3.connect(self.activeDrawing.path)
1950
        with conn:
1951
            try:
1952
                # Get a cursor object
1953
                cursor = conn.cursor()
1954
                query = f"SELECT name from sqlite_master WHERE type='table' AND name='{table_name}';"
1955
                cursor.execute(query)
1956
                res = cursor.fetchone()
1957
                if res == None:
1958
                    result = False
1959
                else:
1960
                    result =  True
1961
            # Catch the exception
1962
            except Exception as ex:
1963
                from App import App
1964

    
1965
                # Roll back any change if something goes wrong
1966
                conn.rollback()
1967

    
1968
                message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
1969
                                                               sys.exc_info()[-1].tb_lineno)
1970
                App.mainWnd().addMessage.emit(MessageType.Error, message)
1971
        return result
1972

    
1973
    def execute_query(self, sqls: List) -> bool:
1974
        if not sqls:
1975
            return True
1976

    
1977
        result = False
1978

    
1979
        conn = sqlite3.connect(self.activeDrawing.path)
1980
        with conn:
1981
            try:
1982
                cursor = conn.cursor()
1983
                for sqlquery in sqls:
1984
                    cursor.execute(sqlquery)
1985
                result = True
1986

    
1987
            # Catch the exception
1988
            except Exception as ex:
1989

    
1990
                message = 'error occurred({}) in {}:{}'.format(ex,
1991
                                                               sys.exc_info()[-1].tb_frame.f_code.co_filename,
1992
                                                               sys.exc_info()[-1].tb_lineno)
1993
                App.mainWnd().addMessage.emit(MessageType.Error, message)
1994

    
1995
        return result
1996

    
1997
    def getPAPInfomations(self):
1998
        pap_Infomations = []
1999

    
2000
        try:
2001
            conn = sqlite3.connect(self.activeDrawing.path)
2002
            conn.execute('PRAGMA foreign_keys = ON')
2003
            cursor = conn.cursor()
2004
            sql = """ SELECT Project_UID, ProjectNo, CalculationCase 
2005
                      FROM PAPUploadInformation
2006
                      ORDER BY CreateDateTime DESC
2007
                """
2008
            try:
2009
                cursor.execute(sql)
2010
                rows = cursor.fetchall()
2011
                for row in rows:
2012
                    pap_Infomations.append(PAPUploadInformation(row[0], row[1], row[2]))
2013
            except Exception as ex:
2014
                from App import App
2015

    
2016
                message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
2017
                                                               sys.exc_info()[-1].tb_lineno)
2018
                App.mainWnd().addMessage.emit(MessageType.Error, message)
2019
        finally:
2020
            conn.close()
2021

    
2022
        return pap_Infomations
2023

    
2024
    def getPAPInfomationItems(self, Project_UID = ''):
2025
        pap_InfomationItems = []
2026
        try:
2027
            conn = sqlite3.connect(self.activeDrawing.path)
2028
            conn.execute('PRAGMA foreign_keys = ON')
2029
            cursor = conn.cursor()
2030
            sql = f"""Select Project_UID, 
2031
                             ProjectNo,
2032
                             Components_UID,
2033
                             Components_Type,
2034
                             Components_ItemNo,
2035
                             Components_DataCase
2036
                      From PAPUploadInformationItem"""
2037

    
2038
            if Project_UID:
2039
                sql += f""" WHERE Project_UID = '{Project_UID}' """
2040

    
2041
            cursor.execute(sql)
2042
            rows = cursor.fetchall()
2043
            for row in rows:
2044
                pap_InfomationItems.append(PAPUploadInformationItem(row[0],
2045
                                                                    row[1],
2046
                                                                    row[2],
2047
                                                                    row[3],
2048
                                                                    row[4],
2049
                                                                    row[5]))
2050
        except Exception as ex:
2051
            from App import App
2052

    
2053
            message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
2054
                                                           sys.exc_info()[-1].tb_lineno)
2055
            App.mainWnd().addMessage.emit(MessageType.Error, message)
2056
        finally:
2057
            conn.close()
2058

    
2059
        return pap_InfomationItems
2060

    
2061
    def create_database_PAPUpdateInfomation(self):
2062
        """ This method seems to be working now"""
2063
        result = False
2064
        # Creates or opens a file called mydb with a SQLite3 DB
2065
        conn = sqlite3.connect(self.activeDrawing.path)
2066
        with conn:
2067
            try:
2068
                # Get a cursor object
2069
                cursor = conn.cursor()
2070
                query = f"""CREATE TABLE if not exists PAPUploadInformation (
2071
                                            Project_UID        TEXT NOT NULL,
2072
                                            ProjectNo            TEXT,
2073
                                            CalculationCase        TEXT,
2074
                                            CreateDateTime datetime NOT NULL DEFAULT (datetime('now', 'localtime')),
2075
                                            PRIMARY KEY(Project_UID));""";
2076
                cursor.execute(query)
2077
                query = f"""CREATE TABLE if not exists PAPUploadInformationItem (
2078
                                                    Components_UID        TEXT NOT NULL,
2079
                                                Project_UID        TEXT NOT NULL,
2080
                                                ProjectNo        TEXT,
2081
                                                Components_Type        TEXT,
2082
                                                Components_ItemNo        TEXT,
2083
                                                Components_DataCase        TEXT,
2084
                                                PRIMARY KEY(Components_UID,Project_UID));""";
2085
                cursor.execute(query)
2086
            # Catch the exception
2087
            except Exception as ex:
2088
                from App import App
2089

    
2090
                # Roll back any change if something goes wrong
2091
                conn.rollback()
2092

    
2093
                message = 'error occurred({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename,
2094
                                                               sys.exc_info()[-1].tb_lineno)
2095
                App.mainWnd().addMessage.emit(MessageType.Error, message)
2096

    
2097
        return result
2098

    
2099

    
2100

    
2101
    '''
2102
        @brief  getter of activeDrawing
2103
        @author humkyung
2104
        @date   2018.07.07
2105
    '''
2106

    
2107
    @property
2108
    def activeDrawing(self):
2109
        return self._activeDrawing
2110

    
2111
    '''
2112
        @brief  setter of activeDrawing
2113
        @author humkyung
2114
        @date   2018.07.07
2115
    '''
2116

    
2117
    @activeDrawing.setter
2118
    def activeDrawing(self, value):
2119
        self._activeDrawing = value
클립보드 이미지 추가 (최대 크기: 500 MB)