1

I would like to know how I can update a value stored in an array, in crate.io

  • I have a blog table - blog_tbl
  • A column, with data type array - tags
  • A id column
  • Inside the tags column I have - ["tag1","tag2","tag3"]

I would to know how I would go about changing 'tag1' to 'tag99'

I tried

update blog_tbl set tags['tag1'] = 'tag99' where id = '1';

Also how would I add one the the end? so making it -

["tag1","tag2","tag3","tag4"]

many thanks

Sam FarajpourGhamari
  • 14,601
  • 4
  • 52
  • 56

2 Answers2

1

Unfortunately it's not possible currently. Array elements can only be selected using the subscript notation (e.g. select tags[1] from blog_tbl;) but not updated. Maybe add a GH issue requesting that feature.

Sebastian Utz
  • 719
  • 3
  • 9
0

You can use the pattern found here: https://crate.io/docs/reference/sql/occ.html#optimistic-update

However, that requires you to perform the modification on client side. Pseudo code:

updated = False
while not updated:
    cursor.execute('SELECT array_field, "_version" FROM table WHERE id=1')
    row = cursor.fetchone()
    current_array_field = row[array_field]
    current_array_field.append('newtag')
    cursor.execute('UPDATE array_field = current_array_field WHERE id=1 AND "_version" = row[version]')
    if cursor.rowcount > 0:
        updated = True

This will make your update semi safe for concurrent updates of the same field.

pjotr_dolphin
  • 1,207
  • 9
  • 34