]> gitweb.factorcode.org Git - factor.git/blob - basis/db/db-docs.factor
cb697a7db75929c624f59672a7ffc282bfa76a74
[factor.git] / basis / db / db-docs.factor
1 ! Copyright (C) 2008 Doug Coleman.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: classes kernel help.markup help.syntax sequences
4 alien assocs strings math quotations db.private ;
5 IN: db
6
7 HELP: db-connection
8 { $description "The " { $snippet "db-connection" } " class is the superclass of all other database classes. It stores a " { $snippet "handle" } " to the database as well as insert, update, and delete queries. Stores the current database object as a dynamic variable." } ;
9
10 HELP: new-db-connection
11 { $values { "class" class } { "obj" db-connection } }
12 { $description "Creates a new database object from a given class with caches for prepared statements. Does not actually connect to the database until " { $link db-open } " or " { $link with-db } " is called." }
13 { $notes "User-defined databases must call this constructor word instead of " { $link new } "." } ;
14
15 HELP: db-open
16 { $values { "db" "a database configuration object" } { "db-connection" db-connection } }
17 { $description "Opens a database using the configuration data stored in a " { $snippet "database configuration object" } "tuple. The database object now references a database handle that must be cleaned up. Therefore, it is better to use the " { $link with-db } " combinator than calling this word directly." } ;
18
19 HELP: db-close
20 { $values { "handle" alien } }
21 { $description "Closes a database using the handle provided. Use of the " { $link with-db } " combinator is preferred over manually opening and closing databases so that resources are not leaked." } ;
22
23 { db-open db-close with-db } related-words
24
25 HELP: dispose-statements
26 { $values { "assoc" assoc } }
27 { $description "Disposes an associative list of statements." } ;
28
29 HELP: statement
30 { $description "A " { $snippet "statement" } " stores the information about a statement, such as the SQL statement text, the in/out parameters, and type information." } ;
31
32 HELP: result-set
33 { $description "An object encapsulating a raw SQL result object. There are two ways in which a result set can be accessed, but they are specific to the database backend in use."
34 { $subsections
35     "db-random-access-result-set"
36     "db-sequential-result-set"
37 }
38 } ;
39
40 HELP: new-result-set
41 { $values
42      { "query" "a query" } { "handle" alien } { "class" class }
43      { "result-set" result-set } }
44 { $description "Creates a new " { $link result-set } " object of type " { $snippet "class" } "." } ;
45
46 HELP: new-statement
47 { $values { "sql" string } { "in" sequence } { "out" sequence } { "class" class } { "statement" statement } }
48 { $description "Makes a new statement object from the given parameters." } ;
49
50 HELP: bind-statement
51 { $values
52      { "obj" object } { "statement" statement } }
53 { $description "Sets the statement's " { $slot "bind-params" } " and calls " { $link bind-statement* } " to do the database-specific bind. Sets " { $slot "bound?" } " to true if binding succeeds." } ;
54
55 HELP: bind-statement*
56 { $values
57      { "statement" statement } }
58 { $description "Does a low-level bind of the SQL statement's tuple parameters if the database requires. Some databases should treat this as a no-op and bind instead when the actual statement is run." } ;
59
60 HELP: <simple-statement>
61 { $values { "string" string } { "in" sequence } { "out" sequence }
62     { "statement" statement } }
63 { $description "Makes a new simple statement object from the given parameters.." }
64 { $warning "Using a simple statement can lead to SQL injection attacks in PostgreSQL. The Factor database implementation for SQLite only uses " { $link <prepared-statement> } " as the sole kind of statement; simple statements alias to prepared ones." } ;
65
66 HELP: <prepared-statement>
67 { $values { "string" string } { "in" sequence } { "out" sequence }
68     { "statement" statement } }
69 { $description "Makes a new prepared statement object from the given parameters. A prepared statement's parameters will be escaped by the database backend to avoid SQL injection attacks. Prepared statements should be preferred over simple statements." } ;
70
71 HELP: prepare-statement
72 { $values { "statement" statement } }
73 { $description "For databases which implement a method on this generic, it does some internal processing to ready the statement for execution." } ;
74
75 HELP: low-level-bind
76 { $values
77      { "statement" statement } }
78 { $description "For use with prepared statements, methods on this word should bind the datatype in the SQL spec to its identifier in the SQL string. To name bound variables, SQLite uses identifiers in the form of " { $snippet ":name" } ", while PostgreSQL uses increasing numbers beginning with a dollar sign, e.g. " { $snippet "$1" } "." } ;
79
80 HELP: query-results
81 { $values { "query" object }
82     { "result-set" result-set }
83 }
84 { $description "Returns a " { $link result-set } " object representing the results of a SQL query. See " { $link "db-result-sets" } "." } ;
85
86 HELP: #rows
87 { $values { "result-set" result-set } { "n" integer } }
88 { $description "Returns the number of rows in a result set." } ;
89
90 HELP: #columns
91 { $values { "result-set" result-set } { "n" integer } }
92 { $description "Returns the number of columns in a result set." } ;
93
94 HELP: row-column
95 { $values { "result-set" result-set } { "column" integer }
96     { "obj" object }
97 }
98 { $description "Returns the value indexed by " { $snippet "column" } " in the current row of a " { $link result-set } "." } ;
99
100 HELP: row-column-typed
101 { $values { "result-set" result-set } { "column" integer }
102     { "sql" "sql" } }
103 { $description "Returns the value indexed by " { $snippet "column" } " in the current row of a " { $link result-set } " and converts the result based on a type stored in the " { $link result-set } "'s " { $slot "out-params" } "." } ;
104
105 HELP: advance-row
106 { $values { "result-set" result-set } }
107 { $description "Advanced the pointer to an underlying SQL result set stored in a " { $link result-set } " object." } ;
108
109 HELP: more-rows?
110 { $values { "result-set" result-set } { "?" boolean } }
111 { $description "Returns true if the " { $link result-set } " has more rows to traverse." } ;
112
113
114
115 HELP: begin-transaction
116 { $description "Begins a new transaction. User code should make use of the " { $link with-transaction } " combinator." } ;
117
118 HELP: commit-transaction
119 { $description "Commits a transaction. User code should make use of the " { $link with-transaction } " combinator." } ;
120
121 HELP: in-transaction
122 { $description "A variable that is set true when a transaction is in progress." } ;
123
124 HELP: in-transaction?
125 { $values
126      { "?" boolean } }
127 { $description "Returns true if there is currently a transaction in progress in this scope." } ;
128
129 HELP: query-each
130 { $values
131      { "statement" statement } { "quot" quotation } }
132 { $description "A combinator that calls a quotation on a sequence of SQL statements to their results query results." } ;
133
134 HELP: query-map
135 { $values
136      { "statement" statement } { "quot" quotation }
137      { "seq" sequence } }
138 { $description "A combinator that maps a sequence of SQL statements to their results query results." } ;
139
140 HELP: rollback-transaction
141 { $description "Rolls back a transaction; no data is committed to the database. User code should make use of the " { $link with-transaction } " combinator." } ;
142
143 HELP: sql-command
144 { $values
145      { "sql" string } }
146 { $description "Executes a SQL string using the database in the " { $link db-connection } " symbol." } ;
147
148 HELP: sql-query
149 { $values
150      { "sql" string }
151      { "rows" "an array of arrays of strings" } }
152 { $description "Runs a SQL query of raw text in the database in the " { $link db-connection } " symbol. Each row is returned as an array of strings; no type-conversions are done on the resulting data." } ;
153
154 { sql-command sql-query } related-words
155
156 HELP: sql-row
157 { $values
158      { "result-set" result-set }
159      { "seq" sequence } }
160 { $description "Returns the current row in a " { $link result-set } " as an array of strings." } ;
161
162 HELP: sql-row-typed
163 { $values
164      { "result-set" result-set }
165      { "seq" sequence } }
166 { $description "Returns the current row in a " { $link result-set } " as an array of typed Factor objects." } ;
167
168 { sql-row sql-row-typed } related-words
169
170 HELP: with-db
171 { $values
172      { "db" "a database configuration object" } { "quot" quotation } }
173 { $description "Calls the quotation with a database bound to the " { $link db-connection } " symbol. See " { $link "db-custom-database-combinators" } " for help setting up database access." } ;
174
175 HELP: with-transaction
176 { $values
177      { "quot" quotation } }
178 { $description "Calls the quotation inside a database transaction and commits the result to the database after the quotation finishes. If the quotation throws an error, the transaction is aborted." } ;
179
180 ARTICLE: "db" "Database library"
181 "Accessing a database:"
182 { $subsections "db-custom-database-combinators" }
183 "Higher-level database help:"
184 { $vocab-subsection "Database types" "db.types" }
185 { $vocab-subsection "High-level tuple/database integration" "db.tuples" }
186 "Low-level database help:"
187 { $subsections
188     "db-protocol"
189     "db-result-sets"
190     "db-lowlevel-tutorial"
191 }
192 "Supported database backends:"
193 { $vocab-subsection "SQLite" "db.sqlite" }
194 { $vocab-subsection "PostgreSQL" "db.postgresql" } ;
195
196 ARTICLE: "db-random-access-result-set" "Random access result sets"
197 "Random-access result sets do not have to be traversed in order. For instance, PostgreSQL's result set object can be accessed as a matrix with i,j coordinates."
198 $nl
199 "Databases which work in this way must provide methods for the following traversal words:"
200 { $subsections
201     #rows
202     #columns
203     row-column
204     row-column-typed
205 } ;
206
207 ARTICLE: "db-sequential-result-set" "Sequential result sets"
208 "Sequential result sets can be iterated one element after the next. SQLite's result sets offer this method of traversal."
209 $nl
210 "Databases which work in this way must provide methods for the following traversal words:"
211 { $subsections
212     more-rows?
213     advance-row
214     row-column
215     row-column-typed
216 } ;
217
218 ARTICLE: "db-result-sets" "Result sets"
219 "Result sets are the encapsulated, database-specific results from a SQL query."
220 $nl
221 "Two possible protocols for iterating over result sets exist:"
222 { $subsections
223     "db-random-access-result-set"
224     "db-sequential-result-set"
225 }
226 "Query the number of rows or columns:"
227 { $subsections
228     #rows
229     #columns
230 }
231 "Traversing a result set:"
232 { $subsections
233     advance-row
234     more-rows?
235 }
236 "Pulling out a single row of results:"
237 { $subsections
238     row-column
239     row-column-typed
240 } ;
241
242 ARTICLE: "db-protocol" "Low-level database protocol"
243 "The high-level protocol (see " { $vocab-link "db.tuples" } ") uses this low-level protocol for executing statements and queries." $nl
244 "Opening a database:"
245 { $subsections db-open }
246 "Closing a database:"
247 { $subsections db-close }
248 "Creating statements:"
249 { $subsections
250     <simple-statement>
251     <prepared-statement>
252 }
253 "Using statements with the database:"
254 { $subsections
255     prepare-statement
256     bind-statement*
257     low-level-bind
258 }
259 "Performing a query:"
260 { $subsections query-results }
261 "Handling query results:"
262 { $subsections "db-result-sets" }
263 ;
264 ! { $subsection bind-tuple }
265
266 ARTICLE: "db-lowlevel-tutorial" "Low-level database tutorial"
267 "Although Factor makes integrating a database with its object system easy (see " { $vocab-link "db.tuples" } "), sometimes you may want to write SQL directly and get the results back as arrays of strings, for instance, when interfacing with a legacy database that doesn't easily map to " { $snippet "tuples" } "." $nl
268 "Executing a SQL command:"
269 { $subsections sql-command }
270 "Executing a query directly:"
271 { $subsections sql-query }
272 "Here's an example usage where we'll make a book table, insert some objects, and query them." $nl
273 "First, let's set up a custom combinator for using our database. See " { $link "db-custom-database-combinators" } " for more details."
274 { $code """USING: db.sqlite db io.files io.files.temp ;
275 : with-book-db ( quot -- )
276     "book.db" temp-file <sqlite-db> swap with-db ; inline""" }
277 "Now let's create the table manually:"
278 { $code """"create table books
279     (id integer primary key, title text, author text, date_published timestamp,
280      edition integer, cover_price double, condition text)"
281     [ sql-command ] with-book-db""" }
282 "Time to insert some books:"
283 { $code """"insert into books
284     (title, author, date_published, edition, cover_price, condition)
285     values('Factor for Sheeple', 'Mister Stacky Pants', date('now'), 1, 13.37, 'mint')"
286 [ sql-command ] with-book-db""" }
287 "Now let's select the book:"
288 { $code """"select id, title, cover_price from books;" [ sql-query ] with-book-db""" }
289 "Notice that the result of this query is a Factor array containing the database rows as arrays of strings. We would have to convert the " { $snippet "cover_price" } " from a string to a number in order to use it in a calculation." $nl
290 "In conclusion, this method of accessing a database is supported, but it is fairly low-level and generally specific to a single database. The " { $vocab-link "db.tuples" } " vocabulary is a good alternative to writing SQL by hand." ;
291
292 ARTICLE: "db-custom-database-combinators" "Custom database combinators"
293 "Every database library requires some effort on the programmer's part to initialize and open a database. SQLite uses files on your harddisk, so a simple pathname is all the setup required. With PostgreSQL, you log in to a networked server as a user on a specific port." $nl
294
295 "Make a " { $snippet "with-" } " combinator to open and close a database so that resources are not leaked." $nl
296
297 "SQLite example combinator:"
298 { $code """USING: db.sqlite db io.files io.files.temp ;
299 : with-sqlite-db ( quot -- )
300     "my-database.db" temp-file <sqlite-db> swap with-db ; inline""" }
301
302 "PostgreSQL example combinator:"
303 { $code """USING: db.postgresql db ;
304 : with-postgresql-db ( quot -- )
305     <postgresql-db>
306         "localhost" >>host
307         5432 >>port
308         "erg" >>username
309         "secrets?" >>password
310         "factor-test" >>database
311     swap with-db ; inline"""
312 } ;
313
314 ABOUT: "db"