The Cloud Spanner NUMERIC
is an
exact numeric data type capable of representing an exact numeric value with a
precision of 38 and scale of 9. This page provides an overview of how NUMERIC
is represented in client libraries.
Representing NUMERIC in each client library language
To maintain the fidelity of NUMERIC
values, each Cloud Spanner client
library stores those values in an appropriate data type in the client library
language. The following table lists the data types to which NUMERIC
is mapped in
each supported language.
Language | Client library type |
---|---|
C++ | spanner::Numeric |
C# | SpannerNumeric |
Go | big.Rat |
Java | BigDecimal |
Node.js | Big |
PHP | custom Numeric |
Python | Decimal |
Ruby | BigDecimal |
Three client libraries, C++, C# and PHP have each implemented a custom type to
represent Cloud Spanner SQL's NUMERIC
type. All other libraries us an
existing type.
The C++ client library spanner::Numeric
object does not support arithmetic
operations. Instead, convert the contained number to the C++ object of choice.
For example, you can extract the number as a string, which would represent the
number at full fidelity and with no data loss. If, however, you know in advance
that number fits, for example, within the range of std:int64_t or double, then
you can access the value as that type.
Adding a NUMERIC column
The following sample shows how to add a NUMERIC
column to a table called Venues
using
the Cloud Spanner client libraries.
C++
C#
Go
Java
Node.js
PHP
Python
Ruby
Updating NUMERIC data
The following sample shows how update NUMERIC
data using the Cloud Spanner client libraries.
C++
C#
Go
Java
Node.js
PHP
Python
Ruby
Query NUMERIC data
The following sample shows how to query NUMERIC
data using the Cloud Spanner client libraries.
C++
C#
Go
Java
Node.js
PHP
Python
Ruby
NUMERIC
is supported in the JDBC driver using the Java BigDecimal type. For examples of how NUMERIC
is used, see the code samples in Using the open-source JDBC driver.
Handling NUMERIC when creating a client library or driver
The NUMERIC
type is encoded as a string in decimal or scientific notation
within a google.protobuf.Value proto. This proto is wrapped as either a
ResultSet, PartialResultSet, or a Mutation depending on whether
it is being read or written. ResultSetMetadata will use the NUMERIC
TypeCode to indicate that the corresponding value should be read as a NUMERIC
.
When working with NUMERIC in a client library or driver you create, observe the following guidance.
To read a
NUMERIC
from the ResultSet:Read the string_value from the google.protobuf.Value proto when TypeCode is
NUMERIC
Convert that string to the relevant type for the given language
To write a
NUMERIC
using Mutations, use the string representation as the string_value in the google.protobuf.Value proto when given the relevant type.