SDK for Swift를 사용한 Amazon RDS 예제 - AWS SDK 코드 예제

Doc AWS SDK 예제 GitHub 리포지토리에서 더 많은 SDK 예제를 사용할 수 있습니다. AWS

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

SDK for Swift를 사용한 Amazon RDS 예제

다음 코드 예제에서는 Amazon RDS와 함께 AWS SDK for Swift를 사용하여 작업을 수행하고 일반적인 시나리오를 구현하는 방법을 보여줍니다.

기본 사항은 서비스 내에서 필수 작업을 수행하는 방법을 보여주는 코드 예제입니다.

작업은 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 작업은 관련 시나리오의 컨텍스트에 따라 표시되며, 개별 서비스 함수를 직접적으로 호출하는 방법을 보여줍니다.

각 예제에는 컨텍스트에서 코드를 설정하고 실행하는 방법에 대한 지침을 찾을 수 있는 전체 소스 코드에 대한 링크가 포함되어 있습니다.

기본 사항

다음 코드 예제는 다음과 같은 작업을 수행하는 방법을 보여줍니다.

  • 사용자 지정 DB 파라미터 그룹을 생성하고 파라미터 값을 설정합니다.

  • 파라미터 그룹을 사용하도록 구성된 DB 인스턴스를 생성합니다. DB 인스턴스에는 데이터베이스도 포함되어 있습니다.

  • 인스턴스의 스냅샷을 만듭니다.

  • 인스턴스 및 파라미터 그룹을 삭제합니다.

SDK for Swift
참고

GitHub에 더 많은 내용이 있습니다. AWS 코드 예 리포지토리에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

Package.swift 파일.

// swift-tools-version: 5.9 // // The swift-tools-version declares the minimum version of Swift required to // build this package. import PackageDescription let package = Package( name: "rds-scenario", // Let Xcode know the minimum Apple platforms supported. platforms: [ .macOS(.v13), .iOS(.v15) ], dependencies: [ // Dependencies declare other packages that this package depends on. .package( url: "https://github.com/awslabs/aws-sdk-swift", from: "1.4.0"), .package( url: "https://github.com/apple/swift-argument-parser.git", branch: "main" ) ], targets: [ // Targets are the basic building blocks of a package, defining a module or a test suite. // Targets can depend on other targets in this package and products // from dependencies. .executableTarget( name: "rds-scenario", dependencies: [ .product(name: "AWSRDS", package: "aws-sdk-swift"), .product(name: "ArgumentParser", package: "swift-argument-parser") ], path: "Sources") ] )

Swift 코드 파일 entry.swift.

