liquibase.statement.core.InsertStatement Java Examples

The following examples show how to use liquibase.statement.core.InsertStatement. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source Project: liquibase-impala   Author: eselyavka   File: ImpalaLockDatabaseChangeLogGenerator.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Sql[] generateSql(LockDatabaseChangeLogStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) {
    String catalogName = database.getLiquibaseCatalogName();
    String schemaName = database.getDefaultSchemaName();
    String tableName = database.getDatabaseChangeLogLockTableName();
    InsertStatement insertStatement = new InsertStatement(catalogName, schemaName, tableName)
            .addColumnValue("ID", 1)
            .addColumnValue("LOCKED", Boolean.TRUE)
            .addColumnValue("LOCKEDBY", hostname + " [" + hostaddress + "]")
            .addColumnValue("LOCKGRANTED", DateTimeUtils.getCurrentTS("yyyy-MM-dd HH:mm:ss"));

    return CustomSqlGenerator.generateSql(database,
            UserSessionSettings.syncDdlStart(),
            new TruncateTableStatement(catalogName, schemaName, tableName),
            insertStatement,
            UserSessionSettings.syncDdlStop());
}
 
Example #2
Source Project: liquibase-mssql   Author: sabomichal   File: InsertGenerator.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Sql[] generateSql(InsertStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) {
    Boolean identityInsertEnabled = false;
    if (statement instanceof InsertStatementMSSQL) {
        identityInsertEnabled = ((InsertStatementMSSQL)statement).getIdentityInsertEnabled();
    }
    if (identityInsertEnabled == null || !identityInsertEnabled) {
        return super.generateSql(statement, database, sqlGeneratorChain);
    }
    String tableName = database.escapeTableName(statement.getCatalogName(), statement.getSchemaName(), statement.getTableName());
    String enableIdentityInsert = "SET IDENTITY_INSERT " + tableName + " ON";
    String disableIdentityInsert = "SET IDENTITY_INSERT " + tableName + " OFF";
    String safelyEnableIdentityInsert = ifTableHasIdentityColumn(enableIdentityInsert, statement, database.getDefaultSchemaName());
    String safelyDisableIdentityInsert = ifTableHasIdentityColumn(disableIdentityInsert, statement, database.getDefaultSchemaName());

    List<Sql> sql = new ArrayList<Sql>(Arrays.asList(sqlGeneratorChain.generateSql(statement, database)));
    sql.add(0, new UnparsedSql(safelyEnableIdentityInsert));
    sql.add(new UnparsedSql(safelyDisableIdentityInsert));
    return sql.toArray(new Sql[sql.size()]);
}
 
Example #3
Source Project: liquibase-mssql   Author: sabomichal   File: InsertGenerator.java    License: Apache License 2.0 6 votes vote down vote up
private String ifTableHasIdentityColumn(String then, InsertStatement statement, String defaultSchemaName) {
       String tableName = statement.getTableName();
       String schemaName = statement.getSchemaName();
if (schemaName == null) {
    if (defaultSchemaName != null && !defaultSchemaName.isEmpty()) {
	schemaName = defaultSchemaName;
    } else {
	schemaName = "dbo";
    }
}

       Map<String, String> tokens = new HashMap<String, String>();
       tokens.put("${tableName}", tableName);
       tokens.put("${schemaName}", schemaName);
       tokens.put("${then}", then);
       return performTokenReplacement(IF_TABLE_HAS_IDENTITY_STATEMENT, tokens);
   }
 
Example #4
Source Project: liquibase-mssql   Author: sabomichal   File: InsertDataChangeMSSQL.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public SqlStatement[] generateStatements(Database database) {
    SqlStatement[] statements = super.generateStatements(database);
    if (!MSSQLDatabase.PRODUCT_NAME.equals(database.getDatabaseProductName())) {
    	return statements;
    }
    List<SqlStatement> wrappedStatements = new ArrayList<SqlStatement>(statements.length);
    for (SqlStatement statement : statements) {
        if (statement instanceof InsertStatement) {
            wrappedStatements.add(new InsertStatementMSSQL((InsertStatement) statement, identityInsertEnabled));
        } else {
            wrappedStatements.add(statement);
        }
    }
    return wrappedStatements.toArray(new SqlStatement[0]);
}
 
