How can I make Coldfusion Reactor ignore some columns in a table - orm

I'm using Coldfusion 10 + Reactor in project. I add a new TIMESTAMP field which will auto updated to CURRENT_TIMESTAMP. It works when this new field is not included into Reactor objects, e.g. Dao, To, Record. but it will be failed once regenerate ColdFusion objects.
so how can I ignore the new field in reactor?
Here are the related code
<object name="Object">
<hasOne name="XXXX">
<relate from="KeyUUID" to="KeyUUID"/>
</hasOne>
...
</object>
After I regenerated ColdFusion objects, the create/update method in ObjectDao.cfc will include my new field. The ObjectDao.cfc is regenerated by Reactor according to my database table. I want this new field excluded from Reactor objects, e.g. Dao, To, Record.
<cfquery name="qCreate" datasource="#_getConfig().getDsn()#" username="#_getConfig().getUsername()#" password="#_getConfig().getPassword()#">
INSERT INTO #Convention.FormatObjectName(getObjectMetadata())#
(
...
#Convention.formatInsertFieldName('newField', 'Object')#
) VALUES (
...
<cfqueryparam cfsqltype="cf_sql_timestamp"
value="#arguments.to.newField#"
null="#Iif(NOT Len(arguments.to.lastModifiedDBTime), DE(true), DE(false))#"
/>
)
...
</cfquery>

We implement this by update ObjectDao.cfc for now.
<cffunction name="readFields" access="private" hint="I populate the table with fields." output="false" returntype="void">
...
<cfloop query="qFields">
<cfset blnProcess = true />
<cfif structKeyExists(stcFieldsToSkip,arguments.Object.getName())>
<cfif qFields.FIELD EQ stcFieldsToSkip[arguments.Object.getName()]>
<cfset blnProcess = false />
</cfif>
</cfif>
<cfif blnProcess>
<!---
mod by SPJ: in MySql 4 tinytext, text, mediumtext and longtext don't report their maxlength value, so we
have to set it by hand. The field lengths were obtained from http://www.cs.wcupa.edu/~rkline/mysqlEZinfo/data_types.html#Storage_requirements
--->
<cfswitch expression="#qFields.TYPE#">
...
</cfswitch>
<!--- end mod by SPJ --->
<!--- create the field --->
...
<!--- add the field to the table --->
<cfset arguments.Object.addField(Field) />
</cfif>
</cfloop>
</cffunction>

Related

ColdFusion: Insert Date Time in One Variable Into Database Oracle10

