프로젝트

일반

사용자정보

통계
| 개정판:

hytos / HYTOS / HYTOS / AppDocData.py @ a6a2273e

이력 | 보기 | 이력해설 | 다운로드 (131 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

    
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
import numpy as np
18

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

    
24
class Source:
25
    def __init__(self, source):
26
        if type(source) is np.ndarray:
27
            self.source = Image.fromarray(source)
28
        elif type(source) is PngImagePlugin.PngImageFile or type(source) is JpegImagePlugin.JpegImageFile:
29
            self.source = source
30
        elif type(source) is QImage:
31
            self.source = Image.fromqimage(source)
32
        elif type(source) is QPixmap:
33
            self.source = Image.fromqpixmap(source)
34
        
35
    '''
36
        @history    2018.05.18  Jeongwoo    When Parameter [rect] is None, return whole image
37
    '''
38
    def getPyImageOnRect(self, rect = None):
39
        if rect is not None:
40
            return self.source.copy().crop((rect.left(), rect.top(), rect.right(), rect.bottom()))
41
        else:
42
            return self.source.copy()
43

    
44
    def getQImageOnRect(self, rect = None):
45
        image = ImageQt(self.getPyImageOnRect(rect))
46
        return image.convertToFormat(QImage.Format_RGBA8888)
47

    
48
class Config:
49
    def __init__(self, section, key, value):
50
        self.section = section
51
        self.key = key
52
        self.value = value
53

    
54
    '''
55
        @brief  return size value string
56
        @author humkyung
57
        @date   2018.04.24
58
    '''
59
    def sizeValue(self):
60
        return self.inchStr if 'Inch' == self.sizeUnit else self.metricStr
61

    
62
'''
63
    @brief  Pipe color class
64
'''
65
class Color:
66
    def __init__(self, index, red, green, blue):
67
        self.index = index
68
        self.red = red
69
        self.green = green
70
        self.blue = blue
71

    
72
'''
73
    @brief      MessageType
74
    @author     humkyung 
75
    @date       2018.07.31
76
'''
77
class MessageType(Enum):
78
    Normal = 1
79
    Error = 2
80

    
81
class AppDocData(SingletonInstane):
82
    DATABASE = App.NAME + '.db'
83

    
84
    def __init__(self):
85
        from DisplayColors import DisplayColors
86

    
87
        self._imgFilePath = None
88
        self.imgName = None
89
        self.imgWidth = 0
90
        self.imgHeight = 0
91
        self._OCRData = None
92

    
93
        self._areas = []
94
        self.equipments = []
95
        self.lineNos = []
96
        self.lines = []
97
        self.texts = []
98
        self.symbols = []
99
        self.unknowns = []
100
        self.tracerLineNos = []
101
        self.lineIndicators = []
102
        self._colors = None
103
        self._lineNoProperties = None
104
        self._lineTypes = None
105
        self._lineTypeConfigs = None
106
        self._activeDrawing = None
107
        self._titleBlockProperties = None
108
        self.needReOpening = None
109

    
110
        self.configTable = None
111

    
112
    def clearItemList(self, trim):
113
        '''
114
            @brief      clear item list
115
            @author     euisung
116
            @date       2018.11.28
117
        '''
118
        self.equipments.clear()
119
        self.symbols.clear()
120
        self.lineNos.clear()
121
        self.texts.clear()
122
        self.lines.clear()
123
        self.unknowns.clear()
124
        self.lineIndicators.clear()
125
        if trim:
126
            self.tracerLineNos.clear()
127

    
128
    '''
129
        @brief      clear
130
        @author     humkyung
131
        @date       2018.09.06
132
    '''
133
    def clear(self):
134
        self._imgFilePath = None
135
        self.imgName = None
136
        self.imgWidth = 0
137
        self.imgHeight = 0
138

    
139
        self._areas.clear()
140
        self.equipments.clear()
141
        self.lineNos.clear()
142
        self.lines.clear()
143
        self.texts.clear()
144
        self.symbols.clear()
145
        self.unknowns.clear()
146
        self.tracerLineNos.clear()
147
        self.lineIndicators.clear()
148
        self._colors = None
149
        self._lineNoProperties = None
150
        self._lineTypeConfigs = None
151
        self._activeDrawing = None
152
        self._titleBlockProperties = None
153

    
154
    '''
155
        @brief      Get DB file path in ProgramData
156
        @author     Jeongwoo
157
        @date       2018.06.27
158
        @history    2018.06.29  Jeongwoo    Change method to get template db path
159
    '''
160
    def getTemplateDbPath(self):
161
        path = os.path.join(os.getenv('ALLUSERSPROFILE'), App.NAME)
162
        templateDbPath = os.path.join(path, 'Template.db')
163
        return templateDbPath
164

    
165
    def getAppDbPath(self):
166
        """
167
        @brief      Get application DB file path in ProgramData
168
        @author     humkyung
169
        @date       2018.10.01
170
        """
171

    
172
        path = os.path.join(os.getenv('ALLUSERSPROFILE'), App.NAME)
173
        app_database = os.path.join(path, 'App.db')
174
        return app_database 
175

    
176
    '''
177
        @brief  getter of colors 
178
        @author humkyung
179
        @date   2018.06.18
180
    '''
181
    @property
182
    def colors(self):
183
        import random
184

    
185
        if self._colors is None or self._colors == []:
186
            self._colors = []
187
            try:
188
                dbPath = os.path.join(self.getCurrentProject().getDbFilePath() , AppDocData.DATABASE)
189

    
190
                conn = sqlite3.connect(dbPath)
191
                cursor = conn.cursor()
192
                sql = 'SELECT UID,RED,GREEN,BLUE FROM Colors'
193
                cursor.execute(sql)
194
                rows = cursor.fetchall()
195
                for row in rows:
196
                    self._colors.append(Color(int(row[0]), int(row[1]), int(row[2]), int(row[3])))
197
            # Catch the exception
198
            except Exception as ex:
199
                # Roll back any change if something goes wrong
200
                conn.rollback()
201

    
202
                from App import App 
203
                message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
204
                App.mainWnd().addMessage.emit(MessageType.Error, message)
205
            finally:
206
                conn.close()
207

    
208
        return self._colors.pop(random.randrange(0, len(self._colors)))
209

    
210
    '''
211
        @brief  setter of colors
212
        @author humkyung
213
        @date   2018.06.18
214
    '''
215
    @colors.setter
216
    def colors(self, value):
217
        self._colors = value
218

    
219
    '''
220
        @brief      set image file path
221
        @author     humkyung
222
        @date       2018.07.30
223
    '''
224
    def setImgFilePath(self, path):
225
        self._imgFilePath = path
226
        self.imgName = os.path.splitext(os.path.basename(self._imgFilePath))[0]
227

    
228
    '''
229
        @brief  getter of line type configs
230
        @author humkyung
231
        @date   2018.06.28
232
    '''
233
    @property
234
    def lineTypeConfigs(self):
235
        from PyQt5.QtCore import Qt
236

    
237
        if self._lineTypeConfigs is None:
238
            self._lineTypeConfigs = []
239

    
240
            styleMap = [('SolidLine', Qt.SolidLine), ('DashLine', Qt.DashLine), ('DotLine', Qt.DotLine), ('DashDotLine', Qt.DashDotLine), 
241
                ('DashDotDotLine', Qt.DashDotDotLine), ('CustomDashLine', Qt.CustomDashLine)]
242

    
243
            configs = self.getConfigs('LineTypes')
244
            for config in configs:
245
                color, width, _style, transparent = config.value.split(',')
246
                matches = [param for param in styleMap if param[0] == _style]
247
                style = matches[0][1] if matches else Qt.SolidLine
248
                self._lineTypeConfigs.append((config.key, color, int(width), style, float(transparent)))
249
        
250
        return self._lineTypeConfigs
251

    
252
    '''
253
        @brief  setter of line type configs
254
        @author humkyung
255
        @date   2018.06.28
256
    '''
257
    @lineTypeConfigs.setter
258
    def lineTypeConfigs(self, value):
259
        self._lineTypeConfigs = value
260

    
261
    '''
262
        @brief  get line type config of given line type
263
        @author humkyung
264
        @date   2018.06.28
265
    '''
266
    def getLineTypeConfig(self, lineType):
267
        from PyQt5.QtCore import Qt
268

    
269
        matches = [config for config in self.lineTypeConfigs if config[0] == lineType]
270
        return matches[0] if matches else (lineType, '#0000FF', 5, Qt.SolidLine, 50)        
271

    
272
    def setCurrentPidSource(self, image):
273
        self.imgWidth, self.imgHeight = image.size
274

    
275
        self.currentPidSource = Source(image)
276

    
277
    def getCurrentPidSource(self):
278
        return self.currentPidSource
279

    
280
    '''
281
        @brief      Check if data exists or not
282
        @author     Jeongwoo
283
        @date       2018.05.03
284
    '''
285
    def isExistData(self, fieldName, data):
286
        rows = None
287
        try:
288
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
289

    
290
            conn = sqlite3.connect(dbPath)
291
            cursor = conn.cursor()
292
            sql = ""
293
            if isinstance(data, str):
294
                sql = "SELECT * FROM Symbol WHERE " + fieldName + " = '"+ data +"'"
295
            else:
296
                sql = "SELECT * FROM Symbol WHERE " + fieldName + " = "+ str(data) +""
297
            cursor.execute(sql)
298
            rows = cursor.fetchall()
299
        # Catch the exception
300
        except Exception as ex:
301
            # Roll back any change if something goes wrong
302
            conn.rollback()
303
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
304
        finally:
305
            conn.close()
306
            if rows is not None and len(rows) > 0:
307
                return True
308
            else:
309
                return False
310

    
311
    '''
312
        @brief      Check if exist file name or not
313
        @author     Jeongwoo
314
        @date       2018.05.03
315
    '''
316
    def isExistFileName(self, name):
317
        rows = None
318
        try:
319
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
320
            conn = sqlite3.connect(dbPath)
321
            cursor = conn.cursor()
322
            sql = "SELECT * FROM Symbol WHERE name = '"+ name +"'"
323
            cursor.execute(sql)
324
            rows = cursor.fetchall()
325
        # Catch the exception
326
        except Exception as ex:
327
            # Roll back any change if something goes wrong
328
            conn.rollback()
329
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
330
        finally:
331
            conn.close()
332
            if rows is not None and len(rows) > 0:
333
                return True
334
            else:
335
                return False
336

    
337
    '''
338
        @brief      Insert new symbol into Symbol Table, Moved from SG_DbHelper
339
        @author     Jeongwoo
340
        @date       2018.05.03
341
    '''
342
    def insertSymbol(self, symbol):
343
        isAdded = False
344
        try:
345
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
346
            conn = sqlite3.connect(dbPath)
347
            
348
            INSERT_SYMBOL_SQL = """
349
                INSERT INTO Symbol(name, SymbolType_UID, threshold, minMatchPoint, isDetectOrigin, rotationCount, ocrOption, isContainChild, originalPoint, connectionPoint, baseSymbol, additionalSymbol, isExceptDetect, hasInstrumentLabel, width, height, flip) 
350
                VALUES(?, (select UID from SymbolType where Type=?), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);
351
            """
352

    
353
            cursor = conn.cursor()
354
            query = ( symbol.getName(), symbol.getType(), symbol.getThreshold()
355
                           , symbol.getMinMatchCount(), symbol.getIsDetectOnOrigin(), symbol.getRotationCount()
356
                           , symbol.getOcrOption(), symbol.getIsContainChild()
357
                           , symbol.getOriginalPoint(), symbol.getConnectionPoint()
358
                           , symbol.getBaseSymbol(), symbol.getAdditionalSymbol(), symbol.getIsExceptDetect(), symbol.getHasInstrumentLabel()
359
                           , symbol.width, symbol.height, symbol.detectFlip)
360
            cursor.execute(INSERT_SYMBOL_SQL, query)
361
            conn.commit()
362
            isAdded = True
363
        # Catch the exception
364
        except Exception as ex:
365
            # Roll back any change if something goes wrong
366
            conn.rollback()
367
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
368
        finally:
369
            conn.close()
370
            return (isAdded, symbol.getType(), symbol.getName(), symbol.getPath())
371

    
372
    '''
373
        @brief      Update symbol in Symbol Table, Moved from SG_DbHelper
374
        @author     Jeongwoo
375
        @date       2018.05.03
376
    '''
377
    def updateSymbol(self, symbol):
378
        isUpdated = False
379
        try:
380
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
381
            conn = sqlite3.connect(dbPath)
382
            
383
            UPDATE_SYMBOL_SQL = """
384
                UPDATE Symbols
385
                   SET name = ?
386
                     , originalPoint = ?
387
                     , connectionPoint = ?
388
                 WHERE uid = ?
389
            """
390
            
391
            cursor = conn.cursor()
392
            query = (symbol.getName(), symbol.getOriginalPoint(), symbol.getConnectionPoint(), symbol.getUid())
393
            cursor.execute(UPDATE_SYMBOL_SQL, query)
394
            conn.commit()
395
            isUpdated = True
396
        # Catch the exception
397
        except Exception as ex:
398
            # Roll back any change if something goes wrong
399
            conn.rollback()
400
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
401
        finally:
402
            conn.close()
403
            return (isUpdated, symbol.getType(), symbol.getName(), symbol.getPath())
404

    
405
    '''
406
        @brief      Get Detecting Target Symbol List (Field 'isExceptDetect' == False(0))
407
        @author     Jeongwoo
408
        @date       18.04.24
409
        @history    humkyung 2018.06.28 select symbol order by threshold descending
410
    '''
411
    def getTargetSymbolList(self):
412
        targetSymbolList = []
413

    
414
        try:
415
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
416

    
417
            conn = sqlite3.connect(dbPath)
418
            cursor = conn.cursor()
419
            #sql = """SELECT a.UID,a.Name,b.Type,a.Threshold,a.MinMatchPoint,a.IsDetectOrigin,a.RotationCount,a.OCROption,a.IsContainChild,a.OriginalPoint,a.ConnectionPoint,
420
            #        a.BaseSymbol,a.AdditionalSymbol,a.IsExceptDetect,a.HasInstrumentLabel,a.flip FROM Symbol a inner join SymbolType b on a.SymbolType_UID=b.UID WHERE a.IsExceptDetect = 0 order by width * height desc"""
421

    
422
            sql = """select s.UID
423
                          , s.Name
424
                          , t.Category
425
                          , t.Type
426
                          , s.OriginalPoint
427
                          , s.ConnectionPoint
428
                       from Symbols s 
429
                      inner join SymbolType t
430
                         on s.SymbolType_UID = t.UID"""
431

    
432
            try:
433
                cursor.execute(sql)
434
                rows = cursor.fetchall()
435
                for row in rows:
436
                    sym = symbol.SymbolBase(row[0], row[1], row[2], row[3], row[4], row[5])
437
                    targetSymbolList.append(sym)
438
            except Exception as ex:
439
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
440
        finally:
441
            conn.close()
442

    
443
        return targetSymbolList
444

    
445
    '''
446
        @brief  build application database
447
        @author humkyung
448
        @date   2018.04.20
449
    '''
450
    def buildAppDatabase(self):
451
        try:
452
            path = os.path.join(os.getenv('ALLUSERSPROFILE'), App.NAME)
453
            appDatabaseFilePath = os.path.join(path, 'App.db')
454

    
455
            # Creates or opens a file called mydb with a SQLite3 DB
456
            conn = sqlite3.connect(appDatabaseFilePath)
457
            with conn:
458
                # Get a cursor object
459
                cursor = conn.cursor()
460

    
461
                sqlFiles = ['App.sql']
462
                for sqlFile in sqlFiles:
463
                    filePath = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'Scripts', sqlFile)
