idx int64 0 165k | question stringlengths 73 4.15k | target stringlengths 5 918 | len_question int64 21 890 | len_target int64 3 255 |
|---|---|---|---|---|
146,800 | public Where < T , ID > eq ( String columnName , Object value ) throws SQLException { addClause ( new SimpleComparison ( columnName , findColumnFieldType ( columnName ) , value , SimpleComparison . EQUAL_TO_OPERATION ) ) ; return this ; } | Add a = clause so the column must be equal to the value . | 63 | 14 |
146,801 | public Where < T , ID > ge ( String columnName , Object value ) throws SQLException { addClause ( new SimpleComparison ( columnName , findColumnFieldType ( columnName ) , value , SimpleComparison . GREATER_THAN_EQUAL_TO_OPERATION ) ) ; return this ; } | Add a > ; = clause so the column must be greater - than or equals - to the value . | 70 | 22 |
146,802 | public Where < T , ID > gt ( String columnName , Object value ) throws SQLException { addClause ( new SimpleComparison ( columnName , findColumnFieldType ( columnName ) , value , SimpleComparison . GREATER_THAN_OPERATION ) ) ; return this ; } | Add a > ; clause so the column must be greater - than the value . | 65 | 17 |
146,803 | public Where < T , ID > in ( String columnName , Iterable < ? > objects ) throws SQLException { addClause ( new In ( columnName , findColumnFieldType ( columnName ) , objects , true ) ) ; return this ; } | Add a IN clause so the column must be equal - to one of the objects from the list passed in . | 55 | 22 |
146,804 | public Where < T , ID > in ( String columnName , Object ... objects ) throws SQLException { return in ( true , columnName , objects ) ; } | Add a IN clause so the column must be equal - to one of the objects passed in . | 35 | 19 |
146,805 | public Where < T , ID > exists ( QueryBuilder < ? , ? > subQueryBuilder ) { // we do this to turn off the automatic addition of the ID column in the select column list subQueryBuilder . enableInnerQuery ( ) ; addClause ( new Exists ( new InternalQueryBuilderWrapper ( subQueryBuilder ) ) ) ; return this ; } | Add a EXISTS clause with a sub - query inside of parenthesis . | 77 | 16 |
146,806 | public Where < T , ID > isNull ( String columnName ) throws SQLException { addClause ( new IsNull ( columnName , findColumnFieldType ( columnName ) ) ) ; return this ; } | Add a IS NULL clause so the column must be null . = NULL does not work . | 46 | 18 |
146,807 | public Where < T , ID > isNotNull ( String columnName ) throws SQLException { addClause ( new IsNotNull ( columnName , findColumnFieldType ( columnName ) ) ) ; return this ; } | Add a IS NOT NULL clause so the column must not be null . < ; > ; NULL does not work . | 48 | 25 |
146,808 | public Where < T , ID > le ( String columnName , Object value ) throws SQLException { addClause ( new SimpleComparison ( columnName , findColumnFieldType ( columnName ) , value , SimpleComparison . LESS_THAN_EQUAL_TO_OPERATION ) ) ; return this ; } | Add a < ; = clause so the column must be less - than or equals - to the value . | 70 | 22 |
146,809 | public Where < T , ID > lt ( String columnName , Object value ) throws SQLException { addClause ( new SimpleComparison ( columnName , findColumnFieldType ( columnName ) , value , SimpleComparison . LESS_THAN_OPERATION ) ) ; return this ; } | Add a < ; clause so the column must be less - than the value . | 65 | 17 |
146,810 | public Where < T , ID > like ( String columnName , Object value ) throws SQLException { addClause ( new SimpleComparison ( columnName , findColumnFieldType ( columnName ) , value , SimpleComparison . LIKE_OPERATION ) ) ; return this ; } | Add a LIKE clause so the column must mach the value using % patterns . | 60 | 15 |
146,811 | public Where < T , ID > ne ( String columnName , Object value ) throws SQLException { addClause ( new SimpleComparison ( columnName , findColumnFieldType ( columnName ) , value , SimpleComparison . NOT_EQUAL_TO_OPERATION ) ) ; return this ; } | Add a < ; > ; clause so the column must be not - equal - to the value . | 66 | 22 |
146,812 | public Where < T , ID > not ( ) { /* * Special circumstance here when we have a needs future with a not. Something like and().not().like(...). In * this case we satisfy the and()'s future as the not() but the not() becomes the new needs-future. */ Not not = new Not ( ) ; addClause ( not ) ; addNeedsFuture ( not ) ; return this ; } | Used to NOT the next clause specified . | 91 | 8 |
146,813 | public Where < T , ID > not ( Where < T , ID > comparison ) { addClause ( new Not ( pop ( "NOT" ) ) ) ; return this ; } | Used to NOT the argument clause specified . | 38 | 8 |
146,814 | public Where < T , ID > or ( ) { ManyClause clause = new ManyClause ( pop ( "OR" ) , ManyClause . OR_OPERATION ) ; push ( clause ) ; addNeedsFuture ( clause ) ; return this ; } | OR operation which takes the previous clause and the next clause and OR s them together . | 55 | 17 |
146,815 | public Where < T , ID > or ( Where < T , ID > left , Where < T , ID > right , Where < T , ID > ... others ) { Clause [ ] clauses = buildClauseArray ( others , "OR" ) ; Clause secondClause = pop ( "OR" ) ; Clause firstClause = pop ( "OR" ) ; addClause ( new ManyClause ( firstClause , secondClause , clauses , ManyClause . OR_OPERATION ) ) ; return this ; } | OR operation which takes 2 arguments and OR s them together . | 110 | 12 |
146,816 | public Where < T , ID > idEq ( ID id ) throws SQLException { if ( idColumnName == null ) { throw new SQLException ( "Object has no id column specified" ) ; } addClause ( new SimpleComparison ( idColumnName , idFieldType , id , SimpleComparison . EQUAL_TO_OPERATION ) ) ; return this ; } | Add a clause where the ID is equal to the argument . | 84 | 12 |
146,817 | public < OD > Where < T , ID > idEq ( Dao < OD , ? > dataDao , OD data ) throws SQLException { if ( idColumnName == null ) { throw new SQLException ( "Object has no id column specified" ) ; } addClause ( new SimpleComparison ( idColumnName , idFieldType , dataDao . extractId ( data ) , SimpleComparison . EQUAL_TO_OPERATION ) ) ; return this ; } | Add a clause where the ID is from an existing object . | 106 | 12 |
146,818 | public Where < T , ID > raw ( String rawStatement , ArgumentHolder ... args ) { for ( ArgumentHolder arg : args ) { String columnName = arg . getColumnName ( ) ; if ( columnName == null ) { if ( arg . getSqlType ( ) == null ) { throw new IllegalArgumentException ( "Either the column name or SqlType must be set on each argument" ) ; } } else { arg . setMetaInfo ( findColumnFieldType ( columnName ) ) ; } } addClause ( new Raw ( rawStatement , args ) ) ; return this ; } | Add a raw statement as part of the where that can be anything that the database supports . Using more structured methods is recommended but this gives more control over the query and allows you to utilize database specific features . | 129 | 41 |
146,819 | public Where < T , ID > rawComparison ( String columnName , String rawOperator , Object value ) throws SQLException { addClause ( new SimpleComparison ( columnName , findColumnFieldType ( columnName ) , value , rawOperator ) ) ; return this ; } | Make a comparison where the operator is specified by the caller . It is up to the caller to specify an appropriate operator for the database and that it be formatted correctly . | 62 | 33 |
146,820 | public Where < T , ID > reset ( ) { for ( int i = 0 ; i < clauseStackLevel ; i ++ ) { // help with gc clauseStack [ i ] = null ; } clauseStackLevel = 0 ; return this ; } | Reset the Where object so it can be re - used . | 52 | 13 |
146,821 | public String getStatement ( ) throws SQLException { StringBuilder sb = new StringBuilder ( ) ; appendSql ( null , sb , new ArrayList < ArgumentHolder > ( ) ) ; return sb . toString ( ) ; } | Returns the associated SQL WHERE statement . | 54 | 7 |
146,822 | public int execute ( DatabaseConnection databaseConnection , T data , ID newId , ObjectCache objectCache ) throws SQLException { try { // the arguments are the new-id and old-id Object [ ] args = new Object [ ] { convertIdToFieldObject ( newId ) , extractIdToFieldObject ( data ) } ; int rowC = databaseConnection . update ( statement , args , argFieldTypes ) ; if ( rowC > 0 ) { if ( objectCache != null ) { Object oldId = idField . extractJavaFieldValue ( data ) ; T obj = objectCache . updateId ( clazz , oldId , newId ) ; if ( obj != null && obj != data ) { // if our cached value is not the data that will be updated then we need to update it specially idField . assignField ( connectionSource , obj , newId , false , objectCache ) ; } } // adjust the object to assign the new id idField . assignField ( connectionSource , data , newId , false , objectCache ) ; } logger . debug ( "updating-id with statement '{}' and {} args, changed {} rows" , statement , args . length , rowC ) ; if ( args . length > 0 ) { // need to do the cast otherwise we only print the first object in args logger . trace ( "updating-id arguments: {}" , ( Object ) args ) ; } return rowC ; } catch ( SQLException e ) { throw SqlExceptionUtil . create ( "Unable to run update-id stmt on object " + data + ": " + statement , e ) ; } } | Update the id field of the object in the database . | 351 | 11 |
146,823 | public static DatabaseFieldConfig fromReader ( BufferedReader reader ) throws SQLException { DatabaseFieldConfig config = new DatabaseFieldConfig ( ) ; boolean anything = false ; while ( true ) { String line ; try { line = reader . readLine ( ) ; } catch ( IOException e ) { throw SqlExceptionUtil . create ( "Could not read DatabaseFieldConfig from stream" , e ) ; } if ( line == null ) { break ; } // we do this so we can support multiple class configs per file if ( line . equals ( CONFIG_FILE_END_MARKER ) ) { break ; } // skip empty lines or comments if ( line . length ( ) == 0 || line . startsWith ( "#" ) || line . equals ( CONFIG_FILE_START_MARKER ) ) { continue ; } String [ ] parts = line . split ( "=" , - 2 ) ; if ( parts . length != 2 ) { throw new SQLException ( "DatabaseFieldConfig reading from stream cannot parse line: " + line ) ; } readField ( config , parts [ 0 ] , parts [ 1 ] ) ; anything = true ; } // if we got any config lines then we return the config if ( anything ) { return config ; } else { // otherwise we return null for none return null ; } } | Load a configuration in from a text file . | 282 | 9 |
146,824 | public static void write ( BufferedWriter writer , DatabaseFieldConfig config , String tableName ) throws SQLException { try { writeConfig ( writer , config , tableName ) ; } catch ( IOException e ) { throw SqlExceptionUtil . create ( "Could not write config to writer" , e ) ; } } | Write the configuration to a buffered writer . | 69 | 9 |
146,825 | public UpdateBuilder < T , ID > updateColumnValue ( String columnName , Object value ) throws SQLException { FieldType fieldType = verifyColumnName ( columnName ) ; if ( fieldType . isForeignCollection ( ) ) { throw new SQLException ( "Can't update foreign colletion field: " + columnName ) ; } addUpdateColumnToList ( columnName , new SetValue ( columnName , fieldType , value ) ) ; return this ; } | Add a column to be set to a value for UPDATE statements . This will generate something like columnName = value with the value escaped if necessary . | 101 | 29 |
146,826 | public UpdateBuilder < T , ID > updateColumnExpression ( String columnName , String expression ) throws SQLException { FieldType fieldType = verifyColumnName ( columnName ) ; if ( fieldType . isForeignCollection ( ) ) { throw new SQLException ( "Can't update foreign colletion field: " + columnName ) ; } addUpdateColumnToList ( columnName , new SetExpression ( columnName , fieldType , expression ) ) ; return this ; } | Add a column to be set to a value for UPDATE statements . This will generate something like columnName = expression where the expression is built by the caller . | 103 | 31 |
146,827 | public void initialize ( ) { if ( dataClass == null ) { throw new IllegalStateException ( "dataClass was never set on " + getClass ( ) . getSimpleName ( ) ) ; } if ( tableName == null ) { tableName = extractTableName ( databaseType , dataClass ) ; } } | Initialize the class if this is being called with Spring . | 66 | 12 |
146,828 | public void extractFieldTypes ( DatabaseType databaseType ) throws SQLException { if ( fieldTypes == null ) { if ( fieldConfigs == null ) { fieldTypes = extractFieldTypes ( databaseType , dataClass , tableName ) ; } else { fieldTypes = convertFieldConfigs ( databaseType , tableName , fieldConfigs ) ; } } } | Extract the field types from the fieldConfigs if they have not already been configured . | 76 | 18 |
146,829 | public static < T > DatabaseTableConfig < T > fromClass ( DatabaseType databaseType , Class < T > clazz ) throws SQLException { String tableName = extractTableName ( databaseType , clazz ) ; if ( databaseType . isEntityNamesMustBeUpCase ( ) ) { tableName = databaseType . upCaseEntityName ( tableName ) ; } return new DatabaseTableConfig < T > ( databaseType , clazz , tableName , extractFieldTypes ( databaseType , clazz , tableName ) ) ; } | Extract the DatabaseTableConfig for a particular class by looking for class and field annotations . This is used by internal classes to configure a class . | 113 | 29 |
146,830 | public static < T > String extractTableName ( DatabaseType databaseType , Class < T > clazz ) { DatabaseTable databaseTable = clazz . getAnnotation ( DatabaseTable . class ) ; String name = null ; if ( databaseTable != null && databaseTable . tableName ( ) != null && databaseTable . tableName ( ) . length ( ) > 0 ) { name = databaseTable . tableName ( ) ; } if ( name == null && javaxPersistenceConfigurer != null ) { name = javaxPersistenceConfigurer . getEntityName ( clazz ) ; } if ( name == null ) { // if the name isn't specified, it is the class name lowercased if ( databaseType == null ) { // database-type is optional so if it is not specified we just use english name = clazz . getSimpleName ( ) . toLowerCase ( Locale . ENGLISH ) ; } else { name = databaseType . downCaseString ( clazz . getSimpleName ( ) , true ) ; } } return name ; } | Extract and return the table name for a class . | 225 | 11 |
146,831 | public static void openLogFile ( String logPath ) { if ( logPath == null ) { printStream = System . out ; } else { try { printStream = new PrintStream ( new File ( logPath ) ) ; } catch ( FileNotFoundException e ) { throw new IllegalArgumentException ( "Log file " + logPath + " was not found" , e ) ; } } } | Reopen the associated static logging stream . Set to null to redirect to System . out . | 84 | 18 |
146,832 | public long queryForCountStar ( DatabaseConnection databaseConnection ) throws SQLException { if ( countStarQuery == null ) { StringBuilder sb = new StringBuilder ( 64 ) ; sb . append ( "SELECT COUNT(*) FROM " ) ; databaseType . appendEscapedEntityName ( sb , tableInfo . getTableName ( ) ) ; countStarQuery = sb . toString ( ) ; } long count = databaseConnection . queryForLong ( countStarQuery ) ; logger . debug ( "query of '{}' returned {}" , countStarQuery , count ) ; return count ; } | Return a long value which is the number of rows in the table . | 130 | 14 |
146,833 | public long queryForLong ( DatabaseConnection databaseConnection , PreparedStmt < T > preparedStmt ) throws SQLException { CompiledStatement compiledStatement = preparedStmt . compile ( databaseConnection , StatementType . SELECT_LONG ) ; DatabaseResults results = null ; try { results = compiledStatement . runQuery ( null ) ; if ( results . first ( ) ) { return results . getLong ( 0 ) ; } else { throw new SQLException ( "No result found in queryForLong: " + preparedStmt . getStatement ( ) ) ; } } finally { IOUtils . closeThrowSqlException ( results , "results" ) ; IOUtils . closeThrowSqlException ( compiledStatement , "compiled statement" ) ; } } | Return a long value from a prepared query . | 165 | 9 |
146,834 | public SelectIterator < T , ID > buildIterator ( BaseDaoImpl < T , ID > classDao , ConnectionSource connectionSource , int resultFlags , ObjectCache objectCache ) throws SQLException { prepareQueryForAll ( ) ; return buildIterator ( classDao , connectionSource , preparedQueryForAll , objectCache , resultFlags ) ; } | Create and return a SelectIterator for the class using the default mapped query for all statement . | 75 | 18 |
146,835 | public int updateRaw ( DatabaseConnection connection , String statement , String [ ] arguments ) throws SQLException { logger . debug ( "running raw update statement: {}" , statement ) ; if ( arguments . length > 0 ) { // need to do the (Object) cast to force args to be a single object logger . trace ( "update arguments: {}" , ( Object ) arguments ) ; } CompiledStatement compiledStatement = connection . compileStatement ( statement , StatementType . UPDATE , noFieldTypes , DatabaseConnection . DEFAULT_RESULT_FLAGS , false ) ; try { assignStatementArguments ( compiledStatement , arguments ) ; return compiledStatement . runUpdate ( ) ; } finally { IOUtils . closeThrowSqlException ( compiledStatement , "compiled statement" ) ; } } | Return the number of rows affected . | 168 | 7 |
146,836 | public int create ( DatabaseConnection databaseConnection , T data , ObjectCache objectCache ) throws SQLException { if ( mappedInsert == null ) { mappedInsert = MappedCreate . build ( dao , tableInfo ) ; } int result = mappedInsert . insert ( databaseType , databaseConnection , data , objectCache ) ; if ( dao != null && ! localIsInBatchMode . get ( ) ) { dao . notifyChanges ( ) ; } return result ; } | Create a new entry in the database from an object . | 101 | 11 |
146,837 | public int updateId ( DatabaseConnection databaseConnection , T data , ID newId , ObjectCache objectCache ) throws SQLException { if ( mappedUpdateId == null ) { mappedUpdateId = MappedUpdateId . build ( dao , tableInfo ) ; } int result = mappedUpdateId . execute ( databaseConnection , data , newId , objectCache ) ; if ( dao != null && ! localIsInBatchMode . get ( ) ) { dao . notifyChanges ( ) ; } return result ; } | Update an object in the database to change its id to the newId parameter . | 110 | 16 |
146,838 | public int update ( DatabaseConnection databaseConnection , PreparedUpdate < T > preparedUpdate ) throws SQLException { CompiledStatement compiledStatement = preparedUpdate . compile ( databaseConnection , StatementType . UPDATE ) ; try { int result = compiledStatement . runUpdate ( ) ; if ( dao != null && ! localIsInBatchMode . get ( ) ) { dao . notifyChanges ( ) ; } return result ; } finally { IOUtils . closeThrowSqlException ( compiledStatement , "compiled statement" ) ; } } | Update rows in the database . | 115 | 6 |
146,839 | public int refresh ( DatabaseConnection databaseConnection , T data , ObjectCache objectCache ) throws SQLException { if ( mappedRefresh == null ) { mappedRefresh = MappedRefresh . build ( dao , tableInfo ) ; } return mappedRefresh . executeRefresh ( databaseConnection , data , objectCache ) ; } | Does a query for the object s Id and copies in each of the field values from the database to refresh the data parameter . | 70 | 25 |
146,840 | public int delete ( DatabaseConnection databaseConnection , T data , ObjectCache objectCache ) throws SQLException { if ( mappedDelete == null ) { mappedDelete = MappedDelete . build ( dao , tableInfo ) ; } int result = mappedDelete . delete ( databaseConnection , data , objectCache ) ; if ( dao != null && ! localIsInBatchMode . get ( ) ) { dao . notifyChanges ( ) ; } return result ; } | Delete an object from the database . | 98 | 7 |
146,841 | public int deleteById ( DatabaseConnection databaseConnection , ID id , ObjectCache objectCache ) throws SQLException { if ( mappedDelete == null ) { mappedDelete = MappedDelete . build ( dao , tableInfo ) ; } int result = mappedDelete . deleteById ( databaseConnection , id , objectCache ) ; if ( dao != null && ! localIsInBatchMode . get ( ) ) { dao . notifyChanges ( ) ; } return result ; } | Delete an object from the database by id . | 100 | 9 |
146,842 | public int delete ( DatabaseConnection databaseConnection , PreparedDelete < T > preparedDelete ) throws SQLException { CompiledStatement compiledStatement = preparedDelete . compile ( databaseConnection , StatementType . DELETE ) ; try { int result = compiledStatement . runUpdate ( ) ; if ( dao != null && ! localIsInBatchMode . get ( ) ) { dao . notifyChanges ( ) ; } return result ; } finally { IOUtils . closeThrowSqlException ( compiledStatement , "compiled statement" ) ; } } | Delete rows that match the prepared statement . | 117 | 8 |
146,843 | public < CT > CT callBatchTasks ( ConnectionSource connectionSource , Callable < CT > callable ) throws SQLException { if ( connectionSource . isSingleConnection ( tableInfo . getTableName ( ) ) ) { synchronized ( this ) { return doCallBatchTasks ( connectionSource , callable ) ; } } else { return doCallBatchTasks ( connectionSource , callable ) ; } } | Call batch tasks inside of a connection which may or may not have been saved . | 91 | 16 |
146,844 | public static SQLException create ( String message , Throwable cause ) { SQLException sqlException ; if ( cause instanceof SQLException ) { // if the cause is another SQLException, pass alot of the SQL state sqlException = new SQLException ( message , ( ( SQLException ) cause ) . getSQLState ( ) ) ; } else { sqlException = new SQLException ( message ) ; } sqlException . initCause ( cause ) ; return sqlException ; } | Convenience method to allow a cause . Grrrr . | 109 | 13 |
146,845 | public void initialize ( ) throws SQLException { if ( initialized ) { // just skip it if already initialized return ; } if ( connectionSource == null ) { throw new IllegalStateException ( "connectionSource was never set on " + getClass ( ) . getSimpleName ( ) ) ; } databaseType = connectionSource . getDatabaseType ( ) ; if ( databaseType == null ) { throw new IllegalStateException ( "connectionSource is getting a null DatabaseType in " + getClass ( ) . getSimpleName ( ) ) ; } if ( tableConfig == null ) { tableInfo = new TableInfo < T , ID > ( databaseType , dataClass ) ; } else { tableConfig . extractFieldTypes ( databaseType ) ; tableInfo = new TableInfo < T , ID > ( databaseType , tableConfig ) ; } statementExecutor = new StatementExecutor < T , ID > ( databaseType , tableInfo , this ) ; /* * This is a bit complex. Initially, when we were configuring the field types, external DAO information would be * configured for auto-refresh, foreign BaseDaoEnabled classes, and foreign-collections. This would cause the * system to go recursive and for class loops, a stack overflow. * * Then we fixed this by putting a level counter in the FieldType constructor that would stop the configurations * when we reach some recursion level. But this created some bad problems because we were using the DaoManager * to cache the created DAOs that had been constructed already limited by the level. * * What we do now is have a 2 phase initialization. The constructor initializes most of the fields but then we * go back and call FieldType.configDaoInformation() after we are done. So for every DAO that is initialized * here, we have to see if it is the top DAO. If not we save it for dao configuration later. */ List < BaseDaoImpl < ? , ? > > daoConfigList = daoConfigLevelLocal . get ( ) ; daoConfigList . add ( this ) ; if ( daoConfigList . size ( ) > 1 ) { // if we have recursed then just save the dao for later configuration return ; } try { /* * WARNING: We do _not_ use an iterator here because we may be adding to the list as we process it and we'll * get exceptions otherwise. This is an ArrayList so the get(i) should be efficient. * * Also, do _not_ get a copy of daoConfigLevel.doArray because that array may be replaced by another, larger * one during the recursion. */ for ( int i = 0 ; i < daoConfigList . size ( ) ; i ++ ) { BaseDaoImpl < ? , ? > dao = daoConfigList . get ( i ) ; /* * Here's another complex bit. The first DAO that is being constructed as part of a DAO chain is not yet * in the DaoManager cache. If we continue onward we might come back around and try to configure this * DAO again. Forcing it into the cache here makes sure it won't be configured twice. This will cause it * to be stuck in twice when it returns out to the DaoManager but that's a small price to pay. This also * applies to self-referencing classes. */ DaoManager . registerDao ( connectionSource , dao ) ; try { // config our fields which may go recursive for ( FieldType fieldType : dao . getTableInfo ( ) . getFieldTypes ( ) ) { fieldType . configDaoInformation ( connectionSource , dao . getDataClass ( ) ) ; } } catch ( SQLException e ) { // unregister the DAO we just pre-registered DaoManager . unregisterDao ( connectionSource , dao ) ; throw e ; } // it's now been fully initialized dao . initialized = true ; } } finally { // if we throw we want to clear our class hierarchy here daoConfigList . clear ( ) ; daoConfigLevelLocal . remove ( ) ; } } | Initialize the various DAO configurations after the various setters have been called . | 871 | 16 |
146,846 | static < T , ID > Dao < T , ID > createDao ( ConnectionSource connectionSource , Class < T > clazz ) throws SQLException { return new BaseDaoImpl < T , ID > ( connectionSource , clazz ) { } ; } | Helper method to create a Dao object without having to define a class . Dao classes are supposed to be convenient but if you have a lot of classes they can seem to be a pain . | 57 | 39 |
146,847 | private Constructor < T > findNoArgConstructor ( Class < T > dataClass ) { Constructor < T > [ ] constructors ; try { @ SuppressWarnings ( "unchecked" ) Constructor < T > [ ] consts = ( Constructor < T > [ ] ) dataClass . getDeclaredConstructors ( ) ; // i do this [grossness] to be able to move the Suppress inside the method constructors = consts ; } catch ( Exception e ) { throw new IllegalArgumentException ( "Can't lookup declared constructors for " + dataClass , e ) ; } for ( Constructor < T > con : constructors ) { if ( con . getParameterTypes ( ) . length == 0 ) { if ( ! con . isAccessible ( ) ) { try { con . setAccessible ( true ) ; } catch ( SecurityException e ) { throw new IllegalArgumentException ( "Could not open access to constructor for " + dataClass ) ; } } return con ; } } if ( dataClass . getEnclosingClass ( ) == null ) { throw new IllegalArgumentException ( "Can't find a no-arg constructor for " + dataClass ) ; } else { throw new IllegalArgumentException ( "Can't find a no-arg constructor for " + dataClass + ". Missing static on inner class?" ) ; } } | Locate the no arg constructor for the class . | 292 | 10 |
146,848 | public static Method findGetMethod ( Field field , DatabaseType databaseType , boolean throwExceptions ) throws IllegalArgumentException { Method fieldGetMethod = findMethodFromNames ( field , true , throwExceptions , methodFromField ( field , "get" , databaseType , true ) , methodFromField ( field , "get" , databaseType , false ) , methodFromField ( field , "is" , databaseType , true ) , methodFromField ( field , "is" , databaseType , false ) ) ; if ( fieldGetMethod == null ) { return null ; } if ( fieldGetMethod . getReturnType ( ) != field . getType ( ) ) { if ( throwExceptions ) { throw new IllegalArgumentException ( "Return type of get method " + fieldGetMethod . getName ( ) + " does not return " + field . getType ( ) ) ; } else { return null ; } } return fieldGetMethod ; } | Find and return the appropriate getter method for field . | 201 | 11 |
146,849 | public static Method findSetMethod ( Field field , DatabaseType databaseType , boolean throwExceptions ) throws IllegalArgumentException { Method fieldSetMethod = findMethodFromNames ( field , false , throwExceptions , methodFromField ( field , "set" , databaseType , true ) , methodFromField ( field , "set" , databaseType , false ) ) ; if ( fieldSetMethod == null ) { return null ; } if ( fieldSetMethod . getReturnType ( ) != void . class ) { if ( throwExceptions ) { throw new IllegalArgumentException ( "Return type of set method " + fieldSetMethod . getName ( ) + " returns " + fieldSetMethod . getReturnType ( ) + " instead of void" ) ; } else { return null ; } } return fieldSetMethod ; } | Find and return the appropriate setter method for field . | 173 | 11 |
146,850 | public void postProcess ( ) { if ( foreignColumnName != null ) { foreignAutoRefresh = true ; } if ( foreignAutoRefresh && maxForeignAutoRefreshLevel == NO_MAX_FOREIGN_AUTO_REFRESH_LEVEL_SPECIFIED ) { maxForeignAutoRefreshLevel = DatabaseField . DEFAULT_MAX_FOREIGN_AUTO_REFRESH_LEVEL ; } } | Process the settings when we are going to consume them . | 89 | 11 |
146,851 | public static Enum < ? > findMatchingEnumVal ( Field field , String unknownEnumName ) { if ( unknownEnumName == null || unknownEnumName . length ( ) == 0 ) { return null ; } for ( Enum < ? > enumVal : ( Enum < ? > [ ] ) field . getType ( ) . getEnumConstants ( ) ) { if ( enumVal . name ( ) . equals ( unknownEnumName ) ) { return enumVal ; } } throw new IllegalArgumentException ( "Unknwown enum unknown name " + unknownEnumName + " for field " + field ) ; } | Internal method that finds the matching enum for a configured field that has the name argument . | 139 | 17 |
146,852 | public int executeRefresh ( DatabaseConnection databaseConnection , T data , ObjectCache objectCache ) throws SQLException { @ SuppressWarnings ( "unchecked" ) ID id = ( ID ) idField . extractJavaFieldValue ( data ) ; // we don't care about the cache here T result = super . execute ( databaseConnection , id , null ) ; if ( result == null ) { return 0 ; } // copy each field from the result into the passed in object for ( FieldType fieldType : resultsFieldTypes ) { if ( fieldType != idField ) { fieldType . assignField ( connectionSource , data , fieldType . extractJavaFieldValue ( result ) , false , objectCache ) ; } } return 1 ; } | Execute our refresh query statement and then update all of the fields in data with the fields from the result . | 156 | 22 |
146,853 | public QueryBuilder < T , ID > selectColumns ( String ... columns ) { for ( String column : columns ) { addSelectColumnToList ( column ) ; } return this ; } | Add columns to be returned by the SELECT query . If no columns are selected then all columns are returned by default . For classes with id columns the id column is added to the select list automagically . This can be called multiple times to add more columns to select . | 39 | 53 |
146,854 | public QueryBuilder < T , ID > groupBy ( String columnName ) { FieldType fieldType = verifyColumnName ( columnName ) ; if ( fieldType . isForeignCollection ( ) ) { throw new IllegalArgumentException ( "Can't groupBy foreign collection field: " + columnName ) ; } addGroupBy ( ColumnNameOrRawSql . withColumnName ( columnName ) ) ; return this ; } | Add GROUP BY clause to the SQL query statement . This can be called multiple times to add additional GROUP BY clauses . | 88 | 23 |
146,855 | public QueryBuilder < T , ID > groupByRaw ( String rawSql ) { addGroupBy ( ColumnNameOrRawSql . withRawSql ( rawSql ) ) ; return this ; } | Add a raw SQL GROUP BY clause to the SQL query statement . This should not include the GROUP BY . | 44 | 21 |
146,856 | public QueryBuilder < T , ID > orderBy ( String columnName , boolean ascending ) { FieldType fieldType = verifyColumnName ( columnName ) ; if ( fieldType . isForeignCollection ( ) ) { throw new IllegalArgumentException ( "Can't orderBy foreign collection field: " + columnName ) ; } addOrderBy ( new OrderBy ( columnName , ascending ) ) ; return this ; } | Add ORDER BY clause to the SQL query statement . This can be called multiple times to add additional ORDER BY clauses . Ones earlier are applied first . | 86 | 29 |
146,857 | public QueryBuilder < T , ID > orderByRaw ( String rawSql ) { addOrderBy ( new OrderBy ( rawSql , ( ArgumentHolder [ ] ) null ) ) ; return this ; } | Add raw SQL ORDER BY clause to the SQL query statement . | 45 | 12 |
146,858 | public QueryBuilder < T , ID > join ( QueryBuilder < ? , ? > joinedQueryBuilder ) throws SQLException { addJoinInfo ( JoinType . INNER , null , null , joinedQueryBuilder , JoinWhereOperation . AND ) ; return this ; } | Join with another query builder . This will add into the SQL something close to INNER JOIN other - table ... . Either the object associated with the current QueryBuilder or the argument QueryBuilder must have a foreign field of the other one . An exception will be thrown otherwise . | 56 | 55 |
146,859 | private void addJoinInfo ( JoinType type , String localColumnName , String joinedColumnName , QueryBuilder < ? , ? > joinedQueryBuilder , JoinWhereOperation operation ) throws SQLException { JoinInfo joinInfo = new JoinInfo ( type , joinedQueryBuilder , operation ) ; if ( localColumnName == null ) { matchJoinedFields ( joinInfo , joinedQueryBuilder ) ; } else { matchJoinedFieldsByName ( joinInfo , localColumnName , joinedColumnName , joinedQueryBuilder ) ; } if ( joinList == null ) { joinList = new ArrayList < JoinInfo > ( ) ; } joinList . add ( joinInfo ) ; } | Add join info to the query . This can be called multiple times to join with more than one table . | 141 | 21 |
146,860 | public String objectToString ( T object ) { StringBuilder sb = new StringBuilder ( 64 ) ; sb . append ( object . getClass ( ) . getSimpleName ( ) ) ; for ( FieldType fieldType : fieldTypes ) { sb . append ( ' ' ) . append ( fieldType . getColumnName ( ) ) . append ( ' ' ) ; try { sb . append ( fieldType . extractJavaFieldValue ( object ) ) ; } catch ( Exception e ) { throw new IllegalStateException ( "Could not generate toString of field " + fieldType , e ) ; } } return sb . toString ( ) ; } | Return a string representation of the object . | 139 | 8 |
146,861 | private static void logVersionWarnings ( String label1 , String version1 , String label2 , String version2 ) { if ( version1 == null ) { if ( version2 != null ) { warning ( null , "Unknown version" , " for {}, version for {} is '{}'" , new Object [ ] { label1 , label2 , version2 } ) ; } } else { if ( version2 == null ) { warning ( null , "Unknown version" , " for {}, version for {} is '{}'" , new Object [ ] { label2 , label1 , version1 } ) ; } else if ( ! version1 . equals ( version2 ) ) { warning ( null , "Mismatched versions" , ": {} is '{}', while {} is '{}'" , new Object [ ] { label1 , version1 , label2 , version2 } ) ; } } } | Log error information | 194 | 3 |
146,862 | protected MappedPreparedStmt < T , ID > prepareStatement ( Long limit , boolean cacheStore ) throws SQLException { List < ArgumentHolder > argList = new ArrayList < ArgumentHolder > ( ) ; String statement = buildStatementString ( argList ) ; ArgumentHolder [ ] selectArgs = argList . toArray ( new ArgumentHolder [ argList . size ( ) ] ) ; FieldType [ ] resultFieldTypes = getResultFieldTypes ( ) ; FieldType [ ] argFieldTypes = new FieldType [ argList . size ( ) ] ; for ( int selectC = 0 ; selectC < selectArgs . length ; selectC ++ ) { argFieldTypes [ selectC ] = selectArgs [ selectC ] . getFieldType ( ) ; } if ( ! type . isOkForStatementBuilder ( ) ) { throw new IllegalStateException ( "Building a statement from a " + type + " statement is not allowed" ) ; } return new MappedPreparedStmt < T , ID > ( dao , tableInfo , statement , argFieldTypes , resultFieldTypes , selectArgs , ( databaseType . isLimitSqlSupported ( ) ? null : limit ) , type , cacheStore ) ; } | Prepare our statement for the subclasses . | 261 | 9 |
146,863 | public String prepareStatementString ( ) throws SQLException { List < ArgumentHolder > argList = new ArrayList < ArgumentHolder > ( ) ; return buildStatementString ( argList ) ; } | Build and return a string version of the query . If you change the where or make other calls you will need to re - call this method to re - prepare the query for execution . | 43 | 37 |
146,864 | protected boolean appendWhereStatement ( StringBuilder sb , List < ArgumentHolder > argList , WhereOperation operation ) throws SQLException { if ( where == null ) { return operation == WhereOperation . FIRST ; } operation . appendBefore ( sb ) ; where . appendSql ( ( addTableName ? getTableName ( ) : null ) , sb , argList ) ; operation . appendAfter ( sb ) ; return false ; } | Append the WHERE part of the statement to the StringBuilder . | 95 | 13 |
146,865 | private static < T , ID > MappedDeleteCollection < T , ID > build ( Dao < T , ID > dao , TableInfo < T , ID > tableInfo , int dataSize ) throws SQLException { FieldType idField = tableInfo . getIdField ( ) ; if ( idField == null ) { throw new SQLException ( "Cannot delete " + tableInfo . getDataClass ( ) + " because it doesn't have an id field defined" ) ; } StringBuilder sb = new StringBuilder ( 128 ) ; DatabaseType databaseType = dao . getConnectionSource ( ) . getDatabaseType ( ) ; appendTableName ( databaseType , sb , "DELETE FROM " , tableInfo . getTableName ( ) ) ; FieldType [ ] argFieldTypes = new FieldType [ dataSize ] ; appendWhereIds ( databaseType , idField , sb , dataSize , argFieldTypes ) ; return new MappedDeleteCollection < T , ID > ( dao , tableInfo , sb . toString ( ) , argFieldTypes ) ; } | This is private because the execute is the only method that should be called here . | 235 | 16 |
146,866 | @ Override public T next ( ) { SQLException sqlException = null ; try { T result = nextThrow ( ) ; if ( result != null ) { return result ; } } catch ( SQLException e ) { sqlException = e ; } // we have to throw if there is no next or on a SQLException last = null ; closeQuietly ( ) ; throw new IllegalStateException ( "Could not get next result for " + dataClass , sqlException ) ; } | Returns the next object in the table . | 106 | 8 |
146,867 | public static < T > int createTable ( ConnectionSource connectionSource , Class < T > dataClass ) throws SQLException { Dao < T , ? > dao = DaoManager . createDao ( connectionSource , dataClass ) ; return doCreateTable ( dao , false ) ; } | Issue the database statements to create the table associated with a class . | 64 | 13 |
146,868 | public static < T > int createTable ( ConnectionSource connectionSource , DatabaseTableConfig < T > tableConfig ) throws SQLException { Dao < T , ? > dao = DaoManager . createDao ( connectionSource , tableConfig ) ; return doCreateTable ( dao , false ) ; } | Issue the database statements to create the table associated with a table configuration . | 66 | 14 |
146,869 | public static < T , ID > int dropTable ( ConnectionSource connectionSource , Class < T > dataClass , boolean ignoreErrors ) throws SQLException { Dao < T , ID > dao = DaoManager . createDao ( connectionSource , dataClass ) ; return dropTable ( dao , ignoreErrors ) ; } | Issue the database statements to drop the table associated with a class . | 72 | 13 |
146,870 | public static < T , ID > int dropTable ( Dao < T , ID > dao , boolean ignoreErrors ) throws SQLException { ConnectionSource connectionSource = dao . getConnectionSource ( ) ; Class < T > dataClass = dao . getDataClass ( ) ; DatabaseType databaseType = connectionSource . getDatabaseType ( ) ; if ( dao instanceof BaseDaoImpl < ? , ? > ) { return doDropTable ( databaseType , connectionSource , ( ( BaseDaoImpl < ? , ? > ) dao ) . getTableInfo ( ) , ignoreErrors ) ; } else { TableInfo < T , ID > tableInfo = new TableInfo < T , ID > ( databaseType , dataClass ) ; return doDropTable ( databaseType , connectionSource , tableInfo , ignoreErrors ) ; } } | Issue the database statements to drop the table associated with a dao . | 181 | 14 |
146,871 | public static < T , ID > int dropTable ( ConnectionSource connectionSource , DatabaseTableConfig < T > tableConfig , boolean ignoreErrors ) throws SQLException { DatabaseType databaseType = connectionSource . getDatabaseType ( ) ; Dao < T , ID > dao = DaoManager . createDao ( connectionSource , tableConfig ) ; if ( dao instanceof BaseDaoImpl < ? , ? > ) { return doDropTable ( databaseType , connectionSource , ( ( BaseDaoImpl < ? , ? > ) dao ) . getTableInfo ( ) , ignoreErrors ) ; } else { tableConfig . extractFieldTypes ( databaseType ) ; TableInfo < T , ID > tableInfo = new TableInfo < T , ID > ( databaseType , tableConfig ) ; return doDropTable ( databaseType , connectionSource , tableInfo , ignoreErrors ) ; } } | Issue the database statements to drop the table associated with a table configuration . | 191 | 14 |
146,872 | private static < T , ID > void addDropTableStatements ( DatabaseType databaseType , TableInfo < T , ID > tableInfo , List < String > statements , boolean logDetails ) { List < String > statementsBefore = new ArrayList < String > ( ) ; List < String > statementsAfter = new ArrayList < String > ( ) ; for ( FieldType fieldType : tableInfo . getFieldTypes ( ) ) { databaseType . dropColumnArg ( fieldType , statementsBefore , statementsAfter ) ; } StringBuilder sb = new StringBuilder ( 64 ) ; if ( logDetails ) { logger . info ( "dropping table '{}'" , tableInfo . getTableName ( ) ) ; } sb . append ( "DROP TABLE " ) ; databaseType . appendEscapedEntityName ( sb , tableInfo . getTableName ( ) ) ; sb . append ( ' ' ) ; statements . addAll ( statementsBefore ) ; statements . add ( sb . toString ( ) ) ; statements . addAll ( statementsAfter ) ; } | Generate and return the list of statements to drop a database table . | 223 | 14 |
146,873 | private static < T , ID > void addCreateTableStatements ( DatabaseType databaseType , TableInfo < T , ID > tableInfo , List < String > statements , List < String > queriesAfter , boolean ifNotExists , boolean logDetails ) throws SQLException { StringBuilder sb = new StringBuilder ( 256 ) ; if ( logDetails ) { logger . info ( "creating table '{}'" , tableInfo . getTableName ( ) ) ; } sb . append ( "CREATE TABLE " ) ; if ( ifNotExists && databaseType . isCreateIfNotExistsSupported ( ) ) { sb . append ( "IF NOT EXISTS " ) ; } databaseType . appendEscapedEntityName ( sb , tableInfo . getTableName ( ) ) ; sb . append ( " (" ) ; List < String > additionalArgs = new ArrayList < String > ( ) ; List < String > statementsBefore = new ArrayList < String > ( ) ; List < String > statementsAfter = new ArrayList < String > ( ) ; // our statement will be set here later boolean first = true ; for ( FieldType fieldType : tableInfo . getFieldTypes ( ) ) { // skip foreign collections if ( fieldType . isForeignCollection ( ) ) { continue ; } else if ( first ) { first = false ; } else { sb . append ( ", " ) ; } String columnDefinition = fieldType . getColumnDefinition ( ) ; if ( columnDefinition == null ) { // we have to call back to the database type for the specific create syntax databaseType . appendColumnArg ( tableInfo . getTableName ( ) , sb , fieldType , additionalArgs , statementsBefore , statementsAfter , queriesAfter ) ; } else { // hand defined field databaseType . appendEscapedEntityName ( sb , fieldType . getColumnName ( ) ) ; sb . append ( ' ' ) . append ( columnDefinition ) . append ( ' ' ) ; } } // add any sql that sets any primary key fields databaseType . addPrimaryKeySql ( tableInfo . getFieldTypes ( ) , additionalArgs , statementsBefore , statementsAfter , queriesAfter ) ; // add any sql that sets any unique fields databaseType . addUniqueComboSql ( tableInfo . getFieldTypes ( ) , additionalArgs , statementsBefore , statementsAfter , queriesAfter ) ; for ( String arg : additionalArgs ) { // we will have spat out one argument already so we don't have to do the first dance sb . append ( ", " ) . append ( arg ) ; } sb . append ( ") " ) ; databaseType . appendCreateTableSuffix ( sb ) ; statements . addAll ( statementsBefore ) ; statements . add ( sb . toString ( ) ) ; statements . addAll ( statementsAfter ) ; addCreateIndexStatements ( databaseType , tableInfo , statements , ifNotExists , false , logDetails ) ; addCreateIndexStatements ( databaseType , tableInfo , statements , ifNotExists , true , logDetails ) ; } | Generate and return the list of statements to create a database table and any associated features . | 653 | 18 |
146,874 | public void assignField ( ConnectionSource connectionSource , Object data , Object val , boolean parentObject , ObjectCache objectCache ) throws SQLException { if ( logger . isLevelEnabled ( Level . TRACE ) ) { logger . trace ( "assiging from data {}, val {}: {}" , ( data == null ? "null" : data . getClass ( ) ) , ( val == null ? "null" : val . getClass ( ) ) , val ) ; } // if this is a foreign object then val is the foreign object's id val if ( foreignRefField != null && val != null ) { // get the current field value which is the foreign-id Object foreignRef = extractJavaFieldValue ( data ) ; /* * See if we don't need to create a new foreign object. If we are refreshing and the id field has not * changed then there is no need to create a new foreign object and maybe lose previously refreshed field * information. */ if ( foreignRef != null && foreignRef . equals ( val ) ) { return ; } // awhitlock: raised as OrmLite issue: bug #122 Object cachedVal ; ObjectCache foreignCache = foreignDao . getObjectCache ( ) ; if ( foreignCache == null ) { cachedVal = null ; } else { cachedVal = foreignCache . get ( getType ( ) , val ) ; } if ( cachedVal != null ) { val = cachedVal ; } else if ( ! parentObject ) { // the value we are to assign to our field is now the foreign object itself val = createForeignObject ( connectionSource , val , objectCache ) ; } } if ( fieldSetMethod == null ) { try { field . set ( data , val ) ; } catch ( IllegalArgumentException e ) { if ( val == null ) { throw SqlExceptionUtil . create ( "Could not assign object '" + val + "' to field " + this , e ) ; } else { throw SqlExceptionUtil . create ( "Could not assign object '" + val + "' of type " + val . getClass ( ) + " to field " + this , e ) ; } } catch ( IllegalAccessException e ) { throw SqlExceptionUtil . create ( "Could not assign object '" + val + "' of type " + val . getClass ( ) + "' to field " + this , e ) ; } } else { try { fieldSetMethod . invoke ( data , val ) ; } catch ( Exception e ) { throw SqlExceptionUtil . create ( "Could not call " + fieldSetMethod + " on object with '" + val + "' for " + this , e ) ; } } } | Assign to the data object the val corresponding to the fieldType . | 570 | 14 |
146,875 | public Object assignIdValue ( ConnectionSource connectionSource , Object data , Number val , ObjectCache objectCache ) throws SQLException { Object idVal = dataPersister . convertIdNumber ( val ) ; if ( idVal == null ) { throw new SQLException ( "Invalid class " + dataPersister + " for sequence-id " + this ) ; } else { assignField ( connectionSource , data , idVal , false , objectCache ) ; return idVal ; } } | Assign an ID value to this field . | 103 | 9 |
146,876 | public < FV > FV extractRawJavaFieldValue ( Object object ) throws SQLException { Object val ; if ( fieldGetMethod == null ) { try { // field object may not be a T yet val = field . get ( object ) ; } catch ( Exception e ) { throw SqlExceptionUtil . create ( "Could not get field value for " + this , e ) ; } } else { try { val = fieldGetMethod . invoke ( object ) ; } catch ( Exception e ) { throw SqlExceptionUtil . create ( "Could not call " + fieldGetMethod + " for " + this , e ) ; } } @ SuppressWarnings ( "unchecked" ) FV converted = ( FV ) val ; return converted ; } | Return the value from the field in the object that is defined by this FieldType . | 164 | 17 |
146,877 | public Object extractJavaFieldValue ( Object object ) throws SQLException { Object val = extractRawJavaFieldValue ( object ) ; // if this is a foreign object then we want its reference field if ( foreignRefField != null && val != null ) { val = foreignRefField . extractRawJavaFieldValue ( val ) ; } return val ; } | Return the value from the field in the object that is defined by this FieldType . If the field is a foreign object then the ID of the field is returned instead . | 74 | 34 |
146,878 | public Object convertJavaFieldToSqlArgValue ( Object fieldVal ) throws SQLException { /* * Limitation here. Some people may want to override the null with their own value in the converter but we * currently don't allow that. Specifying a default value I guess is a better mechanism. */ if ( fieldVal == null ) { return null ; } else { return fieldConverter . javaToSqlArg ( this , fieldVal ) ; } } | Convert a field value to something suitable to be stored in the database . | 98 | 15 |
146,879 | public Object convertStringToJavaField ( String value , int columnPos ) throws SQLException { if ( value == null ) { return null ; } else { return fieldConverter . resultStringToJava ( this , value , columnPos ) ; } } | Convert a string value into the appropriate Java field value . | 55 | 12 |
146,880 | public Object moveToNextValue ( Object val ) throws SQLException { if ( dataPersister == null ) { return null ; } else { return dataPersister . moveToNextValue ( val ) ; } } | Move the SQL value to the next one for version processing . | 46 | 12 |
146,881 | public < FT , FID > BaseForeignCollection < FT , FID > buildForeignCollection ( Object parent , FID id ) throws SQLException { // this can happen if we have a foreign-auto-refresh scenario if ( foreignFieldType == null ) { return null ; } @ SuppressWarnings ( "unchecked" ) Dao < FT , FID > castDao = ( Dao < FT , FID > ) foreignDao ; if ( ! fieldConfig . isForeignCollectionEager ( ) ) { // we know this won't go recursive so no need for the counters return new LazyForeignCollection < FT , FID > ( castDao , parent , id , foreignFieldType , fieldConfig . getForeignCollectionOrderColumnName ( ) , fieldConfig . isForeignCollectionOrderAscending ( ) ) ; } // try not to create level counter objects unless we have to LevelCounters levelCounters = threadLevelCounters . get ( ) ; if ( levelCounters == null ) { if ( fieldConfig . getForeignCollectionMaxEagerLevel ( ) == 0 ) { // then return a lazy collection instead return new LazyForeignCollection < FT , FID > ( castDao , parent , id , foreignFieldType , fieldConfig . getForeignCollectionOrderColumnName ( ) , fieldConfig . isForeignCollectionOrderAscending ( ) ) ; } levelCounters = new LevelCounters ( ) ; threadLevelCounters . set ( levelCounters ) ; } if ( levelCounters . foreignCollectionLevel == 0 ) { levelCounters . foreignCollectionLevelMax = fieldConfig . getForeignCollectionMaxEagerLevel ( ) ; } // are we over our level limit? if ( levelCounters . foreignCollectionLevel >= levelCounters . foreignCollectionLevelMax ) { // then return a lazy collection instead return new LazyForeignCollection < FT , FID > ( castDao , parent , id , foreignFieldType , fieldConfig . getForeignCollectionOrderColumnName ( ) , fieldConfig . isForeignCollectionOrderAscending ( ) ) ; } levelCounters . foreignCollectionLevel ++ ; try { return new EagerForeignCollection < FT , FID > ( castDao , parent , id , foreignFieldType , fieldConfig . getForeignCollectionOrderColumnName ( ) , fieldConfig . isForeignCollectionOrderAscending ( ) ) ; } finally { levelCounters . foreignCollectionLevel -- ; } } | Build and return a foreign collection based on the field settings that matches the id argument . This can return null in certain circumstances . | 517 | 25 |
146,882 | public < FV > FV getFieldValueIfNotDefault ( Object object ) throws SQLException { @ SuppressWarnings ( "unchecked" ) FV fieldValue = ( FV ) extractJavaFieldValue ( object ) ; if ( isFieldValueDefault ( fieldValue ) ) { return null ; } else { return fieldValue ; } } | Return the value of field in the data argument if it is not the default value for the class . If it is the default then null is returned . | 76 | 30 |
146,883 | public boolean isObjectsFieldValueDefault ( Object object ) throws SQLException { Object fieldValue = extractJavaFieldValue ( object ) ; return isFieldValueDefault ( fieldValue ) ; } | Return whether or not the data object has a default value passed for this field of this type . | 41 | 19 |
146,884 | public Object getJavaDefaultValueDefault ( ) { if ( field . getType ( ) == boolean . class ) { return DEFAULT_VALUE_BOOLEAN ; } else if ( field . getType ( ) == byte . class || field . getType ( ) == Byte . class ) { return DEFAULT_VALUE_BYTE ; } else if ( field . getType ( ) == char . class || field . getType ( ) == Character . class ) { return DEFAULT_VALUE_CHAR ; } else if ( field . getType ( ) == short . class || field . getType ( ) == Short . class ) { return DEFAULT_VALUE_SHORT ; } else if ( field . getType ( ) == int . class || field . getType ( ) == Integer . class ) { return DEFAULT_VALUE_INT ; } else if ( field . getType ( ) == long . class || field . getType ( ) == Long . class ) { return DEFAULT_VALUE_LONG ; } else if ( field . getType ( ) == float . class || field . getType ( ) == Float . class ) { return DEFAULT_VALUE_FLOAT ; } else if ( field . getType ( ) == double . class || field . getType ( ) == Double . class ) { return DEFAULT_VALUE_DOUBLE ; } else { return null ; } } | Return whether or not the field value passed in is the default value for the type of the field . Null will return true . | 295 | 25 |
146,885 | private < FT , FID > FT createForeignShell ( ConnectionSource connectionSource , Object val , ObjectCache objectCache ) throws SQLException { @ SuppressWarnings ( "unchecked" ) Dao < FT , FID > castDao = ( Dao < FT , FID > ) foreignDao ; FT foreignObject = castDao . createObjectInstance ( ) ; foreignIdField . assignField ( connectionSource , foreignObject , val , false , objectCache ) ; return foreignObject ; } | Create a shell object and assign its id field . | 109 | 10 |
146,886 | private FieldType findForeignFieldType ( Class < ? > clazz , Class < ? > foreignClass , Dao < ? , ? > foreignDao ) throws SQLException { String foreignColumnName = fieldConfig . getForeignCollectionForeignFieldName ( ) ; for ( FieldType fieldType : foreignDao . getTableInfo ( ) . getFieldTypes ( ) ) { if ( fieldType . getType ( ) == foreignClass && ( foreignColumnName == null || fieldType . getField ( ) . getName ( ) . equals ( foreignColumnName ) ) ) { if ( ! fieldType . fieldConfig . isForeign ( ) && ! fieldType . fieldConfig . isForeignAutoRefresh ( ) ) { // this may never be reached throw new SQLException ( "Foreign collection object " + clazz + " for field '" + field . getName ( ) + "' contains a field of class " + foreignClass + " but it's not foreign" ) ; } return fieldType ; } } // build our complex error message StringBuilder sb = new StringBuilder ( ) ; sb . append ( "Foreign collection class " ) . append ( clazz . getName ( ) ) ; sb . append ( " for field '" ) . append ( field . getName ( ) ) . append ( "' column-name does not contain a foreign field" ) ; if ( foreignColumnName != null ) { sb . append ( " named '" ) . append ( foreignColumnName ) . append ( ' ' ) ; } sb . append ( " of class " ) . append ( foreignClass . getName ( ) ) ; throw new SQLException ( sb . toString ( ) ) ; } | If we have a class Foo with a collection of Bar s then we go through Bar s DAO looking for a Foo field . We need this field to build the query that is able to find all Bar s that have foo_id that matches our id . | 364 | 52 |
146,887 | public T execute ( DatabaseConnection databaseConnection , ID id , ObjectCache objectCache ) throws SQLException { if ( objectCache != null ) { T result = objectCache . get ( clazz , id ) ; if ( result != null ) { return result ; } } Object [ ] args = new Object [ ] { convertIdToFieldObject ( id ) } ; // @SuppressWarnings("unchecked") Object result = databaseConnection . queryForOne ( statement , args , argFieldTypes , this , objectCache ) ; if ( result == null ) { logger . debug ( "{} using '{}' and {} args, got no results" , label , statement , args . length ) ; } else if ( result == DatabaseConnection . MORE_THAN_ONE ) { logger . error ( "{} using '{}' and {} args, got >1 results" , label , statement , args . length ) ; logArgs ( args ) ; throw new SQLException ( label + " got more than 1 result: " + statement ) ; } else { logger . debug ( "{} using '{}' and {} args, got 1 result" , label , statement , args . length ) ; } logArgs ( args ) ; @ SuppressWarnings ( "unchecked" ) T castResult = ( T ) result ; return castResult ; } | Query for an object in the database which matches the id argument . | 287 | 13 |
146,888 | protected void appendStringType ( StringBuilder sb , FieldType fieldType , int fieldWidth ) { if ( isVarcharFieldWidthSupported ( ) ) { sb . append ( "VARCHAR(" ) . append ( fieldWidth ) . append ( ' ' ) ; } else { sb . append ( "VARCHAR" ) ; } } | Output the SQL type for a Java String . | 75 | 9 |
146,889 | private void appendDefaultValue ( StringBuilder sb , FieldType fieldType , Object defaultValue ) { if ( fieldType . isEscapedDefaultValue ( ) ) { appendEscapedWord ( sb , defaultValue . toString ( ) ) ; } else { sb . append ( defaultValue ) ; } } | Output the SQL type for the default value for the type . | 66 | 12 |
146,890 | private void addSingleUnique ( StringBuilder sb , FieldType fieldType , List < String > additionalArgs , List < String > statementsAfter ) { StringBuilder alterSb = new StringBuilder ( ) ; alterSb . append ( " UNIQUE (" ) ; appendEscapedEntityName ( alterSb , fieldType . getColumnName ( ) ) ; alterSb . append ( ' ' ) ; additionalArgs . add ( alterSb . toString ( ) ) ; } | Add SQL to handle a unique = true field . THis is not for uniqueCombo = true . | 102 | 21 |
146,891 | public static void registerDataPersisters ( DataPersister ... dataPersisters ) { // we build the map and replace it to lower the chance of concurrency issues List < DataPersister > newList = new ArrayList < DataPersister > ( ) ; if ( registeredPersisters != null ) { newList . addAll ( registeredPersisters ) ; } for ( DataPersister persister : dataPersisters ) { newList . add ( persister ) ; } registeredPersisters = newList ; } | Register a data type with the manager . | 105 | 8 |
146,892 | public static DataPersister lookupForField ( Field field ) { // see if the any of the registered persisters are valid first if ( registeredPersisters != null ) { for ( DataPersister persister : registeredPersisters ) { if ( persister . isValidForField ( field ) ) { return persister ; } // check the classes instead for ( Class < ? > clazz : persister . getAssociatedClasses ( ) ) { if ( field . getType ( ) == clazz ) { return persister ; } } } } // look it up in our built-in map by class DataPersister dataPersister = builtInMap . get ( field . getType ( ) . getName ( ) ) ; if ( dataPersister != null ) { return dataPersister ; } /* * Special case for enum types. We can't put this in the registered persisters because we want people to be able * to override it. */ if ( field . getType ( ) . isEnum ( ) ) { return DEFAULT_ENUM_PERSISTER ; } else { /* * Serializable classes return null here because we don't want them to be automatically configured for * forwards compatibility with future field types that happen to be Serializable. */ return null ; } } | Lookup the data - type associated with the class . | 266 | 11 |
146,893 | public int update ( DatabaseConnection databaseConnection , T data , ObjectCache objectCache ) throws SQLException { try { // there is always and id field as an argument so just return 0 lines updated if ( argFieldTypes . length <= 1 ) { return 0 ; } Object [ ] args = getFieldObjects ( data ) ; Object newVersion = null ; if ( versionFieldType != null ) { newVersion = versionFieldType . extractJavaFieldValue ( data ) ; newVersion = versionFieldType . moveToNextValue ( newVersion ) ; args [ versionFieldTypeIndex ] = versionFieldType . convertJavaFieldToSqlArgValue ( newVersion ) ; } int rowC = databaseConnection . update ( statement , args , argFieldTypes ) ; if ( rowC > 0 ) { if ( newVersion != null ) { // if we have updated a row then update the version field in our object to the new value versionFieldType . assignField ( connectionSource , data , newVersion , false , null ) ; } if ( objectCache != null ) { // if we've changed something then see if we need to update our cache Object id = idField . extractJavaFieldValue ( data ) ; T cachedData = objectCache . get ( clazz , id ) ; if ( cachedData != null && cachedData != data ) { // copy each field from the updated data into the cached object for ( FieldType fieldType : tableInfo . getFieldTypes ( ) ) { if ( fieldType != idField ) { fieldType . assignField ( connectionSource , cachedData , fieldType . extractJavaFieldValue ( data ) , false , objectCache ) ; } } } } } logger . debug ( "update data with statement '{}' and {} args, changed {} rows" , statement , args . length , rowC ) ; if ( args . length > 0 ) { // need to do the (Object) cast to force args to be a single object logger . trace ( "update arguments: {}" , ( Object ) args ) ; } return rowC ; } catch ( SQLException e ) { throw SqlExceptionUtil . create ( "Unable to run update stmt on object " + data + ": " + statement , e ) ; } } | Update the object in the database . | 476 | 7 |
146,894 | protected Object [ ] getFieldObjects ( Object data ) throws SQLException { Object [ ] objects = new Object [ argFieldTypes . length ] ; for ( int i = 0 ; i < argFieldTypes . length ; i ++ ) { FieldType fieldType = argFieldTypes [ i ] ; if ( fieldType . isAllowGeneratedIdInsert ( ) ) { objects [ i ] = fieldType . getFieldValueIfNotDefault ( data ) ; } else { objects [ i ] = fieldType . extractJavaFieldToSqlArgValue ( data ) ; } if ( objects [ i ] == null ) { // NOTE: the default value could be null as well objects [ i ] = fieldType . getDefaultValue ( ) ; } } return objects ; } | Return the array of field objects pulled from the data object . | 162 | 12 |
146,895 | private CompiledStatement assignStatementArguments ( CompiledStatement stmt ) throws SQLException { boolean ok = false ; try { if ( limit != null ) { // we use this if SQL statement LIMITs are not supported by this database type stmt . setMaxRows ( limit . intValue ( ) ) ; } // set any arguments if we are logging our object Object [ ] argValues = null ; if ( logger . isLevelEnabled ( Level . TRACE ) && argHolders . length > 0 ) { argValues = new Object [ argHolders . length ] ; } for ( int i = 0 ; i < argHolders . length ; i ++ ) { Object argValue = argHolders [ i ] . getSqlArgValue ( ) ; FieldType fieldType = argFieldTypes [ i ] ; SqlType sqlType ; if ( fieldType == null ) { sqlType = argHolders [ i ] . getSqlType ( ) ; } else { sqlType = fieldType . getSqlType ( ) ; } stmt . setObject ( i , argValue , sqlType ) ; if ( argValues != null ) { argValues [ i ] = argValue ; } } logger . debug ( "prepared statement '{}' with {} args" , statement , argHolders . length ) ; if ( argValues != null ) { // need to do the (Object) cast to force args to be a single object logger . trace ( "prepared statement arguments: {}" , ( Object ) argValues ) ; } ok = true ; return stmt ; } finally { if ( ! ok ) { IOUtils . closeThrowSqlException ( stmt , "statement" ) ; } } } | Assign arguments to the statement . | 367 | 7 |
146,896 | protected DatabaseConnection getSavedConnection ( ) { NestedConnection nested = specialConnection . get ( ) ; if ( nested == null ) { return null ; } else { return nested . connection ; } } | Returns the connection that has been saved or null if none . | 42 | 12 |
146,897 | protected boolean isSavedConnection ( DatabaseConnection connection ) { NestedConnection currentSaved = specialConnection . get ( ) ; if ( currentSaved == null ) { return false ; } else if ( currentSaved . connection == connection ) { // ignore the release when we have a saved connection return true ; } else { return false ; } } | Return true if the connection being released is the one that has been saved . | 72 | 15 |
146,898 | protected boolean clearSpecial ( DatabaseConnection connection , Logger logger ) { NestedConnection currentSaved = specialConnection . get ( ) ; boolean cleared = false ; if ( connection == null ) { // ignored } else if ( currentSaved == null ) { logger . error ( "no connection has been saved when clear() called" ) ; } else if ( currentSaved . connection == connection ) { if ( currentSaved . decrementAndGet ( ) == 0 ) { // we only clear the connection if nested counter is 0 specialConnection . set ( null ) ; } cleared = true ; } else { logger . error ( "connection saved {} is not the one being cleared {}" , currentSaved . connection , connection ) ; } // release should then be called after clear return cleared ; } | Clear the connection that was previously saved . | 165 | 8 |
146,899 | protected boolean isSingleConnection ( DatabaseConnection conn1 , DatabaseConnection conn2 ) throws SQLException { // initialize the connections auto-commit flags conn1 . setAutoCommit ( true ) ; conn2 . setAutoCommit ( true ) ; try { // change conn1's auto-commit to be false conn1 . setAutoCommit ( false ) ; if ( conn2 . isAutoCommit ( ) ) { // if the 2nd connection's auto-commit is still true then we have multiple connections return false ; } else { // if the 2nd connection's auto-commit is also false then we have a single connection return true ; } } finally { // restore its auto-commit conn1 . setAutoCommit ( true ) ; } } | Return true if the two connections seem to one one connection under the covers . | 158 | 15 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.