Example #5
Source Project: liquibase-mssql   Author: sabomichal   File: LoadDataChangeMSSQL.java    License: Apache License 2.0 6 votes vote down vote up
@Override
   public SqlStatement[] generateStatements(Database database) {
SqlStatement[] statements = super.generateStatements(database);
   if (!MSSQLDatabase.PRODUCT_NAME.equals(database.getDatabaseProductName())) {
   	return statements;
   }
List<SqlStatement> wrappedStatements = new ArrayList<SqlStatement>(statements.length);
for (SqlStatement statement : statements) {
    if (statement instanceof InsertStatement) {
	wrappedStatements.add(new InsertStatementMSSQL((InsertStatement) statement, identityInsertEnabled));
    } else if(statement instanceof InsertSetStatement) {
        wrappedStatements.add(new InsertSetStatementMSSQL((InsertSetStatement) statement, identityInsertEnabled));
    } else {
	wrappedStatements.add(statement);
    }
}
return wrappedStatements.toArray(new SqlStatement[0]);
   }
 
Example #6
Source Project: liquibase-mssql   Author: sabomichal   File: InsertGeneratorTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void integrates() throws DatabaseException {

    //Liquibase must find our mssql impl.
    Database database= DatabaseFactory.getInstance().findCorrectDatabaseImplementation(new OfflineConnection("offline:mssql", null));

    InsertStatement statement = new InsertStatement(null, null, "TABLE_NAME");
    statement.addColumnValue("id", 1);
    statement.addColumnValue("name", "asdf");
    
    statement = new InsertStatementMSSQL(statement, true);

    Sql[] sql = SqlGeneratorFactory.getInstance().generateSql(statement, database);
    assertEquals(3, sql.length);

    for (Sql currentSql : sql) {
        assertSqlHasNoDanglingTokens(currentSql.toSql());
    }
}
 
Example #7
Source Project: keycloak   Author: keycloak   File: JpaUpdate1_2_0_Beta1.java    License: Apache License 2.0 6 votes vote down vote up
protected void convertSocialToIdFedUsers() throws SQLException, DatabaseException {
    String federatedIdentityTableName = database.correctObjectName("FEDERATED_IDENTITY", Table.class);
    PreparedStatement statement = jdbcConnection.prepareStatement("select REALM_ID, USER_ID, SOCIAL_PROVIDER, SOCIAL_USER_ID, SOCIAL_USERNAME from " + getTableName("USER_SOCIAL_LINK"));
    try {
        ResultSet resultSet = statement.executeQuery();
        try {
            int count = 0;
            while (resultSet.next()) {
                InsertStatement insert = new InsertStatement(null, null, federatedIdentityTableName)
                        .addColumnValue("REALM_ID", resultSet.getString("REALM_ID"))
                        .addColumnValue("USER_ID", resultSet.getString("USER_ID"))
                        .addColumnValue("IDENTITY_PROVIDER", resultSet.getString("SOCIAL_PROVIDER"))
                        .addColumnValue("FEDERATED_USER_ID", resultSet.getString("SOCIAL_USER_ID"))
                        .addColumnValue("FEDERATED_USERNAME", resultSet.getString("SOCIAL_USERNAME"));
                count++;
                statements.add(insert);
            }

            confirmationMessage.append("Updating " + count + " social links to federated identities. ");
        } finally {
            resultSet.close();
        }
    } finally {
        statement.close();
    }
}
 
Example #8
Source Project: keycloak   Author: keycloak   File: JpaUpdate1_2_0_Beta1.java    License: Apache License 2.0 6 votes vote down vote up
private void addAdminRole(String roleName, String realmId, String applicationId, String realmAdminAppRoleId) {
    String roleTableName = database.correctObjectName("KEYCLOAK_ROLE", Table.class);
    String compositeRoleTableName = database.correctObjectName("COMPOSITE_ROLE", Table.class);
    String newRoleId = KeycloakModelUtils.generateId();

    InsertStatement insertRole = new InsertStatement(null, null, roleTableName)
            .addColumnValue("ID", newRoleId)
            .addColumnValue("APP_REALM_CONSTRAINT", applicationId)
            .addColumnValue("APPLICATION_ROLE", true)
            .addColumnValue("NAME", roleName)
            .addColumnValue("REALM_ID", realmId)
            .addColumnValue("APPLICATION", applicationId);

    // Add newly created role to the composite roles of 'realm-admin' role
    InsertStatement insertCompRole = new InsertStatement(null, null, compositeRoleTableName)
            .addColumnValue("COMPOSITE", realmAdminAppRoleId)
            .addColumnValue("CHILD_ROLE", newRoleId);

    statements.add(insertRole);
    statements.add(insertCompRole);
}
 
