/
search.py
6605 lines (4927 loc) · 222 KB
/
search.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
#################################################################
#
# Copyright (c) 2005, Southpaw Technology
# All Rights Reserved
#
# PROPRIETARY INFORMATION. This software is proprietary to
# Southpaw Technology, and is not to be reproduced, transmitted,
# or disclosed in any way without written permission.
#
#
#
__all__ = [ "SearchException", "SearchInputException", "SObjectException", "SObjectValueException", "Search", "SObject", "SearchType", "SObjectFactory", "SObjectUndo", "SearchKey" ]
import string, types, re, sys
from pyasm.common import *
from pyasm.common.spt_date import SPTDate
from sobject_config import *
from transaction import Transaction
from sobject_mapping import *
from database_impl import DatabaseImpl
# Need to import this way because of how DbResource needs to get imported
from pyasm.search.sql import SqlException, DatabaseException, Sql, DbResource, DbContainer, DbPasswordUtil, Select, Insert, Update, CreateTable, DropTable, AlterTable
import datetime
from dateutil import parser
# this is done for performance reasons
from datetime import datetime as datetimeclass
class SearchException(TacticException):
pass
class SearchInputException(TacticException):
'''Error out for invalid data in SearchWdg'''
pass
class SObjectException(TacticException):
pass
class SObjectValueException(SObjectException):
pass
# for dyanmically importing into this namespace
gl = globals()
lc = locals()
class Search(Base):
'''Search engine using named search types. The search returns a list of sobjects, which are the base class for entities retrieved from the database.
Basic usage:
search_type = "prod/asset"
search = Search(search_type)
serach.add_filter("asset_library", "chr")
sobjects = search.get_sobjects()
'''
def __init__(my, search_type, project_code=None):
# storage for result
my.is_search_done = False
my.sobjects = []
# retired asset flag - retired assets are never shown by default
my.show_retired_flag = False
my.filter_mode = 'and'
# flag that when set, returns empty
my.null_filter = False
my.security_filter = False
protocol = 'local'
if type(search_type) in types.StringTypes:
# project is *always* local. This prevents an infinite loop
if search_type != "sthpw/project":
try:
key = "Search:resource:%s" % search_type
parts = Container.get(key)
if not parts:
from pyasm.biz import Project
if not project_code:
project_code = Project.extract_project_code(search_type)
project = Project.get_by_code(project_code)
#assert(project)
if not project:
raise SearchException("Cannot find project [%s]" % project_code)
resource = project.get_resource()
protocol = resource.get_protocol()
xx = resource.get_project()
if xx:
project_code = xx
parts = [project_code, protocol]
Container.put(key, parts)
else:
cached_project_code, protocol = parts
if not project_code:
project_code = cached_project_code
if protocol == 'xmlrpc':
my.select = RemoteSearch(search_type)
# build a dummy search_type object. Should this be
# build from the real remote info?
my.search_type_obj = SearchType.create("sthpw/search_object")
my.search_type_obj.set_value("search_type", search_type)
return
except Exception, e:
print "WARNING [%s]: Search constructor:" % search_type, str(e)
raise
if search_type == None:
raise SearchException("search_type is None")
# get the search type sobject for the search
if type(search_type) == types.TypeType:
# get search defined in the class
search_type = search_type.SEARCH_TYPE
my.search_type_obj = SearchType.get(search_type)
elif type(search_type) in types.StringTypes:
my.search_type_obj = SearchType.get(search_type)
else:
my.search_type_obj = search_type
search_type = my.search_type_obj.get_base_key()
from pyasm.biz import Project
if project_code:
my.project_code = project_code
else:
my.project_code = Project.extract_project_code(search_type)
base_search_type = SearchKey.extract_base_search_type(search_type)
# Put in a security check for search types that are not sthpw
# or config.
# The "sthpw" and "config" namespaces are always searchable (or
# TACTIC won't function)
#
from pyasm.security import get_security_version
security = Environment.get_security()
security_version = get_security_version()
if security_version >= 2:
# special conditions of task, note and work_hour
if search_type in ['sthpw/task', 'sthpw/note','sthpw/work_hour']:
current_project_code = Project.get_project_code()
key = { "code": base_search_type }
key2 = { "code": base_search_type, "project": current_project_code }
key3 = { "code": "*" }
key4 = { "code": "*", "project": current_project_code }
keys = [key, key2, key3, key4]
default = "allow"
if not security.check_access("search_type", keys, "view", default=default):
print "WARNING: User [%s] security failed for search type [%s]" % (Environment.get_login().get_code(), search_type)
my.set_null_filter()
elif not search_type.startswith("sthpw/") and not search_type.startswith("config/"):
key = { "code": base_search_type }
key2 = { "code": base_search_type, "project": my.project_code }
key3 = { "code": "*" }
key4 = { "code": "*", "project": my.project_code }
keys = [key, key2, key3, key4]
default = "deny"
if not security.check_access("search_type", keys, "view", default=default):
print "WARNING: User [%s] security failed for search type [%s]" % (Environment.get_login().get_code(), search_type)
my.set_null_filter()
else:
# special conditions of task, note and work_hour
if search_type in ['sthpw/task', 'sthpw/note','sthpw/work_hour']:
current_project_code = Project.get_project_code()
else:
current_project_code = my.project_code
key = {
'project' : current_project_code,
'search_type' : base_search_type
}
security = Environment.get_security()
if not security.check_access("sobject", key, "view"):
my.set_null_filter()
# provide the project_code kwarg here
my.full_search_type = Project.get_full_search_type(search_type, project_code=my.project_code)
my.db_resource = Project.get_db_resource_by_search_type(my.full_search_type)
#my.db_resource = None
if my.db_resource:
my.database = my.db_resource.get_database()
my.host = my.db_resource.get_host()
else:
my.database = Project.get_database_by_search_type(my.full_search_type)
my.host = Project.extract_host(my.full_search_type)
my.db_resource = DbResource(database=my.database, host=my.host)
# verify this db exists
db_exists = my.db_resource.exists()
if not db_exists:
raise SearchException('This database [%s] does not exist' %my.database)
my.database_impl = my.db_resource.get_database_impl()
my.select = Select()
my.select.set_database(my.db_resource)
my.select.set_id_col(my.get_id_col())
assert isinstance(my.db_resource, DbResource)
table = my.search_type_obj.get_table()
exists = my.database_impl.table_exists(my.db_resource, table)
if not search_type == 'sthpw/virtual' and not exists:
raise SearchException('This table [%s] does not exist for database [%s]' %(table, my.database))
# add the table
my.select.add_table(table)
# remember the order bys
my.order_bys = []
def set_search_done(my, flag=True):
my.is_search_done = flag
def get_database_impl(my):
return my.database_impl
def get_sql(my):
return my.db_resource.get_sql()
def get_project(my):
from pyasm.biz import Project
return Project.get_by_code(my.project_code)
def get_select(my):
'''returns the select object'''
return my.select
def get_project_code(my):
return my.project_code
def get_database(my):
'''get the database that represents this Search'''
return my.database
def get_db_resource(my):
return my.db_resource
def set_filter_mode(my, mode):
my.select.set_filter_mode(mode)
def get_search_type(my):
return my.full_search_type
def get_table(my):
return my.search_type_obj.get_table()
def get_full_search_type(my):
return my.full_search_type
def get_search_type_obj(my):
return my.search_type_obj
def get_base_search_type(my):
return my.search_type_obj.get_base_key()
def get_id_col(my):
'''returns the column which stores the id of the sobject'''
database_impl = my.db_resource.get_database_impl()
search_type = my.full_search_type
return database_impl.get_id_col(my.db_resource, search_type)
#return my.search_type_obj.get_id_col()
def get_code_col(my):
'''returns the column which stores the id of the sobject'''
database_impl = my.db_resource.get_database_impl()
search_type = my.full_search_type
return database_impl.get_code_col(my.db_resource, search_type)
def get_statement(my):
return my.select.get_statement()
def add_column(my, column, distinct=False, table=None, as_column=None):
my.select.add_column(column, distinct, table=table, as_column=as_column)
def get_columns(my, table=None, show_hidden=False):
#database = my.get_database()
sql = DbContainer.get(my.db_resource)
if not table:
table = my.search_type_obj.get_table()
columns = sql.get_columns(table)
#columns = my.remove_temp_column(columns, sql)
return columns
def set_distinct_col(my, column):
my.select.set_distinct_col(column)
def get_column_info(my):
table_name = my.search_type_obj.get_table()
info = my.database_impl.get_column_info(my.db_resource, table_name)
return info
def column_exists(my, column):
column_info = my.get_column_info()
has_column = column_info.get(column) != None
return has_column
# DEPRECATED: this should not be used as it assumes an SQL database
def add_where(my, filter):
'''add an explicit where clause'''
my.select.add_where(filter)
# DEPRECATED: Still called in my.skip_retired()
def remove_where(my, filter):
'''add an explicit where clause'''
my.select.remove_where(filter)
def add_regex_filter(my, name, regex, op='EQI'):
'''add a regular expression filter
EQ = equal case-sensitive
EQI = equal case-insensitive
NEQ = not equal case-sensitive
NEQI = not equal case-insensitive '''
#my.select.add_filter(name, Search.get_regex_filter(name, regex, op))
my.select.add_where(Search.get_regex_filter(name, regex, op, my.database_impl))
def get_regex_filter(name, regex, op='EQI', impl=None):
if regex:
regex = re.sub(r"'", r"\'", regex)
else:
regex = ''
if not impl:
impl = DatabaseImpl.get()
return impl.get_regex_filter(name, regex, op)
get_regex_filter = staticmethod(get_regex_filter)
# FIXME: this does not take the type into account
# DEPRECATED
"""
def get_filter(my, name, value, op='='):
if value == None:
return '"%s" is NULL' % name
else:
return '"%s" %s %s' % ( name, op, Sql.quote(value) )
"""
def set_null_filter(my):
my.null_filter = True
def set_security_filter(my):
'''set it after Security has done alter_search()'''
my.security_filter = True
def add_filter(my, name, value, op='=', quoted=None, table=''):
if name == None:
raise SearchException("Cannot add null as a name in filter")
#filter = my.get_filter(name, value, op)
#my.select.add_where(filter)
my.select.add_filter(name, value, op=op, quoted=quoted, table=table)
def add_filters(my, name, values, table='', op='in'):
''' add a where name in (val1, val2, ...) '''
"""
if not op:
op = 'in'
if not table:
table = my.select.get_table()
filter = my.get_filters(name, values, table, op)
if filter == "NULL":
my.null_filter = True
#my.select.add_filter(name, filter)
my.select.add_where(filter)
"""
#filter = my.get_filters(name, values, table, op)
#print "filter: ", filter
my.select.add_filters(name, values, op=op, table=table)
# DEPRECATED
"""
def get_filters(my, name, values, table='', op='in'):
assert op in ['in', 'not in']
filter = ''
if not values or values == ['']:
#filter = "%s is NULL" % name
filter = "NULL"
else:
list = [ Sql.quote(value) for value in values ]
if table:
filter = '"%s"."%s" %s (%s)' % ( table, name, op, ", ".join(list) )
else:
filter = '"%s" %s (%s)' % ( name, op, ", ".join(list) )
return filter
"""
def add_null_filter(my, name):
my.add_filter(name, "NULL", quoted=False, op="is")
def add_search_filter(my, name, search, op='in', table=''):
'''combines results of one search filter with another search filter
as a subselect
example:
SELECT * FROM "request" WHERE "id" in ( SELECT "request_id" FROM "job" WHERE "code" = '123MMS' )
'''
select = search.get_select()
my.select.add_select_filter(name, select, op, table=table)
def add_op(my, op, idx=None):
'''add operator like begin, and, or. with an idx number, it will be inserted instead of appended'''
my.select.add_op(op, idx=idx)
def add_op_filters(my, filters):
'''method to add many varied filters to search. This is used in
the Client API, for example.'''
if isinstance(filters, basestring):
filters = jsonloads(filters)
for filter in filters:
if not filter:
continue
if type(filter) in types.StringTypes or len(filter) == 1:
# straight where clause (TODO: should this be allowed?)
if isinstance(filter, basestring):
where = filter
else:
where = filter[0]
my.add_where(where)
elif len(filter) == 2:
name, value = filter
table = ""
if name.find(".") != -1:
parts = name.split(".")
table = parts[0]
name = parts[1]
if name.startswith("@"):
if name == '@ORDER_BY':
my.add_order_by(filter[1])
elif name == '@LIMIT':
my.set_limit(filter[1])
elif name == '@OFFSET':
my.set_offset(filter[1])
elif name == '@UNIQUE':
my.add_column(filter[1], distinct=True)
elif type(value) in types.StringTypes:
# <name> = '<value>'
my.add_filter(name, value, table=table)
#print 'name: [%s],[%s]' % (name, value)
elif type(value) in (types.IntType, types.FloatType, types.BooleanType):
# <name> = '<value>'
my.add_filter(name, value, table=table)
else:
# <name> in ('<value1>', '<value2>')
my.add_filters(name, value, table=table)
elif len(filter) == 3:
name, op, value = filter
table = ""
if name.find(".") != -1:
parts = name.split(".")
table = parts[0]
name = parts[1]
assert op in ('like', 'not like', '<=', '>=', '>', '<', 'is','is not', '~', '!~','~*','!~*','=','!=','in','not in','EQ','NEQ','EQI','NEQI','is after','is before')
#my.add_where( "\"%s\" %s '%s'" % (name,op,value))
if op in ('in', 'not in'):
values = value.split('|')
#avoid empty value
values = [x for x in values if x]
my.add_filters(name, values, op=op, table=table)
elif op in ['EQ','NEQ','EQI','NEQI']:
my.add_regex_filter(name, value, op)
else:
if op == 'is after':
op = '>='
elif op == 'is before':
op = '<='
quoted = True
# special case for NULL
if value == 'NULL':
quoted = False
my.add_filter( name, value, op=op, quoted=quoted, table=table)
def add_interval_filter(my, name, value):
my.add_where( Select.get_interval_where(value,name) )
def add_sobject_filter(my, sobject, prefix="", op=None):
'''convenience function to add a filter for the given sobject'''
my.add_filter("%ssearch_type" % prefix, sobject.get_search_type() )
if sobject.column_exists("code") and my.column_exists("%ssearch_code" % prefix):
search_code = sobject.get_value("code")
if not op:
op = '='
my.add_filter("%ssearch_code" % prefix, search_code, op=op )
else:
if not op:
op = '='
my.add_filter("%ssearch_id" % prefix, sobject.get_id(), op=op )
def add_sobjects_filter(my, sobjects, prefix="", op='in'):
'''convenience function to add a filter for the given sobjects'''
if not sobjects:
return
search_type = sobjects[0].get_search_type()
my.add_filter("%ssearch_type" % prefix, search_type )
# assume they are of the same type
sobject = sobjects[0]
if my.column_exists("%ssearch_code" % prefix):
search_codes = [x.get_value("code") for x in sobjects if x]
my.add_filters("%ssearch_code" % prefix, search_codes, op=op )
else:
search_ids = [str(x.get_id()) for x in sobjects if x]
my.add_filters("%ssearch_id" % prefix, search_ids, op=op )
def add_parent_filter(my, parent, relationship=None):
'''use the schema to determine the relationship and then add the
appropriate filter'''
if not parent:
my.add_id_filter(0)
return
#parent_search_type = parent.get_base_search_type()
#search_type = my.get_base_search_type()
parent_search_type = parent.get_search_type()
search_type = my.get_search_type()
if parent_search_type == search_type:
print "WARNING: parent type and search type are the same for [%s]" % parent_search_type
my.add_id_filter(parent.get_id())
return
from pyasm.biz import Schema
schema = Schema.get()
if not relationship:
relationship = schema.get_relationship(parent_search_type, search_type)
if not relationship:
raise SearchException("Search type [%s] is not related to search_type [%s]" % ( parent_search_type, search_type) )
attrs = schema.get_relationship_attrs(parent_search_type, search_type, path=None)
if relationship == "code":
my.add_relationship_filter(parent)
#my.add_filter(parent.get_foreign_key(), parent.get_code() )
elif relationship == "id":
my.add_relationship_filter(parent)
#my.add_filter(parent.get_foreign_key(), parent.get_id() )
elif relationship == "parent_code":
my.add_filter("parent_code", parent.get_code() )
elif relationship in ["search_type", "search_code", "search_id"]:
if relationship == "search_type":
full_parent_search_type = parent.get_search_type()
full_search_type = my.get_search_type()
relationship = schema.resolve_search_type_relationship(attrs, full_parent_search_type, full_search_type)
prefix = attrs.get("prefix")
if prefix:
prefix = "%s_" % prefix
else:
prefix = ""
my.add_filter("%ssearch_type" % prefix, parent.get_search_type() )
#my.add_filter("%ssearch_id" % prefix, parent.get_id() )
my.add_filter("%ssearch_code" % prefix, parent.get_code() )
def add_relationship_filter(my, sobject, path=None):
'''adds a filter to the current search that are related to the passed
in sobject. The schema takes care of figuring out how to relate
the two search_types
'''
base_search_type = my.get_base_search_type()
#related_type = sobject.get_base_search_type()
search_type = my.get_search_type()
related_type = sobject.get_search_type()
if search_type == related_type:
print "WARNING: related type and search type are the same for [%s]" % search_type
my.add_id_filter(sobject.get_id())
return
from pyasm.biz import Schema
schema = Schema.get()
attrs = schema.get_relationship_attrs(search_type, related_type, path)
if not attrs:
raise SearchException("Search type [%s] is not related to search_type [%s]" % ( search_type, related_type) )
if attrs.get("disabled") == True:
my.null_filter = True
return
relationship = attrs.get('relationship')
my_is_from = attrs['from'] in [base_search_type, '*']
from_col = attrs.get('from_col')
to_col = attrs.get('to_col')
if relationship == "search_type":
relationship = schema.resolve_search_type_relationship(attrs, search_type, related_type)
if relationship in ['id', 'code']:
if my_is_from:
value = sobject.get_value(to_col)
if not value:
my.null_filter = True
return
my.add_filter(from_col, value )
else:
value = sobject.get_value(from_col)
if not value:
my.null_filter = True
return
my.add_filter(to_col, value )
elif relationship in ['search_id']:
prefix = attrs.get("prefix")
if prefix:
prefix = "%s_" % prefix
else:
prefix = ""
if my_is_from:
my.add_filter("%ssearch_type" % prefix, sobject.get_search_type() )
my.add_filter("%ssearch_id" % prefix, sobject.get_id() )
else:
my.add_filter(my.get_id_col(), sobject.get_value("search_id"))
elif relationship in ['search_code']:
prefix = attrs.get("prefix")
if prefix:
prefix = "%s_" % prefix
else:
prefix = ""
if my_is_from:
my.add_filter("%ssearch_type" % prefix, sobject.get_search_type() )
my.add_filter("%ssearch_code" % prefix, sobject.get_code() )
else:
my.add_filter("code", sobject.get_value("search_code"))
else:
raise SearchException("Relationship [%s] not supported yet" % relationship)
def add_relationship_filters(my, sobjects, op='in', path=None, type=None):
'''adds a filter to the current search that are related to the passed
in sobjects. The schema takes care of figuring out how to relate
the two search_types
This method is relatively slower than "add_relationship_search_filter"
because it required you to already have the full sobjects.
'''
if not sobjects:
my.null_filter = True
return
sobject = sobjects[0]
search_type = my.get_base_search_type()
related_type = sobjects[0].get_base_search_type()
# handle case where both search types are the same
if search_type == related_type:
has_code = SearchType.column_exists(search_type, "code")
if has_code:
my.add_filters("code", [x.get_value("code") for x in sobjects], op=op)
else:
my.add_filters(sobject.get_id_col(), [x.get_id() for x in sobjects], op=op)
return
from pyasm.biz import Schema
schema = Schema.get()
attrs = schema.get_relationship_attrs(search_type, related_type, path=path, type=type)
if not attrs:
raise SearchException("Search type [%s] is not related to search_type [%s]" % ( search_type, related_type) )
if attrs.get("disabled") == True:
my.null_filter = True
return
relationship = attrs.get('relationship')
my_is_from = attrs['from'] == search_type
from_col = attrs.get('from_col')
to_col = attrs.get('to_col')
if relationship in ['id', 'code']:
if my_is_from:
col_values = [x.get_value(to_col) for x in sobjects]
my.add_filters(from_col, col_values, op=op )
else:
col_values = [x.get_value(from_col) for x in sobjects]
my.add_filters(to_col, col_values, op=op )
elif relationship in ['search_type','search_code','search_id']:
if my_is_from:
if not to_col:
#if relationship == 'search_type':
# full_search_type = my.get_search_type()
# full_related_type = sobjects[0].get_search_type()
# relationship = schema.resolve_search_type_relationship(attrs, full_search_type, full_related_type)
#if relationship == 'search_id':
# to_col = sobject.get_id_col()
# from_col = 'search_id'
#else:
# to_col = 'code'
# from_col = 'search_code'
attrs = schema.resolve_relationship_attrs(attrs, my.get_search_type(), sobjects[0].get_search_type())
to_col = attrs.get("to_col")
from_col = attrs.get("from_col")
# quickly go through the sobjects to determine if the
# search types are the same
multi_stypes = False
last_st = None
for idx, sobject in enumerate(sobjects):
if idx == 0:
last_st = sobject.get_search_type()
continue
if sobject.get_search_type() != last_st:
multi_stypes = True
break
if not multi_stypes:
col_values = [x.get_value(to_col) for x in sobjects]
my.add_filter("search_type", sobjects[0].get_search_type() )
if isinstance(col_values[0], int) or isinstance(col_values[0], long):
my.add_filters(from_col, col_values, op=op )
else:
my.add_filters("search_code", col_values, op=op)
else:
if op != 'in':
raise SearchException("For searches with multi_stypes, op = 'in' must be used.");
# FIXME: why doesn't the ops work here?
filters = []
for sobject in sobjects:
search_type = sobject.get_search_type()
search_code = sobject.get_value(to_col)
#search.add_filter('search_type', search_type)
#search.add_filter(from_col, search_code)
#search.add_op("and")
filters.append("(search_type = '%s' and %s = '%s')" % (search_type, from_col, search_code))
my.add_where("( %s )" % " or ".join(filters))
else:
# assume default search_type/search_id schema like task, snapshot
# filter out the sobjects that are not the same search type
# as the search
search_type = my.get_search_type()
filtered_sobjects = []
for sobject in sobjects:
if sobject.get_value("search_type") != search_type:
continue
filtered_sobjects.append(sobject)
sobjects = filtered_sobjects
has_code = SearchType.column_exists(search_type, "code")
if has_code:
column = "search_code"
column2 = "code"
else:
column = "search_id"
column2 = "id"
sobject_values = SObject.get_values(sobjects, column, unique=True)
sobject_values = [x for x in sobject_values if x]
my.add_filters(column2, sobject_values, op=op)
else:
raise SearchException("Relationship [%s] not supported yet" % relationship)
def add_relationship_search_filter(my, search, op='in', delay_null=False,use_multidb=None):
'''optimized relationship filter so that you don't need the results
of the sub search. This is much faster because the search is done
completely in the database without having to go through the whole
sobject conversion
@param
delay_null - If True, the set_null_filter action will not be executed when the search passed in has 0 result, this method returns False instead
For example
(slow method):
search = Search("MMS/job")
sobjects = search.get_sobjects()
search2 = Search("MMS/request")
search2.add_relationship_filter(sobjects)
(fast method)
search = Search("MMS/job")
search2 = Search("MMS/request")
search2.add_relationship_search_filter(search)
'''
if not search:
my.null_filter = True
return False
assert op in ['in', 'not in']
search_type = my.get_base_search_type()
full_search_type = my.get_search_type()
related_type = search.get_base_search_type()
full_related_type = search.get_search_type()
search_type_obj = my.get_search_type_obj()
table = search_type_obj.get_table()
if search_type == related_type:
#print "WARNING: related type and search type are the same for [%s]" % search_type
search.add_column("id")
my.add_search_filter("id", search, op, table=table )
return True
from pyasm.biz import Schema
schema = Schema.get()
attrs = schema.get_relationship_attrs(search_type, related_type)
if not attrs:
raise SearchException("Search type [%s] is not related to search_type [%s]" % ( search_type, related_type) )
relationship = attrs.get('relationship')
my_is_from = attrs['from'] == search_type
if relationship in ['id', 'code']:
from_col = attrs['from_col']
to_col = attrs['to_col']
if my_is_from:
search.add_column(to_col)
my.add_search_filter(from_col, search, op, table=table )
else:
search.add_column(from_col)
my.add_search_filter(to_col, search, op, table=table )
elif relationship in ['search_type', 'search_code', 'search_id']:
if relationship == 'search_type':
relationship = schema.resolve_search_type_relationship(attrs, search_type, related_type)
# see if a multi database join can be made
can_join = DatabaseImpl.can_search_types_join(full_search_type, full_related_type)
if can_join and use_multidb != None:
can_join = use_multidb
if can_join:
my.add_op('begin')
if my_is_from:
my.add_filter("search_type", search.get_search_type() )
if relationship == "search_code":
search.add_column("code", distinct=True)
my.add_search_filter("search_code", search)
else:
search.add_column("id", distinct=True)
my.add_search_filter("search_id", search)
else:
search.add_filter("search_type", my.get_search_type())
if relationship == 'search_code':
search.add_column("search_code", distinct=True)
my.add_search_filter("code", search)
else:
search.add_column("search_id", distinct=True)
my.add_search_filter("id", search)
my.add_op('and')
return True
# only apply delay_null in search_type condition
if my_is_from:
# only support to_col == 'id'
# fast way of getting search_ids
if relationship == 'search_code':
s_values = search.get_sobject_codes()
else:
s_values = search.get_sobject_ids()
if delay_null and not s_values:
return False
my.add_op('begin')
my.add_filter("search_type", search.get_search_type() )
if relationship == 'search_code':
my.add_filters("search_code", s_values )
else:
my.add_filters("search_id", s_values )
my.add_op('and')
else:
if relationship == 'search_code':
search.add_column("search_code", distinct=True)
else:
search.add_column("search_id", distinct=True)
search.add_filter("search_type", full_search_type)