I have stuck with this problem for one hour. I am using ColdFusion language. In my code, I want to insert datetime into my database Oracle. Datetime format will look like this:
<cfset form.date_print = #dateFormat(Now(),"yyyy-mm-dd") & " " & timeFormat(now(), "HH:mm:ss")#>
and function to insert my datetime into my database will look like this:
<cfset qAdd = APPLICATION.qbs.insertData(column:'date_print,usr_id_print,qsd_id,loc_id',formData:'#FORM#',table:"qpl_print_log")>
In my table, format for attribute date_print is DATE.
This is snapshot when I click button to insert datetime into my database Oracle:
UPDATE
This is function to insert data to the database
<cffunction name="insertData" access="public" returntype="struct" output="no">
<cfargument name="column" required="true" type="string" hint="data">
<cfargument name="value" required="false" type="string" hint="data">
<cfargument name="formData" required="false" type="struct" hint="data">
<cfargument name="table" required="true" type="string" hint="table">
<cfargument name="dateType" required="false" type="string">
<cfargument name="sqlNvarcharType" required="false" type="string">
<cfargument name="returnID" required="true" type="boolean" default="true">
<cfargument name="db" required="false" type="string" hint="data" default="#variables.db.db_datasource_ro#">
<cfset var local = {}>
<cfset local.counter = 0>
<cfset local.return = {}>
<cfset local.return.status = "OK">
<cfset local.return.id = 0>
<cfset local.return.cuid = APPLICATION.cuid.getCUID()>
<cfif ListFind(column,"submit")>
<cfset column = ListDeleteAt( column, ListFind(column,"submit")) >
</cfif>
<cftry>
<cfquery name="local.insertData" datasource="#db#" result="myresult">
INSERT INTO #table#(#column#,cuid) VALUES(
<cfif isDefined('Arguments.value') AND Arguments.value NEQ "">
<cfloop from="1" to="#ListLen(Arguments.value,';')#" index="item">
<cfif isDefined('Arguments.dateType') AND ListFind(dateType,item)><cfqueryparam cfsqltype="cf_sql_date" value="#convertDate(trim(listGetAt(value, item,';')))#">
<cfelseif isDefined('Arguments.sqlNvarcharType') AND ListFind(sqlNvarcharType,item)><cfqueryparam cfsqltype="cf_sql_nvarchar" value="#trim(listGetAt(value, item,';'))#">
<cfelse><cfqueryparam cfsqltype="cf_sql_char" value="#trim(listGetAt(value, item,';'))#"></cfif><cfif item LT ListLen(column)>,</cfif>
</cfloop>
<cfelse>
<cfloop list="#column#" index="theField">
<cfset local.counter = local.counter+1>
<cfif isDefined('Arguments.dateType') AND ListFind(dateType,theField)><cfqueryparam cfsqltype="cf_sql_date" value="#convertDate(formData[theField])#">
<cfelseif isDefined('Arguments.sqlNvarcharType') AND ListFind(sqlNvarcharType,theField)><cfqueryparam cfsqltype="cf_sql_nvarchar" value="#trim(formData[theField])#">
<cfelse><cfqueryparam cfsqltype="cf_sql_varchar" value="#trim(formData[theField])#"></cfif><cfif local.counter LT ListLen(column)>,</cfif>
</cfloop>
</cfif>
,'#local.return.cuid#')
</cfquery>
<cfif Arguments.returnID EQ true>
<cfquery name="qetAutoIncrementID" datasource="#db#">
SELECT id
FROM #table#
WHERE cuid = '#local.return.cuid#'
</cfquery>
<cfset local.return.id = qetAutoIncrementID.id>
</cfif>
<cfcatch>
<cfset local.return.status = "BAD">
<cfset local.return.cfcatch = cfcatch>
<cfset APPLICATION.db.notifyError(functionname:"Insert:#table#", args:ARGUMENTS, cfcatch:cfcatch)>
</cfcatch>
</cftry>
<cfreturn local.return>
</cffunction>
In my table, attribute date_print show date format only.
But in ColdFusion, I send the format date and time like this 2016-05-16 14:12:35.
But If I want to see my time format, I need to click the pencil icon.
Hope anyone can help me to fix this problem.
Thank you
You are passing cfsqltype as cf_sql_date. You need to pass CF_SQL_TIMESTAMP as your cfsqltype.
Your cfqueryparam should look like this:
<cfqueryparam cfsqltype="CF_SQL_TIMESTAMP" value="#convertDate(trim(listGetAt(value, item,';')))#">
cf_sql_date truncates date-time to just a date value (actually evaluates as a numeric value) where as cf_sql_timestamp uses a full date time stamp.
You've got a couple of things going on here.
Oracle stores DATE datatypes with values for century, year, month, day, hour, minute and second. Kinda different that MS SQL's epoch storage, but you still have access to your time values in a date datatype. If you need more precision, TIMESTAMP datatype provides you down to I think 5 or 6 digits after the decimal (so lots of milliseconds).
For storing the datetime, Tushar is correct. You should use CF_SQL_TIMESTAMP instead of just CF_SQL_DATE. For Oracle, the TIMESTAMP value will give you the hour:minute:second precision you're looking for. Oracle is very datatype sensitive (whereas MS SQL can be more forgiving sometimes), and I believe a CF_SQL_DATE (which will work in MSSQL) is returned as an integer with the time portion truncated (giving you 0 hr, 0 min and 0 sec), and CF_SQL_TIMESTAMP is an actual timestamp object that Oracle (and other databases, like SQL Server) can better understand. So use TIMESTAMP instead of DATE.
The truncation is why you are seeing the 0:0:0 when you click to edit the value.
Your query tool itself is why you are seeing the date formatted the way you are.
I'm not sure which one you are using, but to change the display in SQL Developer, go to Tools >> Preferences >> Click NLS > Edit Date Format with the mask you want to use (YYYY-MM-DD HH24:MI:SS). This will display your query with your desired date format. TOAD or others should have something similar.
About halfway down the page is a chart with the applicable CF to datatype comparisons.
https://helpx.adobe.com/coldfusion/cfml-reference/coldfusion-tags/tags-p-q/cfqueryparam.html
Be careful when using date masking. Differnt systems do different things, and "y" can be different from "Y", even in ColdFusion.
Also, on a general code review note: Please validate your inputs (especially the table name) and use a maxlength argument in your queryparam. insertData() looks very injectable. Also, if this is CF >9, don't use var local. The LOCAL scope is now built into ColdFusion. It shouldn't break anything, but you're not really doing what your code thinks it's doing.

