获取目标字段类型

@param conn sql connection
@param config 映射配置
@return 字段sqlType
192231
private Map<String, Integer> getTargetColumnType(Connection conn, MappingConfig config) {
        DbMapping dbMapping = config.getDbMapping();
        String cacheKey = config.getDestination() + "." + dbMapping.getDatabase() + "." + dbMapping.getTable();
        Map<String, Integer> columnType = columnsTypeCache.get(cacheKey);
        if (columnType == null) {
            synchronized (RdbSyncService.class) {
                columnType = columnsTypeCache.get(cacheKey);
                if (columnType == null) {
                    columnType = new LinkedHashMap<>();
                    final Map<String, Integer> columnTypeTmp = columnType;
                    String sql = "SELECT * FROM " + SyncUtil.getDbTableName(dbMapping) + " WHERE 1=2";
                    Util.sqlRS(conn, sql, rs -> {
                        try {
                            ResultSetMetaData rsd = rs.getMetaData();
                            int columnCount = rsd.getColumnCount();
                            for (int i = 1; i <= columnCount; i++) {
                                columnTypeTmp.put(rsd.getColumnName(i).toLowerCase(), rsd.getColumnType(i));
                            }
                            columnsTypeCache.put(cacheKey, columnTypeTmp);
                        } catch (SQLException e) {
                            logger.error(e.getMessage(), e);
                        }
                    });
                }
            }
        }
        return columnType;
    }
593700
public static function connect(ConnectionParameters $config){

		//Not static
		$con = new self();
		
		switch(\strtolower(\trim($config->getDriver()))){
			
			case 'sqlite':
				$con->Connection = new \PDO(
						\sprintf('sqlite:%s', $config->getHost()),
						$config->getUsername(),
						$config->getPassword(),
						$config->getOptions());
				break;
			
			default:
				$con->Connection = new \PDO(\sprintf(
						'%s:host=%s;charset=%s;dbname=%s',
						$config->getDriver() ? $config->getDriver() : '',
						$config->getHost() ? $config->getHost() : '',
						$config->getCharset() ? $config->getCharset() : '',
						$config->getDatabaseName() ? $config->getDatabaseName() : ''
					),
					$config->getUsername(),
					$config->getPassword(),
					$config->getOptions());
				break;
			
		}
		
		return $con;

	}
252708
public Long execute(final ConnectionResource _con)
        throws SQLException
    {
        final boolean supGenKey = Context.getDbType().supportsGetGeneratedKeys();

        Long ret = null;
        if (this.newId && !supGenKey)  {
            ret = Context.getDbType().getNewId(_con, getTableName(), getIdColumn());
            this.column(getIdColumn(), ret);
        }

        final StringBuilder cmd = new StringBuilder()
            .append(Context.getDbType().getSQLPart(SQLPart.INSERT))
            .append(" ")
            .append(Context.getDbType().getSQLPart(SQLPart.INTO))
            .append(" ")
            .append(Context.getDbType().getTableQuote())
            .append(getTableName())
            .append(Context.getDbType().getTableQuote())
            .append(" ")
            .append(Context.getDbType().getSQLPart(SQLPart.PARENTHESIS_OPEN));

        final StringBuilder val = new StringBuilder();

        // append SQL values
        boolean first = true;
        for (final ColumnWithSQLValue col : getColumnWithSQLValues())  {
            if (first)  {
                first = false;
            } else  {
                cmd.append(Context.getDbType().getSQLPart(SQLPart.COMMA));
                val.append(Context.getDbType().getSQLPart(SQLPart.COMMA));
            }
            cmd.append(Context.getDbType().getColumnQuote())
                .append(col.getColumnName())
                .append(Context.getDbType().getColumnQuote());
            val.append(col.getSqlValue());
        }

        // append values
        for (final AbstractColumnWithValue<?> col : getColumnWithValues())  {
            if (first)  {
                first = false;
            } else  {
                cmd.append(Context.getDbType().getSQLPart(SQLPart.COMMA));
                val.append(Context.getDbType().getSQLPart(SQLPart.COMMA));
            }
            cmd.append(Context.getDbType().getColumnQuote())
                .append(col.getColumnName())
                .append(Context.getDbType().getColumnQuote());
            val.append('?');
        }
        cmd.append(Context.getDbType().getSQLPart(SQLPart.PARENTHESIS_CLOSE))
            .append(Context.getDbType().getSQLPart(SQLPart.VALUES))
            .append(Context.getDbType().getSQLPart(SQLPart.PARENTHESIS_OPEN))
            .append(val)
            .append(Context.getDbType().getSQLPart(SQLPart.PARENTHESIS_CLOSE));

        SQLInsert.LOG.debug("Executing SQL: {}", cmd.toString());

        final PreparedStatement stmt;
        if (this.newId && supGenKey) {
            if (Context.getDbType().supportsMultiGeneratedKeys()) {
                stmt = _con.prepareStatement(cmd.toString(), new String[]{ getIdColumn() });
            } else {
                stmt = _con.prepareStatement(cmd.toString(), Statement.RETURN_GENERATED_KEYS);
            }
        } else {
            stmt = _con.prepareStatement(cmd.toString());
        }

        int index = 1;
        for (final AbstractColumnWithValue<?> col : getColumnWithValues())  {
            if (SQLInsert.LOG.isDebugEnabled()) {
                SQLInsert.LOG.debug("    " + index + " = " + col.getValue());
            }
            col.set(index++, stmt);
        }

        try {
            final int rows = stmt.executeUpdate();
            if (rows == 0) {
                throw new SQLException("Object for SQL table '" + getTableName()
                        + "' does not exists and was not inserted.");
            }

            // if auto generated get new id
            if (this.newId && supGenKey) {
                final ResultSet resultset = stmt.getGeneratedKeys();
                if (resultset.next()) {
                    ret = resultset.getLong(1);
                }
                resultset.close();
            }
        } finally  {
            stmt.close();
        }

        if (this.newId && SQLInsert.LOG.isDebugEnabled()) {
            SQLInsert.LOG.debug("new generated id " + ret);
        }

        return ret;
    }
