Showing posts with label SQL. Show all posts
Showing posts with label SQL. Show all posts

Wednesday, 11 April 2012

How to use Rebdb

RebDB is a simple database script, you can access to all the most common database function using it. You can downland RebDB from: http://www.dobeash.com/RebDB/RebDB-203.zip

To access it you can use rebol commands or SQL commands, this guide will cover both solution.
First of all you have to load all the script this way:

>> do %db.r


Table of contents:

Using just rebol commands


In order to create a table, you have to use the command db-create, this way:

>> db-create my-table [ID Date Note]
== true

Ok, we create a table named my-table with the columns name: ID, Date and Note.
I didn't specify a type of value for each column, so if I want a description of the table using the db-desc command I obtain:

>> db-desc my-table
== [ID none! Date none! Note none!]


To insert values the command is: db-insert


db-insert my-table [next 1-Jan-2000 "Note"]


Note the use of the special word next to set a new value to the ID, this way we have a unique key (but it isn't necessary).

>> db-insert my-table [next 1-Jan-2000 "Note"]
== [1 1-Jan-2000 "Note"]


Remember that you have to insert always the correct numbers of items of the row:

>> db-insert my-table [next 1-Jan-2000 ]
** User Error: Invalid number of values
** Near: to error! :value


The command db-rows show you the numbers of row:

>> db-rows my-table
== 1


The command db-show shows the current statistics:

>> db-show
== [
"Host" "PC19"
"Address" 192.1.1.1
"Memory" 8023323
"Tables" 1
]

The command db-tables shows the current open tables:

>> db-tables
== [my-table 3 1 true 10-Apr-2012/17:54:47 10-Apr-2012/18:14:42 7 true]

It describes table name, columns, rows, sorted flag, first modify time, last modify time, hits, dirty flag.

Until you don't use db-commit, your changes aren't saved on the disks! So let's use it:

>> db-commit *
== true

Using the asterisk, we save all tables open, I could use also:

>> db-commit my-table
== true


To delete a table there is the db-drop command.

To make a query there is the db-select command:


>> db-select/where * my-table [id = 1]
== [1 1-Jan-2000 "Note"]


Examples:

>> db-insert my-table reduce ['next now to-string now]
== [2 10-Apr-2012/18:43:32+2:00 "10-Apr-2012/18:43:32+2:00"]
>> db-insert my-table reduce ['next now/time to-string now/date ]
== [3 18:43:52 "10-Apr-2012"]
>> db-select * my-table
== [1 1-Jan-2000 "Note" 2 10-Apr-2012/18:43:32+2:00 "10-Apr-2012/18:43:32+2:00" 3 18:43:52 "10-Apr
-2012"]
>> db-select/header * my-table
== [1 1-Jan-2000 "Note" 2 10-Apr-2012/18:43:32+2:00 "10-Apr-2012/18:43:32+2:00" 3 18:43:52 "10-Apr
-2012" [my-table ID Date Note]]


Using the refinement header you always know table name and columns.

The reserved functions of db.r are:

  • db-desc 
  • db-describe 
  • db-rows 
  • db-show 
  • db-table? 
  • db-tables 
  • db-close 
  • db-commit 
  • db-create 
  • db-drop 
  • db-rollback 
  • db-lookup 
  • db-select 
  • db-delete 
  • db-insert 
  • db-truncate 
  • db-update 
  • db-replay
Use the question mark for more information:

>> ? db-desc
USAGE:
DB-DESC 'table /header

DESCRIPTION:
Information about the columns of a table.
DB-DESC is a function value.

ARGUMENTS:
table -- (Type: word)

REFINEMENTS:
/header -- Append header block


Using SQL commands

The first thing to do is to load the db.r script and the SQL.r client:

>> do %db.r
== true
>> do %SQL.r
RebDB v2.0.3

RUN> commit *
true

login.sql ran in 0:00 second(s)
SQL>


Every time you launch SQL.r, it always run the SQL script login.sql. You can use it to do automatic tasks.

Now you are in the SQL cliet, so it accept the SQL grammar.

In order to create a table there is the command create:

SQL> create my-table2 [ID Date Note ]
true

The command describe show you how is made a table:

SQL> describe my-table2
Column Type
-------- ----
ID none
Date none
Note none

3 row(s) selected in 0:00 seconds


The type is just the first row types.

Let's try to insert some values:

SQL> insert into my-table2 values reduce ['next now/date "Note1" ]
ID Date Note
-- ----------- -----
1 11-Apr-2012 Note1

1 row(s) selected in 0:00 seconds


Remember that you are always in a rebol console, so you can mix rebol and SQL.

If we check the table now, here it is the result:

SQL> desc my-table2
Column Type
------ -------
ID integer
Date date
Note string

3 row(s) selected in 0:00 seconds


Here the reserved word list of the SQL client:
  • avg
  • by
  • count
  • desc
  • distinct
  • explain
  • from
  • group
  • header
  • having
  • into
  • joins
  • max
  • min
  • on
  • order
  • replaces
  • rowid
  • set
  • std
  • sum
  • table
  • to
  • values
  • where
  • with

Let's insert more data:

SQL> insert into my-table2 values reduce ['next now/date + 1 "Note2" ]
ID Date Note
-- ----------- -----
2 12-Apr-2012 Note2

1 row(s) selected in 0:00 seconds
SQL> insert into my-table2 values reduce ['next now/date + 3 "Note3" ]
ID Date Note
-- ----------- -----
3 14-Apr-2012 Note3

1 row(s) selected in 0:00 seconds

You can change one or more values with the update command:

SQL> update my-table2 set Date 14-Apr-2014 where [Note = "Note3" ]
1 row(s) updated in 0:00 seconds


With select you can retrieve the data:

SQL> select * my-table2
ID Date Note
-- ----------- -----
1 11-Apr-2012 Note1
2 12-Apr-2012 Note2
3 14-Apr-2014 Note3

3 row(s) selected in 0:00 seconds

SQL> select * my-table2 where [date > 1-1-2013]
ID Date Note
-- ----------- -----
3 14-Apr-2014 Note3

1 row(s) selected in 0:00 seconds


Remember: nothing is written on the disk, until you use commit:

SQL> commit *
true


The command rows show you the numbers of row of a table:

SQL> rows my-table2
3 row(s)

The command tables show you the open tables:

SQL> tables
Table Cols Rows Sorted? Loaded Accessed Hits Dirty?
--------- ---- ---- ------- -------------------- -------------------- ---- ------
my-table2 3 3 true 11-Apr-2012/13:04:37 11-Apr-2012/13:42:55 9 false

1 row(s) selected in 0:00 seconds


The command table? say to you if a table exits:

SQL> table? my-tabe2
false
SQL> table? my-table2
true



See also

For more information see also:

Monday, 26 March 2012

CSV importation

CSV is a very common way to write a table of data. It's very easy to import it using parse, here a simple function:

csv-import: func [
    "Import a CSV file transforming it in a series."
    file [file!] "CSV file"
    /local temp temp2
    ] [
    temp: read/lines file
    temp2: copy []
    foreach item temp [append/only temp2 (parse/all item ",") ]
    return temp2    
    ]
   


And here an example, the following table:
TITLE AUTHOR Editor
Robots and Empire Isaac Asimov Mondadori
Afternoon of Earth Brian W. Aldiss Minotauro
Absolute OpenBSD "2d Edition" Michael W. Lucas No Starch Press
The space merchants Frederik Pohl, C. M. Kornbluth Mondadori

It can be represented in CSV format this way:

TITLE,AUTHOR,EDITOR
Robots and Empire,Isaac Asimov,Mondadori
Afternoon of Earth,Brian W. Aldiss,Minotauro
"Absolute OpenBSD ""2d Edition""",Michael W. Lucas,No Starch Press
The space merchants,"Frederik Pohl, C. M. Kornbluth",Mondadori


Writing it on temp.csv file and using the above functions:

>> a: csv-import %temp.csv
== [["TITLE" "AUTHOR" "EDITOR"] ["Robots and Empire" "Isaac Asimov" "Mondadori"] ["Afternoon of Earth" "Brian W. Aldiss" "Minotauro...

So it's extremely easy to retrieve data:

>> a/1/1
== "TITLE"
>> a/1/2
== "AUTHOR"
>> a/2/1
== "Robots and Empire"

Or this way:

>> for i 1 5 1 [print a/:i/1]
TITLE
Robots and Empire
Afternoon of Earth
Absolute OpenBSD
The space merchants

Monday, 19 December 2011

SQLite

SQLite is SQL database engine small and ready to use. There are many Rebol scripts that handle SQLite, if you don't know this light SQL engine, you should visit:
http://www.sqlite.org/

The first script  I'll show you  is the following:
http://www.rebol.org/view-script.r?script=btn-sqlite.r

you have to put sqlite executable in the same directory of the script (Windows) or in /usr/bin/ (Linux). It's slow but it works this way:

>> do %btn-sqlite.r
>> db: open btn://localhost/test.db3
>> insert db "CREATE TABLE t1 (a int, b text, c text)"
== true
>> repeat i 25 [
[ insert db [{INSERT INTO t1 VALUES (?, ?, ?)} i (join "cool" i) (join "cool"
(25 + 1 - i))]
[ ]
== true
>> insert db "SELECT * FROM t1"
== true
>> probe db/locals/columns
["a" "b" "c"]
== ["a" "b" "c"]
>> res: copy/part db 10
== [["1" "cool1" "cool25"] ["2" "cool2" "cool24"] ["3" "cool3" "cool23"] ["4" "coo
l4" "cool22"] ["5" "cool5" "cool21"] ["6" "cool6"...
>> probe res
[["1" "cool1" "cool25"] ["2" "cool2" "cool24"] ["3" "cool3" "cool23"] ["4" "cool4"
"cool22"] ["5" "cool5" "cool21"] ["6" "cool6" "cool20"] ["7" "cool7" "cool19"] ["
8" "cool8" "cool18"] ["9" "cool9" "cool17"] ["10" "cool10" "cool16"]]
== [["1" "cool1" "cool25"] ["2" "cool2" "cool24"] ["3" "cool3" "cool23"] ["4" "coo
l4" "cool22"] ["5" "cool5" "cool21"] ["6" "cool6"...
>> probe length? res
10
== 10
>> insert db "DROP TABLE t1"
== true
>> close db


The second script is a little bit complex, you have to download the DLL or the Linux library in the script folder, then you can download the following script:
http://www.rebol.org/view-script.r?script=sqlite3.r

modify the script with the correct path to your sql3 library
Windows
sql: load/library %sqlite3.dll
or Linux
sql: load/library %libsqlite3.so
Here how it works:

>> db: sqlite-open %test.db
== 16121296
>> sqlite-exec db "CREATE TABLE t1 (a int , b text , c text);"
== []
>> sqlite-exec db "CREATE TABLE t2 (a int , b text , c text);"
== []
>> ; Testing of 1000 inserts one transaction at a time.
>> t: now/time/precise
== 12:14:23.765
>> repeat i 1000 [ sqlite-exec db reduce [{INSERT INTO t1 VALUES (?,"cool1","cool1");} i]
== []
>> delta: now/time/precise - t
== 0:02:22.422
>> print join "elapsed time = " delta
elapsed time = 0:02:22.422
>> ; Testing of 1000 inserts in one global transaction.
>> t: now/time/precise
== 12:26:49.687
>> sqlite-exec db "begin transaction;"
== []
>> repeat i 1000 [ sqlite-exec db reduce [{INSERT INTO t2 VALUES (?,"cool2","cool2");} i]
== []
>> sqlite-exec db "commit transaction;"
== []
>> delta: now/time/precise - t
== 0:00:00.281
>> print join "elapsed time = " delta
elapsed time = 0:00:00.281
>> ; Select now all data from both tables.
>> ;Just go through "res" block if you want to see the results.

>> res: copy []
== []
>> t: now/time/precise
== 12:29:49.875
>> repeat i 1000 [
insert tail res sqlite-exec/names db reduce ["SELECT * FROM t1 WHERE a=?;" i]
insert tail res sqlite-exec/names db reduce ["SELECT * FROM t2 WHERE a=?;" i]
]
== []
>> delta: now/time/precise - t
== 0:00:04.828
>> print join "elapsed time = " delta
elapsed time = 0:00:04.828
>> sqlite-close db


Then you can attach more databases in a single database, Robert Paluch, alias BobikCZ, shows us how to do it:

do %sqlite3.r ;; load sqlite driver
db: sqlite-open %myfirstdb.db ;; open first db file
sqlite-exec db {attach database 'myseconddb.db' as myseconddb} ;; attach my second db file
res: sqlite-exec db {select * from myseconddb.mytable} ;;resulting select etc..
;; there can be use also joins of tables


If you need to use SQLite over internet, you can with this script:
http://www.rebol.org/view-script.r?script=techfell-protocol.r
Here how it works:

db: open techfell://user:password@webhost.com
insert db "CREATE TABLE t1 (a int, b text, c text)"
repeat i 25 [
insert db [{INSERT INTO t1 VALUES (?, ?, ?)} i (join "cool" i) (join "cool" (25 + 1 - i))]
]
insert db "SELECT * FROM t1"
probe db/locals/columns
res: copy/part db 10
probe res
probe length? res
insert db "DROP TABLE t1"
close db

Monday, 18 July 2011

Libraries

Hello world,
let see this week some Rebol libraries sites:

http://dobeash.com/development.html

  • RebGUI: Lightweight and fantastic alternative to VID that was designed and built from the ground-up on top of REBOL/View.
  • RebDB: Small but highly efficient Pseudo-Relational Database.
  • SQLite Driver: Uses the library access features of REBOL/Pro to provide native REBOL access to SQLite databases.
  • iPhone Development Resources: Details the two iPhone development approaches: Web (using Dashcode & Webkit) and Native (using Xcode and the SDK), plus various useful links.

http://softinnov.org/

  • DRIVERS: MySQL, PostgresQL, LDAP
  • LIBRARIES: Async Call , NTLM , Captcha, NT Services, Scheduler
  • FRAMEWORKS: UniServe
  • MISC: ReBOX! game
  • PRODUCTS: Cheyenne


http://www.rebol.it/power-mezz/   a lot of useful functions!

One-liner of the week:

request-date