1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076
  
     | 
    
      /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "base/basictypes.h"
#include "IDBCursor.h"
#include "mozilla/storage.h"
#include "nsComponentManagerUtils.h"
#include "nsContentUtils.h"
#include "nsDOMClassInfoID.h"
#include "nsEventDispatcher.h"
#include "nsJSUtils.h"
#include "nsThreadUtils.h"
#include "AsyncConnectionHelper.h"
#include "IDBEvents.h"
#include "IDBIndex.h"
#include "IDBObjectStore.h"
#include "IDBTransaction.h"
#include "TransactionThreadPool.h"
#include "ipc/IndexedDBChild.h"
#include "ipc/IndexedDBParent.h"
#include "IndexedDatabaseInlines.h"
USING_INDEXEDDB_NAMESPACE
using namespace mozilla::dom::indexedDB::ipc;
MOZ_STATIC_ASSERT(sizeof(size_t) >= sizeof(IDBCursor::Direction),
                  "Relying on conversion between size_t and "
                  "IDBCursor::Direction");
namespace {
class CursorHelper : public AsyncConnectionHelper
{
public:
  CursorHelper(IDBCursor* aCursor)
  : AsyncConnectionHelper(aCursor->Transaction(), aCursor->Request()),
    mCursor(aCursor), mActor(nullptr)
  {
    NS_ASSERTION(aCursor, "Null cursor!");
  }
  virtual void ReleaseMainThreadObjects() MOZ_OVERRIDE;
  virtual nsresult Dispatch(nsIEventTarget* aDatabaseThread) MOZ_OVERRIDE;
  virtual nsresult
  PackArgumentsForParentProcess(CursorRequestParams& aParams) = 0;
  virtual nsresult
  UnpackResponseFromParentProcess(const ResponseValue& aResponseValue) = 0;
protected:
  nsRefPtr<IDBCursor> mCursor;
private:
  IndexedDBCursorRequestChild* mActor;
};
} // anonymous namespace
BEGIN_INDEXEDDB_NAMESPACE
class ContinueHelper : public CursorHelper
{
public:
  ContinueHelper(IDBCursor* aCursor,
                 int32_t aCount)
  : CursorHelper(aCursor), mCount(aCount)
  {
    NS_ASSERTION(aCount > 0, "Must have a count!");
  }
  ~ContinueHelper()
  {
    IDBObjectStore::ClearCloneReadInfo(mCloneReadInfo);
  }
  virtual nsresult DoDatabaseWork(mozIStorageConnection* aConnection)
                                  MOZ_OVERRIDE;
  virtual nsresult GetSuccessResult(JSContext* aCx,
                                    jsval* aVal) MOZ_OVERRIDE;
  virtual void ReleaseMainThreadObjects() MOZ_OVERRIDE;
  virtual nsresult
  PackArgumentsForParentProcess(CursorRequestParams& aParams) MOZ_OVERRIDE;
  virtual ChildProcessSendResult
  SendResponseToChildProcess(nsresult aResultCode) MOZ_OVERRIDE;
  virtual nsresult
  UnpackResponseFromParentProcess(const ResponseValue& aResponseValue)
                                  MOZ_OVERRIDE;
protected:
  virtual nsresult
  BindArgumentsToStatement(mozIStorageStatement* aStatement) = 0;
  virtual nsresult
  GatherResultsFromStatement(mozIStorageStatement* aStatement) = 0;
  void UpdateCursorState()
  {
    mCursor->mCachedKey = JSVAL_VOID;
    mCursor->mCachedPrimaryKey = JSVAL_VOID;
    mCursor->mCachedValue = JSVAL_VOID;
    mCursor->mHaveCachedKey = false;
    mCursor->mHaveCachedPrimaryKey = false;
    mCursor->mHaveCachedValue = false;
    mCursor->mContinueCalled = false;
    if (mKey.IsUnset()) {
      mCursor->mHaveValue = false;
    }
    else {
      NS_ASSERTION(mCursor->mType == IDBCursor::OBJECTSTORE ||
                   !mObjectKey.IsUnset(), "Bad key!");
      // Set new values.
      mCursor->mKey = mKey;
      mCursor->mObjectKey = mObjectKey;
      mCursor->mContinueToKey.Unset();
      mCursor->mCloneReadInfo.Swap(mCloneReadInfo);
      mCloneReadInfo.mCloneBuffer.clear();
    }
  }
  int32_t mCount;
  Key mKey;
  Key mObjectKey;
  StructuredCloneReadInfo mCloneReadInfo;
};
class ContinueObjectStoreHelper : public ContinueHelper
{
public:
  ContinueObjectStoreHelper(IDBCursor* aCursor,
                            uint32_t aCount)
  : ContinueHelper(aCursor, aCount)
  { }
private:
  nsresult BindArgumentsToStatement(mozIStorageStatement* aStatement);
  nsresult GatherResultsFromStatement(mozIStorageStatement* aStatement);
};
class ContinueIndexHelper : public ContinueHelper
{
public:
  ContinueIndexHelper(IDBCursor* aCursor,
                      uint32_t aCount)
  : ContinueHelper(aCursor, aCount)
  { }
private:
  nsresult BindArgumentsToStatement(mozIStorageStatement* aStatement);
  nsresult GatherResultsFromStatement(mozIStorageStatement* aStatement);
};
class ContinueIndexObjectHelper : public ContinueIndexHelper
{
public:
  ContinueIndexObjectHelper(IDBCursor* aCursor,
                            uint32_t aCount)
  : ContinueIndexHelper(aCursor, aCount)
  { }
private:
  nsresult GatherResultsFromStatement(mozIStorageStatement* aStatement);
};
END_INDEXEDDB_NAMESPACE
// static
already_AddRefed<IDBCursor>
IDBCursor::Create(IDBRequest* aRequest,
                  IDBTransaction* aTransaction,
                  IDBObjectStore* aObjectStore,
                  Direction aDirection,
                  const Key& aRangeKey,
                  const nsACString& aContinueQuery,
                  const nsACString& aContinueToQuery,
                  const Key& aKey,
                  StructuredCloneReadInfo& aCloneReadInfo)
{
  NS_ASSERTION(aObjectStore, "Null pointer!");
  NS_ASSERTION(!aKey.IsUnset(), "Bad key!");
  nsRefPtr<IDBCursor> cursor =
    IDBCursor::CreateCommon(aRequest, aTransaction, aObjectStore, aDirection,
                            aRangeKey, aContinueQuery, aContinueToQuery);
  NS_ASSERTION(cursor, "This shouldn't fail!");
  cursor->mObjectStore = aObjectStore;
  cursor->mType = OBJECTSTORE;
  cursor->mKey = aKey;
  cursor->mCloneReadInfo.Swap(aCloneReadInfo);
  return cursor.forget();
}
// static
already_AddRefed<IDBCursor>
IDBCursor::Create(IDBRequest* aRequest,
                  IDBTransaction* aTransaction,
                  IDBIndex* aIndex,
                  Direction aDirection,
                  const Key& aRangeKey,
                  const nsACString& aContinueQuery,
                  const nsACString& aContinueToQuery,
                  const Key& aKey,
                  const Key& aObjectKey)
{
  NS_ASSERTION(aIndex, "Null pointer!");
  NS_ASSERTION(!aKey.IsUnset(), "Bad key!");
  NS_ASSERTION(!aObjectKey.IsUnset(), "Bad key!");
  nsRefPtr<IDBCursor> cursor =
    IDBCursor::CreateCommon(aRequest, aTransaction, aIndex->ObjectStore(),
                            aDirection, aRangeKey, aContinueQuery,
                            aContinueToQuery);
  NS_ASSERTION(cursor, "This shouldn't fail!");
  cursor->mIndex = aIndex;
  cursor->mType = INDEXKEY;
  cursor->mKey = aKey,
  cursor->mObjectKey = aObjectKey;
  return cursor.forget();
}
// static
already_AddRefed<IDBCursor>
IDBCursor::Create(IDBRequest* aRequest,
                  IDBTransaction* aTransaction,
                  IDBIndex* aIndex,
                  Direction aDirection,
                  const Key& aRangeKey,
                  const nsACString& aContinueQuery,
                  const nsACString& aContinueToQuery,
                  const Key& aKey,
                  const Key& aObjectKey,
                  StructuredCloneReadInfo& aCloneReadInfo)
{
  NS_ASSERTION(aIndex, "Null pointer!");
  NS_ASSERTION(!aKey.IsUnset(), "Bad key!");
  nsRefPtr<IDBCursor> cursor =
    IDBCursor::CreateCommon(aRequest, aTransaction, aIndex->ObjectStore(),
                            aDirection, aRangeKey, aContinueQuery,
                            aContinueToQuery);
  NS_ASSERTION(cursor, "This shouldn't fail!");
  cursor->mObjectStore = aIndex->ObjectStore();
  cursor->mIndex = aIndex;
  cursor->mType = INDEXOBJECT;
  cursor->mKey = aKey;
  cursor->mObjectKey = aObjectKey;
  cursor->mCloneReadInfo.Swap(aCloneReadInfo);
  return cursor.forget();
}
// static
nsresult
IDBCursor::ParseDirection(const nsAString& aDirection, Direction* aResult)
{
  if (aDirection.EqualsLiteral("next")) {
    *aResult = NEXT;
  }
  else if (aDirection.EqualsLiteral("nextunique")) {
    *aResult = NEXT_UNIQUE;
  }
  else if (aDirection.EqualsLiteral("prev")) {
    *aResult = PREV;
  }
  else if (aDirection.EqualsLiteral("prevunique")) {
    *aResult = PREV_UNIQUE;
  }
  else {
    return NS_ERROR_TYPE_ERR;
  }
  
  return NS_OK;
}
// static
already_AddRefed<IDBCursor>
IDBCursor::CreateCommon(IDBRequest* aRequest,
                        IDBTransaction* aTransaction,
                        IDBObjectStore* aObjectStore,
                        Direction aDirection,
                        const Key& aRangeKey,
                        const nsACString& aContinueQuery,
                        const nsACString& aContinueToQuery)
{
  NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
  NS_ASSERTION(aRequest, "Null pointer!");
  NS_ASSERTION(aTransaction, "Null pointer!");
  NS_ASSERTION(aObjectStore, "Null pointer!");
  NS_ASSERTION(!aContinueQuery.IsEmpty() ||
               !IndexedDatabaseManager::IsMainProcess(),
               "Empty query!");
  NS_ASSERTION(!aContinueToQuery.IsEmpty() ||
               !IndexedDatabaseManager::IsMainProcess(),
               "Empty query!");
  nsRefPtr<IDBCursor> cursor = new IDBCursor();
  IDBDatabase* database = aTransaction->Database();
  cursor->mScriptOwner = database->GetScriptOwner();
  if (cursor->mScriptOwner) {
    NS_HOLD_JS_OBJECTS(cursor, IDBCursor);
    cursor->mRooted = true;
  }
  cursor->mRequest = aRequest;
  cursor->mTransaction = aTransaction;
  cursor->mObjectStore = aObjectStore;
  cursor->mDirection = aDirection;
  cursor->mContinueQuery = aContinueQuery;
  cursor->mContinueToQuery = aContinueToQuery;
  cursor->mRangeKey = aRangeKey;
  return cursor.forget();
}
IDBCursor::IDBCursor()
: mScriptOwner(nullptr),
  mType(OBJECTSTORE),
  mDirection(IDBCursor::NEXT),
  mCachedKey(JSVAL_VOID),
  mCachedPrimaryKey(JSVAL_VOID),
  mCachedValue(JSVAL_VOID),
  mActorChild(nullptr),
  mActorParent(nullptr),
  mHaveCachedKey(false),
  mHaveCachedPrimaryKey(false),
  mHaveCachedValue(false),
  mRooted(false),
  mContinueCalled(false),
  mHaveValue(true)
{
  NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
}
IDBCursor::~IDBCursor()
{
  NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
  NS_ASSERTION(!mActorParent, "Actor parent owns us, how can we be dying?!");
  if (mActorChild) {
    NS_ASSERTION(!IndexedDatabaseManager::IsMainProcess(), "Wrong process!");
    mActorChild->Send__delete__(mActorChild);
    NS_ASSERTION(!mActorChild, "Should have cleared in Send__delete__!");
  }
  DropJSObjects();
  IDBObjectStore::ClearCloneReadInfo(mCloneReadInfo);
}
void
IDBCursor::DropJSObjects()
{
  if (!mRooted) {
    return;
  }
  mScriptOwner = nullptr;
  mCachedKey = JSVAL_VOID;
  mCachedPrimaryKey = JSVAL_VOID;
  mCachedValue = JSVAL_VOID;
  mHaveCachedKey = false;
  mHaveCachedPrimaryKey = false;
  mHaveCachedValue = false;
  mRooted = false;
  mHaveValue = false;
  NS_DROP_JS_OBJECTS(this, IDBCursor);
}
nsresult
IDBCursor::ContinueInternal(const Key& aKey,
                            int32_t aCount)
{
  NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
  NS_ASSERTION(aCount > 0, "Must have a count!");
  if (!mTransaction->IsOpen()) {
    return NS_ERROR_DOM_INDEXEDDB_TRANSACTION_INACTIVE_ERR;
  }
  if (!mHaveValue || mContinueCalled) {
    return NS_ERROR_DOM_INDEXEDDB_NOT_ALLOWED_ERR;
  }
  mContinueToKey = aKey;
#ifdef DEBUG
  {
    nsAutoString readyState;
    if (NS_FAILED(mRequest->GetReadyState(readyState))) {
      NS_ERROR("This should never fail!");
    }
    NS_ASSERTION(readyState.EqualsLiteral("done"), "Should be DONE!");
  }
#endif
  mRequest->Reset();
  nsRefPtr<ContinueHelper> helper;
  switch (mType) {
    case OBJECTSTORE:
      helper = new ContinueObjectStoreHelper(this, aCount);
      break;
    case INDEXKEY:
      helper = new ContinueIndexHelper(this, aCount);
      break;
    case INDEXOBJECT:
      helper = new ContinueIndexObjectHelper(this, aCount);
      break;
    default:
      NS_NOTREACHED("Unknown cursor type!");
  }
  nsresult rv = helper->DispatchToTransactionPool();
  NS_ENSURE_SUCCESS(rv, NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
  mContinueCalled = true;
  return NS_OK;
}
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(IDBCursor)
  NS_IMPL_CYCLE_COLLECTION_TRAVERSE_SCRIPT_OBJECTS
  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mRequest)
  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mTransaction)
  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mObjectStore)
  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mIndex)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