260432
static Map<String, JDBConnection> connectionMapFromConfig(Config config) throws InitializationException {

      final Config globalPropertyConfig;
      if(config.hasPath("acp.property")) {
         globalPropertyConfig = config.getObject("acp.property").toConfig();
      } else if(config.hasPath("property")) {
         globalPropertyConfig = config.getObject("property").toConfig();
      } else {
         globalPropertyConfig = null;
      }


      final Config connectionsConfig;
      if(config.hasPath("acp.connection")) {
         connectionsConfig = config.getObject("acp.connection").toConfig();
      } else if(config.hasPath("connection")) {
         connectionsConfig = config.getObject("connection").toConfig();
      } else {
         return Collections.emptyMap();
      }

      Map<String, JDBConnection> connectionMap = Maps.newLinkedHashMap();

      for(String connectionName : uniquePrefixSet(connectionsConfig)) {
         Config connectionConfig = connectionsConfig.getObject(connectionName).toConfig();
         connectionMap.put(connectionName, createConnection(connectionName, connectionConfig, globalPropertyConfig));
      }

      return connectionMap;
   }
464699
public static String getColumnType(DriverTypeEnum.ConnectionProperties theConnectionProperties, String theTableName, String theColumnName) throws SQLException {
		DataSource dataSource = Objects.requireNonNull(theConnectionProperties.getDataSource());
		try (Connection connection = dataSource.getConnection()) {
			return theConnectionProperties.getTxTemplate().execute(t -> {
				DatabaseMetaData metadata;
				try {
					metadata = connection.getMetaData();
					String catalog = connection.getCatalog();
					String schema = connection.getSchema();
					ResultSet indexes = metadata.getColumns(catalog, schema, massageIdentifier(metadata, theTableName), null);

					while (indexes.next()) {

						String tableName = toUpperCase(indexes.getString("TABLE_NAME"), Locale.US);
						if (!theTableName.equalsIgnoreCase(tableName)) {
							continue;
						}
						String columnName = toUpperCase(indexes.getString("COLUMN_NAME"), Locale.US);
						if (!theColumnName.equalsIgnoreCase(columnName)) {
							continue;
						}

						int dataType = indexes.getInt("DATA_TYPE");
						Long length = indexes.getLong("COLUMN_SIZE");
						switch (dataType) {
							case Types.VARCHAR:
								return BaseTableColumnTypeTask.ColumnTypeEnum.STRING.getDescriptor(length);
							case Types.NUMERIC:
							case Types.BIGINT:
							case Types.DECIMAL:
								return BaseTableColumnTypeTask.ColumnTypeEnum.LONG.getDescriptor(null);
							case Types.INTEGER:
								return BaseTableColumnTypeTask.ColumnTypeEnum.INT.getDescriptor(null);
							case Types.TIMESTAMP:
							case Types.TIMESTAMP_WITH_TIMEZONE:
								return BaseTableColumnTypeTask.ColumnTypeEnum.DATE_TIMESTAMP.getDescriptor(null);
							default:
								throw new IllegalArgumentException("Don't know how to handle datatype " + dataType + " for column " + theColumnName + " on table " + theTableName);
						}

					}

					return null;

				} catch (SQLException e) {
					throw new InternalErrorException(e);
				}

			});
		}
	}
