Spaces:
Running
Running
File size: 49,951 Bytes
e5fc993 34f04d3 e5fc993 dd84d5b e5fc993 34f04d3 e5fc993 34f04d3 e5fc993 34f04d3 e5fc993 34f04d3 e5fc993 34f04d3 e5fc993 34f04d3 e5fc993 34f04d3 e5fc993 34f04d3 e5fc993 34f04d3 e5fc993 34f04d3 e5fc993 34f04d3 e5fc993 34f04d3 e5fc993 34f04d3 e5fc993 34f04d3 e5fc993 34f04d3 e5fc993 34f04d3 e5fc993 34f04d3 e5fc993 34f04d3 e5fc993 34f04d3 e5fc993 34f04d3 e5fc993 34f04d3 e5fc993 34f04d3 e5fc993 34f04d3 e5fc993 34f04d3 e5fc993 34f04d3 e5fc993 34f04d3 e5fc993 34f04d3 e5fc993 34f04d3 e5fc993 34f04d3 e5fc993 34f04d3 e5fc993 34f04d3 e5fc993 34f04d3 e5fc993 34f04d3 e5fc993 dd84d5b e5fc993 34f04d3 e5fc993 34f04d3 e5fc993 34f04d3 e5fc993 dd84d5b e5fc993 34f04d3 dd84d5b 34f04d3 e5fc993 34f04d3 e5fc993 34f04d3 e5fc993 dd84d5b e5fc993 dd84d5b 34f04d3 e5fc993 dd84d5b 34f04d3 e5fc993 34f04d3 e5fc993 34f04d3 e5fc993 dd84d5b e5fc993 34f04d3 e5fc993 34f04d3 e5fc993 34f04d3 e5fc993 34f04d3 e5fc993 dd84d5b e5fc993 dd84d5b 34f04d3 e5fc993 dd84d5b e5fc993 dd84d5b e5fc993 34f04d3 e5fc993 34f04d3 e5fc993 dd84d5b e5fc993 dd84d5b e5fc993 dd84d5b 34f04d3 e5fc993 34f04d3 e5fc993 34f04d3 e5fc993 dd84d5b 34f04d3 e5fc993 34f04d3 e5fc993 dd84d5b 34f04d3 e5fc993 dd84d5b e5fc993 34f04d3 dd84d5b 34f04d3 e5fc993 34f04d3 e5fc993 34f04d3 dd84d5b e5fc993 dd84d5b 34f04d3 e5fc993 34f04d3 e5fc993 34f04d3 e5fc993 dd84d5b e5fc993 34f04d3 e5fc993 dd84d5b e5fc993 34f04d3 e5fc993 34f04d3 e5fc993 34f04d3 dd84d5b e5fc993 dd84d5b 34f04d3 dd84d5b 34f04d3 e5fc993 34f04d3 e5fc993 34f04d3 e5fc993 34f04d3 e5fc993 34f04d3 e5fc993 34f04d3 e5fc993 34f04d3 e5fc993 34f04d3 e5fc993 34f04d3 e5fc993 34f04d3 e5fc993 34f04d3 e5fc993 34f04d3 e5fc993 34f04d3 e5fc993 dd84d5b e5fc993 34f04d3 e5fc993 dd84d5b e5fc993 34f04d3 e5fc993 34f04d3 e5fc993 34f04d3 e5fc993 34f04d3 e5fc993 34f04d3 e5fc993 34f04d3 e5fc993 34f04d3 e5fc993 34f04d3 e5fc993 34f04d3 e5fc993 34f04d3 e5fc993 34f04d3 e5fc993 34f04d3 e5fc993 34f04d3 e5fc993 34f04d3 e5fc993 34f04d3 e5fc993 34f04d3 e5fc993 34f04d3 e5fc993 34f04d3 e5fc993 dd84d5b e5fc993 dd84d5b |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 |
# /// script
# requires-python = ">=3.11"
# dependencies = [
# "marimo",
# "duckdb==1.2.2",
# "polars==1.27.0",
# "numpy==2.2.4",
# "pyarrow==19.0.1",
# "pandas==2.2.3",
# "sqlglot==26.12.1",
# "plotly==5.23.1",
# "statsmodels==0.14.4",
# ]
# ///
import marimo
__generated_with = "0.13.4"
app = marimo.App(width="medium")
@app.cell(hide_code=True)
def _(mo):
mo.md(
rf"""
<p align="center">
<img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSxHAqB0W_61zuIGVMiU6sEeQyTaw-9xwiprw&s" alt="DuckDB Image"/>
</p>
"""
)
return
@app.cell(hide_code=True)
def _(mo):
mo.md(
rf"""
# 🦆 **DuckDB**: An Embeddable Analytical Database System
## What is DuckDB?
[DuckDB](https://duckdb.org/) is a _high-performance_, in-process, embeddable SQL OLAP (Online Analytical Processing) Database Management System (DBMS) designed for simplicity and speed. It's essentially a fully-featured database that runs directly within your application's process, without needing a separate server. This makes it excellent for complex analytical workloads, offering a robust SQL interface and efficient processing – perfect for learning about databases and data analysis concepts. It's a great alternative to heavier database systems like PostgreSQL or MySQL when you don't need a full-blown server.
---
## ⚡ Key Features
| Feature | Description |
|:---------|:-------------|
| **In-Process Architecture** | Runs directly within your application's memory space - no separate server needed, simplifying deployment |
| **Columnar Storage** | Data stored in columns instead of rows, dramatically improving performance for analytical queries |
| **Vectorized Execution** | Performs operations on entire columns at once, significantly speeding up data processing |
| **ACID Transactions** | Ensures data integrity and reliability across operations |
| **Multi-Language Support** | Provides APIs for `Python`, `R`, `Java`, `C++`, and more |
| **Zero External Dependencies** | Minimal dependencies, making setup and deployment straightforward |
| **High Portability** | Works across various operating systems (Windows, macOS, Linux) and hardware architectures |
---
## [Use Cases](https://github.com/davidgasquez/awesome-duckdb?tab=readme-ov-file):
- **Data Analysis and Exploration:** DuckDB is ideal for quickly querying and analyzing datasets, especially for initial exploratory analysis.
- **Embedded Analytics in Applications:** You can integrate DuckDB directly into your applications to provide analytical capabilities without the need for a separate database server.
- **ETL (Extract, Transform, Load) Processes:** DuckDB can be used to perform initial data transformation and cleaning steps as part of an ETL pipeline.
- **Data Science and Machine Learning Workflows:** It's a lightweight alternative to larger databases for prototyping data analysis and machine learning models.
- **Rapid Prototyping of Data Analysis Pipelines:** Quickly test and iterate on data analysis ideas without the complexity of setting up a full-blown database environment.
- **Small to Medium Datasets:** DuckDB shines when working with datasets that don't require the massive scalability of a traditional database server.
---
### [Installation](https://duckdb.org/docs/installation/?version=stable&environment=python):
- Python installation:
```
pip install duckdb
```
```
conda install python-duckdb -c conda-forge.
```
<!-- >**_Note_:** DuckDB requires Python 3.7 or newer. You also need to have Python and `pip` or `conda` installed on your system. -->
/// attention | Note
DuckDB requires Python 3.7 or newer. You also need to have Python and `pip` or `conda` installed on your system.
///
"""
)
return
@app.cell(hide_code=True)
def _(mo):
mo.md(
r"""
# [1. DuckDB Connections: In-Memory vs. File-based](https://duckdb.org/docs/stable/connect/overview.html)
DuckDB is a lightweight, _relational database management system (RDBMS)_ designed for analytical workloads. Unlike traditional client-server databases, it operates _in-process_ (embedded within your application) and supports both _in-memory_ (temporary) and _file-based_ (persistent) storage.
---
| Feature | In-Memory Connection | File-Based Connection |
|:---------|:---------------------|:----------------------|
| Persistence | Temporary (lost when session ends) | Stored on disk (persists between sessions) |
| Use Cases | Quick analysis, ephemeral data, testing | Long-term storage, data that needs to be accessed later |
| Performance | Faster for most operations | Slightly slower but provides persistence |
| Creation | duckdb.connect(':memory:') | duckdb.connect('filename.db') |
| Multiple Connection Access | Limited to single connection | Multiple connections can access the same database |
"""
)
return
@app.cell(hide_code=True)
def _(os):
# Remove previous database if it exists
if os.path.exists("example.db"):
os.remove("example.db")
if not os.path.exists("data"):
os.makedirs("data")
return
@app.cell(hide_code=True)
def _(mo):
_df = mo.sql(
f"""
-- Print the DuckDB version
SELECT version() AS version_info
"""
)
return
@app.cell(hide_code=True)
def _(mo):
mo.md(
"""
## Creating DuckDB Connections
Let's create both types of DuckDB connections and explore their characteristics.
1. **In-memory connection**: Data exists only during the current session
2. **File-based connection**: Data persists between sessions
We'll then demonstrate the key differences between these connection types.
"""
)
return
@app.cell(hide_code=True)
def _(duckdb):
# Create an in-memory DuckDB connection
memory_db = duckdb.connect(":memory:")
# Create a file-based DuckDB connection
file_db = duckdb.connect("example.db")
return file_db, memory_db
@app.cell(hide_code=True)
def _(file_db, memory_db):
# Test both connections
memory_db.execute(
"CREATE TABLE IF NOT EXISTS mem_test (id INTEGER, name VARCHAR)"
)
memory_db.execute("INSERT INTO mem_test VALUES (1, 'Memory Test')")
file_db.execute(
"CREATE TABLE IF NOT EXISTS file_test (id INTEGER, name VARCHAR)"
)
file_db.execute("INSERT INTO file_test VALUES (1, 'File Test')")
return
@app.cell(hide_code=True)
def _(mo):
mo.md(
r"""
## Testing Connection Persistence
Let's demonstrate how in-memory databases are ephemeral, while file-based databases persist.
1. First, we'll query our tables to confirm the data was properly inserted
2. Then, we'll simulate an application restart by creating new connections
3. Finally, we'll check which data persists after the "restart"
"""
)
return
@app.cell(hide_code=True)
def _(mo):
mo.md(r"""## Current Database Contents""")
return
@app.cell(hide_code=True)
def _(mem_test, memory_db, mo):
_df = mo.sql(
f"""
SELECT * FROM mem_test
""",
engine=memory_db
)
return
@app.cell(hide_code=True)
def _(file_db, file_test, mo):
_df = mo.sql(
f"""
SELECT * FROM file_test
""",
engine=file_db
)
return
@app.cell
def _():
# We don't actually close the connections here since we need them for later cells
# Just a placeholder for the concept
return
@app.cell(hide_code=True)
def _(mo):
mo.md(rf"""## 🔄 Simulating Application Restart...""")
return
@app.cell(hide_code=True)
def _(duckdb):
# Create new connections (simulating restart)
new_memory_db = duckdb.connect(":memory:")
new_file_db = duckdb.connect("example.db")
return new_file_db, new_memory_db
@app.cell(hide_code=True)
def _(new_memory_db):
# Try to query tables in the new memory connection
try:
new_memory_db.execute("SELECT * FROM mem_test").df()
memory_persistence = "✅ Data persisted in memory (unexpected)"
memory_data_available = True
except Exception as e:
memory_persistence = "❌ Data lost from memory (expected behavior)"
memory_data_available = False
return memory_data_available, memory_persistence
@app.cell(hide_code=True)
def _(new_file_db):
# Try to query tables in the new file connection
try:
file_data = new_file_db.execute("SELECT * FROM file_test").df()
file_persistence = "✅ Data persisted in file (expected behavior)"
file_data_available = True
except Exception as e:
file_persistence = "❌ Data lost from file (unexpected)"
file_data_available = False
file_data = None
return file_data, file_data_available, file_persistence
@app.cell(hide_code=True)
def _(
file_data_available,
file_persistence,
memory_data_available,
memory_persistence,
mo,
):
# Create an interactive display to show persistence results
persistence_results = mo.ui.table(
{
"Connection Type": ["In-Memory Database", "File-Based Database"],
"Persistence Status": [memory_persistence, file_persistence],
"Data Available After Restart": [
memory_data_available,
file_data_available,
],
}
)
return (persistence_results,)
@app.cell(hide_code=True)
def _(mo, persistence_results):
mo.vstack(
[
mo.vstack([mo.md(f"""## Persistence Test Results""")], align="center"),
persistence_results,
],
gap=2,
justify="space-between",
)
return
@app.cell(hide_code=True)
def _(file_data, file_data_available, mo):
if file_data_available:
mo.md("### Persisted File-Based Data:")
mo.ui.table(file_data)
return
@app.cell(hide_code=True)
def _(mo):
mo.md(
r"""
# [2. Creating Tables in DuckDB](https://duckdb.org/docs/stable/sql/statements/create_table.html)
DuckDB supports standard SQL syntax for creating tables. Let's create more complex tables to demonstrate different data types and constraints.
## Table Creation Options
DuckDB supports various table creation options, including:
- **Basic tables** with column definitions
- **Temporary tables** that exist only during the session
- **CREATE OR REPLACE** to recreate tables
- **Primary keys** and other constraints
- **Various data types** including INTEGER, VARCHAR, TIMESTAMP, DECIMAL, etc.
"""
)
return
@app.cell(hide_code=True)
def _(file_db, new_memory_db):
# For the memory database
try:
new_memory_db.execute("DROP TABLE IF EXISTS users_memory")
except:
pass
# For the file database
try:
file_db.execute("DROP TABLE IF EXISTS users_file")
except:
pass
return
@app.cell(hide_code=True)
def _(file_db, new_memory_db):
# Create advanced users table in memory database with primary key
new_memory_db.execute("""
CREATE TABLE users_memory (
id INTEGER PRIMARY KEY,
name VARCHAR NOT NULL,
age INTEGER CHECK (age > 0),
email VARCHAR UNIQUE,
registration_date DATE DEFAULT CURRENT_DATE,
last_login TIMESTAMP,
account_balance DECIMAL(10,2) DEFAULT 0.00
)
""")
# Create users table in file database
file_db.execute("""
CREATE TABLE users_file (
id INTEGER PRIMARY KEY,
name VARCHAR NOT NULL,
age INTEGER CHECK (age > 0),
email VARCHAR UNIQUE,
registration_date DATE DEFAULT CURRENT_DATE,
last_login TIMESTAMP,
account_balance DECIMAL(10,2) DEFAULT 0.00
)
""")
return
@app.cell(hide_code=True)
def _(new_memory_db):
# Get table schema information using DuckDB's internal system tables
memory_schema = new_memory_db.execute("""
SELECT column_name, data_type, is_nullable
FROM information_schema.columns
WHERE table_name = 'users_memory'
ORDER BY ordinal_position
""").df()
return (memory_schema,)
@app.cell(hide_code=True)
def _(memory_schema, mo):
mo.vstack(
[
mo.vstack(
[mo.md(f"""## 🔍 Table Schema Information """)], align="center"
),
mo.ui.table(memory_schema),
],
gap=2,
justify="space-between",
)
return
@app.cell(hide_code=True)
def _(mo):
mo.md(
r"""
# [3. Inserting Data Into Tables](https://duckdb.org/docs/stable/sql/statements/insert)
DuckDB supports multiple ways to insert data:
1. **INSERT INTO VALUES**: Insert specific values
2. **INSERT INTO SELECT**: Insert data from query results
3. **Parameterized inserts**: Using prepared statements
4. **Bulk inserts**: For efficient loading of multiple rows
Let's demonstrate these different insertion methods:
"""
)
return
@app.cell(hide_code=True)
def _(date):
today = date.today()
# First check if records already exist to avoid duplicate key errors
def safe_insert(connection, table_name, data):
"""
Safely insert data into a table by checking for existing IDs first
"""
# Check which IDs already exist in the table
existing_ids = (
connection.execute(f"SELECT id FROM {table_name}")
.fetchdf()["id"]
.tolist()
)
# Filter out data with IDs that already exist
new_data = [record for record in data if record[0] not in existing_ids]
if not new_data:
print(
f"No new records to insert into {table_name}. All IDs already exist."
)
return 0
# Prepare the placeholders for the SQL statement
placeholders = ", ".join(
["(" + ", ".join(["?"] * len(new_data[0])) + ")"] * len(new_data)
)
# Flatten the list of tuples for parameter binding
flat_data = [item for sublist in new_data for item in sublist]
# Perform the insertion
if flat_data:
columns = "(id, name, age, email, registration_date, last_login, account_balance)"
connection.execute(
f"INSERT INTO {table_name} {columns} VALUES {placeholders}",
flat_data,
)
return len(new_data)
return 0
return (safe_insert,)
@app.cell(hide_code=True)
def _():
# Prepare the data
user_data = [
(
1,
"Alice",
25,
"[email protected]",
"2021-01-01",
"2023-01-15 14:30:00",
1250.75,
),
(
2,
"Bob",
30,
"[email protected]",
"2021-02-01",
"2023-02-10 09:15:22",
750.50,
),
(
3,
"Charlie",
35,
"[email protected]",
"2021-03-01",
"2023-03-05 17:45:10",
3200.25,
),
(
4,
"David",
40,
"[email protected]",
"2021-04-01",
"2023-04-20 10:30:45",
1800.00,
),
(
5,
"Emma",
45,
"[email protected]",
"2021-05-01",
"2023-05-12 11:20:30",
2500.00,
),
(
6,
"Frank",
50,
"[email protected]",
"2021-06-01",
"2023-06-18 16:10:15",
900.25,
),
]
return (user_data,)
@app.cell(hide_code=True)
def _(file_db, new_memory_db, safe_insert, user_data):
# Safely insert data into memory database
safe_insert(new_memory_db, "users_memory", user_data)
# Safely insert data into file database
safe_insert(file_db, "users_file", user_data)
return
@app.cell(hide_code=True)
def _():
# If you need to add just one record, you can use a similar approach:
new_user = (
7,
"Grace",
28,
"[email protected]",
"2021-07-01",
"2023-07-22 13:45:10",
1675.50,
)
return (new_user,)
@app.cell(hide_code=True)
def _(new_memory_db, new_user):
# Check if the ID exists before inserting
if not new_memory_db.execute(
"SELECT id FROM users_memory WHERE id = ?", [new_user[0]]
).fetchone():
new_memory_db.execute(
"""
INSERT INTO users_memory (id, name, age, email, registration_date, last_login, account_balance)
VALUES (?, ?, ?, ?, ?, ?, ?)
""",
new_user,
)
print(f"Added user {new_user[1]} to users_memory")
else:
print(f"User with ID {new_user[0]} already exists in users_memory")
return
@app.cell(hide_code=True)
def _(file_db, new_user):
# Do the same for the file database
if not file_db.execute(
"SELECT id FROM users_file WHERE id = ?", [new_user[0]]
).fetchone():
file_db.execute(
"""
INSERT INTO users_file (id, name, age, email, registration_date, last_login, account_balance)
VALUES (?, ?, ?, ?, ?, ?, ?)
""",
new_user,
)
print(f"Added user {new_user[1]} to users_file")
else:
print(f"User with ID {new_user[0]} already exists in users_file")
return
@app.cell(hide_code=True)
def _(new_memory_db):
# First try to update
cursor = new_memory_db.execute(
"""
UPDATE users_memory
SET name = ?, age = ?, email = ?,
registration_date = ?, last_login = ?, account_balance = ?
WHERE id = ?
""",
(
"Henry",
33,
"[email protected]",
"2021-08-01",
"2023-08-05 09:10:15",
3100.75,
8, # ID should be the last parameter
),
)
return (cursor,)
@app.cell(hide_code=True)
def _(cursor, mo, new_memory_db):
# If no rows were updated, perform an insert
if cursor.rowcount == 0:
new_memory_db.execute(
"""
INSERT INTO users_memory
(id, name, age, email, registration_date, last_login, account_balance)
VALUES (?, ?, ?, ?, ?, ?, ?)
""",
(
8,
"Henry",
33,
"[email protected]",
"2021-08-01",
"2023-08-05 09:10:15",
3100.75,
),
)
mo.md(
f"""
Upserted Henry into users_memory.
"""
)
return
@app.cell(hide_code=True)
def _(file_db, mo):
# For DuckDB using ON CONFLICT, we need to specify the conflict target column
file_db.execute(
"""
INSERT INTO users_file (id, name, age, email, registration_date, last_login, account_balance)
VALUES (?, ?, ?, ?, ?, ?, ?)
ON CONFLICT (id) DO UPDATE SET
name = EXCLUDED.name,
age = EXCLUDED.age,
email = EXCLUDED.email,
registration_date = EXCLUDED.registration_date,
last_login = EXCLUDED.last_login,
account_balance = EXCLUDED.account_balance
""",
(
8,
"Henry",
33,
"[email protected]",
"2021-08-01",
"2023-08-05 09:10:15",
3100.75,
),
)
mo.md(
f"""
Upserted Henry into users_file.
"""
)
return
@app.cell(hide_code=True)
def _(new_memory_db):
# Display memory data using DuckDB's query capabilities
memory_results = new_memory_db.execute("""
SELECT
id,
name,
age,
email,
registration_date,
last_login,
account_balance
FROM users_memory
ORDER BY id
""").df()
return (memory_results,)
@app.cell(hide_code=True)
def _(file_db):
# Display file data with formatting
file_results = file_db.execute("""
SELECT
id,
name,
age,
email,
registration_date,
last_login,
CAST(account_balance AS DECIMAL(10,2)) AS account_balance
FROM users_file
ORDER BY id
""").df()
return (file_results,)
@app.cell(hide_code=True)
def _(file_results, memory_results, mo):
tabs = mo.ui.tabs(
{
"In-Memory Database": mo.ui.table(memory_results),
"File-Based Database": mo.ui.table(file_results),
}
)
mo.vstack(
[
mo.vstack(
[mo.md(f"""## 📊 Database Contents After Insertion""")],
align="center",
),
tabs,
],
gap=2,
justify="space-between",
)
return
@app.cell(hide_code=True)
def _(mo):
mo.md(
r"""
# [4. Using SQL Directly in marimo](https://duckdb.org/docs/stable/sql/query_syntax/select)
There are multiple ways to leverage DuckDB's SQL capabilities in marimo:
1. **Direct execution**: Using DuckDB connections to execute SQL
2. **marimo SQL**: Using marimo's built-in SQL engine
3. **Interactive queries**: Combining UI elements with SQL execution
Let's explore these approaches:
"""
)
return
@app.cell(hide_code=True)
def _(mo):
mo.vstack(
[
mo.vstack([mo.md(f"""## 🔍 Query with marimo SQL""")], align="center"),
mo.md(
"### marimo has its own [built-in SQL engine](https://docs.marimo.io/guides/working_with_data/sql/) that can work with DataFrames."
),
],
gap=2,
justify="space-between",
)
return
@app.cell(hide_code=True)
def _(memory_results, mo):
# Create a SQL selector for users with age threshold
age_threshold = mo.ui.slider(
25, 50, value=30, label="Minimum Age", full_width=True, show_value=True
)
# Create a function to filter users based on the slider value
def filtered_users():
# Use DuckDB directly instead of mo.sql with users param
filtered_df = memory_results[memory_results["age"] >= age_threshold.value]
filtered_df = filtered_df.sort_values("age")
return mo.ui.table(filtered_df)
return age_threshold, filtered_users
@app.cell(hide_code=True)
def _(age_threshold, filtered_users, mo):
layout = mo.vstack(
[
mo.md("### Select minimum age:"),
age_threshold,
mo.md("### Users meeting age criteria:"),
filtered_users(),
],
gap=2,
justify="space-between",
)
layout
return
@app.cell(hide_code=True)
def _(mo):
mo.md(r"""# [5. Working with Polars and DuckDB](https://duckdb.org/docs/stable/guides/python/polars.html)""")
return
@app.cell(hide_code=True)
def _(pl):
# Create a Polars DataFrame
polars_df = pl.DataFrame(
{
"id": [101, 102, 103],
"name": ["Product A", "Product B", "Product C"],
"price": [29.99, 49.99, 19.99],
"category": ["Electronics", "Furniture", "Books"],
}
)
return (polars_df,)
@app.cell(hide_code=True)
def _(mo, polars_df):
mo.vstack(
[
mo.vstack(
[mo.md(f"""## Original Polars DataFrame:""")], align="center"
),
mo.ui.table(polars_df),
],
gap=2,
justify="space-between",
)
return
@app.cell(hide_code=True)
def _(new_memory_db, polars_df):
# Register the Polars DataFrame as a DuckDB table in memory connection
new_memory_db.register("products_polars", polars_df)
# Query the registered table
polars_query_result = new_memory_db.execute(
"SELECT * FROM products_polars WHERE price > 25"
).df()
return (polars_query_result,)
@app.cell(hide_code=True)
def _(mo, polars_query_result):
mo.vstack(
[
mo.vstack(
[mo.md(f"""## DuckDB Query Result (From Polars Data):""")],
align="center",
),
mo.ui.table(polars_query_result),
],
gap=2,
justify="space-between",
)
return
@app.cell(hide_code=True)
def _(new_memory_db):
# Demonstrate a more complex query
complex_query_result = new_memory_db.execute("""
SELECT
category,
COUNT(*) as product_count,
AVG(price) as avg_price,
MIN(price) as min_price,
MAX(price) as max_price
FROM products_polars
GROUP BY category
ORDER BY avg_price DESC
""").df()
return (complex_query_result,)
@app.cell(hide_code=True)
def _(complex_query_result, mo):
mo.vstack(
[
mo.vstack(
[mo.md(f"""## Aggregated Product Data by Category:""")],
align="center",
),
mo.ui.table(complex_query_result),
],
gap=2,
justify="space-between",
)
return
@app.cell(hide_code=True)
def _(mo):
mo.md(r"""# [6. Advanced Queries: Joins Between Tables](https://duckdb.org/docs/stable/guides/performance/join_operations.html)""")
return
@app.cell(hide_code=True)
def _(new_memory_db):
# Create another table to join with
new_memory_db.execute("""
CREATE TABLE IF NOT EXISTS departments (
id INTEGER,
department_name VARCHAR,
manager_id INTEGER
)
""")
return
@app.cell(hide_code=True)
def _(new_memory_db):
new_memory_db.execute("""
INSERT INTO departments VALUES
(101, 'Engineering', 1),
(102, 'Marketing', 2),
(103, 'Finance', NULL)
""")
return
@app.cell(hide_code=True)
def _(new_memory_db):
# Execute a join query
join_result = new_memory_db.execute("""
SELECT
u.id,
u.name,
u.age,
d.department_name
FROM users_memory u
LEFT JOIN departments d ON u.id = d.manager_id
ORDER BY u.id
""").df()
return (join_result,)
@app.cell(hide_code=True)
def _(mo):
mo.md(
rf"""
<!-- Display the join result -->
## Join Result (Users and Departments):
"""
)
return
@app.cell
def _(join_result, mo):
mo.ui.table(join_result)
return
@app.cell(hide_code=True)
def _(mo):
mo.md(
rf"""
<!-- Demonstrate different types of joins -->
## Different Types of Joins
"""
)
return
@app.cell(hide_code=True)
def _(new_memory_db):
# Inner join
inner_join = new_memory_db.execute("""
SELECT u.id, u.name, d.department_name
FROM users_memory u
INNER JOIN departments d ON u.id = d.manager_id
""").df()
# Right join
right_join = new_memory_db.execute("""
SELECT u.id, u.name, d.department_name
FROM users_memory u
RIGHT JOIN departments d ON u.id = d.manager_id
""").df()
# Full outer join
full_join = new_memory_db.execute("""
SELECT u.id, u.name, d.department_name
FROM users_memory u
FULL OUTER JOIN departments d ON u.id = d.manager_id
""").df()
# Cross join
cross_join = new_memory_db.execute("""
SELECT u.id, u.name, d.department_name
FROM users_memory u
CROSS JOIN departments d
""").df()
# Self join (Joining user table with itself to find users with the same age)
self_join = new_memory_db.execute("""
SELECT u1.id, u1.name, u2.name AS same_age_user
FROM users_memory u1
JOIN users_memory u2 ON u1.age = u2.age AND u1.id <> u2.id
""").df()
# Semi join (Finding users who are also managers)
semi_join = new_memory_db.execute("""
SELECT u.id, u.name, u.age
FROM users_memory u
WHERE EXISTS (
SELECT 1 FROM departments d
WHERE u.id = d.manager_id
)
""").df()
# Anti join (Finding users who are not managers)
anti_join = new_memory_db.execute("""
SELECT u.id, u.name, u.age
FROM users_memory u
WHERE NOT EXISTS (
SELECT 1 FROM departments d
WHERE u.id = d.manager_id
)
""").df()
return (
anti_join,
cross_join,
full_join,
inner_join,
right_join,
self_join,
semi_join,
)
@app.cell(hide_code=True)
def _(mo, new_memory_db):
# Display base table side by side
users = new_memory_db.execute("SELECT * FROM users_memory").df()
departments = new_memory_db.execute("SELECT * FROM departments").df()
base_tables = mo.vstack(
[
mo.vstack([mo.md(f"""# Base Tables""")], align="center"),
mo.ui.tabs(
{
"User Table": mo.ui.table(users),
"Departments Table": mo.ui.table(departments),
}
),
]
)
base_tables
return
@app.cell(hide_code=True)
def _(
anti_join,
cross_join,
full_join,
inner_join,
join_result,
mo,
right_join,
self_join,
semi_join,
):
join_description = {
"Left Join": "Shows all records from the left table and matching records from the right table. Non-matches filled with NULL.",
"Inner Join": "Shows only the records where there's a match in both tables.",
"Right Join": "Shows all records from the right table and matching records from the left table. Non-matches filled with NULL.",
"Full Outer Join": "Shows all records from both tables, with NULL values where there's no match.",
"Cross Join": "Returns the Cartesian product - all possible combinations of rows from both tables.",
"Self Join": "Joins a table with itself, used to compare rows within the same table.",
"Semi Join": "Returns rows from the first table where one or more matches exist in the second table.",
"Anti Join": "Returns rows from the first table where no matches exist in the second table.",
}
join_tabs = mo.ui.tabs(
{
"Left Join": mo.ui.table(join_result),
"Inner Join": mo.ui.table(inner_join),
"Right Join": mo.ui.table(right_join),
"Full Outer Join": mo.ui.table(full_join),
"Cross Join": mo.ui.table(cross_join),
"Self Join": mo.ui.table(self_join),
"Semi Join": mo.ui.table(semi_join),
"Anti Join": mo.ui.table(anti_join),
}
)
return join_description, join_tabs
@app.cell(hide_code=True)
def _(join_description, join_tabs, mo):
join_display = mo.vstack(
[
mo.vstack([mo.md(f"""# SQL Join Operations""")], align="center"),
mo.md(f"**{join_tabs.value}**: {join_description[join_tabs.value]}"),
mo.md("## Join Results"),
join_tabs,
],
gap=2,
justify="space-between",
)
join_display
return
@app.cell(hide_code=True)
def _(mo):
mo.md(r"""# [7. Aggregate Functions in DuckDB](https://duckdb.org/docs/stable/sql/functions/aggregates.html)""")
return
@app.cell(hide_code=True)
def _(new_memory_db):
# Execute an aggregate query
agg_result = new_memory_db.execute("""
SELECT
AVG(age) as avg_age,
MAX(age) as max_age,
MIN(age) as min_age,
COUNT(*) as total_users,
SUM(account_balance) as total_balance
FROM users_memory
""").df()
return (agg_result,)
@app.cell(hide_code=True)
def _(agg_result, mo):
mo.vstack(
[
mo.vstack(
[mo.md(f"""## Aggregate Results (All Users):""")], align="center"
),
mo.ui.table(agg_result),
],
gap=2,
justify="space-between",
)
return
@app.cell(hide_code=True)
def _(new_memory_db):
age_groups = new_memory_db.execute("""
SELECT
CASE
WHEN age < 30 THEN 'Under 30'
WHEN age BETWEEN 30 AND 40 THEN '30 to 40'
ELSE 'Over 40'
END as age_group,
COUNT(*) as count,
AVG(age) as avg_age,
AVG(account_balance) as avg_balance
FROM users_memory
GROUP BY 1
ORDER BY 1
""").df()
return (age_groups,)
@app.cell(hide_code=True)
def _(age_groups, mo):
mo.ui.table(age_groups)
mo.vstack(
[
mo.vstack(
[mo.md(f"""## Aggregate Results (Grouped by Age Range):""")],
align="center",
),
mo.ui.table(age_groups),
],
gap=2,
justify="space-between",
)
return
@app.cell(hide_code=True)
def _(new_memory_db):
window_result = new_memory_db.execute("""
SELECT
id,
name,
age,
account_balance,
RANK() OVER (ORDER BY account_balance DESC) as balance_rank,
account_balance - AVG(account_balance) OVER () as diff_from_avg,
account_balance / SUM(account_balance) OVER () * 100 as pct_of_total
FROM users_memory
ORDER BY balance_rank
""").df()
return (window_result,)
@app.cell(hide_code=True)
def _(mo, window_result):
mo.vstack(
[
mo.vstack([mo.md(f"""## Window Functions Example""")], align="center"),
mo.ui.table(window_result),
],
gap=2,
justify="space-between",
)
return
@app.cell(hide_code=True)
def _(mo):
mo.md(r"""# [8. Converting DuckDB Results to Polars/Pandas](https://duckdb.org/docs/stable/guides/python/polars.html)""")
return
@app.cell(hide_code=True)
def _(new_memory_db):
polars_result = new_memory_db.execute(
"""SELECT * FROM users_memory WHERE age > 25 ORDER BY age"""
).pl()
return (polars_result,)
@app.cell(hide_code=True)
def _(mo, polars_result):
mo.vstack(
[
mo.vstack(
[mo.md(f"""## Query Result as Polars DataFrame:""")],
align="center",
),
mo.ui.table(polars_result),
],
gap=2,
justify="space-between",
)
return
@app.cell(hide_code=True)
def _(new_memory_db):
pandas_result = new_memory_db.execute(
"""SELECT * FROM users_memory WHERE age > 25 ORDER BY age"""
).fetch_df()
return (pandas_result,)
@app.cell(hide_code=True)
def _(mo, pandas_result):
mo.vstack(
[
mo.vstack(
[mo.md(f"""## Same Query Result as Pandas DataFrame:""")],
align="center",
),
mo.ui.table(pandas_result),
],
gap=2,
justify="space-between",
)
return
@app.cell(hide_code=True)
def _(mo):
mo.vstack(
[
mo.vstack(
[mo.md(f"""## Differences in DataFrame Handling""")],
align="center",
),
mo.vstack(
[
mo.md(
f"""## Polars: Filter users over 35 and calculate average balance"""
)
],
align="start",
),
],
gap=2, justify="space-between",
)
return
@app.cell(hide_code=True)
def _(mo, pl, polars_result):
def _():
polars_filtered = polars_result.filter(pl.col("age") > 35)
polars_avg = polars_filtered.select(
pl.col("account_balance").mean().alias("avg_balance")
)
layout = mo.vstack(
[
mo.md("### Filtered Polars DataFrame (Age > 35):"),
mo.ui.table(polars_filtered),
mo.md("### Average Account Balance:"),
mo.ui.table(polars_avg),
],
gap=2,
)
return layout
_()
return
@app.cell(hide_code=True)
def _(mo, pandas_result):
pandas_avg = pandas_result[pandas_result["age"] > 35]["account_balance"].mean()
mo.vstack(
[
mo.vstack(
[mo.md(f"""## Pandas: Same operation in pandas style""")],
align="center",
),
mo.vstack(
[mo.md(f"""### Average balance: {pandas_avg:.2f}""")],
align="start",
),
]
)
return
@app.cell(hide_code=True)
def _(mo):
mo.md("""# 9. Data Visualization with DuckDB and Plotly""")
return
@app.cell(hide_code=True)
def _(age_groups, mo, new_memory_db, plotly_express):
# User distribution by age group
fig1 = plotly_express.bar(
age_groups,
x="age_group",
y="count",
title="User Distribution by Age Group",
labels={"count": "Number of Users", "age_group": "Age Group"},
color="age_group",
color_discrete_sequence=plotly_express.colors.qualitative.Plotly,
)
fig1.update_traces(
text=age_groups["count"],
textposition="outside",
)
fig1.update_layout(
height=450,
margin=dict(t=50, b=50, l=50, r=25),
hoverlabel=dict(bgcolor="white", font_size=12),
template="plotly_white",
)
# Average balance by age group
fig2 = plotly_express.bar(
age_groups,
x="age_group",
y="avg_balance",
title="Average Account Balance by Age Group",
labels={"avg_balance": "Average Balance ($)", "age_group": "Age Group"},
color="age_group",
color_discrete_sequence=plotly_express.colors.qualitative.Plotly,
)
fig2.update_traces(
text=[f"${val:.2f}" for val in age_groups["avg_balance"]],
textposition="outside",
)
fig2.update_layout(
height=450,
margin=dict(t=50, b=50, l=50, r=25),
hoverlabel=dict(bgcolor="white", font_size=12),
template="plotly_white",
)
# Age vs Account Balance scatter plot
scatter_data = new_memory_db.execute(
"""
SELECT
name,
age,
account_balance
FROM users_memory
ORDER BY age
"""
).df()
fig3 = plotly_express.scatter(
scatter_data,
x="age",
y="account_balance",
title="Age vs. Account Balance",
labels={"account_balance": "Account Balance ($)", "age": "Age"},
color_discrete_sequence=["#FF7F0E"],
trendline="ols",
hover_data=["age", "account_balance"],
size_max=15,
)
fig3.update_traces(marker=dict(size=12))
fig3.update_layout(
height=450,
margin=dict(t=50, b=50, l=50, r=25),
hoverlabel=dict(bgcolor="white", font_size=12),
template="plotly_white",
)
# Distribution of account balances
balance_data = new_memory_db.execute(
"""
SELECT
name,
account_balance
FROM users_memory
ORDER BY account_balance DESC
"""
).df()
fig4 = plotly_express.pie(
balance_data,
names="name",
values="account_balance",
title="Distribution of Account Balances",
labels={"account_balance": "Account Balance ($)", "name": "User"},
color_discrete_sequence=plotly_express.colors.qualitative.Pastel,
)
fig4.update_traces(textinfo="percent+label", textposition="inside")
fig4.update_layout(
height=450,
margin=dict(t=50, b=50, l=50, r=25),
hoverlabel=dict(bgcolor="white", font_size=12),
template="plotly_white",
)
category_tabs = mo.ui.tabs(
{
"Age Group Analysis": mo.vstack(
[
mo.ui.tabs(
{
"User Distribution": mo.ui.plotly(fig1),
"Average Balance": mo.ui.plotly(fig2),
}
)
],
gap=2,
justify="space-between",
),
"Financial Analysis": mo.vstack(
[
mo.ui.tabs(
{
"Age vs Balance": mo.ui.plotly(fig3),
"Balance Distribution": mo.ui.plotly(fig4),
}
)
],
gap=2,
justify="space-between",
),
},
lazy=True,
)
mo.vstack(
[
mo.vstack(
[mo.md(f"""## Select a visualization category:""")],
align="start",
),
category_tabs,
],
gap=2,
justify="space-between",
)
return
@app.cell(hide_code=True)
def _(mo):
mo.md(
r"""
/// admonition |
## Database Management Best Practices
///
### Closing Connections
It's important to close database connections when you're done with them, especially for file-based connections:
```python
memory_db.close()
file_db.close()
```
### Transaction Management
DuckDB supports transactions, which can be useful for more complex operations:
```python
conn = duckdb.connect('mydb.db')
conn.begin() # Start transaction
try:
conn.execute("INSERT INTO users VALUES (1, 'Test User')")
conn.execute("UPDATE balances SET amount = amount - 100 WHERE user_id = 1")
conn.commit() # Commit changes
except:
conn.rollback() # Undo changes if error
raise
```
### Query Performance
DuckDB is optimized for analytical queries. For best performance:
- Use appropriate data types
- Create indexes for frequently queried columns
- For large datasets, consider partitioning
- Use prepared statements for repeated queries
"""
)
return
@app.cell(hide_code=True)
def _(mo):
mo.md(rf"""## 10. Interactive DuckDB Dashboard with marimo and Plotly""")
return
@app.cell(hide_code=True)
def _(mo):
# Create an interactive filter for age range
min_age = mo.ui.slider(20, 50, value=25, label="Minimum Age")
max_age = mo.ui.slider(20, 50, value=50, label="Maximum Age")
return max_age, min_age
@app.cell(hide_code=True)
def _(max_age, min_age, new_memory_db):
# Create a function to filter data and update visualizations
def get_filtered_data(min_val=min_age.value, max_val=max_age.value):
# Get filtered data based on slider values using parameterized query for safety
return new_memory_db.execute(
"""
SELECT
id,
name,
age,
email,
account_balance,
registration_date
FROM users_memory
WHERE age >= ? AND age <= ?
ORDER BY age
""",
[min_val, max_val],
).df()
return (get_filtered_data,)
@app.cell(hide_code=True)
def _(get_filtered_data):
def get_metrics(data=get_filtered_data()):
return {
"user count": len(data),
"avg_balance": data["account_balance"].mean() if len(data) > 0 else 0,
"total_balance": data["account_balance"].sum() if len(data) > 0 else 0,
}
return (get_metrics,)
@app.cell(hide_code=True)
def _(get_metrics, mo):
def metrics_display(metrics=get_metrics()):
return mo.hstack(
[
mo.vstack(
[
mo.md("### Selected Users"),
mo.md(f"## {metrics['user count']}"),
],
align="center",
),
mo.vstack(
[
mo.md("### Average Balance"),
mo.md(f"## ${metrics['avg_balance']:.2f}"),
],
align="center",
),
mo.vstack(
[
mo.md("### Total Balance"),
mo.md(f"## ${metrics['total_balance']:.2f}"),
],
align="center",
),
],
justify="space-between",
gap=2,
)
return (metrics_display,)
@app.cell(hide_code=True)
def _(get_filtered_data, max_age, min_age, mo, plotly_express):
def create_visualization(
data=get_filtered_data(), min_val=min_age.value, max_val=max_age.value
):
if len(data) == 0:
return mo.ui.text("No data available for the selected age range.")
# Create visualizations for filtered data
fig1 = plotly_express.bar(
data,
x="name",
y="account_balance",
title=f"Account Balance by User (Age {min_val} - {max_val})",
labels={"account_balance": "Account Balance ($)", "name": "User"},
color="account_balance",
color_continuous_scale=plotly_express.colors.sequential.Plasma,
text_auto=".2s",
)
fig1.update_layout(
height=400,
xaxis_tickangle=-45,
margin=dict(t=50, b=70, l=50, r=30),
hoverlabel=dict(bgcolor="white", font_size=12),
template="plotly_white",
)
fig1.update_traces(
textposition="outside",
)
fig2 = plotly_express.histogram(
data,
x="age",
nbins=min(10, len(set(data["age"]))),
title=f"Age Distribution (Age {min_val} - {max_val})",
color_discrete_sequence=["#4C78A8"],
opacity=0.8,
histnorm="probability density",
)
fig2.update_layout(
height=400,
margin=dict(t=50, b=70, l=50, r=30),
bargap=0.1,
hoverlabel=dict(bgcolor="white", font_size=12),
template="plotly_white",
)
fig3 = plotly_express.scatter(
data,
x="age",
y="account_balance",
title=f"Age vs. Account Balance (Age {min_val} - {max_val})",
labels={"account_balance": "Account Balance ($)", "age": "Age"},
color="age",
color_continuous_scale="Viridis",
size_max=25,
size="account_balance",
hover_name="name",
)
fig3.update_layout(
height=400,
margin=dict(t=50, b=70, l=50, r=30),
hoverlabel=dict(bgcolor="white", font_size=12),
template="plotly_white",
)
return mo.ui.tabs(
{
"Account Balance by User": mo.ui.plotly(fig1),
"Age Distribution": mo.ui.plotly(fig2),
"Age vs. Account Balance": mo.ui.plotly(fig3),
}
)
return (create_visualization,)
@app.cell(hide_code=True)
def _(
create_visualization,
get_filtered_data,
max_age,
metrics_display,
min_age,
mo,
):
def dashboard(
min_val=min_age.value,
max_val=max_age.value,
metrics=metrics_display(),
data=get_filtered_data(),
visualization=create_visualization(),
):
return mo.vstack(
[
mo.md(f"### Interactive Dashboard (Age {min_val} - {max_val})"),
metrics,
mo.md("### Data Table"),
mo.ui.table(data, page_size=5),
mo.md("### Visualizations"),
visualization,
],
gap=2,
justify="space-between",
)
dashboard()
return
@app.cell(hide_code=True)
def _(mo):
mo.md(
rf"""
# Summary and Key Takeaways
In this notebook, we've explored DuckDB, a powerful embedded analytical database system. Here's what we covered:
1. **Connection types**: We learned the difference between in-memory databases (temporary) and file-based databases (persistent).
2. **Table creation**: We created tables with various data types, constraints, and primary keys.
3. **Data insertion**: We demonstrated different ways to insert data, including single inserts and bulk loading.
4. **SQL queries**: We executed various SQL queries directly and through marimo's UI components.
5. **Integration with Polars**: We showed how DuckDB can work seamlessly with Polars DataFrames.
6. **Joins and relationships**: We performed JOIN operations between tables to combine related data.
7. **Aggregation**: We used aggregate functions to summarize and analyze data.
8. **Data conversion**: We converted DuckDB results to both Polars and Pandas DataFrames.
9. **Best practices**: We reviewed best practices for managing DuckDB connections and transactions.
10. **Visualization**: We created interactive visualizations and dashboards with Plotly and marimo.
DuckDB is an excellent tool for data analysis, especially for analytical workloads. Its in-process nature makes it fast and easy to use, while its SQL compatibility makes it accessible for anyone familiar with SQL databases.
### Next Steps
- Try loading larger datasets into DuckDB
- Experiment with more complex queries and window functions
- Use DuckDB's COPY functionality to import/export data from/to files
- Create more advanced interactive dashboards with marimo and Plotly
"""
)
return
@app.cell(hide_code=True)
def _():
import marimo as mo
import duckdb
import polars as pl
import os
from datetime import date
import plotly.express as plotly_express
import plotly.graph_objects as plotly_graph_objects
import numpy as np
return date, duckdb, mo, os, pl, plotly_express
if __name__ == "__main__":
app.run()
|