NS_IMPL_CYCLE_COLLECTION_TRACE_BEGIN(IDBCursor)
  NS_ASSERTION(tmp->mHaveCachedKey || JSVAL_IS_VOID(tmp->mCachedKey),
               "Should have a cached key");
  NS_ASSERTION(tmp->mHaveCachedPrimaryKey ||
               JSVAL_IS_VOID(tmp->mCachedPrimaryKey),
               "Should have a cached primary key");
  NS_ASSERTION(tmp->mHaveCachedValue || JSVAL_IS_VOID(tmp->mCachedValue),
               "Should have a cached value");
  NS_IMPL_CYCLE_COLLECTION_TRACE_JS_MEMBER_CALLBACK(mScriptOwner)
  NS_IMPL_CYCLE_COLLECTION_TRACE_JSVAL_MEMBER_CALLBACK(mCachedKey)
  NS_IMPL_CYCLE_COLLECTION_TRACE_JSVAL_MEMBER_CALLBACK(mCachedPrimaryKey)
  NS_IMPL_CYCLE_COLLECTION_TRACE_JSVAL_MEMBER_CALLBACK(mCachedValue)
NS_IMPL_CYCLE_COLLECTION_TRACE_END
NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(IDBCursor)
  // Don't unlink mObjectStore, mIndex, or mTransaction!
  tmp->DropJSObjects();
  NS_IMPL_CYCLE_COLLECTION_UNLINK(mRequest)
