Category Archives: SQL

Postgresql Datatype mismatch default for column cannot be cast to type integer

When converting a table column from varchar to integer I ran into a problem.

[code lang=text]
SQLSTATE[42804]: Datatype mismatch: 7 ERROR: default for column "column_name" cannot be cast to type integer
[/code]

The solution I could find on (Stackoverflow)[http://stackoverflow.com/questions/13170570/change-type-of-varchar-field-to-integer-cannot-be-cast-automatically-to-type-i] was not working:

[code lang=sql]
ALTER TABLE the_table ALTER COLUMN col_name TYPE integer USING (col_name::integer);
[/code]

Looking closer at the error I realised – as is often the case – the error was indicating exactly what the problem was. The default of the column could not be converted.

Not knowing how to convert the default, I simply changed it to something that could be converted:

[code lang=sql]
ALTER TABLE the_table ALTER COLUMN col_name SET DEFAULT 0;
[/code]

Despite it being a varchar column, the integer value 0 was accepted. After which the earlier CAST worked.

PostgreSQL functions and triggers

It is desirable to avoid using database functions. They are black boxes which gift only night horrors to unwary developers. A system is difficult to understand, maintain and debug when chunks of it lurk unseen in the DB.

Despite this – for certain features – using them does make sense. Provided the database function’s code is source controlled and huge lumps of comments referring to both the location and function of said code is spread evenly throughout the associated application code.

For example, in order to bill Ekaya agents accurately we needed a log of show house status changes, from upcoming to active to past or cancelled. Most of these changes were implemented in sweeping SQL statements that, while efficient at their own task, made it difficult to track individual changes.

Continue reading PostgreSQL functions and triggers

Postgresql date formatting

Preamble

Formatting of data should only occur in the final steps of output. Until that point, and as a rule, internally data should remain in a base format that can easily be converted into many others – without being converted into another more basic format first.

For example Unix timestamp for dates or a floating point number for money. Both can readily be converted into more expressive formats without writing code to first parse or disassemble the initial format.

However in a situation where the flow is very specific and unlikely to ever be used to generate a different output it is permissible, even desirable, to generate data in the format it will be finally outputted.

Continue reading Postgresql date formatting