// An example that shows how to use the AWS SDK for Swift to perform a variety // of operations using Amazon Relational Database Service (RDS). // import ArgumentParser import Foundation import AWSRDS struct ExampleCommand: ParsableCommand { @Option(help: "The AWS Region to run AWS API calls in.") var awsRegion = "us-east-1" @Option(help: "The username to use for the database administrator.") var dbUsername = "admin" @Option(help: "The password to use for the database administrator.") var dbPassword: String static var configuration = CommandConfiguration( commandName: "rds-scenario", abstract: """ Performs various operations to demonstrate the use of Amazon RDS Instances using the AWS SDK for Swift. """, discussion: """ """ ) /// Called by ``main()`` to run the bulk of the example. func runAsync() async throws { let example = try await Example(region: awsRegion, username: dbUsername, password: dbPassword) await example.run() } } class Example { let rdsClient: RDSClient // Storage for AWS RDS properties let dbUsername: String let dbPassword: String var dbInstanceIdentifier: String var dbSnapshotIdentifier: String var dbParameterGroupName: String var dbParameterGroup: RDSClientTypes.DBParameterGroup? var selectedEngineVersion: String? init(region: String, username: String, password: String) async throws{ let rdsConfig = try await RDSClient.RDSClientConfiguration(region: region) rdsClient = RDSClient(config: rdsConfig) dbUsername = username dbPassword = password dbParameterGroupName = "" dbInstanceIdentifier = "" dbSnapshotIdentifier = "" } /// The example's main body. func run() async { var parameterGroupFamilies: Set<String> = [] //===================================================================== // 1. Get available database engine families for MySQL. //===================================================================== let engineVersions = await getDBEngineVersions(engineName: "mysql") for version in engineVersions { if version.dbParameterGroupFamily != nil { parameterGroupFamilies.insert(version.dbParameterGroupFamily!) } } if engineVersions.count > 0 { selectedEngineVersion = engineVersions.last!.engineVersion } else { print("*** Unable to find a valid database engine version. Canceling operations.") await cleanUp() return } print("Found \(parameterGroupFamilies.count) parameter group families:") for family in parameterGroupFamilies { print(" \(family)") } //===================================================================== // 2. Select an engine family and create a custom DB parameter group. // We select a family by sorting the set of family names, then // choosing the last one. //===================================================================== let sortedFamilies = parameterGroupFamilies.sorted() guard let selectedFamily = sortedFamilies.last else { print("*** Unable to find a database engine family. Canceling operations.") await cleanUp() return } print("Selected database engine family \(selectedFamily)") dbParameterGroupName = tempName(prefix: "rds-example") print("Creating a database parameter group named \(dbParameterGroupName) using \(selectedFamily)") dbParameterGroup = await createDBParameterGroup(groupName: dbParameterGroupName, familyName: selectedFamily) //===================================================================== // 3. Get the parameter group's details. //===================================================================== print("Getting the database parameter group list...") let dbParameterGroupList = await describeDBParameterGroups(groupName: dbParameterGroupName) guard let dbParameterGroupList else { await cleanUp() return } print("Found \(dbParameterGroupList.count) parameter groups...") for group in dbParameterGroupList { print(" \(group.dbParameterGroupName ?? "<unknown>")") } print() //===================================================================== // 4. Get a list of the parameter group's parameters. This list is // likely to be long, so use pagination. Find the // auto_increment_offset and auto_increment_increment parameters. //===================================================================== let parameters = await describeDBParameters(groupName: dbParameterGroupName) //===================================================================== // 5. Parse and display each parameter's name, description, and // allowed values. //===================================================================== for parameter in parameters { let name = parameter.parameterName guard let name else { print("*** Unable to get parameter name!") continue } if name == "auto_increment_offset" || name == "auto_increment_increment" { print("Parameter \(name):") print(" Value: \(parameter.parameterValue ?? "<undefined>")") print(" Data type: \(parameter.dataType ?? "<unknown>")") print(" Description: \(parameter.description ?? "")") print(" Allowed values: \(parameter.allowedValues ?? "<unspecified")") print(String(repeating: "=", count: 78)) } } //===================================================================== // 6. Modify both the auto_increment_offset and // auto_increment_increment parameters in one call in the custom // parameter group. Set their parameterValue fields to a new // permitted value. //===================================================================== print("Setting auto_increment_offset and auto_increment_increment both to 5...") await modifyDBParameters(groupName: dbParameterGroupName) //===================================================================== // 7. Get and display the updated parameters, specifying a source of // "user" to get only the modified parameters. //===================================================================== let updatedParameters = await describeDBParameters(groupName: dbParameterGroupName, source: "user") for parameter in updatedParameters { let name = parameter.parameterName guard let name else { print("*** Unable to get parameter name!") continue } print("Parameter \(name):") print(" Value: \(parameter.parameterValue ?? "<undefined>")") print(" Data type: \(parameter.dataType ?? "<unknown>")") print(" Description: \(parameter.description ?? "")") print(" Allowed values: \(parameter.allowedValues ?? "<unspecified")") print(String(repeating: "=", count: 78)) } //===================================================================== // 8. Get a list of allowed engine versions using // DescribeRDSEngineVersions. //===================================================================== await listAllowedEngines(family: selectedFamily) //===================================================================== // 9. Get a list of micro instance classes available for the selected // engine and engine version. //===================================================================== let dbInstanceClass = await chooseMicroInstance(engine: "mysql", engineVersion: selectedEngineVersion) guard let dbInstanceClass else { print("Did not get a valid instance class. Canceling operations.") await cleanUp() return } //===================================================================== // 10. Create an RDS database that contains a MySQL database and uses // the parameter group we created. //===================================================================== print("Creating the database instance...") guard let instanceClass = dbInstanceClass.dbInstanceClass else { print("Instance class name is unknown. Canceling operations.") await cleanUp() return } dbInstanceIdentifier = tempName(prefix: "sample-identifier") let dbInstanceArn = await createDBInstance( name: "SampleDatabase\(Int.random(in: 1000000..<1000000000))", instanceIdentifier: dbInstanceIdentifier, parameterGroupName: dbParameterGroupName, engine: "mysql", engineVersion: selectedEngineVersion!, instanceClass: instanceClass, username: dbUsername, password: dbPassword ) if dbInstanceArn == nil { await cleanUp() return } //===================================================================== // 11. Wait for the database instance to be ready by calling // DescribeDBInstances repeatedly until it reports // dbInstanceStatus as "available". This can take upwards of 10 // minutes, let the user know that. //===================================================================== guard let endpoint = await waitUntilDBInstanceReady(instanceIdentifier: dbInstanceIdentifier) else { print("\nDid not get a valid endpoint from AWS RDS.") await cleanUp() return } guard let endpointAddress = endpoint.address else { print("\nNo endpoint address returned.") await cleanUp() return } guard let endpointPort = endpoint.port else { print("\nNo endpoint port returned.") await cleanUp() return } //===================================================================== // 12. Display connection information for the database instance. //===================================================================== print("\nTo connect to the new database instance using 'mysql' from the shell:") print(" mysql -h \(endpointAddress) -P \(endpointPort) -u \(self.dbUsername)") //===================================================================== // 13. Create a snapshot of the database instance. //===================================================================== dbSnapshotIdentifier = tempName(prefix: "sample-snapshot") await createDBSnapshot(instanceIdentifier: dbInstanceIdentifier, snapshotIdentifier: dbSnapshotIdentifier) //===================================================================== // 14. Wait for the snapshot to be ready. //===================================================================== await waitUntilDBSnapshotReady(instanceIdentifier: dbInstanceIdentifier, snapshotIdentifier: dbSnapshotIdentifier) // That's it! Clean up and exit! print("Example complete! Cleaning up...") await cleanUp() } /// Clean up by discarding and closing down all allocated EC2 items. func cleanUp() async { print("Deleting the database instance \(dbInstanceIdentifier)...") await deleteDBInstance(instanceIdentifier: dbInstanceIdentifier) await waitUntilDBInstanceDeleted(instanceIdentifier: dbInstanceIdentifier) print("Deleting the database parameter group \(dbParameterGroupName)...") await deleteDBParameterGroup(groupName: dbParameterGroupName) } /// Get all the database engine versions available for the specified /// database engine. /// /// - Parameter engineName: The name of the database engine to query. /// /// - Returns: An array of `RDSClientTypes.DBEngineVersion` structures, /// each describing one supported version of the specified database. func getDBEngineVersions(engineName: String) async -> [RDSClientTypes.DBEngineVersion] { do { let output = try await rdsClient.describeDBEngineVersions( input: DescribeDBEngineVersionsInput( engine: engineName ) ) return output.dbEngineVersions ?? [] } catch { return [] } } /// Create a new database parameter group with the specified name. /// /// - Parameters: /// - groupName: The name of the new parameter group. /// - familyName: The name of the parameter group family. /// - Returns: func createDBParameterGroup(groupName: String, familyName: String) async -> RDSClientTypes.DBParameterGroup? { do { let output = try await rdsClient.createDBParameterGroup( input: CreateDBParameterGroupInput( dbParameterGroupFamily: familyName, dbParameterGroupName: groupName, description: "Created using the AWS SDK for Swift" ) ) return output.dbParameterGroup } catch { print("*** Error creating the parameter group: \(error.localizedDescription)") return nil } } /// Get descriptions of the database parameter groups matching the given /// name. /// /// - Parameter groupName: The name of the parameter group to describe. /// /// - Returns: An array of [RDSClientTypes.DBParameterGroup] objects /// describing the parameter group. func describeDBParameterGroups(groupName: String) async -> [RDSClientTypes.DBParameterGroup]? { do { let output = try await rdsClient.describeDBParameterGroups( input: DescribeDBParameterGroupsInput( dbParameterGroupName: groupName ) ) return output.dbParameterGroups } catch { print("*** Error getting the database parameter group's details: \(error.localizedDescription)") return nil } } /// Returns the detailed parameter list for the specified database /// parameter group. /// /// - Parameters: /// - groupName: The name of the parameter group to return parameters for. /// - source: The types of parameters to return (`user`, `system`, or /// `engine-default`). /// /// - Returns: An array of `RdSClientTypes.Parameter` objects, each /// describing one of the group's parameters. func describeDBParameters(groupName: String, source: String? = nil) async -> [RDSClientTypes.Parameter] { var parameterList: [RDSClientTypes.Parameter] = [] do { let pages = rdsClient.describeDBParametersPaginated( input: DescribeDBParametersInput( dbParameterGroupName: groupName, source: source ) ) for try await page in pages { guard let parameters = page.parameters else { return [] } parameterList += parameters } } catch { print("*** Error getting database parameters: \(error.localizedDescription)") return [] } return parameterList } /// Demonstrates modifying two of the specified database parameter group's /// parameters. /// /// - Parameter groupName: The name of the parameter group to change /// parameters for. func modifyDBParameters(groupName: String) async { let parameter1 = RDSClientTypes.Parameter( applyMethod: RDSClientTypes.ApplyMethod.immediate, parameterName: "auto_increment_offset", parameterValue: "5" ) let parameter2 = RDSClientTypes.Parameter( applyMethod: RDSClientTypes.ApplyMethod.immediate, parameterName: "auto_increment_increment", parameterValue: "5" ) let parameterList = [parameter1, parameter2] do { _ = try await rdsClient.modifyDBParameterGroup( input: ModifyDBParameterGroupInput( dbParameterGroupName: groupName, parameters: parameterList ) ) print("Successfully modified the parameter group \(groupName).") } catch { print("*** Error modifying the parameter group \(groupName): \(error.localizedDescription)") } } /// Output a list of the database engine versions supported by the /// specified family. /// /// - Parameter family: The family for which to list allowed database /// engines. func listAllowedEngines(family: String?) async { do { let output = try await rdsClient.describeDBEngineVersions( input: DescribeDBEngineVersionsInput( dbParameterGroupFamily: family, engine: "mysql" ) ) guard let engineVersions = output.dbEngineVersions else { print("No engine versions returned.") return } print("Found \(engineVersions.count) database engine versions:") for version in engineVersions { print(" \(version.engineVersion ?? "<unknown>"): \(version.dbEngineDescription ?? "")") } } catch { print("*** Error getting database engine version list: \(error.localizedDescription)") return } } /// Print a list of available database instances with "micro" in the class /// name, then return one of them to be used by other code. /// /// - Parameters: /// - engine: The database engine for which to list database instance /// classes. /// - engineVersion: The database version for which to list instances. /// /// - Returns: An `RDSClientTypes.OrderableDBInstanceOption` describing /// the selected instance type. func chooseMicroInstance(engine: String = "mysql", engineVersion: String? = nil) async -> RDSClientTypes.OrderableDBInstanceOption? { do { let pages = rdsClient.describeOrderableDBInstanceOptionsPaginated( input: DescribeOrderableDBInstanceOptionsInput( engine: engine, engineVersion: engineVersion ) ) var optionsList: [RDSClientTypes.OrderableDBInstanceOption] = [] for try await page in pages { guard let orderableDBInstanceOptions = page.orderableDBInstanceOptions else { continue } for dbInstanceOption in orderableDBInstanceOptions { guard let className = dbInstanceOption.dbInstanceClass else { continue } if className.contains("micro") { optionsList.append(dbInstanceOption) } } } print("Found \(optionsList.count) database instances of 'micro' class types:") for dbInstanceOption in optionsList { print(" \(dbInstanceOption.engine ?? "<unknown>") \(dbInstanceOption.engineVersion ?? "<unknown>") (\(dbInstanceOption.dbInstanceClass ?? "<unknown class>"))") } return optionsList[0] } catch { print("*** Error getting a list of orderable instance options: \(error.localizedDescription)") return nil } } /// Create a new database instance. /// /// - Parameters: /// - name: The name of the database to create. /// - instanceIdentifier: The identifier to give the new database /// instance. /// - parameterGroupName: The name of the parameter group to associate /// with the new database instance. /// - engine: The database engine to use. /// - engineVersion: The version of the database given by `engine` to /// use. /// - instanceClass: The memory and compute capacity of the database /// instance, such as `db.m5.large``. /// - username: The admin user's username to establish for the new /// instance. /// - password: The password to use for the specified user's access. /// /// - Returns: A string indicating the ARN of the newly created database /// instance, or nil if the instance couldn't be created. func createDBInstance(name: String, instanceIdentifier: String, parameterGroupName: String, engine: String, engineVersion: String, instanceClass: String, username: String, password: String) async -> String? { do { let output = try await rdsClient.createDBInstance( input: CreateDBInstanceInput( allocatedStorage: 100, dbInstanceClass: instanceClass, dbInstanceIdentifier: instanceIdentifier, dbName: name, dbParameterGroupName: parameterGroupName, engine: engine, engineVersion: engineVersion, masterUserPassword: password, masterUsername: username, storageType: "gp2" ) ) guard let dbInstance = output.dbInstance else { print("*** Unable to get the database instance.") return nil } return dbInstance.dbInstanceArn } catch { print("*** An error occurred while creating the database instance: \(error.localizedDescription)") return nil } } /// Wait until the specified database is available to use. /// /// - Parameter instanceIdentifier: The database instance identifier of the /// database to wait for. func waitUntilDBInstanceReady(instanceIdentifier: String) async -> RDSClientTypes.Endpoint? { do { putString("Waiting for the database instance to be ready to use. This may take 10 minutes or more...") while true { let output = try await rdsClient.describeDBInstances( input: DescribeDBInstancesInput( dbInstanceIdentifier: instanceIdentifier ) ) guard let instanceList = output.dbInstances else { continue } for instance in instanceList { let status = instance.dbInstanceStatus guard let status else { print("\nUnable to determine the status.") continue } if status.contains("available") { return instance.endpoint } else { putString(".") do { try await Task.sleep(for: .seconds(15)) } catch { print("*** Error pausing the task!") } } } } } catch { print("*** Unable to wait until the database is ready: \(error.localizedDescription)") return nil } } /// Create a snapshot of the specified name. /// /// - Parameters: /// - instanceIdentifier: The identifier of the database instance to /// snapshot. /// - snapshotIdentifier: A unique identifier to give the newly-created /// snapshot. func createDBSnapshot(instanceIdentifier: String, snapshotIdentifier: String) async { do { let output = try await rdsClient.createDBSnapshot( input: CreateDBSnapshotInput( dbInstanceIdentifier: instanceIdentifier, dbSnapshotIdentifier: snapshotIdentifier ) ) guard let snapshot = output.dbSnapshot else { print("No snapshot returned.") return } print("The snapshot has been created with ID \(snapshot.dbiResourceId ?? "<unknown>")") } catch { print("*** Unable to create the database snapshot named \(snapshotIdentifier): \(error.localizedDescription)") } } /// Wait until the specified database snapshot is available to use. /// /// - Parameters: /// - instanceIdentifier: The identifier of the database for which the /// snapshot was taken. /// - snapshotIdentifier: The identifier of the snapshot to wait for. func waitUntilDBSnapshotReady(instanceIdentifier: String, snapshotIdentifier: String) async { var snapshotReady = false putString("Waiting for the snapshot to be ready...") do { while !snapshotReady { let output = try await rdsClient.describeDBSnapshots( input: DescribeDBSnapshotsInput( dbInstanceIdentifier: instanceIdentifier, dbSnapshotIdentifier: snapshotIdentifier ) ) guard let snapshotList = output.dbSnapshots else { return } for snapshot in snapshotList { guard let snapshotReadyStr = snapshot.status else { return } if snapshotReadyStr.contains("available") { snapshotReady = true print() } else { putString(".") do { try await Task.sleep(for: .seconds(15)) } catch { print("\n*** Error pausing the task!") } } } } } catch { print("\n*** Unable to wait for the database snapshot to be ready: \(error.localizedDescription)") } } /// Delete the specified database instance. /// /// - Parameter instanceIdentifier: The identifier of the database /// instance to delete. func deleteDBInstance(instanceIdentifier: String) async { do { _ = try await rdsClient.deleteDBInstance( input: DeleteDBInstanceInput( dbInstanceIdentifier: instanceIdentifier, deleteAutomatedBackups: true, skipFinalSnapshot: true ) ) } catch { print("*** Error deleting the database instance \(instanceIdentifier): \(error.localizedDescription)") } } /// Wait until the specified database instance has been deleted. /// /// - Parameter instanceIdentifier: The identifier of the database /// instance to wait for. func waitUntilDBInstanceDeleted(instanceIdentifier: String) async { putString("Waiting for the database instance to be deleted. This may take a few minutes...") do { var isDatabaseDeleted = false var foundInstance = false while !isDatabaseDeleted { let output = try await rdsClient.describeDBInstances(input: DescribeDBInstancesInput()) guard let instanceList = output.dbInstances else { return } foundInstance = false for instance in instanceList { guard let foundInstanceIdentifier = instance.dbInstanceIdentifier else { continue } if instanceIdentifier == foundInstanceIdentifier { foundInstance = true break } else { putString(".") do { try await Task.sleep(for: .seconds(15)) } catch { print("\n*** Error pausing the task!") } } } if !foundInstance { isDatabaseDeleted = true print() } } } catch { print("\n*** Error waiting for the database instance to be deleted: \(error.localizedDescription)") } } /// Delete the specified database parameter group. /// /// - Parameter groupName: The name of the parameter group to delete. func deleteDBParameterGroup(groupName: String) async { do { _ = try await rdsClient.deleteDBParameterGroup( input: DeleteDBParameterGroupInput( dbParameterGroupName: groupName ) ) } catch { print("*** Error deleting the database parameter group \(groupName): \(error.localizedDescription)") } } /// Generate and return a unique file name that begins with the specified /// string. /// /// - Parameters: /// - prefix: Text to use at the beginning of the returned name. /// /// - Returns: A string containing a unique filename that begins with the /// specified `prefix`. /// /// The returned name uses a random number between 1 million and 1 billion to /// provide reasonable certainty of uniqueness for the purposes of this /// example. func tempName(prefix: String) -> String { return "\(prefix)-\(Int.random(in: 1000000..<1000000000))" } /// Print a string to standard output without a trailing newline, and /// without buffering. /// /// - Parameter str: The string to output. func putString(_ str: String = "") { if str.length >= 1 { let data = str.data(using: .utf8) guard let data else { return } FileHandle.standardOutput.write(data) } } } /// The program's asynchronous entry point. @main struct Main { static func main() async { let args = Array(CommandLine.arguments.dropFirst()) do { let command = try ExampleCommand.parse(args) try await command.runAsync() } catch { ExampleCommand.exit(withError: error) } } }