Example #9
Source Project: keycloak   Author: keycloak   File: CustomInsertLockRecordGenerator.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Sql[] generateSql(InitializeDatabaseChangeLogLockTableStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) {
    // get the IDs that are already in the database if migration
    Set<Integer> currentIds = new HashSet<>();
    if (statement instanceof CustomInitializeDatabaseChangeLogLockTableStatement) {
        currentIds = ((CustomInitializeDatabaseChangeLogLockTableStatement) statement).getCurrentIds();
    }

    // generate all the IDs that are currently missing in the lock table
    List<Sql> result = new ArrayList<>();
    for (DBLockProvider.Namespace lock : DBLockProvider.Namespace.values()) {
        if (!currentIds.contains(lock.getId())) {
            InsertStatement insertStatement = new InsertStatement(database.getLiquibaseCatalogName(), database.getLiquibaseSchemaName(), database.getDatabaseChangeLogLockTableName())
                    .addColumnValue("ID", lock.getId())
                    .addColumnValue("LOCKED", Boolean.FALSE);
            result.addAll(Arrays.asList(SqlGeneratorFactory.getInstance().generateSql(insertStatement, database)));
        }
    }

    return result.toArray(new Sql[result.size()]);
}
 
Example #10
@Override
public Sql[] generateSql(InitializeDatabaseChangeLogLockTableStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) {
    String catalogName = database.getLiquibaseCatalogName();
    String schemaName = database.getDefaultSchemaName();
    String tableName = database.getDatabaseChangeLogLockTableName();
    InsertStatement insertStatement = new InsertStatement(catalogName, schemaName, tableName)
            .addColumnValue("ID", 1)
            .addColumnValue("LOCKED", Boolean.FALSE);

    return CustomSqlGenerator.generateSql(database,
            UserSessionSettings.syncDdlStart(),
            new TruncateTableStatement(catalogName, schemaName, tableName),
            insertStatement,
            UserSessionSettings.syncDdlStop());
}
 
Example #11
Source Project: liquibase-impala   Author: eselyavka   File: ImpalaUnlockDatabaseChangeLogGenerator.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Sql[] generateSql(UnlockDatabaseChangeLogStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) {
    String catalogName = database.getLiquibaseCatalogName();
    String schemaName = database.getDefaultSchemaName();
    String tableName = database.getDatabaseChangeLogLockTableName();
    InsertStatement insertStatement = new InsertStatement(catalogName, schemaName, tableName)
            .addColumnValue("ID", 1)
            .addColumnValue("LOCKED", Boolean.FALSE);

    return CustomSqlGenerator.generateSql(database,
            UserSessionSettings.syncDdlStart(),
            new TruncateTableStatement(catalogName, schemaName, tableName),
            insertStatement,
            UserSessionSettings.syncDdlStop());
}
 
Example #12
Source Project: liquibase-spatial   Author: lonnyj   File: AbstractSpatialInsertGenerator.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Find any fields that look like WKT or EWKT and replace them with the database-specific value.
 */
@Override
public Sql[] generateSql(final InsertStatement statement, final Database database,
      final SqlGeneratorChain sqlGeneratorChain) {
   for (final Entry<String, Object> entry : statement.getColumnValues().entrySet()) {
      entry.setValue(handleColumnValue(entry.getValue(), database));
   }
   return super.generateSql(statement, database, sqlGeneratorChain);
}
 
Example #13
Source Project: liquibase-mssql   Author: sabomichal   File: InsertSetStatementMSSQL.java    License: Apache License 2.0 5 votes vote down vote up
public InsertSetStatementMSSQL(InsertSetStatement statement, Boolean identityInsertEnable) {
    super(statement.getCatalogName(), statement.getSchemaName(), statement.getTableName());
    for (InsertStatement insertStatement : statement.getStatements()) {
        addInsertStatement(insertStatement);
    }
    this.identityInsertEnabled = identityInsertEnable;
}
 
Example #14
Source Project: liquibase-mssql   Author: sabomichal   File: InsertStatementMSSQL.java    License: Apache License 2.0 5 votes vote down vote up
public InsertStatementMSSQL(InsertStatement statement, Boolean identityInsertEnable) {
    super(statement.getCatalogName(), statement.getSchemaName(), statement.getTableName());
    Map<String, Object> values = statement.getColumnValues();
    for (String key : values.keySet()) {
        addColumnValue(key, values.get(key));
    }
    this.identityInsertEnabled = identityInsertEnable;
}
 
Example #15
Source Project: keycloak   Author: keycloak   File: JpaUpdate1_2_0_CR1.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void generateStatementsImpl() throws CustomChangeException {
    String realmClientTableName = database.correctObjectName("REALM_CLIENT", Table.class);

    try {
        String trueValue = DataTypeFactory.getInstance().getTrueBooleanValue(database);
        PreparedStatement statement = jdbcConnection.prepareStatement("select CLIENT.REALM_ID, CLIENT.ID CLIENT_ID from " + getTableName("CLIENT") + " CLIENT where CLIENT.CONSENT_REQUIRED = " + trueValue);

        try {
            ResultSet resultSet = statement.executeQuery();
            try {
                while (resultSet.next()) {
                    String realmId = resultSet.getString("REALM_ID");
                    String oauthClientId = resultSet.getString("CLIENT_ID");

                    InsertStatement realmClientInsert = new InsertStatement(null, null, realmClientTableName)
                            .addColumnValue("REALM_ID", realmId)
                            .addColumnValue("CLIENT_ID", oauthClientId);
                    statements.add(realmClientInsert);
                }
            } finally {
                resultSet.close();
            }
        } finally {
            statement.close();
        }

        confirmationMessage.append("Inserted " + statements.size() + " OAuth Clients to REALM_CLIENT table");
    } catch (Exception e) {
        throw new CustomChangeException(getTaskId() + ": Exception when updating data from previous version", e);
    }
}
 
Example #16
Source Project: keycloak   Author: keycloak   File: AuthzResourceUseMoreURIs.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void generateStatementsImpl() throws CustomChangeException {
    try {
        PreparedStatement statement = jdbcConnection.prepareStatement("select ID,URI from " + getTableName("RESOURCE_SERVER_RESOURCE") + " where URI is not null");

        try {
            ResultSet resultSet = statement.executeQuery();
            try {
                while (resultSet.next()) {
                    String resourceId = resultSet.getString(1);
                    String resourceUri = resultSet.getString(2);

                    InsertStatement insertComponent = new InsertStatement(null, null, database.correctObjectName("RESOURCE_URIS", Table.class))
                            .addColumnValue("RESOURCE_ID", resourceId)
                            .addColumnValue("VALUE", resourceUri);

                    statements.add(insertComponent);
                }
            } finally {
                resultSet.close();
            }
        } finally {
            statement.close();
        }

        confirmationMessage.append("Moved " + statements.size() + " records from RESOURCE_SERVER_RESOURCE to RESOURCE_URIS table");
    } catch (Exception e) {
        throw new CustomChangeException(getTaskId() + ": Exception when updating data from previous version", e);
    }
}
 
Example #17
Source Project: keycloak   Author: keycloak   File: JpaUpdate4_0_0_DefaultClientScopes.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void generateStatementsImpl() throws CustomChangeException {
    String clientTableName = database.correctObjectName("CLIENT", Table.class);
    String clientScopeClientTableName = database.correctObjectName("CLIENT_SCOPE_CLIENT", Table.class);

    try (PreparedStatement statement = jdbcConnection.prepareStatement("SELECT ID, CLIENT_TEMPLATE_ID FROM " + clientTableName);
      ResultSet rs = statement.executeQuery()) {
        while (rs.next()) {
            String clientId = rs.getString(1);
            String clientTemplateId = rs.getString(2);

            if (clientId == null || clientId.trim().isEmpty()) {
                continue;
            }
            if (clientTemplateId == null || clientTemplateId.trim().isEmpty()) {
                continue;
            }

            statements.add(
              new InsertStatement(null, null, clientScopeClientTableName)
                .addColumnValue("CLIENT_ID", clientId.trim())
                .addColumnValue("SCOPE_ID", clientTemplateId.trim())
                .addColumnValue("DEFAULT_SCOPE", Boolean.TRUE)
            );
        }

        confirmationMessage.append("Updated " + statements.size() + " records in CLIENT_SCOPE_CLIENT table");
    } catch (Exception e) {
        throw new CustomChangeException(getTaskId() + ": Exception when updating data from previous version", e);
    }
}
 
