프로젝트

일반

사용자정보

개정판 5ddf3ffe

ID5ddf3ffee8e9ceb4e32c84c4aad4d4cedfcd2946
상위 50bad001
하위 d4ca9bd3

김연진이(가) 5년 이상 전에 추가함

issue #1048 : 화면/메뉴/툴바 개발 - Project DB 에서 Drawing DB로 변경 되면서 불필요한 파일 삭제

Change-Id: Ife46ead4e08756028655017814a0e2c03d11b9d7

차이점 보기:

HYTOS/HYTOS/AirFinCooler.py
9 9
from PyQt5 import QtCore, QtGui, QtWidgets
10 10
from PyQt5.QtWidgets import *
11 11
import os
12
from Project import Project
13 12
from AppDocData import AppDocData
14 13
import AirFinCooler_UI
15 14
import math
HYTOS/HYTOS/App.py
99 99
'''
100 100
if __name__ == '__main__':
101 101
    from AppDocData import AppDocData
102
    from ProjectDialog import Ui_Dialog
103 102
    from MainWindow import MainWindow
104 103
    from ExceptionHandler import QExceptionHandler
105 104

  
HYTOS/HYTOS/AppDocData.py
51 51
        self.key = key
52 52
        self.value = value
53 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

  
54
    
72 55
'''
73 56
    @brief      MessageType
74 57
    @author     humkyung 
......
79 62
    Error = 2
80 63

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

  
65
    
84 66
    def __init__(self):
85 67
        from DisplayColors import DisplayColors
86 68

  
......
174 156
        return app_database 
175 157

  
176 158
    '''
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 159
        @brief  build application database
447 160
        @author humkyung
448 161
        @date   2018.04.20
......
484 197
    def loadAppStyle(self):
485 198
        style = 'Fusion'
486 199

  
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 200
        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

  
201
        
548 202
    @property
549 203
    def border_file_path(self):
550 204
        """ return border file path """
......
559 213
        path = os.path.join(os.getenv('ALLUSERSPROFILE'), App.NAME)
560 214
        return os.path.join(path, 'svg')
561 215

  
562
    '''
563
        @brief  Get current Project
564
    '''
565
    def getCurrentProject(self):
566
        return self.project
216
    def getRoughness(self):
217
        res = []
567 218

  
568
    '''
569
        @brief      return project database path
570
        @history    humkyung 2018.04.19 return Project.db in Program Data folder instead of PROJECT_DB_PATH variable
571
    '''
572
    def getPrjDatabasePath(self):
573
        path = os.path.join(os.getenv('ALLUSERSPROFILE'), App.NAME)
574
        if not os.path.exists(path): os.makedirs(path)
219
        conn = sqlite3.connect(self.activeDrawing.path)
220
        with conn:
221
            try:
222
                conn.row_factory = sqlite3.Row
223
                # Get a cursor object
224
                cursor = conn.cursor()
225

  
226
                sql = "select UID, Material, Meter, Inch, Feet, Milimeter from Roughness" 
227
                cursor.execute(sql)
228
                rows = cursor.fetchall()
229
                for row in rows:                
230
                    res.append((row[0], row[1], row[2], row[3], row[4], row[5]))
231
            # Catch the exception
232
            except Exception as ex:
233
                # Roll back any change if something goes wrong
234
                conn.rollback()
235
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
575 236

  
576
        prjDatabaseFilePath = os.path.join(path, 'Project.db')
237
        return res
238

  
239
    def getInsideDiameter(self, nominaldiameter_uid, schedule_uid):
240
        res = []
577 241
        try:
578
            # Creates or opens a file called mydb with a SQLite3 DB
579
            conn = sqlite3.connect(prjDatabaseFilePath)
242
            db = sqlite3.connect(self.activeDrawing.path)
580 243
            # Get a cursor object
581
            cursor = conn.cursor()
244
            cursor = db.cursor()
582 245

  
583
            filePath = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'Scripts', 'Project.Projects.sql')
584
            try:
585
                file = QFile(filePath)
586
                file.open(QFile.ReadOnly)
587
                sql = file.readAll()
588
                sql = str(sql, encoding='utf8')
589
                cursor.executescript(sql)
590
            finally:
591
                file.close()
592
            conn.commit()
246
            sql = """select UID
247
                          , Milimeter
248
                          , Inch 
249
                       from InsideDiameter
250
                      where NominalDiameter_UID = ?
251
                        and Schedule_UID = ?"""
252

  
253
            param = (nominaldiameter_uid, schedule_uid)
254
            cursor.execute(sql, param)
255
            rows = cursor.fetchall()
256
            for row in rows:                
257
                res.append((row[0], row[1], row[2]))
593 258
        # Catch the exception
594 259
        except Exception as ex:
595 260
            # Roll back any change if something goes wrong
596
            conn.rollback()
261
            db.rollback()
597 262
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
598 263
        finally:
599 264
            # Close the db connection
600
            conn.close()
601
        
602
        return prjDatabaseFilePath
265
            db.close()
603 266

  
604
    def getErrorItemSvgPath(self):
605
        '''