작업

다음 코드 예시는 CreateDBInstance의 사용 방법을 보여 줍니다.

SDK for Swift
참고

GitHub에 더 많은 내용이 있습니다. AWS 코드 예 리포지토리에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

import AWSRDS /// Create a new database instance. /// /// - Parameters: /// - name: The name of the database to create. /// - instanceIdentifier: The identifier to give the new database /// instance. /// - parameterGroupName: The name of the parameter group to associate /// with the new database instance. /// - engine: The database engine to use. /// - engineVersion: The version of the database given by `engine` to /// use. /// - instanceClass: The memory and compute capacity of the database /// instance, such as `db.m5.large``. /// - username: The admin user's username to establish for the new /// instance. /// - password: The password to use for the specified user's access. /// /// - Returns: A string indicating the ARN of the newly created database /// instance, or nil if the instance couldn't be created. func createDBInstance(name: String, instanceIdentifier: String, parameterGroupName: String, engine: String, engineVersion: String, instanceClass: String, username: String, password: String) async -> String? { do { let output = try await rdsClient.createDBInstance( input: CreateDBInstanceInput( allocatedStorage: 100, dbInstanceClass: instanceClass, dbInstanceIdentifier: instanceIdentifier, dbName: name, dbParameterGroupName: parameterGroupName, engine: engine, engineVersion: engineVersion, masterUserPassword: password, masterUsername: username, storageType: "gp2" ) ) guard let dbInstance = output.dbInstance else { print("*** Unable to get the database instance.") return nil } return dbInstance.dbInstanceArn } catch { print("*** An error occurred while creating the database instance: \(error.localizedDescription)") return nil } }
  • API 세부 정보는 AWS SDK for Swift API 참조CreateDBInstance를 참조하세요.