MS SQL Identity Column Not Counting Correctly on Identity Column [duplicate]

This question already has answers here:
Identity increment is jumping in SQL Server database
(6 answers)
Closed 7 years ago.
I am using MS SQL Server. Will someone please tell me why my identity column in my database just did a crazy jump in numbers when it is supposed to auto increment by 1 automatically? First off I have been entering data in row by row. Eventually after maybe 100 entries it would place them not in order sticking 101 right after 31 not in order. Now all of sudden it has jumped from 290's to 1400's when it should still be in order.... Management tools still show the right number of entries but it just makes no sense how this is supposed to be counting by one. Will someone please explain this to me?
<cfif structKeyExists(form, "user_pass")>
<!--- form has been submitted --->
<cffile
action = "upload"
fileField = "filefieldname"
destination = "#expandPath("/webapps/dash/images/")#"
nameConflict = "MakeUnique"
result = "myfile"
/>
<cfset imagePath = myfile.serverDirectory & "/" & myfile.serverFile>
<cfif isImageFile(imagePath)>
<cfquery datasource="test" name="UserRegistration">
INSERT INTO dbo.Users (employee_number, user_name, user_pass, firstname, lastname, position, email, phone_extension, branch, department, status, picture, admin)
VALUES (
<cfqueryparam value='#form.employee_number#' cfsqltype='cf_sql_varchar' />
, <cfqueryparam value='#form.user_name#' cfsqltype='cf_sql_varchar' />
, <cfqueryparam value='#form.user_pass#' cfsqltype='cf_sql_varchar' />
, <cfqueryparam value='#form.firstname#' cfsqltype='cf_sql_varchar' />
, <cfqueryparam value='#form.lastname#' cfsqltype='cf_sql_varchar' />
, <cfqueryparam value='#form.position#' cfsqltype='cf_sql_varchar' />
, <cfqueryparam value='#form.email#' cfsqltype='cf_sql_varchar' />
, <cfqueryparam value='#form.phone_extension#' cfsqltype='cf_sql_varchar' />
, <cfqueryparam value='Desoto' cfsqltype='cf_sql_varchar' />
, <cfqueryparam value='#form.department#' cfsqltype='cf_sql_varchar' />
, <cfqueryparam value='Active' cfsqltype='cf_sql_varchar' />
, <cfqueryparam value='#myfile.serverFile#' cfsqltype='cf_sql_varchar' />
, <cfqueryparam value='No' cfsqltype='cf_sql_varchar' />
)
</cfquery>
<script>
self.location="../login.cfm";
</script>
<cfelse>
<script>
<!--- not an image file so return some kind of validation message... --->
alert("Not an image file");
self.location="../register.cfm";
</script>
</cfif>
</cfif>
The numbers are guaranteed to be monotonically increasing, but not adjacent. Here is some relevant documentation.
In general, identity columns are also constrained to be unique or primary keys. However, they are not even guaranteed to be unique without these constraints.
They do increase. And the weird behavior is for efficiency, particularly in parallel systems.
It is easy enough to get a sequential value with no gaps, if you need it, at query time:
select row_number() over (order by id) as sequential_with_no_gaps

