connection.go 38 KB

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