release 1.200001
[dbsrgits/DBIx-Class-Manual-SQLHackers.git] / lib / DBIx / Class / Manual / SQLHackers / UPDATE.pod
CommitLineData
6c2a4396 1=head1 NAME
2
3DBIx::Class::Manual::SQLHackers::UPDATE - DBIx::Class for SQL Hackers - UPDATE
4
5=over
6
7=item L<Introduction|DBIx::Class::Manual::SQLHackers::Introduction>
8
9=item L<CREATE|DBIx::Class::Manual::SQLHackers::CREATE>
10
11=item L<INSERT|DBIx::Class::Manual::SQLHackers::INSERT>
12
13=item L<SELECT|DBIx::Class::Manual::SQLHackers::SELECT>
14
15=item UPDATE
16
17=item L<DELETE|DBIx::Class::Manual::SQLHackers::DELETE>
18
19=item L<BEGIN, COMMIT|DBIx::Class::Manual::SQLHackers::Transactions>
20
21=back
22
23=head1 UPDATEing data
24
abc32120 25=head2 Single row delayed update versus direct update
6c2a4396 26
abc32120 27Individual rows may be updated via their Result object in one of two
28ways. You can create an object representing an existing database table
1060e1bd 29row and hold it in your program's memory, passing it around from
abc32120 30function to function changing its values, before actually updating
31the contents into the database. This is a delayed update.
6c2a4396 32
33A direct update still involves fetching the existing row from the
34database, but instead of storing new column values in the Row object,
35the update method is called and passed the set of new values to store
36in the table.
37
38NOTE: Running a direct update on a row object that already has changed
1060e1bd 39values will B<also> apply those values to the database. If some values are
40changed both on the object and in the update method arguments, the
6c2a4396 41argument values take precedence.
42
43=head2 Updating a row in memory
44
1060e1bd 45To create a Row object for delayed update (or other manipulations), first fetch it from the database as described in L<Simple SELECT|DBIx::Class::Manual::SQLHackers::SELECT/Simple SELECT, one row via the primary key>.
6c2a4396 46
47=over
48
49=item 1. Create a Schema object representing the database you are working with:
50
51 my $schema = MyDatabase::Schema->connect('dbi:SQLite:my.db');
52
53=item 2. Call the B<find> method on the resultset for the L<ResultSource|DBIx::Class::ResultSource> you wish to update the contents of:
54
55 my $fred_user = $schema->resultset('User')->find({ id => 1 });
56
abc32120 57B<$fred_user>'s contents can now be changed using the accessor
6c2a4396 58methods created by B<add_columns>, back in
59L<CREATE|DBIx::Class::Manual::SQLHackers::CREATE>. These are generally named
60after the columns in the database, so to change fred's real name, use
61the B<realname> method.
62
63=item 3. Call the B<realname> accessor method on the $fred_user object:
64
65 $fred_user->realname("John Bloggs");
66
abc32120 67
68This value has not yet changed in the database, we can make the actual
1060e1bd 69update by calling B<update>:
6c2a4396 70
1060e1bd 71=item 4. Write the new value(s) into the database:
6c2a4396 72
73 $fred_user->update();
74
75=back
76
abc32120 77The update method will only actually send an UPDATE statement to the
78database if one or more of the columns have changed. The internal
79tracking of which columns have been changed can be queried using
80several methods. B<is_changed> returns true (or a list of changed
1060e1bd 81column names) if any column values have changed. B<is_column_changed>
abc32120 82will return true or false for the given column name argument. The
83previous values of the columns are not stored.
84
85
6c2a4396 86=head2 Update a single row with simple values
87
88 UPDATE users
89 SET username = 'new@email.address'
90 WHERE id = 1;
91
92To update an existing row, first B<find> it using the methods shown in L<DBIx::Class::Manual::SQLHackers::SELECT/Simple SELECT, one row via the primary key> or L<DBIx::Class::Manual::SQLHackers::SELECT/Simple SELECT, one row via a unique key>, for example:
93
94=over
95
96=item 1. Create a Schema object representing the database you are working with:
97
98 my $schema = MyDatabase::Schema->connect('dbi:SQLite:my.db');
99
100=item 2. Call the B<find> method on the resultset for the L<ResultSource|DBIx::Class::ResultSource> you wish to fetch data from:
101
102 my $fred_user = $schema->resultset('User')->find({ id => 1 });
103
1060e1bd 104The Row object has an B<update> method that will change the values on
105the object and send an UPDATE query to the database.
6c2a4396 106
107=item 3. Call the B<update> method, passing it a hashref of new data:
108
109 $fred_user->update({ username => 'new@email.address' });
110
111=back
112
1060e1bd 113See also: L</Single row direct update versus delayed update>.
bf3e7004 114
115=head2 Update a row or rows using a column calculation
116
117 -- Yet another pointless example
118 UPDATE users
119 SET username = username || '.uk'
120 WHERE id = 1;
121
122=over
123
124=item 1. Create a Schema object representing the database you are working with:
125
126 my $schema = MyDatabase::Schema->connect('dbi:SQLite:my.db');
127
128=item 2. Call the B<find> method on the resultset for the L<ResultSource|DBIx::Class::ResultSource> you wish to fetch data from:
129
130 my $fred_user = $schema->resultset('User')->find({ id => 1 });
131
132The Row object has an B<update> method that will change the values on
133the object, and send an UPDATE query to the database.
134
135=item 3. Call the B<update> method, passing it a hashref of new data:
136
137 $fred_user->update({ username => \['username || ?', [ {} => '.uk'] ] });
138
1060e1bd 139The C<\[ ... ]> syntax here is based on L<SQL::Abstract/Literal SQL with placeholders and bind values (subqueries)>, and adds some extra syntax for the "values" to be able to supply things like the exact SQL bind type and so on. This extra syntax will be documented in DBIx::Class soon.
bf3e7004 140
141=back
142
6c2a4396 143=head2 Update multiple rows with simple values
144
145 -- Warning, pointless example!
146 UPDATE users
147 SET dob = '2010-08-16'
148 WHERE realname LIKE 'jess%';
149
150To update a whole set of rows, or all of them, we first need to create a ResultSet object representing the query conditions that would be needed to select that same set of rows. We need to use B<search>, then we use the B<update> method on the ResultSet.
151
152=over
153
154=item 1. Create a Schema object representing the database you are working with:
155
156 my $schema = MyDatabase::Schema->connect('dbi:SQLite:my.db');
157
158=item 2. Call the B<search> method on the resultset for the L<ResultSource|DBIx::Class::ResultSource> you wish to fetch data from:
159
160 my $user_search = $schema->resultset('User')->search(
161 { realname => { like => 'jess%' } }
162 );
163
164=item 3. Call the B<update> method on the resultset to change the matching rows:
165
166 $user_search->update({ dob => '2010-08-16' });
167
168=back
169
6c2a4396 170=head2 Update or create a row
171
172 -- MySQL non-standardness (and another silly example)
173 INSERT INTO users ( ... )
174 VALUES ( ... )
175 ON DUPLICATE KEY UPDATE password = 'newpass';
176
177 -- OR:
178 BEGIN TRANSACTION;
179 SELECT id, username, dob, realname, password
180 FROM users
181 WHERE username = 'joebloggs';
182
183 UPDATE users
184 SET id = ?, username = ?, dob = ?, realname = ?, password = ?;
185 COMMIT;
186
2f41b1a9 187DBIx::Class does not yet produce the non-standard MySQL "ON DUPLICATE KEY
0e8be732 188UPDATE", instead it has a shortcut for combining B<find> and B<update>.
6c2a4396 189
190To avoid race conditions, this should be done in a transaction.
191
192=over
193
194=item 1. Create a Schema object representing the database you are working with:
195
196 my $schema = MyDatabase::Schema->connect('dbi:SQLite:my.db');
197
198=item 2. Call the B<txn_do> method on the schema object, passing it a coderef to execute inside the transaction:
0e8be732 199
6c2a4396 200 $schema->txn_do( sub {
201
202=item 3. Call the B<update_or_create> method on the resultset for the L<ResultSource|DBIx::Class::ResultSource> you wish to update data in:
203
1060e1bd 204 $schema->resultset('User')->update_or_create(
205 {
206 username => 'joebloggs',
207 dob => '2010-09-10',
208 realname = 'Joe Bloggs'
209 },
210 {
211 key => 'uniq_username'
212 }
213 );
6c2a4396 214
1060e1bd 215=item 4. Close off the coderef / transaction:
6c2a4396 216
217 } );
218
219=back
220
221A transaction is issued containing two statements, a B<SELECT> and then
222either an B<INSERT> or an B<UPDATE> depending on the results.
223
1060e1bd 224Do not use this method if you don't definitely have either the primary
225key or a unique index value available. The B<find> method used under
6c2a4396 226the hood will probably not do what you expect. In this case, manually
1060e1bd 227run a separate B<search> method call to check for existence, and then
6c2a4396 228call B<create>.
229