Skip to content

Commit

Permalink
feat: allow default database name different from root user name
Browse files Browse the repository at this point in the history
  • Loading branch information
dnz-bdeboer committed Oct 13, 2023
1 parent cdd2cca commit 8f6e4ee
Show file tree
Hide file tree
Showing 14 changed files with 140 additions and 76 deletions.
4 changes: 2 additions & 2 deletions .projen/deps.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion .projenrc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,12 @@ const project = new awscdk.AwsCdkConstructLibrary({
workflow: false,
},
constructsVersion: "10.1.168",
cdkVersion: "2.51.1",
cdkVersion: "2.64.0",
disableTsconfig: true,
tsconfigDev: {
compilerOptions: {
esModuleInterop: true,
noUnusedLocals: false,
},
},
eslint: true,
Expand Down
10 changes: 9 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ const cluster = new rds.ServerlessCluster(this, "Cluster", {
parameterGroup: rds.ParameterGroup.fromParameterGroupName(
this,
"ParameterGroup",
"default.aurora-postgresql10"
"default.aurora-postgresql11"
),
removalPolicy: RemovalPolicy.DESTROY,
scaling: {
Expand Down Expand Up @@ -227,6 +227,14 @@ Test code via projen with:

You can run the sample stack with:

npx cdk deploy --context vpc-id=vpc-0123456789 TestServerlessV1Stack

Or for v2:

npx cdk deploy TestServerlessV2Stack

If you want to use an existing vpc:

npx cdk deploy --context vpc-id=vpc-0123456789 TestServerlessV2Stack

# To do
Expand Down
64 changes: 32 additions & 32 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions package.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

16 changes: 12 additions & 4 deletions src/handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -206,12 +206,12 @@ export const handler = async (
| CloudFormationCustomResourceUpdateEvent
| CloudFormationCustomResourceDeleteEvent
): Promise<any> => {
//console.debug("EVENT", event)
console.log("event", event)

const requestType = event.RequestType
const resource: RdsSqlResource = event.ResourceProperties.Resource
const resourceId = event.ResourceProperties.ResourceId
const database = event.ResourceProperties.Database
const databaseName = event.ResourceProperties.DatabaseName

if (!Object.keys(jumpTable).includes(event.ResourceProperties.Resource)) {
throw `Resource type '${resource}' not recognised.`
Expand Down Expand Up @@ -250,8 +250,12 @@ export const handler = async (
}

if (sql) {
//console.debug("DATABASE", database)
console.debug("SQL", sql)
let database: string
if (resource === RdsSqlResource.ROLE) {
database = secretValues.dbname
} else {
database = databaseName ?? secretValues.dbname // connect to given database if possible, else to database mentioned in secret
}
const params = {
host: secretValues.host,
port: secretValues.port,
Expand All @@ -261,6 +265,10 @@ export const handler = async (
connectionTimeoutMillis: 2000, // return an error if a connection could not be established within 2 seconds
}
//console.debug ("PARAMS", params)
console.debug(
`Connecting to host ${params.host}:${params.port}, database ${params.database} as ${params.user}`
)
console.debug("Executing SQL", sql)
const pg_client = new Client(params)
await pg_client.connect()
try {
Expand Down
15 changes: 13 additions & 2 deletions src/provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,11 @@ import { Construct } from "constructs"

export interface RdsSqlProps {
/**
* VPC of your cluster.
* VPC network to place the provider lambda.
*
* Normally this is the VPC of your database.
*
* @default - Function is not placed within a VPC.
*/
readonly vpc: IVpc

Expand All @@ -26,6 +30,13 @@ export interface RdsSqlProps {
* Usually this is your cluster's master secret.
*/
readonly secret: ISecret

/**
* Timeout for lambda to do its work.
*
* @default - 5 minutes
*/
readonly timeout?: Duration
}

export class Provider extends Construct {
Expand Down Expand Up @@ -76,7 +87,7 @@ export class Provider extends Construct {
vpc: props.vpc,
entry: entry,
runtime: Runtime.NODEJS_18_X,
timeout: Duration.seconds(300),
timeout: props.timeout ?? Duration.seconds(300),
bundling: {
sourceMap: true,
externalModules: ["pg-native"],
Expand Down
2 changes: 1 addition & 1 deletion src/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ export class Schema extends CustomResource {
Resource: RdsSqlResource.SCHEMA,
ResourceId: props.schemaName,
SecretArn: props.provider.secret.secretArn,
Database: props.database ? props.database.databaseName : undefined,
DatabaseName: props.database ? props.database.databaseName : undefined,
},
})
this.node.addDependency(props.provider)
Expand Down
2 changes: 1 addition & 1 deletion src/sql.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ export class Sql extends CustomResource {
properties: {
Resource: RdsSqlResource.SQL,
SecretArn: props.provider.secret.secretArn,
Database: props.database ? props.database.databaseName : undefined,
DatabaseName: props.database ? props.database.databaseName : undefined,
Statement: props.statement,
},
})
Expand Down
11 changes: 8 additions & 3 deletions test/handler.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,9 @@ const SecretsManagerClientMock = SecretsManagerClient as jest.MockedClass<
>

const DB_PORT = 5432
const DB_MASTER_USERNAME = "postgres"
const DB_MASTER_USERNAME = "pgroot"
const DB_MASTER_PASSWORD = "masterpwd"
const DB_DEFAULT_DB = "postgres"
const DB_DEFAULT_DB = "dummy"

let pgContainer: StartedTestContainer
let pgHost: string
Expand All @@ -31,7 +31,9 @@ let pgPort: number
beforeEach(async () => {
pgContainer = await new GenericContainer("postgres")
.withExposedPorts(DB_PORT)
.withEnv("POSTGRES_USER", DB_MASTER_USERNAME)
.withEnv("POSTGRES_PASSWORD", DB_MASTER_PASSWORD)
.withEnv("POSTGRES_DB", DB_DEFAULT_DB)
.start()
pgHost = pgContainer.getHost()
pgPort = pgContainer.getMappedPort(DB_PORT)
Expand All @@ -50,6 +52,9 @@ SecretsManagerClientMock.prototype.send.mockImplementation(() => {
port: pgPort,
username: DB_MASTER_USERNAME,
password: DB_MASTER_PASSWORD,
dbname: DB_DEFAULT_DB,
engine: "postgres",
dbClusterIdentifier: "dummy",
}),
}
})
Expand Down Expand Up @@ -189,7 +194,7 @@ test("database with owner", async () => {
expect(await databaseExists(client, databaseName)).toEqual(true)
expect(await databaseOwnerIs(client, databaseName, roleName)).toEqual(true)
const create_table = createRequest("sql", "", {
Database: databaseName,
DatabaseName: databaseName,
Statement: "create table t(i int)",
})
await handler(create_table)
Expand Down
Loading

0 comments on commit 8f6e4ee

Please sign in to comment.