How to use getConnection method of com.testsigma.config.DatabaseMigrationConfig class

Best Testsigma code snippet using com.testsigma.config.DatabaseMigrationConfig.getConnection

Source:DatabaseMigrationConfig.java Github

copy

Full Screen

...42 }43 private void setUpDatabase() throws Exception {44 Flyway flyway;45 try {46 connection = getConnection();47 if (isNewDatabase()) {48 log.debug("Initializing bootstrap data");49 executeBootStrap();50 addMigrationEntries();51 } else {52 log.info("Running any migrations if present on existing database");53 flyway = Flyway.configure().dataSource(dataSourceUrl, dataSourceUser, dataSourcePassword).placeholderReplacement(false).load();54 flyway.migrate();55 }56 } catch (Exception e) {57 log.error(e.getMessage(), e);58 throw e;59 } finally {60 if (connection != null)61 connection.close();62 }63 }64 /*65 If db is up to date, we just add migration entries if any without executing SQLs66 */67 private void addMigrationEntries() throws SQLException, IOException {68 log.debug("....Adding migration entries....");69 SortedMap<Integer, File> versionAndFileMap = getVersionAndFileMap();70 int installedRank = 1;71 for (Integer version : versionAndFileMap.keySet()) {72 File migrationFile = versionAndFileMap.get(version);73 int checksum = getChecksum(migrationFile.getAbsolutePath());74 addMigrationEntryToHistory(installedRank, version, migrationFile, checksum);75 installedRank++;76 }77 }78 private void executeBootStrap() throws SQLException {79 log.info("Executing bootstrap");80 Flyway flyway = Flyway.configure().dataSource(dataSourceUrl, dataSourceUser, dataSourcePassword)81 .locations(SCHEMA_PATH_RESOURCE)82 .placeholderReplacement(false)83 .load();84 flyway.migrate();85 clearHistoryForSchema();86 }87 private void clearHistoryForSchema() throws SQLException {88 Statement stmt = connection.createStatement();89 stmt.executeUpdate(DELETE_HISTORY);90 }91 private boolean isNewDatabase() throws SQLException {92 ResultSet resultSet = connection.createStatement().executeQuery("SHOW TABLES");93 return !(resultSet.next());94 }95 private int getChecksum(String absoluteFilePath) {96 FileSystemResource r = new FileSystemResource(null, absoluteFilePath, Charset.forName("UTF-8"), false);97 return ChecksumCalculator.calculate(r);98 }99 private SortedMap<Integer, File> getVersionAndFileMap() throws IOException {100 SortedMap<Integer, File> sortedByVersion = new TreeMap<>();//We need to sort by version for DB entry101 Set<File> migrationSQLFiles;102 ClassLoader classLoader = Thread.currentThread().getContextClassLoader();103 URL url = classLoader.getResource(MIGRATION_PATH);104 if(url == null){105 return sortedByVersion;106 }107 String urlProtocol = url.getProtocol();108 log.debug(String.format("URL Path:%s, URL protocol:%s", url.getPath(),urlProtocol));109 if (urlProtocol.equalsIgnoreCase("jar")) {110 log.debug("URL type is jar, extracting migration files from jar");111 JarExtractorUtil jarExtractorUtil = new JarExtractorUtil();112 migrationSQLFiles = jarExtractorUtil.extractJarAndCreateTempFiles(url,MIGRATION_PATH,".sql");113 } else {114 log.debug("Extracting migration files from file system");115 FileSystemClassPathLocationScanner classPathLocationScanner = new FileSystemClassPathLocationScanner();116 Set<String> classpathResourceFilePaths = classPathLocationScanner.findResourceNames(MIGRATION_PATH, url);117 log.info("Migration files from file system::"+classpathResourceFilePaths);118 migrationSQLFiles = getFilesFromResourcePaths(classpathResourceFilePaths);119 }120 for (File migrationFile : migrationSQLFiles) {121 sortedByVersion.put(getVersionFromFilePath(migrationFile), migrationFile);122 }123 return sortedByVersion;124 }125 private Set<File> getFilesFromResourcePaths(Set<String> classpathResourceFilePaths) {126 Set<File> fileSet = new TreeSet<>();127 for(String resourcePath:classpathResourceFilePaths){128 log.debug("Resource path from classpath:"+resourcePath);129 URL fileURL = Thread.currentThread().getContextClassLoader().getResource(resourcePath);130 File file = new File(fileURL.getPath());131 fileSet.add(file);132 }133 return fileSet;134 }135 private Integer getVersionFromFilePath(File sqlFile) {136 String fileName = sqlFile.getName();137 String versionString = StringUtils.substringBetween(fileName, VERSION_CHAR, VERSION_SEPARATOR);138 return Integer.parseInt(versionString);139 }140 private void addMigrationEntryToHistory(int installedRank, Integer version, File migrationFile, int checksum) throws SQLException {141 String description = getFileDescription(migrationFile.getName());142 log.info("Adding migration entry for:" + migrationFile.getName());143 PreparedStatement preparedStatement = connection.prepareStatement(INSERT_HISTORY);144 preparedStatement.setInt(1, installedRank);145 preparedStatement.setString(2, version.toString());146 preparedStatement.setString(3, description);147 preparedStatement.setString(4, migrationFile.getName());148 preparedStatement.setInt(5, checksum);149 preparedStatement.setString(6, dataSourceUser);150 int i = preparedStatement.executeUpdate();151 if (i == 0) {152 throw new SQLException("Unable to update migration entry for sql file:" + migrationFile.getName());153 }154 }155 private String getFileDescription(String fileName) {156 String versionTruncated = fileName.substring(fileName.indexOf(VERSION_SEPARATOR) + 2, fileName.indexOf("."));157 return versionTruncated.replaceAll("_", " ");158 }159 private Connection getConnection() throws SQLException {160 if (connection == null) {161 try {162 connection = DriverManager.getConnection(dataSourceUrl, dataSourceUser, dataSourcePassword);163 } catch (SQLSyntaxErrorException e) {164 if ((e.getSQLState().equals("42000")) && e.getMessage().startsWith("Unknown database")) {165 log.info("Database does not exist, creating it");166 String dbName = parseMysqlDatabaseName(dataSourceUrl);167 createDatabase(dbName);168 connection = DriverManager.getConnection(dataSourceUrl, dataSourceUser, dataSourcePassword);169 }170 }171 }172 return connection;173 }174 private void createDatabase(String dbName) throws SQLException {175 log.info("Trying to create a database - " + dbName);176 String mysqlHostName = parseMysqlHostName(dataSourceUrl);177 String parseMysqlPort = parseMysqlPort(dataSourceUrl);178 String connectionUrl = "jdbc:mysql://" + mysqlHostName + ":" + parseMysqlPort + "?useSSL=false";179 Connection connection1 = null;180 try {181 log.info("Establishing connection to mysql server - " + connectionUrl);182 connection1 = DriverManager.getConnection(connectionUrl, dataSourceUser, dataSourcePassword);183 Statement stmt = connection1.createStatement();184 stmt.executeUpdate(String.format(CREATE_DATABASE, dbName));185 } catch (SQLException e) {186 log.error("Error creating database", e);187 } finally {188 if (connection1 != null) {189 connection1.close();190 }191 }192 }193 private String parseMysqlDatabaseName(String url) {194 String dbName = "testsigma_opensource";195 try {196 Pattern pattern = Pattern.compile("^jdbc:mysql:\\/\\/(.+):([0-9]+)\\/(.+)\\?useSSL=false$");...

Full Screen

Full Screen

getConnection

Using AI Code Generation

copy

Full Screen

1import com.testsigma.config.DatabaseMigrationConfig;2def config = new DatabaseMigrationConfig()3def connection = config.getConnection()4import com.testsigma.config.DatabaseMigrationConfig;5def config = new DatabaseMigrationConfig()6def connection = config.getConnection()7def result = config.executeQuery(connection, "select * from table_name")8import com.testsigma.config.DatabaseMigrationConfig;9def config = new DatabaseMigrationConfig()10def connection = config.getConnection()11def result = config.executeUpdate(connection, "update table_name set column_name = 'value'")12import com.testsigma.config.DatabaseMigrationConfig;13def config = new DatabaseMigrationConfig()14def connection = config.getConnection()15def result = config.executeInsert(connection, "insert into table_name (column_name) values ('value')")16import com.testsigma.config.DatabaseMigrationConfig;17def config = new DatabaseMigrationConfig()18def connection = config.getConnection()19def result = config.executeDelete(connection, "delete from table_name where column_name = 'value'")20import com.testsigma.config.DatabaseMigrationConfig;21def config = new DatabaseMigrationConfig()22def connection = config.getConnection()23def result = config.executeBatch(connection, ["insert into table_name (column_name) values ('value')", "update table_name set column_name = 'value'"])24import com.testsigma.config.DatabaseMigrationConfig;25def config = new DatabaseMigrationConfig()26def connection = config.getConnection()27def result = config.executeBatch(connection, ["insert into table_name (column_name) values ('value')", "update table_name set column_name = 'value'"])28import com.testsigma.config.DatabaseMigrationConfig;29def config = new DatabaseMigrationConfig()30def connection = config.getConnection()31def result = config.executeBatch(connection, ["insert into table_name (column_name) values ('value')", "update table_name set column_name = 'value'"])

Full Screen

Full Screen

getConnection

Using AI Code Generation

copy

Full Screen

1Connection connection = DatabaseMigrationConfig.getConnection();2ResultSet rs = DatabaseMigrationConfig.executeQuery(connection, "select * from test_table");3Map<String, String> map = DatabaseMigrationConfig.getResultSetAsMap(rs);4DatabaseMigrationConfig.closeConnection(connection);5MigrationConfig migrationConfig = DatabaseMigrationConfig.getMigrationConfig();6MigrationConfig migrationConfig = DatabaseMigrationConfig.getMigrationConfig();7MigrationConfig migrationConfig = DatabaseMigrationConfig.getMigrationConfig();8MigrationConfig migrationConfig = DatabaseMigrationConfig.getMigrationConfig();9MigrationConfig migrationConfig = DatabaseMigrationConfig.getMigrationConfig();10MigrationConfig migrationConfig = DatabaseMigrationConfig.getMigrationConfig();11MigrationConfig migrationConfig = DatabaseMigrationConfig.getMigrationConfig();12MigrationConfig migrationConfig = DatabaseMigrationConfig.getMigrationConfig();13MigrationConfig migrationConfig = DatabaseMigrationConfig.getMigrationConfig();14MigrationConfig migrationConfig = DatabaseMigrationConfig.getMigrationConfig();

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful