Data types- Developing guide

Data types

ColdFusion is often referred to as typeless because you do not assign types to variables and ColdFusion does not associate a type with the variable name. However, the data that a variable represents does have a type, and the data type affects how ColdFusion evaluates an expression or function argument. ColdFusion can automatically convert many data types into others when it evaluates expressions. For simple data, such as numbers and strings, the data type is unimportant until the variable is used in an expression or as a function argument.
ColdFusion variable data belongs to one of the following type categories:

  • Simple One value. Can use directly in ColdFusion expressions. Include numbers, strings, Boolean values, and date-time values.
  • Binary Raw data, such as the contents of a GIF file or an executable program file.
  • Complex ** A container for data. Generally represent more than one value. ColdFusion built-in complex data types include arrays, structures, queries, and XML document objects. You cannot use a complex variable, such as an array, directly in a ColdFusion expression, but you can use simple data type elements of a complex variable in an expression. For example, with a one-dimensional array of numbers called myArray, you cannot use the expression myArray * 5. However, you could use an expression myArray3 * 5 to multiply the third element in the array by five.
  • Objects Complex constructs. Often encapsulate both data and functional operations. The following table lists the types of objects that ColdFusion can use, and identifies the chapters that describe how to use them:

Data type notes

Although ColdFusion variables do not have types, it is often convenient to use "variable type" as a shorthand for the type of data that the variable represents.
ColdFusion can validate the type of data contained in form fields and query parameters. For more information, see Testing for a variables existence in the Ensuring variable existence and Using cfqueryparam in the Enhancing security with cfqueryparam. The cfdump tag displays the entire contents of a variable, including ColdFusion complex data structures. It is an excellent tool for debugging complex data and the code that handles it.ColdFusion provides the following functions for identifying the data type of a variable:

Note:

ColdFusion (2016 release) and earlier:

ColdFusion does not use a null data type. However, if ColdFusion receives a null value from an external source such as a database, a Java object, or some other mechanism, it maintains the null value until you use it as a simple value. At that time, ColdFusion converts the null to an empty string ( "" ). Also, you can use the JavaCast function in a call to a Java object to convert a ColdFusion empty string to a Java null.

NULL variable support

In ColdFusion (2016 release) and earlier versions, CFML did not support NULL values. ColdFusion converts a null value to an empty string. In operations such as SerializeJSON and CFquery, Null values are automatically converted into empty strings, a non-null value.

While the code below runs as expected:

 

<cfscript>
 myvar=""; // empty string
 writeOutput(isNULL(myvar)); // returns NO
</cfscript>

The code below throws an exception:

 

<cfscript>
 myvar=NULL; // value is NULL
 writeOutput(isNULL(myvar)); // returns Variable NULL is undefined
</cfscript>

Although, you could always assign NULL to a variable through JavaCast function. For example,

 

<cfscript>
 myvar=JavaCast("null",0); 
 writeOutput(isNULL(myvar)); // returns TRUE
</cfscript>

The 2018 release of ColdFusion supports Null values. Null support is turned off by default. To enable Null support, follow the following steps:

  1. Enable NULL support in the ColdFusion Administrator for all global CF applications. In Server Settings > Settings, select the check-box Enable Null Support.

    After the change, the code below works as expected:

    <cfscript>
      myvar=NULL;
      writeOutput(isNull(myvar)); // returns TRUE
    </cfscript>
    
  2. You can enable Null support at the application level. There is a new variable, enableNULLSupport, which you can use to add NULL support in your project.

    For example, the code below adds NULL support in Application.cfc:

    component{
     this.enableNULLSupport=true;
    }
    

Null strings are different from null values. When you dump a null value using either writeDump or <cfdump>, the null value appears as [null]. For example,

For example, with the enableNULLSupport flag set to true, create a query as shown below, with null values and null strings.

Note:

Note:

You can find the CFFiddle demo of this function and other spreadsheet functions as part of a project that is shared with you.

Click the button below to launch CFFiddle.

