DEV Community

Marcos Silva
Marcos Silva

Posted on

Simplifying Data Conversion with the toIntegerList() Function

Introduction

This is a short blog about the toIntegerList() function, we'll explore a function that takes a list of values and produces a new list containing only integer values.

About toIntegerList()

The toIntegerList() function is designed to efficiently convert values in a list to integers. It scans each element in the input list and attempts to convert it to an integer. If successful, the converted integer value is added to the new output list. However, if the conversion fails, the corresponding element in the output list is set to null.

Regression Tests

To improve the understanding, dive into the regression tests!

! -- toIntegerList()
! SELECT * FROM cypher('expr', $$
!     RETURN toIntegerList([1, 7.8, 9.0, '88'])
! $$) AS (toIntegerList agtype);
!  tointegerlist 
! ---------------
!  [1, 7, 9, 88]
! (1 row)
! 
! SELECT * FROM cypher('expr', $$
!     RETURN toIntegerList([4.2, '123', '8', 8])
! $$) AS (toIntegerList agtype);
!  tointegerlist  
! ----------------
!  [4, 123, 8, 8]
! (1 row)
! 
! SELECT * FROM cypher('expr', $$
!     RETURN toIntegerList(['41', '12', 2])
! $$) AS (toIntegerList agtype);
!  tointegerlist 
! ---------------
!  [41, 12, 2]
! (1 row)
! 
! SELECT * FROM cypher('expr', $$
!     RETURN toIntegerList([1, 2, 3, '10.2'])
! $$) AS (toIntegerList agtype);
!  tointegerlist 
! ---------------
!  [1, 2, 3, 10]
! (1 row)
! 
! SELECT * FROM cypher('expr', $$
!     RETURN toIntegerList([0000])
! $$) AS (toIntegerList agtype);
!  tointegerlist 
! ---------------
!  [0]
! (1 row)
! 
! -- should return null
! SELECT * FROM cypher('expr', $$
!     RETURN toIntegerList(["false_", 'asdsad', '123k1kdk1'])
! $$) AS (toIntegerList agtype);
!    tointegerlist    
! --------------------
!  [null, null, null]
! (1 row)
! 
! SELECT * FROM cypher('expr', $$
!     RETURN toIntegerList([null, ['A', 'B'], 'one'])
! $$) AS (toIntegerList agtype);
!    tointegerlist    
! --------------------
!  [null, null, null]
! (1 row)
! 
! -- should fail
! SELECT * FROM cypher('expr', $$
!     RETURN toIntegerList(123, '123')
! $$) AS (toIntegerList agtype);
! ERROR:  toIntegerList() argument must resolve to a list or null
! SELECT * FROM cypher('expr', $$
!     RETURN toIntegerList([12]12)
! $$) AS (toIntegerList agtype);
! ERROR:  syntax error at or near "12"
! LINE 2:     RETURN toIntegerList([12]12)
!                  
Enter fullscreen mode Exit fullscreen mode

Top comments (0)