Which way is better in optimal terms for use Active Record query - mysql

Actually I am working in a WebSite that uses MySql DataBase and I want to know which of these two forms is better to make:
Using the object to create others queries:
#inform=Dailyinform.where(:scheduled_start => (##datestart..##dateend)).order("scheduled_start DESC").searchServer(##serverSearch).searchDomain(##domain_name)
#dailyInforms=#inform.where.not(:status => 'COMPLETED').searchFailed.page(params[:page]).per_page(5000)
#restarts=#inform.searchRelaunched.order("scheduled_start DESC").page(params[:page]).per_page(5000)
or Directly with the ActiveRecord Model - Base:
#dailyInforms=Dailyinform.where.not(:status => 'COMPLETED').where(:scheduled_start => (##datestart..##dateend)).order("scheduled_start DESC").searchFailed(##serverSearch).page(params[:page]).per_page(5000)
#restarts=Dailyinform.where(:scheduled_start => (##datestart..##dateend)).order("scheduled_start DESC").search2(##serverSearch).page(params[:page]).per_page(5000)
My question arose because i felt that the second way is faster that the first way. Maybe is just my impression! Thanks

When it comes to performance I don't think there will be any difference. Active record is good at being lazy when it comes to making queries, it won't perform any until you actually try to use the result.
For this reason I would say that the first method is preferable since it is more DRY.

Related

Yii model relationship, how is it important?

It is my first time to use yii and unlike my old programming style, i notice that it use relationship automatically in its model.
public function relations()
{
return array(
'author'=>array(self::BELONGS_TO, 'User', 'author_id'),
'categories'=>array(self::MANY_MANY, 'Category',
'tbl_post_category(post_id, category_id)'),
);
}
I'm not used in doing this MySQL relationship. my old programming habit is connecting/manipulating the data to the php program itself.. To clarify my question, is this yii model relationship important? if i dont use this method, will i encounter problems?
Yii relations are very useful and if you work with it you will see that it will make you do less coding and make your code more readable.
while it is so much used in Yii applications, if you don't use relations, you won't get into any trouble, it is supposed to help you code and develop faster.
like if you looked at Yii blog, you have relation between Post model and Comments model, and you could go like this:
$post = Post::model()->findByPk( $id ); // find one post
$allCommentsRelated = $post->comments; // just one line for all search query and instanciating models
BTW in relations, there are two type of loading:
lazy loading (this is default mechanism)
eager loading
you have to know your scenario, and choose one that suites that scenario best

Why can't we use :key => value in CodeIgniter's DB library?