606
            @brief  return error item svg path
607
            @author euisung
608
            @date   2019.04.02
609
        '''
610
        return os.path.join(os.getenv('ALLUSERSPROFILE'), App.NAME, 'Explode.svg')
611

  
612
    def updateTitleBlockProperties(self, titleBlockProps):
613
        '''
614
            @brief  update title block properties
615
            @author euisung
616
            @date   2018.11.09
617
        '''
618
        try:
619
            for titleBlockProp in titleBlockProps:
620
                titleBlockProp[1] = self.imgName + '!@!' + titleBlockProp[1]
621
            originTitleBlockProps = self.getTitleBlockProperties()
622
            deletedTitleBlockProps = []
623
            for originTitleBlockProp in originTitleBlockProps:
624
                for titleBlockProp in titleBlockProps:
625
                    # uid compare for determine delete props
626
                    if originTitleBlockProp[0] == titleBlockProp[0]:
627
                        break
628
                deletedTitleBlockProps.append(originTitleBlockProp[0])
629
            
630
            # Creates or opens a file called mydb with a SQLite3 DB
631
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
632
            conn = sqlite3.connect(dbPath)
633
            # Get a cursor object
634
            cursor = conn.cursor()
635

  
636
            for deletedTitleBlockProp in deletedTitleBlockProps:
637
                sql = "delete from TitleBlockProperties where UID='{}'".format(deletedTitleBlockProp)
638
                cursor.execute(sql)
639

  
640
            for titleBlockProp in titleBlockProps:
641
                sql = "insert or replace into TitleBlockProperties values(?,?,?)"
642
                param = (titleBlockProp[0], titleBlockProp[1], titleBlockProp[2]) # uid, name, area
643
                cursor.execute(sql, param)
644
            conn.commit()
645
        # Catch the exception
646
        except Exception as ex:
647
            # Roll back any change if something goes wrong
648
            conn.rollback()
649
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
650
        finally:
651
            # Close the db connection
652
            conn.close()
653

  
654
        self._titleBlockProperties = None
655
    
656
    def getTitleBlockProperties(self):
657
        '''
658
            @brief  return title block properties
659
            @author euisung
660
            @date   2018.11.09
661
        '''
662
        res = None
663
        if True:#self._titleBlockProperties is None:
664
            try:
665
                self._titleBlockProperties = []
666

  
667
                # Creates or opens a file called mydb with a SQLite3 DB
668
                dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
669
                db = sqlite3.connect(dbPath)
670
                # Get a cursor object
671
                cursor = db.cursor()
672

  
673
                sql = "select UID, Name, AREA from TitleBlockProperties" 
674
                cursor.execute(sql)
675
                rows = cursor.fetchall()
676
                for row in rows:
677
                    if row[1].split('!@!')[0] != self.imgName:
678
                        continue
679
                    else:
680
                        attr = []
681
                        attr.append(row[0]) # uid
682
                        attr.append(row[1].split('!@!')[1]) # name
683
                        attr.append(row[2]) # area
684
                        self._titleBlockProperties.append(attr)
685
                
686
                res = self._titleBlockProperties
687
            # Catch the exception
688
            except Exception as ex:
689
                # Roll back any change if something goes wrong
690
                db.rollback()
691
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
692
            finally:
693
                # Close the db connection
694
                db.close()
695
        else:
696
            res = self._titleBlockProperties
697

  
698
        return res
699

  
700
    def clearLineNoProperties(self):
701
        self._lineNoProperties = None
702

  
703
    '''
704
        @brief  return line properties
705
        @author humkyung
706
        @date   2018.04.09
