core.py 53 KB

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