loader.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910
  1. #
  2. # Metrix++, Copyright 2009-2013, Metrix++ Project
  3. # Link: http://metrixplusplus.sourceforge.net
  4. #
  5. # This file is a part of Metrix++ Tool.
  6. #
  7. # Metrix++ is free software: you can redistribute it and/or modify
  8. # it under the terms of the GNU General Public License as published by
  9. # the Free Software Foundation, version 3 of the License.
  10. #
  11. # Metrix++ is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. # GNU General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU General Public License
  17. # along with Metrix++. If not, see <http://www.gnu.org/licenses/>.
  18. #
  19. import logging
  20. import os.path
  21. import core.api
  22. import core.db.sqlite
  23. ####################################
  24. # Data Interface
  25. ####################################
  26. class Data(object):
  27. def __init__(self):
  28. self.data = {}
  29. def get_data(self, namespace, field):
  30. if namespace not in self.data.keys():
  31. return None
  32. if field not in self.data[namespace].keys():
  33. return None
  34. return self.data[namespace][field]
  35. def set_data(self, namespace, field, value):
  36. if namespace not in self.data:
  37. self.data[namespace] = {}
  38. self.data[namespace][field] = value
  39. def iterate_namespaces(self):
  40. for namespace in self.data.keys():
  41. yield namespace
  42. def iterate_fields(self, namespace):
  43. for field in self.data[namespace].keys():
  44. yield (field, self.data[namespace][field])
  45. def get_data_tree(self, namespaces=None):
  46. return self.data
  47. def __repr__(self):
  48. return object.__repr__(self) + " with data " + self.data.__repr__()
  49. class LoadableData(Data):
  50. def __init__(self, loader, file_id, region_id):
  51. Data.__init__(self)
  52. self.loader = loader
  53. self.file_id = file_id
  54. self.region_id = region_id
  55. self.loaded_namespaces = []
  56. self.changed_namespaces = []
  57. def load_namespace(self, namespace):
  58. try:
  59. row = self.loader.db.get_row(namespace, self.file_id, self.region_id)
  60. except Exception:
  61. logging.debug("No data in the database for namespace: " + namespace)
  62. return
  63. if row == None:
  64. return
  65. for column_name in row.keys():
  66. packager = self.loader.get_namespace(namespace).get_field_packager(column_name)
  67. if packager == None:
  68. continue
  69. Data.set_data(self, namespace, column_name, packager.unpack(row[column_name]))
  70. def set_data(self, namespace, field, value):
  71. if namespace not in self.changed_namespaces:
  72. self.changed_namespaces.append(namespace)
  73. return Data.set_data(self, namespace, field, value)
  74. def get_data(self, namespace, field):
  75. if namespace not in self.loaded_namespaces:
  76. self.loaded_namespaces.append(namespace)
  77. self.load_namespace(namespace)
  78. return Data.get_data(self, namespace, field)
  79. def is_namespace_updated(self, namespace):
  80. return namespace in self.changed_namespaces
  81. def is_namespace_loaded(self, namespace):
  82. return namespace in self.loaded_namespaces
  83. def get_data_tree(self, namespaces=None):
  84. if namespaces == None:
  85. namespaces = self.loader.iterate_namespace_names()
  86. for each in namespaces:
  87. self.load_namespace(each)
  88. return Data.get_data_tree(self)
  89. class FileRegionData(LoadableData):
  90. class T(object):
  91. NONE = 0x00
  92. GLOBAL = 0x01
  93. CLASS = 0x02
  94. STRUCT = 0x04
  95. NAMESPACE = 0x08
  96. FUNCTION = 0x10
  97. INTERFACE = 0x20
  98. ANY = 0xFFFFFFFF
  99. def to_str(self, group):
  100. if group == self.NONE:
  101. return "none"
  102. elif group == self.GLOBAL:
  103. return "global"
  104. elif group == self.CLASS:
  105. return "class"
  106. elif group == self.STRUCT:
  107. return "struct"
  108. elif group == self.NAMESPACE:
  109. return "namespace"
  110. elif group == self.FUNCTION:
  111. return "function"
  112. elif group == self.INTERFACE:
  113. return "interface"
  114. else:
  115. assert(False)
  116. def __init__(self, loader, file_id, region_id, region_name, offset_begin, offset_end, line_begin, line_end, cursor_line, group, checksum):
  117. LoadableData.__init__(self, loader, file_id, region_id)
  118. self.name = region_name
  119. self.begin = offset_begin
  120. self.end = offset_end
  121. self.line_begin = line_begin
  122. self.line_end = line_end
  123. self.cursor = cursor_line
  124. self.group = group
  125. self.checksum = checksum
  126. self.children = []
  127. def get_id(self):
  128. return self.region_id
  129. def get_name(self):
  130. return self.name
  131. def get_offset_begin(self):
  132. return self.begin
  133. def get_offset_end(self):
  134. return self.end
  135. def get_line_begin(self):
  136. return self.line_begin
  137. def get_line_end(self):
  138. return self.line_end
  139. def get_cursor(self):
  140. return self.cursor
  141. def get_type(self):
  142. return self.group
  143. def get_checksum(self):
  144. return self.checksum
  145. def register_subregion_id(self, child_id):
  146. self.children.append(child_id)
  147. def iterate_subregion_ids(self):
  148. return self.children
  149. class Marker(object):
  150. class T(object):
  151. NONE = 0x00
  152. COMMENT = 0x01
  153. STRING = 0x02
  154. PREPROCESSOR = 0x04
  155. ALL_EXCEPT_CODE = 0x07
  156. def to_str(self, group):
  157. if group == self.NONE:
  158. return "none"
  159. elif group == self.COMMENT:
  160. return "comment"
  161. elif group == self.STRING:
  162. return "string"
  163. elif group == self.PREPROCESSOR:
  164. return "preprocessor"
  165. else:
  166. assert(False)
  167. def __init__(self, offset_begin, offset_end, group):
  168. self.begin = offset_begin
  169. self.end = offset_end
  170. self.group = group
  171. def get_offset_begin(self):
  172. return self.begin
  173. def get_offset_end(self):
  174. return self.end
  175. def get_type(self):
  176. return self.group
  177. class FileData(LoadableData):
  178. def __init__(self, loader, path, file_id, checksum, content):
  179. LoadableData.__init__(self, loader, file_id, None)
  180. self.path = path
  181. self.checksum = checksum
  182. self.content = content
  183. self.regions = None
  184. self.markers = None
  185. self.loader = loader
  186. self.loading_tmp = []
  187. def get_id(self):
  188. return self.file_id
  189. def get_path(self):
  190. return self.path
  191. def get_checksum(self):
  192. return self.checksum
  193. def get_content(self, exclude = Marker.T.NONE):
  194. if exclude == Marker.T.NONE:
  195. return self.content
  196. if exclude == (Marker.T.COMMENT | Marker.T.STRING | Marker.T.PREPROCESSOR):
  197. # optimise frequent queries of this type
  198. if hasattr(self, 'content_cache'):
  199. return self.content_cache
  200. last_pos = 0
  201. content = ""
  202. for marker in self.iterate_markers(exclude):
  203. content += self.content[last_pos:marker.begin]
  204. content += " " * (marker.end - marker.begin)
  205. last_pos = marker.end
  206. content += self.content[last_pos:]
  207. if exclude == (Marker.T.COMMENT | Marker.T.STRING | Marker.T.PREPROCESSOR):
  208. self.content_cache = content
  209. assert(len(content) == len(self.content))
  210. return content
  211. def internal_append_region(self, region):
  212. # here we apply some magic - we rely on special ordering of coming regions,
  213. # which is supported by code parsers
  214. prev_id = None
  215. while True:
  216. if len(self.loading_tmp) == 0:
  217. break
  218. prev_id = self.loading_tmp.pop()
  219. if self.get_region(prev_id).get_offset_end() > region.get_offset_begin():
  220. self.loading_tmp.append(prev_id) # return back
  221. break
  222. self.loading_tmp.append(region.get_id())
  223. if prev_id != None:
  224. self.get_region(prev_id).register_subregion_id(region.get_id())
  225. self.regions.append(region)
  226. def load_regions(self):
  227. if self.regions == None:
  228. self.regions = []
  229. for each in self.loader.db.iterate_regions(self.get_id()):
  230. self.internal_append_region(FileRegionData(self.loader,
  231. self.get_id(),
  232. each.region_id,
  233. each.name,
  234. each.begin,
  235. each.end,
  236. each.line_begin,
  237. each.line_end,
  238. each.cursor,
  239. each.group,
  240. each.checksum))
  241. assert(len(self.regions) == each.region_id)
  242. def add_region(self, region_name, offset_begin, offset_end, line_begin, line_end, cursor_line, group, checksum):
  243. if self.regions == None:
  244. self.regions = [] # do not load in time of collection
  245. new_id = len(self.regions) + 1
  246. self.internal_append_region(FileRegionData(self.loader, self.get_id(), new_id, region_name, offset_begin, offset_end, line_begin, line_end, cursor_line, group, checksum))
  247. self.loader.db.create_region(self.file_id, new_id, region_name, offset_begin, offset_end, line_begin, line_end, cursor_line, group, checksum)
  248. return new_id
  249. def get_region(self, region_id):
  250. self.load_regions()
  251. return self.regions[region_id - 1]
  252. def iterate_regions(self, filter_group = FileRegionData.T.ANY):
  253. self.load_regions()
  254. for each in self.regions:
  255. if each.group & filter_group:
  256. yield each
  257. def are_regions_loaded(self):
  258. return self.regions != None
  259. def load_markers(self):
  260. if self.markers == None:
  261. self.markers = []
  262. for each in self.loader.db.iterate_markers(self.get_id()):
  263. self.markers.append(Marker(each.begin, each.end, each.group))
  264. def add_marker(self, offset_begin, offset_end, group):
  265. if self.markers == None:
  266. self.markers = [] # do not load in time of collection
  267. self.markers.append(Marker(offset_begin, offset_end, group))
  268. self.loader.db.create_marker(self.file_id, offset_begin, offset_end, group)
  269. def iterate_markers(self, filter_group = Marker.T.COMMENT |
  270. Marker.T.STRING | Marker.T.PREPROCESSOR,
  271. region_id = None, exclude_children = True):
  272. self.load_markers()
  273. if region_id == None:
  274. for each in self.markers:
  275. if each.group & filter_group:
  276. yield each
  277. else:
  278. region = self.get_region(region_id)
  279. if region != None:
  280. if hasattr(region, 'markers_list') == False:
  281. def cache_markers_list_req(data, region_id, marker_start_pos):
  282. region = data.get_region(region_id)
  283. region.markers_list = []
  284. region.first_marker_pos = marker_start_pos
  285. for sub_id in region.iterate_subregion_ids():
  286. subregion = data.get_region(sub_id)
  287. while len(data.markers) > marker_start_pos and \
  288. subregion.get_offset_begin() > data.markers[marker_start_pos].get_offset_begin():
  289. region.markers_list.append(marker_start_pos)
  290. marker_start_pos += 1
  291. marker_start_pos = cache_markers_list_req(data, sub_id, marker_start_pos)
  292. while len(data.markers) > marker_start_pos and \
  293. region.get_offset_end() > data.markers[marker_start_pos].get_offset_begin():
  294. region.markers_list.append(marker_start_pos)
  295. marker_start_pos += 1
  296. return marker_start_pos
  297. next_marker_pos = cache_markers_list_req(self, 1, 0)
  298. assert(next_marker_pos == len(self.markers))
  299. if exclude_children == True:
  300. for marker_pos in region.markers_list:
  301. marker = self.markers[marker_pos]
  302. if marker.group & filter_group:
  303. yield marker
  304. elif len(self.markers) > region.first_marker_pos:
  305. for marker in self.markers[region.first_marker_pos:]:
  306. if marker.get_offset_begin() >= region.get_offset_end():
  307. break
  308. if region.get_offset_begin() > marker.get_offset_begin():
  309. continue
  310. if marker.group & filter_group:
  311. yield marker
  312. def get_marker_types(self):
  313. return Marker.T
  314. def get_region_types(self):
  315. return FileRegionData.T
  316. def are_markers_loaded(self):
  317. return self.markers != None
  318. def __repr__(self):
  319. return Data.__repr__(self) + " and regions " + self.regions.__repr__()
  320. class AggregatedData(Data):
  321. def __init__(self, loader, path):
  322. Data.__init__(self)
  323. self.path = path
  324. self.loader = loader
  325. self.subdirs = None
  326. self.subfiles = None
  327. def get_subdirs(self):
  328. if self.subdirs != None:
  329. return self.subdirs
  330. self.subdirs = []
  331. if self.path != None:
  332. for subdir in self.loader.db.iterate_dircontent(self.path, include_subdirs = True, include_subfiles = False):
  333. self.subdirs.append(subdir)
  334. return self.subdirs
  335. def get_subfiles(self):
  336. if self.subfiles != None:
  337. return self.subfiles
  338. self.subfiles = []
  339. if self.path != None:
  340. for subfile in self.loader.db.iterate_dircontent(self.path, include_subdirs = False, include_subfiles = True):
  341. self.subfiles.append(subfile)
  342. return self.subfiles
  343. class SelectData(Data):
  344. def __init__(self, loader, path, file_id, region_id):
  345. Data.__init__(self)
  346. self.loader = loader
  347. self.path = path
  348. self.file_id = file_id
  349. self.region_id = region_id
  350. self.region = None
  351. def get_path(self):
  352. return self.path
  353. def get_region(self):
  354. if self.region == None and self.region_id != None:
  355. row = self.loader.db.get_region(self.file_id, self.region_id)
  356. if row != None:
  357. self.region = FileRegionData(self.loader,
  358. self.file_id,
  359. self.region_id,
  360. row.name,
  361. row.begin,
  362. row.end,
  363. row.line_begin,
  364. row.line_end,
  365. row.cursor,
  366. row.group,
  367. row.checksum)
  368. return self.region
  369. class DiffData(Data):
  370. def __init__(self, new_data, old_data):
  371. Data.__init__(self)
  372. self.new_data = new_data
  373. self.old_data = old_data
  374. def get_data(self, namespace, field):
  375. new_data = self.new_data.get_data(namespace, field)
  376. old_data = self.old_data.get_data(namespace, field)
  377. if new_data == None:
  378. return None
  379. if old_data == None:
  380. # non_zero fields has got zero value by default if missed
  381. # the data can be also unavailable,
  382. # because previous collection does not include that
  383. # but external tools (like limit.py) should warn about this,
  384. # using list of registered database properties
  385. old_data = 0
  386. return new_data - old_data
  387. ####################################
  388. # Packager Interface
  389. ####################################
  390. class PackagerError(Exception):
  391. def __init__(self):
  392. Exception.__init__(self, "Failed to pack or unpack.")
  393. class PackagerFactory(object):
  394. def create(self, python_type, non_zero):
  395. if python_type == None:
  396. return PackagerFactory.SkipPackager()
  397. if python_type == int:
  398. if non_zero == False:
  399. return PackagerFactory.IntPackager()
  400. else:
  401. return PackagerFactory.IntNonZeroPackager()
  402. if python_type == float and non_zero == False:
  403. return PackagerFactory.FloatPackager()
  404. if python_type == str:
  405. return PackagerFactory.StringPackager()
  406. class PackagerFactoryError(Exception):
  407. def __init__(self, python_type):
  408. Exception.__init__(self, "Python type '" + str(python_type) + "' is not supported by the factory.")
  409. raise PackagerFactoryError(python_type)
  410. def get_python_type(self, sql_type):
  411. if sql_type == "integer":
  412. return int
  413. if sql_type == "real":
  414. return float
  415. if sql_type == "text":
  416. return str
  417. class PackagerFactoryError(Exception):
  418. def __init__(self, sql_type):
  419. Exception.__init__(self, "SQL type '" + str(sql_type) + "' is not supported by the factory.")
  420. raise PackagerFactoryError(sql_type)
  421. class IPackager(object):
  422. def pack(self, unpacked_data):
  423. raise core.api.InterfaceNotImplemented(self)
  424. def unpack(self, packed_data):
  425. raise core.api.InterfaceNotImplemented(self)
  426. def get_sql_type(self):
  427. raise core.api.InterfaceNotImplemented(self)
  428. def get_python_type(self):
  429. raise core.api.InterfaceNotImplemented(self)
  430. def is_non_zero(self):
  431. return False
  432. class IntPackager(IPackager):
  433. def pack(self, unpacked_data):
  434. if not isinstance(unpacked_data, int):
  435. raise PackagerError()
  436. return str(unpacked_data)
  437. def unpack(self, packed_data):
  438. try:
  439. return int(packed_data)
  440. except ValueError:
  441. raise PackagerError()
  442. def get_sql_type(self):
  443. return "integer"
  444. def get_python_type(self):
  445. return int
  446. class IntNonZeroPackager(IntPackager):
  447. def pack(self, unpacked_data):
  448. if unpacked_data == 0:
  449. raise PackagerError()
  450. return PackagerFactory.IntPackager.pack(self, unpacked_data)
  451. def is_non_zero(self):
  452. return True
  453. class FloatPackager(IPackager):
  454. def pack(self, unpacked_data):
  455. if not isinstance(unpacked_data, float):
  456. raise PackagerError()
  457. return str(unpacked_data)
  458. def unpack(self, packed_data):
  459. try:
  460. return float(packed_data)
  461. except ValueError:
  462. raise PackagerError()
  463. def get_sql_type(self):
  464. return "real"
  465. def get_python_type(self):
  466. return float
  467. class FloatNonZeroPackager(FloatPackager):
  468. def pack(self, unpacked_data):
  469. if unpacked_data == 0:
  470. raise PackagerError()
  471. return PackagerFactory.FloatPackager.pack(self, unpacked_data)
  472. def is_non_zero(self):
  473. return True
  474. class StringPackager(IPackager):
  475. def pack(self, unpacked_data):
  476. if not isinstance(unpacked_data, str):
  477. raise PackagerError()
  478. return str(unpacked_data)
  479. def unpack(self, packed_data):
  480. try:
  481. return str(packed_data)
  482. except ValueError:
  483. raise PackagerError()
  484. def get_sql_type(self):
  485. return "text"
  486. def get_python_type(self):
  487. return str
  488. class SkipPackager(IPackager):
  489. def pack(self, unpacked_data):
  490. return None
  491. def unpack(self, packed_data):
  492. return None
  493. def get_sql_type(self):
  494. return None
  495. def get_python_type(self):
  496. return None
  497. ####################################
  498. # Loader
  499. ####################################
  500. class NamespaceError(Exception):
  501. def __init__(self, namespace, reason):
  502. Exception.__init__(self, "Namespace '"
  503. + namespace
  504. + "': '"
  505. + reason
  506. + "'")
  507. class FieldError(Exception):
  508. def __init__(self, field, reason):
  509. Exception.__init__(self, "Field '"
  510. + field
  511. + "': '"
  512. + reason
  513. + "'")
  514. class Namespace(object):
  515. def __init__(self, db_handle, name, support_regions = False):
  516. if not isinstance(name, str):
  517. raise NamespaceError(name, "name not a string")
  518. self.name = name
  519. self.support_regions = support_regions
  520. self.fields = {}
  521. self.db = db_handle
  522. if self.db.check_table(name) == False:
  523. self.db.create_table(name, support_regions)
  524. else:
  525. for column in self.db.iterate_columns(name):
  526. self.add_field(column.name, PackagerFactory().get_python_type(column.sql_type), non_zero=column.non_zero)
  527. def get_name(self):
  528. return self.name
  529. def are_regions_supported(self):
  530. return self.support_regions
  531. def add_field(self, field_name, python_type, non_zero=False):
  532. if not isinstance(field_name, str):
  533. raise FieldError(field_name, "field_name not a string")
  534. packager = PackagerFactory().create(python_type, non_zero)
  535. if field_name in self.fields.keys():
  536. raise FieldError(field_name, "double used")
  537. self.fields[field_name] = packager
  538. if self.db.check_column(self.get_name(), field_name) == False:
  539. self.db.create_column(self.name, field_name, packager.get_sql_type(), non_zero=non_zero)
  540. def iterate_field_names(self):
  541. for name in self.fields.keys():
  542. yield name
  543. def get_field_packager(self, field_name):
  544. if field_name in self.fields.keys():
  545. return self.fields[field_name]
  546. else:
  547. return None
  548. def get_field_sql_type(self, field_name):
  549. return self.get_field_packager(field_name).get_sql_type()
  550. def get_field_python_type(self, field_name):
  551. return self.get_field_packager(field_name).get_python_type()
  552. class DataNotPackable(Exception):
  553. def __init__(self, namespace, field, value, packager, extra_message):
  554. Exception.__init__(self, "Data '"
  555. + str(value)
  556. + "' of type "
  557. + str(value.__class__)
  558. + " referred by '"
  559. + namespace
  560. + "=>"
  561. + field
  562. + "' is not packable by registered packager '"
  563. + str(packager.__class__)
  564. + "': " + extra_message)
  565. class Loader(object):
  566. def __init__(self):
  567. self.namespaces = {}
  568. self.db = None
  569. self.last_file_data = None # for performance boost reasons
  570. def create_database(self, dbfile, previous_db = None):
  571. self.db = core.db.sqlite.Database()
  572. if os.path.exists(dbfile):
  573. logging.warn("Removing existing file: " + dbfile)
  574. os.unlink(dbfile)
  575. if previous_db != None and os.path.exists(previous_db) == False:
  576. raise core.api.ExitError(None, "Database file '" + previous_db + "' does not exist")
  577. self.db.create(dbfile, clone_from=previous_db)
  578. def open_database(self, dbfile, read_only = True):
  579. self.db = core.db.sqlite.Database()
  580. if os.path.exists(dbfile) == False:
  581. raise core.api.ExitError(None, "Database file '" + dbfile + "' does not exist")
  582. self.db.connect(dbfile, read_only=read_only)
  583. for table in self.db.iterate_tables():
  584. self.create_namespace(table.name, table.support_regions)
  585. def set_property(self, property_name, value):
  586. if self.db == None:
  587. return None
  588. return self.db.set_property(property_name, value)
  589. def get_property(self, property_name):
  590. if self.db == None:
  591. return None
  592. return self.db.get_property(property_name)
  593. def iterate_properties(self):
  594. if self.db == None:
  595. return None
  596. return self.db.iterate_properties()
  597. def create_namespace(self, name, support_regions = False):
  598. if self.db == None:
  599. return None
  600. if name in self.namespaces.keys():
  601. raise NamespaceError(name, "double used")
  602. new_namespace = Namespace(self.db, name, support_regions)
  603. self.namespaces[name] = new_namespace
  604. return new_namespace
  605. def iterate_namespace_names(self):
  606. for name in self.namespaces.keys():
  607. yield name
  608. def get_namespace(self, name):
  609. if name in self.namespaces.keys():
  610. return self.namespaces[name]
  611. else:
  612. return None
  613. def create_file_data(self, path, checksum, content):
  614. if self.db == None:
  615. return None
  616. (new_id, is_updated) = self.db.create_file(path, checksum)
  617. result = FileData(self, path, new_id, checksum, content)
  618. self.last_file_data = result
  619. return (result, is_updated)
  620. def load_file_data(self, path):
  621. if self.db == None:
  622. return None
  623. if self.last_file_data != None and self.last_file_data.get_path() == path:
  624. return self.last_file_data
  625. data = self.db.get_file(path)
  626. if data == None:
  627. return None
  628. result = FileData(self, data.path, data.id, data.checksum, None)
  629. self.last_file_data = result
  630. return result
  631. def save_file_data(self, file_data):
  632. if self.db == None:
  633. return None
  634. class DataIterator(object):
  635. def iterate_packed_values(self, data, namespace, support_regions = False):
  636. for each in data.iterate_fields(namespace):
  637. space = self.loader.get_namespace(namespace)
  638. if space == None:
  639. raise DataNotPackable(namespace, each[0], each[1], None, "The namespace has not been found")
  640. packager = space.get_field_packager(each[0])
  641. if packager == None:
  642. raise DataNotPackable(namespace, each[0], each[1], None, "The field has not been found")
  643. if space.support_regions != support_regions:
  644. raise DataNotPackable(namespace, each[0], each[1], packager, "Incompatible support for regions")
  645. try:
  646. packed_data = packager.pack(each[1])
  647. if packed_data == None:
  648. continue
  649. except PackagerError:
  650. raise DataNotPackable(namespace, each[0], each[1], packager, "Packager raised exception")
  651. yield (each[0], packed_data)
  652. def __init__(self, loader, data, namespace, support_regions = False):
  653. self.loader = loader
  654. self.iterator = self.iterate_packed_values(data, namespace, support_regions)
  655. def __iter__(self):
  656. return self.iterator
  657. for namespace in file_data.iterate_namespaces():
  658. if file_data.is_namespace_updated(namespace) == False:
  659. continue
  660. self.db.add_row(namespace,
  661. file_data.get_id(),
  662. None,
  663. DataIterator(self, file_data, namespace))
  664. if file_data.are_regions_loaded():
  665. for region in file_data.iterate_regions():
  666. for namespace in region.iterate_namespaces():
  667. if region.is_namespace_updated(namespace) == False:
  668. continue
  669. self.db.add_row(namespace,
  670. file_data.get_id(),
  671. region.get_id(),
  672. DataIterator(self, region, namespace, support_regions = True))
  673. def iterate_file_data(self, path = None, path_like_filter = "%"):
  674. if self.db == None:
  675. return None
  676. final_path_like = path_like_filter
  677. if path != None:
  678. if self.db.check_dir(path) == False and self.db.check_file(path) == False:
  679. return None
  680. final_path_like = path + path_like_filter
  681. class FileDataIterator(object):
  682. def iterate_file_data(self, loader, final_path_like):
  683. for data in loader.db.iterate_files(path_like=final_path_like):
  684. yield FileData(loader, data.path, data.id, data.checksum, None)
  685. def __init__(self, loader, final_path_like):
  686. self.iterator = self.iterate_file_data(loader, final_path_like)
  687. def __iter__(self):
  688. return self.iterator
  689. if self.db == None:
  690. return None
  691. return FileDataIterator(self, final_path_like)
  692. def load_aggregated_data(self, path = None, path_like_filter = "%", namespaces = None):
  693. if self.db == None:
  694. return None
  695. final_path_like = path_like_filter
  696. if path != None:
  697. if self.db.check_dir(path) == False and self.db.check_file(path) == False:
  698. return None
  699. final_path_like = path + path_like_filter
  700. if namespaces == None:
  701. namespaces = self.namespaces.keys()
  702. result = AggregatedData(self, path)
  703. for name in namespaces:
  704. namespace = self.get_namespace(name)
  705. data = self.db.aggregate_rows(name, path_like = final_path_like)
  706. for field in data.keys():
  707. if namespace.get_field_packager(field).is_non_zero() == True:
  708. data[field]['min'] = None
  709. data[field]['avg'] = None
  710. result.set_data(name, field, data[field])
  711. return result
  712. def load_selected_data(self, namespace, fields = None, path = None, path_like_filter = "%", filters = []):
  713. if self.db == None:
  714. return None
  715. # TODO implement restriction for non_zero fields
  716. final_path_like = path_like_filter
  717. if path != None:
  718. if self.db.check_dir(path) == False and self.db.check_file(path) == False:
  719. return None
  720. final_path_like = path + path_like_filter
  721. namespace_obj = self.get_namespace(namespace)
  722. if namespace_obj == None:
  723. return None
  724. class SelectDataIterator(object):
  725. def iterate_selected_values(self, loader, namespace_obj, final_path_like, fields, filters):
  726. for row in loader.db.select_rows(namespace_obj.get_name(), path_like=final_path_like, filters=filters):
  727. region_id = None
  728. if namespace_obj.are_regions_supported() == True:
  729. region_id = row['region_id']
  730. data = SelectData(loader, row['path'], row['id'], region_id)
  731. field_names = fields
  732. if fields == None:
  733. field_names = namespace_obj.iterate_field_names()
  734. for field in field_names:
  735. data.set_data(namespace, field, row[field])
  736. yield data
  737. def __init__(self, loader, namespace_obj, final_path_like, fields, filters):
  738. self.iterator = self.iterate_selected_values(loader, namespace_obj, final_path_like, fields, filters)
  739. def __iter__(self):
  740. return self.iterator
  741. return SelectDataIterator(self, namespace_obj, final_path_like, fields, filters)