다음 코드 예시는 CreateDBParameterGroup의 사용 방법을 보여 줍니다.

SDK for Swift
참고

GitHub에 더 많은 내용이 있습니다. AWS 코드 예 리포지토리에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

import AWSRDS /// Create a new database parameter group with the specified name. /// /// - Parameters: /// - groupName: The name of the new parameter group. /// - familyName: The name of the parameter group family. /// - Returns: func createDBParameterGroup(groupName: String, familyName: String) async -> RDSClientTypes.DBParameterGroup? { do { let output = try await rdsClient.createDBParameterGroup( input: CreateDBParameterGroupInput( dbParameterGroupFamily: familyName, dbParameterGroupName: groupName, description: "Created using the AWS SDK for Swift" ) ) return output.dbParameterGroup } catch { print("*** Error creating the parameter group: \(error.localizedDescription)") return nil } }

다음 코드 예시는 CreateDBSnapshot의 사용 방법을 보여 줍니다.

SDK for Swift
참고

GitHub에 더 많은 내용이 있습니다. AWS 코드 예 리포지토리에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

import AWSRDS /// Create a snapshot of the specified name. /// /// - Parameters: /// - instanceIdentifier: The identifier of the database instance to /// snapshot. /// - snapshotIdentifier: A unique identifier to give the newly-created /// snapshot. func createDBSnapshot(instanceIdentifier: String, snapshotIdentifier: String) async { do { let output = try await rdsClient.createDBSnapshot( input: CreateDBSnapshotInput( dbInstanceIdentifier: instanceIdentifier, dbSnapshotIdentifier: snapshotIdentifier ) ) guard let snapshot = output.dbSnapshot else { print("No snapshot returned.") return } print("The snapshot has been created with ID \(snapshot.dbiResourceId ?? "<unknown>")") } catch { print("*** Unable to create the database snapshot named \(snapshotIdentifier): \(error.localizedDescription)") } }
  • API 세부 정보는 AWS SDK for Swift API 참조CreateDBSnapshot을 참조하세요.