707
    '''
708
    def getLineProperties(self):
709
        from SymbolAttr import SymbolAttr
710

  
711
        res = None
712
        if self._lineNoProperties is None:
713
            try:
714
                self._lineNoProperties = []
715

  
716
                # Creates or opens a file called mydb with a SQLite3 DB
717
                dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
718
                db = sqlite3.connect(dbPath)
719
                # Get a cursor object
720
                cursor = db.cursor()
721

  
722
                sql = "select UID, Name, DisplayName, Type, LimitNumber, [index] from LineProperties order by [index]" 
723
                cursor.execute(sql)
724
                rows = cursor.fetchall()
725
                for row in rows:
726
                    attr = SymbolAttr()
727
                    attr.UID = row[0]
728
                    attr.Attribute = row[1]
729
                    attr.DisplayAttribute = row[2]
730
                    attr.AttributeType = row[3]
731
                    attr.Length = row[4]
732
                    self._lineNoProperties.append(attr)
733
                
734
                res = self._lineNoProperties
735
            # Catch the exception
736
            except Exception as ex:
737
                # Roll back any change if something goes wrong
738
                db.rollback()
739
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
740
            finally:
741
                # Close the db connection
742
                db.close()
743
        else:
744
            res = self._lineNoProperties
745

  
746
        return res
747

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

  
756
        res = []
757
        try:
758
            # Creates or opens a file called mydb with a SQLite3 DB
759
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
760
            db = sqlite3.connect(dbPath)
761
            # Get a cursor object
762
            cursor = db.cursor()
763

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

  
784
        return res
785

  
786
    def getRoughness(self):
787
        res = []
788

  
789
        conn = sqlite3.connect(self.activeDrawing.path)
790
        with conn:
791
            try:
792
                conn.row_factory = sqlite3.Row
793
                # Get a cursor object
794
                cursor = conn.cursor()
795

  
796
                sql = "select UID, Material, Meter, Inch, Feet, Milimeter from Roughness" 
797
                cursor.execute(sql)
798
                rows = cursor.fetchall()
799
                for row in rows:                
800
                    res.append((row[0], row[1], row[2], row[3], row[4], row[5]))
801
            # Catch the exception
802
            except Exception as ex:
803
                # Roll back any change if something goes wrong
804
                conn.rollback()
805
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
806

  
807
        return res
808

  
809
    def getInsideDiameter(self, nominaldiameter_uid, schedule_uid):
810
        res = []
811
        try:
812
            # Creates or opens a file called mydb with a SQLite3 DB
813
            #dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
814
            #db = sqlite3.connect(dbPath)
815
            db = sqlite3.connect(self.activeDrawing.path)
816
            # Get a cursor object
817
            cursor = db.cursor()
818

  
819
            sql = """select UID
820
                          , Milimeter
821
                          , Inch 
822
                       from InsideDiameter
823
                      where NominalDiameter_UID = ?
824
                        and Schedule_UID = ?"""
825

  
826
            param = (nominaldiameter_uid, schedule_uid)
827
            cursor.execute(sql, param)
828
            rows = cursor.fetchall()
829
            for row in rows:                
830
                res.append((row[0], row[1], row[2]))
831
        # Catch the exception
832
        except Exception as ex:
833
            # Roll back any change if something goes wrong
834
            db.rollback()
835
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
836
        finally:
837
            # Close the db connection
838
            db.close()
839

  
840
        return res
267
        return res
841 268

  
842 269
    def getSchedule(self):
843 270
        res = []
......
861 288

  
862 289
        return res
863 290

  
864
    def getNominalDiameter(self):
865
        
291
    def getNominalDiameter(self):        
866 292
        res = []
867 293

  
868 294
        # Creates or opens a file called mydb with a SQLite3 DB
......
885 311

  
886 312
        return res
887 313

  
888
    '''
889
        @brief  return line types 
890
        @author humkyung
891
        @date   2018.06.27
892
    '''
893
    def getLineTypes(self):
894
        from LineTypeConditions import LineTypeConditions
895

  
896
        res = []
897
        try:
898
            # Creates or opens a file called mydb with a SQLite3 DB
899
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
900
            db = sqlite3.connect(dbPath)
901
            # Get a cursor object
902
            cursor = db.cursor()
903

  
904
            sql = "select UID,Name,Type1,Conditions1,Type2,Conditions2 from LineTypes order by Name" 
905
            cursor.execute(sql)
906
            rows = cursor.fetchall()
907
            for row in rows:
908
                line_type = LineTypeConditions(row[0], row[1])
909
                line_type._conditions[0][0] = row[2]
910
                line_type._conditions[0][1] = row[3]
911
                line_type._conditions[1][0] = row[4]
912
                line_type._conditions[1][1] = row[5]
913
                res.append(line_type)
914
        # Catch the exception
915
        except Exception as ex:
916
            # Roll back any change if something goes wrong
917
            db.rollback()
918
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
919
        finally:
920
            # Close the db connection
921
            db.close()
922

  
923
        return res
924

  
925
    '''
926
        @brief      Insert New Project Info
927
        @author     Jeongwoo
928
        @date       2018.04.06
929
        @history    humkyung 2018.04.19 use getPrjDatabasePath function instead of PROJECT_DB_PATH variable
