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

Revision 4447:5ff2593c0dd8, 5.6 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``oracreate`` prints the DDL of all objects in an Oracle database schema in a
17way that can be used to recreate the schema (i.e. objects will be ordered so
18that no errors happen for non-existant objects during script execution).
19``oracreate`` can also be used to actually recreate the schema.
20
21
22Options
23-------
24
25``oracreate`` 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    ``-s``, ``--seqcopy`` : ``false``, ``no``, ``0``, ``true``, ``yes`` or ``1``
39        Outputs ``CREATE SEQUENCE`` statements for the existing sequences that have
40        the current value of the sequence as the starting value. (Otherwise the
41        sequences will restart with their initial value)
42
43    ``-x``, ``--execute`` : connectstring
44        When the ``-x`` argument is given the SQL script isn't printed on stdout,
45        but executed in the database specfied as the ``-x`` argument.
46
47    ``-k``, ``--keepjunk`` : ``false``, ``no``, ``0``, ``true``, ``yes`` or ``1``
48        If given, database objects that have ``$`` or ``SYS_EXPORT_SCHEMA_`` in
49        their name will be skipped (otherwise these objects will be included).
50
51    ``-i``, ``--ignore`` : ``false``, ``no``, ``0``, ``true``, ``yes`` or ``1``
52        If given, errors occuring while the database is read or written will be
53        ignored.
54
55    ``-e``, ``--encoding`` : encoding
56        The encoding of the output (if ``-x`` is not given; default is ``utf-8``).
57
58
59Examples
60--------
61
62Print the content of the database schema ``user@db``::
63
64    $ oracreate user/pwd@db >db.sql
65
66Copy the database schema ``user@db`` to ``user2@db2``::
67
68    $ oracreate user/pwd@db -x user2/pwd2@db2 -v
69"""
70
71
72import sys, os, argparse
73
74from ll import misc, astyle, orasql
75
76
77__docformat__ = "reStructuredText"
78
79
80s4warning = astyle.Style.fromenv("LL_ORASQL_REPRANSI_WARNING", "red:black")
81s4error = astyle.Style.fromenv("LL_ORASQL_REPRANSI_ERROR", "red:black")
82s4connectstring = astyle.Style.fromenv("LL_ORASQL_REPRANSI_CONNECTSTRING", "yellow:black")
83s4object = astyle.Style.fromenv("LL_ORASQL_REPRANSI_OBJECT", "green:black")
84
85
86def main(args=None):
87    p = argparse.ArgumentParser(description="Print (or execute) the DDL of all objects in an Oracle database schema")
88    p.add_argument("connectstring", help="Oracle connect string")
89    p.add_argument("-v", "--verbose", dest="verbose", help="Give a progress report? (default %(default)s)", default=False, action=misc.FlagAction)
90    p.add_argument("-c", "--color", dest="color", help="Color output (default %(default)s)", default="auto", choices=("yes", "no", "auto"))
91    p.add_argument("-s", "--seqcopy", dest="seqcopy", help="copy sequence values? (default %(default)s)", default=False, action=misc.FlagAction)
92    p.add_argument("-x", "--execute", metavar="CONNECTSTRING2", dest="execute", help="Execute in target database")
93    p.add_argument("-k", "--keepjunk", dest="keepjunk", help="Output objects with '$' or 'SYS_EXPORT_SCHEMA_' in their name? (default %(default)s)", default=False, action=misc.FlagAction)
94    p.add_argument("-i", "--ignore", dest="ignore", help="Ignore errors? (default %(default)s)", default=False, action=misc.FlagAction)
95    p.add_argument("-e", "--encoding", dest="encoding", help="Encoding for output (default %(default)s)", default="utf-8")
96
97    args = p.parse_args(args)
98
99    if args.color == "yes":
100        color = True
101    elif args.color == "no":
102        color = False
103    else:
104        color = None
105    stdout = astyle.Stream(sys.stdout, color)
106    stderr = astyle.Stream(sys.stderr, color)
107
108    connection = orasql.connect(args.connectstring)
109
110    if args.execute:
111        connection2 = orasql.connect(args.execute)
112        cursor2 = connection2.cursor()
113        term = False
114    else:
115        term = True
116
117    cs1 = s4connectstring(connection.connectstring())
118    if args.execute:
119        cs2 = s4connectstring(connection2.connectstring())
120
121    def keep(obj):
122        if obj.owner is not None:
123            return False
124        if args.keepjunk:
125            return True
126        # output pk, fks etc. only when they belong to a table we do output
127        if isinstance(obj, (orasql.Constraint, orasql.Index)):
128            obj = obj.table()
129        if "$" in obj.name or obj.name.startswith("SYS_EXPORT_SCHEMA_"):
130            return False
131        return True
132
133    for (i, obj) in enumerate(connection.iterobjects(mode="create", schema="user")):
134        keepobj = keep(obj)
135        if args.verbose:
136            if args.execute:
137                msg = astyle.style_default("oracreate.py: ", cs1, " -> ", cs2, ": fetching/creating #{}".format(i+1))
138            else:
139                msg = astyle.style_default("oracreate.py: ", cs1, " fetching #{}".format(i+1))
140            msg = astyle.style_default(msg, " ", s4object(str(obj)))
141            if not keepobj:
142                msg = astyle.style_default(msg, " ", s4warning("(skipped)"))
143            stderr.writeln(msg)
144
145        if keepobj:
146            if isinstance(obj, orasql.Sequence) and args.seqcopy:
147                ddl = obj.createddlcopy(connection, term)
148            else:
149                ddl = obj.createddl(connection, term)
150            if ddl:
151                if args.execute:
152                    try:
153                        cursor2.execute(ddl)
154                    except orasql.DatabaseError, exc:
155                        if not args.ignore or "ORA-01013" in str(exc):
156                            raise
157                        stderr.writeln("oracreate.py: ", s4error("{}: {}".format(exc.__class__.__name__, str(exc).strip())))
158                else:
159                    stdout.writeln(ddl.encode(args.encoding))
160                    stdout.writeln()
161
162
163if __name__ == "__main__":
164    sys.exit(main())
Note: See TracBrowser for help on using the browser.