Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1#!/usr/local/bin/python 

2# encoding: utf-8 

3""" 

4*Probe a database to determine if a given table exists* 

5 

6:Author: 

7 David Young 

8""" 

9import sys 

10import os 

11os.environ['TERM'] = 'vt100' 

12from fundamentals import tools 

13from fundamentals.mysql import readquery 

14 

15def table_exists( 

16 dbConn, 

17 log, 

18 dbTableName): 

19 """*Probe a database to determine if a given table exists* 

20 

21 **Key Arguments** 

22 

23 - ``dbConn`` -- mysql database connection 

24 - ``log`` -- logger 

25 - ``dbTableName`` -- the database tablename 

26  

27 

28 **Return** 

29 

30 - ``tableExists`` -- True or False 

31  

32 

33 **Usage** 

34 

35 To test if a table exists in a database: 

36 

37 ```python 

38 from fundamentals.mysql import table_exists 

39 exists = table_exists( 

40 dbConn=dbConn, 

41 log=log, 

42 dbTableName="stupid_named_table" 

43 ) 

44 

45 print exists 

46 

47 # OUTPUT: False 

48 ``` 

49  

50 """ 

51 log.debug('starting the ``table_exists`` function') 

52 

53 sqlQuery = u""" 

54 SELECT count(*) 

55 FROM information_schema.tables 

56 WHERE table_name = '%(dbTableName)s' 

57 """ % locals() 

58 tableExists = readquery( 

59 log=log, 

60 sqlQuery=sqlQuery, 

61 dbConn=dbConn, 

62 quiet=False 

63 ) 

64 

65 if tableExists[0]["count(*)"] == 0: 

66 tableExists = False 

67 else: 

68 tableExists = True 

69 

70 log.debug('completed the ``table_exists`` function') 

71 return tableExists