Serialization Error

Probably more a Python question than an Anvil one (though maybe not) -

The result array from pymysql below is showing the error underneath that.
pymysql returns that “Decimal” when I do aggregation functions (eg SUM) in my SQL. If I don’t use them then the results are fine (they don’t have Decimal in there).

My question is - how can i get that resulting array into a format that can be returned to the calling function?

[{‘country’: ‘Eritrea MISSING’, ‘calls’: Decimal(‘21’), ‘duration’: Decimal(‘2’), ‘answered’: Decimal(‘4’)}, {‘country’: ‘Mali MISSING’, ‘calls’: Decimal(‘11’), ‘duration’: Decimal(‘0’), ‘answered’: Decimal(‘0’)}, {‘country’: ‘Nigeria MISSING’, ‘calls’: Decimal(‘7’), ‘duration’: Decimal(‘0’), ‘answered’: Decimal(‘0’)}, {‘country’: ‘UAE MISSING’, ‘calls’: Decimal(‘1’), ‘duration’: Decimal(‘0’), ‘answered’: Decimal(‘0’)}]

AnvilSerializationError: Cannot serialize return value from function. You can only pass strings, numbers, arrays, lists, LiveObjects and Media to or from server functions

Context:
I recognize Decimal. In my experience, Decimal('21') is a call to a function, defined in standard library module decimal, that constructs an object of class Decimal. When such a value is converted back to text, for display, this is how it appears.

Objects of this class perform their arithmetic in base 10, and can have more than the usual number of significant digits.

Hypothesis:

  1. mysql is using its own extended-precision (decimal) arithmetic. (Many database servers do.)
  2. pymysql is receiving SUM's result in mysql’s extended format
  3. In order to preserve the full precision of that result, in its worst case, pymysql is storing it in values of class Decimal.

Suggestions:

  1. If you have access to the SQL code containing the SUM call, then, in that code, cast SUM's return value to a more suitable type. (This applies also to any other server-side arithmetic result.) pymysql should then receive that type of value, instead.
  2. If you don’t have that access, then iterate through the list, converting each Decimal value to a suitable type (int or float). Module decimal has all the conversion functions you’ll need.

Either approach should net you a list that can be transmitted from server to client (browser).

1 Like

Thanks for that. In all my SQL days I’ve never seen that before, but then I’ve never used Python to access a DB before.

Will try the above and report back.

EDIT - converting them to float worked just fine. I was definitely having a wood/trees day on Wednesday…