다음 코드 예시는 DeleteDBInstance의 사용 방법을 보여 줍니다.

SDK for Swift
참고

GitHub에 더 많은 내용이 있습니다. AWS 코드 예 리포지토리에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

import AWSRDS /// Delete the specified database instance. /// /// - Parameter instanceIdentifier: The identifier of the database /// instance to delete. func deleteDBInstance(instanceIdentifier: String) async { do { _ = try await rdsClient.deleteDBInstance( input: DeleteDBInstanceInput( dbInstanceIdentifier: instanceIdentifier, deleteAutomatedBackups: true, skipFinalSnapshot: true ) ) } catch { print("*** Error deleting the database instance \(instanceIdentifier): \(error.localizedDescription)") } }
  • API 세부 정보는 AWS SDK for Swift API 참조DeleteDBInstance를 참조하세요.

다음 코드 예시는 DeleteDBParameterGroup의 사용 방법을 보여 줍니다.

SDK for Swift
참고

GitHub에 더 많은 내용이 있습니다. AWS 코드 예 리포지토리에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

import AWSRDS /// Delete the specified database parameter group. /// /// - Parameter groupName: The name of the parameter group to delete. func deleteDBParameterGroup(groupName: String) async { do { _ = try await rdsClient.deleteDBParameterGroup( input: DeleteDBParameterGroupInput( dbParameterGroupName: groupName ) ) } catch { print("*** Error deleting the database parameter group \(groupName): \(error.localizedDescription)") } }

