public boolean createSqlTableFrom ( Connection connection , String tableToClone ) { long startTime = System . currentTimeMillis ( ) ; try { Statement statement = connection . createStatement ( ) ; // Drop target table to avoid a conflict. String dropSql = String . format ( "drop table if exists %s" , name ) ; LOG . info ( dropSql ) ; statement . execute ( dropSql ) ; if ( tableToClone . endsWith ( "stop_times" ) ) { normalizeAndCloneStopTimes ( statement , name , tableToClone ) ; } else { // Adding the unlogged keyword gives about 12 percent speedup on loading, but is non-standard. // FIXME: Which create table operation is more efficient? String createTableAsSql = String . format ( "create table %s as table %s" , name , tableToClone ) ; // Create table in the image of the table we're copying (indexes are not included). LOG . info ( createTableAsSql ) ; statement . execute ( createTableAsSql ) ; } applyAutoIncrementingSequence ( statement ) ; // FIXME: Is there a need to add primary key constraint here? if ( usePrimaryKey ) { // Add primary key to ID column for any tables that require it. String addPrimaryKeySql = String . format ( "ALTER TABLE %s ADD PRIMARY KEY (id)" , name ) ; LOG . info ( addPrimaryKeySql ) ; statement . execute ( addPrimaryKeySql ) ; } return true ; } catch ( SQLException ex ) { LOG . error ( "Error cloning table {}: {}" , name , ex . getSQLState ( ) ) ; LOG . error ( "details: " , ex ) ; try { connection . rollback ( ) ; // It is likely that if cloning the table fails, the reason was that the table did not already exist. // Try to create the table here from scratch. // FIXME: Maybe we should check that the reason the clone failed was that the table already exists. createSqlTable ( connection , true ) ; return true ; } catch ( SQLException e ) { e . printStackTrace ( ) ; return false ; } } finally { LOG . info ( "Cloned table {} as {} in {} ms" , tableToClone , name , System . currentTimeMillis ( ) - startTime ) ; } }
Creates a SQL table from the table to clone . This uses the SQL syntax create table x as y not only copies the table structure but also the data from the original table . Creating table indexes is not handled by this method .