- Recipes
- AWS Redshift to Amazon S3 NDJSON file
Connect AWS Redshift and Amazon S3 NDJSON file in our serverless environment
Use this template to Read rows from AWS Redshift table using them to create NDJSON file entries in Amazon S3 Bucket.
Share
Read rows from AWS Redshift table
Used integrations:
- JavaScript
- Python
class AwsRedshiftSourceSelect {
async init() {
// TODO: Create your aws-redshift credential
// More info at https://yepcode.io/docs/integrations/aws-redshift/#credential-configuration
this.awsRedshift = yepcode.integration.awsRedshift(
"your-aws-redshift-credential-name"
);
// TODO: Customize the command to be executed
// More info at https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/clients/client-redshift-data/interfaces/executestatementcommandinput.html
const {
Id
} = await this.awsRedshift.send(
new ExecuteStatementCommand({
ClusterIdentifier: "your-cluster-identifier",
Database: "your-database-name",
DbUser: "your-database-user",
Sql: "SELECT * FROM your-table-name;",
})
);
this.statementId = Id;
await this._awaitStatementToFinish();
}
async fetch(publish, done) {
let nextToken;
// if result is returned paginated, iterate to publish entire statement result
do {
const result = await this.awsRedshift.send(
new GetStatementResultCommand({
Id: this.statementId,
NextToken: nextToken,
})
);
nextToken = result.NextToken;
for (const record of result.Records) {
// Each record come as a list of record cells
// More info at https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/clients/client-redshift-data/interfaces/getstatementresultcommandoutput.html
// TODO: Customize record columns mapping to the item that will be published
const item = {
id: record.id,
...record
};
await publish(item);
}
} while (nextToken);
done();
}
async close() {}
_awaitStatementToFinish() {
return new Promise((resolve, reject) => {
const describeStatementCommand = new DescribeStatementCommand({
Id: this.statementId,
});
// Configure interval to check statement status
const intervalId = setInterval(async () => {
const result = await this.awsRedshift.send(describeStatementCommand);
if (result.Status === "FINISHED") {
clearInterval(intervalId);
resolve();
return;
}
if (result.Status === "FAILED" || result.Status === "ABORTED") {
clearInterval(intervalId);
reject();
return;
}
}, 1000);
});
}
}
import time
class AwsRedshiftSourceSelect:
def setup(self):
# TODO: Create your Redshift credential:
# More info at https://yepcode.io/docs/integrations/aws-redshift/#credential-configuration
self.aws_redshift_client = yepcode.integration.awsRedshift(
"your-redshift-credential-name"
)
# TODO: Customize your cluster id, database name, user and sql query
response = self.aws_redshift_client.execute_statement(
ClusterIdentifier="cluster-name",
Database="db-name",
DbUser="db-user",
Sql="SELECT * FROM your-table-name"
)
self.statement_id = response.get("Id")
self._await_statement_to_finish()
def generator(self):
# See all supported params in: https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/redshift-data/client/execute_statement.html
response = self.aws_redshift_client.get_statement_result(Id=self.statement_id)
for record in response.get("Records", []):
yield record
def _await_statement_to_finish(self):
while True:
response = self.aws_redshift_client.describe_statement(
Id=self.statement_id
)
status = response["Status"]
if status == "FINISHED":
return
if status in ("FAILED", "ABORTED"):
raise Exception(f"Statement failed with status: {status}")
time.sleep(1)
def close(self):
pass
Do you need help solving this integration with YepCode?
Let's talkCreate NDJSON file entries in Amazon S3 Bucket
Used integrations:
- JavaScript
- Python
class AwsS3TargetUploadNdjson {
async init() {
// TODO: Create your aws-s3 credential
// More info at https://yepcode.io/docs/integrations/aws-s3/#credential-configuration
const awsS3 = yepcode.integration.awsS3("your-aws-s3-credential-name");
// Transforms the items into a ndjson format
this.stringifier = ndjson.stringify();
const targetStream = new PassThrough();
this.stringifier.pipe(targetStream);
// TODO: customize the Upload content
// More info at: https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/interfaces/_aws_sdk_lib_storage.options-1.html
const upload = new Upload({
client: awsS3,
params: {
Bucket: "your-bucket-name",
Key: "your-file-name.ndjson",
Body: targetStream,
},
});
upload.on("httpUploadProgress", (progress) => {
console.log(`Upload progress`, progress);
});
this.uploadPromise = upload.done();
}
async consume(item) {
this.stringifier.write(item);
}
async close() {
try {
this.stringifier.end();
} catch (error) {
console.error(`Error ending stringifier`, error);
}
try {
await this.uploadPromise;
} catch (error) {
console.error(`Error ending upload`, error);
}
}
}
import ndjson
import io
class AccumulatingStream:
def __init__(self):
self.data = io.BytesIO()
def write(self, item):
self.data.write(item.encode("utf-8"))
def get_stream(self):
self.data.seek(0)
return self.data
class AwsS3TargetUploadNdjson:
def setup(self):
# TODO: Create your S3 credential:
# More info at https://yepcode.io/docs/integrations/aws-s3/#credential-configuration
self.aws_s3_client = yepcode.integration.awsS3("your-s3-credential-name")
self.acc_stream = AccumulatingStream()
self.stringifier = ndjson.writer(self.acc_stream, ensure_ascii=False)
def consume(self, generator, done):
for item in generator:
self.stringifier.writerow(item)
done()
def close(self):
# TODO: customize the bucket name and object key
try:
self.aws_s3_client.upload_fileobj(
self.acc_stream.get_stream(),
"bucket-name",
"path/to/object.ndjson",
)
except Exception as error:
print(f"Error uploading object: {error}")
FAQs
YepCode is a SaaS platform that enables the creation, execution and monitoring of integrations and automations using source code in a serverless environment.
We like to call it the Zapier for developers, since we bring all the agility and benefits of NoCode tools (avoid server provisioning, environment configuration, deployments,...), but with all the power of being able to use a programming language like JavaScript or Python.
These recipes are an excellent starting point for creating your own YepCode processes and solving complex integration and automation problems.
You only have to complete the sign up form and your account will be created with our FREE plan (no credit card required).
YepCode has been created with a clear enterprise focus, offering a multi-tenant environment, team management capabilities, high security and auditing standards, Identity Provider (IdP) integrations, and on-premise options. It serves as the Swiss army knife for engineering teams, especially those requiring the extraction or transmission of information to external systems. It excels in scenarios demanding flexibility and adaptability to change within the process.
Sure! You only need to configure YepCode servers to establish a connection with that service. Check our docs page to get more information.