connection.go 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299
  1. package pgserver
  2. import (
  3. "bufio"
  4. "bytes"
  5. "encoding/binary"
  6. "encoding/hex"
  7. "errors"
  8. "fmt"
  9. "io"
  10. "log"
  11. "net"
  12. "regexp"
  13. "sort"
  14. "strconv"
  15. "strings"
  16. "github.com/danfragoso/pizzasql-next/pkg/executor"
  17. "github.com/danfragoso/pizzasql-next/pkg/lexer"
  18. "github.com/danfragoso/pizzasql-next/pkg/parser"
  19. "github.com/danfragoso/pizzasql-next/pkg/storage"
  20. )
  21. // Connection represents a client connection
  22. type Connection struct {
  23. conn net.Conn
  24. reader *bufio.Reader
  25. writer *bufio.Writer
  26. executor *executor.Executor
  27. schema *storage.SchemaManager
  28. dbManager *storage.DatabaseManager
  29. database string
  30. params map[string]string
  31. txStatus byte
  32. quiet bool // Disable query logging
  33. statements map[string]*preparedStatement
  34. portals map[string]*portal
  35. extendedFailed bool
  36. }
  37. type preparedStatement struct {
  38. query string
  39. paramOIDs []int32
  40. }
  41. type portal struct {
  42. query string
  43. executed bool
  44. }
  45. // NewConnection creates a new connection handler
  46. func NewConnection(conn net.Conn, dbManager *storage.DatabaseManager, quiet bool) *Connection {
  47. return &Connection{
  48. conn: conn,
  49. reader: bufio.NewReader(conn),
  50. writer: bufio.NewWriter(conn),
  51. dbManager: dbManager,
  52. params: make(map[string]string),
  53. statements: make(map[string]*preparedStatement),
  54. portals: make(map[string]*portal),
  55. txStatus: TxStatusIdle,
  56. quiet: quiet,
  57. }
  58. }
  59. // Handle processes the connection
  60. func (c *Connection) Handle() error {
  61. defer func() {
  62. if c.executor != nil {
  63. if err := c.executor.RollbackActive(); err != nil && !c.quiet {
  64. log.Printf("failed to roll back disconnected transaction: %v", err)
  65. }
  66. }
  67. c.conn.Close()
  68. }()
  69. // First, check for SSL request (sent before startup message)
  70. // SSL request is 8 bytes: length(4) + code(4) where code = 80877103
  71. firstBytes := make([]byte, 8)
  72. n, err := io.ReadFull(c.reader, firstBytes)
  73. if err != nil {
  74. return fmt.Errorf("failed to read initial bytes: %w", err)
  75. }
  76. // Check if it's an SSL request (code 80877103 = 0x04D2162F)
  77. if n == 8 {
  78. length := binary.BigEndian.Uint32(firstBytes[0:4])
  79. code := binary.BigEndian.Uint32(firstBytes[4:8])
  80. if length == 8 && code == 80877103 {
  81. // SSL request - we don't support SSL, send 'N'
  82. if !c.quiet {
  83. log.Printf("Client requested SSL, sending rejection")
  84. }
  85. if _, err := c.conn.Write([]byte{'N'}); err != nil {
  86. return fmt.Errorf("failed to send SSL rejection: %w", err)
  87. }
  88. // Now read the actual startup message
  89. } else {
  90. // Not SSL request, this is part of startup message
  91. // We need to prepend these bytes back for ReadStartupMessage
  92. // Create a multi-reader that first reads our buffered bytes, then continues with the reader
  93. c.reader = bufio.NewReader(io.MultiReader(bytes.NewReader(firstBytes), c.reader))
  94. }
  95. }
  96. // Read startup message
  97. if !c.quiet {
  98. log.Printf("Reading startup message...")
  99. }
  100. params, err := ReadStartupMessage(c.reader)
  101. if err != nil {
  102. return fmt.Errorf("failed to read startup message: %w", err)
  103. }
  104. c.params = params
  105. if !c.quiet {
  106. log.Printf("Startup params: %+v", params)
  107. }
  108. // Get database name from params (default to "pizzasql")
  109. dbName := params["database"]
  110. if dbName == "" {
  111. dbName = "pizzasql"
  112. }
  113. c.database = dbName
  114. if !c.quiet {
  115. log.Printf("New connection: user=%s database=%s", params["user"], dbName)
  116. }
  117. // Initialize database
  118. if err := c.initDatabase(dbName); err != nil {
  119. c.sendError("FATAL", ErrCodeConnectionFailure, fmt.Sprintf("Failed to initialize database: %v", err))
  120. return err
  121. }
  122. // Send authentication OK (no auth for now)
  123. if err := c.sendAuthenticationOk(); err != nil {
  124. return err
  125. }
  126. // Send parameter status messages
  127. if err := c.sendParameterStatus("server_version", "14.0 (PizzaSQL)"); err != nil {
  128. return err
  129. }
  130. if err := c.sendParameterStatus("server_encoding", "UTF8"); err != nil {
  131. return err
  132. }
  133. if err := c.sendParameterStatus("client_encoding", "UTF8"); err != nil {
  134. return err
  135. }
  136. if err := c.sendParameterStatus("DateStyle", "ISO, MDY"); err != nil {
  137. return err
  138. }
  139. if err := c.sendParameterStatus("TimeZone", "UTC"); err != nil {
  140. return err
  141. }
  142. // Send backend key data (for cancellation - we don't implement this yet)
  143. if err := c.sendBackendKeyData(12345, 67890); err != nil {
  144. return err
  145. }
  146. // Send ready for query
  147. if err := c.sendReadyForQuery(); err != nil {
  148. return err
  149. }
  150. // Message loop
  151. for {
  152. msg, err := ReadMessage(c.reader)
  153. if err != nil {
  154. if err == io.EOF {
  155. log.Printf("Connection closed by client")
  156. return nil
  157. }
  158. return fmt.Errorf("failed to read message: %w", err)
  159. }
  160. if err := c.handleMessage(msg); err != nil {
  161. if err == io.EOF {
  162. // Normal termination
  163. log.Printf("Connection closed normally")
  164. return nil
  165. }
  166. log.Printf("Error handling message: %v", err)
  167. return err
  168. }
  169. }
  170. }
  171. // initDatabase initializes the database connection
  172. func (c *Connection) initDatabase(dbName string) error {
  173. db, err := c.dbManager.GetDatabase(dbName)
  174. if err != nil {
  175. return err
  176. }
  177. c.schema = db.Schema
  178. c.executor = executor.New(db.Schema, db.Table)
  179. c.executor.SyncCatalog()
  180. return nil
  181. }
  182. // handleMessage processes a client message
  183. func (c *Connection) handleMessage(msg *Message) error {
  184. switch msg.Type {
  185. case MsgQuery:
  186. return c.handleQuery(msg)
  187. case MsgTerminate:
  188. log.Printf("Client requested termination")
  189. return io.EOF
  190. case MsgParse:
  191. return c.handleParse(msg)
  192. case MsgBind:
  193. return c.handleBind(msg)
  194. case MsgDescribe:
  195. return c.handleDescribe(msg)
  196. case MsgExecute:
  197. return c.handleExecute(msg)
  198. case MsgClose:
  199. return c.handleClose(msg)
  200. case MsgFlush:
  201. return c.writer.Flush()
  202. case MsgSync:
  203. c.extendedFailed = false
  204. return c.sendReadyForQuery()
  205. default:
  206. log.Printf("Unknown message type: %c (%d)", msg.Type, msg.Type)
  207. c.sendError("ERROR", ErrCodeProtocolViolation, fmt.Sprintf("Unknown message type: %c", msg.Type))
  208. return c.sendReadyForQuery()
  209. }
  210. }
  211. // handleQuery processes a simple query
  212. func (c *Connection) handleQuery(msg *Message) error {
  213. // A Query message carries a single NUL-terminated query string.
  214. if len(msg.Data) == 0 || msg.Data[len(msg.Data)-1] != 0 {
  215. c.sendError("ERROR", ErrCodeProtocolViolation, "invalid Query message: missing null terminator")
  216. return c.sendReadyForQuery()
  217. }
  218. sql := string(msg.Data[:len(msg.Data)-1])
  219. if !c.quiet {
  220. log.Printf("Query: %s", sql)
  221. }
  222. // Handle empty query
  223. sqlTrimmed := strings.TrimSpace(sql)
  224. if sqlTrimmed == "" || sqlTrimmed == ";" {
  225. if err := c.sendEmptyQueryResponse(); err != nil {
  226. return err
  227. }
  228. return c.sendReadyForQuery()
  229. }
  230. // Handle special PostgreSQL system queries that drivers send
  231. sqlUpper := strings.ToUpper(strings.TrimSpace(sql))
  232. singleStatement := isSingleStatementSQL(sql)
  233. // In a failed transaction only ROLLBACK (or ROLLBACK TO SAVEPOINT) is
  234. // accepted. Gate before honoring the special driver queries below so they
  235. // return 25P02 instead of a result. Multi-statement batches are gated
  236. // per statement in the execution loop below.
  237. if c.txStatus == TxStatusFailed && singleStatement && !isRollbackStatement(sql) {
  238. c.sendError("ERROR", ErrCodeTransactionAborted, "current transaction is aborted, commands ignored until end of transaction block")
  239. return c.sendReadyForQuery()
  240. }
  241. // lib/pq and other drivers query these for connection validation
  242. if singleStatement && strings.Contains(sqlUpper, "SELECT VERSION()") {
  243. // Return a fake PostgreSQL version
  244. return c.handleVersionQuery()
  245. }
  246. if singleStatement && strings.Contains(sqlUpper, "SELECT CURRENT_USER") {
  247. // Return the current user
  248. return c.handleCurrentUserQuery()
  249. }
  250. if singleStatement && strings.Contains(sqlUpper, "SHOW") && (strings.Contains(sqlUpper, "SERVER_VERSION") ||
  251. strings.Contains(sqlUpper, "SERVER_ENCODING") ||
  252. strings.Contains(sqlUpper, "CLIENT_ENCODING")) {
  253. // Handle SHOW commands
  254. return c.handleShowCommand(sqlUpper)
  255. }
  256. if result, handled, err := c.catalogResult(sql); handled {
  257. if err != nil {
  258. c.sendError("ERROR", ErrCodeInternalError, err.Error())
  259. return c.sendReadyForQuery()
  260. }
  261. if err := c.sendTabularResult(result, "SELECT"); err != nil {
  262. return err
  263. }
  264. return c.sendReadyForQuery()
  265. }
  266. // Parse the complete batch before executing its first statement. This keeps
  267. // unsupported trailing clauses from turning into committed writes.
  268. l := lexer.New(sql)
  269. p := parser.New(l)
  270. stmts, err := p.ParseMultiple()
  271. if err != nil {
  272. c.sendError("ERROR", ErrCodeSyntaxError, fmt.Sprintf("Syntax error: %v", err))
  273. return c.sendReadyForQuery()
  274. }
  275. for _, stmt := range stmts {
  276. if c.txStatus == TxStatusFailed {
  277. if _, rollback := stmt.(*parser.RollbackStmt); !rollback {
  278. c.sendError("ERROR", ErrCodeTransactionAborted, "current transaction is aborted, commands ignored until end of transaction block")
  279. return c.sendReadyForQuery()
  280. }
  281. }
  282. result, err := c.executor.Execute(stmt)
  283. if err != nil {
  284. code := ErrCodeInternalError
  285. message := fmt.Sprintf("Execution error: %v", err)
  286. var uniqueErr *storage.UniqueViolationError
  287. if errors.Is(err, storage.ErrSerialization) {
  288. code = ErrCodeSerializationFailure
  289. c.txStatus = TxStatusIdle
  290. } else if errors.As(err, &uniqueErr) {
  291. code = ErrCodeUniqueViolation
  292. message = fmt.Sprintf("Execution error: UNIQUE constraint failed: %s", uniqueErr.Constraint)
  293. if c.txStatus == TxStatusInBlock {
  294. c.txStatus = TxStatusFailed
  295. }
  296. } else if errors.Is(err, executor.ErrUnsupportedFeature) {
  297. code = ErrCodeFeatureNotSupported
  298. if c.txStatus == TxStatusInBlock {
  299. c.txStatus = TxStatusFailed
  300. }
  301. } else if c.txStatus == TxStatusInBlock {
  302. c.txStatus = TxStatusFailed
  303. }
  304. c.sendError("ERROR", code, message)
  305. return c.sendReadyForQuery()
  306. }
  307. if err := c.sendResult(result, stmt); err != nil {
  308. return err
  309. }
  310. }
  311. return c.sendReadyForQuery()
  312. }
  313. func (c *Connection) handleParse(msg *Message) error {
  314. if c.extendedFailed {
  315. return nil
  316. }
  317. name, pos, err := readCString(msg.Data, 0)
  318. if err != nil {
  319. return c.failExtended(ErrCodeProtocolViolation, err)
  320. }
  321. query, pos, err := readCString(msg.Data, pos)
  322. if err != nil || pos+2 > len(msg.Data) {
  323. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Parse message"))
  324. }
  325. count := int(binary.BigEndian.Uint16(msg.Data[pos : pos+2]))
  326. pos += 2
  327. if pos+count*4 != len(msg.Data) {
  328. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Parse parameter list"))
  329. }
  330. oids := make([]int32, count)
  331. for i := range oids {
  332. oids[i] = int32(binary.BigEndian.Uint32(msg.Data[pos : pos+4]))
  333. pos += 4
  334. }
  335. c.statements[name] = &preparedStatement{query: query, paramOIDs: oids}
  336. return c.writeMessage(MsgParseComplete, nil)
  337. }
  338. func (c *Connection) handleBind(msg *Message) error {
  339. if c.extendedFailed {
  340. return nil
  341. }
  342. portalName, pos, err := readCString(msg.Data, 0)
  343. if err != nil {
  344. return c.failExtended(ErrCodeProtocolViolation, err)
  345. }
  346. statementName, pos, err := readCString(msg.Data, pos)
  347. if err != nil {
  348. return c.failExtended(ErrCodeProtocolViolation, err)
  349. }
  350. statement, ok := c.statements[statementName]
  351. if !ok {
  352. return c.failExtended(ErrCodeInvalidParameter, fmt.Errorf("prepared statement %q does not exist", statementName))
  353. }
  354. formats, pos, err := readInt16List(msg.Data, pos)
  355. if err != nil || pos+2 > len(msg.Data) {
  356. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Bind format list"))
  357. }
  358. paramCount := int(binary.BigEndian.Uint16(msg.Data[pos : pos+2]))
  359. pos += 2
  360. params := make([]boundParameter, paramCount)
  361. for i := range params {
  362. if pos+4 > len(msg.Data) {
  363. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Bind parameter"))
  364. }
  365. length := int32(binary.BigEndian.Uint32(msg.Data[pos : pos+4]))
  366. pos += 4
  367. params[i].oid = parameterOID(statement.paramOIDs, i)
  368. params[i].format = parameterFormat(formats, i)
  369. if length == -1 {
  370. params[i].null = true
  371. continue
  372. }
  373. if length < 0 || pos+int(length) > len(msg.Data) {
  374. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Bind parameter length"))
  375. }
  376. params[i].value = append([]byte(nil), msg.Data[pos:pos+int(length)]...)
  377. pos += int(length)
  378. }
  379. _, pos, err = readInt16List(msg.Data, pos) // result formats; text output is currently used
  380. if err != nil || pos != len(msg.Data) {
  381. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Bind result format list"))
  382. }
  383. query, err := bindQuery(statement.query, params)
  384. if err != nil {
  385. return c.failExtended(ErrCodeInvalidParameter, err)
  386. }
  387. c.portals[portalName] = &portal{query: query}
  388. return c.writeMessage(MsgBindComplete, nil)
  389. }
  390. func (c *Connection) handleDescribe(msg *Message) error {
  391. if c.extendedFailed {
  392. return nil
  393. }
  394. if len(msg.Data) < 2 {
  395. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Describe message"))
  396. }
  397. name, pos, err := readCString(msg.Data, 1)
  398. if err != nil || pos != len(msg.Data) {
  399. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Describe name"))
  400. }
  401. switch msg.Data[0] {
  402. case 'S':
  403. statement, ok := c.statements[name]
  404. if !ok {
  405. return c.failExtended(ErrCodeInvalidParameter, fmt.Errorf("prepared statement %q does not exist", name))
  406. }
  407. mb := NewMessageBuilder()
  408. mb.WriteInt16(int16(len(statement.paramOIDs)))
  409. for _, oid := range statement.paramOIDs {
  410. mb.WriteInt32(oid)
  411. }
  412. if err := c.writeMessage(MsgParameterDescription, mb.Bytes()); err != nil {
  413. return err
  414. }
  415. case 'P':
  416. if _, ok := c.portals[name]; !ok {
  417. return c.failExtended(ErrCodeInvalidParameter, fmt.Errorf("portal %q does not exist", name))
  418. }
  419. default:
  420. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Describe target"))
  421. }
  422. // Execute sends the row description once the bound statement has been
  423. // analyzed, avoiding side effects during Describe.
  424. return c.writeMessage(MsgNoData, nil)
  425. }
  426. func (c *Connection) handleExecute(msg *Message) error {
  427. if c.extendedFailed {
  428. return nil
  429. }
  430. name, pos, err := readCString(msg.Data, 0)
  431. if err != nil || pos+4 != len(msg.Data) {
  432. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Execute message"))
  433. }
  434. portal, ok := c.portals[name]
  435. if !ok {
  436. return c.failExtended(ErrCodeInvalidParameter, fmt.Errorf("portal %q does not exist", name))
  437. }
  438. if portal.executed {
  439. return c.failExtended(ErrCodeFeatureNotSupported, fmt.Errorf("portal can only be executed once"))
  440. }
  441. portal.executed = true
  442. // Check the transaction state before catalog emulation. Catalog queries do
  443. // not all parse as regular PizzaSQL statements, but must still return 25P02
  444. // while the transaction is aborted.
  445. if c.txStatus == TxStatusFailed && !isRollbackStatement(portal.query) {
  446. return c.failExtended(ErrCodeTransactionAborted, fmt.Errorf("current transaction is aborted, commands ignored until end of transaction block"))
  447. }
  448. if result, handled, catalogErr := c.catalogResult(portal.query); handled {
  449. if catalogErr != nil {
  450. return c.failExtended(ErrCodeInternalError, catalogErr)
  451. }
  452. return c.sendTabularResult(result, "SELECT")
  453. }
  454. l := lexer.New(portal.query)
  455. stmt, err := parser.New(l).Parse()
  456. if err != nil {
  457. return c.failExtended(ErrCodeSyntaxError, fmt.Errorf("syntax error: %w", err))
  458. }
  459. result, err := c.executor.Execute(stmt)
  460. if err != nil {
  461. code := ErrCodeInternalError
  462. var uniqueErr *storage.UniqueViolationError
  463. if errors.Is(err, storage.ErrSerialization) {
  464. code = ErrCodeSerializationFailure
  465. c.txStatus = TxStatusIdle
  466. } else if errors.As(err, &uniqueErr) {
  467. code = ErrCodeUniqueViolation
  468. if c.txStatus == TxStatusInBlock {
  469. c.txStatus = TxStatusFailed
  470. }
  471. } else if errors.Is(err, executor.ErrUnsupportedFeature) {
  472. code = ErrCodeFeatureNotSupported
  473. if c.txStatus == TxStatusInBlock {
  474. c.txStatus = TxStatusFailed
  475. }
  476. } else if c.txStatus == TxStatusInBlock {
  477. c.txStatus = TxStatusFailed
  478. }
  479. if uniqueErr != nil {
  480. return c.failExtended(code, fmt.Errorf("execution error: UNIQUE constraint failed: %s", uniqueErr.Constraint))
  481. }
  482. return c.failExtended(code, fmt.Errorf("execution error: %w", err))
  483. }
  484. return c.sendResult(result, stmt)
  485. }
  486. var catalogFilterPattern = regexp.MustCompile(`(?i)\b(table_name|tablename|table_schema|schemaname|constraint_name|indexname)\s*=\s*'((?:''|[^'])*)'`)
  487. func (c *Connection) catalogResult(sql string) (*executor.Result, bool, error) {
  488. if !isSingleStatementSQL(sql) {
  489. return nil, false, nil
  490. }
  491. upper := strings.ToUpper(sql)
  492. var source string
  493. for _, candidate := range []string{
  494. "INFORMATION_SCHEMA.TABLES", "INFORMATION_SCHEMA.COLUMNS",
  495. "INFORMATION_SCHEMA.TABLE_CONSTRAINTS", "INFORMATION_SCHEMA.KEY_COLUMN_USAGE",
  496. "PG_TABLES", "PG_INDEXES",
  497. } {
  498. if strings.Contains(upper, "FROM "+candidate) {
  499. source = candidate
  500. break
  501. }
  502. }
  503. if source == "" {
  504. return nil, false, nil
  505. }
  506. if c.txStatus == TxStatusIdle {
  507. c.schema.LockStatement()
  508. defer c.schema.UnlockStatement()
  509. }
  510. tables, err := c.schema.ListTables()
  511. if err != nil {
  512. return nil, true, err
  513. }
  514. rows := make([]map[string]interface{}, 0)
  515. switch source {
  516. case "INFORMATION_SCHEMA.TABLES":
  517. for _, table := range tables {
  518. rows = append(rows, map[string]interface{}{
  519. "table_catalog": c.database, "table_schema": "public", "table_name": table, "table_type": "BASE TABLE",
  520. })
  521. }
  522. case "PG_TABLES":
  523. for _, table := range tables {
  524. indexes, _ := c.schema.ListTableIndexes(table)
  525. rows = append(rows, map[string]interface{}{
  526. "schemaname": "public", "tablename": table, "tableowner": c.params["user"], "tablespace": nil,
  527. "hasindexes": len(indexes) > 0, "hasrules": false, "hastriggers": false, "rowsecurity": false,
  528. })
  529. }
  530. case "INFORMATION_SCHEMA.COLUMNS":
  531. for _, table := range tables {
  532. schema, schemaErr := c.schema.GetSchema(table)
  533. if schemaErr != nil {
  534. continue
  535. }
  536. for i, column := range schema.Columns {
  537. rows = append(rows, map[string]interface{}{
  538. "table_catalog": c.database, "table_schema": "public", "table_name": table,
  539. "column_name": column.Name, "ordinal_position": int64(i + 1), "column_default": column.Default,
  540. "is_nullable": yesNo(column.Nullable), "data_type": strings.ToLower(column.Type),
  541. })
  542. }
  543. }
  544. case "INFORMATION_SCHEMA.TABLE_CONSTRAINTS", "INFORMATION_SCHEMA.KEY_COLUMN_USAGE":
  545. for _, table := range tables {
  546. schema, schemaErr := c.schema.GetSchema(table)
  547. if schemaErr != nil || schema.PrimaryKey == "" || schema.PrimaryKey == "_rowid_" {
  548. continue
  549. }
  550. row := map[string]interface{}{
  551. "constraint_catalog": c.database, "constraint_schema": "public", "constraint_name": table + "_pkey",
  552. "table_catalog": c.database, "table_schema": "public", "table_name": table,
  553. }
  554. if source == "INFORMATION_SCHEMA.TABLE_CONSTRAINTS" {
  555. row["constraint_type"] = "PRIMARY KEY"
  556. row["is_deferrable"] = "NO"
  557. row["initially_deferred"] = "NO"
  558. } else {
  559. row["column_name"] = schema.PrimaryKey
  560. row["ordinal_position"] = int64(1)
  561. }
  562. rows = append(rows, row)
  563. }
  564. case "PG_INDEXES":
  565. for _, table := range tables {
  566. indexes, _ := c.schema.ListTableIndexes(table)
  567. for _, index := range indexes {
  568. columns := make([]string, len(index.Columns))
  569. for i, column := range index.Columns {
  570. columns[i] = column.Name
  571. }
  572. unique := ""
  573. if index.Unique {
  574. unique = "UNIQUE "
  575. }
  576. rows = append(rows, map[string]interface{}{
  577. "schemaname": "public", "tablename": table, "indexname": index.Name, "tablespace": nil,
  578. "indexdef": fmt.Sprintf("CREATE %sINDEX %s ON %s (%s)", unique, index.Name, table, strings.Join(columns, ", ")),
  579. })
  580. }
  581. }
  582. }
  583. for _, match := range catalogFilterPattern.FindAllStringSubmatch(sql, -1) {
  584. column, expected := strings.ToLower(match[1]), strings.ReplaceAll(match[2], "''", "'")
  585. filtered := rows[:0]
  586. for _, row := range rows {
  587. if value, ok := row[column]; ok && strings.EqualFold(fmt.Sprintf("%v", value), expected) {
  588. filtered = append(filtered, row)
  589. }
  590. }
  591. rows = filtered
  592. }
  593. columns := catalogProjection(sql, rows)
  594. result := executor.NewResult("SELECT")
  595. if len(columns) == 1 && columns[0] == "count(*)" {
  596. result.AddColumnWithType("count", "INTEGER")
  597. result.AddRow(int64(len(rows)))
  598. return result, true, nil
  599. }
  600. for _, column := range columns {
  601. columnType := "TEXT"
  602. if column == "ordinal_position" {
  603. columnType = "INTEGER"
  604. } else if strings.HasPrefix(column, "has") || column == "rowsecurity" {
  605. columnType = "BOOLEAN"
  606. }
  607. result.AddColumnWithType(column, columnType)
  608. }
  609. for _, row := range rows {
  610. values := make([]interface{}, len(columns))
  611. for i, column := range columns {
  612. values[i] = row[column]
  613. }
  614. result.AddRow(values...)
  615. }
  616. return result, true, nil
  617. }
  618. func isSingleStatementSQL(sql string) bool {
  619. trimmed := strings.TrimSpace(sql)
  620. if strings.HasSuffix(trimmed, ";") {
  621. trimmed = strings.TrimSpace(strings.TrimSuffix(trimmed, ";"))
  622. }
  623. inString, inIdent := false, false
  624. for i := 0; i < len(trimmed); i++ {
  625. switch trimmed[i] {
  626. case '\'':
  627. if !inIdent {
  628. if inString && i+1 < len(trimmed) && trimmed[i+1] == '\'' {
  629. i++
  630. continue
  631. }
  632. inString = !inString
  633. }
  634. case '"':
  635. if !inString {
  636. inIdent = !inIdent
  637. }
  638. case ';':
  639. if !inString && !inIdent {
  640. return false
  641. }
  642. }
  643. }
  644. return true
  645. }
  646. // isRollbackStatement reports whether sql parses as a single ROLLBACK
  647. // statement, including ROLLBACK TO SAVEPOINT.
  648. func isRollbackStatement(sql string) bool {
  649. stmt, err := parser.New(lexer.New(sql)).Parse()
  650. if err != nil {
  651. return false
  652. }
  653. _, ok := stmt.(*parser.RollbackStmt)
  654. return ok
  655. }
  656. func catalogProjection(sql string, rows []map[string]interface{}) []string {
  657. upper := strings.ToUpper(sql)
  658. selectPos, fromPos := strings.Index(upper, "SELECT"), strings.Index(upper, " FROM ")
  659. if selectPos < 0 || fromPos < 0 || fromPos <= selectPos+6 {
  660. return nil
  661. }
  662. projection := strings.TrimSpace(sql[selectPos+6 : fromPos])
  663. projection = strings.TrimSpace(strings.TrimPrefix(strings.ToUpper(projection), "DISTINCT "))
  664. if projection == "*" && len(rows) > 0 {
  665. columns := make([]string, 0, len(rows[0]))
  666. for column := range rows[0] {
  667. columns = append(columns, column)
  668. }
  669. sort.Strings(columns)
  670. return columns
  671. }
  672. parts := strings.Split(projection, ",")
  673. columns := make([]string, 0, len(parts))
  674. for _, part := range parts {
  675. column := strings.TrimSpace(part)
  676. if index := strings.Index(strings.ToUpper(column), " AS "); index >= 0 {
  677. column = strings.TrimSpace(column[:index])
  678. }
  679. if index := strings.LastIndex(column, "."); index >= 0 {
  680. column = column[index+1:]
  681. }
  682. columns = append(columns, strings.ToLower(strings.Trim(column, `"`)))
  683. }
  684. return columns
  685. }
  686. func yesNo(value bool) string {
  687. if value {
  688. return "YES"
  689. }
  690. return "NO"
  691. }
  692. func (c *Connection) sendTabularResult(result *executor.Result, tag string) error {
  693. if err := c.sendRowDescription(result.Columns, result.ColumnTypes); err != nil {
  694. return err
  695. }
  696. for _, row := range result.Rows {
  697. if err := c.sendDataRow(row, result.Columns); err != nil {
  698. return err
  699. }
  700. }
  701. return c.sendCommandComplete(fmt.Sprintf("%s %d", tag, len(result.Rows)))
  702. }
  703. func (c *Connection) handleClose(msg *Message) error {
  704. if c.extendedFailed {
  705. return nil
  706. }
  707. if len(msg.Data) < 2 {
  708. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Close message"))
  709. }
  710. name, pos, err := readCString(msg.Data, 1)
  711. if err != nil || pos != len(msg.Data) {
  712. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Close name"))
  713. }
  714. if msg.Data[0] == 'S' {
  715. delete(c.statements, name)
  716. } else if msg.Data[0] == 'P' {
  717. delete(c.portals, name)
  718. } else {
  719. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Close target"))
  720. }
  721. return c.writeMessage(MsgCloseComplete, nil)
  722. }
  723. func (c *Connection) failExtended(code string, err error) error {
  724. c.extendedFailed = true
  725. return c.sendError("ERROR", code, err.Error())
  726. }
  727. type boundParameter struct {
  728. value []byte
  729. oid int32
  730. format int16
  731. null bool
  732. }
  733. func readCString(data []byte, pos int) (string, int, error) {
  734. if pos < 0 || pos >= len(data) {
  735. return "", pos, fmt.Errorf("missing null-terminated string")
  736. }
  737. end := bytes.IndexByte(data[pos:], 0)
  738. if end < 0 {
  739. return "", pos, fmt.Errorf("unterminated string")
  740. }
  741. return string(data[pos : pos+end]), pos + end + 1, nil
  742. }
  743. func readInt16List(data []byte, pos int) ([]int16, int, error) {
  744. if pos+2 > len(data) {
  745. return nil, pos, fmt.Errorf("missing list length")
  746. }
  747. count := int(binary.BigEndian.Uint16(data[pos : pos+2]))
  748. pos += 2
  749. if pos+count*2 > len(data) {
  750. return nil, pos, fmt.Errorf("truncated list")
  751. }
  752. result := make([]int16, count)
  753. for i := range result {
  754. result[i] = int16(binary.BigEndian.Uint16(data[pos : pos+2]))
  755. pos += 2
  756. }
  757. return result, pos, nil
  758. }
  759. func parameterOID(oids []int32, index int) int32 {
  760. if index < len(oids) {
  761. return oids[index]
  762. }
  763. return 0
  764. }
  765. func parameterFormat(formats []int16, index int) int16 {
  766. if len(formats) == 1 {
  767. return formats[0]
  768. }
  769. if index < len(formats) {
  770. return formats[index]
  771. }
  772. return 0
  773. }
  774. func bindQuery(query string, params []boundParameter) (string, error) {
  775. var result strings.Builder
  776. inString, inIdent := false, false
  777. for i := 0; i < len(query); {
  778. ch := query[i]
  779. if ch == '\'' && !inIdent {
  780. result.WriteByte(ch)
  781. if inString && i+1 < len(query) && query[i+1] == '\'' {
  782. result.WriteByte(query[i+1])
  783. i += 2
  784. continue
  785. }
  786. inString = !inString
  787. i++
  788. continue
  789. }
  790. if ch == '"' && !inString {
  791. inIdent = !inIdent
  792. result.WriteByte(ch)
  793. i++
  794. continue
  795. }
  796. if ch == '$' && !inString && !inIdent && i+1 < len(query) && query[i+1] >= '0' && query[i+1] <= '9' {
  797. end := i + 1
  798. for end < len(query) && query[end] >= '0' && query[end] <= '9' {
  799. end++
  800. }
  801. n, _ := strconv.Atoi(query[i+1 : end])
  802. if n < 1 || n > len(params) {
  803. return "", fmt.Errorf("parameter $%d was not provided", n)
  804. }
  805. literal, err := parameterLiteral(params[n-1])
  806. if err != nil {
  807. return "", fmt.Errorf("parameter $%d: %w", n, err)
  808. }
  809. result.WriteString(literal)
  810. i = end
  811. continue
  812. }
  813. result.WriteByte(ch)
  814. i++
  815. }
  816. return result.String(), nil
  817. }
  818. func parameterLiteral(param boundParameter) (string, error) {
  819. if param.null {
  820. return "NULL", nil
  821. }
  822. if param.format == 1 {
  823. switch param.oid {
  824. case 16:
  825. if len(param.value) != 1 {
  826. return "", fmt.Errorf("invalid binary boolean")
  827. }
  828. if param.value[0] == 0 {
  829. return "FALSE", nil
  830. }
  831. return "TRUE", nil
  832. case 21:
  833. if len(param.value) != 2 {
  834. return "", fmt.Errorf("invalid binary int2")
  835. }
  836. return strconv.FormatInt(int64(int16(binary.BigEndian.Uint16(param.value))), 10), nil
  837. case 23:
  838. if len(param.value) != 4 {
  839. return "", fmt.Errorf("invalid binary int4")
  840. }
  841. return strconv.FormatInt(int64(int32(binary.BigEndian.Uint32(param.value))), 10), nil
  842. case 20:
  843. if len(param.value) != 8 {
  844. return "", fmt.Errorf("invalid binary int8")
  845. }
  846. return strconv.FormatInt(int64(binary.BigEndian.Uint64(param.value)), 10), nil
  847. default:
  848. return "", fmt.Errorf("binary format is unsupported for OID %d", param.oid)
  849. }
  850. }
  851. value := string(param.value)
  852. switch param.oid {
  853. case 0:
  854. if strings.EqualFold(value, "true") || strings.EqualFold(value, "false") {
  855. return strings.ToUpper(value), nil
  856. }
  857. if _, err := strconv.ParseFloat(value, 64); err == nil && value != "" {
  858. return value, nil
  859. }
  860. return "'" + strings.ReplaceAll(value, "'", "''") + "'", nil
  861. case 16:
  862. if strings.EqualFold(value, "true") || value == "1" || value == "t" {
  863. return "TRUE", nil
  864. }
  865. return "FALSE", nil
  866. case 20, 21, 23, 26, 700, 701, 1700:
  867. if _, err := strconv.ParseFloat(value, 64); err != nil {
  868. return "", fmt.Errorf("invalid numeric value")
  869. }
  870. return value, nil
  871. default:
  872. return "'" + strings.ReplaceAll(value, "'", "''") + "'", nil
  873. }
  874. }
  875. // sendResult sends query results
  876. func (c *Connection) sendResult(result *executor.Result, stmt parser.Statement) error {
  877. // Any statement that produced a row set (SELECT, or INSERT/UPDATE/DELETE
  878. // with RETURNING) sends a row description and its data rows. Other
  879. // statements only send the command completion tag.
  880. if len(result.Columns) > 0 {
  881. if err := c.sendRowDescription(result.Columns, wireColumnTypes(result)); err != nil {
  882. return err
  883. }
  884. for _, row := range result.Rows {
  885. if err := c.sendDataRow(row, result.Columns); err != nil {
  886. return err
  887. }
  888. }
  889. return c.sendCommandComplete(c.getCommandTag(stmt, result))
  890. }
  891. // For other statements, just send command complete
  892. tag := c.getCommandTag(stmt, result)
  893. return c.sendCommandComplete(tag)
  894. }
  895. // wireColumnTypes corrects declared-affinity metadata when SQLite has stored a
  896. // value of another type. In particular, binding []byte to a VARCHAR column is
  897. // still a BLOB in SQLite; advertising TEXT while encoding PostgreSQL bytea text
  898. // would make clients receive the literal "\\x..." instead of the original
  899. // bytes.
  900. func wireColumnTypes(result *executor.Result) []string {
  901. types := append([]string(nil), result.ColumnTypes...)
  902. if len(types) < len(result.Columns) {
  903. types = append(types, make([]string, len(result.Columns)-len(types))...)
  904. }
  905. for _, row := range result.Rows {
  906. for i, value := range row {
  907. if i >= len(types) {
  908. break
  909. }
  910. if _, ok := value.([]byte); ok {
  911. types[i] = "BLOB"
  912. }
  913. }
  914. }
  915. return types
  916. }
  917. // getCommandTag returns the command completion tag
  918. func (c *Connection) getCommandTag(stmt parser.Statement, result *executor.Result) string {
  919. switch s := stmt.(type) {
  920. case *parser.SelectStmt:
  921. return fmt.Sprintf("SELECT %d", len(result.Rows))
  922. case *parser.CreateTableStmt:
  923. return "CREATE TABLE"
  924. case *parser.DropTableStmt:
  925. return "DROP TABLE"
  926. case *parser.CreateIndexStmt:
  927. return "CREATE INDEX"
  928. case *parser.DropIndexStmt:
  929. return "DROP INDEX"
  930. case *parser.AlterTableStmt:
  931. return "ALTER TABLE"
  932. case *parser.InsertStmt:
  933. return fmt.Sprintf("INSERT 0 %d", result.RowsAffected)
  934. case *parser.UpdateStmt:
  935. return fmt.Sprintf("UPDATE %d", result.RowsAffected)
  936. case *parser.DeleteStmt:
  937. return fmt.Sprintf("DELETE %d", result.RowsAffected)
  938. case *parser.BeginStmt:
  939. c.txStatus = TxStatusInBlock
  940. return "BEGIN"
  941. case *parser.CommitStmt:
  942. c.txStatus = TxStatusIdle
  943. return "COMMIT"
  944. case *parser.RollbackStmt:
  945. if s.Savepoint != "" {
  946. c.txStatus = TxStatusInBlock
  947. return "ROLLBACK"
  948. }
  949. c.txStatus = TxStatusIdle
  950. return "ROLLBACK"
  951. case *parser.SavepointStmt:
  952. c.txStatus = TxStatusInBlock
  953. return "SAVEPOINT"
  954. case *parser.ReleaseStmt:
  955. c.txStatus = TxStatusInBlock
  956. return "RELEASE"
  957. default:
  958. return "OK"
  959. }
  960. }
  961. // sendAuthenticationOk sends authentication OK message
  962. func (c *Connection) sendAuthenticationOk() error {
  963. mb := NewMessageBuilder()
  964. mb.WriteInt32(0) // Auth OK
  965. return c.writeMessage(MsgAuthenticationOk, mb.Bytes())
  966. }
  967. // sendParameterStatus sends a parameter status message
  968. func (c *Connection) sendParameterStatus(name, value string) error {
  969. mb := NewMessageBuilder()
  970. mb.WriteString(name)
  971. mb.WriteString(value)
  972. return c.writeMessage(MsgParameterStatus, mb.Bytes())
  973. }
  974. // sendBackendKeyData sends backend key data
  975. func (c *Connection) sendBackendKeyData(processID, secretKey int32) error {
  976. mb := NewMessageBuilder()
  977. mb.WriteInt32(processID)
  978. mb.WriteInt32(secretKey)
  979. return c.writeMessage(MsgBackendKeyData, mb.Bytes())
  980. }
  981. // sendReadyForQuery sends ready for query message
  982. func (c *Connection) sendReadyForQuery() error {
  983. mb := NewMessageBuilder()
  984. mb.AppendByte(c.txStatus)
  985. if err := c.writeMessage(MsgReadyForQuery, mb.Bytes()); err != nil {
  986. return err
  987. }
  988. // ReadyForQuery closes out a response cycle, so flush everything buffered
  989. // so far. This is what makes simple-query results and Sync responses
  990. // visible to the client.
  991. return c.writer.Flush()
  992. }
  993. // sendEmptyQueryResponse sends empty query response
  994. func (c *Connection) sendEmptyQueryResponse() error {
  995. return c.writeMessage(MsgEmptyQueryResponse, []byte{})
  996. }
  997. // sendRowDescription sends row description (column metadata)
  998. func (c *Connection) sendRowDescription(columns []string, columnTypes []string) error {
  999. mb := NewMessageBuilder()
  1000. mb.WriteInt16(int16(len(columns)))
  1001. for i, col := range columns {
  1002. colType := ""
  1003. if i < len(columnTypes) {
  1004. colType = columnTypes[i]
  1005. }
  1006. mb.WriteString(col)
  1007. mb.WriteInt32(0) // table OID
  1008. mb.WriteInt16(0) // column attribute number
  1009. mb.WriteInt32(c.getOIDForType(colType)) // type OID
  1010. mb.WriteInt16(c.getTypeSizeForType(colType)) // type size
  1011. mb.WriteInt32(-1) // type modifier
  1012. mb.WriteInt16(0) // format code (text)
  1013. }
  1014. return c.writeMessage(MsgRowDescription, mb.Bytes())
  1015. }
  1016. // sendDataRow sends a data row
  1017. func (c *Connection) sendDataRow(row []interface{}, columns []string) error {
  1018. mb := NewMessageBuilder()
  1019. mb.WriteInt16(int16(len(row)))
  1020. for _, value := range row {
  1021. if value == nil {
  1022. mb.WriteInt32(-1) // NULL indicator
  1023. continue
  1024. }
  1025. // Convert value to string
  1026. strValue := c.valueToString(value)
  1027. mb.WriteInt32(int32(len(strValue)))
  1028. mb.WriteBytes([]byte(strValue))
  1029. }
  1030. return c.writeMessage(MsgDataRow, mb.Bytes())
  1031. }
  1032. // sendCommandComplete sends command complete message
  1033. func (c *Connection) sendCommandComplete(tag string) error {
  1034. mb := NewMessageBuilder()
  1035. mb.WriteString(tag)
  1036. return c.writeMessage(MsgCommandComplete, mb.Bytes())
  1037. }
  1038. // sendError sends an error response
  1039. func (c *Connection) sendError(severity, code, message string) error {
  1040. mb := NewMessageBuilder()
  1041. mb.AppendByte(ErrorFieldSeverity)
  1042. mb.WriteString(severity)
  1043. mb.AppendByte(ErrorFieldCode)
  1044. mb.WriteString(code)
  1045. mb.AppendByte(ErrorFieldMessage)
  1046. mb.WriteString(message)
  1047. mb.AppendByte(0) // Terminator
  1048. if err := c.writeMessage(MsgErrorResponse, mb.Bytes()); err != nil {
  1049. return err
  1050. }
  1051. // Errors must be visible promptly, including FATAL startup failures that
  1052. // are not followed by a ReadyForQuery before the connection closes.
  1053. return c.writer.Flush()
  1054. }
  1055. // writeMessage buffers a message for the connection. It does not flush, so
  1056. // callers that need to make a response visible to the client must flush at the
  1057. // appropriate protocol boundary (ReadyForQuery, an explicit Flush message, or
  1058. // an error response). Buffering amortizes the per-message syscalls that a
  1059. // result set would otherwise incur; the underlying bufio.Writer bounds memory
  1060. // use so large result sets cannot grow the buffer without limit.
  1061. func (c *Connection) writeMessage(msgType byte, data []byte) error {
  1062. if !c.quiet {
  1063. log.Printf("Sending message type=%c length=%d", msgType, len(data)+4)
  1064. }
  1065. return WriteMessage(c.writer, msgType, data)
  1066. }
  1067. // getOIDForType returns PostgreSQL OID for type
  1068. func (c *Connection) getOIDForType(typeName string) int32 {
  1069. switch strings.ToUpper(typeName) {
  1070. case "INTEGER", "INT":
  1071. return 23 // INT4OID
  1072. case "BIGINT":
  1073. return 20 // INT8OID
  1074. case "TEXT", "VARCHAR", "CHAR", "UUID":
  1075. // UUID is stored as text (SQLite-style), so it reports TEXTOID rather
  1076. // than the native PG UUID OID.
  1077. return 25 // TEXTOID
  1078. case "REAL", "FLOAT":
  1079. return 700 // FLOAT4OID
  1080. case "DOUBLE":
  1081. return 701 // FLOAT8OID
  1082. case "BOOLEAN", "BOOL":
  1083. return 16 // BOOLOID
  1084. case "BLOB":
  1085. return 17 // BYTEAOID
  1086. case "DATETIME", "TIMESTAMP":
  1087. // Datetime values are exchanged as UTC RFC3339 (ISO8601 with a timezone
  1088. // offset), which timestamptz decodes directly.
  1089. return 1184 // TIMESTAMPTZOID
  1090. case "DATE":
  1091. return 1082 // DATEOID
  1092. default:
  1093. return 25 // Default to TEXT
  1094. }
  1095. }
  1096. // getTypeSizeForType returns type size
  1097. func (c *Connection) getTypeSizeForType(typeName string) int16 {
  1098. switch strings.ToUpper(typeName) {
  1099. case "INTEGER", "INT":
  1100. return 4
  1101. case "BIGINT":
  1102. return 8
  1103. case "REAL", "FLOAT":
  1104. return 4
  1105. case "DOUBLE":
  1106. return 8
  1107. case "BOOLEAN", "BOOL":
  1108. return 1
  1109. case "DATETIME", "TIMESTAMP":
  1110. return 8
  1111. case "DATE":
  1112. return 4
  1113. default:
  1114. return -1 // Variable length
  1115. }
  1116. }
  1117. // valueToString converts a value to string
  1118. func (c *Connection) valueToString(value interface{}) string {
  1119. if value == nil {
  1120. return ""
  1121. }
  1122. // PostgreSQL's text format for bytea is \x followed by hex. Emitting that
  1123. // lets libpq/pgx decode a BLOB column (OID 17) losslessly.
  1124. if b, ok := value.([]byte); ok {
  1125. return `\x` + hex.EncodeToString(b)
  1126. }
  1127. return fmt.Sprintf("%v", value)
  1128. }
  1129. // handleVersionQuery handles SELECT version()
  1130. func (c *Connection) handleVersionQuery() error {
  1131. columns := []string{"version"}
  1132. columnTypes := []string{"TEXT"}
  1133. if err := c.sendRowDescription(columns, columnTypes); err != nil {
  1134. return err
  1135. }
  1136. row := []interface{}{"PostgreSQL 14.0 (PizzaSQL)"}
  1137. if err := c.sendDataRow(row, columns); err != nil {
  1138. return err
  1139. }
  1140. if err := c.sendCommandComplete("SELECT 1"); err != nil {
  1141. return err
  1142. }
  1143. return c.sendReadyForQuery()
  1144. }
  1145. // handleCurrentUserQuery handles SELECT current_user
  1146. func (c *Connection) handleCurrentUserQuery() error {
  1147. columns := []string{"current_user"}
  1148. columnTypes := []string{"TEXT"}
  1149. if err := c.sendRowDescription(columns, columnTypes); err != nil {
  1150. return err
  1151. }
  1152. user := c.params["user"]
  1153. if user == "" {
  1154. user = "pizzasql"
  1155. }
  1156. row := []interface{}{user}
  1157. if err := c.sendDataRow(row, columns); err != nil {
  1158. return err
  1159. }
  1160. if err := c.sendCommandComplete("SELECT 1"); err != nil {
  1161. return err
  1162. }
  1163. return c.sendReadyForQuery()
  1164. }
  1165. // handleShowCommand handles SHOW commands
  1166. func (c *Connection) handleShowCommand(sqlUpper string) error {
  1167. var value string
  1168. var name string
  1169. if strings.Contains(sqlUpper, "SERVER_VERSION") {
  1170. name = "server_version"
  1171. value = "14.0"
  1172. } else if strings.Contains(sqlUpper, "SERVER_ENCODING") {
  1173. name = "server_encoding"
  1174. value = "UTF8"
  1175. } else if strings.Contains(sqlUpper, "CLIENT_ENCODING") {
  1176. name = "client_encoding"
  1177. value = "UTF8"
  1178. } else {
  1179. // Unknown SHOW command
  1180. c.sendError("ERROR", ErrCodeFeatureNotSupported, "SHOW command not supported")
  1181. return c.sendReadyForQuery()
  1182. }
  1183. columns := []string{name}
  1184. columnTypes := []string{"TEXT"}
  1185. if err := c.sendRowDescription(columns, columnTypes); err != nil {
  1186. return err
  1187. }
  1188. row := []interface{}{value}
  1189. if err := c.sendDataRow(row, columns); err != nil {
  1190. return err
  1191. }
  1192. if err := c.sendCommandComplete("SHOW"); err != nil {
  1193. return err
  1194. }
  1195. return c.sendReadyForQuery()
  1196. }