/** * pass in an object - mysqli, pdo, or codeigniter database object. * If you need another adapter, email John Loehrer <*****@*****.**> or submit your own. * Thinking about writing an adapter for DBAL -- doctrine's data access layer. */ function __construct($core) { while ($core instanceof \Wukka\DB && $core->core() instanceof Iface) { $core = $core->core(); } $this->core = $core; if ($core instanceof \PDO) { $this->_ = DB\Closure\PDO::closures($core); } elseif ($core instanceof \MySQLi) { $this->_ = DB\Closure\MySQLi::closures($core); } else { trigger_error('invalid db object', E_USER_ERROR); exit(1); } }
public static function closures(\PDO $db) { $_ = array(); $lastquery = ''; $_['__tostring'] = function () use($db, &$lastquery) { list($errstate, $errcode, $errmsg) = $db->errorInfo(); $error = $errmsg ? $errcode . ': ' . $errmsg : ''; $res = '(Wukka\\DB\\PDO object - ' . "\n" . ' [driver] => ' . $db->getAttribute(\PDO::ATTR_DRIVER_NAME) . "\n" . ' [connection] => ' . @$db->getAttribute(\PDO::ATTR_CONNECTION_STATUS) . "\n" . ' [error] => ' . $error . "\n" . ' [lastquery] => ' . $lastquery . "\n" . ')'; return $res; }; $_['prep_args'] = $format_args = function ($query, array $args) use($db) { if (!$args || count($args) < 1) { return $query; } return \Wukka\DB\Query::prepare($query, $args, function ($v) use($db) { return $db->quote($v); }); }; $_['execute'] = function ($query) use($db, &$lastquery) { try { $lastquery = $query; if (strlen($lastquery) > 500) { $lastquery = substr($lastquery, 0, 485) . ' ...[trucated]'; } $res = $db->query($query); if (!$res) { return FALSE; } $_ = array(); $_['fetch'] = function () use($res) { return $res->fetch(\PDO::FETCH_ASSOC); }; $_['free'] = function () use($res) { $res->closeCursor(); }; $_['affected'] = $res->rowCount(); $_['insertid'] = $db->lastInsertId(); return new Result($_); } catch (\Exception $e) { return FALSE; } }; $_['start'] = function ($auth = NULL) use($db) { if ($db instanceof Iface) { return $db->start($auth); } return $db->beginTransaction(); }; $_['commit'] = function ($auth = NULL) use($db) { if ($db instanceof Iface) { return $db->commit($auth); } return $db->commit(); }; $_['rollback'] = function ($auth = NULL) use($db) { if ($db instanceof Iface) { return $db->rollback($auth); } return $db->rollback(); }; $_['error'] = function () use($db) { $info = $db->errorInfo(); return $info[2]; }; $_['errorcode'] = function () use($db) { $info = $db->errorInfo(); return $info[1]; }; $_['isa'] = function ($name) use($db) { if ($db instanceof $name) { return TRUE; } if ($name == $db->getAttribute(\PDO::ATTR_DRIVER_NAME)) { return TRUE; } return FALSE; }; $_['hash'] = function () use($db) { if ($db instanceof Iface) { return $db->hash(); } return spl_object_hash($db); }; return $_; }