├── .gitignore ├── LICENSE.md ├── README.md ├── db_00.R ├── db_10.R ├── db_10_solutions.R ├── db_11.R ├── db_11_solutions.R ├── db_12.R ├── db_12_solutions.R ├── db_13.R ├── db_13_solutions.R ├── db_21.R ├── db_21_solutions.R ├── db_22.R ├── db_23.R ├── db_23_solutions.R ├── db_31.R ├── db_31_solutions.R ├── db_32.R ├── db_33.R ├── db_33_solutions.R ├── db_40_solutions.R ├── index.html ├── part-2.html ├── part-3.html ├── part-4.html └── workshop-conf-2024.Rproj /.gitignore: -------------------------------------------------------------------------------- 1 | .Rproj.user 2 | .Rhistory 3 | .RData 4 | .Ruserdata 5 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | ## creative commons 2 | 3 | # Attribution-ShareAlike 4.0 International 4 | 5 | Creative Commons Corporation (“Creative Commons”) is not a law firm and does not provide legal services or legal advice. Distribution of Creative Commons public licenses does not create a lawyer-client or other relationship. Creative Commons makes its licenses and related information available on an “as-is” basis. Creative Commons gives no warranties regarding its licenses, any material licensed under their terms and conditions, or any related information. Creative Commons disclaims all liability for damages resulting from their use to the fullest extent possible. 6 | 7 | ### Using Creative Commons Public Licenses 8 | 9 | Creative Commons public licenses provide a standard set of terms and conditions that creators and other rights holders may use to share original works of authorship and other material subject to copyright and certain other rights specified in the public license below. The following considerations are for informational purposes only, are not exhaustive, and do not form part of our licenses. 10 | 11 | * __Considerations for licensors:__ Our public licenses are intended for use by those authorized to give the public permission to use material in ways otherwise restricted by copyright and certain other rights. Our licenses are irrevocable. Licensors should read and understand the terms and conditions of the license they choose before applying it. Licensors should also secure all rights necessary before applying our licenses so that the public can reuse the material as expected. Licensors should clearly mark any material not subject to the license. This includes other CC-licensed material, or material used under an exception or limitation to copyright. [More considerations for licensors](http://wiki.creativecommons.org/Considerations_for_licensors_and_licensees#Considerations_for_licensors). 12 | 13 | * __Considerations for the public:__ By using one of our public licenses, a licensor grants the public permission to use the licensed material under specified terms and conditions. If the licensor’s permission is not necessary for any reason–for example, because of any applicable exception or limitation to copyright–then that use is not regulated by the license. Our licenses grant only permissions under copyright and certain other rights that a licensor has authority to grant. Use of the licensed material may still be restricted for other reasons, including because others have copyright or other rights in the material. A licensor may make special requests, such as asking that all changes be marked or described. Although not required by our licenses, you are encouraged to respect those requests where reasonable. [More considerations for the public](http://wiki.creativecommons.org/Considerations_for_licensors_and_licensees#Considerations_for_licensees). 14 | 15 | ## Creative Commons Attribution-ShareAlike 4.0 International Public License 16 | 17 | By exercising the Licensed Rights (defined below), You accept and agree to be bound by the terms and conditions of this Creative Commons Attribution-ShareAlike 4.0 International Public License ("Public License"). To the extent this Public License may be interpreted as a contract, You are granted the Licensed Rights in consideration of Your acceptance of these terms and conditions, and the Licensor grants You such rights in consideration of benefits the Licensor receives from making the Licensed Material available under these terms and conditions. 18 | 19 | ### Section 1 – Definitions. 20 | 21 | a. __Adapted Material__ means material subject to Copyright and Similar Rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor. For purposes of this Public License, where the Licensed Material is a musical work, performance, or sound recording, Adapted Material is always produced where the Licensed Material is synched in timed relation with a moving image. 22 | 23 | b. __Adapter's License__ means the license You apply to Your Copyright and Similar Rights in Your contributions to Adapted Material in accordance with the terms and conditions of this Public License. 24 | 25 | c. __BY-SA Compatible License__ means a license listed at [creativecommons.org/compatiblelicenses](http://creativecommons.org/compatiblelicenses), approved by Creative Commons as essentially the equivalent of this Public License. 26 | 27 | d. __Copyright and Similar Rights__ means copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights, without regard to how the rights are labeled or categorized. For purposes of this Public License, the rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights. 28 | 29 | e. __Effective Technological Measures__ means those measures that, in the absence of proper authority, may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar international agreements. 30 | 31 | f. __Exceptions and Limitations__ means fair use, fair dealing, and/or any other exception or limitation to Copyright and Similar Rights that applies to Your use of the Licensed Material. 32 | 33 | g. __License Elements__ means the license attributes listed in the name of a Creative Commons Public License. The License Elements of this Public License are Attribution and ShareAlike. 34 | 35 | h. __Licensed Material__ means the artistic or literary work, database, or other material to which the Licensor applied this Public License. 36 | 37 | i. __Licensed Rights__ means the rights granted to You subject to the terms and conditions of this Public License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed Material and that the Licensor has authority to license. 38 | 39 | j. __Licensor__ means the individual(s) or entity(ies) granting rights under this Public License. 40 | 41 | k. __Share__ means to provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, communication, or importation, and to make material available to the public including in ways that members of the public may access the material from a place and at a time individually chosen by them. 42 | 43 | l. __Sui Generis Database Rights__ means rights other than copyright resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world. 44 | 45 | m. __You__ means the individual or entity exercising the Licensed Rights under this Public License. Your has a corresponding meaning. 46 | 47 | ### Section 2 – Scope. 48 | 49 | a. ___License grant.___ 50 | 51 | 1. Subject to the terms and conditions of this Public License, the Licensor hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, irrevocable license to exercise the Licensed Rights in the Licensed Material to: 52 | 53 | A. reproduce and Share the Licensed Material, in whole or in part; and 54 | 55 | B. produce, reproduce, and Share Adapted Material. 56 | 57 | 2. __Exceptions and Limitations.__ For the avoidance of doubt, where Exceptions and Limitations apply to Your use, this Public License does not apply, and You do not need to comply with its terms and conditions. 58 | 59 | 3. __Term.__ The term of this Public License is specified in Section 6(a). 60 | 61 | 4. __Media and formats; technical modifications allowed.__ The Licensor authorizes You to exercise the Licensed Rights in all media and formats whether now known or hereafter created, and to make technical modifications necessary to do so. The Licensor waives and/or agrees not to assert any right or authority to forbid You from making technical modifications necessary to exercise the Licensed Rights, including technical modifications necessary to circumvent Effective Technological Measures. For purposes of this Public License, simply making modifications authorized by this Section 2(a)(4) never produces Adapted Material. 62 | 63 | 5. __Downstream recipients.__ 64 | 65 | A. __Offer from the Licensor – Licensed Material.__ Every recipient of the Licensed Material automatically receives an offer from the Licensor to exercise the Licensed Rights under the terms and conditions of this Public License. 66 | 67 | B. __Additional offer from the Licensor – Adapted Material. Every recipient of Adapted Material from You automatically receives an offer from the Licensor to exercise the Licensed Rights in the Adapted Material under the conditions of the Adapter’s License You apply. 68 | 69 | C. __No downstream restrictions.__ You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material. 70 | 71 | 6. __No endorsement.__ Nothing in this Public License constitutes or may be construed as permission to assert or imply that You are, or that Your use of the Licensed Material is, connected with, or sponsored, endorsed, or granted official status by, the Licensor or others designated to receive attribution as provided in Section 3(a)(1)(A)(i). 72 | 73 | b. ___Other rights.___ 74 | 75 | 1. Moral rights, such as the right of integrity, are not licensed under this Public License, nor are publicity, privacy, and/or other similar personality rights; however, to the extent possible, the Licensor waives and/or agrees not to assert any such rights held by the Licensor to the limited extent necessary to allow You to exercise the Licensed Rights, but not otherwise. 76 | 77 | 2. Patent and trademark rights are not licensed under this Public License. 78 | 79 | 3. To the extent possible, the Licensor waives any right to collect royalties from You for the exercise of the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any right to collect such royalties. 80 | 81 | ### Section 3 – License Conditions. 82 | 83 | Your exercise of the Licensed Rights is expressly made subject to the following conditions. 84 | 85 | a. ___Attribution.___ 86 | 87 | 1. If You Share the Licensed Material (including in modified form), You must: 88 | 89 | A. retain the following if it is supplied by the Licensor with the Licensed Material: 90 | 91 | i. identification of the creator(s) of the Licensed Material and any others designated to receive attribution, in any reasonable manner requested by the Licensor (including by pseudonym if designated); 92 | 93 | ii. a copyright notice; 94 | 95 | iii. a notice that refers to this Public License; 96 | 97 | iv. a notice that refers to the disclaimer of warranties; 98 | 99 | v. a URI or hyperlink to the Licensed Material to the extent reasonably practicable; 100 | 101 | B. indicate if You modified the Licensed Material and retain an indication of any previous modifications; and 102 | 103 | C. indicate the Licensed Material is licensed under this Public License, and include the text of, or the URI or hyperlink to, this Public License. 104 | 105 | 2. You may satisfy the conditions in Section 3(a)(1) in any reasonable manner based on the medium, means, and context in which You Share the Licensed Material. For example, it may be reasonable to satisfy the conditions by providing a URI or hyperlink to a resource that includes the required information. 106 | 107 | 3. If requested by the Licensor, You must remove any of the information required by Section 3(a)(1)(A) to the extent reasonably practicable. 108 | 109 | b. ___ShareAlike.___ 110 | 111 | In addition to the conditions in Section 3(a), if You Share Adapted Material You produce, the following conditions also apply. 112 | 113 | 1. The Adapter’s License You apply must be a Creative Commons license with the same License Elements, this version or later, or a BY-SA Compatible License. 114 | 115 | 2. You must include the text of, or the URI or hyperlink to, the Adapter's License You apply. You may satisfy this condition in any reasonable manner based on the medium, means, and context in which You Share Adapted Material. 116 | 117 | 3. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, Adapted Material that restrict exercise of the rights granted under the Adapter's License You apply. 118 | 119 | ### Section 4 – Sui Generis Database Rights. 120 | 121 | Where the Licensed Rights include Sui Generis Database Rights that apply to Your use of the Licensed Material: 122 | 123 | a. for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, reuse, reproduce, and Share all or a substantial portion of the contents of the database; 124 | 125 | b. if You include all or a substantial portion of the database contents in a database in which You have Sui Generis Database Rights, then the database in which You have Sui Generis Database Rights (but not its individual contents) is Adapted Material, including for purposes of Section 3(b); and 126 | 127 | c. You must comply with the conditions in Section 3(a) if You Share all or a substantial portion of the contents of the database. 128 | 129 | For the avoidance of doubt, this Section 4 supplements and does not replace Your obligations under this Public License where the Licensed Rights include other Copyright and Similar Rights. 130 | 131 | ### Section 5 – Disclaimer of Warranties and Limitation of Liability. 132 | 133 | a. __Unless otherwise separately undertaken by the Licensor, to the extent possible, the Licensor offers the Licensed Material as-is and as-available, and makes no representations or warranties of any kind concerning the Licensed Material, whether express, implied, statutory, or other. This includes, without limitation, warranties of title, merchantability, fitness for a particular purpose, non-infringement, absence of latent or other defects, accuracy, or the presence or absence of errors, whether or not known or discoverable. Where disclaimers of warranties are not allowed in full or in part, this disclaimer may not apply to You.__ 134 | 135 | b. __To the extent possible, in no event will the Licensor be liable to You on any legal theory (including, without limitation, negligence) or otherwise for any direct, special, indirect, incidental, consequential, punitive, exemplary, or other losses, costs, expenses, or damages arising out of this Public License or use of the Licensed Material, even if the Licensor has been advised of the possibility of such losses, costs, expenses, or damages. Where a limitation of liability is not allowed in full or in part, this limitation may not apply to You.__ 136 | 137 | c. The disclaimer of warranties and limitation of liability provided above shall be interpreted in a manner that, to the extent possible, most closely approximates an absolute disclaimer and waiver of all liability. 138 | 139 | ### Section 6 – Term and Termination. 140 | 141 | a. This Public License applies for the term of the Copyright and Similar Rights licensed here. However, if You fail to comply with this Public License, then Your rights under this Public License terminate automatically. 142 | 143 | b. Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates: 144 | 145 | 1. automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or 146 | 147 | 2. upon express reinstatement by the Licensor. 148 | 149 | For the avoidance of doubt, this Section 6(b) does not affect any right the Licensor may have to seek remedies for Your violations of this Public License. 150 | 151 | c. For the avoidance of doubt, the Licensor may also offer the Licensed Material under separate terms or conditions or stop distributing the Licensed Material at any time; however, doing so will not terminate this Public License. 152 | 153 | d. Sections 1, 5, 6, 7, and 8 survive termination of this Public License. 154 | 155 | ### Section 7 – Other Terms and Conditions. 156 | 157 | a. The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed. 158 | 159 | b. Any arrangements, understandings, or agreements regarding the Licensed Material not stated herein are separate from and independent of the terms and conditions of this Public License.t stated herein are separate from and independent of the terms and conditions of this Public License. 160 | 161 | ### Section 8 – Interpretation. 162 | 163 | a. For the avoidance of doubt, this Public License does not, and shall not be interpreted to, reduce, limit, restrict, or impose conditions on any use of the Licensed Material that could lawfully be made without permission under this Public License. 164 | 165 | b. To the extent possible, if any provision of this Public License is deemed unenforceable, it shall be automatically reformed to the minimum extent necessary to make it enforceable. If the provision cannot be reformed, it shall be severed from this Public License without affecting the enforceability of the remaining terms and conditions. 166 | 167 | c. No term or condition of this Public License will be waived and no failure to comply consented to unless expressly agreed to by the Licensor. 168 | 169 | d. Nothing in this Public License constitutes or may be interpreted as a limitation upon, or waiver of, any privileges and immunities that apply to the Licensor or You, including from the legal processes of any jurisdiction or authority. 170 | 171 | > Creative Commons is not a party to its public licenses. Notwithstanding, Creative Commons may elect to apply one of its public licenses to material it publishes and in those instances will be considered the “Licensor.” Except for the limited purpose of indicating that material is shared under a Creative Commons public license or as otherwise permitted by the Creative Commons policies published at [creativecommons.org/policies](http://creativecommons.org/policies), Creative Commons does not authorize the use of the trademark “Creative Commons” or any other trademark or logo of Creative Commons without its prior written consent including, without limitation, in connection with any unauthorized modifications to any of its public licenses or any other arrangements, understandings, or agreements concerning use of licensed material. For the avoidance of doubt, this paragraph does not form part of the public licenses. 172 | > 173 | > Creative Commons may be contacted at creativecommons.org -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Databases with R 2 | ================ 3 | 4 | ### posit::conf(2024) 5 | 6 | by Kirill Müller 7 | 8 | ----- 9 | 10 | :spiral_calendar: August 12, 2024 11 | :alarm_clock: 09:00 - 17:00 12 | :hotel: 402 Chiliwack 13 | :writing_hand: [pos.it/conf](http://pos.it/conf) 14 | 15 | ----- 16 | 17 | ## Description 18 | 19 | As a data professional, you likely have to deal with databases that are larger than your available RAM. 20 | Downloading the data requires patience, applying traditional workflows is frustrating. 21 | This workshop will teach you to work with your (large) data: 22 | 23 | - if it resides in a traditional database, effortlessly 24 | 25 | - from local storage, using DuckDB, a modern database engine tailored to data analysis 26 | 27 | The workshop will introduce basic database concepts and move on with practical work with traditional databases and DuckDB. 28 | You are encouraged to bring your own data(base) to immediately apply what you have learned during the workshop. 29 | Among others, the workshop showcases the DBI, dbplyr, duckdb, duckplyr, and dm packages. 30 | 31 | ## Audience 32 | 33 | This course is for you if you: 34 | 35 | - have worked with the dplyr package. 36 | 37 | - have just read or heard about databases and are ready to get your hands dirty. 38 | 39 | - performed basic operations on a database, and you would like to deepen your knowledge. 40 | 41 | - have heard about DuckDB and want to know what makes it unique and how to leverage it in your daily workflow. 42 | 43 | ## Prework 44 | 45 | #### Laptop 46 | 47 | - We strongly recommend you to bring a laptop where you have permission to install software 48 | - If this is not possible, a cloud environment will be made available with material and software already installed 49 | 50 | #### R and RStudio IDE 51 | 52 | - Follow installation instructions [here](https://posit.co/download/rstudio-desktop/) 53 | - If you have R installed, make sure you have at least R version 4.1.0 54 | 55 | #### R Packages Installation 56 | 57 | Open RStudio and install the required R Packages: 58 | 59 | ```r 60 | # Alternative: use pak::pak(...), see https://pak.r-lib.org/ 61 | install.packages(c( 62 | "tidyverse", 63 | "devtools", 64 | "duckplyr", 65 | "RMariaDB", 66 | "adbi", 67 | "dm", 68 | "pixarfilms", 69 | "nycflights13", 70 | "config", 71 | "rstudioapi", 72 | "progress", 73 | "DiagrammeR", 74 | "DiagrammeRsvg", 75 | "arrow", 76 | "odbc", 77 | "parquetize" 78 | )) 79 | ``` 80 | 81 | #### Discord 82 | 83 | Discord will be our communication tool for the workshop. 84 | 85 | - Register for a Discord account [here](https://discord.com/register) 86 | - Make sure your name match the one you used to register for the conference 87 | - Add the the workshop you are enrolled in your "About Me" 88 | - You'll receive an invite to join the Discord server closer to the conference and you'll be added to the workshop channel 89 | 90 | #### Database setup 91 | 92 | We will be using DuckDB for demonstration purposes, with selected exercises targeting a publicly accessible database server. 93 | 94 | 95 | #### Test your setup 96 | 97 | Run the following lines of code: 98 | 99 | ```r 100 | library(DBI) 101 | library(duckdb) 102 | duckdb_con <- dbConnect(duckdb()) 103 | 104 | dbExecute(duckdb_con, "INSTALL httpfs") 105 | dbExecute(duckdb_con, "LOAD httpfs") 106 | dbExecute(duckdb_con, "INSTALL json") 107 | dbExecute(duckdb_con, "LOAD json") 108 | 109 | dbDisconnect(duckdb_con) 110 | ``` 111 | 112 | #### Data 113 | 114 | **We invite you to bring your own data and/or databases** to experiment with techniques during the last session on your own data. 115 | 116 | We will provide a backup for you in case you don't have any. 117 | 118 | ## Schedule 119 | 120 | | Time | Activity | 121 | | :------------ | :--------------- | 122 | | 09:00 - 10:30 | Talking to the database | 123 | | 10:30 - 11:00 | *Coffee break* | 124 | | 11:00 - 12:30 | Working with files | 125 | | 12:30 - 13:30 | *Lunch break* | 126 | | 13:30 - 15:00 | Digging in deeper | 127 | | 15:00 - 15:30 | *Coffee break* | 128 | | 15:30 - 17:00 | Exercises - Bring your own data | 129 | 130 | ## Instructor 131 | 132 | [Kirill Müller](https://www.cynkra.com/about/) has been working on the boundary between data and computer science for more than 25 years. He has been awarded five R consortium projects to improve database connectivity and performance in R. Kirill is a core contributor to several tidyverse packages, including dplyr and tibble, and is currently working on duckplyr, the next iteration of dplyr that uses DuckDB as a backend. He holds a Ph.D. in Civil Engineering from ETH Zurich and is a founder and partner at cynkra. 133 | 134 | ----- 135 | 136 | ![](https://i.creativecommons.org/l/by/4.0/88x31.png) This work is 137 | licensed under a [Creative Commons Attribution 4.0 International 138 | License](https://creativecommons.org/licenses/by/4.0/). 139 | Add materials for your workshop in this folder. You can then remove this README, and rename this folder if you prefer. 140 | -------------------------------------------------------------------------------- /db_00.R: -------------------------------------------------------------------------------- 1 | # install.packages(c("tidyverse", "dm", "DiagrammeR", "RSQLite", "RMariaDB", "duckdb", "duckplyr", "progress", "pixarfilms", "nycflights13", "parquetize"), type = "binary") 2 | # pak::pak(c("tidyverse", "dm", "DiagrammeR", "RSQLite", "RMariaDB", "duckdb", "duckplyr", "progress", "pixarfilms", "nycflights13", "parquetize")) 3 | 4 | library(tidyverse) 5 | library(dm) 6 | library(DiagrammeR) 7 | library(RSQLite) 8 | library(RMariaDB) 9 | library(duckdb) 10 | library(duckplyr) 11 | library(progress) 12 | library(pixarfilms) 13 | library(nycflights13) 14 | library(parquetize) 15 | -------------------------------------------------------------------------------- /db_10.R: -------------------------------------------------------------------------------- 1 | # attach relevant packages 2 | library(DBI) 3 | 4 | ### First steps ################################################################ 5 | 6 | # Connection ------------------------------------------------------------------- 7 | 8 | con <- dbConnect(duckdb::duckdb()) 9 | con 10 | 11 | # Discover tables -------------------------------------------------------------- 12 | 13 | dbListTables(con) 14 | 15 | # Populate database (normally done by other people) --------------------------- 16 | 17 | # Magic: import tables into the database 18 | dm::copy_dm_to( 19 | con, 20 | dm::dm_pixarfilms(), 21 | set_key_constraints = FALSE, 22 | temporary = FALSE 23 | ) 24 | 25 | # Discover tables -------------------------------------------------------------- 26 | 27 | dbListTables(con) 28 | dbListFields(con, "box_office") 29 | 30 | # First steps: Exercises ------------------------------------------------------- 31 | 32 | con 33 | 34 | # 1. List all columns from the `pixar_films` table. 35 | # 2. Review the help for `dbListFields()` and `dbListTables()`, 36 | # and the index on . 37 | -------------------------------------------------------------------------------- /db_10_solutions.R: -------------------------------------------------------------------------------- 1 | 2 | # attach relevant packages 3 | library(DBI) 4 | 5 | # Connection ------------------------------------------------------------------- 6 | 7 | con <- dbConnect(duckdb::duckdb()) 8 | con 9 | 10 | # Magic: import tables into the database 11 | dm::copy_dm_to( 12 | con, 13 | dm::dm_pixarfilms(), 14 | set_key_constraints = FALSE, 15 | temporary = FALSE 16 | ) 17 | 18 | # Reading tables: Exercises ---------------------------------------------------- 19 | 20 | # 1. List all columns from the `pixar_films` table. 21 | 22 | dbListFields(con, "pixar_films") 23 | 24 | # 2. Review the help for `dbListFields()` and `dbListTables()`, 25 | # and the index on . 26 | 27 | ?dbListFields 28 | ?dbListTables 29 | browseURL("https://dbi.r-dbi.org/reference/") 30 | -------------------------------------------------------------------------------- /db_11.R: -------------------------------------------------------------------------------- 1 | # attach relevant packages 2 | library(tidyverse) 3 | library(DBI) 4 | 5 | ### Reading whole tables from the database ##################################### 6 | 7 | # Connection ------------------------------------------------------------------- 8 | 9 | con <- dbConnect(duckdb::duckdb()) 10 | con 11 | 12 | # Discover tables -------------------------------------------------------------- 13 | 14 | dbListTables(con) 15 | 16 | # Populate database (normally done by other people) --------------------------- 17 | 18 | # Magic: import tables into the database 19 | dm::copy_dm_to( 20 | con, 21 | dm::dm_pixarfilms(), 22 | set_key_constraints = FALSE, 23 | temporary = FALSE 24 | ) 25 | 26 | # Discover tables -------------------------------------------------------------- 27 | 28 | dbListTables(con) 29 | dbListFields(con, "pixar_films") 30 | 31 | # Read table ------------------------------------------------------------------- 32 | 33 | df_pixar_films <- dbReadTable(con, "pixar_films") 34 | df_pixar_films 35 | as_tibble(df_pixar_films) 36 | 37 | # Execute queries -------------------------------------------------------------- 38 | 39 | dbGetQuery(con, "SELECT * FROM pixar_films") 40 | 41 | sql <- "SELECT * FROM pixar_films WHERE release_date >= '2020-01-01'" 42 | # sql <- r"(SELECT * FROM "pixar_films" WHERE "release_date" >= '2020-01-01')" 43 | dbGetQuery(con, sql) 44 | 45 | # Further pointers ------------------------------------------------------------- 46 | 47 | # Quoting identifiers 48 | dbQuoteIdentifier(con, "academy") 49 | dbQuoteIdentifier(con, "from") 50 | 51 | # Quoting literals 52 | dbQuoteLiteral(con, "Toy Story") 53 | dbQuoteLiteral(con, as.Date("2020-01-01")) 54 | 55 | # Paste queries with glue_sql() 56 | 57 | # Parameterized queries 58 | sql <- "SELECT count(*) FROM pixar_films WHERE release_date >= ?" 59 | dbGetQuery(con, sql, params = list(as.Date("2020-01-01"))) 60 | 61 | # Reading tables: Exercises ---------------------------------------------------- 62 | 63 | con 64 | 65 | # 1. Read the `academy` table. 66 | # 2. Read all records from the `academy` table that correspond to awards won 67 | # - Hint: Use the query "SELECT * FROM academy WHERE status = 'Won'" 68 | # 3. Use quoting and/or a query parameter to make the previous query more robust. 69 | # - Hint: `sql <- paste0("SELECT * FROM academy WHERE ", quoted_column, " = ?")` 70 | -------------------------------------------------------------------------------- /db_11_solutions.R: -------------------------------------------------------------------------------- 1 | 2 | # attach relevant packages 3 | library(tidyverse) 4 | library(DBI) 5 | 6 | # Connection ------------------------------------------------------------------- 7 | 8 | con <- dbConnect(duckdb::duckdb()) 9 | con 10 | 11 | # Magic: import tables into the database 12 | dm::copy_dm_to( 13 | con, 14 | dm::dm_pixarfilms(), 15 | set_key_constraints = FALSE, 16 | temporary = FALSE 17 | ) 18 | 19 | # Reading tables: Exercises ---------------------------------------------------- 20 | 21 | # 1. List all columns from the `box_office` table. 22 | 23 | dbListFields(con, "box_office") 24 | 25 | # 2. Read the `academy` table. 26 | 27 | dbReadTable(con, "academy") 28 | 29 | # 3. Read all records from the `academy` table that correspond to awards won 30 | # - Hint: Use the query "SELECT * FROM academy WHERE status = 'Won'" 31 | 32 | dbGetQuery(con, "SELECT * FROM academy WHERE status = 'Won'") 33 | 34 | # 4. Use quoting and/or query parameters to stabilize the previous query. 35 | 36 | dbGetQuery(con, 37 | paste( 38 | "SELECT * FROM", dbQuoteIdentifier(con, "academy"), 39 | "WHERE status = ?" 40 | ), 41 | params = list("Won") 42 | ) 43 | 44 | # dbDisconnect(con) 45 | -------------------------------------------------------------------------------- /db_12.R: -------------------------------------------------------------------------------- 1 | # attach relevant packages 2 | library(tidyverse) 3 | 4 | ### Downsizing on the database ################################################# 5 | 6 | # Connection ------------------------------------------------------------------- 7 | 8 | con <- DBI::dbConnect(duckdb::duckdb()) 9 | dm::copy_dm_to(con, dm::dm_pixarfilms(), set_key_constraints = FALSE, temporary = FALSE) 10 | 11 | # Lazy tables ------------------------------------------------------------------ 12 | 13 | pixar_films <- tbl(con, "pixar_films") 14 | pixar_films 15 | 16 | # Get all data ---- 17 | 18 | df_pixar_films <- 19 | pixar_films |> 20 | collect() 21 | df_pixar_films 22 | 23 | # Projection (column selection) ----------------------------------------------- 24 | 25 | pixar_films |> 26 | select(1:3) 27 | 28 | # Computations happens on the database! 29 | pixar_films |> 30 | select(1:3) |> 31 | show_query() 32 | 33 | # Bring the data into the R session 34 | df_pixar_films_3 <- 35 | pixar_films |> 36 | select(1:3) |> 37 | collect() 38 | df_pixar_films_3 39 | 40 | # Immutable data: original data unchanged 41 | pixar_films |> 42 | collect() 43 | 44 | # Filtering (row selection) --------------------------------------------------- 45 | 46 | pixar_films |> 47 | filter(release_date >= "2020-01-01") 48 | 49 | # Computations happens on the database! 50 | pixar_films |> 51 | filter(release_date >= "2020-01-01") |> 52 | show_query() 53 | 54 | # Bring the data into the R session 55 | df_pixar_films_202x <- 56 | pixar_films |> 57 | filter(release_date >= "2020-01-01") |> 58 | collect() 59 | df_pixar_films_202x 60 | 61 | # Immutable data: original data unchanged 62 | pixar_films |> 63 | collect() 64 | 65 | # Downsizing on the database: Exercises ---------------------------------------- 66 | 67 | # `select()` ------------------------------------------------------------------- 68 | 69 | pixar_films 70 | 71 | # * Find several ways to select the 3 first columns 72 | # * What happens if you include the name of a variable multiple times in a `select()` call? 73 | # * Select all columns that contain underscores (use `contains()`) 74 | # * Use `all_of()` to select 2 columns of your choice 75 | 76 | # `filter()` ------------------------------------------------------------------- 77 | 78 | pixar_films 79 | 80 | # Find all films that 81 | # 1. Are rated "PG" 82 | # 2. Had a run time below 95 83 | # 3. Had a rating of "N/A" or "Not Rated" 84 | # 4. Were released after and including year 2020 85 | # 5. Have a missing name (`film` column) or `run_time` 86 | # 6. Are a first sequel (the name ends with "2", as in "Toy Story 2") 87 | # - Hint: Bring the data into the R session before filtering 88 | -------------------------------------------------------------------------------- /db_12_solutions.R: -------------------------------------------------------------------------------- 1 | # attach relevant packages 2 | library(tidyverse) 3 | 4 | # Connection ------------------------------------------------------------------- 5 | 6 | con <- DBI::dbConnect(duckdb::duckdb()) 7 | dm::copy_dm_to(con, dm::dm_pixarfilms(), set_key_constraints = FALSE, temporary = FALSE) 8 | 9 | # Lazy tables ------------------------------------------------------------------ 10 | 11 | pixar_films <- tbl(con, "pixar_films") 12 | 13 | # Downsizing on the database: Exercises ---------------------------------------- 14 | 15 | # `select()` ------------------------------------------------------------------- 16 | 17 | pixar_films 18 | 19 | # * Find several ways to select the 3 first columns 20 | 21 | select(pixar_films, 1:3) 22 | select(pixar_films, number:release_date) 23 | select(pixar_films, !4:ncol(pixar_films)) 24 | 25 | # * What happens if you include the name of a variable multiple times in a `select()` call? 26 | 27 | select(pixar_films, number, release_date, number) 28 | 29 | # * Select all columns that contain underscores (use `contains()`) 30 | 31 | select(pixar_films, contains("_")) 32 | 33 | # * Use `all_of()` to select 2 columns of your choice 34 | 35 | select(pixar_films, all_of(head(colnames(pixar_films), n = 2))) 36 | 37 | # `filter()` ------------------------------------------------------------------- 38 | 39 | pixar_films 40 | 41 | # Find all films that 42 | # 1. Are rated "PG" 43 | 44 | filter(pixar_films, film_rating == "PG") 45 | 46 | # 2. Had a run time below 95 47 | 48 | filter(pixar_films, run_time < 95) 49 | 50 | # 3. Had a rating of "N/A" or "Not Rated" 51 | 52 | filter(pixar_films, film_rating %in% c("N/A", "Not Rated")) 53 | 54 | # 4. Were released after and including year 2020 55 | 56 | filter(pixar_films, release_date >= as.Date("2020-01-01")) 57 | 58 | # 5. Have a missing name (`film` column) or `run_time` 59 | 60 | filter(pixar_films, is.na(film) | is.na(run_time)) 61 | 62 | # 6. Are a first sequel (the name ends with "2", as in "Toy Story 2") 63 | # - Hint: Bring the data into the R session before filtering 64 | 65 | filter(collect(pixar_films), grepl("2$", film)) 66 | 67 | # `count()`, `summarize()`, `group_by()`, `ungroup()` -------------------------- 68 | 69 | pixar_films 70 | 71 | # 1. How many films are stored in the table? 72 | 73 | count(pixar_films) 74 | 75 | # 2. How many films released after 2005 are stored in the table? 76 | 77 | filter(pixar_films, release_date >= as.Date("2006-01-01")) |> 78 | count() 79 | 80 | # 3. What is the total run time of all films? 81 | # - Hint: Use `summarize(sum(...))`, watch out for the warning 82 | 83 | summarize(pixar_films, total_time = sum(run_time, na.rm = TRUE)) 84 | 85 | # 4. What is the total run time of all films, per rating? 86 | # - Hint: Use `group_by()` or `.by` 87 | 88 | pixar_films |> 89 | summarize(.by = film_rating, total_time = sum(run_time, na.rm = TRUE)) 90 | 91 | # dbDisconnect(con) 92 | -------------------------------------------------------------------------------- /db_13.R: -------------------------------------------------------------------------------- 1 | # attach relevant packages 2 | library(tidyverse) 3 | 4 | ### Downsizing on the database ################################################# 5 | 6 | # Connection ------------------------------------------------------------------- 7 | 8 | con <- DBI::dbConnect(duckdb::duckdb()) 9 | dm::copy_dm_to(con, dm::dm_pixarfilms(), set_key_constraints = FALSE, temporary = FALSE) 10 | 11 | # Lazy tables ------------------------------------------------------------------ 12 | 13 | pixar_films <- tbl(con, "pixar_films") 14 | pixar_films 15 | 16 | # Aggregation ------------------------------------------------------------------ 17 | 18 | pixar_films |> 19 | summarize(.by = film_rating, n = n()) 20 | 21 | # Shortcut 22 | pixar_films |> 23 | count(film_rating) 24 | 25 | # Computations happens on the database! 26 | pixar_films |> 27 | count(film_rating) |> 28 | show_query() 29 | 30 | # Bring the data into the R session 31 | df_pixar_films_by_rating <- 32 | pixar_films |> 33 | count(film_rating) |> 34 | collect() 35 | df_pixar_films_by_rating 36 | 37 | # Immutable data: original data unchanged 38 | pixar_films |> 39 | collect() 40 | 41 | # Second lazy table -------------------------------------------------------------- 42 | 43 | academy <- tbl(con, "academy") 44 | 45 | academy 46 | academy |> 47 | count(status) 48 | 49 | # Left join ------ 50 | 51 | academy |> 52 | left_join(pixar_films) 53 | 54 | academy |> 55 | left_join(pixar_films, join_by(film)) 56 | 57 | academy |> 58 | left_join(pixar_films, join_by(film)) |> 59 | show_query() 60 | 61 | # Join with prior computation ------ 62 | 63 | academy_won <- 64 | academy |> 65 | filter(status == "Won") |> 66 | count(film, name = "n_won") 67 | academy_won 68 | 69 | pixar_films |> 70 | left_join(academy_won, join_by(film)) 71 | 72 | academy_won |> 73 | right_join(pixar_films, join_by(film)) |> 74 | arrange(release_date) 75 | 76 | academy_won |> 77 | right_join(pixar_films, join_by(film)) |> 78 | mutate(n_won = coalesce(n_won, 0L)) |> 79 | arrange(release_date) 80 | 81 | pixar_films |> 82 | left_join(academy_won, join_by(film)) |> 83 | mutate(n_won = coalesce(n_won, 0L)) |> 84 | arrange(release_date) |> 85 | show_query() 86 | 87 | # Caveat: tables must be on the same source ------------------------------------ 88 | 89 | try( 90 | academy |> 91 | left_join(pixarfilms::pixar_films, join_by(film)) 92 | ) 93 | 94 | academy |> 95 | left_join(pixarfilms::pixar_films, join_by(film), copy = TRUE) 96 | 97 | academy |> 98 | left_join(pixarfilms::pixar_films, join_by(film), copy = TRUE) |> 99 | show_query() 100 | 101 | try( 102 | pixarfilms::academy |> 103 | left_join(pixar_films, join_by(film)) 104 | ) 105 | 106 | pixarfilms::academy |> 107 | left_join(pixar_films, join_by(film), copy = TRUE) 108 | 109 | pixar_films_db <- 110 | copy_to(con, pixarfilms::pixar_films) 111 | 112 | academy |> 113 | left_join(pixar_films_db, join_by(film)) 114 | 115 | 116 | # Downsizing on the database: Exercises ---------------------------------------- 117 | 118 | # `count()`, `summarize()`, `group_by()`, `ungroup()` -------------------------- 119 | 120 | pixar_films 121 | 122 | # 1. How many films are stored in the table? 123 | # 2. How many films released after 2005 are stored in the table? 124 | # 3. What is the total run time of all films? 125 | # - Hint: Use `summarize(sum(...))`, watch out for the warning 126 | # 4. What is the total run time of all films, per rating? 127 | # - Hint: Use `group_by()` or `.by` 128 | 129 | # `left_join()` -------------------------------------------------------------------- 130 | 131 | pixar_films |> 132 | left_join(academy, join_by(film)) 133 | 134 | # 1. How many rows does the join between `academy` and `pixar_films` contain? 135 | # Try to find out without loading all the data into memory. Explain. 136 | # 2. Which films are not yet listed in the `academy` table? What does the 137 | # resulting SQL query look like? 138 | # - Hint: Use `anti_join()` 139 | # 3. Plot a bar chart with the number of awards won and nominated per year. 140 | # Compute as much as possible on the database. 141 | # - Hint: "Long form" or "wide form"? 142 | -------------------------------------------------------------------------------- /db_13_solutions.R: -------------------------------------------------------------------------------- 1 | # attach relevant packages 2 | library(tidyverse) 3 | 4 | # Connection ------------------------------------------------------------------- 5 | 6 | con <- DBI::dbConnect(duckdb::duckdb()) 7 | dm::copy_dm_to(con, dm::dm_pixarfilms(), set_key_constraints = FALSE, temporary = FALSE) 8 | 9 | # Lazy tables ------------------------------------------------------------------ 10 | 11 | pixar_films <- tbl(con, "pixar_films") 12 | academy <- tbl(con, "academy") 13 | 14 | # Downsizing on the database: Exercises ---------------------------------------- 15 | 16 | # `count()`, `summarize()`, `group_by()`, `ungroup()` -------------------------- 17 | 18 | pixar_films 19 | 20 | # 1. How many films are stored in the table? 21 | 22 | count(pixar_films) 23 | 24 | # 2. How many films released after 2005 are stored in the table? 25 | 26 | filter(pixar_films, release_date >= as.Date("2006-01-01")) |> 27 | count() 28 | 29 | # 3. What is the total run time of all films? 30 | # - Hint: Use `summarize(sum(...))`, watch out for the warning 31 | 32 | summarize(pixar_films, total_time = sum(run_time, na.rm = TRUE)) 33 | 34 | # 4. What is the total run time of all films, per rating? 35 | # - Hint: Use `group_by()` or `.by` 36 | 37 | pixar_films |> 38 | summarize(.by = film_rating, total_time = sum(run_time, na.rm = TRUE)) 39 | 40 | # `left_join()` -------------------------------------------------------------------- 41 | 42 | # 1. How many rows does the join between `academy` and `pixar_films` contain? 43 | # Try to find out without loading all the data into memory. Explain. 44 | 45 | left_join(pixar_films, academy, join_by(film)) |> 46 | count() 47 | 48 | count(academy) 49 | 50 | # 2. Which films are not yet listed in the `academy` table? What does the 51 | # resulting SQL query look like? 52 | # - Hint: Use `anti_join()` 53 | 54 | anti_join(pixar_films, academy, join_by(film)) 55 | 56 | # 3. Plot a bar chart with the number of awards won and nominated per year. 57 | # Compute as much as possible on the database. 58 | # - Hint: "Long form" or "wide form"? 59 | 60 | academy_won_nominated <- 61 | academy |> 62 | filter(status %in% c("Nominated", "Won")) |> 63 | select(film, status) 64 | 65 | per_year_won_nominated <- 66 | pixar_films |> 67 | transmute(film, year = year(release_date)) |> 68 | inner_join(academy_won_nominated, join_by(film)) |> 69 | count(year, status) |> 70 | collect() 71 | per_year_won_nominated 72 | 73 | ggplot(per_year_won_nominated, aes(x = year, y = n, fill = status)) + 74 | geom_col() 75 | 76 | # dbDisconnect(con) 77 | -------------------------------------------------------------------------------- /db_21.R: -------------------------------------------------------------------------------- 1 | library(DBI) 2 | library(tidyverse) 3 | requireNamespace("duckplyr") 4 | 5 | ### Working with database dumps ################################################# 6 | 7 | # Create data ------------------------------------------------------------------- 8 | 9 | arrow::write_parquet(nycflights13::flights, "flights.parquet") 10 | 11 | fs::file_size("flights.parquet") 12 | object.size(nycflights13::flights) 13 | 14 | # Processing the local data ---- 15 | 16 | # Read as tibble ---- 17 | 18 | df <- arrow::read_parquet("flights.parquet") 19 | df 20 | 21 | # Read as Arrow dataset ---- 22 | 23 | ds <- arrow::open_dataset("flights.parquet") 24 | ds 25 | ds |> 26 | count(year, month, day) |> 27 | collect() 28 | 29 | # Register as duckdb lazy table ---- 30 | 31 | con_memory <- dbConnect(duckdb::duckdb(), dbdir = ":memory:") 32 | 33 | tbl <- duckdb::tbl_file(con_memory, "flights.parquet") 34 | tbl 35 | class(tbl) 36 | 37 | tbl |> 38 | count(year, month, day) 39 | 40 | tbl |> 41 | count(year, month, day) |> 42 | filter(month == 1) |> 43 | explain() 44 | 45 | # The future: Register as duckplyr lazy data frame ---- 46 | 47 | duckplyr_df <- duckplyr::duckplyr_df_from_parquet("flights.parquet") 48 | class(duckplyr_df) 49 | 50 | filtered <- 51 | duckplyr_df |> 52 | count(year, month, day) |> 53 | filter(month == 1) 54 | 55 | filtered |> 56 | explain() 57 | 58 | filtered 59 | 60 | filtered |> 61 | explain() 62 | 63 | duckplyr_df |> 64 | count(year, month, day) |> 65 | filter(month == 1L) |> 66 | explain() 67 | 68 | # Create partitioned data ------------------------------------------------------------------ 69 | 70 | arrow::write_dataset( 71 | nycflights13::flights, 72 | "flights-part/", 73 | partitioning = c("year", "month") 74 | ) 75 | 76 | fs::dir_tree("flights-part") 77 | 78 | # Read partitioned data ------------------------------------------------------------------ 79 | 80 | tbl_part <- duckdb::tbl_query( 81 | con_memory, 82 | "read_parquet('flights-part/*/*/*.parquet', hive_partitioning = true)" 83 | ) 84 | tbl_part 85 | class(tbl_part) 86 | 87 | tbl_part |> 88 | count(year, month, day) 89 | 90 | tbl_part |> 91 | filter(month %in% 1:3) |> 92 | explain() 93 | 94 | # Create CSV data ------------------------------------------------------------------------ 95 | 96 | readr::write_csv(nycflights13::flights, "flights.csv") 97 | 98 | # Read CSV data -------------------------------------------------------------------------- 99 | 100 | tbl_csv <- duckdb::tbl_file(con_memory, "flights.csv") 101 | 102 | tbl_csv |> 103 | count(year, month, day) 104 | 105 | tbl_csv |> 106 | count(year, month, day) |> 107 | explain() 108 | 109 | duckplyr_df_csv <- duckplyr::duckplyr_df_from_csv("flights.csv") 110 | 111 | duckplyr_df_csv |> 112 | count(year, month, day) 113 | 114 | duckplyr_df_csv |> 115 | count(year, month, day) |> 116 | explain() 117 | 118 | # Create derived Parquet data with duckplyr --------------------------------------------------------- 119 | 120 | duckplyr_df_csv |> 121 | count(year, month, day) |> 122 | duckplyr::df_to_parquet("flights-count.parquet") 123 | 124 | fs::file_size("flights-count.parquet") 125 | 126 | duckplyr_df_count <- 127 | duckplyr::duckplyr_df_from_parquet("flights-count.parquet") 128 | 129 | duckplyr_df_count |> 130 | explain() 131 | 132 | duckplyr_df_count 133 | 134 | duckplyr_df_count |> 135 | explain() 136 | 137 | # Exercises ------------------------------------------------------------------------- 138 | 139 | # 1. From the Parquet file, compute a lazy dbplyr tables 140 | # showing the mean and median departure delay 141 | # for each month. 142 | # 2. Compute the same data as duckplyr lazy data frames. 143 | # 3. Store this data as a Parquet file. 144 | # 4. Read the Parquet file and plot the data. 145 | -------------------------------------------------------------------------------- /db_21_solutions.R: -------------------------------------------------------------------------------- 1 | library(DBI) 2 | library(tidyverse) 3 | requireNamespace("duckplyr") 4 | 5 | arrow::write_parquet(nycflights13::flights, "flights.parquet") 6 | 7 | # 1. From the Parquet file, compute a lazy dbplyr tables 8 | # showing the mean and median departure delay 9 | # for each month. 10 | 11 | con <- dbConnect(duckdb::duckdb(), dbdir = ":memory:") 12 | 13 | flights <- duckdb::tbl_file(con, "flights.parquet") 14 | 15 | month_delay <- 16 | flights |> 17 | summarise( 18 | .by = month, 19 | mean_delay = mean(dep_delay), 20 | median_delay = median(dep_delay) 21 | ) 22 | 23 | month_delay 24 | 25 | # 2. Compute the same data as duckplyr lazy data frames. 26 | 27 | nycflights13::flights |> 28 | select(month, dep_delay) |> 29 | duckplyr::as_duckplyr_df() |> 30 | summarise( 31 | .by = month, 32 | mean_delay = mean(dep_delay), 33 | median_delay = median(dep_delay) 34 | ) 35 | 36 | # 3. Store this data as a Parquet file. 37 | 38 | nycflights13::flights |> 39 | select(month, dep_delay) |> 40 | duckplyr::as_duckplyr_df() |> 41 | summarise( 42 | .by = month, 43 | mean_delay = mean(dep_delay), 44 | median_delay = median(dep_delay), 45 | ) |> 46 | duckplyr::df_to_parquet("delay-by-month.parquet") 47 | 48 | # 4. Read the Parquet file and plot the data. 49 | 50 | library(ggplot2) 51 | 52 | duckplyr::duckplyr_df_from_parquet("delay-by-month.parquet") |> 53 | pivot_longer(cols = c(mean_delay, median_delay), names_to = "delay_type", values_to = "delay") |> 54 | ggplot(aes(x = month, y = delay, color = delay_type)) + 55 | geom_point() + 56 | geom_line() + 57 | labs(title = "Mean delay by month") 58 | -------------------------------------------------------------------------------- /db_22.R: -------------------------------------------------------------------------------- 1 | library(DBI) 2 | library(dplyr) 3 | 4 | ### DuckDB + SQL showcase ####################################################### 5 | 6 | # Create data ------------------------------------------------------------------- 7 | 8 | arrow::write_parquet(nycflights13::flights, "flights.parquet") 9 | con_memory <- dbConnect(duckdb::duckdb(), dbdir = ":memory:") 10 | tbl <- duckdb::tbl_file(con_memory, "flights.parquet") 11 | 12 | # Application: DBI <=> dbplyr and pivoting ------------------------------------------------- 13 | 14 | daily_flights_by_dest <- 15 | tbl |> 16 | count(year, month, day, dest) 17 | 18 | daily_flights_by_dest 19 | 20 | daily_flights_by_dest_sql <- 21 | daily_flights_by_dest |> 22 | dbplyr::sql_render() 23 | daily_flights_by_dest_sql 24 | 25 | pivot_sql <- paste0( 26 | "PIVOT (", daily_flights_by_dest_sql, ") ON dest USING SUM(n)" 27 | ) 28 | 29 | as_tibble(dbGetQuery(con_memory, pivot_sql)) 30 | 31 | system.time( 32 | as_tibble(dbGetQuery(con_memory, pivot_sql)) 33 | ) 34 | 35 | system.time( 36 | nycflights13::flights |> 37 | count(year, month, day, dest) |> 38 | tidyr::pivot_wider(names_from = dest, values_from = n, values_fill = 0) 39 | ) 40 | 41 | write_pivot_sql <- paste0( 42 | "COPY (", pivot_sql, ") TO 'pivot.parquet' (FORMAT PARQUET)" 43 | ) 44 | dbExecute(con_memory, write_pivot_sql) 45 | 46 | q_unpivot_dyn <- 47 | "(SELECT * FROM ( 48 | UNPIVOT 'pivot.parquet' 49 | ON COLUMNS(* EXCLUDE (year, month, day)) 50 | INTO NAME dest VALUE n))" 51 | tbl(con_memory, from = q_unpivot_dyn) 52 | -------------------------------------------------------------------------------- /db_23.R: -------------------------------------------------------------------------------- 1 | library(DBI) 2 | library(duckdb) 3 | library(dplyr) 4 | library(dbplyr) 5 | 6 | ### Database dumps ############################################################# 7 | 8 | # Connection ------------------------------------------------------------------- 9 | 10 | if (fs::file_exists("flights.duckdb")) { 11 | fs::file_delete("flights.duckdb") 12 | } 13 | 14 | con_rw <- dbConnect(duckdb::duckdb(), dbdir = "flights.duckdb") 15 | flights_duckdb <- copy_to( 16 | con_rw, 17 | nycflights13::flights, 18 | name = "flights", 19 | temporary = FALSE 20 | ) 21 | dbDisconnect(con_rw) 22 | 23 | # Exploration ---- 24 | 25 | con <- dbConnect( 26 | duckdb::duckdb(), 27 | dbdir = "flights.duckdb", 28 | read_only = TRUE 29 | ) 30 | flights_duckdb <- tbl(con, "flights") 31 | 32 | # Method 1: via local data frame ---- 33 | 34 | flights_duckdb |> 35 | filter(month == 1) |> 36 | collect() |> 37 | duckplyr::df_to_parquet("flights-jan.parquet") 38 | 39 | flights_duckdb |> 40 | collect() |> 41 | duckplyr::df_to_parquet("flights.parquet") 42 | 43 | # Method 2: via DBI ---- 44 | 45 | sql_jan <- flights_duckdb |> 46 | filter(month == 1) |> 47 | dbplyr::sql_render() 48 | 49 | fs::dir_create("flights-arrow") 50 | 51 | res <- dbSendQuery(con, sql_jan) 52 | i <- 0 53 | repeat { 54 | df <- dbFetch(res, n = 10000) 55 | if (nrow(df) == 0) break 56 | path <- fs::path("flights-arrow", sprintf("part-%05d.parquet", i)) 57 | duckplyr::df_to_parquet(df, path) 58 | i <- i + 1 59 | message("Written ", nrow(df), " rows to ", path) 60 | } 61 | dbClearResult(res) 62 | 63 | fs::dir_tree("flights-arrow/") 64 | 65 | # Method 3: via parquetize ---- 66 | 67 | parquetize::dbi_to_parquet( 68 | con, 69 | sql_jan, 70 | "flights-parquetized", 71 | max_rows = 10000 72 | ) 73 | 74 | fs::dir_tree("flights-parquetized/") 75 | 76 | # Method 4: via DBI and arrow ---- 77 | 78 | con_adbi <- dbConnect( 79 | adbi::adbi(duckdb::duckdb_adbc()), 80 | path = "flights.duckdb" 81 | ) 82 | 83 | sql <- "SELECT * FROM flights" 84 | 85 | res <- dbSendQueryArrow(con_adbi, sql) 86 | stream <- dbFetchArrow(res) 87 | arrow::write_dataset( 88 | arrow::as_record_batch_reader(stream), 89 | "flights-adbi/" 90 | ) 91 | dbClearResult(res) 92 | 93 | # Partitions ---- 94 | 95 | nycflights13::flights |> 96 | arrow::write_dataset( 97 | "flights-part-arrow/", 98 | partitioning = "month" 99 | ) 100 | 101 | fs::dir_tree("flights-part-arrow/") 102 | 103 | # Adding partitions to a dataset ---- 104 | 105 | write_month <- function(month) { 106 | sql <- flights_duckdb |> 107 | filter(month == !!month) |> 108 | dbplyr::sql_render() 109 | 110 | dir <- fs::path( 111 | "flights-part-manual", 112 | sprintf("month=%d", month) 113 | ) 114 | fs::dir_create(dir) 115 | 116 | df <- dbGetQuery(con, sql) 117 | duckplyr::df_to_parquet( 118 | df, 119 | fs::path(dir, "part-0.parquet") 120 | ) 121 | } 122 | 123 | write_month(1) 124 | write_month(2) 125 | write_month(3) 126 | 127 | fs::dir_tree("flights-part-manual") 128 | 129 | # Exercises ------------------------------------------------------------------------- 130 | 131 | 132 | 133 | # 1. Write code to create a partitioned dataset with the `flights` table, 134 | # partitioned by `origin`. 135 | # - Hint: The dataset only contains flights departing from New York City airports. 136 | -------------------------------------------------------------------------------- /db_23_solutions.R: -------------------------------------------------------------------------------- 1 | # 1. Write code to create a partitioned dataset with the `flights` table, 2 | # partitioned by `origin`. 3 | # - Hint: The dataset only contains flights departing from New York City airports. 4 | 5 | con_rw <- DBI::dbConnect( 6 | duckdb::duckdb(), 7 | dbdir = "flights.duckdb", 8 | read_only = FALSE 9 | ) 10 | 11 | DBI::dbExecute(con_rw, "DROP TABLE IF EXISTS flights;") 12 | 13 | flights_duckdb <- dplyr::copy_to( 14 | con_rw, 15 | nycflights13::flights, 16 | name = "flights", 17 | temporary = FALSE, 18 | overwrite = TRUE 19 | ) 20 | 21 | dplyr::tbl(con_rw, "flights") |> 22 | dplyr::distinct(origin) 23 | 24 | # Method 1 --------------------------------------------------------------------- 25 | 26 | # DB-agnositic 27 | 28 | ewr <- 29 | dplyr::tbl(con_rw, "flights") |> 30 | dplyr::filter(origin == "EWR") |> 31 | dplyr::collect() 32 | 33 | lga <- 34 | dplyr::tbl(con_rw, "flights") |> 35 | dplyr::filter(origin == "LGA") |> 36 | dplyr::collect() 37 | 38 | jfk <- 39 | dplyr::tbl(con_rw, "flights") |> 40 | dplyr::filter(origin == "JFK") |> 41 | dplyr::collect() 42 | 43 | purrr::walk2( 44 | list(ewr, lga, jfk), 45 | list("EWR", "LGA", "JFK"), 46 | function(x, y) { 47 | if (!fs::dir_exists("manual-partition-flights")) { 48 | fs::dir_create("manual-partition-flights") 49 | } 50 | out_path <- fs::dir_create( 51 | fs::path("manual-partition-flights", paste0("origin=", y)) 52 | ) 53 | duckplyr::df_to_parquet( 54 | x, 55 | fs::path(out_path, "part-0.parquet") 56 | ) 57 | } 58 | ) 59 | 60 | # Method 2 --------------------------------------------------------------------- 61 | 62 | # If on DuckDB 63 | 64 | DBI::dbExecute( 65 | con_rw, 66 | "COPY flights TO 'flights-partion' (FORMAT PARQUET, PARTITION_BY origin);" 67 | ) 68 | 69 | # Method 3 --------------------------------------------------------------------- 70 | 71 | # If on DuckDB 72 | 73 | dplyr::tbl(con_rw, "flights") |> 74 | arrow::to_arrow() |> 75 | arrow::write_dataset("flights-partition-arrow", partitioning = "origin") 76 | -------------------------------------------------------------------------------- /db_31.R: -------------------------------------------------------------------------------- 1 | # attach relevant packages 2 | library(tidyverse) 3 | library(DBI) 4 | 5 | ### Extract, Transform, Load ################################################### 6 | 7 | # Extract: Raw data ------------------------------------------------------------ 8 | 9 | pixar_films_raw <- pixarfilms::pixar_films 10 | pixar_films_raw 11 | 12 | # Transform: Fix column type, extract sequel column ---------------------------- 13 | 14 | pixar_films_clean <- 15 | pixar_films_raw |> 16 | separate(film, into = c("franchise", "sequel"), 17 | sep = " (?=[0-9]+$)", fill = "right", remove = FALSE 18 | ) |> 19 | mutate(across(c(number, sequel), as.integer)) |> 20 | mutate(.by = franchise, sequel = if_else(is.na(sequel) & n() > 1, 1L, sequel)) 21 | pixar_films_clean 22 | 23 | # Create target database ------------------------------------------------------- 24 | 25 | if (fs::file_exists("pixar.duckdb")) { 26 | fs::file_delete("pixar.duckdb") 27 | } 28 | 29 | # Load: Write table to the database -------------------------------------------- 30 | 31 | con_rw <- dbConnect(duckdb::duckdb(), dbdir = "pixar.duckdb") 32 | con_rw 33 | 34 | if (!dbExistsTable(con_rw, "pixar_films")) { 35 | dbWriteTable(con_rw, "pixar_films", pixar_films_clean) 36 | dbExecute(con_rw, "CREATE UNIQUE INDEX pixarfilms_pk ON pixar_films (film)") 37 | } 38 | 39 | dbDisconnect(con_rw) 40 | 41 | # Reload: Write table to the database if the table exists ---------------------------------- 42 | 43 | con_rw <- dbConnect(duckdb::duckdb(), dbdir = "pixar.duckdb") 44 | con_rw 45 | 46 | dbExecute(con_rw, "TRUNCATE TABLE pixar_films") 47 | dbAppendTable(con_rw, "pixar_films", pixar_films_clean) 48 | 49 | dbDisconnect(con_rw) 50 | 51 | # Consume: share the file, open it --------------------------------------------- 52 | 53 | con <- dbConnect(duckdb::duckdb(), dbdir = "pixar.duckdb") 54 | my_pixar_films <- tbl(con, "pixar_films") 55 | my_pixar_films 56 | 57 | # Exercises -------------------------------------------------------------------- 58 | 59 | pixar_films_raw 60 | 61 | # 1. Adapt the ETL workflow to convert the `run_time` column to a duration. 62 | # - Hint: Use `mutate()` with `hms::hms(minutes = ...)` . 63 | # 2. Re-run the workflow. 64 | 65 | dbDisconnect(con) 66 | -------------------------------------------------------------------------------- /db_31_solutions.R: -------------------------------------------------------------------------------- 1 | # attach relevant packages 2 | library(tidyverse) 3 | library(DBI) 4 | 5 | ### Extract, Transform, Load ################################################### 6 | 7 | # Extract: Raw data ------------------------------------------------------------ 8 | 9 | pixar_films_raw <- pixarfilms::pixar_films 10 | 11 | # Transform: Fix column type, extract sequel column ---------------------------- 12 | 13 | pixar_films_clean <- 14 | pixar_films_raw |> 15 | separate(film, into = c("franchise", "sequel"), 16 | sep = " (?=[0-9]+$)", fill = "right", remove = FALSE 17 | ) |> 18 | mutate(across(c(number, sequel), as.integer)) |> 19 | mutate(.by = franchise, sequel = if_else(is.na(sequel) & n() > 1, 1L, sequel)) 20 | 21 | # Exercises -------------------------------------------------------------------- 22 | 23 | # 1. Adapt the ETL workflow to convert the `run_time` column to a duration. 24 | 25 | pixar_films_clean <- 26 | pixar_films_clean |> 27 | mutate(run_time = hms::hms(minutes = run_time)) 28 | pixar_films_clean 29 | 30 | # - Hint: Use `mutate()` with `hms::hms(minutes = ...)` . 31 | # 2. Re-run the workflow. 32 | -------------------------------------------------------------------------------- /db_32.R: -------------------------------------------------------------------------------- 1 | # attach relevant packages 2 | library(DBI) 3 | library(dm) 4 | 5 | ### Remote databases ################################################### 6 | 7 | # Connect -------------------------------------------------------------- 8 | 9 | con <- dbConnect( 10 | RMariaDB::MariaDB(), 11 | dbname = "CORA", 12 | username = "guest", 13 | password = "ctu-relational", 14 | host = "relational.fel.cvut.cz" 15 | ) 16 | 17 | # List tables ---------------------------------------------------------- 18 | 19 | dbListTables(con) 20 | 21 | # Use dm for many tables ----------------------------------------------- 22 | 23 | dm <- dm_from_con(con) 24 | 25 | dm 26 | 27 | dm |> 28 | dm_nrow() 29 | 30 | dm$paper 31 | 32 | dm |> 33 | dm_get_tables() 34 | -------------------------------------------------------------------------------- /db_33.R: -------------------------------------------------------------------------------- 1 | # attach relevant packages 2 | library(tidyverse) 3 | library(dm) 4 | 5 | # display chosen presentation (it might take a few seconds to appear) 6 | slide_viewer <- function(path) { 7 | tmp <- tempfile(fileext = ".html") 8 | file.copy(path, tmp) 9 | rstudioapi::viewer(tmp) 10 | } 11 | # slide_viewer("materials/databases.html") 12 | 13 | ### Data models ################################################################ 14 | 15 | # Data model objects ----- 16 | 17 | pixar_dm <- dm_pixarfilms() 18 | pixar_dm 19 | 20 | pixar_dm |> 21 | dm_draw() 22 | 23 | names(pixar_dm) 24 | 25 | pixar_dm$pixar_films 26 | pixar_dm$academy 27 | 28 | pixar_dm |> 29 | dm_get_tables() 30 | 31 | # Showcase: wrapping all tables in a data model: 32 | pixar_films_wrapped <- 33 | pixar_dm |> 34 | dm_wrap_tbl(pixar_films) |> 35 | pull_tbl(pixar_films) 36 | 37 | pixar_films_wrapped 38 | pixar_films_wrapped$academy[1:2] 39 | 40 | 41 | ### Keys, constraints, normalization ########################################### 42 | 43 | # Data model object ------ 44 | 45 | pixar_dm <- dm_pixarfilms() 46 | 47 | # Primary keys ---- 48 | 49 | any(duplicated(pixar_dm$pixar_films$film)) 50 | check_key(pixar_dm$pixar_films, film) 51 | any(duplicated(pixar_dm$academy[c("film", "award_type")])) 52 | check_key(pixar_dm$academy, film, award_type) 53 | try( 54 | check_key(pixar_dm$academy, film) 55 | ) 56 | 57 | # Foreign keys ---- 58 | 59 | all(pixar_dm$academy$film %in% pixar_dm$pixar_films$film) 60 | check_subset(pixar_dm$academy, film, pixar_dm$pixar_films, film) 61 | try( 62 | check_subset(pixar_dm$pixar_films, film, pixar_dm$academy, film) 63 | ) 64 | 65 | # Constraints ---- 66 | 67 | pixar_dm |> 68 | dm_examine_constraints() 69 | 70 | dm_pixarfilms(consistent = TRUE) |> 71 | dm_examine_constraints() 72 | 73 | dm_nycflights13() |> 74 | dm_examine_constraints() 75 | 76 | # Joins ---- 77 | 78 | pixar_dm |> 79 | dm_zoom_to(academy) 80 | 81 | # With zooming: 82 | pixar_dm |> 83 | dm_zoom_to(academy) |> 84 | left_join(pixar_films, select = c(film, release_date)) 85 | 86 | # With flattening: 87 | pixar_dm |> 88 | dm_flatten_to_tbl(academy) 89 | 90 | dm_nycflights13() |> 91 | dm_select(weather, -year, -month, -day, -hour) |> 92 | dm_flatten_to_tbl(flights) 93 | 94 | # Joining is easy, leave the tables separate for as long as possible! 95 | 96 | # Exercises -------------------------------------------------------------------- 97 | 98 | venue <- tibble( 99 | venue_id = character(), 100 | floor = character(), 101 | capacity = integer(), 102 | ) 103 | 104 | event <- tibble( 105 | event_id = character(), 106 | event_name = character(), 107 | event_type = character(), 108 | venue_id = character(), 109 | date_start = vctrs::new_datetime(), 110 | date_end = vctrs::new_datetime(), 111 | ) 112 | 113 | attendee <- tibble( 114 | attendee_name = character(), 115 | favorite_package = character(), 116 | ) 117 | 118 | speaker <- tibble( 119 | speaker_name = character(), 120 | event_id = character(), 121 | ) 122 | 123 | event_attendee <- tibble( 124 | event_id = character(), 125 | attendee_name = character(), 126 | ) 127 | 128 | # 1. Explore and the built-in data models 129 | # `dm_nycflights13()` and `dm_pixarfilms()` 130 | # 2. Given the table structure above, create a dm object setting suitable 131 | # PK and FK relationships and unique keys. 132 | # Each speaker is an attendee, each event has a venue and exactly one speaker. 133 | # The helper table event_attendees matches attendees to events. 134 | # - Hint: Use the `dm()` function to create a dm object from scratch 135 | # - Hint: Use a unique key on `speakers$event_name` 136 | # 3. Draw the dm object 137 | # 4. Colour the tables 138 | # - Hint: Review colors at 139 | # 5. Deploy the data model to a DuckDB database 140 | -------------------------------------------------------------------------------- /db_33_solutions.R: -------------------------------------------------------------------------------- 1 | library(tibble) 2 | library(dm) 3 | library(DBI) 4 | 5 | # 1. Explore and the built-in data models 6 | # `dm_nycflights13()` and `dm_pixarfilms()` 7 | 8 | dm_nycflights13() |> 9 | dm_draw() 10 | 11 | dm_pixarfilms() |> 12 | dm_draw(view_type = "all") 13 | 14 | # 2. 15 | 16 | venue <- tibble( 17 | venue_id = character(), 18 | floor = character(), 19 | capacity = integer(), 20 | ) 21 | 22 | event <- tibble( 23 | event_id = character(), 24 | event_name = character(), 25 | event_type = character(), 26 | venue_id = character(), 27 | date_start = vctrs::new_datetime(), 28 | date_end = vctrs::new_datetime(), 29 | ) 30 | 31 | attendee <- tibble( 32 | attendee_name = character(), 33 | favorite_package = character(), 34 | ) 35 | 36 | speaker <- tibble( 37 | speaker_name = character(), 38 | event_id = character(), 39 | ) 40 | 41 | event_attendee <- tibble( 42 | event_id = character(), 43 | attendee_name = character(), 44 | ) 45 | 46 | # 2. Given the table structure above, create a dm object setting suitable 47 | # PK and FK relationships and unique keys. 48 | # Each speaker is an attendee, each event has a venue and exactly one speaker. 49 | # The helper table event_attendees matches attendees to events. 50 | # - Hint: Use the `dm()` function to create a dm object from scratch 51 | # - Hint: Use a unique key on `speakers$event_name` 52 | dm_conf_target <- 53 | dm(venue, event, attendee, speaker, event_attendee) |> 54 | dm_add_pk(venue, venue_id) |> 55 | dm_add_pk(event, event_id) |> 56 | dm_add_pk(speaker, speaker_name) |> 57 | dm_add_pk(attendee, attendee_name) |> 58 | dm_add_fk(speaker, event_id, event) |> 59 | dm_add_fk(event, venue_id, venue) |> 60 | dm_add_fk(speaker, speaker_name, attendee, attendee_name) |> 61 | dm_add_fk(event_attendee, event_id, event) |> 62 | dm_add_fk(event_attendee, attendee_name, attendee) |> 63 | dm_add_uk(speaker, event_id) 64 | 65 | # 3. Draw the dm object 66 | dm_conf_target |> 67 | dm_draw() 68 | 69 | # 4. Color the tables (optional) 70 | dm_conf_target |> 71 | dm_set_colors( 72 | blue = event, 73 | red = venue, 74 | green3 = speaker, 75 | seagreen = attendee, 76 | ) |> 77 | dm_draw() 78 | 79 | # 5. Deploy the data model to a DuckDB database 80 | con_rw <- dbConnect(duckdb::duckdb(), "posit-conf.duckdb") 81 | dm_conf_target <- copy_dm_to(con_rw, dm_conf_target, temporary = FALSE) 82 | 83 | dbListTables(con_rw) 84 | 85 | dm_conf_target |> 86 | dm_get_tables() 87 | 88 | dbDisconnect(con_rw) 89 | -------------------------------------------------------------------------------- /db_40_solutions.R: -------------------------------------------------------------------------------- 1 | library(DBI) 2 | library(duckdb) 3 | library(dplyr) 4 | library(dm) 5 | 6 | fs::dir_create("sec") 7 | 8 | # https://www.sec.gov/files/structureddata/data/form-d-data-sets/2023q4_d.zip 9 | 10 | sec_paths <- fs::dir_ls("sec") 11 | 12 | if (FALSE) { 13 | purrr::walk(sec_paths, ~ unzip(.x, exdir = "sec-unzipped")) 14 | } 15 | 16 | if (fs::file_exists("formd.duckdb")) { 17 | fs::file_delete("formd.duckdb") 18 | } 19 | 20 | # Form D ------------------------------------------------------------------------ 21 | 22 | duckdb_con <- dbConnect(duckdb()) 23 | 24 | form_d <- duckdb::tbl_file( 25 | duckdb_con, 26 | "sec-unzipped/2023Q4_d/FORMDSUBMISSION.tsv" 27 | ) 28 | 29 | # explore column names 30 | try(names(form_d)) 31 | colnames(form_d) |> 32 | writeLines() 33 | 34 | # duplicates check 35 | form_d |> 36 | rename_with(tolower) |> 37 | summarise(.by = accessionnumber, n = n()) |> 38 | filter(n > 1) |> 39 | count() 40 | 41 | # Issuers ---------------------------------------------------------------------- 42 | 43 | issuers <- duckdb::tbl_file( 44 | duckdb_con, 45 | "sec-unzipped/2023Q4_d/ISSUERS.tsv" 46 | ) 47 | 48 | # explore column names 49 | colnames(issuers) |> 50 | writeLines() 51 | 52 | # duplicates check 53 | issuers |> 54 | rename_with(tolower) |> 55 | summarise(.by = accessionnumber, n = n()) |> 56 | filter(n > 1) |> 57 | count() 58 | 59 | issuers |> 60 | rename_with(tolower) |> 61 | summarise(.by = c(accessionnumber, issuer_seq_key), n = n()) |> 62 | filter(n > 1) |> 63 | count() 64 | 65 | 66 | # Offering --------------------------------------------------------------------- 67 | 68 | offering <- duckdb::tbl_file( 69 | duckdb_con, 70 | "sec-unzipped/2023Q4_d/OFFERING.tsv" 71 | ) 72 | 73 | # explore column names 74 | colnames(offering) |> 75 | writeLines() 76 | 77 | # duplicates check 78 | offering |> 79 | rename_with(tolower) |> 80 | summarise(.by = accessionnumber, n = n()) |> 81 | filter(n > 1) |> 82 | count() 83 | 84 | # Recipients ------------------------------------------------------------------- 85 | 86 | recipients <- duckdb::tbl_file( 87 | duckdb_con, 88 | "sec-unzipped/2023Q4_d/RECIPIENTS.tsv" 89 | ) 90 | 91 | # explore column names 92 | colnames(recipients) |> 93 | writeLines() 94 | 95 | recipients |> 96 | rename_with(tolower) |> 97 | summarise(.by = accessionnumber, n = n()) |> 98 | filter(n > 1) |> 99 | count() 100 | 101 | recipients |> 102 | rename_with(tolower) |> 103 | summarise(.by = c(accessionnumber, recipient_seq_key), n = n()) |> 104 | filter(n > 1) |> 105 | count() 106 | 107 | # dm --------------------------------------------------------------------------- 108 | 109 | dm_formd_set_pk_fk <- function(dm) { 110 | 111 | stopifnot(is_dm(dm)) 112 | 113 | dm |> 114 | dm_add_pk(form_d, ACCESSIONNUMBER, check = TRUE) |> 115 | dm_add_pk(issuers, c(ACCESSIONNUMBER, ISSUER_SEQ_KEY)) |> 116 | dm_add_pk(offering, ACCESSIONNUMBER) |> 117 | dm_add_pk(recipients, c(ACCESSIONNUMBER, RECIPIENT_SEQ_KEY)) |> 118 | dm_add_fk(issuers, ACCESSIONNUMBER, form_d) |> 119 | dm_add_fk(offering, ACCESSIONNUMBER, form_d) |> 120 | dm_add_fk(recipients, ACCESSIONNUMBER, form_d) 121 | 122 | } 123 | 124 | formd_dm_keys <- 125 | dm(form_d, issuers, offering, recipients) |> 126 | dm_formd_set_pk_fk() 127 | 128 | dm_draw(formd_dm_keys) 129 | 130 | dm_examine_constraints(formd_dm_keys) 131 | 132 | # Analyze ---------------------------------------------------------------------- 133 | 134 | base_dat <- 135 | formd_dm_keys |> 136 | dm_flatten_to_tbl(.start = issuers) |> # help(dm_flatten_to_tbl) 137 | rename_with(tolower) |> 138 | left_join( 139 | rename_with(pull_tbl(formd_dm_keys, offering), tolower), 140 | join_by(accessionnumber) 141 | ) |> 142 | mutate( 143 | filing_date = sql("STRPTIME(filing_date, '%d-%b-%Y')") 144 | ) |> 145 | mutate( 146 | filing_date = sql("CAST(filing_date AS DATE)") 147 | ) |> 148 | transmute( 149 | year = lubridate::year(filing_date), 150 | month = lubridate::month(filing_date), 151 | accessionnumber, 152 | entityname, 153 | stateorcountry, 154 | stateorcountrydescription, 155 | entitytype, 156 | federalexemptions_items_list, 157 | submissiontype, 158 | totalamountsold, 159 | totalofferingamount = as.numeric( 160 | sql("nullif(totalofferingamount, 'Indefinite')") 161 | ) 162 | ) 163 | 164 | # submissiontype per month ---- 165 | 166 | type_dat <- 167 | base_dat |> 168 | count(year, month, submissiontype) |> 169 | collect() |> 170 | mutate(filing_date = lubridate::make_date(year, month)) |> 171 | arrange(year, month) 172 | 173 | library(ggplot2) 174 | type_dat |> 175 | mutate(dte = lubridate::make_date(year, month)) |> 176 | ggplot(aes(dte, n, fill = submissiontype)) + 177 | geom_col(position = "dodge") + 178 | theme_minimal() + 179 | labs(title = "Form D submission Q1") 180 | 181 | # amount sold per state ---- 182 | base_dat |> 183 | summarise( 184 | .by = stateorcountrydescription, 185 | tot_sold = sum(totalamountsold, na.rm = TRUE), 186 | tot_offered = sum(totalofferingamount, na.rm = TRUE) 187 | ) |> 188 | filter(tot_sold > 0) |> 189 | collect() |> 190 | mutate( 191 | stateorcountrydescription = forcats::fct_reorder( 192 | stateorcountrydescription, 193 | tot_sold 194 | ) 195 | ) |> 196 | ggplot(aes(stateorcountrydescription, tot_sold)) + 197 | geom_col() + 198 | coord_flip() + 199 | theme_minimal() 200 | 201 | 202 | # rank ten best raising capital ---- 203 | base_dat |> 204 | dbplyr::window_order(totalamountsold) |> 205 | mutate(row_num = row_number()) |> 206 | filter(between(row_num, max(row_num) - 9L, max(row_num))) |> 207 | collect() |> 208 | arrange(desc(totalamountsold)) |> 209 | select(entityname, totalamountsold) 210 | 211 | # Multi ------------------------------------------------------------------------ 212 | 213 | q_form_d <- 214 | "CREATE OR REPLACE TABLE form_d AS 215 | SELECT * 216 | FROM read_csv( 217 | 'sec-unzipped/*/FORMDSUBMISSION.tsv', 218 | types={'FILING_DATE': 'VARCHAR'} 219 | ); 220 | " 221 | 222 | dbExecute(duckdb_con, q_form_d) 223 | 224 | q_issuers <- 225 | "CREATE OR REPLACE TABLE issuers AS 226 | SELECT * 227 | FROM read_csv( 228 | 'sec-unzipped/*/ISSUERS.tsv' 229 | ); 230 | " 231 | 232 | dbExecute(duckdb_con, q_issuers) 233 | 234 | q_offering <- 235 | "CREATE OR REPLACE TABLE offering AS 236 | SELECT * 237 | FROM read_csv('sec-unzipped/*/OFFERING.tsv'); 238 | " 239 | 240 | dbExecute(duckdb_con, q_offering) 241 | 242 | q_recipients <- 243 | "CREATE OR REPLACE TABLE recipients AS 244 | SELECT * 245 | FROM read_csv('sec-unzipped/*/RECIPIENTS.tsv'); 246 | " 247 | 248 | dbExecute(duckdb_con, q_recipients) 249 | 250 | stopifnot(length(dbListTables(duckdb_con)) == 4L) 251 | 252 | formd_dm <- 253 | dm::dm_from_con(duckdb_con) |> 254 | dm_formd_set_pk_fk() 255 | 256 | dbDisconnect(duckdb_con) 257 | -------------------------------------------------------------------------------- /workshop-conf-2024.Rproj: -------------------------------------------------------------------------------- 1 | Version: 1.0 2 | 3 | RestoreWorkspace: Default 4 | SaveWorkspace: Default 5 | AlwaysSaveHistory: Default 6 | 7 | EnableCodeIndexing: Yes 8 | UseSpacesForTab: Yes 9 | NumSpacesForTab: 2 10 | Encoding: UTF-8 11 | 12 | RnwWeave: Sweave 13 | LaTeX: pdfLaTeX 14 | --------------------------------------------------------------------------------