Welcome, guest | Sign In | My Account | Store | Cart

A wrapper script for mysqldump that allows to dump a database excluding some tables.

Python, 144 lines
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
#!/export/home/www.netuni.nl/local/bin/python

import sys, os, getopt, getpass
import MySQLdb

def ohmysqldump(db, user, passwd, excluded, options, host=''):
    conn = MySQLdb.connect(host='', db=db, user=user, passwd=passwd)
    c = conn.cursor()
    sql = 'show tables;'
    c.execute(sql)
    tables = c.fetchall()
    conn.close()
    arguments = [db]
    for table in tables:
        try:
            if not table[0] in excluded:
                arguments.append(table[0])
        except:
            print "You cannot exclude non-existing tables."
            sys.exit(1)
    arguments.insert(0, "mysqldump")
    command = 'mysqldump'
    os.execvp(command, arguments)

def usage():
    print """

ohmysqldump is a wrapper for mysqldump including an option to dump a
mysqldatabase EXCEPT the listed tables.

Usage: [OPTIONS] [database] [tables]

  -E, exclude           Exclude the tables
  
The -p and --password options in mysqldump has an optional argument. This
technique isn't supported (consider -p database table. Is 'database' a
password? Or is it the name of the database?). You can store the password in
an optionfile (~/.my.cnf) or ohmysqldump will ask for it (twice).

All (other) options in mysqldump are supported. 
    """
    #mysqldump --help follows:
    #os.execvp("mysqldump", ["mysqldump", "--help"])

def main():

    shortoptions = "aAB#:?cCeEFOfh:lKntdpP:qQS:Tu:vVw:Xx"
    
    longoptions = ["all", "debug=", "character-sets-dir=", "help", "complete-insert", \
    "compress", "default-character-set=", "extended-insert", "add-drop-table", \
    "add-locks", "allow-keywords", "delayed-insert", "master-data", "flush-logs", \
    "force", "host=", "lock-tables", "no-autocommit", "disable-keys", \
    "no-create-db", "no-create-info" "no-data", "opt", "password=", "port=", \
    "quick", "quote-names", "socket=", "tab=", "user=", "verbose", "version", \
    "where=", "xml", "first-slave" "fields-terminated-by=", \
    "fields-enclosed-by=", "fields-optionally-enclosed-by=", \
    "fields-escaped-by=", "lines-terminated-by=", "all-databases", \
    "databases", "tables", "exclude"]

    #Try to find additional info in the mysql option-files
    f = os.popen("my_print_defaults client mysqldump")
    myoptions = f.readlines()
    f.close
    for line in myoptions:
        if len(line):
            # Inject it into the commandline for easy parding by getopt
            # Inject it in front so any commandline-parameters will override
            # the optionfile
            sys.argv.insert(1,line.replace("\n",""))

    try:
        opts, args = getopt.getopt(sys.argv[1:], shortoptions, longoptions)
    except getopt.GetoptError:
        #print "error"
        # print help information and exit
        usage()
        sys.exit(2)
        
    if not opts and not args:
        usage()
        sys.exit()

    options = []
    
    runohmy = 0
    askpasswd = 0
    
    db=""
    user = ""
    host=""
    passwd = ""

    for opt, arg in opts:
        # Catch some options to handle here
        if opt in ["-?", "--help"]:
            usage()
        elif opt in ["-E", "--exclude"]:
            runohmy = 1
            if len(args)>1:
                db = args[0]
                excluded = args[1:]
                # Don' pass it along
                continue
            else:
                usage()
                sys.exit(1)
        elif opt in ["-p", "--password"]:
            if arg:
                passwd = arg
            else:
                askpasswd = 1
        elif opt in ["-u", "--user"]:
            user = arg
        elif opt in ["-h", "--host"]:
            host = arg
        elif opt in ["-V", "--version"]:
            print "ohmysqldump v0.3"
            os.execvp("mysqldump", ["mysqldump", "--version"])

        if opt[2:]+"=" in longoptions:
            options.append(opt+"="+arg)
        elif opt[1:]+":" in shortoptions:
            options.append(opt)
            options.append(arg)
        else:
            options.append(opt+arg)

    if not runohmy:
        options.insert(0, "mysqldump")
        command = 'mysqldump'
        for arg in args:
            options.append(arg)
        os.execvp(command, options)
    else:
        if (not passwd and askpasswd):
            passwd = getpass.getpass("password: ")
        if not (user and (passwd and not askpasswd) and db and excluded):
            usage()
            sys.exit(1)
        else:
            ohmysqldump(db, user, passwd, excluded, options, host='')

if __name__ == "__main__":
    main();

1 comment

George Lambert 16 years, 5 months ago  # | flag

BUGFIX.

# BUGFIX 2007-10-28 - marchon(at)gmail.com - ONLY ADD OPTIONS IF THEY ARE IN THE ABOVE LIST
# Added this IF LINE
            if line in longoptions:
# before
               sys.argv.insert(1,line.replace("\n",""))