930
    '''
931
    def insertProjectInfo(self, desc, dir):
932
        try:
933
            prjDatabaseFilePath = self.getPrjDatabasePath()
934
            conn = sqlite3.connect(prjDatabaseFilePath)
935
            folderName = dir.split('/')[-1]
936
            if folderName:
937
                nowDate = datetime.datetime.now().strftime('%Y.%m.%d %H:%M')
938
                sql = "insert or replace into Projects(Name, [Desc], Path, CreatedDate, UpdatedDate) values(?, ?, ?, ?, ?)"
939
                param = (folderName, desc, dir, nowDate, nowDate)
940 314
    
941
                cursor = conn.cursor()
942
                cursor.execute(sql, param)
943
                conn.commit()
944
            else:
945
                print("Empty folder name")
946
        except Exception as ex:
947
            # Roll back any change if something goes wrong
948
            conn.rollback()
949
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
950
        finally:
951
            conn.close()
952

  
953
    def removeProjectInfo(self, targetProject):
954
        '''
955
        @brief      Remove Project Info
956
        @author     Euisung
957
        @date       2019.01.28
958
        '''
959
        try:
960
            prjDatabaseFilePath = self.getPrjDatabasePath()
961
            conn = sqlite3.connect(prjDatabaseFilePath)
962
            sql = "delete from Projects where Id = '{}'".format(targetProject.id)
963
            cur = conn.cursor()
964
            cur.execute(sql)
965
            conn.commit()
966
        except Exception as ex:
967
            # Roll back any change if something goes wrong
968
            conn.rollback()
969
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
970
        finally:
971
            conn.close()
972

  
973
    '''
974
        @brief      Update Project UpdatedDate Field
975
        @author     Jeongwoo
976
        @date       2018.04.06
977
        @history    humkyung 2018.04.19 use getPrjDatabasePath function instead of PROJECT_DB_PATH variable
978
    '''
979
    def updateProjectUpdatedDate(self, id, desc):
980
        try:
981
            prjDatabaseFilePath = self.getPrjDatabasePath()
982
            conn = sqlite3.connect(prjDatabaseFilePath)
983
            nowDate = datetime.datetime.now().strftime('%Y.%m.%d %H:%M')
984
            sql = '''
985
                UPDATE Projects
986
                SET UpdatedDate = ?,[Desc]=? 
987
                WHERE Id = ?
988
            '''
989
            cur = conn.cursor()
990
            cur.execute(sql, (nowDate, desc, id))
991
            conn.commit()
992
        except Exception as ex:
993
            # Roll back any change if something goes wrong
994
            conn.rollback()
995
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
996
        finally:
997
            conn.close()
998

  
999
    '''
1000
        @brief  get project list from database
1001
        @history    humkyung 2018.04.18 add only project which's project exists
1002
    '''
1003
    def getProjectList(self):
1004
        from Project import Project
1005

  
1006
        projectList = []
1007

  
1008
        try:
1009
            conn = sqlite3.connect(self.getPrjDatabasePath())
1010
            cursor = conn.cursor()
1011
            sql = 'SELECT id,name,[desc],path,createddate,updateddate  FROM Projects ORDER BY UpdatedDate DESC'
1012
            try:
1013
                cursor.execute(sql)
1014
                rows = cursor.fetchall()
1015
                for row in rows:
1016
                    if os.path.isdir(row[3]):   # check if folder exists
1017
                        projectList.append(Project(row[0], row[1], desc=row[2], path=row[3], createDate=row[4], updateDate=row[5]))
1018
            except Exception as ex:
1019
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1020
        finally:
1021
            conn.close()
1022

  
1023
        return projectList
1024

  
1025
    '''
1026
        @brief  get sliding window size
1027
        @author humkyung
1028
    '''
1029
    def getSlidingWindowSize(self):
1030
        res = [10,15]
1031
        try:
1032
            configs = self.getConfigs('Sliding Window')
1033
            for config in configs:
1034
                if config.key == 'Width':
1035
                    res[0] = int(config.value)
1036
                elif config.key == 'Height':
1037
                    res[1] = int(config.value)
1038
        # Catch the exception
1039
        except Exception as ex:
1040
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1041
        
1042
        return res
1043

  
1044
    '''
1045
        @brief  get line no configuration
1046
        @author humkyung
1047
        @date   2018.04.16
