Skip to content

Commit 506e01f

Browse files
author
Matt Kafonek
authored
add make_sql_cell function (#140)
* add make_sql_cell function * break tests into unit and e2e, add sql cell test * Ruff snuck in an extra dupe line! * changelog
1 parent 0d19aa0 commit 506e01f

File tree

12 files changed

+47
-0
lines changed

12 files changed

+47
-0
lines changed

CHANGELOG.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
77
For pre-1.0 releases, see [0.0.35 Changelog](https://github.com/noteable-io/origami/blob/0.0.35/CHANGELOG.md)
88

99
## [Unreleased]
10+
### Added
11+
- `origami.models.notebook.make_sql_cell` convenience function, returns a `CodeCell` with appropriate metadata
1012

1113
## [1.0.0-alpha.2] - 2023-07-26
1214
### Changed

origami/models/notebook.py

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@
88
Devs: as usual with Pydantic modeling, the top-level model (Notebook) is at the bottom of this file,
99
read from bottom up for most clarity.
1010
"""
11+
import random
12+
import string
1113
import uuid
1214
from typing import Any, Dict, List, Literal, Optional, Union
1315

@@ -97,6 +99,34 @@ def output_collection_id(self) -> Optional[Union[str, uuid.UUID]]:
9799
return self.metadata.get("noteable", {}).get("output_collection_id")
98100

99101

102+
def make_sql_cell(
103+
cell_id: Optional[str] = None,
104+
source: str = '',
105+
db_connection: str = '@noteable',
106+
assign_results_to: Optional[str] = None,
107+
) -> CodeCell:
108+
cell_id = cell_id or str(uuid.uuid4())
109+
# Remove first line of source if it starts with %%sql. That is the right syntax for regular
110+
# code cells with sql magic support, but Noteable SQL cells should have just the sql source
111+
if source.startswith('%%sql'):
112+
lines = source.splitlines()
113+
source = '\n'.join(lines[1:])
114+
115+
if not assign_results_to:
116+
name_suffix = "".join(random.choices(string.ascii_lowercase, k=4))
117+
assign_results_to = 'df_' + name_suffix
118+
metadata = {
119+
'language': 'sql',
120+
'type': 'code',
121+
'noteable': {
122+
'cell_type': 'sql',
123+
'db_connection': db_connection,
124+
'assign_results_to': assign_results_to,
125+
},
126+
}
127+
return CodeCell(cell_id=cell_id, source=source, metadata=metadata)
128+
129+
100130
class MarkdownCell(CellBase):
101131
cell_type: Literal["markdown"] = "markdown"
102132

File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.

0 commit comments

Comments
 (0)