Class SchemaTool


  • public class SchemaTool
    extends java.lang.Object
    The SchemaTool is used to manage the database schema. Note that the tool never adds or drops unique constraints from existing tables, because JDBC DatabaseMetaData does not include information on these constraints.
    Author:
    Abe White, Patrick Linskey
    • Nested Class Summary

      Nested Classes 
      Modifier and Type Class Description
      static class  SchemaTool.Flags
      Run flags.
    • Method Summary

      All Methods Static Methods Instance Methods Concrete Methods 
      Modifier and Type Method Description
      protected void add()
      Adds any components present in the schema repository but absent from the database.
      protected void add​(SchemaGroup db, SchemaGroup repos)
      Adds all database components in the repository schema that are not present in the given database schema to the database.
      boolean addColumn​(Column col)
      Add the given column to the database schema.
      boolean addForeignKey​(ForeignKey fk)
      Add the given foreign key to the database schema.
      boolean addPrimaryKey​(PrimaryKey pk)
      Add the given primary key to the database schema.
      protected SchemaGroup assertSchemaGroup()  
      protected void build()
      Re-execute all SQL used for the creation of the current database; this action is usually used when creating SQL scripts.
      protected void buildSchema​(SchemaGroup db, SchemaGroup repos, boolean considerDatabaseState)  
      void clear()
      Cleanup DataSource after run()/record()
      protected void createDB()
      Re-execute all SQL used for the creation of the current database; this action is usually used when creating SQL scripts.
      boolean createIndex​(Index idx, Table table)
      Add the given index to the database schema.
      boolean createIndex​(Index idx, Table table, Unique[] uniques)  
      boolean createSequence​(Sequence seq)
      Add the given sequence to the database schema.
      boolean createTable​(Table table)
      Add the given table to the database schema.
      protected void deleteTableContents()
      Issue DELETE statement against all known tables.
      protected void drop()
      Drops all schema components in the schema repository that also exist in the database.
      protected void drop​(SchemaGroup db, SchemaGroup repos)  
      boolean dropColumn​(Column col)
      Drop the given column from the database schema.
      protected void dropDB()
      Drop the current database.
      boolean dropForeignKey​(ForeignKey fk)
      Drop the given foreign key from the database schema.
      boolean dropIndex​(Index idx)
      Drop the given index from the database schema.
      boolean dropPrimaryKey​(PrimaryKey pk)
      Drop the given primary key from the database schema.
      protected void dropSchema()
      Drops all schema components in the schema repository.
      boolean dropSequence​(Sequence seq)
      Drop the given sequence from the database schema.
      boolean dropTable​(Table table)
      Drop the given table from the database schema.
      protected void dropTables​(java.util.Collection<Table> tables, SchemaGroup change)
      Remove the given collection of tables from the database schema.
      protected void executeScript()  
      protected boolean executeSQL​(java.lang.String[] sql)
      Executes the given array of non-selecting SQL statements, correctly logging the SQL calls and optionally ignoring errors.
      protected ForeignKey findForeignKey​(Table dbTable, ForeignKey fk)
      Find a foreign key in the given table that matches the given one.
      protected Index findIndex​(Table dbTable, Index idx)
      Find an index in the given table that matches the given one.
      java.lang.String getAction()
      The action supplied on construction.
      SchemaGroup getDBSchemaGroup()
      Return the database schema.
      protected SchemaGroup getDBSchemaGroup​(boolean full)
      Return the database schema.
      boolean getDropSequences()
      If true, sequences that appear to be unused will be dropped.
      boolean getDropTables()
      If true, tables that appear to be unused will be dropped.
      boolean getForeignKeys()
      Whether foreign keys on existing tables should be manipulated.
      boolean getIgnoreErrors()
      If true, SQLExceptions thrown during schema manipulation will be printed but ignored.
      boolean getIndexes()
      Whether indexes on existing tables should be manipulated.
      boolean getOpenJPATables()
      Whether to act on special tables used by OpenJPA components for bookkeeping.
      boolean getPrimaryKeys()
      Whether primary keys on existing tables should be manipulated.
      boolean getRollbackBeforeDDL()
      If true, rollback will be performed before each DDL statement is executed.
      SchemaGroup getSchemaGroup()
      Return the schema group the tool will act on.
      boolean getSequences()
      Whether sequences should be manipulated.
      java.io.Writer getWriter()
      The stream to write to for the creation of SQL scripts.
      protected void handleException​(java.sql.SQLException sql)
      Handle the given exception, logging it and optionally ignoring it, depending on the flags this SchemaTool was created with.
      protected boolean isDroppable​(Sequence seq)
      Return true if the sequence is droppable.
      protected boolean isDroppable​(Table table)
      Return true if the table is droppable.
      static void main​(java.lang.String[] args)
      Usage: java org.apache.openjpa.jdbc.schema.SchemaTool [option]* [-action/-a <add | retain | drop | refresh | createDB | dropDB | build | reflect | import | export>] <.schema file or resource>* Where the following options are recognized.
      void record()
      Record the changes made to the DB in the current SchemaFactory.
      protected void refresh()
      Adds any components present in the schema repository but absent from the database, and drops unused database components.
      protected void retain()
      Drops database components that are not mentioned in the schema repository.
      protected void retain​(SchemaGroup db, SchemaGroup repos, boolean tables, boolean sequences)
      Drops all database components that are in the given database schema but not in the repository schema.
      void run()
      Run the tool action.
      static boolean run​(JDBCConfiguration conf, java.lang.String[] args, SchemaTool.Flags flags, java.lang.ClassLoader loader)
      Run the tool.
      static boolean run​(JDBCConfiguration conf, java.lang.String[] args, Options opts)
      Run the tool.
      void setDBSchemaGroup​(SchemaGroup db)
      Set the database schema.
      void setDropSequences​(boolean dropSeqs)
      If true, sequences that appear to be unused will be dropped.
      void setDropTables​(boolean dropTables)
      If true, tables that appear to be unused will be dropped.
      void setForeignKeys​(boolean fks)
      Whether foreign keys on existing tables should be manipulated.
      void setIgnoreErrors​(boolean ignoreErrs)
      If true, SQLExceptions thrown during schema manipulation will be printed but ignored.
      void setIndexes​(boolean indexes)
      Whether indexes on existing tables should be manipulated.
      void setOpenJPATables​(boolean openjpaTables)
      Whether to act on special tables used by OpenJPA components for bookkeeping.
      void setPrimaryKeys​(boolean pks)
      Whether primary keys on existing tables should be manipulated.
      void setRollbackBeforeDDL​(boolean rollbackBeforeDDL)
      If true, rollback will be performed before each DDL statement is executed.
      void setSchemaGroup​(SchemaGroup group)
      Set the schema group the tool will act on.
      void setScriptToExecute​(java.lang.String scriptToExecute)  
      void setSequences​(boolean seqs)
      Whether sequences should be manipulated.
      void setSQLTerminator​(java.lang.String t)  
      void setWriter​(java.io.Writer writer)
      The stream to write to for the creation of SQL scripts.
      • Methods inherited from class java.lang.Object

        clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
    • Field Detail

      • ACTION_DROP_SCHEMA

        public static final java.lang.String ACTION_DROP_SCHEMA
        See Also:
        Constant Field Values
      • ACTION_DELETE_TABLE_CONTENTS

        public static final java.lang.String ACTION_DELETE_TABLE_CONTENTS
        See Also:
        Constant Field Values
      • ACTION_EXECUTE_SCRIPT

        public static final java.lang.String ACTION_EXECUTE_SCRIPT
        See Also:
        Constant Field Values
      • ACTIONS

        public static final java.lang.String[] ACTIONS
      • _loc

        protected static final Localizer _loc
      • _ds

        protected final javax.sql.DataSource _ds
      • _log

        protected final Log _log
      • _fullDB

        protected boolean _fullDB
      • _sqlTerminator

        protected java.lang.String _sqlTerminator
      • _scriptToExecute

        protected java.lang.String _scriptToExecute
    • Constructor Detail

      • SchemaTool

        public SchemaTool​(JDBCConfiguration conf)
        Default constructor. Tools constructed this way will not have an action, so the run() method will be a no-op.
      • SchemaTool

        public SchemaTool​(JDBCConfiguration conf,
                          java.lang.String action)
        Construct a tool to perform the given action.
    • Method Detail

      • clear

        public void clear()
        Cleanup DataSource after run()/record()
      • getAction

        public java.lang.String getAction()
        The action supplied on construction.
      • getIgnoreErrors

        public boolean getIgnoreErrors()
        If true, SQLExceptions thrown during schema manipulation will be printed but ignored.
      • setIgnoreErrors

        public void setIgnoreErrors​(boolean ignoreErrs)
        If true, SQLExceptions thrown during schema manipulation will be printed but ignored.
      • getOpenJPATables

        public boolean getOpenJPATables()
        Whether to act on special tables used by OpenJPA components for bookkeeping.
      • setOpenJPATables

        public void setOpenJPATables​(boolean openjpaTables)
        Whether to act on special tables used by OpenJPA components for bookkeeping.
      • getDropTables

        public boolean getDropTables()
        If true, tables that appear to be unused will be dropped. Defaults to true.
      • setDropTables

        public void setDropTables​(boolean dropTables)
        If true, tables that appear to be unused will be dropped. Defaults to true.
      • getDropSequences

        public boolean getDropSequences()
        If true, sequences that appear to be unused will be dropped. Defaults to true.
      • setDropSequences

        public void setDropSequences​(boolean dropSeqs)
        If true, sequences that appear to be unused will be dropped. Defaults to true.
      • getRollbackBeforeDDL

        public boolean getRollbackBeforeDDL()
        If true, rollback will be performed before each DDL statement is executed. Defaults to true.
      • setRollbackBeforeDDL

        public void setRollbackBeforeDDL​(boolean rollbackBeforeDDL)
        If true, rollback will be performed before each DDL statement is executed. Defaults to true.
      • getSequences

        public boolean getSequences()
        Whether sequences should be manipulated. Defaults to true.
      • setSequences

        public void setSequences​(boolean seqs)
        Whether sequences should be manipulated. Defaults to true.
      • getIndexes

        public boolean getIndexes()
        Whether indexes on existing tables should be manipulated. Defaults to true.
      • setIndexes

        public void setIndexes​(boolean indexes)
        Whether indexes on existing tables should be manipulated. Defaults to true.
      • getForeignKeys

        public boolean getForeignKeys()
        Whether foreign keys on existing tables should be manipulated. Defaults to true.
      • setForeignKeys

        public void setForeignKeys​(boolean fks)
        Whether foreign keys on existing tables should be manipulated. Defaults to true.
      • getPrimaryKeys

        public boolean getPrimaryKeys()
        Whether primary keys on existing tables should be manipulated. Defaults to true.
      • setPrimaryKeys

        public void setPrimaryKeys​(boolean pks)
        Whether primary keys on existing tables should be manipulated. Defaults to true.
      • getWriter

        public java.io.Writer getWriter()
        The stream to write to for the creation of SQL scripts. If the stream is non-null, all SQL will be written to this stream rather than executed against the database.
      • setWriter

        public void setWriter​(java.io.Writer writer)
        The stream to write to for the creation of SQL scripts. If the stream is non-null, all SQL will be written to this stream rather than executed against the database.
      • setSQLTerminator

        public void setSQLTerminator​(java.lang.String t)
      • setScriptToExecute

        public void setScriptToExecute​(java.lang.String scriptToExecute)
      • getSchemaGroup

        public SchemaGroup getSchemaGroup()
        Return the schema group the tool will act on.
      • setSchemaGroup

        public void setSchemaGroup​(SchemaGroup group)
        Set the schema group the tool will act on.
      • run

        public void run()
                 throws java.sql.SQLException
        Run the tool action.
        Throws:
        java.sql.SQLException
      • add

        protected void add()
                    throws java.sql.SQLException
        Adds any components present in the schema repository but absent from the database.
        Throws:
        java.sql.SQLException
      • drop

        protected void drop()
                     throws java.sql.SQLException
        Drops all schema components in the schema repository that also exist in the database.
        Throws:
        java.sql.SQLException
      • dropSchema

        protected void dropSchema()
                           throws java.sql.SQLException
        Drops all schema components in the schema repository.
        Throws:
        java.sql.SQLException
      • retain

        protected void retain()
                       throws java.sql.SQLException
        Drops database components that are not mentioned in the schema repository.
        Throws:
        java.sql.SQLException
      • refresh

        protected void refresh()
                        throws java.sql.SQLException
        Adds any components present in the schema repository but absent from the database, and drops unused database components.
        Throws:
        java.sql.SQLException
      • createDB

        protected void createDB()
                         throws java.sql.SQLException
        Re-execute all SQL used for the creation of the current database; this action is usually used when creating SQL scripts.
        Throws:
        java.sql.SQLException
      • build

        protected void build()
                      throws java.sql.SQLException
        Re-execute all SQL used for the creation of the current database; this action is usually used when creating SQL scripts.
        Throws:
        java.sql.SQLException
      • dropDB

        protected void dropDB()
                       throws java.sql.SQLException
        Drop the current database.
        Throws:
        java.sql.SQLException
      • deleteTableContents

        protected void deleteTableContents()
                                    throws java.sql.SQLException
        Issue DELETE statement against all known tables.
        Throws:
        java.sql.SQLException
      • executeScript

        protected void executeScript()
                              throws java.sql.SQLException
        Throws:
        java.sql.SQLException
      • record

        public void record()
        Record the changes made to the DB in the current SchemaFactory.
      • add

        protected void add​(SchemaGroup db,
                           SchemaGroup repos)
                    throws java.sql.SQLException
        Adds all database components in the repository schema that are not present in the given database schema to the database.
        Throws:
        java.sql.SQLException
      • buildSchema

        protected void buildSchema​(SchemaGroup db,
                                   SchemaGroup repos,
                                   boolean considerDatabaseState)
                            throws java.sql.SQLException
        Throws:
        java.sql.SQLException
      • retain

        protected void retain​(SchemaGroup db,
                              SchemaGroup repos,
                              boolean tables,
                              boolean sequences)
                       throws java.sql.SQLException
        Drops all database components that are in the given database schema but not in the repository schema.
        Throws:
        java.sql.SQLException
      • drop

        protected void drop​(SchemaGroup db,
                            SchemaGroup repos)
                     throws java.sql.SQLException
        Throws:
        java.sql.SQLException
      • isDroppable

        protected boolean isDroppable​(Table table)
        Return true if the table is droppable.
      • isDroppable

        protected boolean isDroppable​(Sequence seq)
        Return true if the sequence is droppable.
      • findIndex

        protected Index findIndex​(Table dbTable,
                                  Index idx)
        Find an index in the given table that matches the given one.
      • findForeignKey

        protected ForeignKey findForeignKey​(Table dbTable,
                                            ForeignKey fk)
        Find a foreign key in the given table that matches the given one.
      • dropTables

        protected void dropTables​(java.util.Collection<Table> tables,
                                  SchemaGroup change)
                           throws java.sql.SQLException
        Remove the given collection of tables from the database schema. Orders the removals according to foreign key constraints on the tables.
        Throws:
        java.sql.SQLException
      • createTable

        public boolean createTable​(Table table)
                            throws java.sql.SQLException
        Add the given table to the database schema.
        Returns:
        true if the operation was successful, false otherwise
        Throws:
        java.sql.SQLException
      • dropTable

        public boolean dropTable​(Table table)
                          throws java.sql.SQLException
        Drop the given table from the database schema.
        Returns:
        true if the operation was successful, false otherwise
        Throws:
        java.sql.SQLException
      • createSequence

        public boolean createSequence​(Sequence seq)
                               throws java.sql.SQLException
        Add the given sequence to the database schema.
        Returns:
        true if the operation was successful, false otherwise
        Throws:
        java.sql.SQLException
      • dropSequence

        public boolean dropSequence​(Sequence seq)
                             throws java.sql.SQLException
        Drop the given sequence from the database schema.
        Returns:
        true if the operation was successful, false otherwise
        Throws:
        java.sql.SQLException
      • createIndex

        public boolean createIndex​(Index idx,
                                   Table table)
                            throws java.sql.SQLException
        Add the given index to the database schema.
        Returns:
        true if the operation was successful, false otherwise
        Throws:
        java.sql.SQLException
      • createIndex

        public boolean createIndex​(Index idx,
                                   Table table,
                                   Unique[] uniques)
                            throws java.sql.SQLException
        Throws:
        java.sql.SQLException
      • dropIndex

        public boolean dropIndex​(Index idx)
                          throws java.sql.SQLException
        Drop the given index from the database schema.
        Returns:
        true if the operation was successful, false otherwise
        Throws:
        java.sql.SQLException
      • addColumn

        public boolean addColumn​(Column col)
                          throws java.sql.SQLException
        Add the given column to the database schema.
        Returns:
        true if the operation was successful, false otherwise
        Throws:
        java.sql.SQLException
      • dropColumn

        public boolean dropColumn​(Column col)
                           throws java.sql.SQLException
        Drop the given column from the database schema.
        Returns:
        true if the operation was successful, false otherwise
        Throws:
        java.sql.SQLException
      • addPrimaryKey

        public boolean addPrimaryKey​(PrimaryKey pk)
                              throws java.sql.SQLException
        Add the given primary key to the database schema.
        Returns:
        true if the operation was successful, false otherwise
        Throws:
        java.sql.SQLException
      • dropPrimaryKey

        public boolean dropPrimaryKey​(PrimaryKey pk)
                               throws java.sql.SQLException
        Drop the given primary key from the database schema.
        Returns:
        true if the operation was successful, false otherwise
        Throws:
        java.sql.SQLException
      • addForeignKey

        public boolean addForeignKey​(ForeignKey fk)
                              throws java.sql.SQLException
        Add the given foreign key to the database schema.
        Returns:
        true if the operation was successful, false otherwise
        Throws:
        java.sql.SQLException
      • dropForeignKey

        public boolean dropForeignKey​(ForeignKey fk)
                               throws java.sql.SQLException
        Drop the given foreign key from the database schema.
        Returns:
        true if the operation was successful, false otherwise
        Throws:
        java.sql.SQLException
      • getDBSchemaGroup

        public SchemaGroup getDBSchemaGroup()
        Return the database schema.
      • setDBSchemaGroup

        public void setDBSchemaGroup​(SchemaGroup db)
        Set the database schema.
      • getDBSchemaGroup

        protected SchemaGroup getDBSchemaGroup​(boolean full)
                                        throws java.sql.SQLException
        Return the database schema.
        Parameters:
        full - if false, only the tables named in the set schema repository will be generated
        Throws:
        java.sql.SQLException
      • assertSchemaGroup

        protected SchemaGroup assertSchemaGroup()
      • executeSQL

        protected boolean executeSQL​(java.lang.String[] sql)
                              throws java.sql.SQLException
        Executes the given array of non-selecting SQL statements, correctly logging the SQL calls and optionally ignoring errors.
        Returns:
        true if there was SQL to execute and the calls were successful, false otherwise
        Throws:
        java.sql.SQLException
      • handleException

        protected void handleException​(java.sql.SQLException sql)
                                throws java.sql.SQLException
        Handle the given exception, logging it and optionally ignoring it, depending on the flags this SchemaTool was created with.
        Throws:
        java.sql.SQLException
      • main

        public static void main​(java.lang.String[] args)
                         throws java.io.IOException,
                                java.sql.SQLException
        Usage: java org.apache.openjpa.jdbc.schema.SchemaTool [option]* [-action/-a <add | retain | drop | refresh | createDB | dropDB | build | reflect | import | export>] <.schema file or resource>* Where the following options are recognized.
        • -properties/-p <properties file or resource>: The path or resource name of a OpenJPA properties file containing information such as the license key and connection data as outlined in JDBCConfiguration. Optional.
        • -<property name> <property value>: All bean properties of the OpenJPA JDBCConfiguration can be set by using their names and supplying a value. For example: -licenseKey adslfja83r3lkadf
        • -ignoreErrors/-i <true/t | false/f>: If false, an exception will will be thrown if the tool encounters any database exceptions; defaults to false.
        • -file/-f <stdout | output file or resource>: Use this option to write a SQL script for the planned schema modifications, rather than committing them to the database. This option also applies to the export and reflect actions.
        • -openjpaTables/-kt <true/t | false/f>: Under the reflect action, whether to reflect on tables with the name OPENJPA_*. Under other actions, whether to drop such tables. Defaults to false.
        • -dropTables/-dt <true/t | false/f>: Set this option to true to drop tables that appear to be unused during retain and refresh actions. Defaults to true.
        • -dropSequences/-dsq <true/t | false/f>: Set this option to true to drop sequences that appear to be unused during retain and refresh actions. Defaults to true.
        • -rollbackBeforeDDL/-rbddl <true/t | false/f>: Set this option to true to send an initail rollback on the connection before any DDL statement is sent
        • -primaryKeys/-pk <true/t | false/f>: Whether primary keys on existing tables are manipulated. Defaults to true.
        • -foreignKeys/-fk <true/t | false/f>: Whether foreign keys on existing tables are manipulated. Defaults to true.
        • -indexes/-ix <true/t | false/f>: Whether indexes on existing tables are manipulated. Defaults to true.
        • -sequences/-sq <true/t | false/f>: Whether to manipulate sequences. Defaults to true.
        • -record/-r <true/t | false/f>: Set this option to false to prevent writing the schema changes to the current SchemaFactory.
        Actions can be composed in a comma-separated list. The various actions are as follows.
        • add: Bring the schema up-to-date with the latest changes to the schema XML data by adding tables, columns, indexes, etc. This action never drops any data. This is the default action.
        • retain: Keep all schema components in the schema XML, but drop the rest from the database. This action never adds any data.
        • drop: Drop all the schema components in the schema XML.
        • refresh: Equivalent to retain, then add.
        • createDB: Execute SQL to re-create the current database. This action is typically used in conjuction with the file option.
        • build: Execute SQL to build the schema defined in the XML. Because it doesn't take the current database schema into account, this action is typically used in conjuction with the file option.
        • reflect: Reflect on the current database schema. Write the schema's XML representation to the file specified with the file option, or to stdout if no file is given.
        • dropDB: Execute SQL to drop the current database. This action implies dropTables.
        • deleteTableContents: Execute SQL to delete all rows from all tables that OpenJPA knows about.
        • import: Import the given XML schema definition into the current SchemaFactory.
        • export: Export the current SchemaFactory's recorded schema to an XML schema definition file.
        Examples:
        • Write a script to stdout to re-create the current database schema:
          java org.apache.openjpa.jdbc.schema.SchemaTool -f stdout -a createDB
        • Drop the current database schema:
          java org.apache.openjpa.jdbc.schema.SchemaTool -a dropDB
        • Refresh the schema and delete all records in all tables:
          java org.apache.openjpa.jdbc.schema.SchemaTool -a refresh,deleteTableContents
        • Create a schema based on an XML schema definition file:
          java org.apache.openjpa.jdbc.schema.SchemaTool myschema.xml
        Throws:
        java.io.IOException
        java.sql.SQLException
      • run

        public static boolean run​(JDBCConfiguration conf,
                                  java.lang.String[] args,
                                  Options opts)
                           throws java.io.IOException,
                                  java.sql.SQLException
        Run the tool. Returns false if any invalid options were given.
        Throws:
        java.io.IOException
        java.sql.SQLException
        See Also:
        main(java.lang.String[])
      • run

        public static boolean run​(JDBCConfiguration conf,
                                  java.lang.String[] args,
                                  SchemaTool.Flags flags,
                                  java.lang.ClassLoader loader)
                           throws java.io.IOException,
                                  java.sql.SQLException
        Run the tool. Return false if invalid options were given.
        Throws:
        java.io.IOException
        java.sql.SQLException