1048
    '''
1049
    def getLineNoConfiguration(self):
1050
        res = None
1051
        try:
1052
            # Creates or opens a file called mydb with a SQLite3 DB
1053
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
1054
            conn = sqlite3.connect(dbPath)
1055
            # Get a cursor object
1056
            cursor = conn.cursor()
1057

  
1058
            delimiter = None
1059
            sql = "select * from configuration where section='Line No' and key='Delimiter"
1060
            cursor.execute(sql)
1061
            rows = cursor.fetchall()
1062
            if len(rows) == 1:
1063
                delimiter = rows[0][2]
1064

  
1065
            if delimiter is not None:
1066
                sql = "select * from configuration where section='Line No' and key='Configuration'"
1067
                cursor.execute(sql)
1068
                rows = cursor.fetchall()
1069
                if len(rows) == 1:
1070
                    res = rows[0][2].split(delimiter)
1071
        # Catch the exception
1072
        except Exception as ex:
1073
            # Roll back any change if something goes wrong
1074
            conn.rollback()
1075
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1076
        finally:
1077
            # Close the db connection
1078
            conn.close()
1079
        
1080
        return res
1081

  
1082
    '''
1083
        @brief  get area list
1084
        @author humkyung
1085
        @history    euisung     2018.11.20 (0,0),(0,0) process add
1086
    '''
1087
    def getAreaList(self):
1088
        from Area import Area
1089

  
1090
        if len(self._areas) == 0:
1091
            try:
1092
                # Creates or opens a file called mydb with a SQLite3 DB
1093
                dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
1094
                conn = sqlite3.connect(dbPath)
1095
                # Get a cursor object
1096
                cursor = conn.cursor()
1097

  
1098
                sql = "select * from configuration where section='Area'"
1099
                cursor.execute(sql)
1100
                rows = cursor.fetchall()
1101
                for row in rows:
1102
                    name = row[1]
1103
                    area = Area(name)
1104
                    area.parse(row[2])
1105
                    self._areas.append(area)
1106
            # Catch the exception
1107
            except Exception as ex:
1108
                # Roll back any change if something goes wrong
1109
                conn.rollback()
1110
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1111
            finally:
1112
                # Close the db connection
1113
                conn.close()
1114
        
1115
        return self._areas 
1116

  
1117
    '''
1118
        @brief  get area of given name
1119
        @author humkyung
1120
        @date   2018.04.07
1121
    '''
1122
    def getArea(self, name):
1123
        areas = self.getAreaList()
1124
        matches = [area for area in areas if area.name==name]
1125
        if 1 == len(matches) and matches[0].height is not 0 and matches[0].width is not 0:
1126
            return matches[0]
1127

  
1128
        return None
1129

  
1130
    '''
1131
        @brief  get configurations
1132
        @author humkyung
1133
        @date   2018.04.16
1134
        @history kyouho 2018.07.09 change query method
1135
    '''
1136
    '''
1137
    def getConfigs(self, section, key=None):
1138
        res = []
1139

  
1140
        try:
1141
            # Creates or opens a file called mydb with a SQLite3 DB
1142
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
1143
            conn = sqlite3.connect(dbPath)
1144
            # Get a cursor object
1145
            cursor = conn.cursor()
1146

  
1147
            if key is not None:
1148
                sql = "select * from configuration where section=? and key=?"
1149
                param = (section, key)
1150
            else:
1151
                sql = "select * from configuration where section=?"
1152
                param = (section,)
1153

  
1154
            cursor.execute(sql, param)
1155
            rows = cursor.fetchall()
1156
            for row in rows:
1157
                res.append(Config(row[0], row[1], row[2]))
1158
        # Catch the exception
1159
        except Exception as ex:
1160
            # Roll back any change if something goes wrong
1161
            conn.rollback()
1162
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1163
        finally:
1164
            # Close the db connection
1165
            conn.close()
1166

  
1167
        return res
1168
        '''
1169
    def getConfigs(self, section, key=None):        
1170
        res = []
1171

  
1172
        if self.configTable is None:
1173
            self.configTable = []
1174
            try:
1175
                # Creates or opens a file called mydb with a SQLite3 DB
1176
                dbPath = self.getAppDbPath()
1177
                conn = sqlite3.connect(dbPath)
1178
                # Get a cursor object
1179
                cursor = conn.cursor()
1180

  
1181
                sql = "select Section, Key, Value from configuration"
1182
            
1183
                cursor.execute(sql)
1184
                rows = cursor.fetchall()
1185
                for row in rows:
1186
                    self.configTable.append(Config(row[0], row[1], row[2]))
1187
                # Catch the exception
1188
            except Exception as ex:
1189
                # Roll back any change if something goes wrong
1190
                conn.rollback()
1191
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1192
            finally:
1193
                # Close the db connection
1194
                conn.close()
1195

  
1196
        if key is not None:
1197
            for con in self.configTable:
1198
                if con.section == section and con.key == key:
1199
                    res.append(con)
1200
        else:
1201
            for con in self.configTable:
1202
                if con.section == section:
1203
                    res.append(con)
1204

  
1205
        return res
1206

  
1207 315
    def getAppConfigs(self, section, key=None):
1208 316
        """
1209 317
            @brief  get application configurations
1210
            @author humkyung
1211
            @date   2018.11.01
1212
        """
1213

  
1214
        res = []
1215

  
1216
        try:
1217
            # Creates or opens a file called mydb with a SQLite3 DB
1218
            dbPath = self.getAppDbPath()
1219
            conn = sqlite3.connect(dbPath)
1220
            # Get a cursor object
1221
            cursor = conn.cursor()
1222

  
1223
            if key is not None:
1224
                sql = "select * from configuration where section=? and key=?"
1225
                param = (section, key)
1226
            else:
1227
                sql = "select * from configuration where section=?"
1228
                param = (section,)
1229

  
1230
            cursor.execute(sql, param)
1231
            rows = cursor.fetchall()
1232
            for row in rows:
1233
                res.append(Config(row[0], row[1], row[2]))
1234
        # Catch the exception
1235
        except Exception as ex:
1236
            # Roll back any change if something goes wrong
1237
            conn.rollback()
1238
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1239
        finally:
1240
            # Close the db connection
1241
            conn.close()
1242

  
1243
        return res
1244

  
1245
    '''
