Guest User

Untitled

a guest
Jun 23rd, 2018
238
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.71 KB | None | 0 0
  1. <?php
  2.  
  3. $attributes = ['name' => 'John Doe'];
  4. $query = User::where('email', 'john@example.com'); // $query->toSql() --> select * from `users` where `email` = ?
  5. $grammar = $query->getQuery()->getGrammar();
  6. $sql = $grammar->compileUpdate($query->getQuery(), $attributes); // update `users` set `name` = ? where `email` = ?
  7. $bindings = $query->getBindings(); // ['john@example.com']
  8. if( ! array_has($bindings, 'join') ) {
  9. array_set($bindings, 'join', []); // because Grammar stupidly assumes a join binding
  10. }
  11. $bindings = $grammar->prepareBindingsForUpdate($bindings, $attributes); // ['John Doe', 'john@example.com']
  12. $params = array_values(array_filter($bindings, function ($binding) {
  13. return ! $binding instanceof \Illuminate\Database\Query\Expression;
  14. }));
  15.  
  16. $replacements = [];
  17. foreach($params as $i => $param) {
  18. $sql = substr_replace($sql, '$'.($i+1), stripos($sql, '?'), 1);
  19. }
  20. // $sql === update `users` set `name` = $1 where `email` = $2
  21.  
  22. $config = config('database.connections.pgsql');
  23. $connection = pg_connect(
  24. sprintf('host=%s port=%d dbname=%s user=%s password=%s',
  25. array_get($config, 'host'),
  26. array_get($config, 'port'),
  27. array_get($config, 'database'),
  28. array_get($config, 'username'),
  29. array_get($config, 'password')
  30. ));
  31. if(! pg_send_query_params($connection, $sql, $params) ) {
  32. throw new \Exception(pg_last_error($connection));
  33. }
  34.  
  35. pg_close($connection);
  36.  
  37. // You could use DB::extend('pgsqlbg') to create a custom driver for `Connection`
  38. // that accepts `update(string|Query|Model $query, array $bindings = [])` which
  39. // would mask away the statement preparation details inside of the driver.
  40. // Unfortunately there will be a lot of PDO assumptions which will need to be nooped.
Add Comment
Please, Sign In to add comment