Skip to content

Instantly share code, notes, and snippets.

@DavidWells
Created February 24, 2025 19:43
Show Gist options
  • Save DavidWells/705bc164ea8d4e28cc493ca8d689f3be to your computer and use it in GitHub Desktop.
Save DavidWells/705bc164ea8d4e28cc493ca8d689f3be to your computer and use it in GitHub Desktop.
DynamoDB to SQL statement
function as_sql_insert(attributes, table_name) {
// Create a copy to avoid modifying the original object
let attrs = Object.assign({}, attributes)
console.log('attributes in sql insert: ', attrs)
const removed_attributes = ['__initialised__', 'PK', "SK", "GSI1PK", "GSI1SK", "GSI2PK", "GSI2SK", "GSI3PK", "GSI3SK", "batch"]
for (const attribute of removed_attributes) {
if (attribute in attrs) {
delete attrs[attribute]
}
}
let sql = `insert into ${table_name} (${Object.keys(attrs).join(',')}) values (`
for (const [attr_name, val] of Object.entries(attrs)) {
sql += typeof val === 'string' ? `'${val}'` : val
sql += ","
}
return sql.slice(0, -1) + ')'
}
// Example DynamoDB item
const transaction = {
PK: "TRANSACTION#123",
SK: "METADATA",
GSI1PK: "USER#456",
GSI1SK: "2023-10-15",
transaction_id: "tr_789456",
amount: 99.99,
currency: "USD",
payment_status: "pending",
customer_name: "John Doe",
email: "[email protected]"
}
// Generate SQL INSERT statement
const insertSQL = as_sql_insert(transaction, "transactions")
console.log(insertSQL)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment