/** * Initialize data base with 'MDA' JIRA project. */ @BeforeClass public static void initializeJiraDataBaseForSla() throws SQLException { final DataSource datasource = new SimpleDriverDataSource(new JDBCDriver(), "jdbc:hsqldb:mem:dataSource", null, null); final Connection connection = datasource.getConnection(); try { ScriptUtils.executeSqlScript(connection, new EncodedResource(new ClassPathResource("sql/sla/jira-create.sql"), StandardCharsets.UTF_8)); ScriptUtils.executeSqlScript(connection, new EncodedResource(new ClassPathResource("sql/sla/jira.sql"), StandardCharsets.UTF_8)); } finally { connection.close(); } }
/** * Initialize data base with 'MDA' JIRA project. */ @BeforeClass public static void initializeJiraDataBase() throws SQLException { datasource = new SimpleDriverDataSource(new JDBCDriver(), "jdbc:hsqldb:mem:dataSource", null, null); final Connection connection = datasource.getConnection(); final JdbcTemplate jdbcTemplate = new JdbcTemplate(datasource); try { ScriptUtils.executeSqlScript(connection, new EncodedResource(new ClassPathResource("sql/base-1/jira-create.sql"), StandardCharsets.UTF_8)); ScriptUtils.executeSqlScript(connection, new EncodedResource(new ClassPathResource("sql/base-1/jira.sql"), StandardCharsets.UTF_8)); jdbcTemplate.queryForList("SELECT * FROM pluginversion WHERE ID = 10075"); } finally { connection.close(); } }
/** * Initialize data base with 'MDA' JIRA project. */ @BeforeClass public static void initializeJiraDataBaseForImport() throws SQLException { datasource = new SimpleDriverDataSource(new JDBCDriver(), "jdbc:hsqldb:mem:dataSource", null, null); final Connection connection = datasource.getConnection(); try { ScriptUtils.executeSqlScript(connection, new EncodedResource(new ClassPathResource("sql/base-1/jira-create.sql"), StandardCharsets.UTF_8)); ScriptUtils.executeSqlScript(connection, new EncodedResource(new ClassPathResource("sql/base-2/jira-create.sql"), StandardCharsets.UTF_8)); ScriptUtils.executeSqlScript(connection, new EncodedResource(new ClassPathResource("sql/upload/jira-create.sql"), StandardCharsets.UTF_8)); ScriptUtils.executeSqlScript(connection, new EncodedResource(new ClassPathResource("sql/base-1/jira.sql"), StandardCharsets.UTF_8)); ScriptUtils.executeSqlScript(connection, new EncodedResource(new ClassPathResource("sql/base-2/jira.sql"), StandardCharsets.UTF_8)); ScriptUtils.executeSqlScript(connection, new EncodedResource(new ClassPathResource("sql/upload/jira.sql"), StandardCharsets.UTF_8)); } finally { connection.close(); } }
@RequestMapping(value = "/executeSql", method = RequestMethod.POST) public void executeSql(MultipartFile file, HttpServletResponse response) throws SQLException, IOException { Connection connection = DriverManager.getConnection(url + "mysql", username, password); String db = ("SC" + UUID.randomUUID().toString().substring(0, 5)).toLowerCase(); List<String> sqls = Arrays.asList("CREATE DATABASE IF NOT EXISTS " + db + " DEFAULT CHARSET utf8", "CREATE USER '" + db + "'@'%' IDENTIFIED BY '" + db + "'", "grant all privileges on " + db + ".* to '" + db + "'@'%' identified by '" + db + "'"); for (String sql : sqls) { Statement statement = connection.createStatement(); statement.execute(sql); statement.close(); } connection.close(); String jdbcUrl = url + db; connection = DriverManager.getConnection(url, db, db); ScriptUtils.executeSqlScript(connection, new InputStreamResource(file.getInputStream())); connection.close(); datasourceService.save(new Datasource() .setJdbcUrl(jdbcUrl) .setName(file.getOriginalFilename().substring(0, file.getOriginalFilename().lastIndexOf("."))) .setUsername(db) .setPassword(db) .setDriver("com.mysql.jdbc.Driver")); response.sendRedirect("/"); }
/** * Clean data base with 'MDA' JIRA project. */ @AfterClass public static void cleanJiraDataBaseForSla() throws SQLException { final DataSource datasource = new SimpleDriverDataSource(new JDBCDriver(), "jdbc:hsqldb:mem:dataSource", null, null); final Connection connection = datasource.getConnection(); try { ScriptUtils.executeSqlScript(connection, new EncodedResource(new ClassPathResource("sql/sla/jira-drop.sql"), StandardCharsets.UTF_8)); } finally { connection.close(); } }
/** * Clean data base with 'MDA' JIRA project. */ @AfterClass public static void cleanJiraDataBase() throws SQLException { final Connection connection = datasource.getConnection(); try { ScriptUtils.executeSqlScript(connection, new EncodedResource(new ClassPathResource("sql/base-1/jira-drop.sql"), StandardCharsets.UTF_8)); } finally { connection.close(); } }
/** * Initialize data base with 'MDA' JIRA project. */ @BeforeClass public static void initializeJiraDataBaseForImport() throws SQLException { final DataSource datasource = new SimpleDriverDataSource(new JDBCDriver(), "jdbc:hsqldb:mem:dataSource", null, null); final Connection connection = datasource.getConnection(); try { ScriptUtils.executeSqlScript(connection, new EncodedResource(new ClassPathResource("sql/upload/jira-create.sql"), StandardCharsets.UTF_8)); ScriptUtils.executeSqlScript(connection, new EncodedResource(new ClassPathResource("sql/upload/jira.sql"), StandardCharsets.UTF_8)); } finally { connection.close(); } }
/** * Clean data base with 'MDA' JIRA project. */ @AfterClass public static void cleanJiraDataBaseForImport() throws SQLException { final DataSource datasource = new SimpleDriverDataSource(new JDBCDriver(), "jdbc:hsqldb:mem:dataSource", null, null); final Connection connection = datasource.getConnection(); try { ScriptUtils.executeSqlScript(connection, new EncodedResource(new ClassPathResource("sql/upload/jira-drop.sql"), StandardCharsets.UTF_8)); } finally { connection.close(); } }
/** * Initialize data base with 'MDA' JIRA project. */ @BeforeClass public static void initializeJiraDataBase3() throws SQLException { final Connection connection = datasource.getConnection(); try { ScriptUtils.executeSqlScript(connection, new EncodedResource(new ClassPathResource("sql/base-3/jira-create.sql"), StandardCharsets.UTF_8)); ScriptUtils.executeSqlScript(connection, new EncodedResource(new ClassPathResource("sql/base-3/jira.sql"), StandardCharsets.UTF_8)); } finally { connection.close(); } }
/** * Clean data base with 'MDA' JIRA project. */ @AfterClass public static void cleanJiraDataBase3() throws SQLException { final Connection connection = datasource.getConnection(); try { ScriptUtils.executeSqlScript(connection, new EncodedResource(new ClassPathResource("sql/base-3/jira-drop.sql"), StandardCharsets.UTF_8)); } finally { connection.close(); } }
/** * Clean data base with 'MDA' JIRA project. */ @AfterClass public static void cleanJiraDataBaseForImport() throws SQLException { final Connection connection = datasource.getConnection(); try { ScriptUtils.executeSqlScript(connection, new EncodedResource(new ClassPathResource("sql/base-1/jira-drop.sql"), StandardCharsets.UTF_8)); ScriptUtils.executeSqlScript(connection, new EncodedResource(new ClassPathResource("sql/base-2/jira-drop.sql"), StandardCharsets.UTF_8)); ScriptUtils.executeSqlScript(connection, new EncodedResource(new ClassPathResource("sql/upload/jira-drop.sql"), StandardCharsets.UTF_8)); } finally { connection.close(); } }
/** * Initialize data base with 'MDA' JIRA project. */ @BeforeClass public static void initializeJiraDataBase2() throws SQLException { final Connection connection = datasource.getConnection(); try { ScriptUtils.executeSqlScript(connection, new EncodedResource(new ClassPathResource("sql/base-2/jira-create.sql"), StandardCharsets.UTF_8)); ScriptUtils.executeSqlScript(connection, new EncodedResource(new ClassPathResource("sql/base-2/jira.sql"), StandardCharsets.UTF_8)); } finally { connection.close(); } }
/** * Clean data base with 'MDA' JIRA project. */ @AfterClass public static void cleanJiraDataBase2() throws SQLException { final Connection connection = datasource.getConnection(); try { ScriptUtils.executeSqlScript(connection, new EncodedResource(new ClassPathResource("sql/base-2/jira-drop.sql"), StandardCharsets.UTF_8)); } finally { connection.close(); } }
/** * Construct a {@code MergedSqlConfig} instance by merging the configuration * from the supplied local (potentially method-level) {@code @SqlConfig} annotation * with class-level configuration discovered on the supplied {@code testClass}. * <p>Local configuration overrides class-level configuration. * <p>If the test class is not annotated with {@code @SqlConfig}, no merging * takes place and the local configuration is used "as is". */ MergedSqlConfig(SqlConfig localSqlConfig, Class<?> testClass) { Assert.notNull(localSqlConfig, "Local @SqlConfig must not be null"); Assert.notNull(testClass, "testClass must not be null"); // Get global attributes, if any. AnnotationAttributes attributes = AnnotatedElementUtils.findMergedAnnotationAttributes(testClass, SqlConfig.class.getName(), false, false); // Override global attributes with local attributes. if (attributes != null) { for (String key : attributes.keySet()) { Object value = AnnotationUtils.getValue(localSqlConfig, key); if (value != null) { // Is the value explicit (i.e., not a 'default')? if (!value.equals("") && (value != TransactionMode.DEFAULT) && (value != ErrorMode.DEFAULT)) { attributes.put(key, value); } } } } else { // Otherwise, use local attributes only. attributes = AnnotationUtils.getAnnotationAttributes(localSqlConfig, false, false); } this.dataSource = attributes.getString("dataSource"); this.transactionManager = attributes.getString("transactionManager"); this.transactionMode = getEnum(attributes, "transactionMode", TransactionMode.DEFAULT, TransactionMode.INFERRED); this.encoding = attributes.getString("encoding"); this.separator = getString(attributes, "separator", ScriptUtils.DEFAULT_STATEMENT_SEPARATOR); this.commentPrefix = getString(attributes, "commentPrefix", ScriptUtils.DEFAULT_COMMENT_PREFIX); this.blockCommentStartDelimiter = getString(attributes, "blockCommentStartDelimiter", ScriptUtils.DEFAULT_BLOCK_COMMENT_START_DELIMITER); this.blockCommentEndDelimiter = getString(attributes, "blockCommentEndDelimiter", ScriptUtils.DEFAULT_BLOCK_COMMENT_END_DELIMITER); this.errorMode = getEnum(attributes, "errorMode", ErrorMode.DEFAULT, ErrorMode.FAIL_ON_ERROR); }
public static void executeScript(DataSource dataSource, String... sqlResourcePaths) throws DataAccessException, SQLException { for (String sqlResourcePath : sqlResourcePaths) { Resource resource = resourceLoader.getResource(sqlResourcePath); ScriptUtils.executeSqlScript(dataSource.getConnection(), new EncodedResource(resource, DEFAULT_ENCODING)); } }
private void executeScript(Optional<String> databaseName, final String script) { JdbcTemplate jdbcTemplate = databaseName.isPresent() ? jdbcTemplate(databaseName.get()) : jdbcTemplate(); jdbcTemplate.execute(new ConnectionCallback<Object>() { @Override public Object doInConnection(Connection con) throws SQLException, DataAccessException { ScriptUtils.executeSqlScript(con, new ClassPathResource(script)); return null; } }); }
public static void main(String[] args) throws Exception { String url = "jdbc:postgresql://localhost:5432/quartz"; Class.forName("org.postgresql.Driver"); Connection db = DriverManager.getConnection(url, "quartz", "quartz"); System.out.println("Initializing database and creating tables"); db.setAutoCommit(false); ScriptUtils.executeSqlScript(db, new FileSystemResource("tables_postgres.sql")); db.setAutoCommit(true); db.close(); System.out.println("Database initialized"); }
@Before public void setUp() { jdbcStream.execute((Connection conn) -> { ScriptUtils.executeSqlScript(conn, context.getResource("data.sql")); return null; }); }
public void execute(String script, Map<String, Object> creds) throws SQLException { String username = (String) creds.get("username"); String password = (String) creds.get("password"); String uri = "jdbc:" + (String) creds.get("uri"); log.info("Sanitizing " + uri + " " + " as " + username); Connection connection = DriverManager.getConnection(uri, username, password); ScriptUtils.executeSqlScript(connection, new ByteArrayResource(script.getBytes())); }
@Test public void test() { if (drop) { try { transactionTemplate.execute((TransactionCallback<Void>) transactionStatus -> { Session session = entityManager.unwrap(Session.class); session.doWork(connection -> { ScriptUtils.executeSqlScript(connection, new EncodedResource( new ClassPathResource( String.format("flyway/db/%1$s/drop/drop.sql", databaseType) ) ), true, true, ScriptUtils.DEFAULT_COMMENT_PREFIX, ScriptUtils.DEFAULT_BLOCK_COMMENT_START_DELIMITER, ScriptUtils.DEFAULT_BLOCK_COMMENT_END_DELIMITER, ScriptUtils.DEFAULT_COMMENT_PREFIX); }); return null; }); } catch (TransactionException e) { LOGGER.error("Failure", e); } } }
@Transactional public void generateTestRawCcJudgments() throws ScriptException, SQLException { assertEquals(0, rawSourceCcJudgmentRepository.count()); ClassPathResource resource = new ClassPathResource(RAW_JUDGMENT_SQL_PATH); ScriptUtils.executeSqlScript(dataSource.getConnection(), new EncodedResource(resource, "UTF-8")); assertTrue(rawSourceCcJudgmentRepository.count()>10); entityManager.createQuery("update " + RawSourceCcJudgment.class.getName() + " set processingDate = null, processed = false, processingSkipReason = null").executeUpdate(); entityManager.flush(); }
private void recreateSpringBatchTables() throws SQLException { log.debug("dropping spring batch tables"); ClassPathResource resource = new ClassPathResource("dropBatchTables.sql"); ScriptUtils.executeSqlScript(dataSource.getConnection(), new EncodedResource(resource, "UTF-8")); log.debug("creating spring batch tables"); resource = new ClassPathResource("createBatchTables.sql"); ScriptUtils.executeSqlScript(dataSource.getConnection(), new EncodedResource(resource, "UTF-8")); }
@Before public void setUp() throws ScriptException { jdbcTemplate = new JdbcTemplate(dataSource); try { ScriptUtils.executeSqlScript(dataSource.getConnection(), new ClassPathResource("metrics/create-schema.sql")); } catch (Exception e) { // if table exist, error is okay. } }
private void loadSQL(String id, InputStreamReader reader) throws IOException { LineNumberReader fileReader = new LineNumberReader(new BufferedReader(reader)); String query = ScriptUtils.readScript(fileReader, COMMENT_PREFIX, SEPARATOR); cacheQeries.put(id, query); }
protected void executeInitializationScripts() { SdcctDriverDataSource adminDataSrc = null; Connection adminConn = null; try { adminConn = DataSourceUtils.getConnection((adminDataSrc = this.dataSrcConfig.buildDataSource(this.adminUser, true))); for (ResourceSource initScriptSrc : this.initScriptSrcs) { ScriptUtils .executeSqlScript(adminConn, new EncodedResource(new ByteArrayResource(this.embeddedPlaceholderResolver .resolvePlaceholders(new String(initScriptSrc.getBytes(), StandardCharsets.UTF_8)).getBytes(StandardCharsets.UTF_8), initScriptSrc.getResource().getDescription()), StandardCharsets.UTF_8)); } DbUser user = this.dataSrcConfig.getUser(); String userName = user.getName(); Map<String, DbRole> roles = user.getRoles(); StrBuilder secSqlBuilder = new StrBuilder(); secSqlBuilder.append(SdcctHsqlDialect.INSTANCE.getCreateUserString(userName, user.getCredentials())); secSqlBuilder.appendNewLine(); for (String roleName : roles.keySet()) { secSqlBuilder.append(SdcctHsqlDialect.INSTANCE.getCreateRoleString(roleName)); secSqlBuilder.appendNewLine(); secSqlBuilder.append(SdcctHsqlDialect.INSTANCE.getGrantRoleString(roleName, userName)); for (DbAuthority authority : roles.get(roleName).getAuthorities()) { secSqlBuilder.appendNewLine(); secSqlBuilder.append(SdcctHsqlDialect.INSTANCE.getGrantOnString(authority, roleName)); } } ScriptUtils.executeSqlScript(adminConn, new EncodedResource(new ByteArrayResource(secSqlBuilder.build().getBytes(StandardCharsets.UTF_8)), StandardCharsets.UTF_8)); adminConn.commit(); } catch (Exception e) { throw new HibernateException(String.format("Unable to execute database (name=%s) server (hostAddr=%s, port=%d) initialization scripts.", this.dbName, this.hostAddr, this.port), e); } finally { if (adminConn != null) { DataSourceUtils.releaseConnection(adminConn, adminDataSrc); } } }
/** * Read a script from the provided {@code LineNumberReader}, using * "{@code --}" as the comment prefix, and build a {@code String} containing * the lines. * @param lineNumberReader the {@code LineNumberReader} containing the script * to be processed * @return a {@code String} containing the script lines * @see #readScript(LineNumberReader, String) * @deprecated as of Spring 4.0.3, in favor of using * {@link org.springframework.jdbc.datasource.init.ScriptUtils#readScript(LineNumberReader, String, String)} */ @Deprecated public static String readScript(LineNumberReader lineNumberReader) throws IOException { return readScript(lineNumberReader, ScriptUtils.DEFAULT_COMMENT_PREFIX); }
/** * Read a script from the provided {@code LineNumberReader}, using the supplied * comment prefix, and build a {@code String} containing the lines. * <p>Lines <em>beginning</em> with the comment prefix are excluded from the * results; however, line comments anywhere else — for example, within * a statement — will be included in the results. * @param lineNumberReader the {@code LineNumberReader} containing the script * to be processed * @param commentPrefix the prefix that identifies comments in the SQL script — typically "--" * @return a {@code String} containing the script lines * @deprecated as of Spring 4.0.3, in favor of using * {@link org.springframework.jdbc.datasource.init.ScriptUtils#readScript(LineNumberReader, String, String)} */ @Deprecated public static String readScript(LineNumberReader lineNumberReader, String commentPrefix) throws IOException { return ScriptUtils.readScript(lineNumberReader, commentPrefix, ScriptUtils.DEFAULT_STATEMENT_SEPARATOR); }
/** * Determine if the provided SQL script contains the specified delimiter. * @param script the SQL script * @param delim character delimiting each statement — typically a ';' character * @return {@code true} if the script contains the delimiter; {@code false} otherwise * @deprecated as of Spring 4.0.3, in favor of using * {@link org.springframework.jdbc.datasource.init.ScriptUtils#containsSqlScriptDelimiters} */ @Deprecated public static boolean containsSqlScriptDelimiters(String script, char delim) { return ScriptUtils.containsSqlScriptDelimiters(script, String.valueOf(delim)); }
/** * Split an SQL script into separate statements delimited by the provided * delimiter character. Each individual statement will be added to the * provided {@code List}. * <p>Within a statement, "{@code --}" will be used as the comment prefix; * any text beginning with the comment prefix and extending to the end of * the line will be omitted from the statement. In addition, multiple adjacent * whitespace characters will be collapsed into a single space. * @param script the SQL script * @param delim character delimiting each statement — typically a ';' character * @param statements the list that will contain the individual statements * @deprecated as of Spring 4.0.3, in favor of using * {@link org.springframework.jdbc.datasource.init.ScriptUtils#splitSqlScript(String, char, List)} */ @Deprecated public static void splitSqlScript(String script, char delim, List<String> statements) { ScriptUtils.splitSqlScript(script, delim, statements); }