3 DBIx::Class::Manual::SQLHackers::UPDATE - DBIx::Class for SQL Hackers - UPDATE
7 =item L<Introduction|DBIx::Class::Manual::SQLHackers::Introduction>
9 =item L<CREATE|DBIx::Class::Manual::SQLHackers::CREATE>
11 =item L<INSERT|DBIx::Class::Manual::SQLHackers::INSERT>
13 =item L<SELECT|DBIx::Class::Manual::SQLHackers::SELECT>
17 =item L<DELETE|DBIx::Class::Manual::SQLHackers::DELETE>
19 =item L<BEGIN, COMMIT|DBIx::Class::Manual::SQLHackers::Transactions>
25 =head2 Single row delayed update versus direct update
27 Individual rows may be updated via their Result object in one of two
28 ways. You can create an object representing an existing database table
29 row and hold it in your programmes memory, passing it around from
30 function to function changing its values, before actually updating
31 the contents into the database. This is a delayed update.
33 A direct update still involves fetching the existing row from the
34 database, but instead of storing new column values in the Row object,
35 the update method is called and passed the set of new values to store
38 NOTE: Running a direct update on a row object that already has changed
39 values, will *also* apply those values to the database. If values are
40 changed both on the object, and in the update method arguments, the
41 argument values take precedence.
43 =head2 Updating a row in memory
45 To 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>.
49 =item 1. Create a Schema object representing the database you are working with:
51 my $schema = MyDatabase::Schema->connect('dbi:SQLite:my.db');
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:
55 my $fred_user = $schema->resultset('User')->find({ id => 1 });
57 B<$fred_user>'s contents can now be changed using the accessor
58 methods created by B<add_columns>, back in
59 L<CREATE|DBIx::Class::Manual::SQLHackers::CREATE>. These are generally named
60 after the columns in the database, so to change fred's real name, use
61 the B<realname> method.
63 =item 3. Call the B<realname> accessor method on the $fred_user object:
65 $fred_user->realname("John Bloggs");
68 This value has not yet changed in the database, we can make the actual
69 update by calling *update*:
71 =item 4. Update the set value(s) into the database:
77 The update method will only actually send an UPDATE statement to the
78 database if one or more of the columns have changed. The internal
79 tracking of which columns have been changed can be queried using
80 several methods. B<is_changed> returns true (or a list of changed
81 column names), if any column values have changed. B<is_column_changed>
82 will return true or false for the given column name argument. The
83 previous values of the columns are not stored.
86 =head2 Update a single row with simple values
89 SET username = 'new@email.address'
92 To 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:
96 =item 1. Create a Schema object representing the database you are working with:
98 my $schema = MyDatabase::Schema->connect('dbi:SQLite:my.db');
100 =item 2. Call the B<find> method on the resultset for the L<ResultSource|DBIx::Class::ResultSource> you wish to fetch data from:
102 my $fred_user = $schema->resultset('User')->find({ id => 1 });
104 The Row object has an B<update> method that will change the values on
105 the object, and send an UPDATE query to the database.
107 =item 3. Call the B<update> method, passing it a hashref of new data:
109 $fred_user->update({ username => 'new@email.address' });
113 See also: L</Direct update versus delayed update>.
115 =head2 Update multiple rows with simple values
117 -- Warning, pointless example!
119 SET dob = '2010-08-16'
120 WHERE realname LIKE 'jess%';
122 To 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.
126 =item 1. Create a Schema object representing the database you are working with:
128 my $schema = MyDatabase::Schema->connect('dbi:SQLite:my.db');
130 =item 2. Call the B<search> method on the resultset for the L<ResultSource|DBIx::Class::ResultSource> you wish to fetch data from:
132 my $user_search = $schema->resultset('User')->search(
133 { realname => { like => 'jess%' } }
136 =item 3. Call the B<update> method on the resultset to change the matching rows:
138 $user_search->update({ dob => '2010-08-16' });
142 =head2 Update a row or rows using a column calculation
144 -- Yet another pointless example
146 SET username = username || '.uk'
151 =item 1. Create a Schema object representing the database you are working with:
153 my $schema = MyDatabase::Schema->connect('dbi:SQLite:my.db');
155 =item 2. Call the B<find> method on the resultset for the L<ResultSource|DBIx::Class::ResultSource> you wish to fetch data from:
157 my $fred_user = $schema->resultset('User')->find({ id => 1 });
159 The Row object has an B<update> method that will change the values on
160 the object, and send an UPDATE query to the database.
162 =item 3. Call the B<update> method, passing it a hashref of new data:
164 # this won't yet work, DBIC for now mandates the [ {} => $value ] format, the simple \[ $sql, $value1, $value2 ] will start being recognized later on
165 # the only documentation we currently have is this, if you can turn it into a DBIC pod-patch it will be freaking awesome
166 # https://github.com/dbsrgits/dbix-class/commit/0e773352
167 $fred_user->update({ username => \['username || ?', '.uk'] });
169 ^^ you never got around to this
171 # the DBIC syntax is a tad different from te thing above (i.e. we no longer encourage 'dummy' crap)
172 The \[ .. ] syntax here is described in L<SQL::Abstract>
173 documentation, used for passing bind parameters.
178 =head2 Update a row based on data in other tables
180 -- Slightly less pointless example
182 SET title = user.username || title
183 JOIN users user ON user.id = posts.user_id;
185 Joining two tables for an update is a similar sort of exercise to
186 joining them for a select query and using data from both.
190 =item 1. Create a Schema object representing the database you are working with:
192 my $schema = MyDatabase::Schema->connect('dbi:SQLite:my.db');
194 =item 2. Call the B<search> method on the resultset for the L<ResultSource|DBIx::Class::ResultSource> you wish to update data in, joining to the second table:
196 my $posts = $schema->resultset('Post')->search(
201 The B<join> key takes as an argument a nested structure of one or more relation names (see L<DBIx::Class::Manual::SQLHackers::CREATE>).
203 =item 3. Call the B<update> method on the resultset to run the UPDATE statement:
205 $posts->update({ 'me.title' => \[ 'user.username || me.title' ] });
207 ^^ I am 95% sure this won't actually work, please try it (ideally as a passing or failing test)
211 =head2 Update or create a row
213 -- MySQL non-standardness (and another silly example)
214 INSERT INTO users ( ... )
216 ON DUPLICATE KEY UPDATE password = 'newpass';
220 SELECT id, username, dob, realname, password
222 WHERE username = 'joebloggs';
225 SET id = ?, username = ?, dob = ?, realname = ?, password = ?;
228 DBIx::Class does not yet produce the non-standard MySQL "ON DUPLICATE KEY
229 UPDATE", instead it has a shortcut for combining *find* and *update*.
231 To avoid race conditions, this should be done in a transaction.
235 =item 1. Create a Schema object representing the database you are working with:
237 my $schema = MyDatabase::Schema->connect('dbi:SQLite:my.db');
239 =item 2. Call the B<txn_do> method on the schema object, passing it a coderef to execute inside the transaction:
240 ^^ ouch! I didn't realize we don't do that automatically, this is a bug
241 ^^ probably a good idea not to mention it - I'll fix it @ GPW
242 $schema->txn_do( sub {
244 =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:
246 $schema->resultset('User')->update_or_create(
248 username => 'joebloggs',
250 realname = 'Joe Bloggs'
253 key => 'uniq_username'
257 =item 4. Close off the transaction / coderef:
263 A transaction is issued containing two statements, a B<SELECT> and then
264 either an B<INSERT> or an B<UPDATE> depending on the results.
266 Do not use this method if you definitely don't have either the primary
267 key, or a unique index value available. The B<find> method used under
268 the hood will probably not do what you expect. In this case, manually
269 run a separate B<search> method call to check for existance, and then