Coverage for gws-app/gws/plugin/model_field/text/__init__.py: 0%

45 statements  

« prev     ^ index     » next       coverage.py v7.8.0, created at 2025-04-17 01:37 +0200

1"""Text field.""" 

2 

3from typing import Optional, cast 

4 

5import gws 

6import gws.base.database.model 

7import gws.base.model.scalar_field 

8import gws.lib.sa as sa 

9 

10 

11gws.ext.new.modelField('text') 

12 

13 

14class Config(gws.base.model.scalar_field.Config): 

15 textSearch: Optional[gws.TextSearchOptions] 

16 

17 

18class Props(gws.base.model.scalar_field.Props): 

19 pass 

20 

21 

22class Object(gws.base.model.scalar_field.Object): 

23 attributeType = gws.AttributeType.str 

24 textSearch: Optional[gws.TextSearchOptions] 

25 

26 def configure(self): 

27 self.textSearch = self.cfg('textSearch') 

28 if self.textSearch: 

29 self.supportsKeywordSearch = True 

30 

31 def configure_widget(self): 

32 if not super().configure_widget(): 

33 self.widget = self.root.create_shared(gws.ext.object.modelWidget, type='input') 

34 return True 

35 

36 ## 

37 

38 def before_select(self, mc): 

39 super().before_select(mc) 

40 

41 kw = mc.search.keyword 

42 ts = self.textSearch 

43 

44 if not kw or not ts or (ts.minLength and len(kw) < ts.minLength): 

45 return 

46 

47 model = cast(gws.base.database.model.Object, self.model) 

48 col = sa.cast(model.column(self.name), sa.String) 

49 

50 if ts.type == gws.TextSearchType.exact: 

51 mc.dbSelect.keywordWhere.append(col.__eq__(kw)) 

52 return 

53 

54 if ts.type == gws.TextSearchType.any: 

55 kw = '%' + _escape_like(kw) + '%' 

56 elif ts.type == gws.TextSearchType.begin: 

57 kw = _escape_like(kw) + '%' 

58 elif ts.type == gws.TextSearchType.end: 

59 kw = '%' + _escape_like(kw) 

60 elif ts.type == gws.TextSearchType.like: 

61 pass 

62 

63 if ts.caseSensitive: 

64 mc.dbSelect.keywordWhere.append(col.like(kw, escape='\\')) 

65 else: 

66 mc.dbSelect.keywordWhere.append(col.ilike(kw, escape='\\')) 

67 

68 

69def _escape_like(s, escape='\\'): 

70 return ( 

71 s 

72 .replace(escape, escape + escape) 

73 .replace('%', escape + '%') 

74 .replace('_', escape + '_'))