I have a program which opens up a bunch of tars, looks for certain file names, and then adds those tars and filenames to a sqlite database. The same file names occur in multiple places within the tar, so I created a table which points to a unique tar/file tuple and contains a counter for how many times that tuple appears in the tar. Here is the code for the table creation:
DB = Sequel.sqlite('tars.db')
DB.create_table? :tars do
primary_key :id
column :name, String, :unique=>true
end
DB.create_table? :pfiles do
primary_key :id
column :fname, String, :unique=>true
column :nname, String, :unique=>true, :null=>true, :default=>nil
end
DB.create_table? :pfiles_tars do
primary_key :id
foreign_key :tar_id, :tars
foreign_key :pfile_id, :pfiles
unique [:tar_id, :pfile_id]
column :counter, Integer, :default => 1
end
class Tar < Sequel::Model
many_to_many :pfiles
end
class Pfile < Sequel::Model
many_to_many :tars
end
class Pfiles_Tar < Sequel::Model
end
At some point I create the tar entry and the file entry. Then I want to check if an entry exists in the joint table. If it does, increment the counter and create it if not. This is the code that I thought should do this:
sql_tar = Tar.find_or_create(:name => tfile)
sql_pfile = Pfile.find_or_create(:fname => f)
if Pfiles_Tar.find(:tar_id => sql_tar[:id], :pfile_id => sql_pfile[:id])
Pfiles_Tar.find(:tar_id => sql_tar[:id], :pfile_id => sql_pfile[:id]).update(:counter => Sequel.expr(1) + :counter)
else
Pfiles_Tar.create(:tar_id => sql_tar[:id], :pfile_id => sql_pfile[:id])
end
But for some reason this doubles the number of table entries I have in the joint table. If I change the else statement to find_or_create instead of just create
Pfiles_Tar.find_or_create(:tar_id => sql_tar[:id], :pfile_id => sql_pfile[:id])
then I get the correct number, but I fail to see why. Can anyone explain what I am doing wrong? I am pretty new to both Ruby and Sequel.
Aucun commentaire:
Enregistrer un commentaire