1309784
public static function getDbo($config = array(), $cname = '')
	{
		// empty instance of db
		$db = App::get('db');

		// make sure we have a group object
		if (!$group = Group::getInstance(\Request::getString('cn', $cname)))
		{
			return $db;
		}

		// make sure we are a super group
		if (!$group->isSuperGroup())
		{
			return $db;
		}

		// load super group db config if not passed in
		if (empty($config))
		{
			// build path to config file
			$uploadPath = \Component::params( 'com_groups' )->get('uploadpath');
			$configPath = PATH_APP . DS . trim($uploadPath, DS) . DS . $group->get('gidNumber') . DS . 'config' . DS . 'db.php';

			// make sure file exists
			if (!file_exists($configPath))
			{
				return $db;
			}

			// include config
			$config = include $configPath;
		}

		// return instance of db
		return \Hubzero\Database\Driver::getInstance($config);
	}
345104
public static ServerTransport getServerTransport(ServerTransportConfig serverConfig) {
        ServerTransport serverTransport = ExtensionLoaderFactory.getExtensionLoader(ServerTransport.class)
            .getExtension(serverConfig.getContainer(),
                new Class[] { ServerTransportConfig.class },
                new Object[] { serverConfig });
        if (serverTransport != null) {
            String key = Integer.toString(serverConfig.getPort());
            SERVER_TRANSPORT_MAP.put(key, serverTransport);
        }
        return serverTransport;
    }
79759
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;
		}
	}
290219
public static DatabaseStructureType getDatabaseType(WorkspaceEntry wsConfig) throws RepositoryConfigurationException
   {
      try
      {
         if (wsConfig.getContainer().getParameterBoolean("multi-db"))
         {
            return JDBCDataContainerConfig.DatabaseStructureType.MULTI;
         }
         else
         {
            return JDBCDataContainerConfig.DatabaseStructureType.SINGLE;
         }
      }
      catch (Exception e)
      {
         String dbStructureType =
            wsConfig.getContainer().getParameterValue(JDBCWorkspaceDataContainer.DB_STRUCTURE_TYPE).toUpperCase();
         return JDBCDataContainerConfig.DatabaseStructureType.valueOf(dbStructureType);
      }
   }
232681
@Nonnull
    public Configuration filter(Configuration config) {
        final Map<String, Object> values = Maps.newHashMap();

        for (final ConfigurationField field : fields.values()) {
            final String name = field.getName();
            final String type = field.getFieldType();
            switch (type) {
                case BooleanField.FIELD_TYPE:
                    if (config.booleanIsSet(name)) {
                        values.put(name, config.getBoolean(name));
                    }
                    break;
                case NumberField.FIELD_TYPE:
                    if (config.intIsSet(name)) {
                        values.put(name, config.getInt(name));
                    }
                    break;
                case TextField.FIELD_TYPE:
                case DropdownField.FIELD_TYPE:
                    if (config.stringIsSet(name)) {
                        values.put(name, config.getString(name));
                    }
                    break;
                default:
                    throw new IllegalStateException("Unknown field type " + type + " for configuration field \"" + name + "\". This is a bug.");
            }
        }
        return new Configuration(values);
    }
771742
public static SqlConfig getConfig(final String url, final String user, final String password, final String schema,
			final boolean autoCommit, final boolean readOnly) {
		return new DefaultSqlConfig(new JdbcConnectionSupplierImpl(url, user, password, schema, autoCommit, readOnly),
				null);
	}
195588
protected Stream<T> getAllSorted(Connection conn) {
        return executeSelectAsStream(rowMapper, conn, true, calcSqlSelectAllSorted());
    }
