When using databases, you need to ensure data consistency and prevent race conditions - especially in collaborative or high-traffic applications. Now, Data Connect has atomic operations that let you manage counters, lists, and other data structures:
inc
anddec
to increment and decrement a field by the specified amount forInt
,Int64
,Float
,Date
, andTimestamp
data typesadd
andremove
to add and remove items positionally to list types, except Vector listsappend
andprepend
to add to the end and beginning to list types, except Vector lists This blog post will go through each one with an example.
INC and DEC operators
Let’s say you’re building a banking app, and you need to increment and decrement the balance amounts in an account.
inc
increments the field by the specified amount:
mutation BankUpdateAmount($amount: Int!) {
bank_update: {
data: {
balance_update: {
inc: $amount
}
}
}
}
dec
decrements the field by the specified amount:
mutation BankUpdateAmount($amount: Int!) {
bank_update: {
data: {
balance_update: {
dec: $amount
}
}
}
}
List operators
Now, let’s say you’re creating a todo list app, and a user needs to add and remove items to the to-do list.
prepend
adds an item to the start of a list:
mutation AddItemToStart($id: UUID!, $item: String!) {
todoList_update: {
id: $id,
data: {
items_update: { prepend: [$item] }
}
}
}
append
adds an item to the end of a list:
mutation AddItemToEnd($id: UUID!, $item: String!) {
todoList_update: {
id: $id,
data: {
items_update: { append: [$item] }
}
}
}
add
adds to the end of the list only if the item doesn’t already exist in the list. To differentiate add
from append
, append
will always add to the list, even if the item already exists in the list:
mutation AddItemIfDNE($id: UUID!, $item: String!) {
todoList_update: {
id: $id,
data: {
items_update: {add: [$string]}
}
}
}
remove
removes an item from a list if the list contains the value. If there is more than one entry with the value, the list removes all of them:
mutation RemoveItem($id: UUID!, $item: String!) {
todoList_update: {
id: $id,
data: {
items_update: {remove: [$string]}
}
}
}
Try it out!
These new features and improvements are designed to unlock new use cases and make Data Connect a more capable database service for your apps. We’re excited to see what you build with it and these new features. Happy coding!