464
                    try:
465
                        file = QFile(filePath)
466
                        file.open(QFile.ReadOnly)
467
                        sql = file.readAll()
468
                        sql = str(sql, encoding='utf8')
469
                        cursor.executescript(sql)
470
                    finally:
471
                        file.close()
472
                conn.commit()
473
        # Catch the exception
474
        except Exception as ex:
475
            # Roll back any change if something goes wrong
476
            conn.rollback()
477
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
478

    
479
    '''
480
        @brief  load app style
481
        @author humkyung
482
        @date   2018.04.20
483
    '''
484
    def loadAppStyle(self):
485
        style = 'Fusion'
486

    
487
        path = os.path.join(os.getenv('ALLUSERSPROFILE'), App.NAME)
488
        if not os.path.exists(path): os.makedirs(path)
489

    
490
        self.buildAppDatabase()
491
        try:
492
            appDatabaseFilePath = os.path.join(path, 'App.db')
493
            # Creates or opens a file called mydb with a SQLite3 DB
494
            conn = sqlite3.connect(appDatabaseFilePath)
495
            # Get a cursor object
496
            cursor = conn.cursor()
497

    
498
            sql = "select Value from Configuration where Section='App' and Key='Style'" 
499
            cursor.execute(sql)
500
            rows = cursor.fetchall()
501
            style = rows[0][0] if 1 == len(rows) else 'Fusion'
502
        # Catch the exception
503
        except Exception as ex:
504
            # Roll back any change if something goes wrong
505
            conn.rollback()
506
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
507
        finally:
508
            # Close the db connection
509
            conn.close()
510

    
511
        return style
512

    
513
    '''
514
        @brief  load app styles and then return a list
515
        @author humkyung
516
        @date   2018.04.20
517
    '''
518
    def loadAppStyles(self):
519
        styles = []
520

    
521
        try:
522
            self.buildAppDatabase()
523

    
524
            path = os.path.join(os.getenv('ALLUSERSPROFILE'), App.NAME)
525
            appDatabaseFilePath = os.path.join(path, 'App.db')
526

    
527
            # Creates or opens a file called mydb with a SQLite3 DB
528
            conn = sqlite3.connect(appDatabaseFilePath)
529
            # Get a cursor object
530
            cursor = conn.cursor()
531

    
532
            sql = 'select UID,Value from Styles'
533
            cursor.execute(sql)
534
            rows = cursor.fetchall()
535
            for row in rows: styles.append(row[1])
536
            if 0 == len(rows): rows.append('fusion')
537
        # Catch the exception
538
        except Exception as ex:
539
            # Roll back any change if something goes wrong
540
            conn.rollback()
541
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
542
        finally:
543
            # Close the db connection
544
            conn.close()
545

    
546
        return styles
547

    
548
    '''
549
        @brief  Set current Project
550
        @history    2018.06.27  Jeongwoo    If DB file is not, copy DB file from ProgramData
551
    '''
552
    def setCurrentProject(self, project):
553
        self.project = project
554
        try:
555
            # Creates or opens a file called mydb with a SQLite3 DB
556
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath() , App.NAME + '.db')
557
            
558
            if not os.path.isfile(dbPath):
559
                templatePath = self.getTemplateDbPath()
560
                templateFile = QFile(templatePath)
561
                templateFile.copy(dbPath)
562
            else:
563
                try:
564
                    conn = sqlite3.connect(dbPath)
565
                    # Get a cursor object
566
                    cursor = conn.cursor()
567

    
568
                    fileNames = os.listdir(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'Scripts'))
569
                    for fileName in fileNames:
570
                        if fileName.endswith(".sql") and (1 == len(os.path.splitext(fileName)[0].split('.'))):
571
                            try:
572
                                file = QFile(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'Scripts', fileName))
573
                                file.open(QFile.ReadOnly)
574
                                sql = file.readAll()
575
                                sql = str(sql, encoding='utf8')
576
                                cursor.executescript(sql)
577
                            finally:
578
                                file.close()
579
                    conn.commit()
580
                except Exception as ex:
581
                    print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
582
                finally:
583
                    conn.close()
584
        # Catch the exception
585
        except Exception as ex:
586
            # Roll back any change if something goes wrong
587
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
588
        finally:
589
            pass
590

    
591

    
592
    @property
593
    def border_file_path(self):
594
        """ return border file path """
595

    
596
        path = os.path.join(os.getenv('ALLUSERSPROFILE'), App.NAME)
597
        return os.path.join(path, 'Border.png')
598

    
599
    @property
600
    def symbol_file_path(self):
601
        """ return svg symbol file path """
602

    
603
        path = os.path.join(os.getenv('ALLUSERSPROFILE'), App.NAME)
604
        return os.path.join(path, 'svg')
605

    
606
    '''
607
        @brief  Get current Project
608
    '''
609
    def getCurrentProject(self):
610
        return self.project
611

    
612
    '''
613
        @brief      return project database path
614
        @history    humkyung 2018.04.19 return Project.db in Program Data folder instead of PROJECT_DB_PATH variable
615
    '''
616
    def getPrjDatabasePath(self):
617
        path = os.path.join(os.getenv('ALLUSERSPROFILE'), App.NAME)
618
        if not os.path.exists(path): os.makedirs(path)
619

    
620
        prjDatabaseFilePath = os.path.join(path, 'Project.db')
621
        try:
622
            # Creates or opens a file called mydb with a SQLite3 DB
623
            conn = sqlite3.connect(prjDatabaseFilePath)
624
            # Get a cursor object
625
            cursor = conn.cursor()
626

    
627
            filePath = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'Scripts', 'Project.Projects.sql')
628
            try:
629
                file = QFile(filePath)
630
                file.open(QFile.ReadOnly)
631
                sql = file.readAll()
632
                sql = str(sql, encoding='utf8')
633
                cursor.executescript(sql)
634
            finally:
635
                file.close()
636
            conn.commit()
637
        # Catch the exception
638
        except Exception as ex:
639
            # Roll back any change if something goes wrong
640
            conn.rollback()
641
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
642
        finally:
643
            # Close the db connection
644
            conn.close()
645
        
646
        return prjDatabaseFilePath
647

    
648
    def getErrorItemSvgPath(self):
649
        '''
650
            @brief  return error item svg path
651
            @author euisung
652
            @date   2019.04.02
653
        '''
654
        return os.path.join(os.getenv('ALLUSERSPROFILE'), App.NAME, 'Explode.svg')
655

    
656
    def updateTitleBlockProperties(self, titleBlockProps):
657
        '''
658
            @brief  update title block properties
659
            @author euisung
660
            @date   2018.11.09
661
        '''
662
        try:
663
            for titleBlockProp in titleBlockProps:
664
                titleBlockProp[1] = self.imgName + '!@!' + titleBlockProp[1]
665
            originTitleBlockProps = self.getTitleBlockProperties()
666
            deletedTitleBlockProps = []
667
            for originTitleBlockProp in originTitleBlockProps:
668
                for titleBlockProp in titleBlockProps:
669
                    # uid compare for determine delete props
670
                    if originTitleBlockProp[0] == titleBlockProp[0]:
671
                        break
672
                deletedTitleBlockProps.append(originTitleBlockProp[0])
673
            
674
            # Creates or opens a file called mydb with a SQLite3 DB
675
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
676
            conn = sqlite3.connect(dbPath)
677
            # Get a cursor object
678
            cursor = conn.cursor()
679

    
680
            for deletedTitleBlockProp in deletedTitleBlockProps:
681
                sql = "delete from TitleBlockProperties where UID='{}'".format(deletedTitleBlockProp)
682
                cursor.execute(sql)
683

    
684
            for titleBlockProp in titleBlockProps:
685
                sql = "insert or replace into TitleBlockProperties values(?,?,?)"
686
                param = (titleBlockProp[0], titleBlockProp[1], titleBlockProp[2]) # uid, name, area
687
                cursor.execute(sql, param)
688
            conn.commit()
689
        # Catch the exception
690
        except Exception as ex:
691
            # Roll back any change if something goes wrong
692
            conn.rollback()
693
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
694
        finally:
695
            # Close the db connection
696
            conn.close()
697

    
698
        self._titleBlockProperties = None
699
    
700
    def getTitleBlockProperties(self):
701
        '''
702
            @brief  return title block properties
703
            @author euisung
704
            @date   2018.11.09
705
        '''
706
        res = None
707
        if True:#self._titleBlockProperties is None:
708
            try:
709
                self._titleBlockProperties = []
710

    
711
                # Creates or opens a file called mydb with a SQLite3 DB
712
                dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
713
                db = sqlite3.connect(dbPath)
714
                # Get a cursor object
715
                cursor = db.cursor()
716

    
717
                sql = "select UID, Name, AREA from TitleBlockProperties" 
718
                cursor.execute(sql)
719
                rows = cursor.fetchall()
720
                for row in rows:
721
                    if row[1].split('!@!')[0] != self.imgName:
722
                        continue
723
                    else:
724
                        attr = []
725
                        attr.append(row[0]) # uid
726
                        attr.append(row[1].split('!@!')[1]) # name
727
                        attr.append(row[2]) # area
728
                        self._titleBlockProperties.append(attr)
729
                
730
                res = self._titleBlockProperties
731
            # Catch the exception
732
            except Exception as ex:
733
                # Roll back any change if something goes wrong
734
                db.rollback()
735
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
736
            finally:
737
                # Close the db connection
738
                db.close()
739
        else:
740
            res = self._titleBlockProperties
741

    
742
        return res
743

    
744
    def clearLineNoProperties(self):
745
        self._lineNoProperties = None
746

    
747
    '''
748
        @brief  return line properties
749
        @author humkyung
750
        @date   2018.04.09
751
    '''
752
    def getLineProperties(self):
753
        from SymbolAttr import SymbolAttr
754

    
755
        res = None
756
        if self._lineNoProperties is None:
757
            try:
758
                self._lineNoProperties = []
759

    
760
                # Creates or opens a file called mydb with a SQLite3 DB
761
                dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
762
                db = sqlite3.connect(dbPath)
763
                # Get a cursor object
764
                cursor = db.cursor()
765

    
766
                sql = "select UID, Name, DisplayName, Type, LimitNumber, [index] from LineProperties order by [index]" 
767
                cursor.execute(sql)
768
                rows = cursor.fetchall()
769
                for row in rows:
770
                    attr = SymbolAttr()
771
                    attr.UID = row[0]
772
                    attr.Attribute = row[1]
773
                    attr.DisplayAttribute = row[2]
774
                    attr.AttributeType = row[3]
775
                    attr.Length = row[4]
776
                    self._lineNoProperties.append(attr)
777
                
778
                res = self._lineNoProperties
779
            # Catch the exception
780
            except Exception as ex:
781
                # Roll back any change if something goes wrong
782
                db.rollback()
783
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
784
            finally:
785
                # Close the db connection
786
                db.close()
787
        else:
788
            res = self._lineNoProperties
789

    
790
        return res
791

    
792
    '''
793
        @brief  return line properties
794
        @author humkyung
795
        @date   2018.04.09
796
    '''
797
    def getLinePropertiesByUID(self, UID):
798
        from SymbolAttr import SymbolAttr
799

    
800
        res = []
801
        try:
802
            # Creates or opens a file called mydb with a SQLite3 DB
803
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
804
            db = sqlite3.connect(dbPath)
805
            # Get a cursor object
806
            cursor = db.cursor()
807

    
808
            sql = "select UID, Name, DisplayName, Type, LimitNumber, [index] from LineProperties where uid = '{}'".format(UID)
809
            cursor.execute(sql)
810
            rows = cursor.fetchall()
811
            for row in rows:
812
                attr = SymbolAttr()
813
                attr.UID = row[0]
814
                attr.Attribute = row[1]
815
                attr.DisplayAttribute = row[2]
816
                attr.AttributeType = row[3]
817
                attr.Length = row[4]
818
                res.append(attr)
819
        # Catch the exception
820
        except Exception as ex:
821
            # Roll back any change if something goes wrong
822
            db.rollback()
823
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
824
        finally:
825
            # Close the db connection
826
            db.close()
827

    
828
        return res
829

    
830
    def getRoughness(self):
831
        res = []
832
        try:
833
            # Creates or opens a file called mydb with a SQLite3 DB
834
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
835
            db = sqlite3.connect(dbPath)
836
            db.row_factory = sqlite3.Row
837
            # Get a cursor object
838
            cursor = db.cursor()
839

    
840
            sql = "select UID, Material, Meter, Inch, Feet, Milimeter from Roughness" 
841
            cursor.execute(sql)
842
            rows = cursor.fetchall()
843
            for row in rows:                
844
                res.append((row[0], row[1], row[2], row[3], row[4], row[5]))
845
        # Catch the exception
846
        except Exception as ex:
847
            # Roll back any change if something goes wrong
848
            db.rollback()
849
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
850
        finally:
851
            # Close the db connection
852
            db.close()
853

    
854
        return res
855

    
856
    def getInsideDiameter(self, nominaldiameter_uid, schedule_uid):
857
        res = []
858
        try:
859
            # Creates or opens a file called mydb with a SQLite3 DB
860
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
861
            db = sqlite3.connect(dbPath)
862
            # Get a cursor object
863
            cursor = db.cursor()
864

    
865
            sql = """select UID
866
                          , Milimeter
867
                          , Inch 
868
                       from InsideDiameter
869
                      where NominalDiameter_UID = ?
870
                        and Schedule_UID = ?"""
871

    
872
            param = (nominaldiameter_uid, schedule_uid)
873
            cursor.execute(sql, param)
874
            rows = cursor.fetchall()
875
            for row in rows:                
876
                res.append((row[0], row[1], row[2]))
877
        # Catch the exception
878
        except Exception as ex:
879
            # Roll back any change if something goes wrong
880
            db.rollback()
881
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
882
        finally:
883
            # Close the db connection
884
            db.close()
885

    
886
        return res
887

    
888
    def getSchedule(self):
889
        res = []
890
        try:
891
            # Creates or opens a file called mydb with a SQLite3 DB
892
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
893
            db = sqlite3.connect(dbPath)
894
            # Get a cursor object
895
            cursor = db.cursor()
896

    
897
            sql = "select UID, No from Schedule" 
898
            cursor.execute(sql)
899
            rows = cursor.fetchall()
900
            for row in rows:                
901
                res.append((row[0], row[1]))
902
        # Catch the exception
903
        except Exception as ex:
904
            # Roll back any change if something goes wrong
905
            db.rollback()
906
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
907
        finally:
908
            # Close the db connection
909
            db.close()
910

    
911
        return res
912

    
913

    
914

    
915
    def getNominalDiameter(self):
916
        
917
        res = []
918
        try:
919
            # Creates or opens a file called mydb with a SQLite3 DB
920
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
921
            db = sqlite3.connect(dbPath)
922
            # Get a cursor object