NS_IMPL_CYCLE_COLLECTION_UNLINK_END
NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(IDBCursor)
  NS_INTERFACE_MAP_ENTRY(nsIIDBCursor)
  NS_INTERFACE_MAP_ENTRY_CONDITIONAL(nsIIDBCursorWithValue, mType != INDEXKEY)
  NS_DOM_INTERFACE_MAP_ENTRY_CLASSINFO_CONDITIONAL(IDBCursorWithValue,
                                                   mType != INDEXKEY)
  NS_DOM_INTERFACE_MAP_ENTRY_CLASSINFO_CONDITIONAL(IDBCursor,
                                                   mType == INDEXKEY)
  NS_INTERFACE_MAP_ENTRY(nsISupports)
NS_INTERFACE_MAP_END
NS_IMPL_CYCLE_COLLECTING_ADDREF(IDBCursor)
NS_IMPL_CYCLE_COLLECTING_RELEASE(IDBCursor)
DOMCI_DATA(IDBCursor, IDBCursor)
DOMCI_DATA(IDBCursorWithValue, IDBCursor)
NS_IMETHODIMP
IDBCursor::GetDirection(nsAString& aDirection)
{
  NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
  switch (mDirection) {
    case NEXT:
      aDirection.AssignLiteral("next");
      break;
    case NEXT_UNIQUE:
      aDirection.AssignLiteral("nextunique");
      break;
    case PREV:
      aDirection.AssignLiteral("prev");
      break;
    case PREV_UNIQUE:
      aDirection.AssignLiteral("prevunique");
      break;
    case DIRECTION_INVALID:
    default:
      NS_NOTREACHED("Bad direction value!");
      return NS_ERROR_UNEXPECTED;
  }
  return NS_OK;
}
NS_IMETHODIMP
IDBCursor::GetSource(nsISupports** aSource)
{
  NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
  return mType == OBJECTSTORE ?
         CallQueryInterface(mObjectStore, aSource) :
         CallQueryInterface(mIndex, aSource);
}
NS_IMETHODIMP
IDBCursor::GetKey(JSContext* aCx,
                  jsval* aKey)
{
  NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
  NS_ASSERTION(!mKey.IsUnset() || !mHaveValue, "Bad key!");
  if (!mHaveValue) {
    *aKey = JSVAL_VOID;
    return NS_OK;
  }
  if (!mHaveCachedKey) {
    if (!mRooted) {
      NS_HOLD_JS_OBJECTS(this, IDBCursor);
      mRooted = true;
    }
    JSAutoRequest ar(aCx);
    nsresult rv = mKey.ToJSVal(aCx, &mCachedKey);
    NS_ENSURE_SUCCESS(rv, rv);
    mHaveCachedKey = true;
  }
  *aKey = mCachedKey;
  return NS_OK;
}
NS_IMETHODIMP
IDBCursor::GetPrimaryKey(JSContext* aCx,
                         jsval* aValue)
{
  NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
  if (!mHaveValue) {
    *aValue = JSVAL_VOID;
    return NS_OK;
  }
  if (!mHaveCachedPrimaryKey) {
    if (!mRooted) {
      NS_HOLD_JS_OBJECTS(this, IDBCursor);
      mRooted = true;
    }
    JSAutoRequest ar(aCx);
    NS_ASSERTION(mType == OBJECTSTORE ? !mKey.IsUnset() :
                                        !mObjectKey.IsUnset(), "Bad key!");
    const Key& key = mType == OBJECTSTORE ? mKey : mObjectKey;
    nsresult rv = key.ToJSVal(aCx, &mCachedPrimaryKey);
    NS_ENSURE_SUCCESS(rv, rv);
    mHaveCachedPrimaryKey = true;
  }
  *aValue = mCachedPrimaryKey;
  return NS_OK;
}
NS_IMETHODIMP
IDBCursor::GetValue(JSContext* aCx,
                    jsval* aValue)
{
  NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
  NS_ASSERTION(mType != INDEXKEY, "GetValue shouldn't exist on index keys");
  if (!mHaveValue) {
    *aValue = JSVAL_VOID;
    return NS_OK;
  }
  if (!mHaveCachedValue) {
    if (!mRooted) {
      NS_HOLD_JS_OBJECTS(this, IDBCursor);
      mRooted = true;
    }
    jsval val;
    if (!IDBObjectStore::DeserializeValue(aCx, mCloneReadInfo, &val)) {
      return NS_ERROR_DOM_DATA_CLONE_ERR;
    }
    mCloneReadInfo.mCloneBuffer.clear();
    mCachedValue = val;
    mHaveCachedValue = true;
  }
  *aValue = mCachedValue;
  return NS_OK;
}
NS_IMETHODIMP
IDBCursor::Continue(const jsval &aKey,
                    JSContext* aCx)
{
  NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
  Key key;
  nsresult rv = key.SetFromJSVal(aCx, aKey);
  NS_ENSURE_SUCCESS(rv, rv);
  if (!key.IsUnset()) {
    switch (mDirection) {
      case IDBCursor::NEXT:
      case IDBCursor::NEXT_UNIQUE:
        if (key <= mKey) {
          return NS_ERROR_DOM_INDEXEDDB_DATA_ERR;
        }
        break;
      case IDBCursor::PREV:
      case IDBCursor::PREV_UNIQUE:
        if (key >= mKey) {
          return NS_ERROR_DOM_INDEXEDDB_DATA_ERR;
        }
        break;
      default:
        NS_NOTREACHED("Unknown direction type!");
    }
  }
  return ContinueInternal(key, 1);
}
NS_IMETHODIMP
IDBCursor::Update(const jsval& aValue,
                  JSContext* aCx,
                  nsIIDBRequest** _retval)
{
  NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
  if (!mTransaction->IsOpen()) {
    return NS_ERROR_DOM_INDEXEDDB_TRANSACTION_INACTIVE_ERR;
  }
  if (!mTransaction->IsWriteAllowed()) {
    return NS_ERROR_DOM_INDEXEDDB_READ_ONLY_ERR;
  }
  if (!mHaveValue || mType == INDEXKEY) {
    return NS_ERROR_DOM_INDEXEDDB_NOT_ALLOWED_ERR;
  }
  NS_ASSERTION(mObjectStore, "This cannot be null!");
  NS_ASSERTION(!mKey.IsUnset() , "Bad key!");
  NS_ASSERTION(mType != INDEXOBJECT || !mObjectKey.IsUnset(), "Bad key!");
  nsresult rv;
  JSAutoRequest ar(aCx);
  Key& objectKey = (mType == OBJECTSTORE) ? mKey : mObjectKey;
  if (mObjectStore->HasValidKeyPath()) {
    // Make sure the object given has the correct keyPath value set on it.
    const KeyPath& keyPath = mObjectStore->GetKeyPath();
    Key key;
    rv = keyPath.ExtractKey(aCx, aValue, key);
    if (NS_FAILED(rv)) {
      return rv;
    }
    if (key != objectKey) {
      return NS_ERROR_DOM_INDEXEDDB_DATA_ERR;
    }
    return mObjectStore->Put(aValue, JSVAL_VOID, aCx, 0, _retval);
  }
  jsval keyVal;
  rv = objectKey.ToJSVal(aCx, &keyVal);
  NS_ENSURE_SUCCESS(rv, rv);
  return mObjectStore->Put(aValue, keyVal, aCx, 1, _retval);
}
NS_IMETHODIMP
IDBCursor::Delete(JSContext* aCx,
                  nsIIDBRequest** _retval)
{
  NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
  if (!mTransaction->IsOpen()) {
    return NS_ERROR_DOM_INDEXEDDB_TRANSACTION_INACTIVE_ERR;
  }
  if (!mTransaction->IsWriteAllowed()) {
    return NS_ERROR_DOM_INDEXEDDB_READ_ONLY_ERR;
  }
  if (!mHaveValue || mType == INDEXKEY) {
    return NS_ERROR_DOM_INDEXEDDB_NOT_ALLOWED_ERR;
  }
  NS_ASSERTION(mObjectStore, "This cannot be null!");
  NS_ASSERTION(!mKey.IsUnset() , "Bad key!");
  Key& objectKey = (mType == OBJECTSTORE) ? mKey : mObjectKey;
  jsval key;
  nsresult rv = objectKey.ToJSVal(aCx, &key);
  NS_ENSURE_SUCCESS(rv, rv);
  return mObjectStore->Delete(key, aCx, _retval);
}
NS_IMETHODIMP
IDBCursor::Advance(int64_t aCount)
{
  NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
  if (aCount < 1 || aCount > UINT32_MAX) {
    return NS_ERROR_TYPE_ERR;
  }
  Key key;
  return ContinueInternal(key, int32_t(aCount));
}
void
CursorHelper::ReleaseMainThreadObjects()
{
  mCursor = nullptr;
  AsyncConnectionHelper::ReleaseMainThreadObjects();
}
nsresult
CursorHelper::Dispatch(nsIEventTarget* aDatabaseThread)
{
  if (IndexedDatabaseManager::IsMainProcess()) {
    return AsyncConnectionHelper::Dispatch(aDatabaseThread);
  }
  // If we've been invalidated then there's no point sending anything to the
  // parent process.
  if (mCursor->Transaction()->Database()->IsInvalidated()) {
    return NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR;
  }
  IndexedDBCursorChild* cursorActor = mCursor->GetActorChild();
  NS_ASSERTION(cursorActor, "Must have an actor here!");
  CursorRequestParams params;
  nsresult rv = PackArgumentsForParentProcess(params);
  NS_ENSURE_SUCCESS(rv, NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
  NoDispatchEventTarget target;
  rv = AsyncConnectionHelper::Dispatch(&target);
  NS_ENSURE_SUCCESS(rv, NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
  mActor = new IndexedDBCursorRequestChild(this, mCursor, params.type());
  cursorActor->SendPIndexedDBRequestConstructor(mActor, params);
  return NS_OK;
}
nsresult
ContinueHelper::DoDatabaseWork(mozIStorageConnection* aConnection)
{
  // We need to pick a query based on whether or not the cursor's mContinueToKey
  // is set. If it is unset then othing was passed to continue so we'll grab the
  // next item in the database that is greater than (less than, if we're running
  // a PREV cursor) the current key. If it is set then a key was passed to
  // continue so we'll grab the next item in the database that is greater than
  // (less than, if we're running a PREV cursor) or equal to the key that was
  // specified.
  nsAutoCString query;
  if (mCursor->mContinueToKey.IsUnset()) {
    query.Assign(mCursor->mContinueQuery);
  }
  else {
    query.Assign(mCursor->mContinueToQuery);
  }
  NS_ASSERTION(!query.IsEmpty(), "Bad query!");
  query.AppendInt(mCount);
  nsCOMPtr<mozIStorageStatement> stmt = mTransaction->GetCachedStatement(query);
  NS_ENSURE_TRUE(stmt, NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
  mozStorageStatementScoper scoper(stmt);
  nsresult rv = BindArgumentsToStatement(stmt);
  NS_ENSURE_SUCCESS(rv, NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
  NS_ASSERTION(mCount > 0, "Not ok!");
  bool hasResult;
  for (int32_t index = 0; index < mCount; index++) {
    rv = stmt->ExecuteStep(&hasResult);
    NS_ENSURE_SUCCESS(rv, NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
    if (!hasResult) {
      break;
    }
  }
  if (hasResult) {
    rv = GatherResultsFromStatement(stmt);
    NS_ENSURE_SUCCESS(rv, NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
  }
  else {
    mKey.Unset();
  }
  return NS_OK;
}
nsresult
ContinueHelper::GetSuccessResult(JSContext* aCx,
                                 jsval* aVal)
{
  UpdateCursorState();
  if (mKey.IsUnset()) {
    *aVal = JSVAL_NULL;
  }
  else {
    nsresult rv = WrapNative(aCx, mCursor, aVal);
    NS_ENSURE_SUCCESS(rv, rv);
  }
  return NS_OK;
}
void
ContinueHelper::ReleaseMainThreadObjects()
{
  IDBObjectStore::ClearCloneReadInfo(mCloneReadInfo);
  CursorHelper::ReleaseMainThreadObjects();
}
nsresult
ContinueHelper::PackArgumentsForParentProcess(CursorRequestParams& aParams)
{
  ContinueParams params;
  params.key() = mCursor->mContinueToKey;
  params.count() = uint32_t(mCount);
  aParams = params;
  return NS_OK;
}
AsyncConnectionHelper::ChildProcessSendResult
ContinueHelper::SendResponseToChildProcess(nsresult aResultCode)
{
  NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
  NS_ASSERTION(IndexedDatabaseManager::IsMainProcess(), "Wrong process!");
  IndexedDBRequestParentBase* actor = mRequest->GetActorParent();
  NS_ASSERTION(actor, "How did we get this far without an actor?");
  InfallibleTArray<PBlobParent*> blobsParent;
  if (NS_SUCCEEDED(aResultCode)) {
    IDBDatabase* database = mTransaction->Database();
    NS_ASSERTION(database, "This should never be null!");
    ContentParent* contentParent = database->GetContentParent();
    NS_ASSERTION(contentParent, "This should never be null!");
    FileManager* fileManager = database->Manager();
    NS_ASSERTION(fileManager, "This should never be null!");
    const nsTArray<StructuredCloneFile>& files = mCloneReadInfo.mFiles;
    aResultCode =
      IDBObjectStore::ConvertBlobsToActors(contentParent, fileManager, files,
                                           blobsParent);
    if (NS_FAILED(aResultCode)) {
      NS_WARNING("ConvertBlobsToActors failed!");
    }
  }
  ResponseValue response;
  if (NS_FAILED(aResultCode)) {
    response = aResultCode;
  }
  else {
    ContinueResponse continueResponse;
    continueResponse.key() = mKey;
    continueResponse.objectKey() = mObjectKey;
    continueResponse.cloneInfo() = mCloneReadInfo;
    continueResponse.blobsParent().SwapElements(blobsParent);
    response = continueResponse;
  }
  if (!actor->SendResponse(response)) {
    return Error;
  }
  UpdateCursorState();
  return Success_Sent;
}
nsresult
ContinueHelper::UnpackResponseFromParentProcess(
                                            const ResponseValue& aResponseValue)
{
  NS_ASSERTION(aResponseValue.type() == ResponseValue::TContinueResponse,
               "Bad response type!");
  const ContinueResponse& response = aResponseValue.get_ContinueResponse();
  mKey = response.key();
  mObjectKey = response.objectKey();
  const SerializedStructuredCloneReadInfo& cloneInfo = response.cloneInfo();
  NS_ASSERTION((!cloneInfo.dataLength && !cloneInfo.data) ||
               (cloneInfo.dataLength && cloneInfo.data),
               "Inconsistent clone info!");
  if (!mCloneReadInfo.SetFromSerialized(cloneInfo)) {
    NS_WARNING("Failed to copy clone buffer!");
    return NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR;
  }
  IDBObjectStore::ConvertActorsToBlobs(response.blobsChild(),
                                       mCloneReadInfo.mFiles);
  return NS_OK;
}
nsresult
ContinueObjectStoreHelper::BindArgumentsToStatement(
                                               mozIStorageStatement* aStatement)
{
  // Bind object store id.
  nsresult rv = aStatement->BindInt64ByName(NS_LITERAL_CSTRING("id"),
                                            mCursor->mObjectStore->Id());
  NS_ENSURE_SUCCESS(rv, NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
  NS_NAMED_LITERAL_CSTRING(currentKeyName, "current_key");
  NS_NAMED_LITERAL_CSTRING(rangeKeyName, "range_key");
  // Bind current key.
  const Key& currentKey = mCursor->mContinueToKey.IsUnset() ?
                          mCursor->mKey :
                          mCursor->mContinueToKey;
  rv = currentKey.BindToStatement(aStatement, currentKeyName);
  NS_ENSURE_SUCCESS(rv, rv);
  // Bind range key if it is specified.
  const Key& rangeKey = mCursor->mRangeKey;
  if (!rangeKey.IsUnset()) {
    rv = rangeKey.BindToStatement(aStatement, rangeKeyName);
    NS_ENSURE_SUCCESS(rv, rv);
  }
  return NS_OK;
}
nsresult
ContinueObjectStoreHelper::GatherResultsFromStatement(
                                               mozIStorageStatement* aStatement)
{
  // Figure out what kind of key we have next.
  nsresult rv = mKey.SetFromStatement(aStatement, 0);
  NS_ENSURE_SUCCESS(rv, rv);
  rv = IDBObjectStore::GetStructuredCloneReadInfoFromStatement(aStatement, 1, 2,
    mDatabase, mCloneReadInfo);
  NS_ENSURE_SUCCESS(rv, rv);
  return NS_OK;
}
nsresult
ContinueIndexHelper::BindArgumentsToStatement(mozIStorageStatement* aStatement)
{
  // Bind index id.
  nsresult rv = aStatement->BindInt64ByName(NS_LITERAL_CSTRING("id"),
                                            mCursor->mIndex->Id());
  NS_ENSURE_SUCCESS(rv, NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
  NS_NAMED_LITERAL_CSTRING(currentKeyName, "current_key");
  // Bind current key.
  const Key& currentKey = mCursor->mContinueToKey.IsUnset() ?
                          mCursor->mKey :
                          mCursor->mContinueToKey;
  rv = currentKey.BindToStatement(aStatement, currentKeyName);
  NS_ENSURE_SUCCESS(rv, rv);
  // Bind range key if it is specified.
  if (!mCursor->mRangeKey.IsUnset()) {
    NS_NAMED_LITERAL_CSTRING(rangeKeyName, "range_key");
    rv = mCursor->mRangeKey.BindToStatement(aStatement, rangeKeyName);
    NS_ENSURE_SUCCESS(rv, rv);
  }
  // Bind object key if duplicates are allowed and we're not continuing to a
  // specific key.
  if ((mCursor->mDirection == IDBCursor::NEXT ||
       mCursor->mDirection == IDBCursor::PREV) &&
       mCursor->mContinueToKey.IsUnset()) {
    NS_ASSERTION(!mCursor->mObjectKey.IsUnset(), "Bad key!");
    NS_NAMED_LITERAL_CSTRING(objectKeyName, "object_key");
    rv = mCursor->mObjectKey.BindToStatement(aStatement, objectKeyName);
    NS_ENSURE_SUCCESS(rv, rv);
  }
  return NS_OK;
}
nsresult
ContinueIndexHelper::GatherResultsFromStatement(
                                               mozIStorageStatement* aStatement)
{
  nsresult rv = mKey.SetFromStatement(aStatement, 0);
  NS_ENSURE_SUCCESS(rv, rv);
  rv = mObjectKey.SetFromStatement(aStatement, 1);
  NS_ENSURE_SUCCESS(rv, rv);
  return NS_OK;
}
nsresult
ContinueIndexObjectHelper::GatherResultsFromStatement(
                                               mozIStorageStatement* aStatement)
{
  nsresult rv = mKey.SetFromStatement(aStatement, 0);
  NS_ENSURE_SUCCESS(rv, rv);
  rv = mObjectKey.SetFromStatement(aStatement, 1);
  NS_ENSURE_SUCCESS(rv, rv);
  rv = IDBObjectStore::GetStructuredCloneReadInfoFromStatement(aStatement, 2, 3,
    mDatabase, mCloneReadInfo);
  NS_ENSURE_SUCCESS(rv, rv);
  return NS_OK;
}
 
     |