error : Query Of Queries syntax error

<cfquery name="result" datasource="Training">
select TE.firstname,TE.lastname,TD.deparmentname,TE.salary,TE.DateOfBirth
from TEmployee as TE
inner join Tdepartment as TD
on TE.departmentID=TD.departmentID
where 1 = 1
<cfif isdefined('form.fname') AND len(form.fname) gt 0 >
AND TE.FirstName Like '#Form.fname#%'
</cfif>
<cfif isdefined('form.lname') AND len(form.lname) gt 0>
and TE.LastName Like '#Form.lname#%'
</cfif>
<cfif isdefined('form.dept') AND form.dept neq 0>
and TD.DeparmentName='#form.dept#'
</cfif>
<cfif isdefined('form.salary') AND ListLen(Form.salary,'-') EQ 2>
and TE.salary between #ListGetAt(Form.salary,1,'-')# AND #ListGetAt(Form.salary,2,'-')#
</cfif>
<cfif isdefined('form.hidetxt') AND Len(form.hidetxt) GT 0>
order by #form.hidetxt#
</cfif>
</cfquery>
<cfdump var="#result#">
<cfoutput>
<cfquery dbtype="query" name="detail">
select top 2 *
FROM result
WHERE 1=1
<cfif isdefined('form.hidetxt') AND Len(form.hidetxt) GT 0>
order by #form.hidetxt#
</cfif>
</cfquery>
</cfoutput>
<cfdump var="#detail#">
Error in top 2 . but this query is working in database . what mistake i did in this . in second query error occured in "select top 2 * ". what to write for that
TOP is not part of the SQL implementation of QoQ. Use the maxrows attribute on the <cfquery> tag.

Using substring to evaluate table value one with leading zeros