923
            cursor = db.cursor()
924

    
925
            sql = "select UID, Milimeter, Inch from NominalDiameter" 
926
            cursor.execute(sql)
927
            rows = cursor.fetchall()
928
            for row in rows:                
929
                res.append((row[0], row[1], row[2]))
930
        # Catch the exception
931
        except Exception as ex:
932
            # Roll back any change if something goes wrong
933
            db.rollback()
934
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
935
        finally:
936
            # Close the db connection
937
            db.close()
938

    
939
        return res
940

    
941
    '''
942
        @brief  return line types 
943
        @author humkyung
944
        @date   2018.06.27
945
    '''
946
    def getLineTypes(self):
947
        from LineTypeConditions import LineTypeConditions
948

    
949
        res = []
950
        try:
951
            # Creates or opens a file called mydb with a SQLite3 DB
952
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
953
            db = sqlite3.connect(dbPath)
954
            # Get a cursor object
955
            cursor = db.cursor()
956

    
957
            sql = "select UID,Name,Type1,Conditions1,Type2,Conditions2 from LineTypes order by Name" 
958
            cursor.execute(sql)
959
            rows = cursor.fetchall()
960
            for row in rows:
961
                line_type = LineTypeConditions(row[0], row[1])
962
                line_type._conditions[0][0] = row[2]
963
                line_type._conditions[0][1] = row[3]
964
                line_type._conditions[1][0] = row[4]
965
                line_type._conditions[1][1] = row[5]
966
                res.append(line_type)
967
        # Catch the exception
968
        except Exception as ex:
969
            # Roll back any change if something goes wrong
970
            db.rollback()
971
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
972
        finally:
973
            # Close the db connection
974
            db.close()
975

    
976
        return res
977

    
978
    '''
979
        @brief      Insert New Project Info
980
        @author     Jeongwoo
981
        @date       2018.04.06
982
        @history    humkyung 2018.04.19 use getPrjDatabasePath function instead of PROJECT_DB_PATH variable
983
    '''
984
    def insertProjectInfo(self, desc, dir):
985
        try:
986
            prjDatabaseFilePath = self.getPrjDatabasePath()
987
            conn = sqlite3.connect(prjDatabaseFilePath)
988
            folderName = dir.split('/')[-1]
989
            if folderName:
990
                nowDate = datetime.datetime.now().strftime('%Y.%m.%d %H:%M')
991
                sql = "insert or replace into Projects(Name, [Desc], Path, CreatedDate, UpdatedDate) values(?, ?, ?, ?, ?)"
992
                param = (folderName, desc, dir, nowDate, nowDate)
993
    
994
                cursor = conn.cursor()
995
                cursor.execute(sql, param)
996
                conn.commit()
997
            else:
998
                print("Empty folder name")
999
        except Exception as ex:
1000
            # Roll back any change if something goes wrong
1001
            conn.rollback()
1002
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1003
        finally:
1004
            conn.close()
1005

    
1006
    def removeProjectInfo(self, targetProject):
1007
        '''
1008
        @brief      Remove Project Info
1009
        @author     Euisung
1010
        @date       2019.01.28
1011
        '''
1012
        try:
1013
            prjDatabaseFilePath = self.getPrjDatabasePath()
1014
            conn = sqlite3.connect(prjDatabaseFilePath)
1015
            sql = "delete from Projects where Id = '{}'".format(targetProject.id)
1016
            cur = conn.cursor()
1017
            cur.execute(sql)
1018
            conn.commit()
1019
        except Exception as ex:
1020
            # Roll back any change if something goes wrong
1021
            conn.rollback()
1022
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1023
        finally:
1024
            conn.close()
1025

    
1026
    '''
1027
        @brief      Update Project UpdatedDate Field
1028
        @author     Jeongwoo
1029
        @date       2018.04.06
1030
        @history    humkyung 2018.04.19 use getPrjDatabasePath function instead of PROJECT_DB_PATH variable
1031
    '''
1032
    def updateProjectUpdatedDate(self, id, desc):
1033
        try:
1034
            prjDatabaseFilePath = self.getPrjDatabasePath()
1035
            conn = sqlite3.connect(prjDatabaseFilePath)
1036
            nowDate = datetime.datetime.now().strftime('%Y.%m.%d %H:%M')
1037
            sql = '''
1038
                UPDATE Projects
1039
                SET UpdatedDate = ?,[Desc]=? 
1040
                WHERE Id = ?
1041
            '''
1042
            cur = conn.cursor()
1043
            cur.execute(sql, (nowDate, desc, id))
1044
            conn.commit()
1045
        except Exception as ex:
1046
            # Roll back any change if something goes wrong
1047
            conn.rollback()
1048
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1049
        finally:
1050
            conn.close()
1051

    
1052
    '''
1053
        @brief  get project list from database
1054
        @history    humkyung 2018.04.18 add only project which's project exists
1055
    '''
1056
    def getProjectList(self):
1057
        from Project import Project
1058

    
1059
        projectList = []
1060

    
1061
        try:
1062
            conn = sqlite3.connect(self.getPrjDatabasePath())
1063
            cursor = conn.cursor()
1064
            sql = 'SELECT id,name,[desc],path,createddate,updateddate  FROM Projects ORDER BY UpdatedDate DESC'
1065
            try:
1066
                cursor.execute(sql)
1067
                rows = cursor.fetchall()
1068
                for row in rows:
1069
                    if os.path.isdir(row[3]):   # check if folder exists
1070
                        projectList.append(Project(row[0], row[1], desc=row[2], path=row[3], createDate=row[4], updateDate=row[5]))
1071
            except Exception as ex:
1072
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1073
        finally:
1074
            conn.close()
1075

    
1076
        return projectList
1077

    
1078
    '''
1079
        @brief  get sliding window size
1080
        @author humkyung
1081
    '''
1082
    def getSlidingWindowSize(self):
1083
        res = [10,15]
1084
        try:
1085
            configs = self.getConfigs('Sliding Window')
1086
            for config in configs:
1087
                if config.key == 'Width':
1088
                    res[0] = int(config.value)
1089
                elif config.key == 'Height':
1090
                    res[1] = int(config.value)
1091
        # Catch the exception
1092
        except Exception as ex:
1093
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1094
        
1095
        return res
1096

    
1097
    '''
1098
        @brief  get line no configuration
1099
        @author humkyung
1100
        @date   2018.04.16
1101
    '''
1102
    def getLineNoConfiguration(self):
1103
        res = None
1104
        try:
1105
            # Creates or opens a file called mydb with a SQLite3 DB
1106
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
1107
            conn = sqlite3.connect(dbPath)
1108
            # Get a cursor object
1109
            cursor = conn.cursor()
1110

    
1111
            delimiter = None
1112
            sql = "select * from configuration where section='Line No' and key='Delimiter"
1113
            cursor.execute(sql)
1114
            rows = cursor.fetchall()
1115
            if len(rows) == 1:
1116
                delimiter = rows[0][2]
1117

    
1118
            if delimiter is not None:
1119
                sql = "select * from configuration where section='Line No' and key='Configuration'"
1120
                cursor.execute(sql)
1121
                rows = cursor.fetchall()
1122
                if len(rows) == 1:
1123
                    res = rows[0][2].split(delimiter)
1124
        # Catch the exception
1125
        except Exception as ex:
1126
            # Roll back any change if something goes wrong
1127
            conn.rollback()
1128
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1129
        finally:
1130
            # Close the db connection
1131
            conn.close()
1132
        
1133
        return res
1134

    
1135
    '''
1136
        @brief  get area list
1137
        @author humkyung
1138
        @history    euisung     2018.11.20 (0,0),(0,0) process add
1139
    '''
1140
    def getAreaList(self):
1141
        from Area import Area
1142

    
1143
        if len(self._areas) == 0:
1144
            try:
1145
                # Creates or opens a file called mydb with a SQLite3 DB
1146
                dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
1147
                conn = sqlite3.connect(dbPath)
1148
                # Get a cursor object
1149
                cursor = conn.cursor()
1150

    
1151
                sql = "select * from configuration where section='Area'"
1152
                cursor.execute(sql)
1153
                rows = cursor.fetchall()
1154
                for row in rows:
1155
                    name = row[1]
1156
                    area = Area(name)
1157
                    area.parse(row[2])
1158
                    self._areas.append(area)
1159
            # Catch the exception
1160
            except Exception as ex:
1161
                # Roll back any change if something goes wrong
1162
                conn.rollback()
1163
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1164
            finally:
1165
                # Close the db connection
1166
                conn.close()
1167
        
1168
        return self._areas 
1169

    
1170
    '''
1171
        @brief  get area of given name
1172
        @author humkyung
1173
        @date   2018.04.07
1174
    '''
1175
    def getArea(self, name):
1176
        areas = self.getAreaList()
1177
        matches = [area for area in areas if area.name==name]
1178
        if 1 == len(matches) and matches[0].height is not 0 and matches[0].width is not 0:
1179
            return matches[0]
1180

    
1181
        return None
1182

    
1183
    '''
1184
        @brief  get configurations
1185
        @author humkyung
1186
        @date   2018.04.16
1187
        @history kyouho 2018.07.09 change query method
1188
    '''
1189
    '''
1190
    def getConfigs(self, section, key=None):
1191
        res = []
1192

1193
        try:
1194
            # Creates or opens a file called mydb with a SQLite3 DB
1195
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
1196
            conn = sqlite3.connect(dbPath)
1197
            # Get a cursor object
1198
            cursor = conn.cursor()
1199

1200
            if key is not None:
1201
                sql = "select * from configuration where section=? and key=?"
1202
                param = (section, key)
1203
            else:
1204
                sql = "select * from configuration where section=?"
1205
                param = (section,)
1206

1207
            cursor.execute(sql, param)
1208
            rows = cursor.fetchall()
1209
            for row in rows:
1210
                res.append(Config(row[0], row[1], row[2]))
1211
        # Catch the exception
1212
        except Exception as ex:
1213
            # Roll back any change if something goes wrong
1214
            conn.rollback()
1215
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1216
        finally:
1217
            # Close the db connection
1218
            conn.close()
1219

1220
        return res
1221
        '''
1222
    def getConfigs(self, section, key=None):        
1223
        res = []
1224

    
1225
        if self.configTable is None:
1226
            self.configTable = []
1227
            try:
1228
                # Creates or opens a file called mydb with a SQLite3 DB
1229
                dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
1230
                conn = sqlite3.connect(dbPath)
1231
                # Get a cursor object
1232
                cursor = conn.cursor()
1233

    
1234
                sql = "select Section, Key, Value from configuration"
1235
            
1236
                cursor.execute(sql)
1237
                rows = cursor.fetchall()
1238
                for row in rows:
1239
                    self.configTable.append(Config(row[0], row[1], row[2]))
1240
                # Catch the exception
1241
            except Exception as ex:
1242
                # Roll back any change if something goes wrong
1243
                conn.rollback()
1244
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1245
            finally:
1246
                # Close the db connection
1247
                conn.close()
1248

    
1249
        if key is not None:
1250
            for con in self.configTable:
1251
                if con.section == section and con.key == key:
1252
                    res.append(con)
1253
        else:
1254
            for con in self.configTable:
1255
                if con.section == section:
1256
                    res.append(con)
1257

    
1258
        return res
1259

    
1260
    def getAppConfigs(self, section, key=None):
1261
        """
1262
            @brief  get application configurations
1263
            @author humkyung
1264
            @date   2018.11.01
1265
        """
1266

    
1267
        res = []
1268

    
1269
        try:
1270
            # Creates or opens a file called mydb with a SQLite3 DB
1271
            dbPath = self.getAppDbPath()
1272
            conn = sqlite3.connect(dbPath)
1273
            # Get a cursor object
1274
            cursor = conn.cursor()
1275

    
1276
            if key is not None:
1277
                sql = "select * from configuration where section=? and key=?"
1278
                param = (section, key)
1279
            else:
1280
                sql = "select * from configuration where section=?"
1281
                param = (section,)
1282

    
1283
            cursor.execute(sql, param)
1284
            rows = cursor.fetchall()
1285
            for row in rows:
1286
                res.append(Config(row[0], row[1], row[2]))
1287
        # Catch the exception
1288
        except Exception as ex:
1289
            # Roll back any change if something goes wrong
1290
            conn.rollback()
1291
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1292
        finally:
1293
            # Close the db connection
1294
            conn.close()
1295

    
1296
        return res
1297

    
1298
    '''
1299
        @brief      save configurations
1300
        @author     humkyung
1301
        @date       2018.04.16
1302
        @history    humkyung 2018.07.03 replace ' with " if value has '
1303
                    kyouho 2018.07.09 change query method
1304
    '''
1305
    def saveConfigs(self, configs):
1306
        import uuid
1307
        
1308
        try:
1309
            # Creates or opens a file called mydb with a SQLite3 DB
1310
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
1311
            conn = sqlite3.connect(dbPath, isolation_level=None)
1312
            # Get a cursor object
1313
            cursor = conn.cursor()
1314

    
1315
            for config in configs:
1316
                if type(config) is Config:
1317
                    value = config.value
1318
                    if type(value) is str and "'" in value:
1319
                        value = value.replace("'", "''")
1320

    
1321
                    sql = "insert or replace into configuration values(?,?,?,?)"
1322
                    param = (str(uuid.uuid4()), config.section, config.key, value)                    
1323

    
1324
                    cursor.execute(sql, param)
1325
                elif hasattr(config, 'toSql'):
1326
                    sql = config.toSql()
1327
                    if type(sql) is list:
1328
                        for item in sql:
1329
                            if item is not None and 2 == len(item):
1330
                                cursor.execute(item[0], item[1])
1331
                    else:
1332
                        if sql is not None and 2 == len(sql):
1333
                            cursor.execute(sql[0], sql[1])
1334

    
1335
            conn.commit()
1336
        # Catch the exception
1337
        except Exception as ex:
1338
            # Roll back any change if something goes wrong
1339
            conn.rollback()
1340
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1341
        finally:
1342
            # Close the db connection
1343
            conn.close()
1344

    
1345
    def saveAppConfigs(self, configs):
1346
        """
1347
        @brief      save application configurations
1348
        @author     humkyung
1349
        @date       2018.10.01
1350
        """
1351

    
1352
        try:
1353
            # Creates or opens a file called mydb with a SQLite3 DB
1354
            dbPath = self.getAppDbPath()
1355
            conn = sqlite3.connect(dbPath)
1356
            # Get a cursor object
1357
            cursor = conn.cursor()
1358

    
1359
            for config in configs:
1360
                value = config.value
1361
                if type(value) is str and "'" in value:
1362
                    value = value.replace("'", "''")
1363

    
1364
                sql = "insert or replace into configuration values(?,?,?)"
1365
                param = (config.section, config.key, value)
1366

    
1367
                cursor.execute(sql, param)
1368
            conn.commit()
1369
        # Catch the exception
1370
        except Exception as ex:
1371
            # Roll back any change if something goes wrong
1372
            conn.rollback()
1373
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1374
        finally:
1375
            # Close the db connection
1376
            conn.close()
1377

    
1378

    
1379
    def initializeDataByDrawingUID(self, uid):
1380
        try:
1381
            # Creates or opens a file called mydb with a SQLite3 DB
1382
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
1383
            conn = sqlite3.connect(dbPath)