다음 코드 예시는 DescribeDBEngineVersions의 사용 방법을 보여 줍니다.

SDK for Swift
참고

GitHub에 더 많은 내용이 있습니다. AWS 코드 예 리포지토리에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

import AWSRDS /// Get all the database engine versions available for the specified /// database engine. /// /// - Parameter engineName: The name of the database engine to query. /// /// - Returns: An array of `RDSClientTypes.DBEngineVersion` structures, /// each describing one supported version of the specified database. func getDBEngineVersions(engineName: String) async -> [RDSClientTypes.DBEngineVersion] { do { let output = try await rdsClient.describeDBEngineVersions( input: DescribeDBEngineVersionsInput( engine: engineName ) ) return output.dbEngineVersions ?? [] } catch { return [] } }

다음 코드 예시는 DescribeDBInstances의 사용 방법을 보여 줍니다.

SDK for Swift
참고

GitHub에 더 많은 내용이 있습니다. AWS 코드 예 리포지토리에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

import AWSRDS /// Wait until the specified database is available to use. /// /// - Parameter instanceIdentifier: The database instance identifier of the /// database to wait for. func waitUntilDBInstanceReady(instanceIdentifier: String) async -> RDSClientTypes.Endpoint? { do { putString("Waiting for the database instance to be ready to use. This may take 10 minutes or more...") while true { let output = try await rdsClient.describeDBInstances( input: DescribeDBInstancesInput( dbInstanceIdentifier: instanceIdentifier ) ) guard let instanceList = output.dbInstances else { continue } for instance in instanceList { let status = instance.dbInstanceStatus guard let status else { print("\nUnable to determine the status.") continue } if status.contains("available") { return instance.endpoint } else { putString(".") do { try await Task.sleep(for: .seconds(15)) } catch { print("*** Error pausing the task!") } } } } } catch { print("*** Unable to wait until the database is ready: \(error.localizedDescription)") return nil } }

