-
Notifications
You must be signed in to change notification settings - Fork 0
/
oracle.py
2748 lines (2399 loc) · 101 KB
/
oracle.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
from __future__ import with_statement
import sublime, sublime_plugin, sublime_plugin
import re,cx_Oracle,json,xml.parsers.expat
import os,sys,traceback,datetime,time,threading,thread
import pyPEG
from pyPEG import parse,parseLine,keyword, _and, _not, ignore,Symbol
from xml.sax.saxutils import escape
plugin_name = "CFT"
plugin_path = os.path.join(sublime.packages_path(),plugin_name)
cache_path = os.path.join(plugin_path,"cache")
used_classes_file_path = os.path.join(plugin_path,"cache","cft_settings.json")
TIMER_DEBUG = True
pyPEG.print_trace = True
USE_PARSER = False
beg_whites_regex = re.compile(r'^\s*') #ищем начало строки без пробелов
end_whites_regex = re.compile(r'\s*$') #ищем конец строки без пробелов
sections_regex = re.compile(r'(╒═+╕\n│ ([A-Z]+) +│\n)(.*?)\n?(└─+┘\n)'.decode('utf-8'),re.S) #поиск секций
class NewCommand(sublime_plugin.TextCommand):
def run(self, edit):
p = PathHelper(self.view.file_name())
method_id = self.Create_Method(p.class_name,p.oper_name,'HELLO!!!')
self.view.insert(edit, self.view.size(),method_id )
def Create_Method(self,class_name,oper_name,full_name):
connection = cx_Oracle.connect('ibs/ibs@cfttest')
cursor = connection.cursor()
method_id = cursor.var(cx_Oracle.STRING)
plsql = """
BEGIN
:method_id := Z$RUNTIME_PLP_TOOLS.Create_Method(:p_Class, :p_Short_Name, :p_Full_Name);
END;
"""
execute_proc = cursor.execute(plsql, (method_id,class_name, oper_name, full_name))
cursor.close()
connection.close()
return method_id.getvalue();
def with_exec_time(callback):
dbeg = datetime.datetime.now()
r = None
if callback:
r = callback()
delta = datetime.datetime.now() - dbeg
delta_str = (datetime.datetime.min + delta).time().strftime("%H:%M:%S.%f").strip("0:")
print callback.__name__ + ', выполнена за ' + delta_str
return r
def call_async(call_func,on_complete=None,msg=None,async_callback=False):
class ThreadProgress():
def __init__(self, thread, message):
self.thread = thread
self.message = message
self.addend = 1
self.size = 8
self.d_begin = datetime.datetime.now()
sublime.set_timeout(lambda: self.run(0), 100)
def run(self, i):
if not self.thread.is_alive():
if hasattr(self.thread, 'result') and not self.thread.result:
sublime.status_message('')
return
delta = datetime.datetime.now() - self.d_begin
delta_str = (datetime.datetime.min + delta).time().strftime("%H:%M:%S.%f").strip("0:")
how_long = unicode("Выполненно за %s сек" % delta_str,'utf-8')
how_long = unicode(self.message + ". ",'utf-8') + how_long if self.message else how_long
sublime.status_message(how_long)
return
before = i % self.size
after = (self.size - 1) - before
sublime.status_message('%s [%s=%s]' % \
(unicode(self.message,'utf-8'), ' ' * before, ' ' * after))
if not after:
self.addend = -1
if not before:
self.addend = 1
i += self.addend
sublime.set_timeout(lambda: self.run(i), 100)
class RunInThread(threading.Thread):
def run(self):
try:
if msg:
ThreadProgress(self,msg)
#t = timer()
self.result = call_func()
#t.print_time(msg + ' ' if msg else '' + "call_async func:" + call_func.__name__)
if on_complete:
def on_done():
#t = timer()
if not self.result:
on_complete()
elif self.result.__class__ == tuple:
on_complete(*self.result)
else:
on_complete(self.result)
#t.print_time(msg + ' ' + "call_async on_complete:" + on_complete.__name__)
if async_callback:
on_done()
else:
sublime.set_timeout(on_done, 0)
except Exception,e:
print "*** Ошибка асинхронного вызова:",e
print "*** При вызове ",call_func.im_class if hasattr(call_func,"im_class") else "",call_func.__name__
if sys != None:
exc_type, exc_value, exc_traceback = sys.exc_info()
traceback.print_exception(exc_type, exc_value, exc_traceback,
limit=10, file=sys.stdout)
RunInThread(on_complete).start()
def sub(p_str,from_str,to_str,p_start=0):
"""
Функция возвращает подстроку между двумя строками
Включая эти строки
Например sub(text,"declare","end;")
"""
begin = p_str.find(from_str,p_start)#-len(from_str)
end = p_str.rfind(to_str,p_start)+len(to_str)
return p_str[begin:end].strip()
def string_table(arr,template):
rows = ""
tmp = template
re_param = re.compile(r'{(\w+)}')
def get(obj,name):
if type(obj) is dict: return str(obj[name])
return str(getattr(obj,name))
for s in re_param.finditer(template):
name = s.group(1)
l = lambda a: len(get(a,name))
m = l(max(arr,key=l))
tmp = tmp.replace("{%s}"%name,"%-"+str(m)+"s")
for a in arr:
t = tuple(get(a,s.group(1)) for s in re_param.finditer(template))
rows += (tmp%t).rstrip('\n') + "\n"
return rows.rstrip('\n')
class FileReader(object):
def __init__(self):
self.dir_path = os.path.join(sublime.packages_path(),plugin_name,"sql")
self.load()
#call_async(self.load)
@staticmethod
def read(file_path):
if not os.path.exists(file_path):
return ''
f = open(file_path,"r")
text = f.read()
f.close()
fileName, fileExtension = os.path.splitext(file_path)
if fileExtension == '.tst':
def sub(p_str,from_str,to_str,p_start=0):
begin = p_str.find(from_str,p_start)#-len(from_str)
end = p_str.rfind(to_str,p_start)+len(to_str)
return p_str[begin:end].strip()
text = sub(text,"declare","end;")
return text
@staticmethod
def write(file_path,text):
#file_path = os.path.join(sublime.packages_path(),plugin_name,file_path)
f = open(file_path,"w")
f.write(text)
f.close()
def substr(self,p_str,from_str,to_str,p_start=0):
begin = p_str.find(from_str,p_start)+1
end = p_str.find(to_str,p_start)
return p_str[begin:end].strip()
def load(self):
self.cft_schema_sql = self.read(os.path.join(plugin_path,"sql","cft_schema.sql"))
self.method_sources = self.read(os.path.join(plugin_path,"sql","method_sources.tst"))
self.package_sources = self.read(os.path.join(plugin_path,"sql","package_sources.tst"))
self.save_method_sources = self.read(os.path.join(plugin_path,"sql","save_method_sources.tst"))
self.method_sources_json = self.read(os.path.join(plugin_path,"sql","method_sources_json.tst"))
self.save_criteria_text = self.read(os.path.join(plugin_path,"sql","save_criteria_text.tst"))
self.classes_update = self.read(os.path.join(plugin_path,"sql","classes_update.sql"))
class cft_settings_class(dict):
def __init__(self):
super(cft_settings_class,self).__init__()
self.file_path = os.path.join(plugin_path,"cache","cft_settings.json")
self["used_classes"] = list()
call_async(self.load)
def save(self):
f = open(self.file_path,"w")
f.write(json.dumps(self))
f.close()
def load(self):
r = FileReader.read(self.file_path)
if len(r)>0:
super(cft_settings_class,self).__init__(json.loads(r))
def update_used_class(self,class_id):
used_classes = cft_settings["used_classes"]
if class_id in used_classes:
used_classes.remove(class_id)
used_classes.insert(0,class_id)
cft_settings.save()
cft_settings = cft_settings_class()
class timer(object):
def __init__(self):
self.begin = datetime.datetime.now()
self.last = datetime.datetime.now()
def get_time_delta_str(self,begin,end):
delta = end - begin
delta_str = (datetime.datetime.min + delta).time().strftime("%H:%M:%S.%f").strip("0:")
return delta_str
def get_time(self):
#delta = datetime.datetime.now() - self.begin
#delta_str = (datetime.datetime.min + delta).time().strftime("%H:%M:%S.%f").strip("0:")
#return delta_str
return self.get_time_delta_str(self.begin,datetime.datetime.now())
def get_now(self):
return datetime.datetime.now().strftime("%H:%M:%S")
def print_time(self,text):
if TIMER_DEBUG:
print text,"за",self.get_time(),"сек."
self.last = datetime.datetime.now()
def print_interval(self,text):
if TIMER_DEBUG:
print "%-6s"%self.get_time(),"%-6s"%self.get_time_delta_str(self.last,datetime.datetime.now()),text
self.last = datetime.datetime.now()
class EventHook(object):
def __init__(self):
self.__handlers = []
def __iadd__(self, handler):
self.__handlers.append(handler)
return self
def __isub__(self, handler):
self.__handlers.remove(handler)
return self
def fire(self, *args, **keywargs):
for handler in self.__handlers:
handler(*args, **keywargs)
def clearObjectHandlers(self, inObject):
for theHandler in self.__handlers:
if theHandler.im_self == inObject:
self -= theHandler
class cftDB(object):
class db_row(object):
def __init__(self,db,p_list):
self.db = db
self.list = p_list
if p_list.__class__ == dict:
#super(db_row,self).__init__(p_list.values())
for k,v in p_list.iteritems():
setattr(self,k.lower(),v)
else:
#super(db_row,self).__init__(p_list)
for d in p_list:
setattr(self,d[0],d[1])
def __getitem__(self,index):
return self.dir()[index]
def __repr__(self):
try:
#print self.list
s = '('
if self.list.__class__ == tuple:
for r in self.list:
if r[1].__class__== int:
s += "%s : %-3i|" % (r[0],r[1])
else:
s += "%s : %s|" % (r[0],r[1].encode('utf-8')) #ljust
else:
for r in self.list:
s += "%10s:%-10s|" % (r,self.list[r][:20]) #ljust
#r = re.compile(r' +') #Удаляем повторяющиеся пробелы
#s = r.sub(' ',s.rstrip("|")) + ")"
return s.encode('utf-8')
#return self.list[5][1].encode('utf-8')
except Exception,e:
print "*** Ошибка repr:",e
def __str__(self):
return self.__repr__()# [r for r in self.dir()]
class class_row(db_row):
def __init__(self, db, p_list):
super(cftDB.class_row, self).__init__(db,p_list)
self.meths = dict()
self.views = dict()
self.attrs = cftDB.class_attr_collection(self)
self.is_updated = False
def add_method(self,attrs):
m = cftDB.method_row(self.db,self,attrs)
#self.meths[m.id] = m
self.meths[m.short_name] = m
return m
def add_view(self,attrs):
v = cftDB.view_row(self.db,self,attrs)
self.views[v.id] = v
return v
def add_attr(self,attrs):
v = cftDB.attr_row(self.db,self,attrs)
self.attrs[v.short_name] = v
return v
@property
def methods(self):
return self.meths
def get_objects(self):
objs = []
objs.extend([mv for mk,mv in self.meths.iteritems()])
objs.extend([vv for vk,vv in self.views.iteritems()])
return sorted(objs,key = lambda obj: obj.name)
def update(self):
if self.is_updated:
return
else:
self.is_updated = True
t = timer()
sql = self.db.fr.classes_update
xml_class = self.db.select(sql,self.id)
self.meths = dict()
self.views = dict()
self.cur_method = None
def start_element(name, attrs):
#if name.lower() == 'class':
# self.cur_class = cftDB.class_row(db,attrs)
# self[self.cur_class.id] = self.cur_class
if name == 'method':
self.cur_method = self.add_method(attrs)
elif name == 'view':
self.add_view(attrs)
elif name == 'param':
self.cur_method.add_param(attrs)
elif name == 'attr':
a = self.add_attr(attrs)
#print a
def end_element(name):
pass
def char_data(data):
pass
parser = xml.parsers.expat.ParserCreate()
parser.StartElementHandler = start_element
parser.EndElementHandler = end_element
parser.CharacterDataHandler = char_data
xml_class = '<?xml version="1.0" encoding="windows-1251"?>' + xml_class
parser.Parse(xml_class, 1)
#t.print_time("%s update"%self.id)
@property
def target_class(self):
if hasattr(self,"target_class_id"):
cl = self.db.classes[self.target_class_id]
cl.update()
return cl
else:
return None;
def autocomplete_list(self):
self.update()
a = [v for v in self.meths.values()] #методы
#print "attrs=",db.classes[class_name].attrs
a += [attr for attr in self.attrs.values()] #аттрибуты класса
a = sorted(a, key=lambda p: p.short_name)
arr = []
for m in a:
if m.__class__ == cftDB.method_row:
#params_str = "\n"
params_str = ""
for param in sorted(m.params.values(),key=lambda p: int(p.position)):
#params_str += "\t,%-15s \t== ${%s:%-15s} \t--%-2s %-7s %-20s %s\n"%(param.short_name.replace('$','\$')
params_str += "\t, %-15s \t== ${%s:null} \t--%-2s %-7s %-20s %s\n"%(param.short_name.replace('$','\$')
,param.position.replace('$','\$')
#,param.short_name.replace('$','\$')
,param.position.replace('$','\$')
,param.direction.replace('$','\$')
,param.class_id.replace('$','\$')
,param.name.replace('$','\$'))
params_str = params_str.lstrip('\t,')
params_str = "\n\t " + params_str
arr.append((u"M %s\t%s"%(m.short_name,m.name[:20]),"[%s](%s);\n"%(m.short_name,params_str)))
elif m.__class__ == cftDB.attr_row:
arr.append((u"A %s\t%s"%(m.short_name,m.name[:20]),"[%s]"%m.short_name))
return arr
@property
def autocomplete(self):
#print "autocomplete"
arr = self.autocomplete_list()
#print "self=",self.id
if self.base_class_id == "COLLECTION" or self.base_class_id == "REFERENCE":
arr += self.target_class.autocomplete_list()
#print "target=", self.target_class
return arr
class method_row(db_row):
def __init__(self, db, p_class, p_list):
super(cftDB.method_row, self).__init__(db,p_list)
self.class_ref = p_class
self.params = dict()
def add_param(self,attrs):
p = cftDB.param_row(self.db,attrs)
self.params[p.position] = p
return p
def execute_header(self):
params_str = ""
for i,param in enumerate(sorted(self.params.values(),key=lambda p: int(p.position))):
#params_str += "\t,%-15s \t== ${%s:%-15s} \t--%-2s %-7s %-20s %s\n"%(param.short_name.replace('$','\$')
if i<len(self.params)-1: class_id = param.class_id + ","
else: class_id = param.class_id
#if self.db.classes.has_key(class_id): class_id = "::[%s]%stype"%(class_id,'%')
params_str += "\t%-15s %-7s %-20s\t--%-2s %s\n"%(param.short_name
#,param.position
#,param.short_name
,param.direction
,class_id
,param.position
,param.name)
params_str = params_str.lstrip('\t')#.rstrip(',')
params_str = "\n\t" + params_str
params_str = "function %s(%s)return null\nis\n"%(self.short_name,params_str)
params_str = re.sub(r'\n',r'\n\t','\t' + params_str).rstrip('\t')
return params_str
def get_sources(self):
def get_section_with_header(section_name,text):
value ='╒══════════════════════════════════════════════════════════════════════════════╕\n'.decode('utf-8')
value +='│ '.decode('utf-8') + '%-10s' % section_name + ' │\n'.decode('utf-8')
#value +='├──────────────────────────────────────────────────────────────────────────────┤\n'.decode('utf-8')
if section_name == "EXECUTE":
value += self.execute_header()
value += re.sub(r'\n',r'\n\t','\t' + text).rstrip('\t') #добавим служебный таб в начало каждой строки
value +='└──────────────────────────────────────────────────────────────────────────────┘\n'.decode('utf-8')
return value
def read_clob(clob_val):
clob_val = clob_val.getvalue()
if clob_val: clob_val = clob_val.read().decode('1251')
else: clob_val = ""
return clob_val
conn = self.db.pool.acquire()
cursor = conn.cursor()
execute = cursor.var(cx_Oracle.CLOB)
validate = cursor.var(cx_Oracle.CLOB)
public = cursor.var(cx_Oracle.CLOB)
private = cursor.var(cx_Oracle.CLOB)
vbscript = cursor.var(cx_Oracle.CLOB)
cursor.execute(self.db.fr.method_sources,(self.class_ref.id, self.short_name.upper(),execute,validate,public,private,vbscript))
self.execute = read_clob(execute)
self.validate = read_clob(validate)
self.public = read_clob(public)
self.private = read_clob(private)
self.vbscript = read_clob(vbscript)
value = ""
value += get_section_with_header('EXECUTE' ,self.execute)
value += get_section_with_header('VALIDATE' ,self.validate)
value += get_section_with_header('PUBLIC' ,self.public)
value += get_section_with_header('PRIVATE' ,self.private)
value += get_section_with_header('VBSCRIPT' ,self.vbscript)
self.db.pool.release(conn)
#value = re.sub(r' +$','',text,re.MULTILINE) #Удаляем все пробелы в конце строк, потому что цфт тоже их удаляет
return value
def get_package(self,package_type):
def read_clob(clob_val):
clob_val = clob_val.getvalue()
if clob_val: clob_val = clob_val.read().decode('1251')
else: clob_val = ""
return clob_val
conn = self.db.pool.acquire()
cursor = conn.cursor()
s = cursor.var(cx_Oracle.CLOB)
cursor.execute(self.db.fr.package_sources,(self.class_ref.id, self.short_name.upper(),package_type,s))
s = read_clob(s)
self.db.pool.release(conn)
return s
def get_package_body_text(self):
return self.get_package('PACKAGE BODY')
def get_package_text(self):
return self.get_package('PACKAGE')
def set_sources(self,b,v,g,l,s):
try:
# sections_dict = dict()
# class section(object):
# text = ""
# header = ""
# body = ""
# for s in sections_regex.finditer(text):
# text = re.sub(r'\n\t',r'\n',s.group(2)).lstrip('\t') #Удалим служебный таб в начале каждой строки
# text = re.sub(r' +$','',text,re.MULTILINE) #Удаляем все пробелы в конце строк, потому что цфт тоже их удаляет
# sobj = section()
# sobj.text = text
# sections_dict[s.group(1)] = sobj
# s_exec = sections_dict["EXECUTE"]
# s_exec.header = self.execute_header()
# s_exec.body = s_exec.text[len(s_exec.header.replace('\n','')):]
t = timer()
conn = self.db.pool.acquire()
cursor = conn.cursor()
cursor.setinputsizes(
b=cx_Oracle.CLOB,
v=cx_Oracle.CLOB,
g=cx_Oracle.CLOB,
l=cx_Oracle.CLOB,
s=cx_Oracle.CLOB
)
err_clob,out_others,err_num = cursor.var(cx_Oracle.CLOB),cursor.var(cx_Oracle.CLOB),cursor.var(cx_Oracle.NUMBER)
cursor.execute(
self.db.fr.save_method_sources,
class_name=self.class_ref.id,
method_name=self.short_name.upper(),
# b=sections_dict["EXECUTE"].body,
# v=sections_dict["VALIDATE"].text,
# g=sections_dict["PUBLIC"].text,
# l=sections_dict["PRIVATE"].text,
# s=sections_dict["VBSCRIPT"].text,
b=b,
v=v,
g=g,
l=l,
s=s,
out=err_clob,
out_count=err_num,
out_others=out_others
)
#print "Ошибка сохраниения:",unicode(err_clob.getvalue().read(),'1251').strip()
err_num = int(err_num.getvalue())
if out_others.getvalue():
print unicode(out_others.getvalue().read(),'1251').strip()
#print "**********************************************"
# print "╒══════════════════════════════════════════════════════════════════════════════╕"
# print "│ Компиляция %s.%s в %s"% (self.class_ref.id.encode('1251'),self.short_name.encode('1251'),t.get_now())
# print "├──────────────────────────────────────────────────────────────────────────────┤"
#print unicode(err_clob.getvalue().read(),'1251').strip()
if err_num == 0:
#print u"** Успешно откомпилированно за %s сек" % t.get_time()
#print "**********************************************"
pass
else:
#err_msg = unicode(err_clob.getvalue().read(),'1251').strip()
#sublime.active_window().run_command('show_panel', {"panel": "console", "toggle": "true"})
sublime.status_message(u"Ошибок компиляции %s за %s сек" % (err_num,t.get_time()))
#print err_msg#.replace("\n","\n| ")
#print "└──────────────────────────────────────────────────────────────────────────────┘"
conn.commit()
self.db.pool.release(conn)
except Exception,e:
print "*** Ошибка выполнения method_row.set_sources:",e
#print error.code,error.message,error.context,error
if sys != None:
exc_type, exc_value, exc_traceback = sys.exc_info()
traceback.print_exception(exc_type, exc_value, exc_traceback,
limit=10, file=sys.stdout)
def errors(self):
errors = self.db.select("select * from ERRORS t where t.method_id = :method_id order by class,type,sequence,line,position,text",self.id)
if not errors:
errors = list()
return errors
#self.errors_num = err_num
def get_text(self):
#return [self.text,u"Метод"]
return u"Метод: " + self.text
class view_row(db_row):
def __init__(self, db, p_class, p_list):
super(cftDB.view_row, self).__init__(db,p_list)
self.class_ref = p_class
def get_text(self):
#return [self.text,u"Представление"]
#print self
return u"Представление: " + self.text
def get_sources(self):
return self.db.select("select cr.condition from criteria cr where short_name = :view_short_name",self.short_name)
def set_sources(self,value):
try:
t = timer()
#save_criteria_text.tst
#print "set_sourses_view",self.id,self.name,self.short_name,self.class_ref.id
self.db.cursor.setinputsizes(view_src=cx_Oracle.CLOB)
self.db.cursor.execute(self.db.fr.save_criteria_text,view_short_name=self.short_name,view_id=self.id,view_name=self.name,view_class=self.class_ref.id,view_src=value)
# err_num = int(err_num.getvalue())
# if err_num == 0:
# sublime.status_message(u"Успешно откомпилированно за %s сек" % t.get_time())
print u"Успешно откомпилированно за %s сек" % t.get_time()
# else:
# err_msg = unicode(err_clob.getvalue().read(),'1251').strip()
# sublime.active_window().run_command('show_panel', {"panel": "console", "toggle": "true"})
# sublime.status_message(u"Ошибок компиляции %s за %s сек" % (err_num,t.get_time()))
# print "**********************************************"
# print "** %s" % t.get_now()
# print err_msg
self.db.connection.commit()
except cx_Oracle.DatabaseError, e:
print "ошибка"
error, = e
print error.code,error.message,error.context,error
class param_row(db_row):
def __init__(self, db, p_list):
super(cftDB.param_row, self).__init__(db,p_list)
class attr_row(db_row):
def __init__(self, db,p_class, p_list):
super(cftDB.attr_row, self).__init__(db,p_list)
self.class_ref = p_class
@property
def self_class(self):
s_class = self.db[self.self_class_id]
if s_class.base_class_id == "REFERENCE":
return s_class.target_class
else:
return s_class
class class_collection(dict):
def __init__(self, db):
super(cftDB.class_collection, self).__init__()
self.db = db
self.cur_class = None
def parse(self,xml_text):
def start_element(name, attrs):
if name.lower() == 'class':
self.cur_class = cftDB.class_row(db,attrs)
self[self.cur_class.id] = self.cur_class
if name == 'method':
self.cur_class.add_method(attrs)
if name == 'view':
self.cur_class.add_view(attrs)
def end_element(name):
pass
def char_data(data):
pass
parser = xml.parsers.expat.ParserCreate()
parser.StartElementHandler = start_element
parser.EndElementHandler = end_element
parser.CharacterDataHandler = char_data
xml_text = '<?xml version="1.0" encoding="windows-1251"?>' + xml_text
parser.Parse(xml_text, 1)
@property
def as_list(self):
#t = timer()
used_classes = [db.classes[clk] for clk in cft_settings["used_classes"] if db.classes.has_key(clk)]
not_used_classes = [clv for clk,clv in db.classes.iteritems() if clk not in cft_settings.get("used_classes")]
used_classes.extend(not_used_classes)
#t.print_time("get_classes")
return used_classes
@property
def used(self):
#if not hasattr(self,"used_settings"):
# self.used_settings = sublime.load_settings("used_classes.json")
if not hasattr(self,"used_classes"):
text = FileReader.read(used_classes_file_path)
if len(text)>0:
self.json.loads(text)
self.used_classes = self.used_settings.get("classes")
@property
def autocomplete(self):
a = [v for v in self.values()]
a = sorted(a, key=lambda p: p.id)
a = [("%s\t%s"%(c.id,c.name[:20]),"[%s]"%c.id) for c in a]
return a
class class_attr_collection(dict):
def __init__(self, db):
super(cftDB.class_attr_collection, self).__init__()
self.db = db
@property
def autocomplete(self):
a = [attr for attr in self.values()] #аттрибуты класса
a = sorted(a, key=lambda p: p.short_name)
a = [(u"A %s\t%s"%(attr.short_name,attr.name[:20]),"[%s]"%attr.short_name) for attr in a]
return a
def __init__(self):
self.on_classes_cache_loaded = EventHook()
self.on_methods_cache_loaded = EventHook()
self.is_methods_ready = False
self.classes_lock = thread.allocate_lock()
self.select_lock = thread.allocate_lock()
self.connection_lock = thread.allocate_lock()
self.connect("ibs/ibs@cfttest")
def connect(self,connection_string):
try:
self.connection_string = connection_string
user_ = str(connection_string[:connection_string.find('/')])
pass_ = str(connection_string[connection_string.find('/')+1:connection_string.find('@')])
dsn_ = str(connection_string[connection_string.find('@')+1:])
self.pool = cx_Oracle.SessionPool(user = user_,
password = pass_,
dsn = dsn_,
min = 1,
max = 5,
increment = 1,
threaded = True)
call_async(self.load_classes)
call_async(self.load)
call_async(self.read_sql)
#print "DSN=",dsn_
self.name = dsn_
except Exception as e:
print "e=",e
def read_sql(self):
try:
self.fr = FileReader()
except Exception as e:
print "e=",e
def load(self):
self.connection = cx_Oracle.connect(self.connection_string)
self.cursor = self.connection.cursor()
#self.connection = cx_Oracle.connect(self.connection_string)
#self.cursor = self.connection.cursor()
return 1
def select_classes(self):
sql = """select xmlelement(classes,xmlagg(xmlelement(class,XMLAttributes(cl.id as id
,cl.name as name
,cl.target_class_id as target_class_id
,cl.base_class_id as base_class_id
,rpad(cl.name,40,' ') || lpad(cl.id,30,' ')as text)))).getclobval() c from classes cl
"""
#value = self.select_in_tmp_connection(sql)
value = self.select(sql)
return value
def load_classes(self):
call_async(lambda:(FileReader.read(os.path.join(cache_path,"classes.xml")),"class_cache"),self.parse,async_callback=True)
call_async(self.select_classes,lambda txt:self.save_and_parse(os.path.join(cache_path,"classes.xml"),txt,"class_select"),"Загрузка списка классов",async_callback=True)
#call_async(lambda:(FileReader.read(os.path.join(cache_path,"methods.xml")),"methods_cache"),self.parse,async_callback=True)
#call_async(lambda:self.select_in_tmp_connection(FileReader.read(os.path.join(plugin_path,"sql","cft_schema.sql"))),
# lambda txt:self.save_and_parse(os.path.join(cache_path,"methods.xml"),txt,"method_select"),async_callback=True)
def is_connected(self):
#return hasattr(self,"cursor") and hasattr(self,"connection") and self.select("select * from dual")[0][0] == 'X'
try:
if hasattr(self,"pool"):
return True
return False
except Exception:
return False
def select(self,sql,*args):
value = None
try:
conn = self.pool.acquire()
cursor = conn.cursor()
cursor.arraysize = 50
#t = timer()
value = self.select_cursor(cursor, sql, *args)
#t.print_time("Select")
self.pool.release(conn)
except Exception,e:
print "*** Ошибка выполнения select:",e
if sys != None:
exc_type, exc_value, exc_traceback = sys.exc_info()
traceback.print_exception(exc_type, exc_value, exc_traceback,
limit=10, file=sys.stdout)
return value
def select_cursor(self,cursor,sql,*args):
try:
#print "3",re.sub("\s+"," ",sql)
cursor.execute(sql,args)
desc = [d[0].lower() for d in cursor.description]
table = [[(lambda: unicode(t,'1251') if t.__class__ == str else t)() for t in row] for row in cursor]#Конвертнем все строковые значения в юникод
table = [[(lambda: "" if not t else t)() for t in row] for row in table] #Заменяем все значение None на пустую строку
#print "desc_len=",len(desc),"table_len",len(table)
#value = None
if len(desc)==1 and len(table)==1:
if t.__class__.__name__ == 'LOB':
return table[0][0].read()
else:
return table[0][0]
else:
return [cftDB.db_row(self,zip(desc,row)) for row in table]
except Exception,e:
error, = e.args
if error.__class__.__name__ == 'str':
print "error",error
elif error.code == 28:#ошибка нет подключения
return []
else:
print "db.select_cursor.EXCEPTION:",error.code,error.message,error.context,e,sql
if sys != None:
exc_type, exc_value, exc_traceback = sys.exc_info()
traceback.print_exception(exc_type, exc_value, exc_traceback,
limit=10, file=sys.stdout)
#return []
def get_sid(self):
return self.select("select sys_context('userenv','sid') sid, sid from v$mystat where rownum=1")[0]["sid"]
def save_and_parse(self,file_name,txt,type=None):
FileReader.write(file_name,txt)
self.parse(txt,type)
def parse(self,txt,type=None):
try:
#self.classes = ParseXml(txt).classes
#print "before assign classes",type
self.classes_lock.acquire()
new_classes = cftDB.class_collection(self)
#print "after assign classes",type
new_classes.parse(txt)
self.classes = new_classes
#print "after parse classes",type
if type == "class_cache":
self.on_classes_cache_loaded.fire()
elif type == 'methods_cache':
self.is_methods_ready = True
self.on_methods_cache_loaded.fire()
self.classes_lock.release()
except Exception,e:
print "*** Ошибка загрузки классов:",e
if sys != None:
exc_type, exc_value, exc_traceback = sys.exc_info()
traceback.print_exception(exc_type, exc_value, exc_traceback,
limit=10, file=sys.stdout)
def parse_json(self):
out_clob = self.cursor.var(cx_Oracle.CLOB)
self.cursor.execute(self.fr.method_sources_json,out_clob=out_clob)
out_clob = unicode(out_clob.getvalue().read(),'1251')
self.classes = json.loads(out_clob)["classes"]
self.classes = json.loads(out_clob)["classes"]
def get_classes(self):
#t = timer()
used_classes = [db.classes[clk] for clk in cft_settings["used_classes"] if db.classes.has_key(clk)]
not_used_classes = [clv for clk,clv in db.classes.iteritems() if clk not in cft_settings.get("used_classes")]
used_classes.extend(not_used_classes)
#t.print_time("get_classes")
return used_classes
def __getitem__(self, key):
cl = self.classes[key]
cl.update()
return cl
#try:
db = cftDB()
#except Exception,e:
#db = ""
class connectCommand(sublime_plugin.WindowCommand):
def run(self):
print "CONNECT"
self.window.show_input_panel(u"Схема/Пользователь@База_данных:","ibs/ibs@cfttest", self.on_done, self.on_change, self.on_cancel)
def on_done(self, input):
self.window.run_command('show_panel', {"panel": "console", "toggle": "true"})
db.connect(input)
def on_change(self, input):
pass
def on_cancel(self):
pass
class cft_openCommand(sublime_plugin.WindowCommand):
def run(self):
#print "OPEN MEHTODS"
if not db.is_connected():
db.on_classes_cache_loaded += lambda:sublime.set_timeout(self.open_classes,0)
sublime.active_window().run_command('connect',{})
else:
self.open_classes()
def open_classes(self):
self.classes = db.get_classes()
self.window.show_quick_panel([clv.text for clv in self.classes],self.open_methods,sublime.MONOSPACE_FONT)
#def is_methods_ready(self,selected_class):
#if not db.is_methods_ready:
# db.on_methods_cache_loaded += lambda:sublime.set_timeout(lambda:self.open_methods(selected_class),0)
#else:
#self.open_methods(selected_class)
def open_methods(self, selected_class):
try:
if selected_class >= 0:
self.current_class = self.classes[selected_class]
#if db.get_classes() != self.classes and db.classes.has_key(self.current_class.id): #Если за время выбора класса, список классов обновился.
#print "Загрузка была из кэша обновим из базы"
#self.current_class = db.classes[self.current_class.id] #Перезагрузим текущий класс
self.current_class.update()
#meths = [mv.text for mk,mv in self.current_class.meths.iteritems()]
#self.window.show_quick_panel(meths,self.method_on_done,sublime.MONOSPACE_FONT)
self.list_objs = self.current_class.get_objects()
self.window.show_quick_panel([obj.get_text() for obj in self.list_objs],self.method_on_done,sublime.MONOSPACE_FONT)
cft_settings.update_used_class(self.current_class.id)
except Exception,e:
print "Ошибка при вызове open_methods",e
if sys != None:
exc_type, exc_value, exc_traceback = sys.exc_info()
traceback.print_exception(exc_type, exc_value, exc_traceback,
limit=10, file=sys.stdout)
def method_on_done(self,input):
def write(string):
edit = view.begin_edit()
#print view.encoding()
#print "string=",string
view.insert(edit, view.size(), string)
view.end_edit(edit)
if input >= 0:
if len(self.current_class.meths.values()) > 0:
#m = self.current_class.meths.values()[input]
#obj = self.current_class.get_objects()[input]
obj = self.list_objs[input]
#view = sublime.active_window().new_file()
view = dataView.new()
view.set_name(obj.name)
view.set_scratch(True)
view.set_syntax_file("Packages/CFT/PL_SQL (Oracle).tmLanguage")
view.set_encoding("utf-8")
#print os.path.join(cft_settings["work_folder"],obj.class_ref.id + "." + obj.short_name)
#view.set_name(os.path.join(cft_settings["work_folder"],obj.class_ref.id + "." + obj.short_name))
#view.run_command("save")
#view.settings().set("cft_object",{"id": obj.id,"class" : obj.class_ref.id, "type": obj.__class__.__name__})
view.data = obj
#text = obj.get_sources()
text = obj.get_sources()
#print "text",text
#print db.name
FileReader.write(os.path.join(cft_settings["work_folder"],obj.class_ref.id + "." + obj.short_name + '.' + db.name.upper() + ".METHOD")
,text.encode('utf-8'))
write(text)
view.focus()
else:
sublime.status_message(u"У класса нет методов для открытия")
#pass
def on_change(self, input):
pass
def on_cancel(self):
pass
class save_methodCommand(sublime_plugin.TextCommand):
def run(self, edit):
#import cProfile
#self.profiler = cProfile.Profile()
if not db.is_connected():