|
6 | 6 | A simple embedded language for running inline SQL in Python programs.
|
7 | 7 |
|
8 | 8 | ```python
|
9 |
| -import pandas as pd |
10 | 9 | from inline_sql import sql, sql_val
|
11 | 10 |
|
12 |
| - |
13 |
| -def head_data(count: int) -> pd.DataFrame: |
14 |
| - return sql^ "SELECT * FROM 'cars.csv' LIMIT $count" |
15 |
| - |
16 |
| - |
17 |
| -cars = head_data(50) |
18 |
| - |
19 |
| -origin_counts = sql^ """ |
20 |
| - SELECT origin, COUNT() FROM cars |
21 |
| - GROUP BY origin |
22 |
| - ORDER BY count DESC |
23 |
| -""" |
24 |
| -print(origin_counts) |
25 |
| - |
26 |
| -most_common = origin_counts.origin[0] |
27 |
| -print(sql_val^ """ |
28 |
| - SELECT AVG(horsepower) FROM cars |
29 |
| - WHERE origin = $most_common |
30 |
| -""") |
| 11 | +assert sql_val^ "SELECT 1 + 1" == 2 |
| 12 | +assert sql_val^ "SELECT COUNT() FROM 'disasters.csv'" == 803 |
31 | 13 | ```
|
32 | 14 |
|
33 | 15 | Operations in the `inline_sql` library directly use an in-memory database. You can access local datasets (pandas frames), CSV files, and interpolate variables seamlessly into queries. Internally, this is implemented as a small wrapper around [DuckDB](https://duckdb.org/).
|
@@ -76,6 +58,35 @@ The exported `sql` and `sql_val` variables are magic objects that can be used to
|
76 | 58 |
|
77 | 59 | You can run any SQL query as described in the [DuckDB documentation](https://duckdb.org/docs/guides/).
|
78 | 60 |
|
| 61 | +## Library Use |
| 62 | + |
| 63 | +You can use `inline_sql` as a library. Since results from queries are ordinary `pandas.DataFrame` objects, they work in functions and application code. Here's a longer example: |
| 64 | + |
| 65 | +```python |
| 66 | +import pandas as pd |
| 67 | +from inline_sql import sql, sql_val |
| 68 | + |
| 69 | + |
| 70 | +def head_data(count: int) -> pd.DataFrame: |
| 71 | + return sql^ "SELECT * FROM 'cars.csv' LIMIT $count" |
| 72 | + |
| 73 | + |
| 74 | +cars = head_data(50) |
| 75 | + |
| 76 | +origin_counts = sql^ """ |
| 77 | + SELECT origin, COUNT() FROM cars |
| 78 | + GROUP BY origin |
| 79 | + ORDER BY count DESC |
| 80 | +""" |
| 81 | +print(origin_counts) |
| 82 | + |
| 83 | +most_common = origin_counts.origin[0] |
| 84 | +print(sql_val^ """ |
| 85 | + SELECT AVG(horsepower) FROM cars |
| 86 | + WHERE origin = $most_common |
| 87 | +""") |
| 88 | +``` |
| 89 | + |
79 | 90 | ## Acknowledgements
|
80 | 91 |
|
81 | 92 | Created by Eric Zhang ([@ekzhang1](https://twitter.com/ekzhang1)). Licensed under the [MIT license](LICENSE).
|
0 commit comments