다음 코드 예시는 DescribeDBParameterGroups의 사용 방법을 보여 줍니다.

SDK for Swift
참고

GitHub에 더 많은 내용이 있습니다. AWS 코드 예 리포지토리에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

import AWSRDS /// Get descriptions of the database parameter groups matching the given /// name. /// /// - Parameter groupName: The name of the parameter group to describe. /// /// - Returns: An array of [RDSClientTypes.DBParameterGroup] objects /// describing the parameter group. func describeDBParameterGroups(groupName: String) async -> [RDSClientTypes.DBParameterGroup]? { do { let output = try await rdsClient.describeDBParameterGroups( input: DescribeDBParameterGroupsInput( dbParameterGroupName: groupName ) ) return output.dbParameterGroups } catch { print("*** Error getting the database parameter group's details: \(error.localizedDescription)") return nil } }

다음 코드 예시는 DescribeDBParameters의 사용 방법을 보여 줍니다.

SDK for Swift
참고

GitHub에 더 많은 내용이 있습니다. AWS 코드 예 리포지토리에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

import AWSRDS /// Returns the detailed parameter list for the specified database /// parameter group. /// /// - Parameters: /// - groupName: The name of the parameter group to return parameters for. /// - source: The types of parameters to return (`user`, `system`, or /// `engine-default`). /// /// - Returns: An array of `RdSClientTypes.Parameter` objects, each /// describing one of the group's parameters. func describeDBParameters(groupName: String, source: String? = nil) async -> [RDSClientTypes.Parameter] { var parameterList: [RDSClientTypes.Parameter] = [] do { let pages = rdsClient.describeDBParametersPaginated( input: DescribeDBParametersInput( dbParameterGroupName: groupName, source: source ) ) for try await page in pages { guard let parameters = page.parameters else { return [] } parameterList += parameters } } catch { print("*** Error getting database parameters: \(error.localizedDescription)") return [] } return parameterList }

