ColdFusion Function to Delete Generic Records from Generic Tables

Thought I’d share a simple generic ColdFusion delete function I wrote this morning. We develop many sites where I work and often they each end up with their own set of unique content management tools. All of the sites share the need for CRUD (create, read, update, delete) functionality and often the query syntax is the same for data retrieval and deletion:

DELETE
FROM table
WHERE table_id = variable_id

In writing a component for some of the tools I started wondering if, in addition to data, I could also pass the names of database tables and columns to create an all-purpose generic delete function.
I started by created a generic component, generic.cfc and wrote my function:

<cffunction name=”deleteRecordByID” access=”public” returntype=”Boolean”
hint=”Deletes a record from a passed table based on passed id” >
<cfargument name=”tableName” type=”string” required=”yes” />

<cfargument name=”idColumnName” type=”string” required=”yes” />
<cfargument name=”idValue” type=”numeric” required=”yes” />
<cfargument name=”dsn” type=”string” required=”no” default=”myDSN” />
<cftry>
<cfquery name=”qDelRecord” datasource=”#arguments.dsn#”>
DELETE
FROM #arguments.tableName#
WHERE #arguments.idColumnName# = <cfqueryparam value=”#arguments.idValue#” cfsqltype=”cf_sql_integer”>
</cfquery>
<cfcatch type=”any”>
<cfreturn false />
</cfcatch>
</cftry>
<cfreturn true />
</cffunction>

Then I gave it a shot:

<cfset objGeneric = createObject(“component”,”generic”) />
<cfset deleteResult = objGlobal.deleteRecordByID(“myTableName”, “myTableIDColumn”, idValue, request.dsn) />

To my surprise, er I mean just as I expected, it was successful. Whether you find the deleteByRecordID function clever or utterly ridiculous, the knowledge that you can pass database object names for query execution can be useful.

-rG

beginner, coldFusion

If you enjoyed this post, please consider to leave a comment or subscribe to the feed and get future articles delivered to your feed reader.

Comments

4 Responses to “ColdFusion Function to Delete Generic Records from Generic Tables”

Leave Comment

(required)

(required)