Example #18
Source Project: keycloak   Author: keycloak   File: ExtractRealmKeysFromRealmTable.java    License: Apache License 2.0 5 votes vote down vote up
private InsertStatement componentConfigStatement(String componentId, String name, String value) {
    return new InsertStatement(null, null, database.correctObjectName("COMPONENT_CONFIG", Table.class))
            .addColumnValue("ID", KeycloakModelUtils.generateId())
            .addColumnValue("COMPONENT_ID", componentId)
            .addColumnValue("NAME", name)
            .addColumnValue("VALUE", value);
}
 
Example #19
Source Project: keycloak   Author: keycloak   File: AbstractUserFedToComponent.java    License: Apache License 2.0 5 votes vote down vote up
protected InsertStatement componentConfigStatement(String componentId, String name, String value) {
    return new InsertStatement(null, null, database.correctObjectName("COMPONENT_CONFIG", Table.class))
            .addColumnValue("ID", KeycloakModelUtils.generateId())
            .addColumnValue("COMPONENT_ID", componentId)
            .addColumnValue("NAME", name)
            .addColumnValue("VALUE", value);
}
 
Example #20
Source Project: liquibase-spatial   Author: lonnyj   File: SpatialInsertGeneratorGeoDB.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public boolean supports(final InsertStatement statement, final Database database) {
   return database instanceof DerbyDatabase || database instanceof H2Database;
}
 
Example #21
Source Project: liquibase-spatial   Author: lonnyj   File: SpatialInsertGeneratorOracle.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Verifies that the <code>InsertStatement</code> has WKT or EWKT.
 */
@Override
public boolean supports(final InsertStatement statement, final Database database) {
   return database instanceof OracleDatabase;
}
 
Example #22
Source Project: liquibase-spatial   Author: lonnyj   File: AbstractSpatialInsertGenerator.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public ValidationErrors validate(final InsertStatement statement, final Database database,
      final SqlGeneratorChain sqlGeneratorChain) {
   return sqlGeneratorChain.validate(statement, database);
}
 
Example #23
Source Project: liquibase-spatial   Author: lonnyj   File: SpatialInsertGeneratorMySQL.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public boolean supports(final InsertStatement statement, final Database database) {
   return database instanceof MySQLDatabase;
}
 
Example #24
Source Project: liquibase-mssql   Author: sabomichal   File: InsertGenerator.java    License: Apache License 2.0 4 votes vote down vote up
public boolean supports(InsertStatement statement, Database database) {
    return database instanceof MSSQLDatabase;
}
 
Example #25
Source Project: liquibase-mssql   Author: sabomichal   File: InsertGenerator.java    License: Apache License 2.0 4 votes vote down vote up
public ValidationErrors validate(InsertStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) {
    return sqlGeneratorChain.validate(statement, database);
}
 
Example #26
Source Project: keycloak   Author: keycloak   File: JpaUpdate1_2_0_Beta1.java    License: Apache License 2.0 4 votes vote down vote up
protected void convertSocialToIdFedRealms() throws SQLException, DatabaseException {
    String identityProviderTableName = database.correctObjectName("IDENTITY_PROVIDER", Table.class);
    String idpConfigTableName = database.correctObjectName("IDENTITY_PROVIDER_CONFIG", Table.class);

    String realmSocialConfigTable = getTableName("REALM_SOCIAL_CONFIG");
    String realmTableName = getTableName("REALM");
    PreparedStatement statement = jdbcConnection.prepareStatement("select RSC.NAME, VALUE, REALM_ID, UPDATE_PROFILE_ON_SOC_LOGIN from " + realmSocialConfigTable + " RSC," + realmTableName +
            " REALM where RSC.REALM_ID = REALM.ID ORDER BY RSC.REALM_ID, RSC.NAME");
    try {
        ResultSet resultSet = statement.executeQuery();
        try {
            boolean providerInProgress = false;
            String socialProviderId = null;
            String clientId = null;
            String clientSecret;
            String realmId = null;
            boolean updateProfileOnSocialLogin = false;
            boolean first = true;

            while (resultSet.next()) {
                if (first) {
                    confirmationMessage.append("Migrating social to identity providers: ");
                    first = false;
                }

                if (!providerInProgress) {
                    String key = resultSet.getString("NAME");
                    int keyIndex = key.indexOf(".key");
                    if (keyIndex == -1) {
                        throw new IllegalStateException("Can't parse the provider from column: " + key);
                    }

                    socialProviderId = key.substring(0, keyIndex);
                    clientId = resultSet.getString("VALUE");
                    realmId = resultSet.getString("REALM_ID");
                    updateProfileOnSocialLogin = resultSet.getBoolean("UPDATE_PROFILE_ON_SOC_LOGIN");
                    providerInProgress = true;
                } else {
                    clientSecret = resultSet.getString("VALUE");

                    String internalId = KeycloakModelUtils.generateId();
                    InsertStatement idpInsert = new InsertStatement(null, null, identityProviderTableName)
                            .addColumnValue("INTERNAL_ID", internalId)
                            .addColumnValue("ENABLED", true)
                            .addColumnValue("PROVIDER_ALIAS", socialProviderId)
                            .addColumnValue("PROVIDER_ID", socialProviderId)
                            .addColumnValue("UPDATE_PROFILE_FIRST_LOGIN", updateProfileOnSocialLogin)
                            .addColumnValue("STORE_TOKEN", false)
                            .addColumnValue("AUTHENTICATE_BY_DEFAULT", false)
                            .addColumnValue("REALM_ID", realmId);
                    InsertStatement clientIdInsert = new InsertStatement(null, null, idpConfigTableName)
                            .addColumnValue("IDENTITY_PROVIDER_ID", internalId)
                            .addColumnValue("NAME", "clientId")
                            .addColumnValue("VALUE", clientId);
                    InsertStatement clientSecretInsert = new InsertStatement(null, null, idpConfigTableName)
                            .addColumnValue("IDENTITY_PROVIDER_ID", internalId)
                            .addColumnValue("NAME", "clientSecret")
                            .addColumnValue("VALUE", clientSecret);

                    statements.add(idpInsert);
                    statements.add(clientIdInsert);
                    statements.add(clientSecretInsert);
                    confirmationMessage.append(socialProviderId + " in realm " + realmId + ", ");

                    providerInProgress = false;
                }
            }

            // It means that some provider where processed
            if (!first) {
                confirmationMessage.append(". ");
            }
        } finally {
            resultSet.close();
        }
    } finally {
        statement.close();
    }
}
 
Example #27
Source Project: keycloak   Author: keycloak   File: JpaUpdate1_2_0_Beta1.java    License: Apache License 2.0 4 votes vote down vote up
protected void addDefaultProtocolMappers() throws SQLException, DatabaseException {
    String protocolMapperTableName = database.correctObjectName("PROTOCOL_MAPPER", Table.class);
    String protocolMapperCfgTableName = database.correctObjectName("PROTOCOL_MAPPER_CONFIG", Table.class);

    PreparedStatement statement = jdbcConnection.prepareStatement("select ID, NAME, ALLOWED_CLAIMS_MASK from " + getTableName("CLIENT"));

    try {
        ResultSet resultSet = statement.executeQuery();
        try {
            boolean first = true;
            while (resultSet.next()) {
                if (first) {
                    confirmationMessage.append("Migrating claimsMask to protocol mappers for clients: ");
                    first = false;
                }

                Object acmObj = resultSet.getObject("ALLOWED_CLAIMS_MASK");
                long mask = (acmObj != null) ? ((Number) acmObj).longValue() : ClaimMask.ALL;

                MigrationProvider migrationProvider = this.kcSession.getProvider(MigrationProvider.class);
                List<ProtocolMapperRepresentation> protocolMappers = migrationProvider.getMappersForClaimMask(mask);

                for (ProtocolMapperRepresentation protocolMapper : protocolMappers) {
                    String mapperId = KeycloakModelUtils.generateId();

                    InsertStatement insert = new InsertStatement(null, null, protocolMapperTableName)
                            .addColumnValue("ID", mapperId)
                            .addColumnValue("PROTOCOL", protocolMapper.getProtocol())
                            .addColumnValue("NAME", protocolMapper.getName())
                            .addColumnValue("CONSENT_REQUIRED", false)
                            .addColumnValue("PROTOCOL_MAPPER_NAME", protocolMapper.getProtocolMapper())
                            .addColumnValue("CLIENT_ID", resultSet.getString("ID"));
                    statements.add(insert);

                    for (Map.Entry<String, String> cfgEntry : protocolMapper.getConfig().entrySet()) {
                        InsertStatement cfgInsert = new InsertStatement(null, null, protocolMapperCfgTableName)
                                .addColumnValue("PROTOCOL_MAPPER_ID", mapperId)
                                .addColumnValue("NAME", cfgEntry.getKey())
                                .addColumnValue("VALUE", cfgEntry.getValue());
                        statements.add(cfgInsert);
                    }

                }

                confirmationMessage.append(resultSet.getString("NAME") + ", ");
            }

            // It means that some provider where processed
            if (!first) {
                confirmationMessage.append(". ");
            }
        } finally {
            resultSet.close();
        }
    } finally {
        statement.close();
    }
}
 
