2
0

index.ts 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  1. /**
  2. * PizzaSQL Client for JavaScript/TypeScript
  3. * Works with Node.js, Bun, and browsers
  4. */
  5. export interface PizzaSQLConfig {
  6. apiKey?: string;
  7. timeout?: number;
  8. }
  9. export interface Column {
  10. name: string;
  11. type: string;
  12. }
  13. export interface QueryResult<T = Record<string, unknown>> {
  14. columns: Column[];
  15. rows: T[];
  16. rowsAffected: number;
  17. lastInsertId: number;
  18. executionTime: string;
  19. }
  20. export interface ExecuteResult {
  21. results: { rowsAffected: number; lastInsertId: number }[];
  22. totalRowsAffected: number;
  23. executionTime: string;
  24. }
  25. export interface TableInfo {
  26. tables: string[];
  27. count: number;
  28. }
  29. export interface PizzaSQLError {
  30. code: string;
  31. message: string;
  32. details?: Record<string, unknown>;
  33. }
  34. class PizzaSQLClient {
  35. private baseUrl: string;
  36. private apiKey?: string;
  37. private timeout: number;
  38. private database?: string;
  39. constructor(uri: string, config: PizzaSQLConfig = {}) {
  40. // Parse URI: https://host:port/database or https://host:port
  41. const url = new URL(uri);
  42. this.baseUrl = `${url.protocol}//${url.host}`;
  43. this.database = url.pathname.slice(1) || undefined;
  44. this.apiKey = config.apiKey;
  45. this.timeout = config.timeout || 30000;
  46. }
  47. private async request<T>(
  48. path: string,
  49. options: RequestInit = {}
  50. ): Promise<T> {
  51. const headers: Record<string, string> = {
  52. 'Content-Type': 'application/json',
  53. ...(options.headers as Record<string, string>),
  54. };
  55. if (this.apiKey) {
  56. headers['Authorization'] = `Bearer ${this.apiKey}`;
  57. }
  58. if (this.database) {
  59. headers['X-Database'] = this.database;
  60. }
  61. const controller = new AbortController();
  62. const timeoutId = setTimeout(() => controller.abort(), this.timeout);
  63. try {
  64. const response = await fetch(`${this.baseUrl}${path}`, {
  65. ...options,
  66. headers,
  67. signal: controller.signal,
  68. });
  69. const data = await response.json();
  70. if (!response.ok) {
  71. const error = data.error as PizzaSQLError;
  72. throw new Error(`[${error.code}] ${error.message}`);
  73. }
  74. return data as T;
  75. } finally {
  76. clearTimeout(timeoutId);
  77. }
  78. }
  79. /**
  80. * Execute a SQL query with optional parameters
  81. */
  82. async query<T = Record<string, unknown>>(
  83. sql: string,
  84. params: unknown[] = []
  85. ): Promise<QueryResult<T>> {
  86. const result = await this.request<{
  87. columns: Column[];
  88. rows: unknown[][];
  89. rowsAffected: number;
  90. lastInsertId: number;
  91. executionTime: string;
  92. }>('/query', {
  93. method: 'POST',
  94. body: JSON.stringify({ sql, params }),
  95. });
  96. // Transform rows from arrays to objects
  97. const rows = result.rows.map((row) => {
  98. const obj: Record<string, unknown> = {};
  99. result.columns.forEach((col, i) => {
  100. obj[col.name] = row[i];
  101. });
  102. return obj as T;
  103. });
  104. return {
  105. ...result,
  106. rows,
  107. };
  108. }
  109. /**
  110. * Shorthand for query - returns rows directly
  111. */
  112. async sql<T = Record<string, unknown>>(
  113. sql: string,
  114. params: unknown[] = []
  115. ): Promise<T[]> {
  116. const result = await this.query<T>(sql, params);
  117. return result.rows;
  118. }
  119. /**
  120. * Execute multiple statements in a batch
  121. */
  122. async execute(
  123. statements: { sql: string; params?: unknown[] }[],
  124. transaction = true
  125. ): Promise<ExecuteResult> {
  126. return this.request<ExecuteResult>('/execute', {
  127. method: 'POST',
  128. body: JSON.stringify({
  129. statements: statements.map((s) => ({
  130. sql: s.sql,
  131. params: s.params || [],
  132. })),
  133. transaction,
  134. }),
  135. });
  136. }
  137. /**
  138. * List all tables in the database
  139. */
  140. async tables(): Promise<string[]> {
  141. const result = await this.request<TableInfo>('/schema/tables');
  142. return result.tables;
  143. }
  144. /**
  145. * Get schema for a specific table
  146. */
  147. async schema(tableName: string): Promise<Column[]> {
  148. const result = await this.request<{ columns: Column[] }>(
  149. `/schema/tables/${encodeURIComponent(tableName)}`
  150. );
  151. return result.columns;
  152. }
  153. /**
  154. * Health check
  155. */
  156. async health(): Promise<{ status: string; database: string }> {
  157. return this.request('/health');
  158. }
  159. /**
  160. * Use a different database
  161. */
  162. use(database: string): PizzaSQLClient {
  163. const client = new PizzaSQLClient(this.baseUrl, {
  164. apiKey: this.apiKey,
  165. timeout: this.timeout,
  166. });
  167. client.database = database;
  168. return client;
  169. }
  170. }
  171. /**
  172. * Create a new PizzaSQL connection
  173. */
  174. export function connect(uri: string, apiKey?: string): PizzaSQLClient {
  175. return new PizzaSQLClient(uri, { apiKey });
  176. }
  177. /**
  178. * Create a new PizzaSQL connection with full config
  179. */
  180. export function createClient(
  181. uri: string,
  182. config: PizzaSQLConfig = {}
  183. ): PizzaSQLClient {
  184. return new PizzaSQLClient(uri, config);
  185. }
  186. // Default export
  187. export default { connect, createClient };