core.py 50 KB

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