Example #28
Source Project: keycloak   Author: keycloak   File: ExtractRealmKeysFromRealmTable.java    License: Apache License 2.0 4 votes vote down vote up
@Override
protected void generateStatementsImpl() throws CustomChangeException {
    try {
        PreparedStatement statement = jdbcConnection.prepareStatement("select ID, PRIVATE_KEY, CERTIFICATE from " + getTableName("REALM"));

        try {
            ResultSet resultSet = statement.executeQuery();
            try {
                while (resultSet.next()) {
                    String realmId = resultSet.getString(1);
                    String privateKeyPem = resultSet.getString(2);
                    String certificatePem = resultSet.getString(3);

                    String componentId = KeycloakModelUtils.generateId();

                    InsertStatement insertComponent = new InsertStatement(null, null, database.correctObjectName("COMPONENT", Table.class))
                            .addColumnValue("ID", componentId)
                            .addColumnValue("REALM_ID", realmId)
                            .addColumnValue("PARENT_ID", realmId)
                            .addColumnValue("NAME", "rsa")
                            .addColumnValue("PROVIDER_ID", "rsa")
                            .addColumnValue("PROVIDER_TYPE", KeyProvider.class.getName());

                    statements.add(insertComponent);

                    statements.add(componentConfigStatement(componentId, "priority", "100"));
                    statements.add(componentConfigStatement(componentId, "privateKey", privateKeyPem));
                    statements.add(componentConfigStatement(componentId, "certificate", certificatePem));
                }
            } finally {
                resultSet.close();
            }
        } finally {
            statement.close();
        }

        confirmationMessage.append("Updated " + statements.size() + " records in USER_FEDERATION_PROVIDER table");
    } catch (Exception e) {
        throw new CustomChangeException(getTaskId() + ": Exception when updating data from previous version", e);
    }
}
 
Example #29
Source Project: keycloak   Author: keycloak   File: AbstractUserFedToComponent.java    License: Apache License 2.0 4 votes vote down vote up
protected void convertFedProviderToComponent(String providerId, String newMapperType) throws CustomChangeException {
    try {
        PreparedStatement statement = jdbcConnection.prepareStatement("select ID, REALM_ID, PRIORITY, DISPLAY_NAME, FULL_SYNC_PERIOD, CHANGED_SYNC_PERIOD, LAST_SYNC from " + getTableName("USER_FEDERATION_PROVIDER") + " WHERE PROVIDER_NAME=?");
        statement.setString(1, providerId);

        try {
            ResultSet resultSet = statement.executeQuery();
            try {
                while (resultSet.next()) {
                    int index = 1;
                    String id = resultSet.getString(index++);
                    String realmId = resultSet.getString(index++);
                    int priority = resultSet.getInt(index++);
                    String displayName = resultSet.getString(index++);
                    int fullSyncPeriod = resultSet.getInt(index++);
                    int changedSyncPeriod = resultSet.getInt(index++);
                    int lastSync = resultSet.getInt(index++);


                    InsertStatement insertComponent = new InsertStatement(null, null, database.correctObjectName("COMPONENT", Table.class))
                            .addColumnValue("ID", id)
                            .addColumnValue("REALM_ID", realmId)
                            .addColumnValue("PARENT_ID", realmId)
                            .addColumnValue("NAME", displayName)
                            .addColumnValue("PROVIDER_ID", providerId)
                            .addColumnValue("PROVIDER_TYPE", UserStorageProvider.class.getName());

                    statements.add(insertComponent);

                    statements.add(componentConfigStatement(id, "priority", Integer.toString(priority)));
                    statements.add(componentConfigStatement(id, "fullSyncPeriod", Integer.toString(fullSyncPeriod)));
                    statements.add(componentConfigStatement(id, "changedSyncPeriod", Integer.toString(changedSyncPeriod)));
                    statements.add(componentConfigStatement(id, "lastSync", Integer.toString(lastSync)));
                    PreparedStatement configStatement = jdbcConnection.prepareStatement("select name, VALUE from " + getTableName("USER_FEDERATION_CONFIG") + " WHERE USER_FEDERATION_PROVIDER_ID=?");
                    configStatement.setString(1, id);
                    try {
                        ResultSet configSet = configStatement.executeQuery();
                        try {
                            while (configSet.next()) {
                                String name = configSet.getString(1);
                                String value = configSet.getString(2);
                                //logger.info("adding component config: " + name + ": " + value);
                                statements.add(componentConfigStatement(id, name, value));
                            }
                        } finally {
                            configSet.close();
                        }
                    } finally {
                        configStatement.close();
                    }

                    if (newMapperType != null) {
                        convertFedMapperToComponent(realmId, id, newMapperType);
                    }

                    DeleteStatement configDelete = new DeleteStatement(null, null, database.correctObjectName("USER_FEDERATION_CONFIG", Table.class));
                    configDelete.setWhere("USER_FEDERATION_PROVIDER_ID=?");
                    configDelete.addWhereParameters(id);

                    statements.add(configDelete);
                    DeleteStatement deleteStatement = new DeleteStatement(null, null, database.correctObjectName("USER_FEDERATION_PROVIDER", Table.class));
                    deleteStatement.setWhere("ID=?");
                    deleteStatement.addWhereParameters(id);
                    statements.add(deleteStatement);

                }
            } finally {
                resultSet.close();
            }
        } finally {
            statement.close();
        }

        confirmationMessage.append("Updated " + statements.size() + " records in USER_FEDERATION_PROVIDER table for " + providerId + " conversion to component model");
    } catch (Exception e) {
        throw new CustomChangeException(getTaskId() + ": Exception when updating data from previous version", e);
    }
}
 