1384
            # Get a cursor object
1385
            cursor = conn.cursor()
1386

    
1387
            # 0. Delete Points
1388
            sql = "delete from Points where Components_UID in (select UID from Components where Drawings_UID = '{}')".format(uid)
1389
            cursor.execute(sql)
1390

    
1391
            # 1. Delete HMB
1392
            sql = "delete from HMB where Components_UID in (select UID from Components where Drawings_UID = '{}')".format(uid)
1393
            cursor.execute(sql)
1394

    
1395
            # 2. Delete Components
1396
            sql = "delete from Components where Drawings_UID='{}'".format(uid)
1397
            cursor.execute(sql)            
1398
            
1399
            conn.commit()
1400
        # Catch the exception
1401
        except Exception as ex:
1402
            # Roll back any change if something goes wrong
1403
            conn.rollback()
1404
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1405
        finally:
1406
            # Close the db connection
1407
            conn.close()
1408

    
1409
    def deleteDrawingByUID(self, drawing):
1410
        """ delete given drawing """
1411
        conn = sqlite3.connect(self.getAppDbPath())
1412
        with conn:
1413
            try:
1414
                # Get a cursor object
1415
                cursor = conn.cursor()
1416

    
1417
                sql = 'delete from Drawings where UID=?'
1418
                param = (drawing.UID,)
1419
                cursor.execute(sql, param)
1420
                
1421
                conn.commit()
1422
            # Catch the exception
1423
            except Exception as ex:
1424
                # Roll back any change if something goes wrong
1425
                conn.rollback()
1426
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1427

    
1428
    '''
1429
        @brief  delete configurations
1430
        @author humkyung
1431
        @date   2018.06.29
1432
    '''
1433
    def deleteConfigs(self, section, key=None):
1434
        try:
1435
            # Creates or opens a file called mydb with a SQLite3 DB
1436
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
1437
            conn = sqlite3.connect(dbPath)
1438
            # Get a cursor object
1439
            cursor = conn.cursor()
1440

    
1441
            if key is not None:
1442
                sql = "delete from configuration where section='{}' and key='{}'".format(section, key)
1443
            else:
1444
                sql = "delete from configuration where section='{}'".format(section)
1445
            cursor.execute(sql)
1446

    
1447
            conn.commit()
1448
        # Catch the exception
1449
        except Exception as ex:
1450
            # Roll back any change if something goes wrong
1451
            conn.rollback()
1452
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1453
        finally:
1454
            # Close the db connection
1455
            conn.close()
1456

    
1457
    def deleteAppConfigs(self, section, key=None):
1458
        """
1459
        @brief  delete application configurations
1460
        @author humkyung
1461
        @date   2018.11.01
1462
        """
1463

    
1464
        try:
1465
            # Creates or opens a file called mydb with a SQLite3 DB
1466
            dbPath = self.getAppDbPath()
1467
            conn = sqlite3.connect(dbPath)
1468
            # Get a cursor object
1469
            cursor = conn.cursor()
1470

    
1471
            if key is not None:
1472
                sql = "delete from configuration where section='{}' and key='{}'".format(section, key)
1473
            else:
1474
                sql = "delete from configuration where section='{}'".format(section)
1475
            cursor.execute(sql)
1476

    
1477
            conn.commit()
1478
        # Catch the exception
1479
        except Exception as ex:
1480
            # Roll back any change if something goes wrong
1481
            conn.rollback()
1482
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1483
        finally:
1484
            # Close the db connection
1485
            conn.close()
1486

    
1487
    '''
1488
        @brief      set area list
1489
        @history    humkyung 2018.05.18 round area coordinate and dimension before saving
1490
        @history    euisung  2018.11.20 add self._area reset process
1491
    '''
1492
    def setAreaList(self, areas):
1493
        for area in areas:
1494
            matches = [x for x in self._areas if x.name==area.name]
1495
            if 1 == len(matches):
1496
                matches[0].x = area.x
1497
                matches[0].y = area.y
1498
                matches[0].width = area.width
1499
                matches[0].height = area.height
1500
            elif 0 == len(matches):
1501
                self._areas.append(area)
1502

    
1503
        try:
1504
            # Creates or opens a file called mydb with a SQLite3 DB
1505
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
1506
            conn = sqlite3.connect(dbPath)
1507
            # Get a cursor object
1508
            cursor = conn.cursor()
1509

    
1510
            for area in self._areas:
1511
                sql = "insert or replace into configuration values('Area','{}','({},{}),({},{})')".format(area.name, round(area.x), round(area.y), round(area.width), round(area.height))
1512
                cursor.execute(sql)
1513

    
1514
            conn.commit()
1515
        # Catch the exception
1516
        except Exception as ex:
1517
            # Roll back any change if something goes wrong
1518
            conn.rollback()
1519
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1520
        finally:
1521
            # Close the db connection
1522
            self._areas = []
1523
            conn.close()
1524
            
1525
    '''
1526
        @brief  get symbol name list
1527
    '''
1528
    def getSymbolNameList(self):
1529
        symbolNametList = []
1530

    
1531
        try:            
1532
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
1533

    
1534
            conn = sqlite3.connect(dbPath)
1535
            cursor = conn.cursor()
1536
            sql = 'SELECT * FROM SymbolName'
1537
            try:
1538
                cursor.execute(sql)
1539
                rows = cursor.fetchall()
1540
                for row in rows:
1541
                    symbolNametList.append(row[4]) # Name String
1542
            except Exception as ex:
1543
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1544
        finally:
1545
            conn.close()
1546

    
1547
        return symbolNametList
1548

    
1549
    '''
1550
        @brief      get symbol name list by symbol Type
1551
        @author     Jeongwoo
1552
        @date       18.04.06
1553
        @history    .
1554
    '''
1555
    def getSymbolNameListByType(self, type):
1556
        symbolNametList = []
1557

    
1558
        try:
1559
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
1560

    
1561
            conn = sqlite3.connect(dbPath)
1562
            cursor = conn.cursor()
1563
            sql = ''
1564
            if type is not None:
1565
                sql = 'SELECT * FROM SymbolName WHERE type = "' + type + '"'
1566
                try:
1567
                    cursor.execute(sql)
1568
                    rows = cursor.fetchall()
1569
                    for row in rows:
1570
                        symbolNametList.append(row[4]) # Name String
1571
                except Exception as ex:
1572
                    print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1573
        finally:
1574
            conn.close()
1575

    
1576
        return symbolNametList
1577

    
1578
    '''
1579
        @brief  delete added symbol data
1580
    '''
1581
    def deleteSymbol(self, fileName):
1582
        ret = False
1583
        try:
1584
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
1585

    
1586
            conn = sqlite3.connect(dbPath)
1587
            cursor = conn.cursor()
1588
            sql = "DELETE FROM Symbol WHERE name = ?"
1589
            try:
1590
                cursor.execute(sql, (fileName,))
1591
                conn.commit()
1592
                ret = True
1593
            except Exception as ex:
1594
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1595
                ret = False
1596
        finally:
1597
            conn.close()
1598
            return (ret, fileName)
1599
        
1600
    '''
1601
        @brief  get symbol name
1602
        @history    18.04.24    Jeongwoo    Add isExceptDetect Field
1603
    '''
1604
    def getSymbolByQuery(self, fieldName, param):
1605
        ret = None
1606

    
1607
        try:
1608
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
1609
            conn = sqlite3.connect(dbPath)
1610
            cursor = conn.cursor()
1611

    
1612
            sql = """select s.UID
1613
                          , s.Name
1614
                          , t.Category
1615
                          , t.Type
1616
                          , s.OriginalPoint
1617
                          , s.ConnectionPoint
1618
                       from Symbols s
1619
                      inner join SymbolType t
1620
                         on s.SymbolType_UID = t.UID 
1621
                      where """ + "s." + fieldName + '=?'
1622

    
1623
            try:
1624
                cursor.execute(sql, (param,))
1625
                rows = cursor.fetchall()
1626
                if rows is not None and len(rows) > 0:
1627
                    symbolTuple = rows[0]
1628
                    ret = symbol.SymbolBase(symbolTuple[0], symbolTuple[1], symbolTuple[2], symbolTuple[3], symbolTuple[4], symbolTuple[5]) 
1629
            except Exception as ex:
1630
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1631
        finally:
1632
            conn.close()
1633

    
1634
        return ret
1635

    
1636

    
1637
    def getSymbolListByUID(self, uid):
1638
        ret = []
1639

    
1640
        try:
1641
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
1642
            conn = sqlite3.connect(dbPath)
1643
            cursor = conn.cursor()
1644
            
1645
            sql = """select s.UID
1646
                          , s.Name
1647
                          , t.Category
1648
                          , t.Type
1649
                          , s.OriginalPoint
1650
                          , s.ConnectionPoint
1651
                       from Symbols s
1652
                      inner join SymbolType t
1653
                         on s.SymbolType_UID = t.uid 
1654
                      where s.SymbolType_UID = ?"""
1655
           
1656
            try:
1657
                cursor.execute(sql, (uid,))
1658
                rows = cursor.fetchall()
1659
                if rows is not None and len(rows) > 0:
1660
                    for row in rows:
1661
                        sym = symbol.SymbolBase(row[0], row[1], row[2], row[3], row[4], row[5])
1662
                                                
1663
                        ret.append(sym)
1664
            except Exception as ex:
1665
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1666
        finally:
1667
            conn.close()
1668

    
1669
        return ret
1670

    
1671

    
1672
    '''
1673
        @brief  get symbol name list
1674
        @history    18.04.24    Jeongwoo    Add isExceptDetect Field
1675
    '''
1676
    def getSymbolListByType(self, fieldName=None, param=None):
1677
        ret = []
1678

    
1679
        try:
1680
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
1681
            conn = sqlite3.connect(dbPath)
1682
            cursor = conn.cursor()
1683
            if fieldName is not None and param is not None:
1684

    
1685
                sql = """select s.UID
1686
                              , s.Name
1687
                              , t.Category
1688
                              , t.Type
1689
                              , s.OriginalPoint
1690
                              , s.ConnectionPoint
1691
                           from Symbols s 
1692
                          inner join SymbolType t 
1693
                             on s.SymbolType_UID = t.UID
1694
                          where s.SymbolType_UID = (select UID from SymbolType where Type=?)"""
1695
            else:
1696

    
1697
                sql = """select s.UID
1698
                              , s.Name
1699
                              , t.Category
1700
                              , t.Type
1701
                              , s.OriginalPoint
1702
                              , s.ConnectionPoint
1703
                           from Symbols s
1704
                          inner join SymbolType t
1705
                             on s.SymbolType_UID = t.UID"""
1706
            try:
1707
                cursor.execute(sql, (param,)) if param is not None else cursor.execute(sql)
1708
                rows = cursor.fetchall()
1709
                if rows is not None and len(rows) > 0:
1710
                    for row in rows:
1711
                        sym = symbol.SymbolBase(row[0], row[1], row[2], row[3], row[4], row[5])
1712
                                                
1713
                        ret.append(sym)
1714
            except Exception as ex:
1715
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1716
        finally:
1717
            conn.close()
1718

    
1719
        return ret
1720

    
1721
    '''
1722
        @brief      insert NominalDiameter table
1723
        @author     kyouho
1724
        @date       2018.07.16
1725
    '''
1726
    def insertNomialPipeSize(self, pipeSizes):
1727
        try:
1728
            # Creates or opens a file called mydb with a SQLite3 DB
1729
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
1730
            conn = sqlite3.connect(dbPath)
1731
            # Get a cursor object
1732
            cursor = conn.cursor()
1733
            for pipeSize in pipeSizes:
1734
                sql = pipeSize.toSql()
1735
                if type(sql) is list and len(sql) == 1:
1736
                    cursor.execute(sql[0][0], sql[0][1])
1737

    
1738
            conn.commit()
1739
            # Catch the exception
1740
        except Exception as ex:
1741
            # Roll back any change if something goes wrong
1742
            conn.rollback()
1743
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1744
        finally:
1745
            # Close the db connection
1746
            conn.close()
1747

    
1748
    '''
1749
        @brief      delete NominalDiameter table
1750
        @author     kyouho
1751
        @date       2018.07.16
1752
    '''
1753
    def deleteNomialPipeSize(self):
1754
        try:
1755
            dbPath = os.path.join(self.getCurrentProject().getPath(), 'db', AppDocData.DATABASE)
1756
            conn = sqlite3.connect(dbPath)
1757
            cursor = conn.cursor()
1758
            sql = "DELETE FROM NominalDiameter"
1759
            try:
1760
                cursor.execute(sql)
1761
                conn.commit()
1762
            except Exception as ex:
1763
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1764
        finally:
1765
            conn.close()
1766

    
1767
    '''
1768
        @brief      convert inch to metric
1769
        @author     kyouho
1770
        @date       2018.07.09
1771
    '''
1772
    def convertInchToMetric(self, inch):
1773
        result = ''
1774
        try:
1775
            # Creates or opens a file called mydb with a SQLite3 DB
1776
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
1777
            conn = sqlite3.connect(dbPath)
1778
            # Get a cursor object
1779
            cursor = conn.cursor()
1780
            
1781
            sql = "select MetricStr from NominalDiameter WHERE InchStr = ?"
1782
            param = (inch,)
1783
            cursor.execute(sql, param)
1784
            rows = cursor.fetchall()
1785

    
1786
            if rows:
1787
                result = rows[0][0]
1788
            # Catch the exception
1789
        except Exception as ex:
1790
            # Roll back any change if something goes wrong
1791
            conn.rollback()
1792
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1793
        finally:
1794
            # Close the db connection
1795
            conn.close()
1796

    
1797
        return result
1798

    
1799
    '''
1800
        @brief      get Color MaxUID
1801
        @author     kyouho
1802
        @date       2018.07.03
1803
    '''
1804
    def getMaxColorUID(self):
1805
        result = 0
1806

    
1807
        try:
1808
            # Creates or opens a file called mydb with a SQLite3 DB
1809
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
1810
            conn = sqlite3.connect(dbPath)
1811
            # Get a cursor object
1812
            cursor = conn.cursor()
1813

    
1814
            sql = "select MAX(UID) from Colors"
1815
            cursor.execute(sql)
1816
            rows = cursor.fetchall()
1817

    
1818
            result = rows[0][0]
1819
            # Catch the exception
1820
        except Exception as ex:
1821
            # Roll back any change if something goes wrong
1822
            conn.rollback()
1823
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1824
        finally:
1825
            # Close the db connection
1826
            conn.close()
1827

    
1828
        return result
1829

    
1830
    '''
1831
        @brief      insert Color property
1832
        @author     kyouho
1833
        @date       2018.07.09
1834
    '''
1835
    def setPropertyColor(self, _color):
1836
        try:
1837
            # Creates or opens a file called mydb with a SQLite3 DB
1838
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
1839
            conn = sqlite3.connect(dbPath)
1840
            # Get a cursor object
1841
            cursor = conn.cursor()
1842
            sql = "INSERT INTO Colors(UID, RED, GREEN, BLUE, PROPERTY, VALUE) VALUES(?,?,?,?,?,?)"
1843
            param = (_color.index, _color.red, _color.green, _color.blue, _color._property, _color.value)
1844
            cursor.execute(sql, param)
1845
            conn.commit()
1846
            # Catch the exception