I am not having any luck making this work and I am not sure what I am missing. I am new to coldfusion and SQL and still learning.
I have a binding that I am doing within a form. After a user selects a service type in needs to generate a name which is located in another table. The problem I have is that the service type is using a service number which is located in both tables. However in one table the creator added leading zeros to the number. For example one table will have 205 and the other table will have 0000205 I need to compare these to get the name value I want. Here is the coding I have so far. This is using coldfusion and java.
cfc file called servicetype2
<cffunction name="getServiceType2" access="remote" returnType="array">
<cfargument name="CATG_NAME" type="string" required="true">
<cfset var data="">
<cfset var result=ArrayNew(2)>
<cfset var i=0>
<cfquery name="getServiceType2" datasource="SOME DATABASE">
select 1 AS SortBy, '' AS SRTY_NBR, '' AS SRTY_NAME
from SOME TABLE
UNION
select distinct 2 AS SortBy, SRTY_NBR, SRTY_NAME
from SOME TABLE
where CATG_NAME = <cfqueryparam value="#ARGUMENTS.CATG_NAME#" cfsqltype="cf_sql_varchar"> AND EVLN_REQD_FLAG IS NOT NULL
order by SortBy
</cfquery>
<cfloop index="i" from="1" to="#getServiceType2.recordcount#">
<cfset result[i][1]=getServiceType2.SRTY_NAME[i]>
<cfset result[i][2]=getServiceType2.SRTY_NAME[i]>
</cfloop>
<cfreturn result>
</cffunction>
//Table 2
<cffunction name="getUnion" access="remote" returnType="array">
<cfargument name="SRTY_NBR" type="string" required="true">
<cfset var result=ArrayNew(1)>
<cfquery name="union_rq" datasource="SOME DATABASE">
select UNI_NAME, substring(SRTY_NBR, patindex('%[^0]%',SRTY_NBR),10)
from SOME TABLE
where substring(SRTY_NBR, patindex('%[^0]%',SRTY_NBR),10)
= <cfqueryparam value="#ARGUMENTS.SRTY_NBR#" cfsqltype="cf_sql_varchar">
</cfquery>
<cfset result[1]=union_rq.UNI_NAME>
<cfreturn result>
</cffunction>
The code which is in my form is:
<tr id="serv_ty2" style="display: inline;">
<td></td>
<td>Select Service:
<cfselect name="service_type"
bind="cfc:servicetype2.getServiceType2({catdesc})"
bindonload="false"/></td>
</tr>
<tr id="union" style="display: inline;">
<td></td>
<td>Union Attached:
<cfinput name="uni_name"
bind="cfc:servicetype2.getUnion({service_type})"
bindonload="false"
/></td>
</tr>
Again the binding is working fine but I can not get the name to come up and I am sure it has to do with my SQL statement comparing the 205 to 0000205. Any advice on how you would make the sql statement work would be great. If you notice any other errors with the binding that would be great as well.
Thank you in advance for any advice you can provide.
You can use NumberFormat() in your Query
WHERE srty_nbr IN (<cfqueryparam
value="#ARGUMENTS.SRTY_NBR#,#NumberFormat(ARGUMENTS.SRTY_NBR,'0000000')#"
cfsqltype="cf_sql_varchar" list="true">
#NumberFormat(ARGUMENTS.SRTY_NBR,'0000000')# will make sure every number has 7 digits with leading zeros.
Your best bet is casting the value on SQL level. This is easily done by altering the selection of the column to: SELECT ..., CAST(SRTY_NBR AS UNSIGNED) ... This will truncate leading zeros.

INSERT query error: Implicit conversion from data type varchar to varbinary is not allowed. Use the CONVERT function to run this query.

I am trying to run an insert query, but I am getting the error below. How can I pass the values into my insert statement? The value is coming from an array and the [cNotes] column type is varchar NULL.
Thanks in advance.
Error:
Error Executing Database Query.
[Macromedia][SQLServer JDBC Driver][SQLServer]Implicit conversion from data type varchar to varbinary is not allowed. Use the CONVERT function to run this query.
The error occurred in C:\Inetpub\wwwroot\Components\Assessment.cfc: line 510
Called from C:\Inetpub\wwwroot\Components\Assessment.cfc: line 440
508 : ,NULL
509 : </cfif>
510 : ,'#arguments.notes#')
511 : </cfquery>
512 : </cffunction>
--------------------------------------------------------------------------------
SQL INSERT INTO AssessmentToolDetail(iAssessmentToolMaster_ID ,iServiceList_ID ,cRowStartUser_ID ,Service_text ,cNotes) Values(251069 ,3592 ,NULL ,'y ' ,'')
DATASOURCE TIPS4
VENDORERRORCODE 257
SQLSTATE HY000 '
CFC function:
<cffunction name="AddService" access="public" returntype="void" output="false">
<cfargument name="ServiceList" type="Components.ServiceList" required="true">
<cfargument name="notes" type="string" required="false" default="">
<cfargument name="serviceText" type="string" required="false" default="">
<cfquery name="AddServiceListQuery" datasource="#variables.dsn#">
INSERT INTO AssessmentToolDetail (
iAssessmentToolMaster_ID
, iServiceList_ID
, cRowStartUser_ID
, Service_text
, cNotes )
VALUES (
#variables.id#
,#ServiceList.GetId()#
<cfif variables.rowStartUserId neq "">
, '#variables.rowStartUserId#'
<cfelse>
, NULL
</cfif>
<cfif ListFirst( Arguments.serviceText,'_' ) EQ ServiceList.GetId() >
, '#Left(ListLast( Arguments.serviceText,'_'),1)# '
<cfelse>
, NULL
</cfif>
, '#arguments.notes#'
)
</cfquery>
</cffunction>
The error is saying that you're trying to insert a string into a column with a binary storage format, and it can't make the conversion implicitly.
Check that the cNotes column in the AssessmentToolDetail table has a datatype of varchar(n) or nvarchar(n) and not varbinary(n).