You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Let's make sure we don't add the same counter name twice.
94
+
95
+
```rust
96
+
let_response=db
97
+
.query("DEFINE INDEX counter_name ON TABLE counter COLUMNS name UNIQUE")
98
+
.await?;
99
+
```
100
+
101
+
### Too many arguments
102
+
103
+
Tell the user how to use the tool if there is more than one value on the command line. (args includes the name of the executable file so we need to compare with 2 here).
104
+
105
+
```rust
106
+
if2<args.len() {
107
+
eprintln!("Usage: {} NAME to count NAME", args[0]);
108
+
eprintln!(" {} to list all the counters", args[0]);
109
+
std::process::exit(1);
110
+
}
111
+
```
112
+
113
+
### Increment the counter
114
+
115
+
I guess this is the heart of the progam where we fetch the current value of the counter using a `SELECT` statement and then
116
+
update the value in the database. We use `INSERT` here as it can either `CREATE` a new record or `UPDATE` and existing one.
117
+
118
+
```rust
119
+
if2==args.len() {
120
+
letname=&args[1];
121
+
letmutcount=0;
122
+
123
+
letmutentries=db
124
+
.query("SELECT name, count FROM counter WHERE name = $name")
125
+
.bind(("name", name))
126
+
.await?;
127
+
letentries:Vec<Entry> =entries.take(0)?;
128
+
ifletSome(entry) =entries.into_iter().next() {
129
+
count=entry.count;
130
+
}
131
+
132
+
count+=1;
133
+
println!("{}", count);
134
+
135
+
letresponse=db
136
+
.query("INSERT INTO counter (name, count) VALUES ($name, $count) ON DUPLICATE KEY UPDATE count=$count")
0 commit comments