1847
        except Exception as ex:
1848
            # Roll back any change if something goes wrong
1849
            conn.rollback()
1850
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1851
        finally:
1852
            # Close the db connection
1853
            conn.close()
1854

    
1855
    '''
1856
        @brief      delete Color property
1857
        @author     kyouho
1858
        @date       2018.07.09
1859
    '''
1860
    def deletePropertyColor(self, property):
1861
        try:
1862
            # Creates or opens a file called mydb with a SQLite3 DB
1863
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
1864
            conn = sqlite3.connect(dbPath)
1865
            # Get a cursor object
1866
            cursor = conn.cursor()
1867

    
1868
            sql = "DELETE FROM Colors WHERE PROPERTY = '{}'".format(property)
1869
            cursor.execute(sql)
1870
            conn.commit()
1871
            # Catch the exception
1872
        except Exception as ex:
1873
            # Roll back any change if something goes wrong
1874
            conn.rollback()
1875
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1876
        finally:
1877
            # Close the db connection
1878
            conn.close()
1879

    
1880
    '''
1881
        @brief      get Fluid Code
1882
        @author     kyouho
1883
        @date       2018.07.03
1884
        @history    kyouho 2018.07.04 kyouho 2018.07.04 forCheckLineNumber get only code
1885
    '''
1886
    def getFluidCodeData(self, forCheckLineNumber = False):
1887
        from FluidCodeData import FluidCodeData
1888
        result = []
1889

    
1890
        try:
1891
            # Creates or opens a file called mydb with a SQLite3 DB
1892
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
1893
            conn = sqlite3.connect(dbPath)
1894
            # Get a cursor object
1895
            cursor = conn.cursor()
1896

    
1897
            sql = 'select uid, code, description from FluidCode order by length(code) DESC'
1898
            cursor.execute(sql)
1899
            rows = cursor.fetchall()
1900
            for row in rows:
1901
                data = FluidCodeData(row[0], row[1], row[2])
1902
                if forCheckLineNumber:
1903
                    result.append(data.code)
1904
                else:
1905
                    result.append(data)
1906
            # Catch the exception
1907
        except Exception as ex:
1908
            # Roll back any change if something goes wrong
1909
            conn.rollback()
1910
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1911
        finally:
1912
            # Close the db connection
1913
            conn.close()
1914

    
1915
        return result
1916

    
1917
    '''
1918
        @brief      get Symbol Attribute
1919
        @author     kyouho
1920
        @date       2018.07.18
1921
    '''
1922
    def checkAttribute(self, attr):
1923
        try:
1924
            # Creates or opens a file called mydb with a SQLite3 DB
1925
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
1926
            conn = sqlite3.connect(dbPath)
1927
            # Get a cursor object
1928
            cursor = conn.cursor()
1929

    
1930
            sql = 'select UID from SymbolAttribute where UID = ?'
1931
            param = (attr,)
1932
            cursor.execute(sql, param)
1933
            rows = cursor.fetchall()
1934
            if len(rows):
1935
                return True
1936
            else:
1937
                return False
1938
            # Catch the exception
1939
        except Exception as ex:
1940
            # Roll back any change if something goes wrong
1941
            conn.rollback()
1942
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1943
        finally:
1944
            # Close the db connection
1945
            conn.close()
1946

    
1947
        return False
1948

    
1949
    '''
1950
        @brief      get Symbol Attribute
1951
        @author     kyouho
1952
        @date       2018.07.18
1953
        @history    humkyung 2018.10.13 load expression
1954
    '''
1955
    def getSymbolAttribute(self, _type):
1956
        import uuid
1957
        from SymbolAttr import SymbolAttr
1958

    
1959
        result = []
1960

    
1961
        try:
1962
            # Creates or opens a file called mydb with a SQLite3 DB
1963
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
1964
            conn = sqlite3.connect(dbPath)
1965
            # Get a cursor object
1966
            cursor = conn.cursor()
1967

    
1968
            sql = 'select a.UID, a.Attribute, a.DisplayAttribute, a.AttributeType, a.[AttrAt], a.[Expression], a.[index], a.[Target], a.[Property] from SymbolAttribute a inner join SymbolType t on a.SymbolType_UID = t.UID and t.type = ? order by a.[index]'
1969
            param = (_type,)
1970
            cursor.execute(sql, param)
1971
            rows = cursor.fetchall()
1972
            for row in rows:
1973
                attr = SymbolAttr()
1974
                attr.UID = uuid.UUID(row[0], version=4)
1975
                attr.Attribute = row[1]
1976
                attr.DisplayAttribute = row[2]
1977
                attr.AttributeType = row[3]
1978
                attr.AttrAt = row[4]
1979
                attr.Expression = row[5]
1980
                attr.Target = row[7]
1981
                attr.IsProp = bool(row[8])
1982
                result.append(attr)
1983
            # Catch the exception
1984
        except Exception as ex:
1985
            from App import App 
1986

    
1987
            # Roll back any change if something goes wrong
1988
            conn.rollback()
1989

    
1990
            message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
1991
            App.mainWnd().addMessage.emit(MessageType.Error, message)
1992
        finally:
1993
            # Close the db connection
1994
            conn.close()
1995

    
1996
        return result
1997

    
1998
    '''
1999
        @brief      get Symbol Attribute by UID
2000
        @author     kyouho
2001
        @date       2018.08.17
2002
        @history    humkyung 2018.10.13 load expression
2003
    '''
2004
    def getSymbolAttributeByUID(self, UID):
2005
        from SymbolAttr import SymbolAttr
2006

    
2007
        res = None
2008

    
2009
        try:
2010
            # Creates or opens a file called mydb with a SQLite3 DB
2011
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
2012
            conn = sqlite3.connect(dbPath)
2013
            # Get a cursor object
2014
            cursor = conn.cursor()
2015

    
2016
            sql = 'select Attribute, DisplayAttribute, AttributeType, AttrAt, Expression, Target, Property from SymbolAttribute where uid = "{}"'.format(UID)
2017
            cursor.execute(sql)
2018
            rows = cursor.fetchall()
2019
            if len(rows):
2020
                res = SymbolAttr()
2021
                res.UID = UID
2022
                res.Attribute = rows[0][0]
2023
                res.DisplayAttribute = rows[0][1]
2024
                res.AttributeType = rows[0][2]
2025
                res.AttrAt = rows[0][3]
2026
                res.Expression = rows[0][4]
2027
                res.Target = rows[0][5]
2028
                res.IsProp = bool(row[0][6])
2029
            # Catch the exception
2030
        except Exception as ex:
2031
            from App import App
2032

    
2033
            # Roll back any change if something goes wrong
2034
            conn.rollback()
2035

    
2036
            message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
2037
            App.mainWnd().addMessage.emit(MessageType.Error, message)
2038
        finally:
2039
            # Close the db connection
2040
            conn.close()
2041

    
2042
        return res
2043

    
2044
    '''
2045
        @brief      save symbol attributes
2046
        @author     humkyung
2047
        @date       2018.08.14
2048
        @history    humkyung 2018.10.13 save expression
2049
    '''
2050
    def saveSymbolAttributes(self, type, attrs):
2051
        try:
2052
            # Creates or opens a file called mydb with a SQLite3 DB
2053
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
2054
            conn = sqlite3.connect(dbPath)
2055
            # Get a cursor object
2056
            cursor = conn.cursor()
2057

    
2058
            sql = 'delete from SymbolAttribute where SymbolType_UID = ?'
2059
            param = (type,)
2060
            cursor.execute(sql, param)
2061

    
2062
            for attr in attrs:
2063
                sql = 'insert into SymbolAttribute(UID, SymbolType_UID, Attribute, DisplayAttribute, AttributeType, AttrAt, Expression, Target, [index]) values(?, ?, ?, ?, ?, ?, ?, ?, ?)'
2064
                attr.insert(1, type)
2065
                param = tuple(attr)
2066
                cursor.execute(sql, param)
2067

    
2068
            conn.commit()
2069
            # Catch the exception
2070
        except Exception as ex:
2071
            # Roll back any change if something goes wrong
2072
            conn.rollback()
2073
            
2074
            from App import App 
2075
            message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
2076
            App.mainWnd().addMessage.emit(MessageType.Error, message)
2077
        finally:
2078
            # Close the db connection
2079
            conn.close()
2080

    
2081
    '''
2082
        @brief      save symbol attributes
2083
        @author     humkyung
2084
        @date       2018.08.14
2085
    '''
2086
    def saveLineAttributes(self, attrs):
2087
        try:
2088
            # Creates or opens a file called mydb with a SQLite3 DB
2089
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
2090
            conn = sqlite3.connect(dbPath)
2091
            # Get a cursor object
2092
            cursor = conn.cursor()
2093

    
2094
            sql = 'delete from LineProperties'
2095
            cursor.execute(sql)
2096

    
2097
            for attr in attrs:
2098
                sql = 'insert into LineProperties(UID, Name, DisplayName, Type, LimitNumber, [index]) values(?, ?, ?, ?, ?, ?)'
2099
                param = tuple(attr)
2100
                cursor.execute(sql, param)
2101

    
2102
            conn.commit()
2103

    
2104
            self._lineNoProperties = None
2105
            # Catch the exception
2106
        except Exception as ex:
2107
            # Roll back any change if something goes wrong
2108
            conn.rollback()
2109
            
2110
            from App import App 
2111
            message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
2112
            App.mainWnd().addMessage.emit(MessageType.Error, message)
2113
        finally:
2114
            # Close the db connection
2115
            conn.close()
2116

    
2117
    '''
2118
        @brief      get symbol type id
2119
        @author     kyouho
2120
        @date       2018.08.17
2121
    '''
2122
    def getSymbolTypeId(self, symbolType):
2123
        result = []
2124

    
2125
        try:
2126
            # Creates or opens a file called mydb with a SQLite3 DB
2127
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
2128
            conn = sqlite3.connect(dbPath)
2129
            # Get a cursor object
2130
            cursor = conn.cursor()
2131

    
2132
            sql = 'select UID from SymbolType where Type = ?'
2133
            param = (symbolType,)
2134
            cursor.execute(sql, param)
2135
            rows = cursor.fetchall()
2136
            
2137
            if len(rows):
2138
                result = rows[0][0]
2139
            else:
2140
                result = -1
2141
            # Catch the exception
2142
        except Exception as ex:
2143
            # Roll back any change if something goes wrong
2144
            conn.rollback()
2145
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2146
        finally:
2147
            # Close the db connection
2148
            conn.close()
2149

    
2150
        return result
2151

    
2152
    '''
2153
        @brief      get Code Table Data
2154
        @author     kyouho
2155
        @date       2018.07.10
2156
    '''
2157
    def getCodeTable(self, property, forCheckLineNumber = False):
2158
        result = []
2159
        try:
2160
            # Creates or opens a file called mydb with a SQLite3 DB
2161
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
2162
            conn = sqlite3.connect(dbPath)
2163
            # Get a cursor object
2164
            cursor = conn.cursor()
2165

    
2166
            if property.upper().replace(' ','') == "NOMINALDIAMETER" and forCheckLineNumber:
2167
                sql = 'select InchStr, MetricStr from [{}] order by Metric ASC'.format(property)
2168
                cursor.execute(sql)
2169
                rows = cursor.fetchall()
2170
                for index in range(2):
2171
                    for row in rows:
2172
                        if row[index] != '' and result.count(row[index].replace("'", '"')) == 0:
2173
                            result.append(row[index].replace("'", '"'))
2174
            else:
2175
                sql = 'select uid, code, description, Allowables from [{}] order by length(code) DESC'.format(property)
2176
                cursor.execute(sql)
2177
                rows = cursor.fetchall()
2178
                for row in rows:
2179
                    if forCheckLineNumber:
2180
                        data = row[1]
2181
                    else:
2182
                        data = (row[0], row[1], row[2], row[3])
2183
                    result.append(data)
2184
            # Catch the exception
2185
        except Exception as ex:
2186
            # Roll back any change if something goes wrong
2187
            conn.rollback()
2188
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2189
        finally:
2190
            # Close the db connection
2191
            conn.close()
2192

    
2193
        return result
2194

    
2195

    
2196
    def getResistanceCoefficientByMethod(self, method):
2197
        res = []
2198
        try:
2199
            # Creates or opens a file called mydb with a SQLite3 DB
2200
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
2201
            db = sqlite3.connect(dbPath)
2202
            db.row_factory = sqlite3.Row
2203
            # Get a cursor object
2204
            cursor = db.cursor()
2205

    
2206
            sql = """select UID
2207
                          , Method
2208
                          , Category
2209
                          , Type
2210
                          , Name
2211
                          , K 
2212
                       from ResistanceCoefficient 
2213
                      where Method = ?
2214
                      order by rowid""" 
2215

    
2216
            param = (method,)
2217
            cursor.execute(sql, param)
2218
            rows = cursor.fetchall()
2219
            for row in rows:                
2220
                res.append((row[0], row[1], row[2], row[3], row[4], row[5]))
2221
        # Catch the exception
2222
        except Exception as ex:
2223
            # Roll back any change if something goes wrong
2224
            db.rollback()
2225
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2226
        finally:
2227
            # Close the db connection
2228
            db.close()
2229

    
2230
        return res
2231

    
2232

    
2233
    '''
2234
        @brief      Set Common Code Data
2235
        @author     kyouho
2236
        @date       2018.07.12
2237
    '''
2238
    def saveCommonCodeData(self, tableName, datas):
2239
        import uuid
2240

    
2241
        try:
2242
            # Creates or opens a file called mydb with a SQLite3 DB
2243
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
2244
            conn = sqlite3.connect(dbPath)
2245
            # Get a cursor object
2246
            cursor = conn.cursor()
2247

    
2248
            for data in datas:
2249
                uid,code,description,allowables = data[0],data[1],data[2],data[3]
2250
                if not uid:
2251
                    sql = "insert or replace into {}(UID, CODE, DESCRIPTION, ALLOWABLES) values(?, ?, ?, ?)".format(tableName)
2252
                    param = (str(uuid.uuid4()), data[1], data[2], data[3])
2253
                elif uid == '-1':
2254
                    sql = 'delete from {} where uid=?'.format(tableName) 
2255
                    param = (data[-1],)
2256
                else:
2257
                    sql = "update {} SET CODE=?, DESCRIPTION=?, ALLOWABLES=? WHERE UID = ?".format(tableName)
2258
                    param = (data[1], data[2], data[3], data[0])
2259
                cursor.execute(sql, param)
2260

    
2261
            conn.commit()
2262
        
2263
        # Catch the exception
2264
        except Exception as ex:
2265
            # Roll back any change if something goes wrong
2266
            conn.rollback()
