[odb-users] Getting the datatype length

Boris Kolpackov boris at codesynthesis.com
Thu Dec 12 08:29:35 EST 2024


Javier Gutierrez <javier.gutierrez at web.de> writes:

> I am getting the error "Data too long for column" which of course means I
> have to shorten the data to the column length before persisting.
> Now, let's say I define my column this way:
> 
> #pragma db value_type("VARCHAR(255)")
> 
> Is it possible to somehow retrieve the datatype length from the definition?
> (I'd like to prevent hardcoding all these lengths in my code.)

No, I can't think of any way to get to this information. In fact, this
information (the 255 limit) is not even present in the generated code.


> Or to force ODB to truncate the values to that length?

There is no out-of-the box support for this but you could define
a custom string type and provide a mapping for it that would
truncate the string before persisting. Something along these lines:

#pragma db value type("VARCHAR(255)")
class varchar255: public std::string
{
public:
  using string::string;
};

#pragma db map type(varchar255) as(std::string) \
  to((?).substr (0, 255)) \
  from(varchar255 (?))

(You could also change the default std::string mapping to truncate
if it's always mapped to VARCHAR(255) in your application. For that
you would need to specialize odb::value_trait<std::string>.)



More information about the odb-users mailing list