600705
def connection_factory type
      config = Myreplicator.configs[self.source_schema]
      puts self.source_schema
      puts config
      case type
      when :ssh
        if config.has_key? "ssh_password"
          return Net::SSH.start(config["ssh_host"], config["ssh_user"], :password => config["ssh_password"])

        elsif(config.has_key? "ssh_private_key")
          return Net::SSH.start(config["ssh_host"], config["ssh_user"], :keys => [config["ssh_private_key"]])
        end
      when :sftp
        if config.has_key? "ssh_password"
          return Net::SFTP.start(config["ssh_host"], config["ssh_user"], :password => config["ssh_password"])

        elsif(config.has_key? "ssh_private_key")
          return Net::SFTP.start(config["ssh_host"], config["ssh_user"], :keys => [config["ssh_private_key"]])
        end          
      end
    end
167502
protected String buildSelectSQL(final TableMetadata metadata, final Class<? extends Object> type,
			final SqlConfig sqlConfig, final boolean addCondition) {
		final List<? extends TableMetadata.Column> columns = metadata.getColumns();

		final StringBuilder sql = new StringBuilder(
				buildSelectClause(metadata, type, sqlConfig.getSqlAgentFactory().getSqlIdKeyName()));

		if (addCondition) {
			sql.append("/*BEGIN*/").append(System.lineSeparator());
			sql.append("WHERE").append(System.lineSeparator());

			for (final TableMetadata.Column col : columns) {
				final String camelColName = col.getCamelColumnName();
				final StringBuilder parts = new StringBuilder().append("\t").append("AND ")
						.append(col.getColumnIdentifier())
						.append(" = ").append("/*").append(camelColName).append("*/''").append(System.lineSeparator());
				wrapIfComment(sql, parts, col);
			}
			sql.append("/*END*/").append(System.lineSeparator());

			boolean firstFlag = true;
			final List<? extends TableMetadata.Column> keys = metadata.getKeyColumns();
			if (!keys.isEmpty()) {
				sql.append("ORDER BY").append(System.lineSeparator());
				firstFlag = true;
				for (final TableMetadata.Column col : keys) {
					sql.append("\t");
					if (firstFlag) {
						sql.append("  ");
						firstFlag = false;
					} else {
						sql.append(", ");
					}
					sql.append(col.getColumnIdentifier()).append(System.lineSeparator());
				}
			}
		}

		return sql.toString();
	}
1121404
public static function instance($config = [], $name = false)
    {
        if (false === $name) {
            $name = md5(serialize($config));
        }

        if (true === $name || !isset(self::$instance[$name])) {
            // 解析连接参数 支持数组和字符串
            $options = self::parseConfig($config);

            if (empty($options['type'])) {
                throw new InvalidArgumentException('Undefined db type');
            }

            $class = false !== strpos($options['type'], '\\') ? $options['type'] : '\\think\\db\\connector\\' . ucwords($options['type']);
            // 记录初始化信息
            self::$log[] = '[ DB ] INIT ' . $options['type'];

            if (true === $name) {
                $name = md5(serialize($config));
            }

            self::$instance[$name] = new $class($options);
        }

        return self::$instance[$name];
    }
934955
def getConf(self, conftype):
        '''
        
        '''
        zooconf={}
        if conftype not in [ZooConst.CLIENT, ZooConst.WORKER, ZooConst.BROKER]:
            raise Exception('Zooborg.getConf: invalid type')

        self.initconn()
        if conftype in [ZooConst.CLIENT, ZooConst.WORKER]:
            zooconf={'broker': {'connectionstr': None}}
            zoopath='/distark/' + conftype + '/conf/broker/connectionstr'
            zooconf['broker']['connectionstr'], stat = self.zk.get(zoopath)

        if conftype in [ZooConst.BROKER]:
            zooconf={'bindstr': None}
            zoopath='/distark/' + conftype + '/conf/bindstr'
            zooconf['bindstr'], stat = self.zk.get(zoopath)

        return zooconf
1170791
private function getConnectionType(array $config)
    {
        $isGrpcExtensionLoaded = $this->isGrpcLoaded();
        $defaultTransport = $isGrpcExtensionLoaded ? 'grpc' : 'rest';
        $transport = isset($config['transport'])
            ? strtolower($config['transport'])
            : $defaultTransport;

        if ($transport === 'grpc') {
            if (!$isGrpcExtensionLoaded) {
                throw new GoogleException(
                    'gRPC support has been requested but required dependencies ' .
                    'have not been found. ' . $this->getGrpcInstallationMessage()
                );
            }
        }

        return $transport;
    }