Make WordPress Core

Opened 3 years ago

Closed 16 months ago

#22196 closed enhancement (maybelater)

add $wpdb->upsert function

Reported by: thomask Owned by:
Milestone: Priority: normal
Severity: normal Version: 3.4.2
Component: Database Keywords:
Focuses: Cc:


If i read http://codex.wordpress.org/Class_Reference/wpdb right, we have only insert and update functions, but for many occations, if would be lovely, if we would have upsert function as well (using INSERT ... ON DUPLICATE KEY UPDATE http://dev.mysql.com/doc/refman/5.1/en/insert-on-duplicate.html).

So when i am inserting e.g. posts using database function, i do not have to check if post with that id exist (good for some migration / importing tools etc.)

Change History (2)

comment:1 @wonderboymusic3 years ago

This one would be tricky:

Inserts and Updates also take formatting as an argument. If you pass the primary key as an arbitrary value, the primary key and its formatting would have to be removed from the values AND formatting arrays, regardless of what order they were passed.

The resulting SQL needs to look like:

INSERT INTO wp_posts (post_title, post_date, ID, post_content, post_type) 
VALUES ('Title', '2012-10-07 07:00:00', 3, 'This is content', 'event') 
post_title = 'Title',
post_date ='2012-10-07 07:00:00',  
post_content = 'This is content', 
post_type = 'event'

But that can be passed to $wpdb->insert like so:

		'post_title' 	=> 'Title', 
		'post_date' 	=> '2012-10-07 07:00:00', 
		'ID' 		=> 3, 
		'post_content' 	=> 'This is content', 
		'post_type' 	=> 'event' 
	array( '%s', '%s', '%d', '%s', '%s' )

The insert method takes arbitrary arrays as arguments, but to remove the *specific* primary key for any passed table, it would have to be intercepted and altered just in time to create the proper update SQL.

I'm not sure wpdb should get this fancy. Semi-related: https://core.trac.wordpress.org/ticket/19019

Version 0, edited 3 years ago by wonderboymusic (next)

comment:2 @wonderboymusic16 months ago

  • Milestone Awaiting Review deleted
  • Resolution set to maybelater
  • Status changed from new to closed

I'm the only comment, and that was 20 months ago.

Note: See TracTickets for help on using tickets.