To copy the project in your workspace in CFFiddle, follow the steps below:

  1. Log in with your Gmail or Facebook credentials.
  2. Navigate to the project in the left pane.
  3. Once you make some changes in any cfm in the project, a pop up displays asking you to save the project.
  4. Give the project a suitable name and click Save.
<cfscript>
 myquery=querynew("id,name","integer,varchar",[[null,"hello"],[1,"null"],[null,"null"]]);
 writedump(myquery);
 writedump(format="text",var=#myquery#);
</cfscript>

When you dump the values, you can see that null values are represented as [null].

Null values
Null values

Note:

NULL is a reserved keyword. For example, null = "my new null value" is invalid.

You cannot create variables named null.

When NULL support is turned on:

  • The isNull function checks for valid instances of the NULL value. The previous behavior was to consider an undefined variable as NULL.
  • The isDefined function on variables that contain null value now return TRUE. The previous behavior was to return false.
  • Null values cannot be output with <cfoutput> or writeOutput( ), since the value is not of importance to the person viewing the webpage.
  • Undefined elements within an array will now be automatically set to NULL. These would appear as [Undefined Array Element] in previous versions.

Data type preservation

ColdFusion is typeless and does not evaluate or preserve the type information at the time of code generation. At runtime, ColdFusion tries its best to infer the datatype, which may cause an unexpected behavior in some cases. For example, at the time of JSON serialization, ColdFusion attempts at converting a string to a number, if the number is given in double quotes. If the attempt is successful, then the given data is treated as number irrespective of whether you wanted it to be a number or not.

For example, in the previous version of ColdFusion, if the data type of column was not defined, CF used to serialize everything as a string. However, with the data type preservation functionality we infer the data type while serializing the data even though the data type was not defined. In the snippet below:

 

<cfscript> 
 myQuery = queryNew("id,name,ctype","", 
  [ 
  {id=1,name="1",ctype=true}, 
  {id=2,name="Two",ctype=false}, 
  {id=3,name="3",ctype="true"},
  {id="4",name="4",ctype="false"}
  ]); 
 writeOutput ( SerializeJSON(myQuery) );
</cfscript>

New output:

{"COLUMNS":["ID","NAME","CTYPE"],"DATA":[[1,"1",true],[2,"Two",false],[3,"3","true"],["4","4","false"]]}

Old output:

{"COLUMNS":["ID","NAME","CTYPE"],"DATA":[["1","1","true"],["2","Two","false"],["3","3","true"],["4","4","false"]]}

The 2018 release of ColdFusion infers the data type of a variable at compile type. This release has enabled this feature by default. However, these is a new flag introduced to disable this feature and fallback on the previous behavior. You can add this flag to the jvm.config file:

-Dcoldfusion.literal.preservetype=”false/true”

For the flag to work, ensure the following:

  • Restart ColdFusion after enabling/disabling this flag
  • Remove all class files from the <cf_install_root>/<instance_name>/wwwroot/WEB-INF/cfclasses or re-compile the CFM template

There are a few known issues while interacting with the external systems like SharePoint, dotnet, web services, etc. For more information, see the Known Issues document.

With data type preservation, the strings "yes" and "no" will remain as yes or no, not boolean true or false.

Numbers

ColdFusion supports integers and real numbers. You can intermix integers and real numbers in expressions; for example, 1.2 + 3 evaluates to 4.2.

Integers

ColdFusion supports integers between -2,147,483,648 and 2,147,483,647 (32-bit signed integers). You can assign a value outside this range to a variable, but ColdFusion initially stores the number as a string. If you use it in an arithmetic expression, ColdFusion converts it into a floating-point value, preserving its value, but losing precision as the following example shows:

 

<cfscript>
mybignum = 12345678901234567890;
mybignumtimes10=(mybignum * 10);
writeOutput("mybignum is: #mybignum#" & "<br>");
writeOutput("mybignumtimes10 is: #mybignumtimes10#");
</cfscript>

This example generates the following output:

mybignum is: 12345678901234567890
mybignumtimes10 is: 1.23456789012E+020

Real numbers

Real numbers, numbers with a decimal part, are also known as floating point numbers. ColdFusion real numbers can range from approximately -10300 to approximately 10300. A real number can have up to 12 significant digits. As with integers, you can assign a variable a value with more digits, but the data is stored as a string. The string is converted to a real number, and can lose precision, when you use it in an arithmetic expression.
You can represent real numbers in scientific notation. This format is _x_E_y_, where x is a positive or negative real number in the range 1.0 (inclusive) to 10 (exclusive), and y is an integer. The value of a number in scientific notation is x times 10y. For example, 4.0E^2^ is 4.0 times 10^2^, which equals 400. Similarly, 2.5E^-2^ is 2.5 times 10^-2^, which equals 0.025. Scientific notation is useful for writing very large and very small numbers.

BigDecimal numbers

ColdFusion does not have a special BigDecimal data type for arbitrary length decimal numbers such as 1234567890987564.234678503059281. Instead, it represents such numbers as strings. ColdFusion does, however, have a PrecisionEvaluate function that can take an arithmetic expression that uses BigDecimal values, calculate the expression, and return a string with the resulting BigDecimal value. For more information, see PrecisionEvaluate in the CFML Reference.

Strings

In ColdFusion, text values are stored in strings. You specify strings by enclosing them in either single- or double-quotation marks. For example, the following two strings are equivalent:
"This is a string"
'This is a string'
You can write an empty string in the following ways:

  • "" (a pair of double-quotation marks with nothing in between)
  • '' (a pair of single-quotation marks with nothing in between)
    Strings can be any length, limited by the amount of available memory on the ColdFusion server. However, the default size limit for long text retrieval (CLOB) is 64K. The ColdFusion Administrator lets you increase the limit for database string transfers, but doing so can reduce server performance. To change the limit, select the Enable retrieval of long text option on the Advanced Settings page for the data source.

Escaping quotation marks and number signs

To include a single-quotation character in a string that is single-quoted, use two single-quotation marks (known as escaping the single-quotation mark). The following example uses escaped single-quotation marks:

writeOutput("#mystring#");

To include a double-quotation mark in a double-quoted string, use two double-quotation marks (known as escaping the double-quotation mark). The following example uses escaped double-quotation marks:

writeOutput("#mystring#");

Because strings can be in either double-quotation marks or single-quotation marks, both of the preceding examples display the same text:
This is a single-quotation mark: ' This is a double-quotation mark: "
To insert a number sign (#) in a string, you must escape the number sign, as follows:

"This is a number sign ##"

Lists

ColdFusion includes functions that operate on lists, but it does not have a list data type. In ColdFusion, a list is just a string that consists of multiple entries separated by delimiter characters. 
The default delimiter for lists is the comma. If you use any other character to separate list elements, you must specify the delimiter in the list function. You can also specify multiple delimiter characters. For example, you can tell ColdFusion to interpret a comma or a semicolon as a delimiter, as the following example shows:

writeOutput("List length using ; and , as delimiters: #listlen(Mylist, "";,"")#
List length using only , as a delimiter: #listlen(Mylist)#");

This example displays the following output: 

List length using ; and , as delimiters: 5
List length using only , as a delimiter: 3
Each delimiter must be a single character. For example, you cannot tell ColdFusion to require two hyphens in a row as a delimiter. 
If a list has two delimiters in a row, ColdFusion ignores the empty element. For example, if MyList is "1,2,,3,,4,,,5" and the delimiter is the comma, the list has five elements, and list functions treat it the same as "1,2,3,4,5".

Boolean values

Boolean value represents whether something is true or false. ColdFusion has two special constants True and False to represent these values. For example, the Boolean expression 1 IS 1 evaluates to True. The expression "Monkey" CONTAINS "Money" evaluates to False.
You can use Boolean constants directly in expressions, as in the following example:

UserHasBeenHere = True;

In Boolean expressions, True, nonzero numbers, and the strings "Yes", "1", "True" are equivalent; and False, 0, and the strings "No", "0", and "False" are equivalent.

Boolean evaluation is not case sensitive. For example, True, TRUE, and true are equivalent.

Date-Time values

ColdFusion can perform operations on date and time values. Date-time values identify a date and time in the range 100 AD to 9999 AD. Although you can specify just a date or a time, ColdFusion uses one data type representation, called a date-time object, for date, time, and date and time values.
ColdFusion provides many functions to create and manipulate date-time values and to return all or part of the value in several different formats. 
You can enter date and time values directly in a cfset tag with a constant, as follows:

myDate = "October 30, 2001";

When you do this, ColdFusion stores the information as a string. If you use a date-time function, ColdFusion stores the value as a date-time object, which is a separate simple data type. When possible, use date-time functions such as CreateDate and CreateTime to specify dates and times, because these functions can prevent you from specifying the date or time in an invalid format and they create a date-time object immediately.

Date and time formats

You can directly enter a date, time, or date and time, using standard U.S. date formats. ColdFusion processes the two-digit-year values 0 to 29 as twenty-first century dates; it processes the two-digit-year values 30 to 99 as twentieth century dates. Time values can include units down to seconds. The following table lists valid date and time formats:

To specify

Use these formats

Date

October 30, 2003Oct 30, 2003Oct. 30, 200310/30/032003-10-3010-30-2003

Time

02:34:122:34a2:34am02:34am2am

Date and Time

Any combination of valid date and time formats, such as these:October 30, 2003 02:34:12Oct 30, 2003 2:34aOct. 30, 2001 2:34am10/30/03 02:34am2003-10-30 2am10-30-2003 2am

Locale-specific dates and times

ColdFusion provides several functions that let you input and output dates and times (and numbers and currency values) in formats that are specific to the current locale. A locale identifies a language and locality, such as English (US) or French (Swiss). Use these functions to input or output dates and times in formats other than the U.S. standard formats. (Use the SetLocale function to specify the locale.) The following example shows how to do this:

writeOutput("#LSDateFormat(Now(), ""ddd, dd mmmm, yyyy"")#");

This example outputs a line like the following:

mar., 03 juin, 2003 
For more information on international functions, see Developing Globalized Applications and the CFML Reference.

How ColdFusion stores dates and times

ColdFusion stores and manipulates dates and times as date-time objects. Date-time objects store data on a timeline as real numbers. This storage method increases processing efficiency and directly mimics the method used by many database systems. In date-time objects, one day is equal to the difference between two successive integers. The time portion of the date-and-time value is stored in the fractional part of the real number. The value 0 represents 12:00 AM 12/30/1899.
Although you can use arithmetic operations to manipulate date-and-time values directly, this method can result in code that is difficult to understand and maintain. Use the ColdFusion date-time manipulation functions instead. For information on these functions, see the CFML Reference.

Binary data type and binary encoding

Binary data (also referred to as a binary object) is raw data, such as the contents of a GIF file or an executable program file. You do not normally use binary data directly, but you can use the cffile tag to read a binary file into a variable, typically for conversion to a string binary encoding before transmitting the file using e-mail.
A string binary encoding represents a binary value in a string format that can be transmitted over the web. ColdFusion supports three binary encoding formats:

Encoding

Format

Base64

Encodes the binary data in the lowest six bits of each byte. It ensures that binary data and non-ANSI character data can be transmitted using e-mail without corruption. The Base64 algorithm is specified by IETF RFC 2045, atwww.ietf.org/rfc/rfc2045.txt.

Hex

Uses two characters in the range 0-9 and A-F represent the hexadecimal value of each byte; for example, 3A.

UU

Uses the UNIX  UUencode  algorithm to convert the data.

ColdFusion provides the following functions that convert among string data, binary data, and string encoded binary data:

Function

Description

Converts a string that contains encoded binary data to a binary object.

Converts binary data to an encoded string.

Converts a string to binary data in a specified character encoding.

Converts a binary object to a string in a specified character encoding.

Converts string and binary data to Base64 encoded data.

Converts Base64 encoded data to binary data. The BinaryDecode function provides a superset of the ToBase64functionality.

Converts most simple data types to string data. It can convert numbers, date-time objects, and Boolean values. (It converts date-time objects to ODBC timestamp strings.) Adobe recommends that you use  the CharsetEncode  function to convert binary data to a string in new applications.

Complex data types

Arrays, structures, and queries are ColdFusion built-in complex data types. Structures and queries are sometimes referred to as objects, because they are containers for data, not individual data values.
For details on using arrays and structures, see Using Arrays and Structures.

Arrays

Arrays are a way of storing multiple values in a table-like format that can have one or more dimensions. You create arrays using a function or an assignment statement:

  • The ColdFusion ArrayNewfunction creates an array and specifies its initial dimensions. For example, the following line creates an empty two-dimensional array:

myarray=ArrayNew(2);
  • A direct assignment creates an array and populates an array element. For example, the following line creates a two-dimensional array and sets the value of row 1 column 2 to the current date.

myarray[1][2]=Now();

You reference elements using numeric indexes, with one index for each dimension, as shown in the preceding example.

You can create arrays with up to three dimensions directly. However, there is no limit on array size or maximum dimension. To create arrays with more than three dimensions, create arrays of arrays.
After you create an array, you can use functions or direct references to manipulate its contents.
When you assign an existing array to a new variable, ColdFusion creates a new array and copies the old array's contents to the new array. The following example creates a copy of the original array:

<cfset newArray=myArray>

For more information on using arrays, see Using Arrays and Structures.

Structures

ColdFusion structures consist of key-value pairs, where the keys are text strings and the values can be any ColdFusion data type, including other structures. Structures let you build a collection of related variables that are grouped under a single name. To create a structure, use the ColdFusion StructNew function. For example, the following line creates a new, empty, structure called depts:

<cfset depts=StructNew()>

You can also create a structure by assigning a value in the structure. For example, the following line creates a new structure called MyStruct with a key named MyValue, equal to 2:

<cfset MyStruct.MyValue=2>

In ColdFusion versions through ColdFusion 7, this line created a Variables scope variable named "MyStruct.MyValue" with the value 2.

After you create a structure, you can use functions or direct references to manipulate its contents, including adding key-value pairs.
You can use either of the following methods to reference elements stored in a structure:

  • StructureName\.KeyName
  • StructureName["KeyName"]
    The following examples show these methods:
depts["John"]="Sales"

When you assign an existing structure to a new variable, ColdFusion does not create a new structure. Instead, the new variable accesses the same data (location) in memory as the original structure variable. In other words, both variables are references to the same object. 

For example, the following line creates a new variable, myStructure2, that is a reference to the same structure as the myStructure variable:

<cfset myStructure2=myStructure>

When you change the contents of myStructure2, you also change the contents of myStructure. To copy the contents of a structure, use the ColdFusion Duplicate function, which copies the contents of structures and other complex data types.

Structure key names can be the names of complex data objects, including structures or arrays. This lets you create arbitrarily complex structures.
For more information on using structures, see Using Arrays and Structures.

Queries

query object, sometimes referred to as a query, query result, or recordset, is a complex ColdFusion data type that represents data in a set of named columns, like the columns of a database table. Many tags can return data as a query object, including the following:

  • cfquery
  • cfdirectory
  • cfhttp
  • cfldap
  • cfpop
  • cfprocresult
    In these tags, the name attribute specifies the query object's variable name. The QueryNew function also creates query objects.
    When you assign a query to a new variable, ColdFusion does not copy the query object. Instead, both names point to the same recordset data. For example, the following line creates a new variable, myQuery2, that references the same recordset as the myQuery variable:
<cfset myQuery2 = myQuery>

If you make changes to data in myQuery, myQuery2 also shows those changes.

You reference query columns by specifying the query name, a period, and the column name; for example:

myQuery.Dept_ID

When you reference query columns inside tags, such as cfoutput and cfloop, in which you specify the query name in a tag attribute, you do not have to specify the query name.

You can access query columns as if they are one-dimensional arrays. For example, the following line assigns the contents of the Employee column in the second row of the myQuery query to the variable myVar:

<cfset myVar = myQuery.Employee[2]>

You cannot use array notation to reference a row (of all columns) of a query. For example, myQuery2 does not reference the second row of the myQuery query object.

Working with structures and queries

Because structure variables and query variables are references to objects, the rules in the following sections apply to both types of data.

Multiple references to an object

When multiple variables reference a structure or query object, the object continues to exist as long as at least one reference to the object exists. The following example shows how this works:

 

<cfscript>
depts = structnew();
newStructure=depts;
depts.John="Sales";
depts=0;
 writeOutput("#newStructure.John# #depts#");
</cfscript>

This example displays the following output:
Sales 0 
After the depts=0 declaration executes, the depts variable does not reference a structure; it is a simple variable with the value 0. However, the variable newStructure still refers to the original structure object.

Assigning objects to scopes

You can give a query or structure a different scope by assigning it to a new variable in the other scope. For example, the following line creates a server variable, Server.SScopeQuery, using the local myquery variable:

<cfset Server.SScopeQuery = myquery>

To clear the server scope query variable, reassign the query object, as follows:

<cfset Server.SScopeQuery = 0>

This line deletes the reference to the object from the server scope, but does not remove any other references that can exist.

Copying and duplicating objects

You can use the Duplicate function to make a true copy of a structure or query object. Changes to the copy do not affect the original.

Using a query column

When you are not inside a tag such as cfloopcfoutput, or cfmail that has a query attribute, you can treat a query column as an array. However, query column references do not always behave as you might expect. This section explains the behavior of references to query columns using the results of the following cfquery tag in its examples:

SELECT FirstName, LastName
FROM Employee
</cfquery>

To reference elements in a query column, use the row number as an array index. For example, both of the following lines display the word "ben":

<cfoutput> #myQuery.Firstname[1]# </cfoutput><br> 
<cfoutput> #myQuery["Firstname"][1]# </cfoutput><br>

ColdFusion behavior is less straightforward, however, when you use the query column references myQuery.Firstname and myQuery"Firstname" without using an array index. The two reference formats produce different results. 

If you reference myQuery.Firstname, ColdFusion automatically converts it to the first row in the column. For example, the following lines print the word "ben":

<cfoutput>#mycol#</cfoutput>

But the following lines display an error message:

<cfoutput>#mycol[1]#</cfoutput><br>

If you reference Query["Firstname"], ColdFusion does not automatically convert it to the first row of the column. For example, the following line results in an error message indicating that ColdFusion cannot convert a complex type to a simple value:

<cfoutput> #myQuery['Firstname']# </cfoutput><br>

Similarly, the following lines print the name "marjorie", the value of the second row in the column:

<cfoutput>#mycol[2]#</cfoutput><br>

However, when you make an assignment that requires a simple value, ColdFusion automatically converts the query column to the value of the first row. For example, the following lines display the name "ben" twice:

<cfoutput> #myQuery.Firstname# </cfoutput><br> 
<cfset myVar= myQuery['Firstname']> 
<cfoutput> #myVar# </cfoutput><br>

FUNCTION is a ColdFusion data type in ColdFusion 10

 

For example,

<cfscript>
public FUNCTIOn FUNCTION a()
{
return variables.b;
}
public FUNCTION b()
{
return "Hal";
}
writeoutput(a());
writedump(a().getMetadata());
writedump(a.getMetadata());
writedump(a.getMetadata());
</cfscript>

 Adobe

Get help faster and easier

New user?

Adobe MAX 2024

Adobe MAX
The Creativity Conference

Oct 14–16 Miami Beach and online

Adobe MAX

The Creativity Conference

Oct 14–16 Miami Beach and online

Adobe MAX 2024

Adobe MAX
The Creativity Conference

Oct 14–16 Miami Beach and online

Adobe MAX

The Creativity Conference

Oct 14–16 Miami Beach and online