1246
        @brief      save configurations
1247
        @author     humkyung
1248
        @date       2018.04.16
1249
        @history    humkyung 2018.07.03 replace ' with " if value has '
1250
                    kyouho 2018.07.09 change query method
1251
    '''
1252
    def saveConfigs(self, configs):
1253
        import uuid
1254
        
1255
        try:
1256
            # Creates or opens a file called mydb with a SQLite3 DB
1257
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
1258
            conn = sqlite3.connect(dbPath, isolation_level=None)
1259
            # Get a cursor object
1260
            cursor = conn.cursor()
1261

  
1262
            for config in configs:
1263
                if type(config) is Config:
1264
                    value = config.value
1265
                    if type(value) is str and "'" in value:
1266
                        value = value.replace("'", "''")
1267

  
1268
                    sql = "insert or replace into configuration values(?,?,?,?)"
1269
                    param = (str(uuid.uuid4()), config.section, config.key, value)                    
1270

  
1271
                    cursor.execute(sql, param)
1272
                elif hasattr(config, 'toSql'):
1273
                    sql = config.toSql()
1274
                    if type(sql) is list:
1275
                        for item in sql:
1276
                            if item is not None and 2 == len(item):
1277
                                cursor.execute(item[0], item[1])
1278
                    else:
1279
                        if sql is not None and 2 == len(sql):
1280
                            cursor.execute(sql[0], sql[1])
1281

  
1282
            conn.commit()
1283
        # Catch the exception
1284
        except Exception as ex:
1285
            # Roll back any change if something goes wrong
1286
            conn.rollback()
1287
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1288
        finally:
1289
            # Close the db connection
1290
            conn.close()
1291

  
1292
    def saveAppConfigs(self, configs):
1293
        """
1294
        @brief      save application configurations
1295
        @author     humkyung
1296
        @date       2018.10.01
1297
        """
1298

  
1299
        try:
1300
            # Creates or opens a file called mydb with a SQLite3 DB
1301
            dbPath = self.getAppDbPath()
1302
            conn = sqlite3.connect(dbPath)
1303
            # Get a cursor object
1304
            cursor = conn.cursor()
1305

  
1306
            for config in configs:
1307
                value = config.value
1308
                if type(value) is str and "'" in value:
1309
                    value = value.replace("'", "''")
1310

  
1311
                sql = "insert or replace into configuration values(?,?,?)"
1312
                param = (config.section, config.key, value)
1313

  
1314
                cursor.execute(sql, param)
1315
            conn.commit()
1316
        # Catch the exception
1317
        except Exception as ex:
1318
            # Roll back any change if something goes wrong
1319
            conn.rollback()
1320
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1321
        finally:
1322
            # Close the db connection
1323
            conn.close()
1324

  
1325

  
1326
    def initializeDataByDrawingUID(self, uid):
1327
        try:
1328
            # Creates or opens a file called mydb with a SQLite3 DB
1329
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
1330
            conn = sqlite3.connect(dbPath)
1331
            # Get a cursor object
1332
            cursor = conn.cursor()
1333

  
1334
            # 0. Delete Points
1335
            sql = "delete from Points where Components_UID in (select UID from Components where Drawings_UID = '{}')".format(uid)
1336
            cursor.execute(sql)
1337

  
1338
            # 1. Delete HMB
1339
            sql = "delete from HMB where Components_UID in (select UID from Components where Drawings_UID = '{}')".format(uid)
1340
            cursor.execute(sql)
1341

  
1342
            # 2. Delete Components
1343
            sql = "delete from Components where Drawings_UID='{}'".format(uid)
1344
            cursor.execute(sql)            
1345
            
1346
            conn.commit()
1347
        # Catch the exception
1348
        except Exception as ex:
1349
            # Roll back any change if something goes wrong
1350
            conn.rollback()
1351
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1352
        finally:
1353
            # Close the db connection
1354
            conn.close()
1355

  
1356
    def deleteDrawingByName(self, drawingName):
1357
        """ delete given drawing """
1358
        conn = sqlite3.connect(self.getAppDbPath())
1359
        with conn:
1360
            try:
1361
                # Get a cursor object
1362
                cursor = conn.cursor()
1363

  
1364
                sql = 'delete from Drawings where Name=?'
1365
                param = (drawingName,)
1366
                cursor.execute(sql, param)
1367
                
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

  
1375
    '''
