/* * value db_fetch_by_id(string $col_name,int64 $record_id) * value db_get_by_id(string $col_name,int64 $record_id) * Fetch a record using its unique ID from a given collection. * Parameter * col_name: Collection name * record_id: Record number (__id field of a JSON object) * Return * Record content success. NULL on failure (No such record). */ static int unqliteBuiltin_db_fetch_by_id(jx9_context *pCtx,int argc,jx9_value **argv) { unqlite_col *pCol; const char *zName; unqlite_vm *pVm; SyString sName; jx9_int64 nId; int nByte; int rc; /* Extract collection name */ if( argc < 2 ){ /* Missing arguments */ jx9_context_throw_error(pCtx,JX9_CTX_ERR,"Missing collection name and/or record ID"); /* Return NULL */ jx9_result_null(pCtx); return JX9_OK; } zName = jx9_value_to_string(argv[0],&nByte); if( nByte < 1){ jx9_context_throw_error(pCtx,JX9_CTX_ERR,"Invalid collection name"); /* Return NULL */ jx9_result_null(pCtx); return JX9_OK; } /* Extract the record ID */ nId = jx9_value_to_int(argv[1]); SyStringInitFromBuf(&sName,zName,nByte); pVm = (unqlite_vm *)jx9_context_user_data(pCtx); /* Fetch the collection */ pCol = unqliteCollectionFetch(pVm,&sName,UNQLITE_VM_AUTO_LOAD); if( pCol ){ /* Fetch the desired record */ jx9_value *pValue; pValue = jx9_context_new_scalar(pCtx); if( pValue == 0 ){ jx9_context_throw_error(pCtx,JX9_CTX_ERR,"Jx9 is running out of memory"); jx9_result_null(pCtx); return JX9_OK; }else{ rc = unqliteCollectionFetchRecordById(pCol,nId,pValue); if( rc == UNQLITE_OK ){ jx9_result_value(pCtx,pValue); /* pValue will be automatically released as soon we return from this function */ }else{ /* No such record, return null */ jx9_result_null(pCtx); } } }else{ /* No such collection, return null */ jx9_result_null(pCtx); } return JX9_OK; }
/* * Fetch the next record from a given collection. */ UNQLITE_PRIVATE int unqliteCollectionFetchNextRecord(unqlite_col *pCol,jx9_value *pValue) { int rc; for(;;){ if( pCol->nCurid >= pCol->nLastid ){ /* No more records, reset the record cursor ID */ pCol->nCurid = 0; /* Return to the caller */ return SXERR_EOF; } rc = unqliteCollectionFetchRecordById(pCol,pCol->nCurid,pValue); /* Increment the record ID */ pCol->nCurid++; /* Lookup result */ if( rc == UNQLITE_OK || rc != UNQLITE_NOTFOUND ){ break; } } return rc; }