compiler.php 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. <?php namespace System\DB\Query;
  2. class Compiler {
  3. /**
  4. * Build a SQL SELECT statement.
  5. *
  6. * @param Query $query
  7. * @return string
  8. */
  9. public static function select($query)
  10. {
  11. $sql = $query->select.' '.$query->from.' '.$query->where;
  12. if (count($query->orderings) > 0)
  13. {
  14. $sql .= ' ORDER BY '.implode(', ', $query->orderings);
  15. }
  16. if ( ! is_null($query->limit))
  17. {
  18. $sql .= ' LIMIT '.$query->limit;
  19. }
  20. if ( ! is_null($query->offset))
  21. {
  22. $sql .= ' OFFSET '.$query->offset;
  23. }
  24. return $sql;
  25. }
  26. /**
  27. * Build a SQL INSERT statement.
  28. *
  29. * @param Query $query
  30. * @param array $values
  31. * @return string
  32. */
  33. public static function insert($query, $values)
  34. {
  35. $sql = 'INSERT INTO '.$query->wrap($query->table);
  36. $columns = array();
  37. foreach (array_keys($values) as $column)
  38. {
  39. $columns[] = $query->wrap($column);
  40. }
  41. return $sql .= ' ('.implode(', ', $columns).') VALUES ('.$query->parameterize($values).')';
  42. }
  43. /**
  44. * Build a SQL UPDATE statement.
  45. *
  46. * @param Query $query
  47. * @param array $values
  48. * @return string
  49. */
  50. public static function update($query, $values)
  51. {
  52. $sql = 'UPDATE '.$query->wrap($query->table).' SET ';
  53. $sets = array();
  54. foreach (array_keys($values) as $column)
  55. {
  56. $sets[] = $query->wrap($column).' = ?';
  57. }
  58. return $sql .= implode(', ', $sets).' '.$query->where;
  59. }
  60. /**
  61. * Build a SQL DELETE statement.
  62. *
  63. * @param Query $query
  64. * @return string
  65. */
  66. public static function delete($query)
  67. {
  68. return 'DELETE FROM '.$query->wrap($query->table).' '.$query->where;
  69. }
  70. }