Index: sql/scoped_attach.cc |
diff --git a/sql/scoped_attach.cc b/sql/scoped_attach.cc |
new file mode 100644 |
index 0000000000000000000000000000000000000000..d25f6ceb2036cf707b18dd32342385474ad9fc43 |
--- /dev/null |
+++ b/sql/scoped_attach.cc |
@@ -0,0 +1,61 @@ |
+// Copyright (c) 2013 The Chromium Authors. All rights reserved. |
+// Use of this source code is governed by a BSD-style license that can be |
+// found in the LICENSE file. |
+ |
+#include "sql/scoped_attach.h" |
+ |
+#include "base/files/file_path.h" |
+#include "base/logging.h" |
+#include "sql/connection.h" |
+#include "sql/statement.h" |
+ |
+namespace sql { |
+ |
+ScopedAttach::ScopedAttach(Connection* connection) |
+ : db_(connection), |
+ attached_as_() { |
+} |
+ |
+ScopedAttach::~ScopedAttach() { |
+ Detach(); |
+} |
+ |
+bool ScopedAttach::Attach(const base::FilePath& other_db_path, |
+ const char* attach_as) { |
+ DCHECK(attached_as_.empty()); |
+ |
+ // Be strict on attachment point. |
+ for (size_t i = 0; attach_as[i]; ++i) { |
+ DCHECK((attach_as[i] >= '0' && attach_as[i] <= '9') || |
+ (attach_as[i] >= 'a' && attach_as[i] <= 'z') || |
+ (attach_as[i] >= 'A' && attach_as[i] <= 'Z') || |
+ attach_as[i] == '_'); |
+ } |
+ |
+ Statement s(db_->GetUniqueStatement("ATTACH DATABASE ? AS ?")); |
+#if OS_WIN |
+ s.BindString16(0, other_db_path.value()); |
+#else |
+ s.BindString(0, other_db_path.value()); |
+#endif |
+ s.BindString(1, attach_as); |
+ if (!s.Run()) { |
+ LOG(ERROR) << "Failed attach."; |
+ return false; |
+ } |
+ |
+ attached_as_ = attach_as; |
+ return true; |
+} |
+ |
+void ScopedAttach::Detach() { |
+ if (!attached_as_.empty()) { |
+ Statement s(db_->GetUniqueStatement("DETACH DATABASE ?")); |
+ s.BindString(0, attached_as_); |
+ if (!s.Run()) |
+ LOG(ERROR) << "Failed detach."; |
+ attached_as_.clear(); |
+ } |
+} |
+ |
+} // namespace sql |