I've used to use something like this with the regular PHP's PDO:
$data = array(
":name" => "james",
":location" => "Palo Alto, CA"
);
SQL:
SELECT * FROM people WHERE name LIKE :name and location = :location
When i've started to use Codeigniter, it won't let me use namespace keys anymore, it only accepts the traditional ? marks.
Anyway to fix that?
Unfortunately, no, there isn't. Not with CodeIgniter natively.
It helps to remember that CodeIgniter's roots are in PHP4 compliant code (and some of the things they did are not even the most recent PHP 4 -- they use a custom file searching system which is substantially slower than glob which was around by PHP 4.3 (4.4? It was around for the minimum required version), this means that the old '?' was really the best option at the time.
If you feel better about using the newer style, then you might be better off using the PDO classes. They're better and faster anyway. (Frankly, I only use CI's DB classes for compliance. I have a very strong preference for PDO's, especially since all of the modern frameworks seem to use them). I will warn you, though, that the use of PDO's completely invalidates the ActiveRecord framework offered by CodeIgniter. You will not be able to use $this->db->select()->from('table')->where($array)->limit(1,4); More importantly, you will need to know the differences between the different dialects of SQL, something CodeIgniter lets you avoid (and your code won't be DB agnostic anymore).
Maybe you will be more comfortable using Active Record in Codeigniter and doing something like
$this->db->like();
Look here: http://codeigniter.com/user_guide/database/active_record.html

Paper form to database

I am doing a Rails 3 app that replaces a paper form for a company. The paper form spans two pages and contains a LOT of fields, checkboxes, drop downs, etc.
I am wondering how to model that in the DB - one approach is to just create a field in the DB for every field on the form (normalized of course). That will make it somewhat difficult to ad or remove fileds since a migration will be needed. An other approach is to do some kind of key/value store (no - MongoDB/CouchDB is not an option - MySQL is required). Doing key/value will be very flexible but will be a pain to query. And it will directly work against ActiveRecord?
Anyone have a great solution for this?
Regards,
Jacob
I would recommend that you model the most common attributes as separate database fields. Once you have setup as many fields as possible then fall back to using a key-value setup for your pseudo-random attributes. I'd recommend a simple approach of storing a Hash through the ActiveRecord method serialize. For example:
class TPS < ActiveRecord::Base
serialize :custom, Hash
end
#tps = TPS.create(:name => "Kevin", :ssn => "123-456-789", :custom => { :abc => 'ABC', :def => )'DEF' })
#tps.name # Kevin
#tps.ssn # 123-456-789
#tps.custom[:abc] # ABC
#tps.custom[:def] # DEF
If your form is fairly static, go ahead and make a model for it, that's a reasonable approach even if it seems rather rudimentary. It's not your fault the form is so complicated, you're just coming up with a solution that takes that into account. Migrations to make adjustments to this are really simple to implement and easy to understand.
Splitting it up into a key/value version would be better but would take a lot more engineering. If you expect that this form will be subject to frequent and radical revisions it may make more sense to build for the future in this regard. You can see an example of the sort of form-builder you might want to construct at something like WuFoo but of course building form builders is not to be taken lightly.

Group functions of similar functionality

Sometimes I come across this problem where you have a set of functions that obviously belong to the same group. Those functions are needed at several places, and often together.
To give a specific example: consider the filemtime, fileatime and filectime functions. They all provide a similar functionality. If you are building something like a filemanager, you'll probably need to call them one after another to get the info you need. This is the moment that you get thinking about a wrapper. PHP already provides stat, but suppose we don't have that function.
I looked at the php sourcecode to find out how they solved this particular problem, but I can't really find out what's going on.
Obviously, if you have a naive implementation of such a grouping function, say filetimes, would like this:
function filetimes($file) {
return array(
'filectime' => filectime($file)
,'fileatime' => fileatime($file)
,'filemtime' => filemtime($file)
);
}
This would work, but incurs overhead since you would have to open a file pointer for each function call. (I don't know if it's necessary to open a file pointer, but let's assume that for the sake of the example).
Another approach would be to duplicate the code of the fileXtime functions and let them share a file pointer, but this obviously introduces code duplication, which is probably worse than the overhead introduced in the first example.
The third, and probably best, solution I came up with is to add an optional second parameter to the fileXtime functions to supply a filepointer.
The filetimes functions would then look like this:
function filetimes($file) {
$fp = fopen($file, 'r');
return array(
'filectime' => filectime($file, $fp)
,'fileatime' => fileatime($file, $fp)
,'filemtime' => filemtime($file, $fp)
);
}
Somehow this still feels 'wrong'. There's this extra parameter that is only used in some very specific conditions.
So basically the question is: what is best practice in situations like these?
Edit:
I'm aware that this is a typical situation where OOP comes into play. But first off: not everything needs to be a class. I always use an object oriented approach, but I also always have some functions in the global space.
Let's say we're talking about a legacy system here (with these 'non-oop' parts) and there are lots of dependencies on the fileXtime functions.
tdammer's answer is good for the specific example I gave, but does it extend to the broader problem set? Can a solution be defined such that it is applicable to most other problems in this domain?
Use classes, Luke.
I'd rewrite the fileXtime functions to accept either a filename or a file handle as their only parameter. Languages that can overload functions (like C++, C# etc) can use this feature; in PHP, you'd have to check for the type of the argument at run time.
Passing both a filename and a file handle would be redundant, and ambiguous calls could be made:
$fp = fopen('foo', 'r');
$times = file_times('bar', $fp);
Of course, if you want to go OOP, you'd just wrap them all in a FileInfo class, and store a (lazy-loaded?) private file handle there.

LinqToSql and full text search - can it be done?

Has anyone come up with a good way of performing full text searches (FREETEXT() CONTAINS()) for any number of arbitrary keywords using standard LinqToSql query syntax?
I'd obviously like to avoid having to use a Stored Proc or have to generate a Dynamic SQL calls.
Obviously I could just pump the search string in on a parameter to a SPROC that uses FREETEXT() or CONTAINS(), but I was hoping to be more creative with the search and build up queries like:
"pepperoni pizza" and burger, not "apple pie".
Crazy I know - but wouldn't it be neat to be able to do this directly from LinqToSql? Any tips on how to achieve this would be much appreciated.
Update: I think I may be on to something here...
Also: I rolled back the change made to my question title because it actually changed the meaning of what I was asking. I know that full text search is not supported in LinqToSql - I would have asked that question if I wanted to know that. Instead - I have updated my title to appease the edit-happy-trigger-fingered masses.
I've manage to get around this by using a table valued function to encapsulate the full text search component, then referenced it within my LINQ expression maintaining the benefits of delayed execution:
string q = query.Query;
IQueryable<Story> stories = ActiveStories
.Join(tvf_SearchStories(q), o => o.StoryId, i => i.StoryId, (o,i) => o)
.Where (s => (query.CategoryIds.Contains(s.CategoryId)) &&
/* time frame filter */
(s.PostedOn >= (query.Start ?? SqlDateTime.MinValue.Value)) &&
(s.PostedOn <= (query.End ?? SqlDateTime.MaxValue.Value)));
Here 'tvf_SearchStories' is the table valued function that internally uses full text search
Unfortunately LINQ to SQL does not support Full Text Search.
There are a bunch of products out there that I think could: Lucene.NET, NHibernate Search comes to mind. LINQ for NHibernate combined with NHibernate Search would probably give that functionality, but both are still way deep in beta.