core.py 48 KB

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