]> gitweb.factorcode.org Git - factor.git/blob - basis/db/db-docs.factor
arm.64.factor: extra semicolon removed
[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: alien assocs classes db.private help.markup help.syntax
4 kernel math quotations sequences strings ;
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 an 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      { "result-set" result-set } { "quot" quotation } }
132 { $description "Applies the quotation to each row of the " { $link result-set } " in order." } ;
133
134 HELP: query-map
135 { $values
136      { "result-set" result-set } { "quot" quotation }
137      { "seq" sequence } }
138 { $description "Applies the quotation to each row of the " { $link result-set } " in order." } ;
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 an 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 an 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-subsections
185     { "Database types" "db.types" }
186     { "High-level tuple/database integration" "db.tuples" }
187 }
188 "Low-level database help:"
189 { $subsections
190     "db-protocol"
191     "db-result-sets"
192     "db-lowlevel-tutorial"
193 }
194 "Supported database backends:"
195 { $vocab-subsections
196     { "SQLite" "db.sqlite" }
197     { "PostgreSQL" "db.postgresql" }
198 } ;
199
200 ARTICLE: "db-random-access-result-set" "Random access result sets"
201 "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."
202 $nl
203 "Databases which work in this way must provide methods for the following traversal words:"
204 { $subsections
205     #rows
206     #columns
207     row-column
208     row-column-typed
209 } ;
210
211 ARTICLE: "db-sequential-result-set" "Sequential result sets"
212 "Sequential result sets can be iterated one element after the next. SQLite's result sets offer this method of traversal."
213 $nl
214 "Databases which work in this way must provide methods for the following traversal words:"
215 { $subsections
216     more-rows?
217     advance-row
218     row-column
219     row-column-typed
220 } ;
221
222 ARTICLE: "db-result-sets" "Result sets"
223 "Result sets are the encapsulated, database-specific results from an SQL query."
224 $nl
225 "Two possible protocols for iterating over result sets exist:"
226 { $subsections
227     "db-random-access-result-set"
228     "db-sequential-result-set"
229 }
230 "Query the number of rows or columns:"
231 { $subsections
232     #rows
233     #columns
234 }
235 "Traversing a result set:"
236 { $subsections
237     advance-row
238     more-rows?
239 }
240 "Pulling out a single row of results:"
241 { $subsections
242     row-column
243     row-column-typed
244 } ;
245
246 ARTICLE: "db-protocol" "Low-level database protocol"
247 "The high-level protocol (see " { $vocab-link "db.tuples" } ") uses this low-level protocol for executing statements and queries." $nl
248 "Opening a database:"
249 { $subsections db-open }
250 "Closing a database:"
251 { $subsections db-close }
252 "Creating statements:"
253 { $subsections
254     <simple-statement>
255     <prepared-statement>
256 }
257 "Using statements with the database:"
258 { $subsections
259     prepare-statement
260     bind-statement*
261     low-level-bind
262 }
263 "Performing a query:"
264 { $subsections query-results }
265 "Handling query results:"
266 { $subsections "db-result-sets" }
267 ;
268 ! { $subsection bind-tuple }
269
270 ARTICLE: "db-lowlevel-tutorial" "Low-level database tutorial"
271 "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
272 "Executing an SQL command:"
273 { $subsections sql-command }
274 "Executing a query directly:"
275 { $subsections sql-query }
276 "Here's an example usage where we'll make a book table, insert some objects, and query them." $nl
277 "First, let's set up a custom combinator for using our database. See " { $link "db-custom-database-combinators" } " for more details."
278 { $code "USING: db.sqlite db io.files io.files.temp ;
279 : with-book-db ( quot -- )
280     \"book.db\" temp-file <sqlite-db> swap with-db ; inline" }
281 "Now let's create the table manually:"
282 { $code "\"create table books
283     (id integer primary key, title text, author text, date_published timestamp,
284      edition integer, cover_price double, condition text)\"
285     [ sql-command ] with-book-db" }
286 "Time to insert some books:"
287 { $code "\"insert into books
288     (title, author, date_published, edition, cover_price, condition)
289     values('Factor for Sheeple', 'Mister Stacky Pants', date('now'), 1, 13.37, 'mint')\"
290 [ sql-command ] with-book-db" }
291 "Now let's select the book:"
292 { $code "\"select id, title, cover_price from books;\" [ sql-query ] with-book-db" }
293 "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
294 "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." ;
295
296 ARTICLE: "db-custom-database-combinators" "Custom database combinators"
297 "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
298
299 "Make a " { $snippet "with-" } " combinator to open and close a database so that resources are not leaked." $nl
300
301 "SQLite example combinator:"
302 { $code "USING: db.sqlite db io.files io.files.temp ;
303 : with-sqlite-db ( quot -- )
304     \"my-database.db\" temp-file <sqlite-db> swap with-db ; inline" }
305
306 "PostgreSQL example combinator:"
307 { $code "USING: db.postgresql db ;
308 : with-postgresql-db ( quot -- )
309     <postgresql-db>
310         \"localhost\" >>host
311         5432 >>port
312         \"erg\" >>username
313         \"secrets?\" >>password
314         \"factor-test\" >>database
315     swap with-db ; inline"
316 } ;
317
318 ABOUT: "db"