1376
        @brief  delete configurations
1377
        @author humkyung
1378
        @date   2018.06.29
1379
    '''
1380
    def deleteConfigs(self, section, key=None):
1381
        try:
1382
            # Creates or opens a file called mydb with a SQLite3 DB
1383
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
1384
            conn = sqlite3.connect(dbPath)
1385
            # Get a cursor object
1386
            cursor = conn.cursor()
1387

  
1388
            if key is not None:
1389
                sql = "delete from configuration where section='{}' and key='{}'".format(section, key)
1390
            else:
1391
                sql = "delete from configuration where section='{}'".format(section)
1392
            cursor.execute(sql)
1393

  
1394
            conn.commit()
1395
        # Catch the exception
1396
        except Exception as ex:
1397
            # Roll back any change if something goes wrong
1398
            conn.rollback()
1399
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1400
        finally:
1401
            # Close the db connection
1402
            conn.close()
1403

  
1404
    def deleteAppConfigs(self, section, key=None):
1405
        """
1406
        @brief  delete application configurations
1407
        @author humkyung
1408
        @date   2018.11.01
1409
        """
1410

  
1411
        try:
1412
            # Creates or opens a file called mydb with a SQLite3 DB
1413
            dbPath = self.getAppDbPath()
1414
            conn = sqlite3.connect(dbPath)
1415
            # Get a cursor object
1416
            cursor = conn.cursor()
1417

  
1418
            if key is not None:
1419
                sql = "delete from configuration where section='{}' and key='{}'".format(section, key)
1420
            else:
1421
                sql = "delete from configuration where section='{}'".format(section)
1422
            cursor.execute(sql)
1423

  
1424
            conn.commit()
1425
        # Catch the exception
1426
        except Exception as ex:
1427
            # Roll back any change if something goes wrong
1428
            conn.rollback()
1429
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1430
        finally:
1431
            # Close the db connection
1432
            conn.close()
1433

  
1434
    '''
1435
        @brief      set area list
1436
        @history    humkyung 2018.05.18 round area coordinate and dimension before saving
1437
        @history    euisung  2018.11.20 add self._area reset process
1438
    '''
1439
    def setAreaList(self, areas):
1440
        for area in areas:
1441
            matches = [x for x in self._areas if x.name==area.name]
1442
            if 1 == len(matches):
1443
                matches[0].x = area.x
1444
                matches[0].y = area.y
1445
                matches[0].width = area.width
1446
                matches[0].height = area.height
1447
            elif 0 == len(matches):
1448
                self._areas.append(area)
1449

  
1450
        try:
1451
            # Creates or opens a file called mydb with a SQLite3 DB
1452
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
1453
            conn = sqlite3.connect(dbPath)
1454
            # Get a cursor object
1455
            cursor = conn.cursor()
1456

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

  
1461
            conn.commit()
1462
        # Catch the exception
1463
        except Exception as ex:
1464
            # Roll back any change if something goes wrong
1465
            conn.rollback()
1466
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1467
        finally:
1468
            # Close the db connection
1469
            self._areas = []
1470
            conn.close()
1471
            
1472
    '''
1473
        @brief  get symbol name list
1474
    '''
1475
    def getSymbolNameList(self):
1476
        symbolNametList = []
1477

  
1478
        try:            
1479
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
1480

  
1481
            conn = sqlite3.connect(dbPath)
1482
            cursor = conn.cursor()
1483
            sql = 'SELECT * FROM SymbolName'
1484
            try:
1485
                cursor.execute(sql)
1486
                rows = cursor.fetchall()
1487
                for row in rows:
1488
                    symbolNametList.append(row[4]) # Name String
1489
            except Exception as ex:
1490
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1491
        finally:
1492
            conn.close()
1493

  
1494
        return symbolNametList
1495

  
1496
    '''
1497
        @brief      get symbol name list by symbol Type
1498
        @author     Jeongwoo
