core.py 53 KB

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