You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: README.md
+89-53Lines changed: 89 additions & 53 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -13,31 +13,25 @@ A Julia interface to the SQLite library and support for the `DataStreams` data p
13
13
## Package Documentation
14
14
15
15
#### Types/Functions
16
-
*`SQLiteDB(file::String; UTF16::Bool=false)`
16
+
*`SQLite.DB(file::AbstractString)`
17
17
18
-
`SQLiteDB` requires the `file` string argument as the name of either a pre-defined SQLite database to be opened, or if the file doesn't exist, a database will be created.
18
+
`SQLite.DB` requires the `file` string argument as the name of either a pre-defined SQLite database to be opened, or if the file doesn't exist, a database will be created.
19
19
20
-
The `SQLiteDB` object represents a single connection to an SQLite database. All other SQLite.jl functions take an `SQLiteDB` as the first argument as context.
20
+
The `SQLite.DB` object represents a single connection to an SQLite database. All other SQLite.jl functions take an `SQLite.DB` as the first argument as context.
21
21
22
-
The keyword argument `UTF16` can be set to true to force the creation of a database with UTF16-encoded strings.
22
+
To create an in-memory temporary database, call `SQLite.DB()`.
23
23
24
-
To create an in-memory temporary database, one can also call `SQLiteDB(":memory:")`.
24
+
The `SQLite.DB` will automatically closed/shutdown when it goes out of scope (i.e. the end of the Julia session, end of a function call wherein it was created, etc.)
25
25
26
-
*`close(db::SQLiteDB)`
26
+
*`SQLite.Stmt(db::SQLite.DB, sql::String)`
27
27
28
-
Closes an open database connection.
28
+
Constructs and prepares (compiled by the SQLite library) an SQL statement in the context of the provided `db`. Note the SQL statement is not actually executed, but only compiled (mainly for usage where the same statement is repeated with different parameters bound as values. See `bind!` below).
29
29
30
-
*`SQLiteStmt(db::SQLiteDB, sql::String)`
30
+
The `SQLite.Stmt` will automatically closed/shutdown when it goes out of scope (i.e. the end of the Julia session, end of a function call wherein it was created, etc.)
31
31
32
-
Constructs and prepares (compiled by SQLite library) an SQL statement in the context of the provided `db`. Note the SQL statement is not actually executed, but only compiled (mainly for usage where the same statement is repeated with different parameters bound as values. See `bind` below).
32
+
*`SQLite.bind!(stmt::SQLite.Stmt,index,value)`
33
33
34
-
*`close(stmt::SQLiteStmt)`
35
-
36
-
Closes or finalizes an SQLiteStmt. A closed `SQLiteStmt` can no longer be executed.
37
-
38
-
*`bind(stmt::SQLiteStmt,index,value)`
39
-
40
-
Used to bind values to parameter placeholders in an prepared `SQLiteStmt`. From the SQLite documentation:
34
+
Used to bind values to parameter placeholders in an prepared `SQLite.Stmt`. From the SQLite documentation:
41
35
42
36
> Usually, though, it is not useful to evaluate exactly the same SQL statement more than once. More often, one wants to evaluate similar statements. For example, you might want to evaluate an INSERT statement multiple times though with different values to insert. To accommodate this kind of flexibility, SQLite allows SQL statements to contain parameters which are "bound" to values prior to being evaluated. These values can later be changed and the same prepared statement can be evaluated a second time using the new values.
43
37
@@ -51,46 +45,88 @@ A Julia interface to the SQLite library and support for the `DataStreams` data p
51
45
52
46
> In the examples above, NNN is an integer value and AAA is an identifier. A parameter initially has a value of NULL. Prior to calling sqlite3_step() for the first time or immediately after sqlite3_reset(), the application can invoke one of the sqlite3_bind() interfaces to attach values to the parameters. Each call to sqlite3_bind() overrides prior bindings on the same parameter.
53
47
54
-
*`execute(stmt::SQLiteStmt)`
55
-
`execute(db::SQLiteDB, sql::String)`
48
+
*`SQLite.execute!(stmt::SQLite.Stmt)`
49
+
`SQLite.execute!(db::SQLite.DB, sql::String)`
50
+
51
+
Used to execute a prepared `SQLite.Stmt`. The 2nd method is a convenience method to pass in an SQL statement as a string which gets prepared and executed in one call. This method does not check for or return any results, hence it is only useful for database manipulation methods (i.e. ALTER, CREATE, UPDATE, DROP). To return results, see `SQLite.query` below.
An SQL statement `sql` is prepared, executed in the context of `db`, and results, if any, are returned. The return value is a `Data.Table` by default from the `DataStreams.jl` package. The `Data.Table` has a field `.data` which is a `Vector{NullableVector}` which holds the columns of data returned from the `sql` statement.
56
+
57
+
The values in `values` are used in parameter binding (see `bind!` above). If your statement uses nameless parameters `values` must be a `Vector` of the values you wish to bind to your statment. If your statement uses named parameters `values` must be a Dict where the keys are of type `Symbol`. The key must match an identifier name in the statement (the name **should not** include the ':', '@' or '$' prefix).
These are pretty self-explanatory. They're really just a convenience methods to execute DROP TABLE/DROP INDEX commands, while also calling "VACUUM" to clean out freed memory from the database.
Create a new index named `index` for `table` with the columns in `cols`, which should be a comma delimited list of column names. `unique` indicates whether the index will have unique values or not. `ifnotexists` will not throw an error if the index already exists.
Create an `SQLite.Source` type in `db` with the SQL statement `sql`. This prepares and executes the statement, but does not return any data. The source is ready to be streamed to any sink type with an appropriate `Data.stream!` method defined. `rows` can be used to fetch a specific number of rows if known before hand and can help in pre-allocating for sinks. `stricttypes=false` can be used to relax type requirements on returned columns; typically, each value in a column must be of the same type, but SQLite itself uses a fairly weak typing scheme which allows any value to be in a column, regardless of type. Working with data in Julia is much more useful in strongly-typed structures, so by default we try to return strongly-typed columns, but this can be relaxed.
87
+
88
+
*`SQLite.Source(sink::SQLite.Sink,sql)`
89
+
90
+
Creates an `SQLite.Source` type according the `sql` command executed in the same `db` as `sink`. By default, the `sql` command is `select * from $(sink.tablename)`.
Used to execute prepared `SQLiteStmt`. The 2nd method is a convenience method to pass in an SQL statement as a string which gets prepared and executed in one call. This method does not check for or return any results, hence it is only useful for database manipulation methods (i.e. ALTER, CREATE, UPDATE, DROP). To return results, see `query` below. Also consider the `create`, `droptable`, and `append` methods for manipulation statements as further SQLite performance tricks are incorporated automatically.
94
+
Create a `Data.Table` and stream the data from an `SQLite.Source` into it.
An SQL statement `sql` is prepared, executed in the context of `db`, and results, if any, are returned. The return values are a `(String[],Any[])` tuple representing `(column names, result values)`.
98
+
stream the data from `source` to a `CSV.Sink`. `header` indicates whether the column names will be written first to `sink`.
62
99
63
-
The values in `values` are used in parameter binding (see `bind` above). If your statement uses nameless parameters `values` must be a `Vector` of the values you wish to bind to your statment. If your statement uses named parameters `values` must be a Dict where the keys are of type `Symbol`. The key must match an identifier name in the statement (the name **does not** include the ':', '@' or '$' prefix).
Create a new SQLite table as a sink to stream data to in `db`. `schema` is used to create the column names and types. If no `tablename` is supplied, one will be generated. `temp` indicates whether the table will be temporary, i.e. if it will be automatically destroyed when the `db` is closed.
67
103
68
-
Convenience method for "CREATE TABLE" and "INSERT" statements to insert `table` as an SQLite table in the `db` database. `name` will be the name of the SQLite table. `table` can be any AbstractMatrix that supports the `table[i,j]` getindex method. `colnames` is an optional vector to be used as the names of the columns for the SQLite table. `coltypes` is also an optional vector to specify the Julia types of the columns in `table`. The optional keyword `temp` can be set to `true` to specify the creation of a temporary table that will be destroyed when the database connection is closed.
Takes the values in `table` and appends (by repeated inserts) to the SQLite table `name`. No column checking is done to ensure correct types, so care should be taken as SQLite is "typeless" in that it allows items of any type to be stored in columns. Transaction handling is automatic as well as performance enhancements.
`droptable` is pretty self-explanatory. It's really just a convenience wrapper around `query` to execute a DROP TABLE command, while also calling "VACUUM" to clean out freed memory from the database.
Register a scalar (first method) or aggregate (second method) function with a `SQLiteDB`.
119
+
Register a scalar (first method) or aggregate (second method) function with a `SQLite.DB`.
84
120
85
121
*`@register db function`
86
122
87
-
Automatically define then register `function` with a `SQLiteDB`.
123
+
Automatically define then register `function` with a `SQLite.DB`.
88
124
89
125
*`sr"..."`
90
126
91
127
This string literal is used to escape all special characters in the string, useful for using regex in a query.
92
128
93
-
*`sqlreturn(contex, val)`
129
+
*`SQLite.sqlreturn(contex, val)`
94
130
95
131
This function should never be called explicitly. Instead it is exported so that it can be overloaded when necessary, see below.
96
132
@@ -103,19 +139,19 @@ SQLite provides syntax for calling the [`regexp` function](http://sqlite.org/lan
103
139
```julia
104
140
julia>using SQLite
105
141
106
-
julia> db =SQLiteDB("Chinook_Sqlite.sqlite")
142
+
julia> db =SQLite.DB("Chinook_Sqlite.sqlite")
107
143
108
144
julia># using SQLite's in-built syntax
109
145
110
-
julia>query(db, "SELECT FirstName, LastName FROM Employee WHERE LastName REGEXP 'e(?=a)'")
146
+
julia>SQLite.query(db, "SELECT FirstName, LastName FROM Employee WHERE LastName REGEXP 'e(?=a)'")
111
147
1x2 ResultSet
112
148
| Row |"FirstName"|"LastName"|
113
149
|-----|-------------|------------|
114
150
|1|"Jane"|"Peacock"|
115
151
116
152
julia># explicitly calling the regexp() function
117
153
118
-
julia>query(db, "SELECT * FROM Genre WHERE regexp('e[trs]', Name)")
154
+
julia>SQLite.query(db, "SELECT * FROM Genre WHERE regexp('e[trs]', Name)")
119
155
6x2 ResultSet
120
156
| Row |"GenreId"|"Name"|
121
157
|-----|-----------|----------------------|
@@ -128,37 +164,37 @@ julia> query(db, "SELECT * FROM Genre WHERE regexp('e[trs]', Name)")
128
164
129
165
julia># you can even do strange things like this if you really want
130
166
131
-
julia>query(db, "SELECT * FROM Genre ORDER BY GenreId LIMIT 2")
167
+
julia>SQLite.query(db, "SELECT * FROM Genre ORDER BY GenreId LIMIT 2")
132
168
2x2 ResultSet
133
169
| Row |"GenreId"|"Name"|
134
170
|-----|-----------|--------|
135
171
|1|1|"Rock"|
136
172
|2|2|"Jazz"|
137
173
138
-
julia>query(db, "INSERT INTO Genre VALUES (regexp('^word', 'this is a string'), 'My Genre')")
174
+
julia>SQLite.query(db, "INSERT INTO Genre VALUES (regexp('^word', 'this is a string'), 'My Genre')")
139
175
1x1 ResultSet
140
176
| Row |"Rows Affected"|
141
177
|-----|-----------------|
142
178
|1|0|
143
179
144
-
julia>query(db, "SELECT * FROM Genre ORDER BY GenreId LIMIT 2")
180
+
julia>SQLite.query(db, "SELECT * FROM Genre ORDER BY GenreId LIMIT 2")
145
181
2x2 ResultSet
146
182
| Row |"GenreId"|"Name"|
147
183
|-----|-----------|------------|
148
184
|1|0|"My Genre"|
149
185
|2|1|"Rock"|
150
186
```
151
187
152
-
Due to the heavy use of escape characters you may run into problems where julia parses out some backslashes in your query, for example `"\y"`simlpy becomes `"y"`. For example the following two queries are identical
188
+
Due to the heavy use of escape characters you may run into problems where julia parses out some backslashes in your query, for example `"\y"`simply becomes `"y"`. For example the following two queries are identical
153
189
154
190
```julia
155
-
julia>query(db, "SELECT * FROM MediaType WHERE Name REGEXP '-\d'")
191
+
julia>SQLite.query(db, "SELECT * FROM MediaType WHERE Name REGEXP '-\d'")
156
192
1x1 ResultSet
157
193
| Row |"Rows Affected"|
158
194
|-----|-----------------|
159
195
|1|0|
160
196
161
-
julia>query(db, "SELECT * FROM MediaType WHERE Name REGEXP '-d'")
197
+
julia>SQLite.query(db, "SELECT * FROM MediaType WHERE Name REGEXP '-d'")
162
198
1x1 ResultSet
163
199
| Row |"Rows Affected"|
164
200
|-----|-----------------|
@@ -170,15 +206,15 @@ This can be avoided in two ways. You can either escape each backslash yourself o
170
206
```julia
171
207
julia># manually escaping backslashes
172
208
173
-
julia>query(db, "SELECT * FROM MediaType WHERE Name REGEXP '-\\d'")
209
+
julia>SQLite.query(db, "SELECT * FROM MediaType WHERE Name REGEXP '-\\d'")
@@ -191,7 +227,7 @@ The sr"..." currently escapes all special characters in a string but it may be c
191
227
192
228
SQLite.jl also provides a way that you can implement your own [Scalar Functions](https://www.sqlite.org/lang_corefunc.html). This is done using the `register` function and macro.
193
229
194
-
`@register` takes a `SQLiteDB` and a function. The function can be in block syntax
230
+
`@register` takes a `SQLite.DB` and a function. The function can be in block syntax
195
231
196
232
```julia
197
233
julia>@register db functionadd3(x)
@@ -211,9 +247,9 @@ and previously defined functions
211
247
julia>@register db sin
212
248
```
213
249
214
-
The `register` function takes optional arguments; `nargs` which defaults to `-1`, `name` which defaults to the name of the function, `isdeterm` which defaults to `true`. In practice these rarely need to be used.
250
+
The `SQLite.register` function takes optional arguments; `nargs` which defaults to `-1`, `name` which defaults to the name of the function, `isdeterm` which defaults to `true`. In practice these rarely need to be used.
215
251
216
-
The `register` function uses the `sqlreturn` function to return your function's return value to SQLite. By default, `sqlreturn` maps the returned value to a [native SQLite type](http://sqlite.org/c3ref/result_blob.html) or, failing that, serializes the julia value and stores it as a `BLOB`. To change this behaviour simply define a new method for `sqlreturn` which then calls a previously defined method for `sqlreturn`. Methods which map to native SQLite types are
252
+
The `SQLite.register` function uses the `sqlreturn` function to return your function's return value to SQLite. By default, `sqlreturn` maps the returned value to a [native SQLite type](http://sqlite.org/c3ref/result_blob.html) or, failing that, serializes the julia value and stores it as a `BLOB`. To change this behaviour simply define a new method for `sqlreturn` which then calls a previously defined method for `sqlreturn`. Methods which map to native SQLite types are
217
253
218
254
```julia
219
255
sqlreturn(context, ::NullType)
@@ -241,20 +277,20 @@ Any new method defined for `sqlreturn` must take two arguments and must pass the
241
277
242
278
#### Custom Aggregate Functions
243
279
244
-
Using the `register` function, you can also define your own aggregate functions with largely the same semantics.
280
+
Using the `SQLite.register` function, you can also define your own aggregate functions with largely the same semantics.
245
281
246
-
The `register` function for aggregates must take a `SQLiteDB`, an initial value, a step function and a final function. The first argument to the step function will be the return value of the previous function (or the initial value if it is the first iteration). The final function must take a single argument which will be the return value of the last step function.
282
+
The `SQLite.register` function for aggregates must take a `SQLite.DB`, an initial value, a step function and a final function. The first argument to the step function will be the return value of the previous function (or the initial value if it is the first iteration). The final function must take a single argument which will be the return value of the last step function.
247
283
248
284
```julia
249
285
julia>dsum(prev, cur) = prev + cur
250
286
251
287
julia>dsum(prev) =2* prev
252
288
253
-
julia>register(db, 0, dsum, dsum)
289
+
julia>SQLite.register(db, 0, dsum, dsum)
254
290
```
255
291
256
292
If no name is given the name of the first (step) function is used (in this case "dsum"). You can also use lambdas, the following does the same as the previous code snippet
257
293
258
294
```julia
259
-
julia>register(db, 0, (p,c) -> p+c, p ->2p, name="dsum")
295
+
julia>SQLite.register(db, 0, (p,c) -> p+c, p ->2p, name="dsum")
0 commit comments