core.py 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245
  1. """package grass.temporal
  2. GRASS Python scripting module (temporal GIS functions)
  3. Temporal GIS core functions to be used in library modules and scripts.
  4. This module provides the functionality to create the temporal
  5. SQL database and to establish a connection to the database.
  6. Usage:
  7. >>> import grass.temporal as tgis
  8. >>> # Create the temporal database
  9. >>> tgis.init()
  10. >>> # Establish a database connection
  11. >>> dbif, connected = tgis.init_dbif(None)
  12. >>> dbif.connect()
  13. >>> # Execute a SQL statement
  14. >>> dbif.execute_transaction("SELECT datetime(0, 'unixepoch', 'localtime');")
  15. >>> # Mogrify an SQL statement
  16. >>> dbif.mogrify_sql_statement(["SELECT name from raster_base where name = ?",
  17. ... ("precipitation",)])
  18. "SELECT name from raster_base where name = 'precipitation'"
  19. >>> dbif.close()
  20. (C) 2011-2014 by the GRASS Development Team
  21. This program is free software under the GNU General Public
  22. License (>=v2). Read the file COPYING that comes with GRASS
  23. for details.
  24. :author: Soeren Gebbert
  25. """
  26. import sys, traceback
  27. import os
  28. import locale
  29. # i18N
  30. import gettext
  31. gettext.install('grasslibs', os.path.join(os.getenv("GISBASE"), 'locale'))
  32. import grass.script as gscript
  33. from datetime import datetime
  34. from c_libraries_interface import *
  35. # Import all supported database backends
  36. # Ignore import errors since they are checked later
  37. try:
  38. import sqlite3
  39. except ImportError:
  40. pass
  41. # Postgresql is optional, existence is checked when needed
  42. try:
  43. import psycopg2
  44. import psycopg2.extras
  45. except:
  46. pass
  47. import atexit
  48. ###############################################################################
  49. # Profiling function provided by the temporal framework
  50. def profile_function(func):
  51. do_profiling = os.getenv("GRASS_TGIS_PROFILE")
  52. if do_profiling is "True" or do_profiling is "1":
  53. import cProfile, pstats, StringIO
  54. pr = cProfile.Profile()
  55. pr.enable()
  56. func()
  57. pr.disable()
  58. s = StringIO.StringIO()
  59. sortby = 'cumulative'
  60. ps = pstats.Stats(pr, stream=s).sort_stats(sortby)
  61. ps.print_stats()
  62. print s.getvalue()
  63. else:
  64. func()
  65. # Global variable that defines the backend
  66. # of the temporal GIS
  67. # It can either be "sqlite" or "pg"
  68. tgis_backend = None
  69. def get_tgis_backend():
  70. """Return the temporal GIS backend as string
  71. :returns: either "sqlite" or "pg"
  72. """
  73. global tgis_backend
  74. return tgis_backend
  75. # Global variable that defines the database string
  76. # of the temporal GIS
  77. tgis_database = None
  78. def get_tgis_database():
  79. """Return the temporal database string specified with t.connect
  80. """
  81. global tgis_database
  82. return tgis_database
  83. # The version of the temporal framework
  84. # this value must be an integer larger than 0
  85. # Increase this value in case of backward incompatible changes in the TGIS API
  86. tgis_version=2
  87. # The version of the temporal database since framework and database version can differ
  88. # this value must be an integer larger than 0
  89. # Increase this value in case of backward incompatible changes
  90. # temporal database SQL layout
  91. tgis_db_version=2
  92. # We need to know the parameter style of the database backend
  93. tgis_dbmi_paramstyle = None
  94. def get_tgis_dbmi_paramstyle():
  95. """Return the temporal database backend parameter style
  96. :returns: "qmark" or ""
  97. """
  98. global tgis_dbmi_paramstyle
  99. return tgis_dbmi_paramstyle
  100. # We need to access the current mapset quite often in the framework, so we make
  101. # a global variable that will be initiated when init() is called
  102. current_mapset = None
  103. current_location = None
  104. current_gisdbase = None
  105. ###############################################################################
  106. def get_current_mapset():
  107. """Return the current mapset
  108. This is the fastest way to receive the current mapset.
  109. The current mapset is set by init() and stored in a global variable.
  110. This function provides access to this global variable.
  111. """
  112. global current_mapset
  113. return current_mapset
  114. ###############################################################################
  115. def get_current_location():
  116. """Return the current location
  117. This is the fastest way to receive the current location.
  118. The current location is set by init() and stored in a global variable.
  119. This function provides access to this global variable.
  120. """
  121. global current_location
  122. return current_location
  123. ###############################################################################
  124. def get_current_gisdbase():
  125. """Return the current gis database (gisdbase)
  126. This is the fastest way to receive the current gisdbase.
  127. The current gisdbase is set by init() and stored in a global variable.
  128. This function provides access to this global variable.
  129. """
  130. global current_gisdbase
  131. return current_gisdbase
  132. ###############################################################################
  133. # If this global variable is set True, then maps can only be registered in space time datasets
  134. # with the same mapset. In addition, only maps in the current mapset can be inserted, updated or deleted from
  135. # the temporal database.
  136. # Overwrite this global variable by: g.gisenv set="TGIS_DISABLE_MAPSET_CHECK=True"
  137. # ATTENTION: Be aware to face corrupted temporal database in case this global variable is set to False.
  138. # This feature is highly experimental and violates the grass permission guidance.
  139. enable_mapset_check = True
  140. # If this global variable is set True, the timestamps of maps will be written as textfiles
  141. # for each map that will be inserted or updated in the temporal database using the C-library
  142. # timestamp interface.
  143. # Overwrite this global variable by: g.gisenv set="TGIS_DISABLE_TIMESTAMP_WRITE=True"
  144. # ATTENTION: Be aware to face corrupted temporal database in case this global variable is set to False.
  145. # This feature is highly experimental and violates the grass permission guidance.
  146. enable_timestamp_write = True
  147. def get_enable_mapset_check():
  148. """Return True if the mapsets should be checked while insert, update, delete requests
  149. and space time dataset registration.
  150. If this global variable is set True, then maps can only be registered in space time datasets
  151. with the same mapset. In addition, only maps in the current mapset can be inserted, updated or deleted from
  152. the temporal database.
  153. Overwrite this global variable by: g.gisenv set="TGIS_DISABLE_MAPSET_CHECK=True"
  154. ATTENTION: Be aware to face corrupted temporal database in case this global variable is set to False.
  155. This feature is highly experimental and violates the grass permission guidance.
  156. """
  157. global enable_mapset_check
  158. return enable_mapset_check
  159. def get_enable_timestamp_write():
  160. """Return True if the map timestamps should be written to the spatial database metadata as well.
  161. If this global variable is set True, the timestamps of maps will be written as textfiles
  162. for each map that will be inserted or updated in the temporal database using the C-library
  163. timestamp interface.
  164. Overwrite this global variable by: g.gisenv set="TGIS_DISABLE_TIMESTAMP_WRITE=True"
  165. ATTENTION: Be aware that C-libraries can not access timestamp informations if they are not
  166. written as spatial database metadata, hence modules that make use of timestamps
  167. using the C-library interface will not work with maps that were created without
  168. writing the timestamps.
  169. """
  170. global enable_timestamp_write
  171. return enable_timestamp_write
  172. ###############################################################################
  173. # The global variable that stores the PyGRASS Messenger object that
  174. # provides a fast and exit safe interface to the C-library message functions
  175. message_interface=None
  176. def _init_tgis_message_interface(raise_on_error=False):
  177. """Initiate the global mesage interface
  178. :param raise_on_error: If True raise a FatalError exception in case of a fatal error,
  179. call sys.exit(1) otherwise
  180. """
  181. global message_interface
  182. from grass.pygrass import messages
  183. message_interface = messages.get_msgr(raise_on_error=raise_on_error)
  184. def get_tgis_message_interface():
  185. """Return the temporal GIS message interface which is of type
  186. grass.pyhrass.message.Messenger()
  187. Use this message interface to print messages to stdout using the
  188. GRASS C-library messaging system.
  189. """
  190. global message_interface
  191. return message_interface
  192. ###############################################################################
  193. # The global variable that stores the C-library interface object that
  194. # provides a fast and exit safe interface to the C-library libgis,
  195. # libraster, libraster3d and libvector functions
  196. c_library_interface=None
  197. def _init_tgis_c_library_interface():
  198. """Set the global C-library interface variable that
  199. provides a fast and exit safe interface to the C-library libgis,
  200. libraster, libraster3d and libvector functions
  201. """
  202. global c_library_interface
  203. c_library_interface = CLibrariesInterface()
  204. def get_tgis_c_library_interface():
  205. """Return the C-library interface that
  206. provides a fast and exit safe interface to the C-library libgis,
  207. libraster, libraster3d and libvector functions
  208. """
  209. global c_library_interface
  210. return c_library_interface
  211. ###############################################################################
  212. # Set this variable True to raise a FatalError exception
  213. # in case a fatal error occurs using the messenger interface
  214. raise_on_error = False
  215. def set_raise_on_error(raise_exp=True):
  216. """Define behavior on fatal error, invoked using the tgis messenger
  217. interface (msgr.fatal())
  218. The messenger interface will be restarted using the new error policy
  219. :param raise_exp: True to raise a FatalError exception instead of calling
  220. sys.exit(1) when using the tgis messenger interface
  221. >>> import grass.temporal as tgis
  222. >>> tgis.init()
  223. >>> ignore = tgis.set_raise_on_error(False)
  224. >>> msgr = tgis.get_tgis_message_interface()
  225. >>> tgis.get_raise_on_error()
  226. False
  227. >>> msgr.fatal("Ohh no no no!")
  228. Traceback (most recent call last):
  229. File "__init__.py", line 239, in fatal
  230. sys.exit(1)
  231. SystemExit: 1
  232. >>> tgis.set_raise_on_error(True)
  233. False
  234. >>> msgr.fatal("Ohh no no no!")
  235. Traceback (most recent call last):
  236. File "__init__.py", line 241, in fatal
  237. raise FatalError(message)
  238. FatalError: Ohh no no no!
  239. :returns: current status
  240. """
  241. global raise_on_error
  242. tmp_raise = raise_on_error
  243. raise_on_error = raise_exp
  244. global message_interface
  245. if message_interface:
  246. message_interface.set_raise_on_error(raise_on_error)
  247. else:
  248. _init_tgis_message_interface(raise_on_error)
  249. return tmp_raise
  250. def get_raise_on_error():
  251. """Return True if a FatalError exception is raised instead of calling
  252. sys.exit(1) in case a fatal error was invoked with msgr.fatal()
  253. """
  254. global raise_on_error
  255. return raise_on_error
  256. ###############################################################################
  257. def get_tgis_version():
  258. """Get the version number of the temporal framework
  259. :returns: The version number of the temporal framework as string
  260. """
  261. global tgis_version
  262. return tgis_version
  263. ###############################################################################
  264. def get_tgis_db_version():
  265. """Get the version number of the temporal framework
  266. :returns: The version number of the temporal framework as string
  267. """
  268. global tgis_db_version
  269. return tgis_db_version
  270. ###############################################################################
  271. def get_tgis_metadata(dbif=None):
  272. """Return the tgis metadata table as a list of rows (dicts)
  273. or None if not present
  274. :param dbif: The database interface to be used
  275. :returns: The selected rows with key/value columns or None
  276. """
  277. dbif, connected = init_dbif(dbif)
  278. # Select metadata if the table is present
  279. try:
  280. statement = "SELECT * FROM tgis_metadata;\n"
  281. dbif.execute(statement)
  282. rows = dbif.fetchall()
  283. except:
  284. rows = None
  285. if connected:
  286. dbif.close()
  287. return rows
  288. ###############################################################################
  289. # The temporal database string set with t.connect
  290. # with substituted GRASS variables gisdbase, location and mapset
  291. tgis_database_string = None
  292. def get_tgis_database_string():
  293. """Return the preprocessed temporal database string
  294. This string is the temporal database string set with t.connect
  295. that was processed to substitue location, gisdbase and mapset
  296. varibales.
  297. """
  298. global tgis_database_string
  299. return tgis_database_string
  300. ###############################################################################
  301. def get_sql_template_path():
  302. base = os.getenv("GISBASE")
  303. base_etc = os.path.join(base, "etc")
  304. return os.path.join(base_etc, "sql")
  305. ###############################################################################
  306. def stop_subprocesses():
  307. """Stop the messenger and C-interface subprocesses
  308. that are started by tgis.init()
  309. """
  310. global message_interface
  311. global c_library_interface
  312. if message_interface:
  313. message_interface.stop()
  314. if c_library_interface:
  315. c_library_interface.stop()
  316. # We register this function to be called at exit
  317. atexit.register(stop_subprocesses)
  318. def get_available_temporal_mapsets():
  319. """Return a list of of mapset names with temporal database driver and names
  320. that are accessable from the current mapset.
  321. :returns: A dictionary, mapset names are keys, the tuple (driver, database) are the values
  322. """
  323. global c_library_interface
  324. mapsets = c_library_interface.available_mapsets()
  325. tgis_mapsets = {}
  326. for mapset in mapsets:
  327. driver = c_library_interface.get_driver_name(mapset)
  328. database = c_library_interface.get_database_name(mapset)
  329. if driver and database:
  330. tgis_mapsets[mapset] = (driver, database)
  331. return tgis_mapsets
  332. ###############################################################################
  333. def init(raise_fatal_error=False):
  334. """This function set the correct database backend from GRASS environmental variables
  335. and creates the grass temporal database structure for raster,
  336. vector and raster3d maps as well as for the space-time datasets strds,
  337. str3ds and stvds in case it does not exists.
  338. Several global variables are initiated and the messenger and C-library interface
  339. subprocesses are spawned.
  340. Re-run this function in case the following GRASS variables change while the process runs:
  341. - MAPSET
  342. - LOCATION_NAME
  343. - GISDBASE
  344. - TGIS_DISABLE_MAPSET_CHECK
  345. - TGIS_DISABLE_TIMESTAMP_WRITE
  346. Re-run this function if the following t.connect variables change while the process runs:
  347. - temporal GIS driver (set by t.connect driver=)
  348. - temporal GIS database (set by t.connect database=)
  349. The following environmental variables are checked:
  350. - GRASS_TGIS_PROFILE (True, False, 1, 0)
  351. - GRASS_TGIS_RAISE_ON_ERROR (True, False, 1, 0)
  352. ATTENTION: This functions must be called before any spatio-temporal processing
  353. can be started
  354. :param raise_fatal_error: Set this True to assure that the init() function
  355. does not kill a persistent process like the GUI.
  356. If set True a grass.pygrass.messages.FatalError
  357. exception will be raised in case a fatal error occurs
  358. in the init process, otherwise sys.exit(1) will be called.
  359. """
  360. # We need to set the correct database backend and several global variables
  361. # from the GRASS mapset specific environment variables of g.gisenv and t.connect
  362. global tgis_backend
  363. global tgis_database
  364. global tgis_database_string
  365. global tgis_dbmi_paramstyle
  366. global raise_on_error
  367. global enable_mapset_check
  368. global enable_timestamp_write
  369. global current_mapset
  370. global current_location
  371. global current_gisdbase
  372. raise_on_error = raise_fatal_error
  373. # We must run t.connect at first to create the temporal database and to
  374. # get the environmental variables
  375. gscript.run_command("t.connect", flags="c")
  376. grassenv = gscript.gisenv()
  377. # Set the global variable for faster access
  378. current_mapset = grassenv["MAPSET"]
  379. current_location = grassenv["LOCATION_NAME"]
  380. current_gisdbase = grassenv["GISDBASE"]
  381. # Check environment variable GRASS_TGIS_RAISE_ON_ERROR
  382. if os.getenv("GRASS_TGIS_RAISE_ON_ERROR") == "True" or os.getenv("GRASS_TGIS_RAISE_ON_ERROR") == "1":
  383. raise_on_error = True
  384. # Check if the script library raises on error,
  385. # if so we do the same
  386. if gscript.get_raise_on_error() is True:
  387. raise_on_error = True
  388. # Start the GRASS message interface server
  389. _init_tgis_message_interface(raise_on_error)
  390. # Start the C-library interface server
  391. _init_tgis_c_library_interface()
  392. msgr = get_tgis_message_interface()
  393. msgr.debug(1, "Initiate the temporal database")
  394. ciface = get_tgis_c_library_interface()
  395. driver_string = ciface.get_driver_name()
  396. database_string = ciface.get_database_name()
  397. # Set the mapset check and the timestamp write
  398. if grassenv.has_key("TGIS_DISABLE_MAPSET_CHECK"):
  399. if grassenv["TGIS_DISABLE_MAPSET_CHECK"] == "True" or grassenv["TGIS_DISABLE_MAPSET_CHECK"] == "1":
  400. enable_mapset_check = False
  401. msgr.warning("TGIS_DISABLE_MAPSET_CHECK is True")
  402. if grassenv.has_key("TGIS_DISABLE_TIMESTAMP_WRITE"):
  403. if grassenv["TGIS_DISABLE_TIMESTAMP_WRITE"] == "True" or grassenv["TGIS_DISABLE_TIMESTAMP_WRITE"] == "1":
  404. enable_timestamp_write = False
  405. msgr.warning("TGIS_DISABLE_TIMESTAMP_WRITE is True")
  406. if driver_string is not None and driver_string is not "":
  407. if driver_string == "sqlite":
  408. tgis_backend = driver_string
  409. try:
  410. import sqlite3
  411. except ImportError:
  412. msgr.error("Unable to locate the sqlite SQL Python interface module sqlite3.")
  413. raise
  414. dbmi = sqlite3
  415. elif driver_string == "pg":
  416. tgis_backend = driver_string
  417. try:
  418. import psycopg2
  419. except ImportError:
  420. msgr.error("Unable to locate the Postgresql SQL Python interface module psycopg2.")
  421. raise
  422. dbmi = psycopg2
  423. else:
  424. msgr.fatal(_("Unable to initialize the temporal DBMI interface. Please use "
  425. "t.connect to specify the driver and the database string"))
  426. else:
  427. # Set the default sqlite3 connection in case nothing was defined
  428. gscript.run_command("t.connect", flags="d")
  429. driver_string = ciface.get_driver_name()
  430. database_string = ciface.get_database_name()
  431. tgis_backend = driver_string
  432. dbmi = sqlite3
  433. tgis_database_string = database_string
  434. # Set the parameter style
  435. tgis_dbmi_paramstyle = dbmi.paramstyle
  436. # We do not know if the database already exists
  437. db_exists = False
  438. dbif = SQLDatabaseInterfaceConnection()
  439. # Check if the database already exists
  440. if tgis_backend == "sqlite":
  441. # Check path of the sqlite database
  442. if os.path.exists(tgis_database_string):
  443. dbif.connect()
  444. # Check for raster_base table
  445. dbif.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='raster_base';")
  446. name = dbif.fetchone()
  447. if name and name[0] == "raster_base":
  448. db_exists = True
  449. dbif.close()
  450. elif tgis_backend == "pg":
  451. # Connect to database
  452. dbif.connect()
  453. # Check for raster_base table
  454. dbif.execute("SELECT EXISTS(SELECT * FROM information_schema.tables "
  455. "WHERE table_name=%s)", ('raster_base',))
  456. if dbif.fetchone()[0]:
  457. db_exists = True
  458. backup_howto = "The format of your actual temporal database is not supported any more.\n"\
  459. "Solution: You need to export it by restoring the GRASS GIS version used for creating this DB. "\
  460. " From there, create a backup of your temporal database to avoid the loss of your temporal data.\n"\
  461. "Notes: Use t.rast.export and t.vect.export to make a backup of your existing space time datasets."\
  462. "To safe the timestamps of your existing maps and space time datasets, use t.rast.list, "\
  463. "t.vect.list and t.rast3d.list. "\
  464. "You can register the existing time stamped maps easily if you export columns=id,start_time,end_time "\
  465. "into text files and use t.register to register them again in new created space time datasets (t.create). "\
  466. "After the backup remove the existing temporal database, a new one will be created automatically.\n"
  467. if db_exists == True:
  468. # Check the version of the temporal database
  469. dbif.close()
  470. dbif.connect()
  471. metadata = get_tgis_metadata(dbif)
  472. dbif.close()
  473. if metadata is None:
  474. msgr.fatal(_("Unable to receive temporal database metadata.\n"
  475. "Current temporal database info:%(info)s")%({"info":get_database_info_string()}))
  476. for entry in metadata:
  477. if "tgis_version" in entry and entry[1] != str(get_tgis_version()):
  478. msgr.fatal(_("Unsupported temporal database: version mismatch.\n %(backup)s"
  479. "Supported temporal API version is: %(api)i.\n"
  480. "Please update your GRASS GIS installation.\n"
  481. "Current temporal database info:%(info)s")%({"backup":backup_howto, "api":get_tgis_version(),
  482. "info":get_database_info_string()}))
  483. if "tgis_db_version" in entry and entry[1] != str(get_tgis_db_version()):
  484. msgr.fatal(_("Unsupported temporal database: version mismatch.\n %(backup)s"
  485. "Supported temporal database version is: %(tdb)i\n"
  486. "Current temporal database info:%(info)s")%({"backup":backup_howto,"tdb":get_tgis_version(),
  487. "info":get_database_info_string()}))
  488. return
  489. create_temporal_database(dbif)
  490. ###############################################################################
  491. def get_database_info_string():
  492. dbif = SQLDatabaseInterfaceConnection()
  493. info = "\nDBMI interface:..... " + str(dbif.get_dbmi().__name__)
  494. info += "\nTemporal database:.. " + str( get_tgis_database_string())
  495. return info
  496. ###############################################################################
  497. def create_temporal_database(dbif):
  498. """This function will create the temporal database
  499. It will create all tables and triggers that are needed to run
  500. the temporal GIS
  501. :param dbif: The database interface to be used
  502. """
  503. global tgis_backend
  504. global tgis_version
  505. global tgis_db_version
  506. global tgis_database_string
  507. template_path = get_sql_template_path()
  508. msgr = get_tgis_message_interface()
  509. # Read all SQL scripts and templates
  510. map_tables_template_sql = open(os.path.join(
  511. template_path, "map_tables_template.sql"), 'r').read()
  512. raster_metadata_sql = open(os.path.join(
  513. get_sql_template_path(), "raster_metadata_table.sql"), 'r').read()
  514. raster3d_metadata_sql = open(os.path.join(template_path,
  515. "raster3d_metadata_table.sql"),
  516. 'r').read()
  517. vector_metadata_sql = open(os.path.join(template_path,
  518. "vector_metadata_table.sql"),
  519. 'r').read()
  520. raster_views_sql = open(os.path.join(template_path, "raster_views.sql"),
  521. 'r').read()
  522. raster3d_views_sql = open(os.path.join(template_path,
  523. "raster3d_views.sql"), 'r').read()
  524. vector_views_sql = open(os.path.join(template_path, "vector_views.sql"),
  525. 'r').read()
  526. stds_tables_template_sql = open(os.path.join(template_path,
  527. "stds_tables_template.sql"),
  528. 'r').read()
  529. strds_metadata_sql = open(os.path.join(template_path,
  530. "strds_metadata_table.sql"),
  531. 'r').read()
  532. str3ds_metadata_sql = open(os.path.join(template_path,
  533. "str3ds_metadata_table.sql"),
  534. 'r').read()
  535. stvds_metadata_sql = open(os.path.join(template_path,
  536. "stvds_metadata_table.sql"),
  537. 'r').read()
  538. strds_views_sql = open(os.path.join(template_path, "strds_views.sql"),
  539. 'r').read()
  540. str3ds_views_sql = open(os.path.join(template_path, "str3ds_views.sql"),
  541. 'r').read()
  542. stvds_views_sql = open(os.path.join(template_path, "stvds_views.sql"),
  543. 'r').read()
  544. # Create the raster, raster3d and vector tables SQL statements
  545. raster_tables_sql = map_tables_template_sql.replace("GRASS_MAP", "raster")
  546. vector_tables_sql = map_tables_template_sql.replace("GRASS_MAP", "vector")
  547. raster3d_tables_sql = map_tables_template_sql.replace(
  548. "GRASS_MAP", "raster3d")
  549. # Create the space-time raster, raster3d and vector dataset tables
  550. # SQL statements
  551. strds_tables_sql = stds_tables_template_sql.replace("STDS", "strds")
  552. stvds_tables_sql = stds_tables_template_sql.replace("STDS", "stvds")
  553. str3ds_tables_sql = stds_tables_template_sql.replace("STDS", "str3ds")
  554. msgr.message(_("Creating temporal database: %s" % (tgis_database_string)))
  555. if tgis_backend == "sqlite":
  556. # We need to create the sqlite3 database path if it does not exists
  557. tgis_dir = os.path.dirname(tgis_database_string)
  558. if not os.path.exists(tgis_dir):
  559. try:
  560. os.makedirs(tgis_dir)
  561. except Exception as e:
  562. msgr.fatal(_("Unable to create SQLite temporal database\n"
  563. "Exception: %s\nPlease use t.connect to set a "
  564. "read- and writable temporal database path"%(e)))
  565. # Set up the trigger that takes care of
  566. # the correct deletion of entries across the different tables
  567. delete_trigger_sql = open(os.path.join(template_path,
  568. "sqlite3_delete_trigger.sql"),
  569. 'r').read()
  570. indexes_sql = open(os.path.join(template_path, "sqlite3_indexes.sql"), 'r').read()
  571. else:
  572. # Set up the trigger that takes care of
  573. # the correct deletion of entries across the different tables
  574. delete_trigger_sql = open(os.path.join(template_path,
  575. "postgresql_delete_trigger.sql"),
  576. 'r').read()
  577. indexes_sql = open(os.path.join(template_path, "postgresql_indexes.sql"), 'r').read()
  578. # Connect now to the database
  579. if not dbif.connected:
  580. dbif.connect()
  581. # Execute the SQL statements for sqlite
  582. # Create the global tables for the native grass datatypes
  583. dbif.execute_transaction(raster_tables_sql)
  584. dbif.execute_transaction(raster_metadata_sql)
  585. dbif.execute_transaction(raster_views_sql)
  586. dbif.execute_transaction(vector_tables_sql)
  587. dbif.execute_transaction(vector_metadata_sql)
  588. dbif.execute_transaction(vector_views_sql)
  589. dbif.execute_transaction(raster3d_tables_sql)
  590. dbif.execute_transaction(raster3d_metadata_sql)
  591. dbif.execute_transaction(raster3d_views_sql)
  592. # Create the tables for the new space-time datatypes
  593. dbif.execute_transaction(strds_tables_sql)
  594. dbif.execute_transaction(strds_metadata_sql)
  595. dbif.execute_transaction(strds_views_sql)
  596. dbif.execute_transaction(stvds_tables_sql)
  597. dbif.execute_transaction(stvds_metadata_sql)
  598. dbif.execute_transaction(stvds_views_sql)
  599. dbif.execute_transaction(str3ds_tables_sql)
  600. dbif.execute_transaction(str3ds_metadata_sql)
  601. dbif.execute_transaction(str3ds_views_sql)
  602. # The delete trigger
  603. dbif.execute_transaction(delete_trigger_sql)
  604. # The indexes
  605. dbif.execute_transaction(indexes_sql)
  606. # Create the tgis metadata table to store the database
  607. # initial configuration
  608. # The metadata table content
  609. metadata = {}
  610. metadata["tgis_version"] = tgis_version
  611. metadata["tgis_db_version"] = tgis_db_version
  612. metadata["creation_time"] = datetime.today()
  613. _create_tgis_metadata_table(metadata, dbif)
  614. dbif.close()
  615. ###############################################################################
  616. def _create_tgis_metadata_table(content, dbif=None):
  617. """!Create the temporal gis metadata table which stores all metadata
  618. information about the temporal database.
  619. @param content The dictionary that stores the key:value metadata
  620. that should be stored in the metadata table
  621. @param dbif The database interface to be used
  622. """
  623. dbif, connected = init_dbif(dbif)
  624. statement = "CREATE TABLE tgis_metadata (key VARCHAR NOT NULL, value VARCHAR);\n";
  625. dbif.execute_transaction(statement)
  626. for key in content.keys():
  627. statement = "INSERT INTO tgis_metadata (key, value) VALUES " + \
  628. "(\'%s\' , \'%s\');\n"%(str(key), str(content[key]))
  629. dbif.execute_transaction(statement)
  630. if connected:
  631. dbif.close()
  632. ###############################################################################
  633. class SQLDatabaseInterfaceConnection(object):
  634. def __init__(self):
  635. self.tgis_mapsets = get_available_temporal_mapsets()
  636. self.current_mapset = get_current_mapset()
  637. self.connections = {}
  638. self.connected = False
  639. self.unique_connections = {}
  640. for mapset in self.tgis_mapsets.keys():
  641. driver, dbstring = self.tgis_mapsets[mapset]
  642. if dbstring not in self.unique_connections.keys():
  643. self.unique_connections[dbstring] = DBConnection(driver)
  644. self.connections[mapset] = self.unique_connections[dbstring]
  645. self.msgr = get_tgis_message_interface()
  646. def get_dbmi(self, mapset=None):
  647. if mapset is None:
  648. mapset = self.current_mapset
  649. return self.connections[mapset].dbmi
  650. def rollback(self, mapset=None):
  651. """
  652. Roll back the last transaction. This must be called
  653. in case a new query should be performed after a db error.
  654. This is only relevant for postgresql database.
  655. """
  656. if mapset is None:
  657. mapset = self.current_mapset
  658. def connect(self):
  659. """Connect to the DBMI to execute SQL statements
  660. Supported backends are sqlite3 and postgresql
  661. """
  662. for mapset in self.tgis_mapsets.keys():
  663. driver, dbstring = self.tgis_mapsets[mapset]
  664. conn = self.connections[mapset]
  665. if conn.is_connected() is False:
  666. conn .connect(dbstring)
  667. self.connected = True
  668. def is_connected(self):
  669. return self.connected
  670. def close(self):
  671. """Close the DBMI connection
  672. There may be several temporal databases in a location, hence
  673. close all temporal databases that have been opened.
  674. """
  675. for key in self.unique_connections.keys():
  676. self.unique_connections[key] .close()
  677. self.connected = False
  678. def mogrify_sql_statement(self, content, mapset=None):
  679. """Return the SQL statement and arguments as executable SQL string
  680. :param content: The content as tuple with two entries, the first
  681. entry is the SQL statement with DBMI specific
  682. place holder (?), the second entry is the argument
  683. list that should substitute the place holder.
  684. :param mapset: The mapset of the abstract dataset or temporal
  685. database location, if None the current mapset
  686. will be used
  687. """
  688. if mapset is None:
  689. mapset = self.current_mapset
  690. if mapset not in self.tgis_mapsets.keys():
  691. self.msgr.fatal(_("Unable to mogrify sql statement. There is no temporal database "
  692. "connection defined for mapset <%(mapset)s>" % {"mapset":mapset}))
  693. return self.connections[mapset].mogrify_sql_statement(content)
  694. def check_table(self, table_name, mapset=None):
  695. """Check if a table exists in the temporal database
  696. :param table_name: The name of the table to be checked for existence
  697. :param mapset: The mapset of the abstract dataset or temporal
  698. database location, if None the current mapset
  699. will be used
  700. :returns: True if the table exists, False otherwise
  701. TODO:
  702. There may be several temporal databases in a location, hence
  703. the mapset is used to query the correct temporal database.
  704. """
  705. if mapset is None:
  706. mapset = self.current_mapset
  707. if mapset not in self.tgis_mapsets.keys():
  708. self.msgr.fatal(_("Unable to check table. There is no temporal database "
  709. "connection defined for mapset <%(mapset)s>" % {"mapset":mapset}))
  710. return self.connections[mapset].check_table(table_name)
  711. def execute(self, statement, args=None, mapset=None):
  712. """""
  713. :param mapset: The mapset of the abstract dataset or temporal
  714. database location, if None the current mapset
  715. will be used
  716. """
  717. if mapset is None:
  718. mapset = self.current_mapset
  719. if mapset not in self.tgis_mapsets.keys():
  720. self.msgr.fatal(_("Unable to execute sql statement. There is no temporal database "
  721. "connection defined for mapset <%(mapset)s>" % {"mapset":mapset}))
  722. return self.connections[mapset].execute(statement, args)
  723. def fetchone(self, mapset=None):
  724. if mapset is None:
  725. mapset = self.current_mapset
  726. if mapset not in self.tgis_mapsets.keys():
  727. self.msgr.fatal(_("Unable to fetch one. There is no temporal database "
  728. "connection defined for mapset <%(mapset)s>" % {"mapset":mapset}))
  729. return self.connections[mapset].fetchone()
  730. def fetchall(self, mapset=None):
  731. if mapset is None:
  732. mapset = self.current_mapset
  733. if mapset not in self.tgis_mapsets.keys():
  734. self.msgr.fatal(_("Unable to fetch all. There is no temporal database "
  735. "connection defined for mapset <%(mapset)s>" % {"mapset":mapset}))
  736. return self.connections[mapset].fetchall()
  737. def execute_transaction(self, statement, mapset=None):
  738. """Execute a transactional SQL statement
  739. The BEGIN and END TRANSACTION statements will be added automatically
  740. to the sql statement
  741. :param statement: The executable SQL statement or SQL script
  742. """
  743. if mapset is None:
  744. mapset = self.current_mapset
  745. if mapset not in self.tgis_mapsets.keys():
  746. self.msgr.fatal(_("Unable to execute transaction. There is no temporal database "
  747. "connection defined for mapset <%(mapset)s>" % {"mapset":mapset}))
  748. return self.connections[mapset].execute_transaction(statement)
  749. ###############################################################################
  750. class DBConnection(object):
  751. """This class represents the database interface connection
  752. and provides access to the chisen backend modules.
  753. The following DBMS are supported:
  754. - sqlite via the sqlite3 standard library
  755. - postgresql via psycopg2
  756. """
  757. def __init__(self , backend=None):
  758. self.connected = False
  759. if backend is None:
  760. global tgis_backend
  761. if tgis_backend == "sqlite":
  762. self.dbmi = sqlite3
  763. else:
  764. self.dbmi = psycopg2
  765. else:
  766. if backend == "sqlite":
  767. self.dbmi = sqlite3
  768. else:
  769. self.dbmi = psycopg2
  770. self.msgr = get_tgis_message_interface()
  771. self.msgr.debug(1, "SQLDatabaseInterfaceConnection constructor")
  772. def __del__(self):
  773. if self.connected is True:
  774. self.close()
  775. def is_connected(self):
  776. return self.connected
  777. def rollback(self):
  778. """
  779. Roll back the last transaction. This must be called
  780. in case a new query should be performed after a db error.
  781. This is only relevant for postgresql database.
  782. """
  783. if self.dbmi.__name__ == "psycopg2":
  784. if self.connected:
  785. self.connection.rollback()
  786. def connect(self, dbstring=None):
  787. """Connect to the DBMI to execute SQL statements
  788. Supported backends are sqlite3 and postgresql
  789. """
  790. # Connection in the current mapset
  791. if dbstring is None:
  792. global tgis_database_string
  793. dbstring = tgis_database_string
  794. try:
  795. if self.dbmi.__name__ == "sqlite3":
  796. self.connection = self.dbmi.connect(dbstring,
  797. detect_types = self.dbmi.PARSE_DECLTYPES | self.dbmi.PARSE_COLNAMES)
  798. self.connection.row_factory = self.dbmi.Row
  799. self.connection.isolation_level = None
  800. self.cursor = self.connection.cursor()
  801. self.cursor.execute("PRAGMA synchronous = OFF")
  802. self.cursor.execute("PRAGMA journal_mode = MEMORY")
  803. elif self.dbmi.__name__ == "psycopg2":
  804. self.connection = self.dbmi.connect(dbstring)
  805. #self.connection.set_isolation_level(dbmi.extensions.ISOLATION_LEVEL_AUTOCOMMIT)
  806. self.cursor = self.connection.cursor(
  807. cursor_factory = self.dbmi.extras.DictCursor)
  808. self.connected = True
  809. except Exception as e:
  810. self.msgr.fatal(_("Unable to connect to %(db)s database: "
  811. "%(string)s\nException: \"%(ex)s\"\nPlease use t.connect to set a "
  812. "read- and writable temporal database backend")%({"db":self.dbmi.__name__,
  813. "string":tgis_database_string,
  814. "ex":e,}))
  815. def close(self):
  816. """Close the DBMI connection
  817. TODO:
  818. There may be several temporal databases in a location, hence
  819. close all temporal databases that have been opened. Use a dictionary
  820. to manage different connections.
  821. """
  822. self.connection.commit()
  823. self.cursor.close()
  824. self.connected = False
  825. def mogrify_sql_statement(self, content):
  826. """Return the SQL statement and arguments as executable SQL string
  827. TODO:
  828. Use the mapset argument to identify the correct database driver
  829. :param content: The content as tuple with two entries, the first
  830. entry is the SQL statement with DBMI specific
  831. place holder (?), the second entry is the argument
  832. list that should substitute the place holder.
  833. :param mapset: The mapset of the abstract dataset or temporal
  834. database location, if None the current mapset
  835. will be used
  836. Usage:
  837. >>> init()
  838. >>> dbif = SQLDatabaseInterfaceConnection()
  839. >>> dbif.mogrify_sql_statement(["SELECT ctime FROM raster_base WHERE id = ?",
  840. ... ["soil@PERMANENT",]])
  841. "SELECT ctime FROM raster_base WHERE id = 'soil@PERMANENT'"
  842. """
  843. sql = content[0]
  844. args = content[1]
  845. if self.dbmi.__name__ == "psycopg2":
  846. if len(args) == 0:
  847. return sql
  848. else:
  849. if self.connected:
  850. try:
  851. return self.cursor.mogrify(sql, args)
  852. except:
  853. print sql, args
  854. raise
  855. else:
  856. self.connect()
  857. statement = self.cursor.mogrify(sql, args)
  858. self.close()
  859. return statement
  860. elif self.dbmi.__name__ == "sqlite3":
  861. if len(args) == 0:
  862. return sql
  863. else:
  864. # Unfortunately as sqlite does not support
  865. # the transformation of sql strings and qmarked or
  866. # named arguments we must make our hands dirty
  867. # and do it by ourself. :(
  868. # Doors are open for SQL injection because of the
  869. # limited python sqlite3 implementation!!!
  870. pos = 0
  871. count = 0
  872. maxcount = 100
  873. statement = sql
  874. while count < maxcount:
  875. pos = statement.find("?", pos + 1)
  876. if pos == -1:
  877. break
  878. if args[count] is None:
  879. statement = "%sNULL%s" % (statement[0:pos],
  880. statement[pos + 1:])
  881. elif isinstance(args[count], (int, long)):
  882. statement = "%s%d%s" % (statement[0:pos], args[count],
  883. statement[pos + 1:])
  884. elif isinstance(args[count], float):
  885. statement = "%s%f%s" % (statement[0:pos], args[count],
  886. statement[pos + 1:])
  887. else:
  888. # Default is a string, this works for datetime
  889. # objects too
  890. statement = "%s\'%s\'%s" % (statement[0:pos],
  891. str(args[count]),
  892. statement[pos + 1:])
  893. count += 1
  894. return statement
  895. def check_table(self, table_name):
  896. """Check if a table exists in the temporal database
  897. :param table_name: The name of the table to be checked for existence
  898. :param mapset: The mapset of the abstract dataset or temporal
  899. database location, if None the current mapset
  900. will be used
  901. :returns: True if the table exists, False otherwise
  902. TODO:
  903. There may be several temporal databases in a location, hence
  904. the mapset is used to query the correct temporal database.
  905. """
  906. table_exists = False
  907. connected = False
  908. if not self.connected:
  909. self.connect()
  910. connected = True
  911. # Check if the database already exists
  912. if self.dbmi.__name__ == "sqlite3":
  913. self.cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='%s';"%table_name)
  914. name = self.cursor.fetchone()
  915. if name and name[0] == table_name:
  916. table_exists = True
  917. else:
  918. # Check for raster_base table
  919. self.cursor.execute("SELECT EXISTS(SELECT * FROM information_schema.tables "
  920. "WHERE table_name=%s)", ('%s'%table_name,))
  921. if self.cursor.fetchone()[0]:
  922. table_exists = True
  923. if connected:
  924. self.close()
  925. return table_exists
  926. def execute(self, statement, args=None):
  927. """Execute a SQL statement
  928. :param statement: The executable SQL statement or SQL script
  929. """
  930. connected = False
  931. if not self.connected:
  932. self.connect()
  933. connected = True
  934. try:
  935. if args:
  936. self.cursor.execute(statement, args)
  937. else:
  938. self.cursor.execute(statement)
  939. except:
  940. if connected:
  941. self.close()
  942. self.msgr.error(_("Unable to execute :\n %(sql)s" % {"sql":statement}))
  943. raise
  944. if connected:
  945. self.close()
  946. def fetchone(self):
  947. if self.connected:
  948. return self.cursor.fetchone()
  949. return None
  950. def fetchall(self):
  951. if self.connected:
  952. return self.cursor.fetchall()
  953. return None
  954. def execute_transaction(self, statement, mapset=None):
  955. """Execute a transactional SQL statement
  956. The BEGIN and END TRANSACTION statements will be added automatically
  957. to the sql statement
  958. :param statement: The executable SQL statement or SQL script
  959. """
  960. connected = False
  961. if not self.connected:
  962. self.connect()
  963. connected = True
  964. sql_script = ""
  965. sql_script += "BEGIN TRANSACTION;\n"
  966. sql_script += statement
  967. sql_script += "END TRANSACTION;"
  968. try:
  969. if self.dbmi.__name__ == "sqlite3":
  970. self.cursor.executescript(statement)
  971. else:
  972. self.cursor.execute(statement)
  973. self.connection.commit()
  974. except:
  975. if connected:
  976. self.close()
  977. self.msgr.error(_("Unable to execute transaction:\n %(sql)s" % {"sql":statement}))
  978. raise
  979. if connected:
  980. self.close()
  981. ###############################################################################
  982. def init_dbif(dbif):
  983. """This method checks if the database interface connection exists,
  984. if not a new one will be created, connected and True will be returned.
  985. If the database interface exists but is connected, the connection will be established.
  986. :returns: the tuple (dbif, True|False)
  987. Usage code sample:
  988. dbif, connect = tgis.init_dbif(None)
  989. sql = dbif.mogrify_sql_statement(["SELECT * FROM raster_base WHERE ? = ?"],
  990. ["id", "soil@PERMANENT"])
  991. dbif.execute_transaction(sql)
  992. if connect:
  993. dbif.close()
  994. """
  995. if dbif is None:
  996. dbif = SQLDatabaseInterfaceConnection()
  997. dbif.connect()
  998. return dbif, True
  999. elif dbif.is_connected() is False:
  1000. dbif.connect()
  1001. return dbif, True
  1002. return dbif, False
  1003. ###############################################################################
  1004. if __name__ == "__main__":
  1005. import doctest
  1006. doctest.testmod()