actual_queries.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. import pandas as pd
  2. def prepareQuery(queryData):
  3. type = queryData.get('queryType') # KeyError protected -- returns None if the key is not defined
  4. #################
  5. if type=='occ_tables':
  6. return "SELECT name FROM sqlite_master WHERE type='table'"
  7. #################
  8. if type=='forma':
  9. try:
  10. data = queryData['data']
  11. dataNorm = queryData['dataNorm']
  12. except KeyError as err:
  13. raise KeyError('Missing required data for query type ' + type + ': ' + str(err))
  14. joinedQueryData = "'" + "' OR spec LIKE '".join(data) + "'"
  15. if len(dataNorm)==0:
  16. return f"SELECT spec AS forma, nocc AS occ, cod FROM form WHERE spec LIKE {joinedQueryData} ORDER BY idfor"
  17. else:
  18. joinedQueryDataNorm = "'" + "' OR norm LIKE '".join(dataNorm) + "'"
  19. return f"SELECT DISTINCT spec AS forma, nocc AS occ, cod FROM form WHERE (spec LIKE {joinedQueryData}) OR (norm LIKE {joinedQueryDataNorm}) ORDER BY idfor"
  20. ###################
  21. elif type=='lemma':
  22. try:
  23. data = queryData['data']
  24. dataNorm = queryData['dataNorm']
  25. except KeyError as err:
  26. raise KeyError('Missing required data for query type ' + type + ': ' + str(err))
  27. joinedQueryData = "'" + "' OR spec LIKE '".join(data) + "'"
  28. if len(dataNorm)==0:
  29. return f"SELECT spec AS lemma, cat AS cat_gr, omo AS disambiguatore, nocc AS occ, cod FROM lem WHERE spec LIKE {joinedQueryData} ORDER BY idlem"
  30. else:
  31. joinedQueryDataNorm = "'" + "' OR norm LIKE '".join(dataNorm) + "'"
  32. return f"SELECT DISTINCT spec AS lemma, cat AS cat_gr, omo AS disambiguatore, nocc AS occ, cod FROM lem WHERE (spec LIKE {joinedQueryData}) OR (norm LIKE {joinedQueryDataNorm}) ORDER BY idlem"
  33. ########################
  34. elif type=='lemmaForma':
  35. try:
  36. data = queryData['data']
  37. dataNorm = queryData['dataNorm']
  38. except KeyError as err:
  39. raise KeyError('Missing required data for query type ' + type + ': ' + str(err))
  40. joinedQueryData = "'" + "' OR form.spec LIKE '".join(data) + "'"
  41. if len(dataNorm)==0:
  42. return f"SELECT lem.spec AS lemma, lem.cat AS cat_gr, form.spec AS forma, lem.omo AS disambiguatore, pfl.nocc AS occ, lem.cod FROM pfl INNER JOIN form ON form.cod = pfl.forma INNER JOIN lem ON lem.cod != 0 AND lem.cod = pfl.lemma WHERE lem.spec LIKE {joinedQueryData} ORDER BY lem.idlem"
  43. else:
  44. joinedQueryData = "'" + "' OR lem.spec LIKE '".join(data) + "'"
  45. joinedQueryDataNorm = "'" + "' OR lem.norm LIKE '".join(dataNorm) + "'"
  46. return f"SELECT DISTINCT lem.spec AS lemma, lem.cat AS cat_gr, form.spec AS forma, lem.omo AS disambiguatore, pfl.nocc AS occ, lem.cod FROM pfl INNER JOIN form ON form.cod = pfl.forma INNER JOIN lem ON lem.cod = pfl.lemma WHERE (lem.spec LIKE {joinedQueryData}) OR (lem.norm LIKE {joinedQueryDataNorm}) ORDER BY lem.idlem"
  47. ########################
  48. elif type=='formaLemma':
  49. try:
  50. data = queryData['data']
  51. dataNorm = queryData['dataNorm']
  52. except KeyError as err:
  53. raise KeyError('Missing required data for query type ' + type + ': ' + str(err))
  54. joinedQueryData = "'" + "' OR form.spec LIKE '".join(data) + "'"
  55. if len(dataNorm)==0:
  56. return f"SELECT form.spec AS forma, lem.spec AS lemma, lem.cat AS cat_gr, lem.omo AS disambiguatore, pfl.nocc AS occ, form.cod FROM pfl INNER JOIN form ON form.cod = pfl.forma INNER JOIN lem ON lem.cod = pfl.lemma WHERE form.spec LIKE {joinedQueryData} ORDER BY form.idfor"
  57. else:
  58. joinedQueryDataNorm = "'" + "' OR form.norm LIKE '".join(dataNorm) + "'"
  59. return f"SELECT DISTINCT form.spec AS forma, lem.spec AS lemma, lem.cat AS cat_gr, lem.omo AS disambiguatore, pfl.nocc AS occ, form.cod FROM pfl INNER JOIN form ON form.cod = pfl.forma INNER JOIN lem ON lem.cod = pfl.lemma WHERE (form.spec LIKE {joinedQueryData}) OR (form.norm LIKE {joinedQueryDataNorm}) ORDER BY form.idfor"
  60. #################
  61. elif type=='pfl':
  62. try:
  63. codList = queryData['codList']
  64. except KeyError as err:
  65. raise KeyError('Missing required data for query type ' + type + ': ' + str(err))
  66. strlist = ",".join(str(c) for c in codList)
  67. return f"SELECT DISTINCT lemma as codLemma, forma as codForma FROM pfl WHERE lemma IN ({strlist})"
  68. ###################
  69. elif type=='texts':
  70. return complexQueryTexts
  71. ###################
  72. elif type=='co-occurrences':
  73. return complexQueryCooccurrences
  74. ######################
  75. elif type=='bib':
  76. try:
  77. row = queryData['row']
  78. sigla = row['sigla']
  79. except KeyError as err:
  80. raise KeyError('Missing required data for query type ' + type + ': ' + str(err))
  81. return f"SELECT [Anno iniziale], [Anno finale], [Data codificata], [Titolo Abbreviato], [Autore], [Titolo], [Curatore], [Data descrittiva], [Area generica], [Area specifica], [Genere], [Forma], [Tipo], IQ FROM datibib WHERE Sigla='{sigla}'"
  82. #################
  83. elif type=='bibAlt':
  84. try:
  85. siglaSet = queryData['siglaSet']
  86. except KeyError as err:
  87. raise KeyError('Missing required data for query type ' + type + ': ' + str(err))
  88. siglaStr = "'" + "','".join(siglaSet) + "'"
  89. return f"SELECT Sigla, [Anno iniziale], [Anno finale], [Data codificata], [Titolo Abbreviato], [Autore], [Titolo], [Curatore], [Data descrittiva], [Area generica], [Area specifica], [Genere], [Forma], [Tipo], IQ FROM datibib WHERE Sigla IN ({siglaStr})"
  90. #################
  91. elif type=='rif':
  92. try:
  93. row = queryData['row']
  94. numorg = row['numorg']
  95. ntx = row['ntx']
  96. except:
  97. return None
  98. return f"SELECT head AS Rif_organico, full AS Rif_completo FROM org WHERE (indice='{numorg}' AND ntx='{ntx}')"
  99. #################
  100. elif type=='rifAlt':
  101. try:
  102. coordsSet = queryData['coordsSet']
  103. except KeyError as err:
  104. raise KeyError('Missing required data for query type ' + type + ': ' + str(err))
  105. subQueries = []
  106. for coords in coordsSet:
  107. try:
  108. numorg = coords[0]
  109. ntx = coords[1]
  110. except IndexError as err:
  111. raise KeyError('Incomplete required data for query type ' + type + ': ' + str(err))
  112. subQueries.append( f"SELECT indice AS numorg, ntx, head AS Rif_organico, full AS Rif_completo FROM org WHERE (indice='{numorg}' AND ntx='{ntx}')" )
  113. return ' UNION ALL '.join(subQueries)
  114. #################
  115. elif type=='highlight':
  116. try:
  117. row = queryData['row']
  118. col = queryData['col']
  119. except:
  120. return None
  121. return f"SELECT spec as highlight FROM form WHERE cod={row[col]}"
  122. #################
  123. elif type =='singlecontext':
  124. try:
  125. subtype = queryData['querySubtype']
  126. table = queryData['table']
  127. parole = queryData['parole']
  128. periodi = queryData['periodi']
  129. brani = queryData['brani']
  130. ntxlocal = queryData['ntxlocal']
  131. mappalocal = queryData['mappalocal']
  132. periodlocal = queryData['periodlocal']
  133. numbranolocal = queryData['numbranolocal']
  134. except:
  135. return None
  136. if subtype == 'parole':
  137. return f"SELECT tab.pitxt, tab.elemlen FROM {table} AS tab WHERE tab.ntx = {ntxlocal} AND tab.mappa <= {mappalocal+int(parole/2)} AND tab.mappa >= {mappalocal-int(parole/2)}"
  138. elif subtype == 'periodi':
  139. return f"SELECT piniz, pfin FROM periodi WHERE ntx = {ntxlocal} AND numperiod <= {periodlocal+int(periodi/2)} AND numperiod >= {periodlocal-int(periodi/2)}"
  140. elif subtype == 'brani':
  141. return f"SELECT piniz, pfin FROM linkbase WHERE {ntxlocal} = ntx AND tipo = 2 AND id BETWEEN {numbranolocal-int(brani/2)} AND {numbranolocal+int(brani/2)}"
  142. #################
  143. elif type =='links':
  144. try:
  145. subtype = queryData['querySubtype']
  146. ntxlocal = queryData['ntxlocal']
  147. pinizlocal = queryData['pinizlocal']
  148. pfinlocal = queryData['pfinlocal']
  149. pitxtlocal = queryData['pitxtlocal']
  150. except:
  151. return None
  152. if subtype == 'nota':
  153. return f"SELECT ta.ntx, ta.id, ta.piniz, ta.pfin, tb.mappain, tb.mappafin FROM linkbase AS tb INNER JOIN linknoteass AS ta ON tb.ntx = ta.ntx AND tb.id = ta.id WHERE (((tb.tipo= 1) AND (tb.ntx = {ntxlocal})) AND ((tb.piniz BETWEEN {pinizlocal} AND {pfinlocal}) OR ({pitxtlocal} BETWEEN tb.piniz AND tb.pfin)))"
  154. if subtype == 'testo_associato':
  155. return f"SELECT ta.ntx, ta.id, ta.piniz, ta.pfin, tb.mappain, tb.mappafin FROM linkbase AS tb INNER JOIN linknoteass AS ta ON tb.ntx = ta.ntx AND tb.id = ta.id WHERE (((tb.tipo= 2) AND (tb.ntx = {ntxlocal})) AND ((tb.piniz BETWEEN {pinizlocal} AND {pfinlocal}) OR ({pitxtlocal} BETWEEN tb.piniz AND tb.pfin)))"
  156. #####
  157. else:
  158. raise ValueError('Unrecognized query type: ' + type)
  159. def complexQueryTexts(connection, queryData):
  160. try:
  161. codList = queryData['codList']
  162. table = queryData['table']
  163. subtype = queryData['querySubtype']
  164. formCodList = queryData.get('formCodList') # KeyError-safe (None if absent)
  165. except KeyError as err:
  166. raise KeyError('Missing required data for query type ' + type + ': ' + str(err))
  167. strCodList = ",".join(str(c) for c in codList)
  168. # Main query, verified to be fast!
  169. mainQueryString = f"SELECT tab.cod, tab.ntx, tab.pitxt, tab.elemlen, tab.mappa, tab.numperiod, tab.links, tab.numorg, intbib.sigla, tab.vol, tab.pag, tab.riga, tab.col, tab.tipostanza, tab.stanza, tab.verso, tab.numbrano, lem.spec AS lemma, lem.cat AS cat_gr, lem.omo AS disambiguatore FROM {table} AS tab INNER JOIN intbib ON tab.ntx = intbib.ntx INNER JOIN lem ON tab.indlem = lem.cod"
  170. if subtype==0:
  171. condition = f"WHERE tab.cod IN ({strCodList})"
  172. elif subtype==1:
  173. condition = f"WHERE tab.indlem IN ({strCodList})"
  174. elif subtype==2:
  175. if formCodList is None:
  176. return None
  177. strFormCodList = ",".join(str(c) for c in formCodList)
  178. condition = f" WHERE tab.indlem IN ({strCodList}) OR (tab.indlem = 0 AND tab.cod IN ({strFormCodList}))"
  179. mainQueryString = f'{mainQueryString} {condition}'
  180. # This value can be changed to change multiple contexts width. Default value for Gatto is parole=31 #
  181. parole = 31
  182. # C'è la possibilità di scegliere periodi invece che parole, ma per il momento è disabilitata
  183. createTempTable = f'CREATE TEMPORARY TABLE stuff AS {mainQueryString}'
  184. mainQuery = f'SELECT * from stuff'
  185. addQuery1 = f'SELECT stuff.ntx, stuff.mappa, tab.pitxt AS piniz FROM stuff LEFT JOIN Occ00001 AS tab ON tab.ntx=stuff.ntx AND tab.mappa=stuff.mappa-{int(parole/2)}'
  186. addQuery2 = f'SELECT stuff.ntx, stuff.mappa, tab.pitxt AS pfin FROM stuff LEFT JOIN Occ00001 AS tab ON tab.ntx=stuff.ntx AND tab.mappa=stuff.mappa+{int(parole/2)}'
  187. addQuery3 = f'SELECT stuff.ntx, stuff.numperiod, periodi.piniz AS backup_piniz, periodi.pfin AS backup_pfin FROM stuff, periodi WHERE stuff.ntx = periodi.ntx AND stuff.numperiod = periodi.numperiod'
  188. # Start communication with DB
  189. connection.cursor().execute(createTempTable)
  190. results = pd.read_sql(mainQuery, connection)
  191. results_add1 = pd.read_sql(addQuery1, connection)
  192. results_add2 = pd.read_sql(addQuery2, connection)
  193. results_add3 = pd.read_sql(addQuery3, connection)
  194. results['piniz'] = results_add1['piniz']
  195. results['pfin'] = results_add2['pfin']
  196. results[['backup_piniz', 'backup_pfin']] = results_add3[['backup_piniz', 'backup_pfin']]
  197. return results
  198. def complexQueryCooccurrences(connection, queryData):
  199. try:
  200. # the get method for dicts is KeyError-safe (returns None if key is absent)
  201. occurrences = queryData['occurrences']
  202. table = queryData['table']
  203. intervallo = queryData['intervallo']
  204. periodo = queryData.get('periodo') # Unused for the moment
  205. ordinate = queryData.get('ordinate') # Unused for the moment
  206. if periodo is None:
  207. periodo = 0
  208. if ordinate is None:
  209. ordinate = 0
  210. except KeyError as err:
  211. raise KeyError('Missing required data for query: ' + str(err))
  212. # Main part of main query -- verified to be fast!
  213. preMainQueryString = f"SELECT tab.cod, tab.ntx, tab.pitxt, tab.elemlen, tab.mappa, tab.numperiod, tab.links, tab.numorg, intbib.sigla, tab.vol, tab.pag, tab.riga, tab.col, tab.tipostanza, tab.stanza, tab.verso, tab.numbrano, lem.spec AS lemma, lem.cat AS cat_gr, lem.omo AS disambiguatore FROM {table} AS tab INNER JOIN intbib ON tab.ntx = intbib.ntx INNER JOIN lem ON tab.indlem = lem.cod"
  214. # Main loop on the different occurrences searched by user
  215. pitxtList = ['pitxt']
  216. elemlenList = ['elemlen']
  217. for index, occ in enumerate(occurrences):
  218. try:
  219. subtype = occ['querySubtype']
  220. codList = occ['codList']
  221. formCodList = occ.get('formCodList')
  222. except KeyError as err:
  223. raise KeyError('Missing required data for query: ' + str(err))
  224. strCodList = ",".join(str(c) for c in codList)
  225. if subtype==0:
  226. condition = f" WHERE tab.cod IN ({strCodList})"
  227. elif subtype==1:
  228. condition = f" WHERE tab.indlem IN ({strCodList})"
  229. elif subtype==2:
  230. if formCodList is None:
  231. return None
  232. strFormCodList = ",".join(str(c) for c in formCodList)
  233. condition = f" WHERE tab.indlem IN ({strCodList}) OR (tab.indlem = 0 AND tab.cod IN ({strFormCodList}))"
  234. mainQueryString = f'{preMainQueryString} {condition}'
  235. # First occurrence:
  236. if index==0:
  237. # Create a temporary table for results
  238. resTable = 'tempOcc_' + str(index)
  239. connection.cursor().execute(f'CREATE TEMPORARY TABLE {resTable} AS {mainQueryString}')
  240. connection.cursor().execute(f'CREATE INDEX aa_{index} ON {resTable} (ntx, mappa)')
  241. continue
  242. else:
  243. # update results
  244. connection.cursor().execute(f'CREATE TEMPORARY TABLE tempOccB AS {mainQueryString}')
  245. connection.cursor().execute(f'CREATE INDEX bb ON tempOccB (ntx, mappa)')
  246. oldTable = resTable
  247. resTable = 'tempOcc_' + str(index)
  248. connection.cursor().execute(f'CREATE TEMPORARY TABLE {resTable} AS SELECT tabA.cod, tabA.ntx, tabA.{" tabA.".join(pitxtList)}, tabA.{" tabA.".join(elemlenList)}, tabA.mappa, tabA.numperiod, tabA.links, tabA.numorg, tabA.sigla, tabA.vol, tabA.pag, tabA.riga, tabA.col, tabA.tipostanza, tabA.stanza, tabA.verso, tabA.numbrano, tabA.lemma, tabA.cat_gr, tabA.disambiguatore, tabB.ntx AS ntx2, tabB.mappa AS mappa2, tabB.pitxt as pitxt_{index}, tabB.elemlen as elemlen_{index} FROM {oldTable} AS tabA, tempOccB AS tabB WHERE tabA.ntx=tabB.ntx AND tabA.mappa BETWEEN tabB.mappa-{intervallo} AND tabB.mappa+{intervallo} AND tabA.mappa != tabB.mappa')
  249. connection.cursor().execute(f'CREATE INDEX aa_{index} ON {resTable} (ntx, mappa)')
  250. connection.cursor().execute(f'DROP TABLE {oldTable}')
  251. pitxtList.append(f'pitxt_{index}')
  252. elemlenList.append(f'elemlen_{index}')
  253. results = pd.read_sql(f'SELECT * FROM {resTable}', connection)
  254. # This value can be changed to change multiple contexts width. Default value for Gatto is parole=31
  255. parole = 31
  256. # C'è la possibilità di scegliere periodi invece che parole, ma per il momento è disabilitata
  257. queryPiniz = f'SELECT stuff.ntx, stuff.mappa, tab.pitxt AS piniz FROM {resTable} AS stuff LEFT JOIN {table} AS tab ON tab.ntx=stuff.ntx AND tab.mappa=stuff.mappa-{int(parole/2)}'
  258. queryPfin = f'SELECT stuff.ntx, stuff.mappa, tab.pitxt AS pfin FROM {resTable} AS stuff LEFT JOIN {table} AS tab ON tab.ntx=stuff.ntx AND tab.mappa=stuff.mappa+{int(parole/2)}'
  259. queryPeriodi = f'SELECT stuff.ntx, stuff.numperiod, periodi.piniz AS backup_piniz, periodi.pfin AS backup_pfin FROM {resTable} AS stuff, periodi WHERE stuff.ntx = periodi.ntx AND stuff.numperiod = periodi.numperiod'
  260. resultsPiniz = pd.read_sql(queryPiniz, connection)
  261. resultsPfin = pd.read_sql(queryPfin, connection)
  262. resultsPeriodi = pd.read_sql(queryPeriodi, connection)
  263. results['piniz'] = resultsPiniz['piniz']
  264. results['pfin'] = resultsPfin['pfin']
  265. results[['backup_piniz', 'backup_pfin']] = resultsPeriodi[['backup_piniz', 'backup_pfin']]
  266. return results