1 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
2 * vim: sw=2 ts=2 et lcs=trail\:.,tab\:>~ :
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7 #include <limits.h>
8 #include <stdio.h>
9
10 #include "nsError.h"
11 #include "nsMemory.h"
12 #include "nsThreadUtils.h"
13 #include "nsIClassInfoImpl.h"
14 #include "Variant.h"
15
16 #include "mozIStorageError.h"
17
18 #include "mozStorageBindingParams.h"
19 #include "mozStorageConnection.h"
20 #include "mozStorageStatementJSHelper.h"
21 #include "mozStoragePrivateHelpers.h"
22 #include "mozStorageStatementParams.h"
23 #include "mozStorageStatementRow.h"
24 #include "mozStorageStatement.h"
25 #include "GeckoProfiler.h"
26 #include "nsDOMClassInfo.h"
27
28 #include "mozilla/Logging.h"
29
30
31 extern mozilla::LazyLogModule gStorageLog;
32
33 namespace mozilla {
34 namespace storage {
35
36 ////////////////////////////////////////////////////////////////////////////////
37 //// nsIClassInfo
38
39 NS_IMPL_CI_INTERFACE_GETTER(Statement,
40 mozIStorageStatement,
41 mozIStorageBaseStatement,
42 mozIStorageBindingParams,
43 mozIStorageValueArray,
44 mozilla::storage::StorageBaseStatementInternal)
45
46 class StatementClassInfo : public nsIClassInfo
47 {
48 public:
StatementClassInfo()49 constexpr StatementClassInfo() {}
50
51 NS_DECL_ISUPPORTS_INHERITED
52
53 NS_IMETHOD
GetInterfaces(uint32_t * _count,nsIID *** _array)54 GetInterfaces(uint32_t *_count, nsIID ***_array) override
55 {
56 return NS_CI_INTERFACE_GETTER_NAME(Statement)(_count, _array);
57 }
58
59 NS_IMETHOD
GetScriptableHelper(nsIXPCScriptable ** _helper)60 GetScriptableHelper(nsIXPCScriptable **_helper) override
61 {
62 static StatementJSHelper sJSHelper;
63 *_helper = &sJSHelper;
64 return NS_OK;
65 }
66
67 NS_IMETHOD
GetContractID(char ** _contractID)68 GetContractID(char **_contractID) override
69 {
70 *_contractID = nullptr;
71 return NS_OK;
72 }
73
74 NS_IMETHOD
GetClassDescription(char ** _desc)75 GetClassDescription(char **_desc) override
76 {
77 *_desc = nullptr;
78 return NS_OK;
79 }
80
81 NS_IMETHOD
GetClassID(nsCID ** _id)82 GetClassID(nsCID **_id) override
83 {
84 *_id = nullptr;
85 return NS_OK;
86 }
87
88 NS_IMETHOD
GetFlags(uint32_t * _flags)89 GetFlags(uint32_t *_flags) override
90 {
91 *_flags = 0;
92 return NS_OK;
93 }
94
95 NS_IMETHOD
GetClassIDNoAlloc(nsCID * _cid)96 GetClassIDNoAlloc(nsCID *_cid) override
97 {
98 return NS_ERROR_NOT_AVAILABLE;
99 }
100 };
101
NS_IMETHODIMP_(MozExternalRefCountType)102 NS_IMETHODIMP_(MozExternalRefCountType) StatementClassInfo::AddRef() { return 2; }
NS_IMETHODIMP_(MozExternalRefCountType)103 NS_IMETHODIMP_(MozExternalRefCountType) StatementClassInfo::Release() { return 1; }
104 NS_IMPL_QUERY_INTERFACE(StatementClassInfo, nsIClassInfo)
105
106 static StatementClassInfo sStatementClassInfo;
107
108 ////////////////////////////////////////////////////////////////////////////////
109 //// Statement
110
Statement()111 Statement::Statement()
112 : StorageBaseStatementInternal()
113 , mDBStatement(nullptr)
114 , mColumnNames()
115 , mExecuting(false)
116 {
117 }
118
119 nsresult
initialize(Connection * aDBConnection,sqlite3 * aNativeConnection,const nsACString & aSQLStatement)120 Statement::initialize(Connection *aDBConnection,
121 sqlite3 *aNativeConnection,
122 const nsACString &aSQLStatement)
123 {
124 MOZ_ASSERT(aDBConnection, "No database connection given!");
125 MOZ_ASSERT(!aDBConnection->isClosed(), "Database connection should be valid");
126 MOZ_ASSERT(!mDBStatement, "Statement already initialized!");
127 MOZ_ASSERT(aNativeConnection, "No native connection given!");
128
129 int srv = aDBConnection->prepareStatement(aNativeConnection,
130 PromiseFlatCString(aSQLStatement),
131 &mDBStatement);
132 if (srv != SQLITE_OK) {
133 MOZ_LOG(gStorageLog, LogLevel::Error,
134 ("Sqlite statement prepare error: %d '%s'", srv,
135 ::sqlite3_errmsg(aNativeConnection)));
136 MOZ_LOG(gStorageLog, LogLevel::Error,
137 ("Statement was: '%s'", PromiseFlatCString(aSQLStatement).get()));
138 return NS_ERROR_FAILURE;
139 }
140
141 MOZ_LOG(gStorageLog, LogLevel::Debug, ("Initialized statement '%s' (0x%p)",
142 PromiseFlatCString(aSQLStatement).get(),
143 mDBStatement));
144
145 mDBConnection = aDBConnection;
146 mNativeConnection = aNativeConnection;
147 mParamCount = ::sqlite3_bind_parameter_count(mDBStatement);
148 mResultColumnCount = ::sqlite3_column_count(mDBStatement);
149 mColumnNames.Clear();
150
151 nsCString* columnNames = mColumnNames.AppendElements(mResultColumnCount);
152 for (uint32_t i = 0; i < mResultColumnCount; i++) {
153 const char *name = ::sqlite3_column_name(mDBStatement, i);
154 columnNames[i].Assign(name);
155 }
156
157 #ifdef DEBUG
158 // We want to try and test for LIKE and that consumers are using
159 // escapeStringForLIKE instead of just trusting user input. The idea to
160 // check to see if they are binding a parameter after like instead of just
161 // using a string. We only do this in debug builds because it's expensive!
162 const nsCaseInsensitiveCStringComparator c;
163 nsACString::const_iterator start, end, e;
164 aSQLStatement.BeginReading(start);
165 aSQLStatement.EndReading(end);
166 e = end;
167 while (::FindInReadable(NS_LITERAL_CSTRING(" LIKE"), start, e, c)) {
168 // We have a LIKE in here, so we perform our tests
169 // FindInReadable moves the iterator, so we have to get a new one for
170 // each test we perform.
171 nsACString::const_iterator s1, s2, s3;
172 s1 = s2 = s3 = start;
173
174 if (!(::FindInReadable(NS_LITERAL_CSTRING(" LIKE ?"), s1, end, c) ||
175 ::FindInReadable(NS_LITERAL_CSTRING(" LIKE :"), s2, end, c) ||
176 ::FindInReadable(NS_LITERAL_CSTRING(" LIKE @"), s3, end, c))) {
177 // At this point, we didn't find a LIKE statement followed by ?, :,
178 // or @, all of which are valid characters for binding a parameter.
179 // We will warn the consumer that they may not be safely using LIKE.
180 NS_WARNING("Unsafe use of LIKE detected! Please ensure that you "
181 "are using mozIStorageStatement::escapeStringForLIKE "
182 "and that you are binding that result to the statement "
183 "to prevent SQL injection attacks.");
184 }
185
186 // resetting start and e
187 start = e;
188 e = end;
189 }
190 #endif
191
192 return NS_OK;
193 }
194
195 mozIStorageBindingParams *
getParams()196 Statement::getParams()
197 {
198 nsresult rv;
199
200 // If we do not have an array object yet, make it.
201 if (!mParamsArray) {
202 nsCOMPtr<mozIStorageBindingParamsArray> array;
203 rv = NewBindingParamsArray(getter_AddRefs(array));
204 NS_ENSURE_SUCCESS(rv, nullptr);
205
206 mParamsArray = static_cast<BindingParamsArray *>(array.get());
207 }
208
209 // If there isn't already any rows added, we'll have to add one to use.
210 if (mParamsArray->length() == 0) {
211 RefPtr<BindingParams> params(new BindingParams(mParamsArray, this));
212 NS_ENSURE_TRUE(params, nullptr);
213
214 rv = mParamsArray->AddParams(params);
215 NS_ENSURE_SUCCESS(rv, nullptr);
216
217 // We have to unlock our params because AddParams locks them. This is safe
218 // because no reference to the params object was, or ever will be given out.
219 params->unlock(this);
220
221 // We also want to lock our array at this point - we don't want anything to
222 // be added to it. Nothing has, or will ever get a reference to it, but we
223 // will get additional safety checks via assertions by doing this.
224 mParamsArray->lock();
225 }
226
227 return *mParamsArray->begin();
228 }
229
~Statement()230 Statement::~Statement()
231 {
232 (void)internalFinalize(true);
233 }
234
235 ////////////////////////////////////////////////////////////////////////////////
236 //// nsISupports
237
238 NS_IMPL_ADDREF(Statement)
239 NS_IMPL_RELEASE(Statement)
240
241 NS_INTERFACE_MAP_BEGIN(Statement)
242 NS_INTERFACE_MAP_ENTRY(mozIStorageStatement)
243 NS_INTERFACE_MAP_ENTRY(mozIStorageBaseStatement)
244 NS_INTERFACE_MAP_ENTRY(mozIStorageBindingParams)
245 NS_INTERFACE_MAP_ENTRY(mozIStorageValueArray)
246 NS_INTERFACE_MAP_ENTRY(mozilla::storage::StorageBaseStatementInternal)
247 if (aIID.Equals(NS_GET_IID(nsIClassInfo))) {
248 foundInterface = static_cast<nsIClassInfo *>(&sStatementClassInfo);
249 }
250 else
NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports,mozIStorageStatement)251 NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, mozIStorageStatement)
252 NS_INTERFACE_MAP_END
253
254
255 ////////////////////////////////////////////////////////////////////////////////
256 //// StorageBaseStatementInternal
257
258 Connection *
259 Statement::getOwner()
260 {
261 return mDBConnection;
262 }
263
264 int
getAsyncStatement(sqlite3_stmt ** _stmt)265 Statement::getAsyncStatement(sqlite3_stmt **_stmt)
266 {
267 // If we have no statement, we shouldn't be calling this method!
268 NS_ASSERTION(mDBStatement != nullptr, "We have no statement to clone!");
269
270 // If we do not yet have a cached async statement, clone our statement now.
271 if (!mAsyncStatement) {
272 nsDependentCString sql(::sqlite3_sql(mDBStatement));
273 int rc = mDBConnection->prepareStatement(mNativeConnection, sql,
274 &mAsyncStatement);
275 if (rc != SQLITE_OK) {
276 *_stmt = nullptr;
277 return rc;
278 }
279
280 MOZ_LOG(gStorageLog, LogLevel::Debug,
281 ("Cloned statement 0x%p to 0x%p", mDBStatement, mAsyncStatement));
282 }
283
284 *_stmt = mAsyncStatement;
285 return SQLITE_OK;
286 }
287
288 nsresult
getAsynchronousStatementData(StatementData & _data)289 Statement::getAsynchronousStatementData(StatementData &_data)
290 {
291 if (!mDBStatement)
292 return NS_ERROR_UNEXPECTED;
293
294 sqlite3_stmt *stmt;
295 int rc = getAsyncStatement(&stmt);
296 if (rc != SQLITE_OK)
297 return convertResultCode(rc);
298
299 _data = StatementData(stmt, bindingParamsArray(), this);
300
301 return NS_OK;
302 }
303
304 already_AddRefed<mozIStorageBindingParams>
newBindingParams(mozIStorageBindingParamsArray * aOwner)305 Statement::newBindingParams(mozIStorageBindingParamsArray *aOwner)
306 {
307 nsCOMPtr<mozIStorageBindingParams> params = new BindingParams(aOwner, this);
308 return params.forget();
309 }
310
311
312 ////////////////////////////////////////////////////////////////////////////////
313 //// mozIStorageStatement
314
315 // proxy to StorageBaseStatementInternal using its define helper.
316 MIXIN_IMPL_STORAGEBASESTATEMENTINTERNAL(Statement, (void)0;)
317
318 NS_IMETHODIMP
Clone(mozIStorageStatement ** _statement)319 Statement::Clone(mozIStorageStatement **_statement)
320 {
321 RefPtr<Statement> statement(new Statement());
322 NS_ENSURE_TRUE(statement, NS_ERROR_OUT_OF_MEMORY);
323
324 nsAutoCString sql(::sqlite3_sql(mDBStatement));
325 nsresult rv = statement->initialize(mDBConnection, mNativeConnection, sql);
326 NS_ENSURE_SUCCESS(rv, rv);
327
328 statement.forget(_statement);
329 return NS_OK;
330 }
331
332 NS_IMETHODIMP
Finalize()333 Statement::Finalize()
334 {
335 return internalFinalize(false);
336 }
337
338 nsresult
internalFinalize(bool aDestructing)339 Statement::internalFinalize(bool aDestructing)
340 {
341 if (!mDBStatement)
342 return NS_OK;
343
344 int srv = SQLITE_OK;
345
346 if (!mDBConnection->isClosed()) {
347 //
348 // The connection is still open. While statement finalization and
349 // closing may, in some cases, take place in two distinct threads,
350 // we have a guarantee that the connection will remain open until
351 // this method terminates:
352 //
353 // a. The connection will be closed synchronously. In this case,
354 // there is no race condition, as everything takes place on the
355 // same thread.
356 //
357 // b. The connection is closed asynchronously and this code is
358 // executed on the opener thread. In this case, asyncClose() has
359 // not been called yet and will not be called before we return
360 // from this function.
361 //
362 // c. The connection is closed asynchronously and this code is
363 // executed on the async execution thread. In this case,
364 // AsyncCloseConnection::Run() has not been called yet and will
365 // not be called before we return from this function.
366 //
367 // In either case, the connection is still valid, hence closing
368 // here is safe.
369 //
370 MOZ_LOG(gStorageLog, LogLevel::Debug, ("Finalizing statement '%s' during garbage-collection",
371 ::sqlite3_sql(mDBStatement)));
372 srv = ::sqlite3_finalize(mDBStatement);
373 }
374 #ifdef DEBUG
375 else {
376 //
377 // The database connection is either closed or closing. The sqlite
378 // statement has either been finalized already by the connection
379 // or is about to be finalized by the connection.
380 //
381 // Finalizing it here would be useless and segfaultish.
382 //
383
384 char *msg = ::PR_smprintf("SQL statement (%x) should have been finalized"
385 " before garbage-collection. For more details on this statement, set"
386 " NSPR_LOG_MESSAGES=mozStorage:5 .",
387 mDBStatement);
388
389 //
390 // Note that we can't display the statement itself, as the data structure
391 // is not valid anymore. However, the address shown here should help
392 // developers correlate with the more complete debug message triggered
393 // by AsyncClose().
394 //
395
396 #if 0
397 // Deactivate the warning until we have fixed the exising culprit
398 // (see bug 914070).
399 NS_WARNING(msg);
400 #endif // 0
401
402 MOZ_LOG(gStorageLog, LogLevel::Warning, (msg));
403
404 ::PR_smprintf_free(msg);
405 }
406
407 #endif
408
409 mDBStatement = nullptr;
410
411 if (mAsyncStatement) {
412 // If the destructor called us, there are no pending async statements (they
413 // hold a reference to us) and we can/must just kill the statement directly.
414 if (aDestructing)
415 destructorAsyncFinalize();
416 else
417 asyncFinalize();
418 }
419
420 // Release the holders, so they can release the reference to us.
421 mStatementParamsHolder = nullptr;
422 mStatementRowHolder = nullptr;
423
424 return convertResultCode(srv);
425 }
426
427 NS_IMETHODIMP
GetParameterCount(uint32_t * _parameterCount)428 Statement::GetParameterCount(uint32_t *_parameterCount)
429 {
430 if (!mDBStatement)
431 return NS_ERROR_NOT_INITIALIZED;
432
433 *_parameterCount = mParamCount;
434 return NS_OK;
435 }
436
437 NS_IMETHODIMP
GetParameterName(uint32_t aParamIndex,nsACString & _name)438 Statement::GetParameterName(uint32_t aParamIndex,
439 nsACString &_name)
440 {
441 if (!mDBStatement)
442 return NS_ERROR_NOT_INITIALIZED;
443 ENSURE_INDEX_VALUE(aParamIndex, mParamCount);
444
445 const char *name = ::sqlite3_bind_parameter_name(mDBStatement,
446 aParamIndex + 1);
447 if (name == nullptr) {
448 // this thing had no name, so fake one
449 nsAutoCString fakeName(":");
450 fakeName.AppendInt(aParamIndex);
451 _name.Assign(fakeName);
452 }
453 else {
454 _name.Assign(nsDependentCString(name));
455 }
456
457 return NS_OK;
458 }
459
460 NS_IMETHODIMP
GetParameterIndex(const nsACString & aName,uint32_t * _index)461 Statement::GetParameterIndex(const nsACString &aName,
462 uint32_t *_index)
463 {
464 if (!mDBStatement)
465 return NS_ERROR_NOT_INITIALIZED;
466
467 // We do not accept any forms of names other than ":name", but we need to add
468 // the colon for SQLite.
469 nsAutoCString name(":");
470 name.Append(aName);
471 int ind = ::sqlite3_bind_parameter_index(mDBStatement, name.get());
472 if (ind == 0) // Named parameter not found.
473 return NS_ERROR_INVALID_ARG;
474
475 *_index = ind - 1; // SQLite indexes are 1-based, we are 0-based.
476
477 return NS_OK;
478 }
479
480 NS_IMETHODIMP
GetColumnCount(uint32_t * _columnCount)481 Statement::GetColumnCount(uint32_t *_columnCount)
482 {
483 if (!mDBStatement)
484 return NS_ERROR_NOT_INITIALIZED;
485
486 *_columnCount = mResultColumnCount;
487 return NS_OK;
488 }
489
490 NS_IMETHODIMP
GetColumnName(uint32_t aColumnIndex,nsACString & _name)491 Statement::GetColumnName(uint32_t aColumnIndex,
492 nsACString &_name)
493 {
494 if (!mDBStatement)
495 return NS_ERROR_NOT_INITIALIZED;
496 ENSURE_INDEX_VALUE(aColumnIndex, mResultColumnCount);
497
498 const char *cname = ::sqlite3_column_name(mDBStatement, aColumnIndex);
499 _name.Assign(nsDependentCString(cname));
500
501 return NS_OK;
502 }
503
504 NS_IMETHODIMP
GetColumnIndex(const nsACString & aName,uint32_t * _index)505 Statement::GetColumnIndex(const nsACString &aName,
506 uint32_t *_index)
507 {
508 if (!mDBStatement)
509 return NS_ERROR_NOT_INITIALIZED;
510
511 // Surprisingly enough, SQLite doesn't provide an API for this. We have to
512 // determine it ourselves sadly.
513 for (uint32_t i = 0; i < mResultColumnCount; i++) {
514 if (mColumnNames[i].Equals(aName)) {
515 *_index = i;
516 return NS_OK;
517 }
518 }
519
520 return NS_ERROR_INVALID_ARG;
521 }
522
523 NS_IMETHODIMP
Reset()524 Statement::Reset()
525 {
526 if (!mDBStatement)
527 return NS_ERROR_NOT_INITIALIZED;
528
529 #ifdef DEBUG
530 MOZ_LOG(gStorageLog, LogLevel::Debug, ("Resetting statement: '%s'",
531 ::sqlite3_sql(mDBStatement)));
532
533 checkAndLogStatementPerformance(mDBStatement);
534 #endif
535
536 mParamsArray = nullptr;
537 (void)sqlite3_reset(mDBStatement);
538 (void)sqlite3_clear_bindings(mDBStatement);
539
540 mExecuting = false;
541
542 return NS_OK;
543 }
544
545 NS_IMETHODIMP
BindParameters(mozIStorageBindingParamsArray * aParameters)546 Statement::BindParameters(mozIStorageBindingParamsArray *aParameters)
547 {
548 NS_ENSURE_ARG_POINTER(aParameters);
549
550 if (!mDBStatement)
551 return NS_ERROR_NOT_INITIALIZED;
552
553 BindingParamsArray *array = static_cast<BindingParamsArray *>(aParameters);
554 if (array->getOwner() != this)
555 return NS_ERROR_UNEXPECTED;
556
557 if (array->length() == 0)
558 return NS_ERROR_UNEXPECTED;
559
560 mParamsArray = array;
561 mParamsArray->lock();
562
563 return NS_OK;
564 }
565
566 NS_IMETHODIMP
Execute()567 Statement::Execute()
568 {
569 if (!mDBStatement)
570 return NS_ERROR_NOT_INITIALIZED;
571
572 bool ret;
573 nsresult rv = ExecuteStep(&ret);
574 nsresult rv2 = Reset();
575
576 return NS_FAILED(rv) ? rv : rv2;
577 }
578
579 NS_IMETHODIMP
ExecuteStep(bool * _moreResults)580 Statement::ExecuteStep(bool *_moreResults)
581 {
582 PROFILER_LABEL("Statement", "ExecuteStep",
583 js::ProfileEntry::Category::STORAGE);
584
585 if (!mDBStatement)
586 return NS_ERROR_NOT_INITIALIZED;
587
588 // Bind any parameters first before executing.
589 if (mParamsArray) {
590 // If we have more than one row of parameters to bind, they shouldn't be
591 // calling this method (and instead use executeAsync).
592 if (mParamsArray->length() != 1)
593 return NS_ERROR_UNEXPECTED;
594
595 BindingParamsArray::iterator row = mParamsArray->begin();
596 nsCOMPtr<IStorageBindingParamsInternal> bindingInternal =
597 do_QueryInterface(*row);
598 nsCOMPtr<mozIStorageError> error = bindingInternal->bind(mDBStatement);
599 if (error) {
600 int32_t srv;
601 (void)error->GetResult(&srv);
602 return convertResultCode(srv);
603 }
604
605 // We have bound, so now we can clear our array.
606 mParamsArray = nullptr;
607 }
608 int srv = mDBConnection->stepStatement(mNativeConnection, mDBStatement);
609
610 if (srv != SQLITE_ROW && srv != SQLITE_DONE && MOZ_LOG_TEST(gStorageLog, LogLevel::Debug)) {
611 nsAutoCString errStr;
612 (void)mDBConnection->GetLastErrorString(errStr);
613 MOZ_LOG(gStorageLog, LogLevel::Debug,
614 ("Statement::ExecuteStep error: %s", errStr.get()));
615 }
616
617 // SQLITE_ROW and SQLITE_DONE are non-errors
618 if (srv == SQLITE_ROW) {
619 // we got a row back
620 mExecuting = true;
621 *_moreResults = true;
622 return NS_OK;
623 }
624 else if (srv == SQLITE_DONE) {
625 // statement is done (no row returned)
626 mExecuting = false;
627 *_moreResults = false;
628 return NS_OK;
629 }
630 else if (srv == SQLITE_BUSY || srv == SQLITE_MISUSE) {
631 mExecuting = false;
632 }
633 else if (mExecuting) {
634 MOZ_LOG(gStorageLog, LogLevel::Error,
635 ("SQLite error after mExecuting was true!"));
636 mExecuting = false;
637 }
638
639 return convertResultCode(srv);
640 }
641
642 NS_IMETHODIMP
GetState(int32_t * _state)643 Statement::GetState(int32_t *_state)
644 {
645 if (!mDBStatement)
646 *_state = MOZ_STORAGE_STATEMENT_INVALID;
647 else if (mExecuting)
648 *_state = MOZ_STORAGE_STATEMENT_EXECUTING;
649 else
650 *_state = MOZ_STORAGE_STATEMENT_READY;
651
652 return NS_OK;
653 }
654
655 ////////////////////////////////////////////////////////////////////////////////
656 //// mozIStorageValueArray (now part of mozIStorageStatement too)
657
658 NS_IMETHODIMP
GetNumEntries(uint32_t * _length)659 Statement::GetNumEntries(uint32_t *_length)
660 {
661 *_length = mResultColumnCount;
662 return NS_OK;
663 }
664
665 NS_IMETHODIMP
GetTypeOfIndex(uint32_t aIndex,int32_t * _type)666 Statement::GetTypeOfIndex(uint32_t aIndex,
667 int32_t *_type)
668 {
669 if (!mDBStatement)
670 return NS_ERROR_NOT_INITIALIZED;
671
672 ENSURE_INDEX_VALUE(aIndex, mResultColumnCount);
673
674 if (!mExecuting)
675 return NS_ERROR_UNEXPECTED;
676
677 int t = ::sqlite3_column_type(mDBStatement, aIndex);
678 switch (t) {
679 case SQLITE_INTEGER:
680 *_type = mozIStorageStatement::VALUE_TYPE_INTEGER;
681 break;
682 case SQLITE_FLOAT:
683 *_type = mozIStorageStatement::VALUE_TYPE_FLOAT;
684 break;
685 case SQLITE_TEXT:
686 *_type = mozIStorageStatement::VALUE_TYPE_TEXT;
687 break;
688 case SQLITE_BLOB:
689 *_type = mozIStorageStatement::VALUE_TYPE_BLOB;
690 break;
691 case SQLITE_NULL:
692 *_type = mozIStorageStatement::VALUE_TYPE_NULL;
693 break;
694 default:
695 return NS_ERROR_FAILURE;
696 }
697
698 return NS_OK;
699 }
700
701 NS_IMETHODIMP
GetInt32(uint32_t aIndex,int32_t * _value)702 Statement::GetInt32(uint32_t aIndex,
703 int32_t *_value)
704 {
705 if (!mDBStatement)
706 return NS_ERROR_NOT_INITIALIZED;
707
708 ENSURE_INDEX_VALUE(aIndex, mResultColumnCount);
709
710 if (!mExecuting)
711 return NS_ERROR_UNEXPECTED;
712
713 *_value = ::sqlite3_column_int(mDBStatement, aIndex);
714 return NS_OK;
715 }
716
717 NS_IMETHODIMP
GetInt64(uint32_t aIndex,int64_t * _value)718 Statement::GetInt64(uint32_t aIndex,
719 int64_t *_value)
720 {
721 if (!mDBStatement)
722 return NS_ERROR_NOT_INITIALIZED;
723
724 ENSURE_INDEX_VALUE(aIndex, mResultColumnCount);
725
726 if (!mExecuting)
727 return NS_ERROR_UNEXPECTED;
728
729 *_value = ::sqlite3_column_int64(mDBStatement, aIndex);
730
731 return NS_OK;
732 }
733
734 NS_IMETHODIMP
GetDouble(uint32_t aIndex,double * _value)735 Statement::GetDouble(uint32_t aIndex,
736 double *_value)
737 {
738 if (!mDBStatement)
739 return NS_ERROR_NOT_INITIALIZED;
740
741 ENSURE_INDEX_VALUE(aIndex, mResultColumnCount);
742
743 if (!mExecuting)
744 return NS_ERROR_UNEXPECTED;
745
746 *_value = ::sqlite3_column_double(mDBStatement, aIndex);
747
748 return NS_OK;
749 }
750
751 NS_IMETHODIMP
GetUTF8String(uint32_t aIndex,nsACString & _value)752 Statement::GetUTF8String(uint32_t aIndex,
753 nsACString &_value)
754 {
755 // Get type of Index will check aIndex for us, so we don't have to.
756 int32_t type;
757 nsresult rv = GetTypeOfIndex(aIndex, &type);
758 NS_ENSURE_SUCCESS(rv, rv);
759 if (type == mozIStorageStatement::VALUE_TYPE_NULL) {
760 // NULL columns should have IsVoid set to distinguish them from the empty
761 // string.
762 _value.SetIsVoid(true);
763 }
764 else {
765 const char *value =
766 reinterpret_cast<const char *>(::sqlite3_column_text(mDBStatement,
767 aIndex));
768 _value.Assign(value, ::sqlite3_column_bytes(mDBStatement, aIndex));
769 }
770 return NS_OK;
771 }
772
773 NS_IMETHODIMP
GetString(uint32_t aIndex,nsAString & _value)774 Statement::GetString(uint32_t aIndex,
775 nsAString &_value)
776 {
777 // Get type of Index will check aIndex for us, so we don't have to.
778 int32_t type;
779 nsresult rv = GetTypeOfIndex(aIndex, &type);
780 NS_ENSURE_SUCCESS(rv, rv);
781 if (type == mozIStorageStatement::VALUE_TYPE_NULL) {
782 // NULL columns should have IsVoid set to distinguish them from the empty
783 // string.
784 _value.SetIsVoid(true);
785 } else {
786 const char16_t *value =
787 static_cast<const char16_t *>(::sqlite3_column_text16(mDBStatement,
788 aIndex));
789 _value.Assign(value, ::sqlite3_column_bytes16(mDBStatement, aIndex) / 2);
790 }
791 return NS_OK;
792 }
793
794 NS_IMETHODIMP
GetBlob(uint32_t aIndex,uint32_t * _size,uint8_t ** _blob)795 Statement::GetBlob(uint32_t aIndex,
796 uint32_t *_size,
797 uint8_t **_blob)
798 {
799 if (!mDBStatement)
800 return NS_ERROR_NOT_INITIALIZED;
801
802 ENSURE_INDEX_VALUE(aIndex, mResultColumnCount);
803
804 if (!mExecuting)
805 return NS_ERROR_UNEXPECTED;
806
807 int size = ::sqlite3_column_bytes(mDBStatement, aIndex);
808 void *blob = nullptr;
809 if (size) {
810 blob = nsMemory::Clone(::sqlite3_column_blob(mDBStatement, aIndex), size);
811 NS_ENSURE_TRUE(blob, NS_ERROR_OUT_OF_MEMORY);
812 }
813
814 *_blob = static_cast<uint8_t *>(blob);
815 *_size = size;
816 return NS_OK;
817 }
818
819 NS_IMETHODIMP
GetBlobAsString(uint32_t aIndex,nsAString & aValue)820 Statement::GetBlobAsString(uint32_t aIndex, nsAString& aValue)
821 {
822 return DoGetBlobAsString(this, aIndex, aValue);
823 }
824
825 NS_IMETHODIMP
GetBlobAsUTF8String(uint32_t aIndex,nsACString & aValue)826 Statement::GetBlobAsUTF8String(uint32_t aIndex, nsACString& aValue)
827 {
828 return DoGetBlobAsString(this, aIndex, aValue);
829 }
830
831 NS_IMETHODIMP
GetSharedUTF8String(uint32_t aIndex,uint32_t * _length,const char ** _value)832 Statement::GetSharedUTF8String(uint32_t aIndex,
833 uint32_t *_length,
834 const char **_value)
835 {
836 if (_length)
837 *_length = ::sqlite3_column_bytes(mDBStatement, aIndex);
838
839 *_value = reinterpret_cast<const char *>(::sqlite3_column_text(mDBStatement,
840 aIndex));
841 return NS_OK;
842 }
843
844 NS_IMETHODIMP
GetSharedString(uint32_t aIndex,uint32_t * _length,const char16_t ** _value)845 Statement::GetSharedString(uint32_t aIndex,
846 uint32_t *_length,
847 const char16_t **_value)
848 {
849 if (_length)
850 *_length = ::sqlite3_column_bytes16(mDBStatement, aIndex);
851
852 *_value = static_cast<const char16_t *>(::sqlite3_column_text16(mDBStatement,
853 aIndex));
854 return NS_OK;
855 }
856
857 NS_IMETHODIMP
GetSharedBlob(uint32_t aIndex,uint32_t * _size,const uint8_t ** _blob)858 Statement::GetSharedBlob(uint32_t aIndex,
859 uint32_t *_size,
860 const uint8_t **_blob)
861 {
862 *_size = ::sqlite3_column_bytes(mDBStatement, aIndex);
863 *_blob = static_cast<const uint8_t *>(::sqlite3_column_blob(mDBStatement,
864 aIndex));
865 return NS_OK;
866 }
867
868 NS_IMETHODIMP
GetIsNull(uint32_t aIndex,bool * _isNull)869 Statement::GetIsNull(uint32_t aIndex,
870 bool *_isNull)
871 {
872 // Get type of Index will check aIndex for us, so we don't have to.
873 int32_t type;
874 nsresult rv = GetTypeOfIndex(aIndex, &type);
875 NS_ENSURE_SUCCESS(rv, rv);
876 *_isNull = (type == mozIStorageStatement::VALUE_TYPE_NULL);
877 return NS_OK;
878 }
879
880 ////////////////////////////////////////////////////////////////////////////////
881 //// mozIStorageBindingParams
882
883 BOILERPLATE_BIND_PROXIES(
884 Statement,
885 if (!mDBStatement) return NS_ERROR_NOT_INITIALIZED;
886 )
887
888 } // namespace storage
889 } // namespace mozilla
890