Coverage for mindsdb / integrations / handlers / intercom_handler / intercom_tables.py: 0%

72 statements  

« prev     ^ index     » next       coverage.py v7.13.1, created at 2026-01-21 00:36 +0000

1from typing import List 

2from mindsdb.integrations.utilities.sql_utils import extract_comparison_conditions 

3from mindsdb.integrations.libs.api_handler import APIHandler, APITable 

4from mindsdb_sql_parser import ast 

5import pandas as pd 

6from mindsdb_sql_parser.ast.select.constant import Constant 

7import json 

8 

9 

10class Articles(APITable): 

11 name: str = "articles" 

12 

13 def __init__(self, handler: APIHandler): 

14 super().__init__(handler) 

15 

16 def select(self, query: ast.Select) -> pd.DataFrame: 

17 """triggered at the SELECT query 

18 

19 Args: 

20 query (ast.Select): user's entered query 

21 

22 Returns: 

23 pd.DataFrame: the queried information 

24 """ 

25 _id = None 

26 selected_columns = [] 

27 

28 # Get id from where clause, if available 

29 conditions = extract_comparison_conditions(query.where) 

30 for op, arg1, arg2 in conditions: 

31 if arg1 == 'id' and op == '=': 

32 _id = arg2 

33 else: 

34 raise ValueError("Unsupported condition in WHERE clause") 

35 

36 # Get selected columns from query 

37 for target in query.targets: 

38 if isinstance(target, ast.Star): 

39 selected_columns = self.get_columns() 

40 break 

41 elif isinstance(target, ast.Identifier): 

42 selected_columns.append(target.parts[-1]) 

43 else: 

44 raise ValueError(f"Unknown query target {type(target)}") 

45 

46 # Initialize the result DataFrame 

47 result_df = None 

48 

49 if _id is not None: 

50 # Fetch data using the provided endpoint for the specific id 

51 df = self.handler.call_intercom_api(endpoint=f'/articles/{_id}') 

52 

53 if len(df) > 0: 

54 result_df = df[selected_columns] 

55 else: 

56 # Fetch data without specifying an id 

57 page_size = 100 # The page size you want to use for API requests 

58 limit = query.limit.value if query.limit else None 

59 result_df = pd.DataFrame(columns=selected_columns) 

60 

61 if limit: 

62 # Calculate the number of pages required 

63 page_count = (limit + page_size - 1) // page_size 

64 else: 

65 page_count = 1 

66 

67 for page in range(1, page_count + 1): 

68 if limit == 0: 

69 break 

70 if limit: 

71 # Calculate the page size for this request 

72 current_page_size = min(page_size, limit) 

73 else: 

74 current_page_size = page_size 

75 

76 df = pd.DataFrame(self.handler.call_intercom_api(endpoint='/articles', params={'page': page, 'per_page': current_page_size})['data'][0]) 

77 if len(df) == 0: 

78 break 

79 result_df = pd.concat([result_df, df[selected_columns]], ignore_index=True) 

80 if limit: 

81 limit -= current_page_size 

82 return result_df 

83 

84 def insert(self, query: ast.Insert) -> None: 

85 """insert 

86 

87 Args: 

88 query (ast.Insert): user's entered query 

89 

90 Returns: 

91 None 

92 """ 

93 data = {} 

94 for column, value in zip(query.columns, query.values[0]): 

95 if isinstance(value, Constant): 

96 data[column.name] = value.value 

97 else: 

98 data[column.name] = value 

99 self.handler.call_intercom_api(endpoint='/articles', method='POST', data=json.dumps(data)) 

100 

101 def update(self, query: ast.Update) -> None: 

102 """update 

103 

104 Args: 

105 query (ast.Update): user's entered query 

106 

107 Returns: 

108 None 

109 """ 

110 conditions = extract_comparison_conditions(query.where) 

111 # Get page id from query 

112 _id = None 

113 for op, arg1, arg2 in conditions: 

114 if arg1 == 'id' and op == '=': 

115 _id = arg2 

116 else: 

117 raise NotImplementedError 

118 

119 data = {} 

120 for key, value in query.update_columns.items(): 

121 if isinstance(value, Constant): 

122 data[key] = value.value 

123 else: 

124 data[key] = value 

125 self.handler.call_intercom_api(endpoint=f'/articles/{_id}', method='PUT', data=json.dumps(data)) 

126 

127 def get_columns(self, ignore: List[str] = []) -> List[str]: 

128 """columns 

129 

130 Args: 

131 ignore (List[str], optional): exclusion items. Defaults to []. 

132 

133 Returns: 

134 List[str]: available columns with `ignore` items removed from the list. 

135 """ 

136 return [ 

137 "type", 

138 "id", 

139 "workspace_id", 

140 "title", 

141 "description", 

142 "body", 

143 "author_id", 

144 "state", 

145 "created_at", 

146 "updated_at", 

147 "url", 

148 "parent_id", 

149 "parent_ids", 

150 "parent_type", 

151 "statistics" 

152 ]