core.py 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347
  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. global message_interface
  333. mapsets = c_library_interface.available_mapsets()
  334. tgis_mapsets = {}
  335. for mapset in mapsets:
  336. driver = c_library_interface.get_driver_name(mapset)
  337. database = c_library_interface.get_database_name(mapset)
  338. if driver and database:
  339. # Check if the temporal sqlite database exists
  340. # We need to set non-existing databases in case the mapset is the current mapset
  341. # to create it
  342. if (driver == "sqlite" and os.path.exists(database)) or mapset == get_current_mapset() :
  343. tgis_mapsets[mapset] = (driver, database)
  344. # We need to warn if the connection is defined but the database does not
  345. # exists
  346. if driver == "sqlite" and not os.path.exists(database):
  347. message_interface.warning("Temporal database connection defined as:\n" + \
  348. database + "\nBut database file does not exists.")
  349. return tgis_mapsets
  350. ###############################################################################
  351. def init(raise_fatal_error=False):
  352. """This function set the correct database backend from GRASS environmental
  353. variables and creates the grass temporal database structure for raster,
  354. vector and raster3d maps as well as for the space-time datasets strds,
  355. str3ds and stvds in case it does not exists.
  356. Several global variables are initiated and the messenger and C-library
  357. interface subprocesses are spawned.
  358. Re-run this function in case the following GRASS variables change while
  359. the process runs:
  360. - MAPSET
  361. - LOCATION_NAME
  362. - GISDBASE
  363. - TGIS_DISABLE_MAPSET_CHECK
  364. - TGIS_DISABLE_TIMESTAMP_WRITE
  365. Re-run this function if the following t.connect variables change while
  366. the process runs:
  367. - temporal GIS driver (set by t.connect driver=)
  368. - temporal GIS database (set by t.connect database=)
  369. The following environmental variables are checked:
  370. - GRASS_TGIS_PROFILE (True, False, 1, 0)
  371. - GRASS_TGIS_RAISE_ON_ERROR (True, False, 1, 0)
  372. ..warning::
  373. This functions must be called before any spatio-temporal processing
  374. can be started
  375. :param raise_fatal_error: Set this True to assure that the init()
  376. function does not kill a persistent process
  377. like the GUI. If set True a
  378. grass.pygrass.messages.FatalError
  379. exception will be raised in case a fatal
  380. error occurs in the init process, otherwise
  381. sys.exit(1) will be called.
  382. """
  383. # We need to set the correct database backend and several global variables
  384. # from the GRASS mapset specific environment variables of g.gisenv and t.connect
  385. global tgis_backend
  386. global tgis_database
  387. global tgis_database_string
  388. global tgis_dbmi_paramstyle
  389. global raise_on_error
  390. global enable_mapset_check
  391. global enable_timestamp_write
  392. global current_mapset
  393. global current_location
  394. global current_gisdbase
  395. raise_on_error = raise_fatal_error
  396. # We must run t.connect at first to create the temporal database and to
  397. # get the environmental variables
  398. gscript.run_command("t.connect", flags="c")
  399. grassenv = gscript.gisenv()
  400. # Set the global variable for faster access
  401. current_mapset = grassenv["MAPSET"]
  402. current_location = grassenv["LOCATION_NAME"]
  403. current_gisdbase = grassenv["GISDBASE"]
  404. # Check environment variable GRASS_TGIS_RAISE_ON_ERROR
  405. if os.getenv("GRASS_TGIS_RAISE_ON_ERROR") == "True" or \
  406. os.getenv("GRASS_TGIS_RAISE_ON_ERROR") == "1":
  407. raise_on_error = True
  408. # Check if the script library raises on error,
  409. # if so we do the same
  410. if gscript.get_raise_on_error() is True:
  411. raise_on_error = True
  412. # Start the GRASS message interface server
  413. _init_tgis_message_interface(raise_on_error)
  414. # Start the C-library interface server
  415. _init_tgis_c_library_interface()
  416. msgr = get_tgis_message_interface()
  417. msgr.debug(1, "Initiate the temporal database")
  418. ciface = get_tgis_c_library_interface()
  419. driver_string = ciface.get_driver_name()
  420. database_string = ciface.get_database_name()
  421. # Set the mapset check and the timestamp write
  422. if grassenv.has_key("TGIS_DISABLE_MAPSET_CHECK"):
  423. if grassenv["TGIS_DISABLE_MAPSET_CHECK"] == "True" or \
  424. grassenv["TGIS_DISABLE_MAPSET_CHECK"] == "1":
  425. enable_mapset_check = False
  426. msgr.warning("TGIS_DISABLE_MAPSET_CHECK is True")
  427. if grassenv.has_key("TGIS_DISABLE_TIMESTAMP_WRITE"):
  428. if grassenv["TGIS_DISABLE_TIMESTAMP_WRITE"] == "True" or \
  429. grassenv["TGIS_DISABLE_TIMESTAMP_WRITE"] == "1":
  430. enable_timestamp_write = False
  431. msgr.warning("TGIS_DISABLE_TIMESTAMP_WRITE is True")
  432. if driver_string is not None and driver_string is not "":
  433. if driver_string == "sqlite":
  434. tgis_backend = driver_string
  435. try:
  436. import sqlite3
  437. except ImportError:
  438. msgr.error("Unable to locate the sqlite SQL Python interface"
  439. " module sqlite3.")
  440. raise
  441. dbmi = sqlite3
  442. elif driver_string == "pg":
  443. tgis_backend = driver_string
  444. try:
  445. import psycopg2
  446. except ImportError:
  447. msgr.error("Unable to locate the Postgresql SQL Python "
  448. "interface module psycopg2.")
  449. raise
  450. dbmi = psycopg2
  451. else:
  452. msgr.fatal(_("Unable to initialize the temporal DBMI interface. "
  453. "Please use t.connect to specify the driver and the"
  454. " database string"))
  455. else:
  456. # Set the default sqlite3 connection in case nothing was defined
  457. gscript.run_command("t.connect", flags="d")
  458. driver_string = ciface.get_driver_name()
  459. database_string = ciface.get_database_name()
  460. tgis_backend = driver_string
  461. dbmi = sqlite3
  462. tgis_database_string = database_string
  463. # Set the parameter style
  464. tgis_dbmi_paramstyle = dbmi.paramstyle
  465. # We do not know if the database already exists
  466. db_exists = False
  467. dbif = SQLDatabaseInterfaceConnection()
  468. # Check if the database already exists
  469. if tgis_backend == "sqlite":
  470. # Check path of the sqlite database
  471. if os.path.exists(tgis_database_string):
  472. dbif.connect()
  473. # Check for raster_base table
  474. dbif.execute("SELECT name FROM sqlite_master WHERE type='table' "
  475. "AND name='raster_base';")
  476. name = dbif.fetchone()
  477. if name and name[0] == "raster_base":
  478. db_exists = True
  479. dbif.close()
  480. elif tgis_backend == "pg":
  481. # Connect to database
  482. dbif.connect()
  483. # Check for raster_base table
  484. dbif.execute("SELECT EXISTS(SELECT * FROM information_schema.tables "
  485. "WHERE table_name=%s)", ('raster_base',))
  486. if dbif.fetchone()[0]:
  487. db_exists = True
  488. backup_howto = "The format of your actual temporal database is not " \
  489. "supported any more.\nSolution: You need to export it by " \
  490. "restoring the GRASS GIS version used for creating this DB"\
  491. ". From there, create a backup of your temporal database "\
  492. "to avoid the loss of your temporal data.\nNotes: Use " \
  493. "t.rast.export and t.vect.export to make a backup of your" \
  494. " existing space time datasets.To safe the timestamps of" \
  495. " your existing maps and space time datasets, use " \
  496. "t.rast.list, t.vect.list and t.rast3d.list. "\
  497. "You can register the existing time stamped maps easily if"\
  498. " you export columns=id,start_time,end_time into text "\
  499. "files and use t.register to register them again in new" \
  500. " created space time datasets (t.create). After the backup"\
  501. " remove the existing temporal database, a new one will be"\
  502. " created automatically.\n"
  503. if db_exists is True:
  504. # Check the version of the temporal database
  505. dbif.close()
  506. dbif.connect()
  507. metadata = get_tgis_metadata(dbif)
  508. dbif.close()
  509. if metadata is None:
  510. msgr.fatal(_("Unable to receive temporal database metadata.\n"
  511. "Current temporal database info:%(info)s") % (
  512. {"info": get_database_info_string()}))
  513. for entry in metadata:
  514. if "tgis_version" in entry and entry[1] != str(get_tgis_version()):
  515. msgr.fatal(_("Unsupported temporal database: version mismatch."
  516. "\n %(backup)s Supported temporal API version is:"
  517. " %(api)i.\nPlease update your GRASS GIS "
  518. "installation.\nCurrent temporal database info:"
  519. "%(info)s") % ({"backup": backup_howto,
  520. "api": get_tgis_version(),
  521. "info": get_database_info_string()}))
  522. if "tgis_db_version" in entry and entry[1] != str(get_tgis_db_version()):
  523. msgr.fatal(_("Unsupported temporal database: version mismatch."
  524. "\n %(backup)sSupported temporal database version"
  525. " is: %(tdb)i\nCurrent temporal database info:"
  526. "%(info)s") % ({"backup": backup_howto,
  527. "tdb": get_tgis_version(),
  528. "info": get_database_info_string()}))
  529. return
  530. create_temporal_database(dbif)
  531. ###############################################################################
  532. def get_database_info_string():
  533. dbif = SQLDatabaseInterfaceConnection()
  534. info = "\nDBMI interface:..... " + str(dbif.get_dbmi().__name__)
  535. info += "\nTemporal database:.. " + str(get_tgis_database_string())
  536. return info
  537. ###############################################################################
  538. def create_temporal_database(dbif):
  539. """This function will create the temporal database
  540. It will create all tables and triggers that are needed to run
  541. the temporal GIS
  542. :param dbif: The database interface to be used
  543. """
  544. global tgis_backend
  545. global tgis_version
  546. global tgis_db_version
  547. global tgis_database_string
  548. template_path = get_sql_template_path()
  549. msgr = get_tgis_message_interface()
  550. # Read all SQL scripts and templates
  551. map_tables_template_sql = open(os.path.join(
  552. template_path, "map_tables_template.sql"), 'r').read()
  553. raster_metadata_sql = open(os.path.join(
  554. get_sql_template_path(), "raster_metadata_table.sql"), 'r').read()
  555. raster3d_metadata_sql = open(os.path.join(template_path,
  556. "raster3d_metadata_table.sql"),
  557. 'r').read()
  558. vector_metadata_sql = open(os.path.join(template_path,
  559. "vector_metadata_table.sql"),
  560. 'r').read()
  561. raster_views_sql = open(os.path.join(template_path, "raster_views.sql"),
  562. 'r').read()
  563. raster3d_views_sql = open(os.path.join(template_path,
  564. "raster3d_views.sql"), 'r').read()
  565. vector_views_sql = open(os.path.join(template_path, "vector_views.sql"),
  566. 'r').read()
  567. stds_tables_template_sql = open(os.path.join(template_path,
  568. "stds_tables_template.sql"),
  569. 'r').read()
  570. strds_metadata_sql = open(os.path.join(template_path,
  571. "strds_metadata_table.sql"),
  572. 'r').read()
  573. str3ds_metadata_sql = open(os.path.join(template_path,
  574. "str3ds_metadata_table.sql"),
  575. 'r').read()
  576. stvds_metadata_sql = open(os.path.join(template_path,
  577. "stvds_metadata_table.sql"),
  578. 'r').read()
  579. strds_views_sql = open(os.path.join(template_path, "strds_views.sql"),
  580. 'r').read()
  581. str3ds_views_sql = open(os.path.join(template_path, "str3ds_views.sql"),
  582. 'r').read()
  583. stvds_views_sql = open(os.path.join(template_path, "stvds_views.sql"),
  584. 'r').read()
  585. # Create the raster, raster3d and vector tables SQL statements
  586. raster_tables_sql = map_tables_template_sql.replace("GRASS_MAP", "raster")
  587. vector_tables_sql = map_tables_template_sql.replace("GRASS_MAP", "vector")
  588. raster3d_tables_sql = map_tables_template_sql.replace(
  589. "GRASS_MAP", "raster3d")
  590. # Create the space-time raster, raster3d and vector dataset tables
  591. # SQL statements
  592. strds_tables_sql = stds_tables_template_sql.replace("STDS", "strds")
  593. stvds_tables_sql = stds_tables_template_sql.replace("STDS", "stvds")
  594. str3ds_tables_sql = stds_tables_template_sql.replace("STDS", "str3ds")
  595. msgr.message(_("Creating temporal database: %s" % (str(tgis_database_string))))
  596. if tgis_backend == "sqlite":
  597. # We need to create the sqlite3 database path if it does not exists
  598. tgis_dir = os.path.dirname(tgis_database_string)
  599. if not os.path.exists(tgis_dir):
  600. try:
  601. os.makedirs(tgis_dir)
  602. except Exception as e:
  603. msgr.fatal(_("Unable to create SQLite temporal database\n"
  604. "Exception: %s\nPlease use t.connect to set a "
  605. "read- and writable temporal database path" % (e)))
  606. # Set up the trigger that takes care of
  607. # the correct deletion of entries across the different tables
  608. delete_trigger_sql = open(os.path.join(template_path,
  609. "sqlite3_delete_trigger.sql"),
  610. 'r').read()
  611. indexes_sql = open(os.path.join(template_path, "sqlite3_indexes.sql"),
  612. 'r').read()
  613. else:
  614. # Set up the trigger that takes care of
  615. # the correct deletion of entries across the different tables
  616. delete_trigger_sql = open(os.path.join(template_path,
  617. "postgresql_delete_trigger.sql"),
  618. 'r').read()
  619. indexes_sql = open(os.path.join(template_path,
  620. "postgresql_indexes.sql"), 'r').read()
  621. # Connect now to the database
  622. if dbif.connected is not True:
  623. dbif.connect()
  624. # Execute the SQL statements for sqlite
  625. # Create the global tables for the native grass datatypes
  626. dbif.execute_transaction(raster_tables_sql)
  627. dbif.execute_transaction(raster_metadata_sql)
  628. dbif.execute_transaction(raster_views_sql)
  629. dbif.execute_transaction(vector_tables_sql)
  630. dbif.execute_transaction(vector_metadata_sql)
  631. dbif.execute_transaction(vector_views_sql)
  632. dbif.execute_transaction(raster3d_tables_sql)
  633. dbif.execute_transaction(raster3d_metadata_sql)
  634. dbif.execute_transaction(raster3d_views_sql)
  635. # Create the tables for the new space-time datatypes
  636. dbif.execute_transaction(strds_tables_sql)
  637. dbif.execute_transaction(strds_metadata_sql)
  638. dbif.execute_transaction(strds_views_sql)
  639. dbif.execute_transaction(stvds_tables_sql)
  640. dbif.execute_transaction(stvds_metadata_sql)
  641. dbif.execute_transaction(stvds_views_sql)
  642. dbif.execute_transaction(str3ds_tables_sql)
  643. dbif.execute_transaction(str3ds_metadata_sql)
  644. dbif.execute_transaction(str3ds_views_sql)
  645. # The delete trigger
  646. dbif.execute_transaction(delete_trigger_sql)
  647. # The indexes
  648. dbif.execute_transaction(indexes_sql)
  649. # Create the tgis metadata table to store the database
  650. # initial configuration
  651. # The metadata table content
  652. metadata = {}
  653. metadata["tgis_version"] = tgis_version
  654. metadata["tgis_db_version"] = tgis_db_version
  655. metadata["creation_time"] = datetime.today()
  656. _create_tgis_metadata_table(metadata, dbif)
  657. dbif.close()
  658. ###############################################################################
  659. def _create_tgis_metadata_table(content, dbif=None):
  660. """!Create the temporal gis metadata table which stores all metadata
  661. information about the temporal database.
  662. :param content: The dictionary that stores the key:value metadata
  663. that should be stored in the metadata table
  664. :param dbif: The database interface to be used
  665. """
  666. dbif, connected = init_dbif(dbif)
  667. statement = "CREATE TABLE tgis_metadata (key VARCHAR NOT NULL, value VARCHAR);\n";
  668. dbif.execute_transaction(statement)
  669. for key in content.keys():
  670. statement = "INSERT INTO tgis_metadata (key, value) VALUES " + \
  671. "(\'%s\' , \'%s\');\n" % (str(key), str(content[key]))
  672. dbif.execute_transaction(statement)
  673. if connected:
  674. dbif.close()
  675. ###############################################################################
  676. class SQLDatabaseInterfaceConnection(object):
  677. def __init__(self):
  678. self.tgis_mapsets = get_available_temporal_mapsets()
  679. self.current_mapset = get_current_mapset()
  680. self.connections = {}
  681. self.connected = False
  682. self.unique_connections = {}
  683. for mapset in self.tgis_mapsets.keys():
  684. driver, dbstring = self.tgis_mapsets[mapset]
  685. if dbstring not in self.unique_connections.keys():
  686. self.unique_connections[dbstring] = DBConnection(backend=driver,
  687. dbstring=dbstring)
  688. self.connections[mapset] = self.unique_connections[dbstring]
  689. self.msgr = get_tgis_message_interface()
  690. def get_dbmi(self, mapset=None):
  691. if mapset is None:
  692. mapset = self.current_mapset
  693. return self.connections[mapset].dbmi
  694. def rollback(self, mapset=None):
  695. """
  696. Roll back the last transaction. This must be called
  697. in case a new query should be performed after a db error.
  698. This is only relevant for postgresql database.
  699. """
  700. if mapset is None:
  701. mapset = self.current_mapset
  702. def connect(self):
  703. """Connect to the DBMI to execute SQL statements
  704. Supported backends are sqlite3 and postgresql
  705. """
  706. for mapset in self.tgis_mapsets.keys():
  707. driver, dbstring = self.tgis_mapsets[mapset]
  708. conn = self.connections[mapset]
  709. if conn.is_connected() is False:
  710. conn.connect(dbstring)
  711. self.connected = True
  712. def is_connected(self):
  713. return self.connected
  714. def close(self):
  715. """Close the DBMI connection
  716. There may be several temporal databases in a location, hence
  717. close all temporal databases that have been opened.
  718. """
  719. for key in self.unique_connections.keys():
  720. self.unique_connections[key].close()
  721. self.connected = False
  722. def mogrify_sql_statement(self, content, mapset=None):
  723. """Return the SQL statement and arguments as executable SQL string
  724. :param content: The content as tuple with two entries, the first
  725. entry is the SQL statement with DBMI specific
  726. place holder (?), the second entry is the argument
  727. list that should substitute the place holder.
  728. :param mapset: The mapset of the abstract dataset or temporal
  729. database location, if None the current mapset
  730. will be used
  731. """
  732. if mapset is None:
  733. mapset = self.current_mapset
  734. if mapset not in self.tgis_mapsets.keys():
  735. self.msgr.fatal(_("Unable to mogrify sql statement. " +
  736. self._create_mapset_error_message(mapset)))
  737. return self.connections[mapset].mogrify_sql_statement(content)
  738. def check_table(self, table_name, mapset=None):
  739. """Check if a table exists in the temporal database
  740. :param table_name: The name of the table to be checked for existence
  741. :param mapset: The mapset of the abstract dataset or temporal
  742. database location, if None the current mapset
  743. will be used
  744. :returns: True if the table exists, False otherwise
  745. TODO:
  746. There may be several temporal databases in a location, hence
  747. the mapset is used to query the correct temporal database.
  748. """
  749. if mapset is None:
  750. mapset = self.current_mapset
  751. if mapset not in self.tgis_mapsets.keys():
  752. self.msgr.fatal(_("Unable to check table. " +
  753. self._create_mapset_error_message(mapset)))
  754. return self.connections[mapset].check_table(table_name)
  755. def execute(self, statement, args=None, mapset=None):
  756. """
  757. :param mapset: The mapset of the abstract dataset or temporal
  758. database location, if None the current mapset
  759. will be used
  760. """
  761. if mapset is None:
  762. mapset = self.current_mapset
  763. if mapset not in self.tgis_mapsets.keys():
  764. self.msgr.fatal(_("Unable to execute sql statement. " +
  765. self._create_mapset_error_message(mapset)))
  766. return self.connections[mapset].execute(statement, args)
  767. def fetchone(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 one. " +
  772. self._create_mapset_error_message(mapset)))
  773. return self.connections[mapset].fetchone()
  774. def fetchall(self, mapset=None):
  775. if mapset is None:
  776. mapset = self.current_mapset
  777. if mapset not in self.tgis_mapsets.keys():
  778. self.msgr.fatal(_("Unable to fetch all. " +
  779. self._create_mapset_error_message(mapset)))
  780. return self.connections[mapset].fetchall()
  781. def execute_transaction(self, statement, mapset=None):
  782. """Execute a transactional SQL statement
  783. The BEGIN and END TRANSACTION statements will be added automatically
  784. to the sql statement
  785. :param statement: The executable SQL statement or SQL script
  786. """
  787. if mapset is None:
  788. mapset = self.current_mapset
  789. if mapset not in self.tgis_mapsets.keys():
  790. self.msgr.fatal(_("Unable to execute transaction. " +
  791. self._create_mapset_error_message(mapset)))
  792. return self.connections[mapset].execute_transaction(statement)
  793. def _create_mapset_error_message(self, mapset):
  794. return("You have no permission to "
  795. "access mapset <%(mapset)s>, or "
  796. "mapset <%(mapset)s> has no temporal database. "
  797. "Accessable mapsets are: <%(mapsets)s>" % \
  798. {"mapset": mapset,
  799. "mapsets":','.join(self.tgis_mapsets.keys())})
  800. ###############################################################################
  801. class DBConnection(object):
  802. """This class represents the database interface connection
  803. and provides access to the chosen backend modules.
  804. The following DBMS are supported:
  805. - sqlite via the sqlite3 standard library
  806. - postgresql via psycopg2
  807. """
  808. def __init__(self, backend=None, dbstring=None):
  809. """ Constructor of a database connection
  810. param backend:The database backend sqlite or pg
  811. param dbstring: The database connection string
  812. """
  813. self.connected = False
  814. if backend is None:
  815. global tgis_backend
  816. if tgis_backend == "sqlite":
  817. self.dbmi = sqlite3
  818. else:
  819. self.dbmi = psycopg2
  820. else:
  821. if backend == "sqlite":
  822. self.dbmi = sqlite3
  823. else:
  824. self.dbmi = psycopg2
  825. if dbstring is None:
  826. global tgis_database_string
  827. self.dbstring = tgis_database_string
  828. self.msgr = get_tgis_message_interface()
  829. self.msgr.debug(1, "SQLDatabaseInterfaceConnection constructor")
  830. def __del__(self):
  831. if self.connected is True:
  832. self.close()
  833. def is_connected(self):
  834. return self.connected
  835. def rollback(self):
  836. """
  837. Roll back the last transaction. This must be called
  838. in case a new query should be performed after a db error.
  839. This is only relevant for postgresql database.
  840. """
  841. if self.dbmi.__name__ == "psycopg2":
  842. if self.connected:
  843. self.connection.rollback()
  844. def connect(self, dbstring=None):
  845. """Connect to the DBMI to execute SQL statements
  846. Supported backends are sqlite3 and postgresql
  847. param dbstring: The database connection string
  848. """
  849. # Connection in the current mapset
  850. if dbstring is None:
  851. dbstring = self.dbstring
  852. try:
  853. if self.dbmi.__name__ == "sqlite3":
  854. self.connection = self.dbmi.connect(dbstring,
  855. detect_types=self.dbmi.PARSE_DECLTYPES | self.dbmi.PARSE_COLNAMES)
  856. self.connection.row_factory = self.dbmi.Row
  857. self.connection.isolation_level = None
  858. self.cursor = self.connection.cursor()
  859. self.cursor.execute("PRAGMA synchronous = OFF")
  860. self.cursor.execute("PRAGMA journal_mode = MEMORY")
  861. elif self.dbmi.__name__ == "psycopg2":
  862. self.connection = self.dbmi.connect(dbstring)
  863. #self.connection.set_isolation_level(dbmi.extensions.ISOLATION_LEVEL_AUTOCOMMIT)
  864. self.cursor = self.connection.cursor(
  865. cursor_factory=self.dbmi.extras.DictCursor)
  866. self.connected = True
  867. except Exception as e:
  868. self.msgr.fatal(_("Unable to connect to %(db)s database: "
  869. "%(string)s\nException: \"%(ex)s\"\nPlease use"
  870. " t.connect to set a read- and writable "
  871. "temporal database backend") % (
  872. {"db": self.dbmi.__name__,
  873. "string": tgis_database_string, "ex": e, }))
  874. def close(self):
  875. """Close the DBMI connection
  876. TODO:
  877. There may be several temporal databases in a location, hence
  878. close all temporal databases that have been opened. Use a dictionary
  879. to manage different connections.
  880. """
  881. self.connection.commit()
  882. self.cursor.close()
  883. self.connected = False
  884. def mogrify_sql_statement(self, content):
  885. """Return the SQL statement and arguments as executable SQL string
  886. TODO:
  887. Use the mapset argument to identify the correct database driver
  888. :param content: The content as tuple with two entries, the first
  889. entry is the SQL statement with DBMI specific
  890. place holder (?), the second entry is the argument
  891. list that should substitute the place holder.
  892. :param mapset: The mapset of the abstract dataset or temporal
  893. database location, if None the current mapset
  894. will be used
  895. Usage:
  896. .. code-block:: python
  897. >>> init()
  898. >>> dbif = SQLDatabaseInterfaceConnection()
  899. >>> dbif.mogrify_sql_statement(["SELECT ctime FROM raster_base WHERE id = ?",
  900. ... ["soil@PERMANENT",]])
  901. "SELECT ctime FROM raster_base WHERE id = 'soil@PERMANENT'"
  902. """
  903. sql = content[0]
  904. args = content[1]
  905. if self.dbmi.__name__ == "psycopg2":
  906. if len(args) == 0:
  907. return sql
  908. else:
  909. if self.connected:
  910. try:
  911. return self.cursor.mogrify(sql, args)
  912. except:
  913. print sql, args
  914. raise
  915. else:
  916. self.connect()
  917. statement = self.cursor.mogrify(sql, args)
  918. self.close()
  919. return statement
  920. elif self.dbmi.__name__ == "sqlite3":
  921. if len(args) == 0:
  922. return sql
  923. else:
  924. # Unfortunately as sqlite does not support
  925. # the transformation of sql strings and qmarked or
  926. # named arguments we must make our hands dirty
  927. # and do it by ourself. :(
  928. # Doors are open for SQL injection because of the
  929. # limited python sqlite3 implementation!!!
  930. pos = 0
  931. count = 0
  932. maxcount = 100
  933. statement = sql
  934. while count < maxcount:
  935. pos = statement.find("?", pos + 1)
  936. if pos == -1:
  937. break
  938. if args[count] is None:
  939. statement = "%sNULL%s" % (statement[0:pos],
  940. statement[pos + 1:])
  941. elif isinstance(args[count], (int, long)):
  942. statement = "%s%d%s" % (statement[0:pos], args[count],
  943. statement[pos + 1:])
  944. elif isinstance(args[count], float):
  945. statement = "%s%f%s" % (statement[0:pos], args[count],
  946. statement[pos + 1:])
  947. else:
  948. # Default is a string, this works for datetime
  949. # objects too
  950. statement = "%s\'%s\'%s" % (statement[0:pos],
  951. str(args[count]),
  952. statement[pos + 1:])
  953. count += 1
  954. return statement
  955. def check_table(self, table_name):
  956. """Check if a table exists in the temporal database
  957. :param table_name: The name of the table to be checked for existence
  958. :param mapset: The mapset of the abstract dataset or temporal
  959. database location, if None the current mapset
  960. will be used
  961. :returns: True if the table exists, False otherwise
  962. TODO:
  963. There may be several temporal databases in a location, hence
  964. the mapset is used to query the correct temporal database.
  965. """
  966. table_exists = False
  967. connected = False
  968. if not self.connected:
  969. self.connect()
  970. connected = True
  971. # Check if the database already exists
  972. if self.dbmi.__name__ == "sqlite3":
  973. self.cursor.execute("SELECT name FROM sqlite_master WHERE "
  974. "type='table' AND name='%s';" % table_name)
  975. name = self.cursor.fetchone()
  976. if name and name[0] == table_name:
  977. table_exists = True
  978. else:
  979. # Check for raster_base table
  980. self.cursor.execute("SELECT EXISTS(SELECT * FROM information_schema.tables "
  981. "WHERE table_name=%s)", ('%s' % table_name,))
  982. if self.cursor.fetchone()[0]:
  983. table_exists = True
  984. if connected:
  985. self.close()
  986. return table_exists
  987. def execute(self, statement, args=None):
  988. """Execute a SQL statement
  989. :param statement: The executable SQL statement or SQL script
  990. """
  991. connected = False
  992. if not self.connected:
  993. self.connect()
  994. connected = True
  995. try:
  996. if args:
  997. self.cursor.execute(statement, args)
  998. else:
  999. self.cursor.execute(statement)
  1000. except:
  1001. if connected:
  1002. self.close()
  1003. self.msgr.error(_("Unable to execute :\n %(sql)s" %
  1004. {"sql": statement}))
  1005. raise
  1006. if connected:
  1007. self.close()
  1008. def fetchone(self):
  1009. if self.connected:
  1010. return self.cursor.fetchone()
  1011. return None
  1012. def fetchall(self):
  1013. if self.connected:
  1014. return self.cursor.fetchall()
  1015. return None
  1016. def execute_transaction(self, statement, mapset=None):
  1017. """Execute a transactional SQL statement
  1018. The BEGIN and END TRANSACTION statements will be added automatically
  1019. to the sql statement
  1020. :param statement: The executable SQL statement or SQL script
  1021. """
  1022. connected = False
  1023. if not self.connected:
  1024. self.connect()
  1025. connected = True
  1026. sql_script = ""
  1027. sql_script += "BEGIN TRANSACTION;\n"
  1028. sql_script += statement
  1029. sql_script += "END TRANSACTION;"
  1030. try:
  1031. if self.dbmi.__name__ == "sqlite3":
  1032. self.cursor.executescript(statement)
  1033. else:
  1034. self.cursor.execute(statement)
  1035. self.connection.commit()
  1036. except:
  1037. if connected:
  1038. self.close()
  1039. self.msgr.error(_("Unable to execute transaction:\n %(sql)s" %
  1040. {"sql": statement}))
  1041. raise
  1042. if connected:
  1043. self.close()
  1044. ###############################################################################
  1045. def init_dbif(dbif):
  1046. """This method checks if the database interface connection exists,
  1047. if not a new one will be created, connected and True will be returned.
  1048. If the database interface exists but is connected, the connection will
  1049. be established.
  1050. :returns: the tuple (dbif, True|False)
  1051. Usage code sample:
  1052. .. code-block:: python
  1053. dbif, connect = tgis.init_dbif(None)
  1054. sql = dbif.mogrify_sql_statement(["SELECT * FROM raster_base WHERE ? = ?"],
  1055. ["id", "soil@PERMANENT"])
  1056. dbif.execute_transaction(sql)
  1057. if connect:
  1058. dbif.close()
  1059. """
  1060. if dbif is None:
  1061. dbif = SQLDatabaseInterfaceConnection()
  1062. dbif.connect()
  1063. return dbif, True
  1064. elif dbif.is_connected() is False:
  1065. dbif.connect()
  1066. return dbif, True
  1067. return dbif, False
  1068. ###############################################################################
  1069. if __name__ == "__main__":
  1070. import doctest
  1071. doctest.testmod()