2267
            print('error occured({}:{}) in {}:{}'.format(tableName, ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2268
        finally:
2269
            # Close the db connection
2270
            conn.close()
2271

    
2272
    '''
2273
        @brief      Set Common Code Data
2274
        @author     kyouho
2275
        @date       2018.07.12
2276
    '''
2277
    def deleteCommonCodeData(self, datas):
2278
        try:
2279
            # Creates or opens a file called mydb with a SQLite3 DB
2280
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
2281
            conn = sqlite3.connect(dbPath)
2282
            # Get a cursor object
2283
            cursor = conn.cursor()
2284

    
2285
            for data in datas:
2286
                uid = data[0]
2287
                tableName = data[1]
2288

    
2289
                if uid:
2290
                    sql = "delete from {} where UID = ?".format(tableName)
2291
                    param = (uid,)
2292
                    cursor.execute(sql, param)
2293

    
2294
                cursor.execute(sql, param)
2295

    
2296
            conn.commit()
2297
        
2298
        # Catch the exception
2299
        except Exception as ex:
2300
            # Roll back any change if something goes wrong
2301
            conn.rollback()
2302
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2303
        finally:
2304
            # Close the db connection
2305
            conn.close()
2306

    
2307
    '''
2308
        @brief      delete data list
2309
        @author     kyouho
2310
        @date       2018.08.16
2311
    '''
2312
    def deleteDataList(self, tableName, UID):
2313
        try:
2314
            # Creates or opens a file called mydb with a SQLite3 DB
2315
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
2316
            conn = sqlite3.connect(dbPath)
2317
            # Get a cursor object
2318
            cursor = conn.cursor()
2319

    
2320
            sql = 'delete from {} where UID = {}'.format(tableName, UID)
2321
            
2322
            cursor.execute(sql)
2323

    
2324
            conn.commit()
2325

    
2326
        # Catch the exception
2327
        except Exception as ex:
2328
            # Roll back any change if something goes wrong
2329
            conn.rollback()
2330
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2331
        finally:
2332
            # Close the db connection
2333
            conn.close()
2334

    
2335
    def getDocumentNameList(self):
2336
        '''
2337
            @brief      get documentName list
2338
            @author     euisung
2339
            @date       2018.12.11
2340
        '''
2341
        result = []
2342

    
2343
        try:
2344
            # Creates or opens a file called mydb with a SQLite3 DB
2345
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
2346
            conn = sqlite3.connect(dbPath)
2347
            # Get a cursor object
2348
            cursor = conn.cursor()
2349

    
2350
            sql = 'select DISTINCT(PNID_NO) from LINE_DATA_LIST'
2351
            cursor.execute(sql)
2352
            sql = 'select DISTINCT(PNID_NO) from EQUIPMENT_DATA_LIST'
2353
            cursor.execute(sql)
2354
            sql = 'select DISTINCT(PNID_NO) from INSTRUMENT_DATA_LIST'
2355
            cursor.execute(sql)
2356
            sql = 'select DISTINCT(PNID_NO) from NOTE_DATA_LIST'
2357
            cursor.execute(sql)
2358
            sql = 'select DISTINCT(PNID_NO) from VALVE_DATA_LIST'
2359
            cursor.execute(sql)
2360

    
2361
            rows = cursor.fetchall()
2362
            for row in rows:
2363
                result.append(row[0])
2364

    
2365
            result = list(set(result))
2366
            result.sort()
2367
        # Catch the exception
2368
        except Exception as ex:
2369
            # Roll back any change if something goes wrong
2370
            conn.rollback()
2371
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2372
        finally:
2373
            # Close the db connection
2374
            conn.close()
2375

    
2376
        return result
2377

    
2378

    
2379
    '''
2380
        @brief      get line documentName list
2381
        @author     kyouho
2382
        @date       2018.08.13
2383
    '''
2384
    def getLineDocumentNameList(self):
2385
        result = []
2386

    
2387
        try:
2388
            # Creates or opens a file called mydb with a SQLite3 DB
2389
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
2390
            conn = sqlite3.connect(dbPath)
2391
            # Get a cursor object
2392
            cursor = conn.cursor()
2393

    
2394
            sql = 'select DISTINCT(PNID_NO) from LINE_DATA_LIST'
2395

    
2396
            cursor.execute(sql)
2397
            rows = cursor.fetchall()
2398
            for row in rows:
2399
                result.append(row[0])
2400
        # Catch the exception
2401
        except Exception as ex:
2402
            # Roll back any change if something goes wrong
2403
            conn.rollback()
2404
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2405
        finally:
2406
            # Close the db connection
2407
            conn.close()
2408

    
2409
        return result
2410

    
2411
    '''
2412
        @brief      get line documentName list
2413
        @author     kyouho
2414
        @date       2018.08.14
2415
    '''
2416
    def getEquipDocumentNameList(self):
2417
        result = []
2418

    
2419
        try:
2420
            # Creates or opens a file called mydb with a SQLite3 DB
2421
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
2422
            conn = sqlite3.connect(dbPath)
2423
            # Get a cursor object
2424
            cursor = conn.cursor()
2425

    
2426
            sql = 'select DISTINCT(PNID_NO) from EQUIPMENT_DATA_LIST'
2427

    
2428
            cursor.execute(sql)
2429
            rows = cursor.fetchall()
2430
            for row in rows:
2431
                result.append(row[0])
2432
        # Catch the exception
2433
        except Exception as ex:
2434
            # Roll back any change if something goes wrong
2435
            conn.rollback()
2436
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2437
        finally:
2438
            # Close the db connection
2439
            conn.close()
2440

    
2441
        return result
2442

    
2443

    
2444
    '''
2445
        @brief      get line data list
2446
        @author     kyouho
2447
        @date       2018.08.13
2448
    '''
2449
    def getLineDataList(self, docName = None):
2450
        result = []
2451

    
2452
        try:
2453
            # Creates or opens a file called mydb with a SQLite3 DB
2454
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
2455
            conn = sqlite3.connect(dbPath)
2456
            # Get a cursor object
2457
            cursor = conn.cursor()
2458

    
2459
            sql = 'select UID, LINE_SIZE, LINE_SYMBOL, LINE_NO, LINE_CLASS, LINE_ROUTING_FROM, LINE_ROUTING_TO, SERVICE_FLUID, SERVICE_DENSITY, SERVICE_STATE, OPERATION_CONDITION_TEMP, OPERATION_CONDITION_PRESS, DESIGN_CONDITION_TEMP, DESIGN_CONDITION_PRESS, TEST_CONDITION_TEMP, TEST_CONDITION_PRESS, INSUL_CODE, PAINT_CODE, NDE_CODE, PWHT, PNID_NO from LINE_DATA_LIST'
2460
            if docName is not None:
2461
                sql += " where PNID_NO = '{}'".format(docName)
2462

    
2463
            cursor.execute(sql)
2464
            #columnName = list(map(lambda x: x[0].upper(), cursor.description))
2465
            rows = cursor.fetchall()
2466
            for row in rows:
2467
                data = []
2468
                for index in range(len(cursor.description)):
2469
                    data.append(row[index])
2470
                result.append(data)
2471
        # Catch the exception
2472
        except Exception as ex:
2473
            # Roll back any change if something goes wrong
2474
            conn.rollback()
2475
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2476
        finally:
2477
            # Close the db connection
2478
            conn.close()
2479

    
2480
        return result
2481

    
2482
    '''
2483
        @brief      set line data list
2484
        @author     kyouho
2485
        @date       2018.08.13
2486
    '''
2487
    def setLineDataList(self, dataLists):
2488
        try:
2489
            # Creates or opens a file called mydb with a SQLite3 DB
2490
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
2491
            conn = sqlite3.connect(dbPath)
2492
            # Get a cursor object
2493
            cursor = conn.cursor()
2494
            
2495
            for data in dataLists:
2496
                sql = "insert or replace into LINE_DATA_LIST(UID, LINE_SIZE, LINE_SYMBOL, LINE_NO, LINE_CLASS, LINE_ROUTING_FROM, LINE_ROUTING_TO, SERVICE_FLUID, SERVICE_DENSITY, SERVICE_STATE, OPERATION_CONDITION_TEMP, OPERATION_CONDITION_PRESS, DESIGN_CONDITION_TEMP, DESIGN_CONDITION_PRESS, TEST_CONDITION_TEMP, TEST_CONDITION_PRESS, INSUL_CODE, PAINT_CODE, NDE_CODE, PWHT, PNID_NO) values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
2497
                param = tuple(data)
2498
                cursor.execute(sql, param)
2499

    
2500
            conn.commit()
2501

    
2502
        # Catch the exception
2503
        except Exception as ex:
2504
            # Roll back any change if something goes wrong
2505
            conn.rollback()
2506
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2507
        finally:
2508
            # Close the db connection
2509
            conn.close()
2510

    
2511
    '''
2512
        @brief      delete line data list
2513
        @author     kyouho
2514
        @date       2018.08.13
2515
    '''
2516
    def deleteLineDataList(self, removeUID):
2517
        try:
2518
            # Creates or opens a file called mydb with a SQLite3 DB
2519
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
2520
            conn = sqlite3.connect(dbPath)
2521
            # Get a cursor object
2522
            cursor = conn.cursor()
2523
            
2524
            for uid in removeUID:
2525
                sql = "delete from LINE_DATA_LIST where uid = '{}'".format(uid)
2526
                cursor.execute(sql)
2527

    
2528
            conn.commit()
2529

    
2530
        # Catch the exception
2531
        except Exception as ex:
2532
            # Roll back any change if something goes wrong
2533
            conn.rollback()
2534
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2535
        finally:
2536
            # Close the db connection
2537
            conn.close()
2538

    
2539
    '''
2540
        @brief      delete line data list
2541
        @author     kyouho
2542
        @date       2018.08.13
2543
    '''
2544
    def deleteLineDataList_LineNo(self, removeUID):
2545
        try:
2546
            # Creates or opens a file called mydb with a SQLite3 DB
2547
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
2548
            conn = sqlite3.connect(dbPath)
2549
            # Get a cursor object
2550
            cursor = conn.cursor()
2551
            
2552
            for uid in removeUID:
2553
                sql = "delete from LINE_DATA_LIST where LINE_NO = ?"
2554
                param = (uid,)
2555
                cursor.execute(sql, param)
2556

    
2557
            conn.commit()
2558

    
2559
        # Catch the exception
2560
        except Exception as ex:
2561
            # Roll back any change if something goes wrong
2562
            conn.rollback()
2563
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2564
        finally:
2565
            # Close the db connection
2566
            conn.close()
2567

    
2568
    '''
2569
        @brief      delete equip data list
2570
        @author     kyouho
2571
        @date       2018.08.14
2572
    '''
2573
    def deleteEquipDataList(self, removeUID):
2574
        try:
2575
            # Creates or opens a file called mydb with a SQLite3 DB
2576
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
2577
            conn = sqlite3.connect(dbPath)
2578
            # Get a cursor object
2579
            cursor = conn.cursor()
2580
            
2581
            for uid in removeUID:
2582
                sql = "delete from EQUIPMENT_DATA_LIST where uid = '{}'".format(uid)
2583
                cursor.execute(sql)
2584

    
2585
            conn.commit()
2586

    
2587
        # Catch the exception
2588
        except Exception as ex:
2589
            # Roll back any change if something goes wrong
2590
            conn.rollback()
2591
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2592
        finally:
2593
            # Close the db connection
2594
            conn.close()
2595

    
2596
    '''
2597
        @brief      delete inst data list
2598
        @author     kyouho
2599
        @date       2018.08.14
2600
    '''
2601
    def deleteInstDataList(self, removeUID):
2602
        try:
2603
            # Creates or opens a file called mydb with a SQLite3 DB
2604
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
2605
            conn = sqlite3.connect(dbPath)
2606
            # Get a cursor object
2607
            cursor = conn.cursor()
2608
            
2609
            for uid in removeUID:
2610
                sql = "delete from INSTRUMENT_DATA_LIST where uid = '{}'".format(uid)
2611
                cursor.execute(sql)
2612

    
2613
            conn.commit()
2614

    
2615
        # Catch the exception
2616
        except Exception as ex:
2617
            # Roll back any change if something goes wrong
2618
            conn.rollback()
2619
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2620
        finally:
2621
            # Close the db connection
2622
            conn.close()
2623

    
2624
    '''
2625
        @brief      delete note data list
2626
        @author     kyouho
2627
        @date       2018.10.10
2628
    '''
2629
    def deleteNoteDataList(self, removeUID):
2630
        try:
2631
            # Creates or opens a file called mydb with a SQLite3 DB
2632
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
2633
            conn = sqlite3.connect(dbPath)
2634
            # Get a cursor object
2635
            cursor = conn.cursor()
2636
            
2637
            for uid in removeUID:
2638
                sql = "delete from NOTE_DATA_LIST where uid = '{}'".format(uid)
2639
                cursor.execute(sql)
2640

    
2641
            conn.commit()
2642

    
2643
        # Catch the exception
2644
        except Exception as ex:
2645
            # Roll back any change if something goes wrong
2646
            conn.rollback()
2647
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2648
        finally:
2649
            # Close the db connection
2650
            conn.close()
2651

    
2652
    '''
2653
        @brief      get equipment data list
2654
        @author     humkyung
2655
        @date       2018.05.03
2656
    '''
2657
    def getEquipmentDataList(self, docName = None):
2658
        result = []
2659
        try:
2660
            # Creates or opens a file called mydb with a SQLite3 DB
2661
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
2662
            conn = sqlite3.connect(dbPath)
2663
            # Get a cursor object
2664
            cursor = conn.cursor()
2665

    
2666
            sql = 'select a.*,C.Attribute,B.Value  from EQUIPMENT_DATA_LIST a left join Attributes B on a.UID=B.Components_UID ' \
2667
                                                                             'left join SymbolAttribute C on B.SymbolAttribute_UID=C.UID'
2668
            if docName is not None:
2669
                sql += " where PNID_NO = '{}'".format(docName)
2670

    
2671
            cursor.execute(sql)
2672
            col_names = [desc[0] for desc in cursor.description]    # get coloumn name
2673
            rows = cursor.fetchall()
2674
            for row in rows:
2675
                matches = [res for res in result if res['UID']==row[0]]
2676
                if matches:
2677
                    matches[0][row[len(row)-2]] = row[len(row)-1]
2678
                else:
2679
                    data = dict(zip(col_names[:-2], row[:-2]))
2680
                    if row[len(row)-2] is not None:
2681
                        data[row[len(row)-2]] = row[len(row)-1]
2682
                    result.append(data)
2683
        # Catch the exception
2684
        except Exception as ex:
2685
            from App import App 
2686

    
2687
            # Roll back any change if something goes wrong
2688
            conn.rollback()
2689
            
2690
            message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
2691
            App.mainWnd().addMessage.emit(MessageType.Error, message)
2692
        finally:
2693
            # Close the db connection
2694
            conn.close()
2695

    
2696
        return result
2697

    
2698
    def get_valve_data_list(self, docName = None):
2699
        """
2700
        @brief      get valve data list
2701
        @author     humkyung
2702
        @date       2018.10.11
2703
        """
2704

    
2705
        result = []
2706
        try:
2707
            # Creates or opens a file called mydb with a SQLite3 DB
2708
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
2709
            conn = sqlite3.connect(dbPath)
2710
            # Get a cursor object
2711
            cursor = conn.cursor()
2712

    
2713
            sql = 'select a.UID,a.ITEM_NO,a.PNID_NO,a.MainSize,a.SubSize,c.Attribute,b.Value from VALVE_DATA_LIST a left join Attributes b on a.uid=b.Components_UID ' \
2714
                  'left join SymbolAttribute c on b.SymbolAttribute_UID=c.UID'
2715
            if docName is not None:
2716
                sql += " where PNID_NO = '{}'".format(docName)
2717

    
2718
            cursor.execute(sql)
2719
            rows = cursor.fetchall()
2720
            for row in rows:
2721
                matches = [res for res in result if res['UID'] == row[0]]
2722
                if matches:
2723
                    matches[0][row[5]] = row[6]
2724
                else:
2725
                    data = {'UID':row[0], 'ITEM_NO':row[1], 'PNID_NO':row[2], 'MainSize':row[3], 'SubSize':row[4]}
2726
                    data[row[5]] = row[6]
2727
                    result.append(data)
2728

    
2729
        # Catch the exception
2730
        except Exception as ex:
2731
            from App import App 
2732

    
2733
            # Roll back any change if something goes wrong
2734
            conn.rollback()
2735
            
2736
            message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
2737
            App.mainWnd().addMessage.emit(MessageType.Error, message)
2738
        finally:
2739
            # Close the db connection
2740
            conn.close()
2741

    
2742
        return result
2743

    
2744
    '''
2745
        @brief      get instrument data list
2746
        @author     kyouho
2747
        @date       2018.08.14
2748
    '''
2749
    def getInstrumentDataList(self, docName = None):
2750
        result = []
2751
        try:
2752
            # Creates or opens a file called mydb with a SQLite3 DB
2753
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
2754
            conn = sqlite3.connect(dbPath)
2755
            # Get a cursor object
2756
            cursor = conn.cursor()
2757

    
2758
            #sql = 'select UID, ITEM_NO, SERVICE, FLOW_RATE, PRESSURE, TEMPERATURE, TYPE, RANGE, NOR_LEVEL_MM, NOR_LEVEL_PERCENT, DEL_PRESS, SHUT_OFF, LOCATION, PNID_NO, REV from INSTRUMENT_DATA_LIST'
2759
            sql = 'select * from INSTRUMENT_DATA_LIST'
2760
            if docName is not None:
2761
                sql += " where PNID_NO = '{}'".format(docName)
2762

    
2763
            cursor.execute(sql)
2764
            rows = cursor.fetchall()
2765
            for row in rows:
2766
                data = []
2767
                for index in range(len(cursor.description)): 
2768
                    data.append(row[index])
2769
                result.append(data)
2770
        # Catch the exception
2771
        except Exception as ex:
2772
            # Roll back any change if something goes wrong
2773
            conn.rollback()
2774
            from App import App
2775

    
2776
            message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
2777
            App.mainWnd().addMessage.emit(MessageType.Error, message)
2778
        finally:
2779
            # Close the db connection
2780
            conn.close()
2781

    
2782
        return result
2783

    
2784
    '''
2785
        @brief      get Note data list
2786
        @author     kyouho
2787
        @date       2018.10.10
2788
    '''
2789
    def getNoteDataList(self, docName = None):
2790
        result = []
2791
        try:
2792
            # Creates or opens a file called mydb with a SQLite3 DB
2793
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
2794
            conn = sqlite3.connect(dbPath)
2795
            # Get a cursor object
2796
            cursor = conn.cursor()
2797

    
2798
            sql = 'select UID, NOTE_NO, DESCRIPTION, PNID_NO from NOTE_DATA_LIST'
2799
            if docName is not None:
2800
                sql += " where PNID_NO = '{}'".format(docName)
2801

    
2802
            sql += ' ORDER BY NOTE_NO ASC'
2803
            cursor.execute(sql)
2804
            rows = cursor.fetchall()
2805
            for row in rows:
2806
                data = []
2807
                for index in range(len(cursor.description)): 
2808
                    data.append(row[index])
2809
                result.append(data)
2810
        # Catch the exception
2811
        except Exception as ex:
2812
            # Roll back any change if something goes wrong
2813
            conn.rollback()
2814
            from App import App
2815

    
2816
            message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
2817
            App.mainWnd().addMessage.emit(MessageType.Error, message)
2818
        finally:
2819
            # Close the db connection
2820
            conn.close()
2821

    
2822
        return result
2823

    
2824

    
2825
    '''
2826
        @brief      save to database
2827
        @author     yjkim
2828
        @date       2019.08.28
2829
    '''
2830
    def saveToDatabase(self, item, index):
2831
        """ save given items to database """
2832
        conn = sqlite3.connect(self.activeDrawing.path, isolation_level=None)
2833
        with conn:
2834
            try:
2835
                # Get a cursor object
2836
                cursor = conn.cursor()
2837

    
2838
                if index == 0:
2839
                    # delete Points
2840
                    sql = 'delete from Points'
2841
                    cursor.execute(sql)
2842

    
2843
                    # delete HMB
2844
                    sql = 'delete from HMB'
2845
                    cursor.execute(sql)
2846

    
2847
                    # delete Components 
2848
                    sql = 'delete from Components'
2849
                    cursor.execute(sql)
2850
                
2851
                sql = item.toSql()
2852
                if type(sql) is list:
2853
                    for item in sql:
2854
                        if item is not None and 2 == len(item):
2855
                            cursor.execute(item[0], item[1])
2856
                else:
2857
                    if sql is not None and 2 == len(sql):
2858
                        cursor.execute(sql[0], sql[1])
2859

    
2860
                conn.commit()
2861
            # Catch the exception
2862
            except Exception as ex:
2863
                from App import App
2864
                # Roll back any change if something goes wrong
2865
                conn.rollback()
2866

    
2867
                message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
2868
                print(message)
2869
                print(sql)
2870
                App.mainWnd().addMessage.emit(MessageType.Error, message)
2871

    
2872
    '''
2873
        @brief      set equipment data list
2874
        @author     humkyung
2875
        @date       2018.05.03
2876
    '''
2877
    def setEquipmentDataList(self, dataList):
2878
        try:
2879
            # Creates or opens a file called mydb with a SQLite3 DB
2880
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
2881
            conn = sqlite3.connect(dbPath)
2882
            # Get a cursor object
2883
            cursor = conn.cursor()
2884

    
2885
            for data in dataList:
2886
                sql = "insert or replace into EQUIPMENT_DATA_LIST(UID, ITEM_NO, SERVICE, NO_REQ, FLUID, DESC_OF_PART, OPERATION_CONDITION_TEMP, OPERATION_CONDITION_PRESS, DESIGN_CONDITION_TEMP, DESIGN_CONDITION_PRESS, MATERIAL, WEIGHT, POWER, INSULATION, PNID_NO, REV) values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
2887
                param = tuple(data)
2888
                cursor.execute(sql, param)
2889
            conn.commit()
2890
        # Catch the exception
2891
        except Exception as ex:
2892
            # Roll back any change if something goes wrong
2893
            conn.rollback()
2894
            from App import App
2895

    
2896
            message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
2897
            App.mainWnd().addMessage.emit(MessageType.Error, message)
2898
        finally:
2899
            # Close the db connection
2900
            conn.close()
2901

    
2902
    """
2903
        @brief      exists drawing
2904
        @author     yeonjin
2905
        @date       2019.07.03
2906
    """
2907
    def exists_drawing(self, drawingName):
2908
        rows = None
2909
        try:           
2910
            # Creates or opens a file called mydb with a SQLite3 DB
2911
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
2912
            conn = sqlite3.connect(dbPath)
2913
            # Get a cursor object
2914
            cursor = conn.cursor()
2915
            sql = "select name from Drawings where upper(name) = '" + drawingName.upper() + "'"
2916
            cursor.execute(sql)
2917
            rows = cursor.fetchall()
2918
        # Catch the exception
2919
        except Exception as ex:
2920
            # Roll back any change if something goes wrong
2921
            conn.rollback()
2922
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
2923
        finally:
2924
            # Close the db connection
2925
            conn.close()
2926
            if rows is not None and len(rows) > 0:
2927
                return True
2928
            else:
2929
                return False
2930

    
2931
    def getDrawings(self):
2932
        """
2933
        @brief      get drawings
2934
        @author     humkyung
2935
        @date       2018.11.03
2936
        """
2937
        from Drawing import Drawing
2938

    
2939
        res = []
2940
        # Creates or opens a file called mydb with a SQLite3 DB
2941
        dbPath = self.getAppDbPath()
2942
        conn = sqlite3.connect(dbPath)
2943
        with conn:
2944
            try:
2945
                conn.row_factory = sqlite3.Row
2946
                # Get a cursor object
2947
                cursor = conn.cursor()
2948

    
2949
                sql = 'select UID,[NAME],[DATETIME] from Drawings'
2950
                cursor.execute(sql)
2951
                rows = cursor.fetchall()
2952
                for row in rows:
2953
                    res.append(Drawing(row[0], row[1], row[2]))
2954
            # Catch the exception
2955
            except Exception as ex:
2956
                # Roll back any change if something goes wrong
2957
                conn.rollback()
2958
                from App import App
2959

    
2960
                message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
2961
                App.mainWnd().addMessage.emit(MessageType.Error, message)
2962

    
2963
        return res
2964

    
2965
    '''
2966
        @brief      update drawings
2967
        @author     yeonjin
2968
        @date       2019.08.07
2969
    '''
2970
    def updateDrawing(self, drawing):
2971
        import uuid
2972
        
2973
        # Creates or opens a file called mydb with a SQLite3 DB
2974
        dbPath = self.getAppDbPath()
2975
        conn = sqlite3.connect(dbPath)
2976
        with conn:
2977
            try:
2978
                # Get a cursor object
2979
                cursor = conn.cursor()
2980
                    
2981
                sql = """update Drawings
2982
                            set Name = ?
2983
                                , DateTime = ?
2984
                            where uid = ?"""
2985
                param = (drawing[0][1], drawing[0][2], drawing[0][0])
2986
                cursor.execute(sql, param)
2987

    
2988
                conn.commit()
2989

    
2990
            # Catch the exception
2991
            except Exception as ex:
2992
                # Roll back any change if something goes wrong
2993
                conn.rollback()
2994
                from App import App
2995

    
2996
                message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
2997
                App.mainWnd().addMessage.emit(MessageType.Error, message)
2998

    
2999
    '''
3000
        @brief      save drawings
3001
        @author     humkyung
3002
        @date       2018.11.03
3003
    '''
3004
    def saveDrawing(self, drawing):
3005
        import uuid
3006
        from shutil import copyfile       
3007

    
3008
        conn = sqlite3.connect(self.getAppDbPath())
3009
        with conn:
3010
            try:
3011
                # Get a cursor object
3012
                cursor = conn.cursor()
3013
                    
3014
                sql = 'insert or replace into Drawings(UID, [NAME], [DATETIME]) values(?, ?, ?)'
3015
                param = (drawing.UID, drawing.path, drawing.date_time)
3016
                cursor.execute(sql, param)
3017

    
3018
                conn.commit()
3019

    
3020
                if not os.path.exists(drawing.path): copyfile(self.getTemplateDbPath(), drawing.path)
3021
            # Catch the exception
3022
            except Exception as ex:
3023
                # Roll back any change if something goes wrong
3024
                conn.rollback()
3025
                from App import App
3026

    
3027
                message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
3028
                App.mainWnd().addMessage.emit(MessageType.Error, message)
3029

    
3030
    '''
3031
        @brief      Return Symbol Category Items
3032
        @author     yeonjin
3033
        @date       19.07.11
3034
    '''
3035
    def getSymbolCategoryList(self):
3036
        SymbolCategoryList = []
3037

    
3038
        try:
3039
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
3040

    
3041
            conn = sqlite3.connect(dbPath)
3042
            cursor = conn.cursor()
3043
            sql = 'SELECT DISTINCT CATEGORY FROM SymbolType ORDER BY type ASC'
3044
            try:
3045
                cursor.execute(sql)
3046
                rows = cursor.fetchall()
3047
                for row in rows:
3048
                    SymbolCategoryList.append((row[0])) # category
3049
            except Exception as ex:
3050
                from App import App
3051

    
3052
                message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
3053
                App.mainWnd().addMessage.emit(MessageType.Error, message)
3054
        finally:
3055
            conn.close()
3056

    
3057
        return SymbolCategoryList
3058

    
3059

    
3060
    def getComponentByComponentUID(self, uid):
3061
        ComponentList = []
3062

    
3063
        conn = sqlite3.connect(self.activeDrawing.path)
3064
        with conn:
3065
            try:
3066
                conn.row_factory = sqlite3.Row
3067
                cursor = conn.cursor()
3068
                
3069
                sql = """select c.uid
3070
                                , c.Name
3071
                                , c.Symbols_UID
3072
                                , t.Category
3073
                                , t.type
3074
                                , s.Name
3075
                                , s.OriginalPoint
3076
                                , c.X
3077
                                , c.Y
3078
                                , c.Rotation
3079
                                , c.Scale
3080
                                , p.uid
3081
                                , p.[Index]
3082
                                , p.x
3083
                                , p.y
3084
                                , p.ConnectedItem_UID
3085
                            from points p
3086
                            left join components c
3087
                                on p.components_uid = c.uid
3088
                            left join symbols s
3089
                                on c.Symbols_UID = s.UID    
3090
                            left join SymbolType t
3091
                                on s.symboltype_uid = t.uid
3092
                            where c.uid = ?
3093
                            order by p.[Index]"""
3094
                param = (uid,)                      
3095
                cursor.execute(sql, param)
3096
                rows = cursor.fetchall()
3097
                for row in rows:
3098
                    data = []
3099
                    for index in range(len(cursor.description)):
3100
                        data.append(row[index])
3101
                    ComponentList.append(data) # Components_UID
3102
            except Exception as ex:
3103
                from App import App
3104

    
3105
                message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
3106
                App.mainWnd().addMessage.emit(MessageType.Error, message)
3107

    
3108
        return ComponentList
3109

    
3110
    def get_nozzle_data(self, uid):
3111
        """ get nozzle data of given uid """
3112
        from EngineeringConnectorItem import NozzleData
3113

    
3114
        res = None
3115
        db_path = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
3116
        conn = sqlite3.connect(db_path)
3117
        with conn:
3118
            conn.row_factory = sqlite3.Row
3119
            cursor = conn.cursor()
3120
            sql = 'select Pressure, Pressure_Drop, Elevation, Over_Design_CV from Nozzles where Points_UID=?' 
3121
            param = (uid, )
3122
            cursor.execute(sql, param)
3123
            rows = cursor.fetchall()
3124
            if rows:
3125
                res = NozzleData()
3126
                if rows[0]['Pressure']:
3127
                    res.pressure = float(rows[0]['Pressure'])
3128
                if rows[0]['Pressure_Drop']:
3129
                    res.pressure_drop = float(rows[0]['Pressure_Drop'])
3130
                if rows[0]['Elevation']:
3131
                    res.elevation = float(rows[0]['Elevation'])
3132
                if rows[0]['Over_Design_CV']:
3133
                    res.over_design_cv = float(rows[0]['Over_Design_CV'])
3134
        return res
3135

    
3136
    def getDrawingsUnitsByDrawingUID(self, uid):
3137
        unitsList = []
3138

    
3139
        try:
3140
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
3141

    
3142
            conn = sqlite3.connect(dbPath)
3143
            cursor = conn.cursor()
3144
            #sql = 'select UID from Components where Drawings_UID = ? order by x desc'
3145

    
3146
            sql = """select du.Units
3147
                          , u.Value
3148
                       from DrawingsUnits du 
3149
                       left join units u 
3150
                         on du.Units_UID = u.uid
3151
                      where du.drawings_uid = ?"""
3152
            try:
3153
                param = (uid, )
3154
                cursor.execute(sql, param)
3155
                rows = cursor.fetchall()
3156
                for row in rows:
3157
                    unitsList.append((row[0], row[1])) 
3158
            except Exception as ex:
3159
                from App import App
3160

    
3161
                message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
3162
                App.mainWnd().addMessage.emit(MessageType.Error, message)
3163
        finally:
3164
            conn.close()
3165

    
3166
        return unitsList
3167

    
3168

    
3169
    '''
3170
        @brief      Return Components By DrawingUID
3171
        @author     yeonjin
3172
        @date       19.07.29
3173
    '''
3174
    def getComponentListByDrawingUID(self, drawing):
3175
        ComponentList = []
3176

    
3177
        conn = sqlite3.connect(drawing.path)
3178
        with conn:
3179
            try:
3180
                conn.row_factory = sqlite3.Row
3181
                cursor = conn.cursor()
3182
                sql = 'select UID from Components order by x desc'
3183
                cursor.execute(sql)
3184
                rows = cursor.fetchall()
3185
                for row in rows:
3186
                    ComponentList.append((row[0])) # Components_UID
3187
            except Exception as ex:
3188
                from App import App
3189

    
3190
                message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
3191
                App.mainWnd().addMessage.emit(MessageType.Error, message)
3192

    
3193
        return ComponentList
3194

    
3195
    '''
3196
        @brief      Return Symbol Type Items By Category
3197
        @author     yeonjin
3198
        @date       19.07.11
3199
    '''
3200
    def getSymbolTypeListByCategory(self, category):
3201
        symbolTypeList = []
3202

    
3203
        try:
3204
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
3205

    
3206
            conn = sqlite3.connect(dbPath)
3207
            cursor = conn.cursor()
3208
            sql = 'SELECT UID, Category, Type FROM SymbolType WHERE Category = "' + category + '"'
3209
            try:
3210
                cursor.execute(sql)
3211
                rows = cursor.fetchall()
3212
                for row in rows:
3213
                    symbolTypeList.append((row[0], row[1], row[2])) # UID, Category, Type
3214
            except Exception as ex:
3215
                from App import App
3216

    
3217
                message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
3218
                App.mainWnd().addMessage.emit(MessageType.Error, message)
3219
        finally:
3220
            conn.close()
3221

    
3222
        return symbolTypeList
3223

    
3224
    def getUnits(self):
3225
        unitsList = []
3226

    
3227
        try:
3228
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
3229

    
3230
            conn = sqlite3.connect(dbPath)
3231
            cursor = conn.cursor()
3232
            sql = 'Select UID, Key, Value From Units'
3233
            try:
3234
                cursor.execute(sql)
3235
                rows = cursor.fetchall()
3236
                for row in rows:
3237
                    unitsList.append((row[0], row[1], row[2])) # UID, Key, Value
3238
            except Exception as ex:
3239
                from App import App
3240

    
3241
                message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
3242
                App.mainWnd().addMessage.emit(MessageType.Error, message)
3243
        finally:
3244
            conn.close()
3245

    
3246
        return unitsList
3247

    
3248

    
3249
    def getUnitsByDrawingName(self, drawingName):
3250
        unitsList = []
3251

    
3252
        try:
3253
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
3254

    
3255
            conn = sqlite3.connect(dbPath)
3256
            cursor = conn.cursor()
3257
            sql = """select ifnull(d.display_name, u.column_name)
3258
                          , u.UNIT
3259
                       from units u
3260
                       left join displayNames d
3261
                         on u.TABLE_NAME = d.TABLE_NAME and u.COLUMN_NAME = d.COLUMN_NAME    
3262
                      where u.uid in (
3263
                                        select distinct du.units_uid
3264
                                          from drawings d
3265
                                         inner join drawingsunits du
3266
                                            on d.uid = du.drawings_uid
3267
                                         where d.name = ?
3268
                                     )
3269
                        and u.table_name = 'HMB'"""
3270
            param = (drawingName, )
3271
            try:
3272
                cursor.execute(sql, param)
3273
                rows = cursor.fetchall()
3274
                for row in rows:
3275
                    unitsList.append((row[0], row[1])) 
3276
            except Exception as ex:
3277
                from App import App
3278

    
3279
                message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
3280
                App.mainWnd().addMessage.emit(MessageType.Error, message)
3281
        finally:
3282
            conn.close()
3283

    
3284
        return unitsList
3285

    
3286
    def getHMBDisplayNameAndUnitsExpression(self):
3287
        res = []
3288

    
3289
        try:
3290
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
3291

    
3292
            conn = sqlite3.connect(dbPath)
3293
            cursor = conn.cursor()
3294
            sql = """SELECT dn.DISPLAY_NAME
3295
                          , hu.Units_Expression
3296
                       FROM DisplayNames dn
3297
                       left join HMBUnits hu
3298
                         on dn.COLUMN_NAME = Hu.Column_Name
3299
                      where dn.Table_Name = 'HMB'
3300
                      order by dn.[Order]"""    
3301
            try:
3302
                cursor.execute(sql)  
3303
                rows = cursor.fetchall()
3304
                for row in rows:
3305
                    res.append((row[0], row[1])) 
3306
            except Exception as ex:
3307
                from App import App
3308

    
3309
                message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
3310
                App.mainWnd().addMessage.emit(MessageType.Error, message)
3311
        finally:
3312
            conn.close()
3313

    
3314
        return res
3315

    
3316

    
3317

    
3318
    def getColumnDisplayNames(self, uid, table):
3319
        columnDisplayNameList = []
3320

    
3321
        try:
3322
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
3323

    
3324
            conn = sqlite3.connect(dbPath)
3325
            cursor = conn.cursor()
3326
            sql = """SELECT dn.DISPLAY_NAME
3327
                          , u.Value
3328
                       FROM DisplayNames dn
3329
                       left join drawingsUnits du
3330
                         on dn.TABLE_NAME = du.Table_Name and dn.COLUMN_NAME = du.Column_Name
3331
                       left join Units u
3332
                         on du.Units_UID = u.UID
3333
                      where du.Drawings_UID = ?
3334
                        and dn.Table_Name = ?
3335
                      order by dn.[Order]"""    
3336
            try:
3337
                param = (uid, table,)
3338
                cursor.execute(sql, param)
3339
  
3340
                rows = cursor.fetchall()
3341
                for row in rows:
3342
                    columnDisplayNameList.append((row[0], row[1])) # Display_Name
3343
            except Exception as ex:
3344
                from App import App
3345

    
3346
                message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
3347
                App.mainWnd().addMessage.emit(MessageType.Error, message)
3348
        finally:
3349
            conn.close()
3350

    
3351
        return columnDisplayNameList
3352

    
3353

    
3354

    
3355
    '''
3356
        @brief      Return Symbol Type Items
3357
        @author     Jeongwoo
3358
        @date       18.04.20
3359
        @history    18.05.08    Jeongwoo type index changed
3360
    '''
3361
    def getSymbolTypeList(self):
3362
        symbolTypeList = []
3363

    
3364
        try:
3365
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
3366

    
3367
            conn = sqlite3.connect(dbPath)
3368
            cursor = conn.cursor()
3369
            sql = 'SELECT * FROM SymbolType ORDER BY type ASC'
3370
            try:
3371
                cursor.execute(sql)
3372
                rows = cursor.fetchall()
3373
                for row in rows:
3374
                    symbolTypeList.append((row[0], row[1], row[2])) # UID, category, type
3375
            except Exception as ex:
3376
                from App import App
3377

    
3378
                message = 'error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno)
3379
                App.mainWnd().addMessage.emit(MessageType.Error, message)
3380
        finally:
3381
            conn.close()
3382

    
3383
        return symbolTypeList
3384

    
3385
    '''
3386
        @brief      Get Symbol Category by Symbol Type
3387
        @author     Jeongwoo
3388
        @date       2018.05.09
3389
    '''
3390
    def getSymbolCategoryByType(self, type):
3391
        category = None
3392
        try:
3393
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
3394
            
3395
            conn = sqlite3.connect(dbPath)
3396
            cursor = conn.cursor()
3397
            sql = 'SELECT Category FROM SymbolType WHERE type = "' + type + '"'
3398
            cursor.execute(sql)
3399
            rows = cursor.fetchall()
3400
            if rows is not None and len(rows) > 0:
3401
                category = rows[0][0]
3402
        except Exception as ex:
3403
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
3404
        finally:
3405
            conn.close()
3406

    
3407
        return category
3408

    
3409
    '''
3410
        @brief      Check Symbol Type is included in 'Equipment' Category
3411
        @author     Jeongwoo
3412
        @date       2018.05.09
3413
    '''
3414
    def isEquipmentType(self, type):
3415
        category = self.getSymbolCategoryByType(type)
3416
        return (category is not None and category == 'Equipment')
3417

    
3418
    '''
3419
        @brief      Return Symbol Type Items with "None"
3420
        @author     Jeongwoo
3421
        @date       18.04.06
3422
        @history    Seperate SymbolTypeList and "None"
3423
    '''
3424
    def getSymbolTypeComboBoxItems(self):
3425
        symbolTypeList = self.getSymbolTypeList()
3426
        symbolTypeList.insert(0, ('None', 'None', 'None'))
3427

    
3428
        return symbolTypeList
3429

    
3430
    '''
3431
        @brief  get Base Symbol ComboBox Items
3432
    '''
3433
    def getBaseSymbolComboBoxItems(self, type = None):
3434
        bsymbolNameList = self.getSymbolNameListByType(type)
3435
        bsymbolNameList.sort()
3436
        bsymbolNameList.insert(0, "None")
3437
        return bsymbolNameList
3438

    
3439
    '''
3440
        @brief  get Additional Symbol ComboBox Items
3441
    '''
3442
    def getAdditionalSymbolComboBoxItems(self):
3443
        asymbolNameList = self.getSymbolNameList()
3444
        asymbolNameList.sort()
3445
        asymbolNameList.insert(0, "None")
3446
        return asymbolNameList
3447

    
3448
    '''
3449
        @brief  get Additional Symbol's default direction ComboBox Items
3450
    '''
3451
    def getDefaultSymbolDirectionComboBoxItems(self):
3452
        return [("UP", 0), ("DOWN", 2), ("LEFT", 3), ("RIGHT", 1)]
3453
    
3454
    '''
3455
        @brief  getter of activeDrawing
3456
        @author humkyung
3457
        @date   2018.07.07
3458
    '''
3459
    @property
3460
    def activeDrawing(self):
3461
        return self._activeDrawing
3462

    
3463
    '''
3464
        @brief  setter of activeDrawing
3465
        @author humkyung
3466
        @date   2018.07.07
3467
    '''
3468
    @activeDrawing.setter
3469
    def activeDrawing(self, value):
3470
        self._activeDrawing = value
3471

    
3472
    def getColNames(self, table):
3473
        """
3474
        return column names of given table and attribute names if tabe is VALVE_DATA_LIST or EQUIPMET_DATA_LIST
3475
        """
3476
        res = None
3477
        try:
3478
            # Creates or opens a file called mydb with a SQLite3 DB
3479
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
3480
            conn = sqlite3.connect(dbPath)
3481
            cursor = conn.execute('select * from {}'.format(table))
3482
            res = [col_name[0] for col_name in cursor.description]
3483

    
3484
            if table == 'EQUIPMET_DATA_LIST' or table == 'VALVE_DATA_LIST':
3485
                sql = 'select distinct c.Attribute from {} a left join Attributes b on a.uid=b.Components_UID ' \
3486
                                                            'left join SymbolAttribute c on b.SymbolAttribute_UID=c.UID where c.Attribute is not NULL'.format(table)
3487
                cursor = conn.execute(sql)
3488
                rows = cursor.fetchall()
3489
                for row in rows:
3490
                    res.append(row[0])
3491
        # Catch the exception
3492
        except Exception as ex:
3493
            # Roll back any change if something goes wrong
3494
            conn.rollback()
3495
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
3496
        finally:
3497
            # Close the db connection
3498
            conn.close()
3499

    
3500
        return res
3501
    
3502
    def add_column_into_table(self, table, columnName):
3503
        '''
3504
            @brief  add column into table
3505
            @author euisung
3506
            @date   2019.03.13
3507
        '''
3508
        err = False
3509
        try:
3510
            # Creates or opens a file called mydb with a SQLite3 DB
3511
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
3512
            conn = sqlite3.connect(dbPath)
3513
            # Get a cursor object
3514
            cursor = conn.cursor()
3515
            sql = "alter table {} add {}".format(table, columnName)
3516
            cursor.execute(sql)
3517

    
3518
            conn.commit()
3519

    
3520
        # Catch the exception
3521
        except Exception as ex:
3522
            # Roll back any change if something goes wrong
3523
            conn.rollback()
3524
            err = True
3525
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
3526
        finally:
3527
            # Close the db connection
3528
            conn.close()
3529
            return (True if not err else False)
3530

    
3531
    def edit_column_Name_in_table(self, table, columnName, newColName):
3532
        '''
3533
            @brief  edit column into table
3534
            @author euisung
3535
            @date   2019.03.13
3536
        '''
3537
        err = False
3538
        colNames = AppDocData.instance().getColNames(table)
3539

    
3540
        for index in range(len(colNames)):
3541
            if colNames[index] == columnName:
3542
                colNames[index] = newColName
3543
                break
3544

    
3545
        try:
3546
            # Creates or opens a file called mydb with a SQLite3 DB
3547
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
3548
            conn = sqlite3.connect(dbPath)
3549
            # Get a cursor object
3550
            cursor = conn.cursor()
3551
            sql = "ALTER TABLE {} RENAME TO {}".format(table, table + '_orig')
3552
            cursor.execute(sql)
3553
            value = []
3554
            for colName in colNames:
3555
                value.append(colName + ' TEXT')
3556
            sql = "CREATE TABLE {}({}, CONSTRAINT '{}_PK' PRIMARY KEY('UID'))".format(table, ','.join(value), table)
3557
            cursor.execute(sql)
3558
            sql = "INSERT INTO {} SELECT * FROM {}".format(table, table + '_orig')
3559
            cursor.execute(sql)
3560
            sql = "DROP TABLE {}".format(table + '_orig')
3561
            cursor.execute(sql)
3562

    
3563
            conn.commit()
3564

    
3565
        # Catch the exception
3566
        except Exception as ex:
3567
            # Roll back any change if something goes wrong
3568
            conn.rollback()
3569
            err = True
3570
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
3571
        finally:
3572
            # Close the db connection
3573
            conn.close()
3574
            return (True if not err else False)
3575

    
3576
    '''
3577
        @brief  getter of OCRData
3578
        @author humkyung
3579
        @date   2018.11.19
3580
    '''
3581
    @property
3582
    def OCRData(self):
3583
        if self._OCRData is None:
3584
            configs = self.getConfigs('Text Recognition', 'OCR Data')
3585
            self._OCRData = configs[0].value if 1 == len(configs) else 'eng'
3586

    
3587
        return self._OCRData
3588

    
3589
    '''
3590
        @brief  setter of OCRData
3591
        @author humkyung
3592
        @date   2018.11.19
3593
    '''
3594
    @OCRData.setter
3595
    def OCRData(self, value):
3596
        self._OCRData = value
클립보드 이미지 추가 (최대 크기: 500 MB)