1499
        @date       18.04.06
1500
        @history    .
1501
    '''
1502
    def getSymbolNameListByType(self, type):
1503
        symbolNametList = []
1504

  
1505
        try:
1506
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
1507

  
1508
            conn = sqlite3.connect(dbPath)
1509
            cursor = conn.cursor()
1510
            sql = ''
1511
            if type is not None:
1512
                sql = 'SELECT * FROM SymbolName WHERE type = "' + type + '"'
1513
                try:
1514
                    cursor.execute(sql)
1515
                    rows = cursor.fetchall()
1516
                    for row in rows:
1517
                        symbolNametList.append(row[4]) # Name String
1518
                except Exception as ex:
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
            conn.close()
1522

  
1523
        return symbolNametList
1524

  
1525
    '''
1526
        @brief  delete added symbol data
1527
    '''
1528
    def deleteSymbol(self, fileName):
1529
        ret = False
1530
        try:
1531
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
1532

  
1533
            conn = sqlite3.connect(dbPath)
1534
            cursor = conn.cursor()
1535
            sql = "DELETE FROM Symbol WHERE name = ?"
1536
            try:
1537
                cursor.execute(sql, (fileName,))
1538
                conn.commit()
1539
                ret = True
1540
            except Exception as ex:
1541
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1542
                ret = False
1543
        finally:
1544
            conn.close()
1545
            return (ret, fileName)
1546
        
1547
    '''
1548
        @brief  get symbol name
1549
        @history    18.04.24    Jeongwoo    Add isExceptDetect Field
1550
    '''
1551
    def getSymbolByQuery(self, fieldName, param):
1552
        ret = None
1553

  
1554
        conn = sqlite3.connect(self.activeDrawing.path)
1555
        with conn:
1556
            cursor = conn.cursor()
1557

  
1558
            sql = """select s.UID
1559
                            , s.Name
1560
                            , t.Category
1561
                            , t.Type
1562
                            , s.OriginalPoint
1563
                            , s.ConnectionPoint
1564
                        from Symbols s
1565
                        inner join SymbolType t
1566
                            on s.SymbolType_UID = t.UID 
1567
                        where """ + "s." + fieldName + '=?'
1568

  
1569
            try:
1570
                cursor.execute(sql, (param,))
1571
                rows = cursor.fetchall()
1572
                if rows is not None and len(rows) > 0:
1573
                    symbolTuple = rows[0]
1574
                    ret = symbol.SymbolBase(symbolTuple[0], symbolTuple[1], symbolTuple[2], symbolTuple[3], symbolTuple[4], symbolTuple[5]) 
1575
            except Exception as ex:
1576
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1577

  
1578
        return ret
1579

  
1580
    def getSymbolListByUID(self, uid):
1581
        """ get symbol list by given uid """
1582
        ret = []
1583

  
1584
        conn = sqlite3.connect(self.getTemplateDbPath())
1585
        with conn:
1586
            cursor = conn.cursor()
1587
            
1588
            sql = """select s.UID
1589
                            , s.Name
1590
                            , t.Category
1591
                            , t.Type
1592
                            , s.OriginalPoint
1593
                            , s.ConnectionPoint
1594
                        from Symbols s
1595
                        inner join SymbolType t
1596
                            on s.SymbolType_UID = t.uid 
1597
                        where s.SymbolType_UID = ?"""
1598
            
1599
            try:
1600
                cursor.execute(sql, (uid,))
1601
                rows = cursor.fetchall()
1602
                if rows is not None and len(rows) > 0:
1603
                    for row in rows:
1604
                        sym = symbol.SymbolBase(row[0], row[1], row[2], row[3], row[4], row[5])
1605
                                                
1606
                        ret.append(sym)
1607
            except Exception as ex:
1608
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1609

  
1610
        return ret
1611

  
1612

  
1613
    '''
1614
        @brief  get symbol name list
1615
        @history    18.04.24    Jeongwoo    Add isExceptDetect Field
1616
    '''
1617
    def getSymbolListByType(self, fieldName=None, param=None):
1618
        ret = []
1619

  
1620
        try:
1621
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), AppDocData.DATABASE)
1622
            conn = sqlite3.connect(dbPath)
1623
            cursor = conn.cursor()
1624
            if fieldName is not None and param is not None:
1625

  
1626
                sql = """select s.UID
1627
                              , s.Name
1628
                              , t.Category
1629
                              , t.Type
1630
                              , s.OriginalPoint
1631
                              , s.ConnectionPoint
... 이 차이점은 표시할 수 있는 최대 줄수를 초과해서 이 차이점은 잘렸습니다.

내보내기 Unified diff

클립보드 이미지 추가 (최대 크기: 500 MB)