KirbyBase 2.3: How to insert record if key does not exist

B

basi

Hello,

I have a word frequency table, thus:

tgl_tokens = db.create_table(
:tgltokens,
:tgltoken, :String,
:count, :Integer)

With data from a hash, I'm trying to insert a record into the table,
but only if the key does not exist in the table. If it does, then add
the new frequency count into the stored frequency count.

tgl_texts.select.each do |t|
freq = Hash.new(0)
for word in t.text.to_s.downcase.tr_s('^A-Za-z-',' ').split(' ')
freq[word] += 1
end
freq.delete("")

freq.each do |w,c|
-- if w exists in tgl_tokens, then
-- add c to the stored count value of w
-- else
tgl_tokens.insert do |token|
token.tgltoken = w
token.count = c
end
-- end
end
end

Basically the KirbyBase / Ruby syntax that eludes me corresponds to
this SQL snippet:

begin
select 1 into v_dummy
from tgltokens
where tgltoken = w;
-- if found then
update tgltokens
set count = count + c
where tgltoken = w;
exception
when no_data_found then
insert into tgltokens values (w, c);
end

Thanks!
basi
 
J

Jamey Cribbs

basi said:
Hello,

I have a word frequency table, thus:

tgl_tokens = db.create_table(
:tgltokens,
:tgltoken, :String,
:count, :Integer)

With data from a hash, I'm trying to insert a record into the table,
but only if the key does not exist in the table. If it does, then add
the new frequency count into the stored frequency count.

tgl_texts.select.each do |t|
freq = Hash.new(0)
for word in t.text.to_s.downcase.tr_s('^A-Za-z-',' ').split(' ')
freq[word] += 1
end
freq.delete("")

freq.each do |w,c|
-- if w exists in tgl_tokens, then
-- add c to the stored count value of w
-- else
tgl_tokens.insert do |token|
token.tgltoken = w
token.count = c
end
-- end
end
end

Basically the KirbyBase / Ruby syntax that eludes me corresponds to
this SQL snippet:

begin
select 1 into v_dummy
from tgltokens
where tgltoken = w;
-- if found then
update tgltokens
set count = count + c
where tgltoken = w;
exception
when no_data_found then
insert into tgltokens values (w, c);
end
If I understand you correctly, you would simply do this:

freq.each do |w,c|
if tgl_tokens.select { |token| token.tgltoken == w }.size > 0
tgl_tokens.update { |token| token.tgltoken == w }.set do |token|
token.count += c
end
else
tgl_tokens.insert do |token|
token.tgltoken = w
token.count = c
end
end
end

Jamey Cribbs
 
B

basi

Yes, this works well. Now I know how to check if a record exists on the
basis of the value of a field.

Thanks again!
basi
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top