tgis_base.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  1. """!@package grass.script.tgis_base
  2. @brief GRASS Python scripting module (temporal GIS functions)
  3. Temporal GIS base classes to be used in other
  4. Python temporal gis packages.
  5. This packages includes all base classes to stor basic information like id, name,
  6. mapset creation and modification time as well as sql serialization and deserialization
  7. and the sqlite3 database interface.
  8. Usage:
  9. @code
  10. from grass.script import tgis_core as grass
  11. rbase = grass.raster_base(ident="soil")
  12. ...
  13. @endcode
  14. (C) 2008-2011 by the GRASS Development Team
  15. This program is free software under the GNU General Public
  16. License (>=v2). Read the file COPYING that comes with GRASS
  17. for details.
  18. @author Soeren Gebbert
  19. """
  20. from tgis_core import *
  21. ###############################################################################
  22. class dict_sql_serializer(object):
  23. def __init__(self):
  24. self.D = {}
  25. def serialize(self, type, table, where=None):
  26. """Convert the internal dictionary into a string of semicolon separated SQL statements
  27. The keys are the colum names and the values are the row entries
  28. @type must be SELECT. INSERT, UPDATE
  29. @table The name of the table to select, insert or update
  30. @where The optinal where statment
  31. @return the sql string
  32. """
  33. sql = ""
  34. args = []
  35. # Create ordered select statement
  36. if type == "SELECT":
  37. sql += 'SELECT '
  38. count = 0
  39. for key in self.D.keys():
  40. if count == 0:
  41. sql += ' %s ' % key
  42. else:
  43. sql += ' , %s ' % key
  44. count += 1
  45. sql += ' FROM ' + table + ' '
  46. if where:
  47. sql += where
  48. # Create insert statement
  49. if type =="INSERT":
  50. count = 0
  51. sql += 'INSERT INTO ' + table + ' ('
  52. for key in self.D.keys():
  53. if count == 0:
  54. sql += ' %s ' % key
  55. else:
  56. sql += ' ,%s ' % key
  57. count += 1
  58. count = 0
  59. sql += ') VALUES ('
  60. for key in self.D.keys():
  61. if count == 0:
  62. sql += '?'
  63. else:
  64. sql += ',?'
  65. count += 1
  66. args.append(self.D[key])
  67. sql += ') '
  68. if where:
  69. sql += where
  70. # Create update statement
  71. if type =="UPDATE":
  72. count = 0
  73. sql += 'UPDATE ' + table + ' SET '
  74. for key in self.D.keys():
  75. # Update only entries which are not None
  76. if self.D[key] != None:
  77. if count == 0:
  78. sql += ' %s = ? ' % key
  79. else:
  80. sql += ' ,%s = ? ' % key
  81. count += 1
  82. args.append(self.D[key])
  83. if where:
  84. sql += where
  85. return sql, tuple(args)
  86. def deserialize(self, row):
  87. """Convert the content of the sqlite row into the internal dictionary"""
  88. self.D = {}
  89. for key in row.keys():
  90. self.D[key] = row[key]
  91. def clear(self):
  92. """Remove all the content of this class"""
  93. self.D = {}
  94. def print_self(self):
  95. print self.D
  96. def test(self):
  97. t = dict_sql_serializer()
  98. t.D["id"] = "soil@PERMANENT"
  99. t.D["name"] = "soil"
  100. t.D["mapset"] = "PERMANENT"
  101. t.D["creator"] = "soeren"
  102. t.D["creation_time"] = datetime.now()
  103. t.D["modification_time"] = datetime.now()
  104. t.D["revision"] = 1
  105. sql, values = t.serialize(type="SELECT", table="raster_base")
  106. print sql, '\n', values
  107. sql, values = t.serialize(type="INSERT", table="raster_base")
  108. print sql, '\n', values
  109. sql, values = t.serialize(type="UPDATE", table="raster_base")
  110. print sql, '\n', values
  111. ###############################################################################
  112. class sql_database_interface(dict_sql_serializer):
  113. """This is the sql database interface to sqlite3"""
  114. def __init__(self, table=None, ident=None, database=None):
  115. dict_sql_serializer.__init__(self)
  116. self.table = table # Name of the table, set in the subclass
  117. if database == None:
  118. self.database = get_grass_location_db_path()
  119. else:
  120. self.database = database
  121. self.ident = ident
  122. def get_table_name(self):
  123. return self.table
  124. def connect(self):
  125. self.connection = sqlite3.connect(self.database, detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES)
  126. self.connection.row_factory = sqlite3.Row
  127. self.cursor = self.connection.cursor()
  128. def close(self):
  129. self.connection.commit()
  130. self.cursor.close()
  131. def get_delete_statement(self):
  132. return "DELETE FROM " + self.get_table_name() + " WHERE id = \"" + str(self.ident) + "\""
  133. def delete(self):
  134. self.connect()
  135. sql = self.get_delete_statement()
  136. #print sql
  137. self.cursor.execute(sql)
  138. self.close()
  139. def get_is_in_db_statement(self):
  140. return "SELECT id FROM " + self.get_table_name() + " WHERE id = \"" + str(self.ident) + "\""
  141. def is_in_db(self):
  142. self.connect()
  143. sql = self.get_is_in_db_statement()
  144. #print sql
  145. self.cursor.execute(sql)
  146. row = self.cursor.fetchone()
  147. self.close()
  148. # Nothing found
  149. if row == None:
  150. return False
  151. return True
  152. def get_select_statement(self):
  153. return self.serialize("SELECT", self.get_table_name(), "WHERE id = \"" + str(self.ident) + "\"")
  154. def select(self):
  155. self.connect()
  156. sql, args = self.get_select_statement()
  157. #print sql
  158. #print args
  159. if len(args) == 0:
  160. self.cursor.execute(sql)
  161. else:
  162. self.cursor.execute(sql, args)
  163. row = self.cursor.fetchone()
  164. # Nothing found
  165. if row == None:
  166. return False
  167. if len(row) > 0:
  168. self.deserialize(row)
  169. else:
  170. raise IOError
  171. self.close()
  172. return True
  173. def get_insert_statement(self):
  174. return self.serialize("INSERT", self.get_table_name())
  175. def insert(self):
  176. self.connect()
  177. sql, args = self.get_insert_statement()
  178. #print sql
  179. #print args
  180. self.cursor.execute(sql, args)
  181. self.close()
  182. def get_update_statement(self):
  183. return self.serialize("UPDATE", self.get_table_name(), "WHERE id = \"" + str(self.ident) + "\"")
  184. def update(self):
  185. if self.ident == None:
  186. raise IOError("Missing identifer");
  187. sql, args = self.get_update_statement()
  188. #print sql
  189. #print args
  190. self.connect()
  191. self.cursor.execute(sql, args)
  192. self.close()
  193. ###############################################################################
  194. class dataset_base(sql_database_interface):
  195. """This is the base class for all maps and spacetime datasets storing basic information"""
  196. def __init__(self, table=None, ident=None, name=None, mapset=None, creator=None, ctime=None,\
  197. mtime=None, ttype=None, revision=1):
  198. sql_database_interface.__init__(self, table, ident)
  199. self.set_id(ident)
  200. self.set_name(name)
  201. self.set_mapset(mapset)
  202. self.set_creator(creator)
  203. self.set_ctime(ctime)
  204. self.set_mtime(mtime)
  205. self.set_ttype(ttype)
  206. self.set_revision(revision)
  207. def set_id(self, ident):
  208. """Convenient method to set the unique identifier (primary key)"""
  209. self.ident = ident
  210. self.D["id"] = ident
  211. def set_name(self, name):
  212. """Set the name of the map"""
  213. self.D["name"] = name
  214. def set_mapset(self, mapset):
  215. """Set the mapset of the map"""
  216. self.D["mapset"] = mapset
  217. def set_creator(self, creator):
  218. """Set the creator of the map"""
  219. self.D["creator"] = creator
  220. def set_ctime(self, ctime=None):
  221. """Set the creation time of the map, if nothing set the current time is used"""
  222. if ctime == None:
  223. self.D["creation_time"] = datetime.now()
  224. else:
  225. self.D["creation_time"] = ctime
  226. def set_mtime(self, mtime=None):
  227. """Set the modification time of the map, if nothing set the current time is used"""
  228. if mtime == None:
  229. self.D["modification_time"] = datetime.now()
  230. else:
  231. self.D["modification_time"] = mtime
  232. def set_ttype(self, ttype):
  233. """Set the temporal type of the map: absolute or relative, if nothing set absolute time will assumed"""
  234. if ttype == None or (ttype != "absolute" and ttype != "relative"):
  235. self.D["temporal_type"] = "absolute"
  236. else:
  237. self.D["temporal_type"] = ttype
  238. def set_revision(self, revision=1):
  239. """Set the revision of the map: if nothing set revision 1 will assumed"""
  240. self.D["revision"] = revision
  241. def get_id(self):
  242. """Convenient method to get the unique identifier (primary key)
  243. @return None if not found
  244. """
  245. if self.D.has_key("id"):
  246. return self.D["id"]
  247. else:
  248. return None
  249. def get_name(self):
  250. """Get the name of the map
  251. @return None if not found"""
  252. if self.D.has_key("name"):
  253. return self.D["name"]
  254. else:
  255. return None
  256. def get_mapset(self):
  257. """Get the mapset of the map
  258. @return None if not found"""
  259. if self.D.has_key("mapset"):
  260. return self.D["mapset"]
  261. else:
  262. return None
  263. def get_creator(self):
  264. """Get the creator of the map
  265. @return None if not found"""
  266. if self.D.has_key("creator"):
  267. return self.D["creator"]
  268. else:
  269. return None
  270. def get_ctime(self):
  271. """Get the creation time of the map, datatype is datetime
  272. @return None if not found"""
  273. if self.D.has_key("creation_time"):
  274. return self.D["creation_time"]
  275. else:
  276. return None
  277. def get_mtime(self):
  278. """Get the modification time of the map, datatype is datetime
  279. @return None if not found"""
  280. if self.D.has_key("modification_time"):
  281. return self.D["modification_time"]
  282. else:
  283. return None
  284. def get_ttype(self):
  285. """Get the temporal type of the map
  286. @return None if not found"""
  287. if self.D.has_key("temporal_type"):
  288. return self.D["temporal_type"]
  289. else:
  290. return None
  291. def get_revision(self):
  292. """Get the revision of the map
  293. @return None if not found"""
  294. if self.D.has_key("revision"):
  295. return self.D["revision"]
  296. else:
  297. return None
  298. def print_info(self):
  299. """Print information about this class in human readable style"""
  300. # 0123456789012345678901234567890
  301. print " Id: ........................ " + str(self.get_id())
  302. print " Name: ...................... " + str(self.get_name())
  303. print " Mapset: .................... " + str(self.get_mapset())
  304. print " Creator: ................... " + str(self.get_creator())
  305. print " Creation time: ............. " + str(self.get_ctime())
  306. print " Modification time: ......... " + str(self.get_mtime())
  307. print " Temporal type: ............. " + str(self.get_ttype())
  308. print " Revision in database: ...... " + str(self.get_revision())
  309. def print_shell_info(self):
  310. """Print information about this class in shell style"""
  311. print "id=" + str(self.get_id())
  312. print "name=" + str(self.get_name())
  313. print "mapset=" + str(self.get_mapset())
  314. print "creator=" + str(self.get_creator())
  315. print "creation_time=" + str(self.get_ctime())
  316. print "modification_time=" + str(self.get_mtime())
  317. print "temporal_type=" + str(self.get_ttype())
  318. print "revision=" + str(self.get_revision())
  319. ###############################################################################
  320. class raster_base(dataset_base):
  321. def __init__(self, ident=None, name=None, mapset=None, creator=None, creation_time=None,\
  322. modification_time=None, temporal_type=None, revision=1):
  323. dataset_base.__init__(self, "raster_base", ident, name, mapset, creator, creation_time,\
  324. modification_time, temporal_type, revision)
  325. class raster3d_base(dataset_base):
  326. def __init__(self, ident=None, name=None, mapset=None, creator=None, creation_time=None,\
  327. modification_time=None, temporal_type=None, revision=1):
  328. dataset_base.__init__(self, "raster3d_base", ident, name, mapset, creator, creation_time,\
  329. modification_time, temporal_type, revision)
  330. class vector_base(dataset_base):
  331. def __init__(self, ident=None, name=None, mapset=None, creator=None, creation_time=None,\
  332. modification_time=None, temporal_type=None, revision=1):
  333. dataset_base.__init__(self, "vector_base", ident, name, mapset, creator, creation_time,\
  334. modification_time, temporal_type, revision)
  335. ###############################################################################
  336. class stds_base(dataset_base):
  337. def __init__(self, table=None, ident=None, name=None, mapset=None, semantic_type=None, creator=None, creation_time=None,\
  338. modification_time=None, temporal_type=None, revision=1):
  339. dataset_base.__init__(self, table, ident, name, mapset, creator, creation_time,\
  340. modification_time, temporal_type, revision)
  341. self.set_semantic_type(semantic_type)
  342. def set_semantic_type(self, semantic_type):
  343. """Set the semantic type of the space time dataset"""
  344. self.D["semantic_type"] = semantic_type
  345. def get_semantic_type(self):
  346. """Get the semantic type of the space time dataset
  347. @return None if not found"""
  348. if self.D.has_key("semantic_type"):
  349. return self.D["semantic_type"]
  350. else:
  351. return None
  352. ###############################################################################
  353. class strds_base(stds_base):
  354. def __init__(self, ident=None, name=None, mapset=None, semantic_type=None, creator=None, creation_time=None,\
  355. modification_time=None, temporal_type=None, revision=1):
  356. stds_base.__init__(self, "strds_base", ident, name, mapset, semantic_type, creator, creation_time,\
  357. modification_time, temporal_type, revision)
  358. class str3ds_base(stds_base):
  359. def __init__(self, ident=None, name=None, mapset=None, semantic_type=None, creator=None, creation_time=None,\
  360. modification_time=None, temporal_type=None, revision=1):
  361. stds_base.__init__(self, "str3ds_base", ident, name, mapset, semantic_type, creator, creation_time,\
  362. modification_time, temporal_type, revision)
  363. class stvds_base(stds_base):
  364. def __init__(self, ident=None, name=None, mapset=None, semantic_type=None, creator=None, creation_time=None,\
  365. modification_time=None, temporal_type=None, revision=1):
  366. stds_base.__init__(self, "stvds_base", ident, name, mapset, semantic_type, creator, creation_time,\
  367. modification_time, temporal_type, revision)