core.py 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219
  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. dbmi = sqlite3
  427. else:
  428. # Set the default sqlite3 connection in case nothing was defined
  429. gscript.run_command("t.connect", flags="d")
  430. driver_string = ciface.get_driver_name()
  431. database_string = ciface.get_database_name()
  432. tgis_backend = driver_string
  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. def get_dbmi(self, mapset=None):
  646. if mapset is None:
  647. mapset = self.current_mapset
  648. return self.connections[mapset].dbmi
  649. def rollback(self, mapset=None):
  650. """
  651. Roll back the last transaction. This must be called
  652. in case a new query should be performed after a db error.
  653. This is only relevant for postgresql database.
  654. """
  655. if mapset is None:
  656. mapset = self.current_mapset
  657. def connect(self):
  658. """Connect to the DBMI to execute SQL statements
  659. Supported backends are sqlite3 and postgresql
  660. """
  661. for mapset in self.tgis_mapsets.keys():
  662. driver, dbstring = self.tgis_mapsets[mapset]
  663. conn = self.connections[mapset]
  664. if conn.is_connected() is False:
  665. conn .connect(dbstring)
  666. self.connected = True
  667. def is_connected(self):
  668. return self.connected
  669. def close(self):
  670. """Close the DBMI connection
  671. There may be several temporal databases in a location, hence
  672. close all temporal databases that have been opened.
  673. """
  674. for key in self.unique_connections.keys():
  675. self.unique_connections[key] .close()
  676. self.connected = False
  677. def mogrify_sql_statement(self, content, mapset=None):
  678. """Return the SQL statement and arguments as executable SQL string
  679. :param content: The content as tuple with two entries, the first
  680. entry is the SQL statement with DBMI specific
  681. place holder (?), the second entry is the argument
  682. list that should substitute the place holder.
  683. :param mapset: The mapset of the abstract dataset or temporal
  684. database location, if None the current mapset
  685. will be used
  686. """
  687. if mapset is None:
  688. mapset = self.current_mapset
  689. return self.connections[mapset].mogrify_sql_statement(content)
  690. def check_table(self, table_name, mapset=None):
  691. """Check if a table exists in the temporal database
  692. :param table_name: The name of the table to be checked for existence
  693. :param mapset: The mapset of the abstract dataset or temporal
  694. database location, if None the current mapset
  695. will be used
  696. :returns: True if the table exists, False otherwise
  697. TODO:
  698. There may be several temporal databases in a location, hence
  699. the mapset is used to query the correct temporal database.
  700. """
  701. if mapset is None:
  702. mapset = self.current_mapset
  703. return self.connections[mapset].check_table(table_name)
  704. def execute(self, statement, args=None, mapset=None):
  705. """""
  706. :param mapset: The mapset of the abstract dataset or temporal
  707. database location, if None the current mapset
  708. will be used
  709. """
  710. if mapset is None:
  711. mapset = self.current_mapset
  712. return self.connections[mapset].execute(statement, args)
  713. def fetchone(self, mapset=None):
  714. if mapset is None:
  715. mapset = self.current_mapset
  716. return self.connections[mapset].fetchone()
  717. def fetchall(self, mapset=None):
  718. if mapset is None:
  719. mapset = self.current_mapset
  720. return self.connections[mapset].fetchall()
  721. def execute_transaction(self, statement, mapset=None):
  722. """Execute a transactional SQL statement
  723. The BEGIN and END TRANSACTION statements will be added automatically
  724. to the sql statement
  725. :param statement: The executable SQL statement or SQL script
  726. """
  727. if mapset is None:
  728. mapset = self.current_mapset
  729. return self.connections[mapset].execute_transaction(statement)
  730. ###############################################################################
  731. class DBConnection(object):
  732. """This class represents the database interface connection
  733. and provides access to the chisen backend modules.
  734. The following DBMS are supported:
  735. - sqlite via the sqlite3 standard library
  736. - postgresql via psycopg2
  737. """
  738. def __init__(self , backend=None):
  739. self.connected = False
  740. if backend is None:
  741. global tgis_backend
  742. if tgis_backend == "sqlite":
  743. self.dbmi = sqlite3
  744. else:
  745. self.dbmi = psycopg2
  746. else:
  747. if backend == "sqlite":
  748. self.dbmi = sqlite3
  749. else:
  750. self.dbmi = psycopg2
  751. self.msgr = get_tgis_message_interface()
  752. self.msgr.debug(1, "SQLDatabaseInterfaceConnection constructor")
  753. def __del__(self):
  754. if self.connected is True:
  755. self.close()
  756. def is_connected(self):
  757. return self.connected
  758. def rollback(self):
  759. """
  760. Roll back the last transaction. This must be called
  761. in case a new query should be performed after a db error.
  762. This is only relevant for postgresql database.
  763. """
  764. if self.dbmi.__name__ == "psycopg2":
  765. if self.connected:
  766. self.connection.rollback()
  767. def connect(self, dbstring=None):
  768. """Connect to the DBMI to execute SQL statements
  769. Supported backends are sqlite3 and postgresql
  770. """
  771. # Connection in the current mapset
  772. if dbstring is None:
  773. global tgis_database_string
  774. dbstring = tgis_database_string
  775. try:
  776. if self.dbmi.__name__ == "sqlite3":
  777. self.connection = self.dbmi.connect(dbstring,
  778. detect_types = self.dbmi.PARSE_DECLTYPES | self.dbmi.PARSE_COLNAMES)
  779. self.connection.row_factory = self.dbmi.Row
  780. self.connection.isolation_level = None
  781. self.cursor = self.connection.cursor()
  782. self.cursor.execute("PRAGMA synchronous = OFF")
  783. self.cursor.execute("PRAGMA journal_mode = MEMORY")
  784. elif self.dbmi.__name__ == "psycopg2":
  785. self.connection = self.dbmi.connect(dbstring)
  786. #self.connection.set_isolation_level(dbmi.extensions.ISOLATION_LEVEL_AUTOCOMMIT)
  787. self.cursor = self.connection.cursor(
  788. cursor_factory = self.dbmi.extras.DictCursor)
  789. self.connected = True
  790. except Exception as e:
  791. self.msgr.fatal(_("Unable to connect to %(db)s database: "
  792. "%(string)s\nException: \"%(ex)s\"\nPlease use t.connect to set a "
  793. "read- and writable temporal database backend")%({"db":self.dbmi.__name__,
  794. "string":tgis_database_string,
  795. "ex":e,}))
  796. def close(self):
  797. """Close the DBMI connection
  798. TODO:
  799. There may be several temporal databases in a location, hence
  800. close all temporal databases that have been opened. Use a dictionary
  801. to manage different connections.
  802. """
  803. self.connection.commit()
  804. self.cursor.close()
  805. self.connected = False
  806. def mogrify_sql_statement(self, content):
  807. """Return the SQL statement and arguments as executable SQL string
  808. TODO:
  809. Use the mapset argument to identify the correct database driver
  810. :param content: The content as tuple with two entries, the first
  811. entry is the SQL statement with DBMI specific
  812. place holder (?), the second entry is the argument
  813. list that should substitute the place holder.
  814. :param mapset: The mapset of the abstract dataset or temporal
  815. database location, if None the current mapset
  816. will be used
  817. Usage:
  818. >>> init()
  819. >>> dbif = SQLDatabaseInterfaceConnection()
  820. >>> dbif.mogrify_sql_statement(["SELECT ctime FROM raster_base WHERE id = ?",
  821. ... ["soil@PERMANENT",]])
  822. "SELECT ctime FROM raster_base WHERE id = 'soil@PERMANENT'"
  823. """
  824. sql = content[0]
  825. args = content[1]
  826. if self.dbmi.__name__ == "psycopg2":
  827. if len(args) == 0:
  828. return sql
  829. else:
  830. if self.connected:
  831. try:
  832. return self.cursor.mogrify(sql, args)
  833. except:
  834. print sql, args
  835. raise
  836. else:
  837. self.connect()
  838. statement = self.cursor.mogrify(sql, args)
  839. self.close()
  840. return statement
  841. elif self.dbmi.__name__ == "sqlite3":
  842. if len(args) == 0:
  843. return sql
  844. else:
  845. # Unfortunately as sqlite does not support
  846. # the transformation of sql strings and qmarked or
  847. # named arguments we must make our hands dirty
  848. # and do it by ourself. :(
  849. # Doors are open for SQL injection because of the
  850. # limited python sqlite3 implementation!!!
  851. pos = 0
  852. count = 0
  853. maxcount = 100
  854. statement = sql
  855. while count < maxcount:
  856. pos = statement.find("?", pos + 1)
  857. if pos == -1:
  858. break
  859. if args[count] is None:
  860. statement = "%sNULL%s" % (statement[0:pos],
  861. statement[pos + 1:])
  862. elif isinstance(args[count], (int, long)):
  863. statement = "%s%d%s" % (statement[0:pos], args[count],
  864. statement[pos + 1:])
  865. elif isinstance(args[count], float):
  866. statement = "%s%f%s" % (statement[0:pos], args[count],
  867. statement[pos + 1:])
  868. else:
  869. # Default is a string, this works for datetime
  870. # objects too
  871. statement = "%s\'%s\'%s" % (statement[0:pos],
  872. str(args[count]),
  873. statement[pos + 1:])
  874. count += 1
  875. return statement
  876. def check_table(self, table_name):
  877. """Check if a table exists in the temporal database
  878. :param table_name: The name of the table to be checked for existence
  879. :param mapset: The mapset of the abstract dataset or temporal
  880. database location, if None the current mapset
  881. will be used
  882. :returns: True if the table exists, False otherwise
  883. TODO:
  884. There may be several temporal databases in a location, hence
  885. the mapset is used to query the correct temporal database.
  886. """
  887. table_exists = False
  888. connected = False
  889. if not self.connected:
  890. self.connect()
  891. connected = True
  892. # Check if the database already exists
  893. if self.dbmi.__name__ == "sqlite3":
  894. self.cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='%s';"%table_name)
  895. name = self.cursor.fetchone()
  896. if name and name[0] == table_name:
  897. table_exists = True
  898. else:
  899. # Check for raster_base table
  900. self.cursor.execute("SELECT EXISTS(SELECT * FROM information_schema.tables "
  901. "WHERE table_name=%s)", ('%s'%table_name,))
  902. if self.cursor.fetchone()[0]:
  903. table_exists = True
  904. if connected:
  905. self.close()
  906. return table_exists
  907. def execute(self, statement, args=None):
  908. """Execute a SQL statement
  909. :param statement: The executable SQL statement or SQL script
  910. """
  911. connected = False
  912. if not self.connected:
  913. self.connect()
  914. connected = True
  915. try:
  916. if args:
  917. self.cursor.execute(statement, args)
  918. else:
  919. self.cursor.execute(statement)
  920. except:
  921. if connected:
  922. self.close()
  923. self.msgr.error(_("Unable to execute :\n %(sql)s" % {"sql":statement}))
  924. raise
  925. if connected:
  926. self.close()
  927. def fetchone(self):
  928. if self.connected:
  929. return self.cursor.fetchone()
  930. return None
  931. def fetchall(self):
  932. if self.connected:
  933. return self.cursor.fetchall()
  934. return None
  935. def execute_transaction(self, statement, mapset=None):
  936. """Execute a transactional SQL statement
  937. The BEGIN and END TRANSACTION statements will be added automatically
  938. to the sql statement
  939. :param statement: The executable SQL statement or SQL script
  940. """
  941. connected = False
  942. if not self.connected:
  943. self.connect()
  944. connected = True
  945. sql_script = ""
  946. sql_script += "BEGIN TRANSACTION;\n"
  947. sql_script += statement
  948. sql_script += "END TRANSACTION;"
  949. try:
  950. if self.dbmi.__name__ == "sqlite3":
  951. self.cursor.executescript(statement)
  952. else:
  953. self.cursor.execute(statement)
  954. self.connection.commit()
  955. except:
  956. if connected:
  957. self.close()
  958. self.msgr.error(_("Unable to execute transaction:\n %(sql)s" % {"sql":statement}))
  959. raise
  960. if connected:
  961. self.close()
  962. ###############################################################################
  963. def init_dbif(dbif):
  964. """This method checks if the database interface connection exists,
  965. if not a new one will be created, connected and True will be returned.
  966. If the database interface exists but is connected, the connection will be established.
  967. :returns: the tuple (dbif, True|False)
  968. Usage code sample:
  969. dbif, connect = tgis.init_dbif(None)
  970. sql = dbif.mogrify_sql_statement(["SELECT * FROM raster_base WHERE ? = ?"],
  971. ["id", "soil@PERMANENT"])
  972. dbif.execute_transaction(sql)
  973. if connect:
  974. dbif.close()
  975. """
  976. if dbif is None:
  977. dbif = SQLDatabaseInterfaceConnection()
  978. dbif.connect()
  979. return dbif, True
  980. elif dbif.is_connected() is False:
  981. dbif.connect()
  982. return dbif, True
  983. return dbif, False
  984. ###############################################################################
  985. if __name__ == "__main__":
  986. import doctest
  987. doctest.testmod()