Skip to main content Início Criadores jeremylongshore tons-of-skills-marketplace snowflake-sdk-patterns
snowflake-sdk-patterns Apply production-ready Snowflake SDK patterns for snowflake-sdk and snowflake-connector-python.
Use when implementing connection pooling, async execute wrappers, streaming results,
or establishing team coding standards for Snowflake.
Trigger with phrases like "snowflake SDK patterns", "snowflake best practices",
"snowflake code patterns", "idiomatic snowflake", "snowflake connection pool".
Ir para a instalação Skills Marketplace Descubra e explore skills de IA criadas pela comunidade.
Instalar com Codex ou Claude Copie este prompt, cole no Codex, Claude ou outro assistente e deixe que ele revise a página da skill e instale para você.
Copiar promptMostrar detalhes do prompt Um comando direto ignora o prompt de revisão. Verifique a origem antes de executá-lo.
npx skills add https://github.com/jeremylongshore/tons-of-skills-marketplace --skill snowflake-sdk-patternsO comando permanece em uma só linha. Role horizontalmente para revisá-lo antes de copiar.
Prefere uma cópia local? Baixe os arquivos disponíveis atualmente no SkillsMP.
Baixar Zip Baixando... Mais deste repositório langchain-deploy-integration Deploy a LangChain 1.0 / LangGraph 1.0 app to Cloud Run, Vercel, or LangServe correctly — with timeouts sized for chain length, cold-start mitigation, SSE anti-buffering headers, and Secret Manager over .env. Use when prepping a first production deploy, debugging a stream that hangs behind a proxy, or diagnosing p99 latency spikes. Trigger with "langchain deploy", "langchain cloud run", "langchain vercel python", "langchain langserve", or "langchain docker".
langchain-langgraph-agents Build a correct LangGraph 1.0 ReAct agent with create_react_agent — typed tools, error propagation, recursion caps, and stop conditions that actually stop. Use when writing a first tool-calling agent, migrating from AgentExecutor or initialize_agent, or diagnosing an agent that loops on vague prompts. Trigger with "langgraph agent", "create_react_agent", "langgraph tool calling", "AgentExecutor migration", or "agent loop cost".
langchain-langgraph-human-in-loop Build LangGraph 1.0 human-in-the-loop approval flows with interrupt_before /
interrupt_after and Command(resume=...) — JSON-serializable state, clean
resume semantics, and UI wiring for approval decisions. Use when adding an
approval gate before an expensive tool call, wiring a Slack/web UI for agent
approvals, or debugging a graph that crashes on interrupt.
Trigger with "langgraph human in loop", "langgraph interrupt_before",
"langgraph approval flow", "Command resume", "langgraph HITL".
name snowflake-sdk-patterns description Apply production-ready Snowflake SDK patterns for snowflake-sdk and snowflake-connector-python.
Use when implementing connection pooling, async execute wrappers, streaming results,
or establishing team coding standards for Snowflake.
Trigger with phrases like "snowflake SDK patterns", "snowflake best practices",
"snowflake code patterns", "idiomatic snowflake", "snowflake connection pool".
allowed-tools Read, Write, Edit version 1.5.0 license MIT author Jeremy Longshore <jeremy@intentsolutions.io> tags ["saas","data-warehouse","analytics","snowflake"] compatibility Designed for Claude Code
Snowflake SDK Patterns
Overview
Production-ready patterns for snowflake-sdk (Node.js) and snowflake-connector-python using real driver APIs.
Prerequisites
Completed snowflake-install-auth setup
Understanding of callback-to-promise conversion patterns
Familiarity with Snowflake's callback-based Node.js API
Instructions
Step 1: Connection Pool (Node.js)
import snowflake from 'snowflake-sdk' ;
interface PoolConfig {
max : number ;
idleTimeoutMs : number ;
}
class SnowflakePool {
private pool : snowflake.Connection [] = [];
private available : snowflake.Connection [] = [];
private waiting : ((conn : snowflake.Connection ) => void )[] = [];
private config : PoolConfig ;
constructor (
private connConfig : snowflake.ConnectionOptions ,
config : Partial <PoolConfig > = {}
) {
this .config = { max : 10 , idleTimeoutMs : 60000 , ...config };
}
(): <snowflake. > {
( . . > ) {
. . ()!;
}
( . . < . . ) {
conn = snowflake. ( . );
< >( {
conn. ( (err ? (err) : ()));
});
. . (conn);
conn;
}
( {
. . (resolve);
});
}
( : snowflake. ): {
( . . > ) {
next = . . ()!;
(conn);
} {
. . (conn);
}
}
withConnection<T>( : <T>): <T> {
conn = . ();
{
(conn);
} {
. (conn);
}
}
}
pool = ({
: process. . !,
: process. . !,
: process. . !,
: process. . || ,
: process. . !,
: process. . || ,
});
async
acquire
Promise
Connection
if
this
available
length
0
return
this
available
pop
if
this
pool
length
this
config
max
const
createConnection
this
connConfig
await
new
Promise
void
(resolve, reject ) =>
connect
(err ) =>
reject
resolve
this
pool
push
return
return
new
Promise
(resolve ) =>
this
waiting
push
release
conn
Connection
void
if
this
waiting
length
0
const
this
waiting
shift
next
else
this
available
push
async
fn
(conn : snowflake.Connection ) =>
Promise
Promise
const
await
this
acquire
try
return
await
fn
finally
this
release
export
const
new
SnowflakePool
account
env
SNOWFLAKE_ACCOUNT
username
env
SNOWFLAKE_USER
password
env
SNOWFLAKE_PASSWORD
warehouse
env
SNOWFLAKE_WAREHOUSE
'COMPUTE_WH'
database
env
SNOWFLAKE_DATABASE
schema
env
SNOWFLAKE_SCHEMA
'PUBLIC'
Step 2: Promise-Based Query Helper
import snowflake from 'snowflake-sdk' ;
interface QueryResult <T = Record <string , any >> {
rows : T[];
statement : snowflake.Statement ;
sqlText : string ;
}
export function query<T = Record <string , any >>(
conn : snowflake.Connection ,
sqlText : string ,
binds ?: snowflake.Binds
): Promise <QueryResult <T>> {
return new Promise ((resolve, reject ) => {
conn.execute ({
sqlText,
binds,
complete : (err, stmt, rows ) => {
if (err) {
reject (Object .assign (err, { sqlText }));
} else {
resolve ({ rows : (rows || []) as T[], statement : stmt, sqlText });
}
},
});
});
}
export async function multiQuery (
conn : snowflake.Connection ,
statements : string []
): Promise <QueryResult []> {
const results : QueryResult [] = [];
for (const sql of statements) {
results.push (await query (conn, sql));
}
return results;
}
Step 3: Streaming for Large Result Sets
export async function * streamQuery<T = Record <string , any >>(
conn : snowflake.Connection ,
sqlText : string ,
binds ?: snowflake.Binds
): AsyncGenerator <T> {
const stmt = await new Promise <snowflake.Statement >((resolve, reject ) => {
conn.execute ({
sqlText,
binds,
streamResult : true ,
complete : (err, stmt ) => {
if (err) reject (err);
else resolve (stmt);
},
});
});
const stream = stmt.streamRows ();
for await (const row of stream) {
yield row as T;
}
}
Step 4: Python Context Manager Pattern
import snowflake.connector
from contextlib import contextmanager
from typing import Generator, Any
class SnowflakePool :
def __init__ (self, **conn_params ):
self ._params = conn_params
@contextmanager
def connection (self ) -> Generator[snowflake.connector.SnowflakeConnection, None , None ]:
conn = snowflake.connector.connect(**self ._params)
try :
yield conn
finally :
conn.close()
@contextmanager
def cursor (self ) -> Generator[snowflake.connector.cursor.SnowflakeCursor, None , None ]:
with self .connection() as conn:
cur = conn.cursor()
try :
yield cur
finally :
cur.close()
def execute (self, sql: str , params: tuple = ( ) ) -> list [dict [str , Any ]]:
with self .cursor() as cur:
cur.execute(sql, params)
columns = [desc[0 ] for desc in cur.description] if cur.description else []
return [dict (zip (columns, row)) for row in cur.fetchall()]
def execute_many (self, sql: str , params_list: list [tuple ] ) -> int :
"""Batch insert — much faster than individual inserts."""
with self .cursor() as cur:
cur.executemany(sql, params_list)
return cur.rowcount
pool = SnowflakePool(
account=os.environ['SNOWFLAKE_ACCOUNT' ],
user=os.environ['SNOWFLAKE_USER' ],
password=os.environ['SNOWFLAKE_PASSWORD' ],
warehouse='COMPUTE_WH' ,
database='MY_DB' ,
schema='PUBLIC' ,
)
users = pool.execute("SELECT * FROM users WHERE status = %s" , ('active' ,))
Step 5: Error Handling Wrapper
export class SnowflakeQueryError extends Error {
constructor (
message : string ,
public readonly sqlState : string ,
public readonly code : number ,
public readonly sqlText : string ,
public readonly retryable : boolean
) {
super (message);
this .name = 'SnowflakeQueryError' ;
}
}
const RETRYABLE_CODES = new Set ([
390114 ,
390503 ,
]);
export async function safeQuery<T>(
conn : snowflake.Connection ,
sqlText : string ,
binds ?: snowflake.Binds ,
maxRetries = 3
): Promise <T[]> {
for (let attempt = 1 ; attempt <= maxRetries; attempt++) {
try {
const { rows } = await query<T>(conn, sqlText, binds);
return rows;
} catch (err : any ) {
const retryable = RETRYABLE_CODES .has (err.code );
if (!retryable || attempt === maxRetries) {
throw new SnowflakeQueryError (
err.message , err.sqlState , err.code , sqlText, retryable
);
}
const delay = 1000 * Math .pow (2 , attempt - 1 );
await new Promise ((r ) => setTimeout (r, delay));
}
}
throw new Error ('Unreachable' );
}
Error Handling Pattern Use Case Benefit Connection pool High concurrency apps Reuses connections, prevents exhaustion Promise wrapper All Node.js code Clean async/await instead of callbacks Streaming Large result sets (>100K rows) Constant memory usage Context manager All Python code Guarantees connection cleanup Retry with backoff Transient failures Handles token expiry, service blips
Resources
Next Steps Apply patterns in snowflake-core-workflow-a for real-world data pipeline usage.