Example #30
Source Project: keycloak   Author: keycloak   File: AbstractUserFedToComponent.java    License: Apache License 2.0 4 votes vote down vote up
protected void convertFedMapperToComponent(String realmId, String parentId, String newMapperType) throws CustomChangeException {
    try {
        PreparedStatement statement = jdbcConnection.prepareStatement("select ID, NAME, FEDERATION_MAPPER_TYPE from " + getTableName("USER_FEDERATION_MAPPER") + " WHERE FEDERATION_PROVIDER_ID=?");
        statement.setString(1, parentId);

        try {
            ResultSet resultSet = statement.executeQuery();
            try {
                while (resultSet.next()) {
                    String id = resultSet.getString(1);
                    String mapperName = resultSet.getString(2);
                    String fedMapperType = resultSet.getString(3);

                    InsertStatement insertComponent = new InsertStatement(null, null, database.correctObjectName("COMPONENT", Table.class))
                            .addColumnValue("ID", id)
                            .addColumnValue("REALM_ID", realmId)
                            .addColumnValue("PARENT_ID", parentId)
                            .addColumnValue("NAME", mapperName)
                            .addColumnValue("PROVIDER_ID", fedMapperType)
                            .addColumnValue("PROVIDER_TYPE", newMapperType);

                    statements.add(insertComponent);



                    PreparedStatement configStatement = jdbcConnection.prepareStatement("select name, VALUE from " + getTableName("USER_FEDERATION_MAPPER_CONFIG") + " WHERE USER_FEDERATION_MAPPER_ID=?");
                    configStatement.setString(1, id);
                    try {
                        ResultSet configSet = configStatement.executeQuery();
                        try {
                            while (configSet.next()) {
                                String name = configSet.getString(1);
                                String value = configSet.getString(2);
                                statements.add(componentConfigStatement(id, name, value));
                            }
                        } finally {
                            configSet.close();
                        }
                    } finally {
                        configStatement.close();
                    }
                    DeleteStatement configDelete = new DeleteStatement(null, null, database.correctObjectName("USER_FEDERATION_MAPPER_CONFIG", Table.class));
                    configDelete.setWhere("USER_FEDERATION_MAPPER_ID=?");
                    configDelete.addWhereParameters(id);
                    statements.add(configDelete);
                    DeleteStatement deleteStatement = new DeleteStatement(null, null, database.correctObjectName("USER_FEDERATION_MAPPER", Table.class));
                    deleteStatement.setWhere("ID=?");
                    deleteStatement.addWhereParameters(id);
                    statements.add(deleteStatement);


                }
            } finally {
                resultSet.close();
            }
        } finally {
            statement.close();
        }

        confirmationMessage.append("Updated " + statements.size() + " records in USER_FEDERATION_MAPPER table for " + parentId + " conversion to component model");
    } catch (Exception e) {
        throw new CustomChangeException(getTaskId() + ": Exception when updating data from previous version", e);
    }
}