root/livinglogic.python.xist/src/ll/orasql/scripts/oradrop.py @ 4447:5ff2593c0dd8

Revision 4447:5ff2593c0dd8, 5.5 KB (checked in by Walter Doerwald <walter@…>, 8 years ago)

Docstring for oradelete. Fix typos.

Line 
1#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3
4## Copyright 2005-2011 by LivingLogic AG, Bayreuth/Germany.
5## Copyright 2005-2011 by Walter Dörwald
6##
7## All Rights Reserved
8##
9## See orasql/__init__.py for the license
10
11
12"""
13Purpose
14-------
15
16``oradrop`` prints the drop statements for all objects in an Oracle database
17schema in the correct order (i.e. objects will be dropped so that no errors
18happen during script execution). ``oradrop`` can also be used to actually
19make the schema empty.
20
21
22Options
23-------
24
25``oradrop`` supports the following options:
26
27    ``connectstring``
28        An Oracle connectstring.
29
30    ``-v``, ``--verbose`` : ``false``, ``no``, ``0``, ``true``, ``yes`` or ``1``
31        Produces output (on stderr) while to datebase is read or written.
32
33    ``-c``, ``--color`` : ``yes``, ``no`` or ``auto``
34        Should the output (when the ``-v`` option is used) be colored. If ``auto``
35        is specified (the default) then the output is colored if stderr is a
36        terminal.
37
38    ``-f``, ``--fks`` : ``keep``, ``disable``, ``drop``
39        Specifies how foreign keys from other schemas pointing to this schema
40        should be treated: ``keep`` will now change the foreign keys in any way
41        (this *will* lead to errors); ``disable`` will disable the foreign keys
42        and ``drop`` will drop them completely.
43
44    ``-x``, ``--execute`` : ``false``, ``no``, ``0``, ``true``, ``yes`` or ``1``
45        When the ``-x`` argument is given the SQL script isn't printed on stdout,
46        but is executed directly. Be careful with this: You *will* have an empty
47        schema after ``oradrop -x``.
48
49    ``-k``, ``--keepjunk`` : ``false``, ``no``, ``0``, ``true``, ``yes`` or ``1``
50        If given, database objects that have ``$`` or ``SYS_EXPORT_SCHEMA_`` in
51        their name will be skipped (otherwise these objects will be included in
52        the output).
53
54    ``-i``, ``--ignore`` : ``false``, ``no``, ``0``, ``true``, ``yes`` or ``1``
55        If given, errors occuring while the database is read or written will be
56        ignored.
57
58    ``-e``, ``--encoding`` : encoding
59        The encoding of the output (if ``-x`` is not given; default is ``utf-8``).
60"""
61
62
63import sys, os, argparse
64
65from ll import misc, astyle, orasql
66
67
68__docformat__ = "reStructuredText"
69
70
71s4warning = astyle.Style.fromenv("LL_ORASQL_REPRANSI_WARNING", "red:black")
72s4error = astyle.Style.fromenv("LL_ORASQL_REPRANSI_ERROR", "red:black")
73s4connectstring = astyle.Style.fromenv("LL_ORASQL_REPRANSI_CONNECTSTRING", "yellow:black")
74s4object = astyle.Style.fromenv("LL_ORASQL_REPRANSI_OBJECT", "green:black")
75
76
77def main(args=None):
78    p = argparse.ArgumentParser(description="Print (or execute) drop statements for all objects in an Oracle database schema")
79    p.add_argument("connectstring", help="Oracle connect string")
80    p.add_argument("-v", "--verbose", dest="verbose", help="Give a progress report? (default %(default)s)", action=misc.FlagAction, default=False)
81    p.add_argument("-c", "--color", dest="color", help="Color output (default %(default)s)", default="auto", choices=("yes", "no", "auto"))
82    p.add_argument("-f", "--fks", dest="fks", help="How should foreign keys from other schemas be treated? (default %(default)s)", default="disable", choices=("keep", "disable", "drop"))
83    p.add_argument("-x", "--execute", dest="execute", help="immediately execute the commands instead of printing them? (default %(default)s)", action=misc.FlagAction, default=False)
84    p.add_argument("-k", "--keepjunk", dest="keepjunk", help="Output objects with '$' in their name? (default %(default)s)", action=misc.FlagAction, default=False)
85    p.add_argument("-i", "--ignore", dest="ignore", help="Ignore errors? (default %(default)s)", default=False, action=misc.FlagAction)
86    p.add_argument("-e", "--encoding", dest="encoding", help="Encoding for output (default %(default)s)", default="utf-8")
87
88    args = p.parse_args(args)
89
90    if args.color == "yes":
91        color = True
92    elif args.color == "no":
93        color = False
94    else:
95        color = None
96
97    stdout = astyle.Stream(sys.stdout, color)
98    stderr = astyle.Stream(sys.stderr, color)
99
100    connection = orasql.connect(args.connectstring)
101
102    term = not args.execute
103
104    cs = s4connectstring(connection.connectstring())
105
106    def keep(obj):
107        if obj.owner is not None and not isinstance(obj, orasql.ForeignKey):
108            return False
109        if args.keepjunk:
110            return True
111        if "$" in obj.name:
112            return False
113        return True
114
115    ddls = []
116    for (i, obj) in enumerate(connection.iterobjects(mode="drop", schema="user")):
117        keepdef = keep(obj)
118        # Get DDL
119        ddl = ""
120        action = "skipped"
121        if obj.owner is not None:
122            if isinstance(obj, orasql.ForeignKey):
123                if args.fks == "disable":
124                    ddl = obj.disableddl(cursor, term)
125                    action = "disabled"
126                elif args.fks == "drop":
127                    ddl = obj.dropddl(cursor, term)
128                    action = None
129        elif keepdef:
130            ddl = obj.dropddl(connection, term)
131            action = None
132
133        # Progress report
134        if args.verbose:
135            msg = astyle.style_default("oradrop.py: ", cs, ": fetching #{} ".format(i+1), s4object(str(obj)))
136            if action is not None:
137                msg = astyle.style_default(msg, " ", s4warning("({})".format(action)))
138            stderr.writeln(msg)
139
140        if ddl:
141            # Print or execute DDL
142            if args.execute:
143                ddls.append((obj, ddl))
144            else:
145                stdout.write(ddl.encode(args.encoding))
146
147    # Execute DDL
148    if args.execute:
149        cursor = connection.cursor()
150        for (i, (obj, ddl)) in enumerate(ddls):
151            if args.verbose:
152                stderr.writeln("oradrop.py: ", cs, ": dropping #{}/{} ".format(i+1, len(ddls)), s4object(str(obj)))
153            try:
154                cursor.execute(ddl)
155            except orasql.DatabaseError, exc:
156                if not args.ignore or "ORA-01013" in str(exc):
157                    raise
158                stderr.writeln("oradrop.py: ", s4error("{}: {}".format(exc.__class__, str(exc).strip())))
159
160
161if __name__ == "__main__":
162    sys.exit(main())
Note: See TracBrowser for help on using the browser.