core.py 50 KB

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