다음 코드 예시는 DescribeDBSnapshots의 사용 방법을 보여 줍니다.

SDK for Swift
참고

GitHub에 더 많은 내용이 있습니다. AWS 코드 예 리포지토리에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

import AWSRDS /// Wait until the specified database snapshot is available to use. /// /// - Parameters: /// - instanceIdentifier: The identifier of the database for which the /// snapshot was taken. /// - snapshotIdentifier: The identifier of the snapshot to wait for. func waitUntilDBSnapshotReady(instanceIdentifier: String, snapshotIdentifier: String) async { var snapshotReady = false putString("Waiting for the snapshot to be ready...") do { while !snapshotReady { let output = try await rdsClient.describeDBSnapshots( input: DescribeDBSnapshotsInput( dbInstanceIdentifier: instanceIdentifier, dbSnapshotIdentifier: snapshotIdentifier ) ) guard let snapshotList = output.dbSnapshots else { return } for snapshot in snapshotList { guard let snapshotReadyStr = snapshot.status else { return } if snapshotReadyStr.contains("available") { snapshotReady = true print() } else { putString(".") do { try await Task.sleep(for: .seconds(15)) } catch { print("\n*** Error pausing the task!") } } } } } catch { print("\n*** Unable to wait for the database snapshot to be ready: \(error.localizedDescription)") } }

다음 코드 예시는 DescribeOrderableDBInstanceOptions의 사용 방법을 보여 줍니다.

SDK for Swift
참고

GitHub에 더 많은 내용이 있습니다. AWS 코드 예 리포지토리에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

import AWSRDS /// Print a list of available database instances with "micro" in the class /// name, then return one of them to be used by other code. /// /// - Parameters: /// - engine: The database engine for which to list database instance /// classes. /// - engineVersion: The database version for which to list instances. /// /// - Returns: An `RDSClientTypes.OrderableDBInstanceOption` describing /// the selected instance type. func chooseMicroInstance(engine: String = "mysql", engineVersion: String? = nil) async -> RDSClientTypes.OrderableDBInstanceOption? { do { let pages = rdsClient.describeOrderableDBInstanceOptionsPaginated( input: DescribeOrderableDBInstanceOptionsInput( engine: engine, engineVersion: engineVersion ) ) var optionsList: [RDSClientTypes.OrderableDBInstanceOption] = [] for try await page in pages { guard let orderableDBInstanceOptions = page.orderableDBInstanceOptions else { continue } for dbInstanceOption in orderableDBInstanceOptions { guard let className = dbInstanceOption.dbInstanceClass else { continue } if className.contains("micro") { optionsList.append(dbInstanceOption) } } } print("Found \(optionsList.count) database instances of 'micro' class types:") for dbInstanceOption in optionsList { print(" \(dbInstanceOption.engine ?? "<unknown>") \(dbInstanceOption.engineVersion ?? "<unknown>") (\(dbInstanceOption.dbInstanceClass ?? "<unknown class>"))") } return optionsList[0] } catch { print("*** Error getting a list of orderable instance options: \(error.localizedDescription)") return nil } }

다음 코드 예시는 ModifyDBParameterGroup의 사용 방법을 보여 줍니다.

SDK for Swift
참고

GitHub에 더 많은 내용이 있습니다. AWS 코드 예 리포지토리에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

import AWSRDS /// Demonstrates modifying two of the specified database parameter group's /// parameters. /// /// - Parameter groupName: The name of the parameter group to change /// parameters for. func modifyDBParameters(groupName: String) async { let parameter1 = RDSClientTypes.Parameter( applyMethod: RDSClientTypes.ApplyMethod.immediate, parameterName: "auto_increment_offset", parameterValue: "5" ) let parameter2 = RDSClientTypes.Parameter( applyMethod: RDSClientTypes.ApplyMethod.immediate, parameterName: "auto_increment_increment", parameterValue: "5" ) let parameterList = [parameter1, parameter2] do { _ = try await rdsClient.modifyDBParameterGroup( input: ModifyDBParameterGroupInput( dbParameterGroupName: groupName, parameters: parameterList ) ) print("Successfully modified the parameter group \(groupName).") } catch { print("*** Error modifying the parameter group \(groupName): \(error.localizedDescription)") } }